Completed
Branch BUG/pantheon-session-fatal-2 (2f2c99)
by
unknown
19:07 queued 09:56
created
core/data_migration_scripts/EE_DMS_Core_4_8_0.dms.php 1 patch
Indentation   +357 added lines, -357 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,
@@ -117,9 +117,9 @@  discard block
 block discarded – undo
117 117
 							PRIMARY KEY  (ATTM_ID),
118 118
 								KEY ATT_ID (ATT_ID),
119 119
 								KEY ATT_email (ATT_email(191))";
120
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
121
-        $table_name = 'esp_country';
122
-        $sql = "CNT_ISO varchar(2) collate utf8_bin NOT NULL,
120
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
121
+		$table_name = 'esp_country';
122
+		$sql = "CNT_ISO varchar(2) collate utf8_bin NOT NULL,
123 123
 					  CNT_ISO3 varchar(3) collate utf8_bin NOT NULL,
124 124
 					  RGN_ID tinyint(3) unsigned DEFAULT NULL,
125 125
 					  CNT_name varchar(45) collate utf8_bin NOT NULL,
@@ -135,25 +135,25 @@  discard block
 block discarded – undo
135 135
 					  CNT_is_EU tinyint(1) DEFAULT '0',
136 136
 					  CNT_active tinyint(1) DEFAULT '0',
137 137
 					  PRIMARY KEY  (CNT_ISO)";
138
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
139
-        $table_name = 'esp_currency';
140
-        $sql = "CUR_code varchar(6) collate utf8_bin NOT NULL,
138
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
139
+		$table_name = 'esp_currency';
140
+		$sql = "CUR_code varchar(6) collate utf8_bin NOT NULL,
141 141
 				CUR_single varchar(45) collate utf8_bin DEFAULT 'dollar',
142 142
 				CUR_plural varchar(45) collate utf8_bin DEFAULT 'dollars',
143 143
 				CUR_sign varchar(45) collate utf8_bin DEFAULT '$',
144 144
 				CUR_dec_plc varchar(1) collate utf8_bin NOT NULL DEFAULT '2',
145 145
 				CUR_active tinyint(1) DEFAULT '0',
146 146
 				PRIMARY KEY  (CUR_code)";
147
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
148
-        $table_name = 'esp_currency_payment_method';
149
-        $sql = "CPM_ID int(11) NOT NULL AUTO_INCREMENT,
147
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
148
+		$table_name = 'esp_currency_payment_method';
149
+		$sql = "CPM_ID int(11) NOT NULL AUTO_INCREMENT,
150 150
 				CUR_code varchar(6) collate utf8_bin NOT NULL,
151 151
 				PMD_ID int(11) NOT NULL,
152 152
 				PRIMARY KEY  (CPM_ID),
153 153
 				KEY PMD_ID (PMD_ID)";
154
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
155
-        $table_name = 'esp_datetime';
156
-        $sql = "DTT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
154
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
155
+		$table_name = 'esp_datetime';
156
+		$sql = "DTT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
157 157
 				  EVT_ID bigint(20) unsigned NOT NULL,
158 158
 				  DTT_name varchar(255) NOT NULL DEFAULT '',
159 159
 				  DTT_description text NOT NULL,
@@ -169,9 +169,9 @@  discard block
 block discarded – undo
169 169
 						KEY DTT_EVT_start (DTT_EVT_start),
170 170
 						KEY EVT_ID (EVT_ID),
171 171
 						KEY DTT_is_primary (DTT_is_primary)";
172
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
173
-        $table_name = 'esp_event_meta';
174
-        $sql = "
172
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
173
+		$table_name = 'esp_event_meta';
174
+		$sql = "
175 175
 			EVTM_ID int(10) NOT NULL AUTO_INCREMENT,
176 176
 			EVT_ID bigint(20) unsigned NOT NULL,
177 177
 			EVT_display_desc tinyint(1) unsigned NOT NULL DEFAULT 1,
@@ -187,34 +187,34 @@  discard block
 block discarded – undo
187 187
 			EVT_donations tinyint(1) NULL,
188 188
 			PRIMARY KEY  (EVTM_ID),
189 189
 			KEY EVT_ID (EVT_ID)";
190
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
191
-        $table_name = 'esp_event_question_group';
192
-        $sql = "EQG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
190
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
191
+		$table_name = 'esp_event_question_group';
192
+		$sql = "EQG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
193 193
 					EVT_ID bigint(20) unsigned NOT NULL,
194 194
 					QSG_ID int(10) unsigned NOT NULL,
195 195
 					EQG_primary tinyint(1) unsigned NOT NULL DEFAULT 0,
196 196
 					PRIMARY KEY  (EQG_ID),
197 197
 					KEY EVT_ID (EVT_ID),
198 198
 					KEY QSG_ID (QSG_ID)";
199
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
200
-        $table_name = 'esp_event_venue';
201
-        $sql = "EVV_ID int(11) NOT NULL AUTO_INCREMENT,
199
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
200
+		$table_name = 'esp_event_venue';
201
+		$sql = "EVV_ID int(11) NOT NULL AUTO_INCREMENT,
202 202
 				EVT_ID bigint(20) unsigned NOT NULL,
203 203
 				VNU_ID bigint(20) unsigned NOT NULL,
204 204
 				EVV_primary tinyint(1) unsigned NOT NULL DEFAULT 0,
205 205
 				PRIMARY KEY  (EVV_ID)";
206
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
207
-        $table_name = 'esp_extra_meta';
208
-        $sql = "EXM_ID int(11) NOT NULL AUTO_INCREMENT,
206
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
207
+		$table_name = 'esp_extra_meta';
208
+		$sql = "EXM_ID int(11) NOT NULL AUTO_INCREMENT,
209 209
 				OBJ_ID int(11) DEFAULT NULL,
210 210
 				EXM_type varchar(45) DEFAULT NULL,
211 211
 				EXM_key varchar(45) DEFAULT NULL,
212 212
 				EXM_value text,
213 213
 				PRIMARY KEY  (EXM_ID),
214 214
 				KEY EXM_type (EXM_type,OBJ_ID,EXM_key)";
215
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
216
-        $table_name = 'esp_extra_join';
217
-        $sql = "EXJ_ID int(11) NOT NULL AUTO_INCREMENT,
215
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
216
+		$table_name = 'esp_extra_join';
217
+		$sql = "EXJ_ID int(11) NOT NULL AUTO_INCREMENT,
218 218
 				EXJ_first_model_id varchar(6) NOT NULL,
219 219
 				EXJ_first_model_name varchar(20) NOT NULL,
220 220
 				EXJ_second_model_id varchar(6) NOT NULL,
@@ -222,9 +222,9 @@  discard block
 block discarded – undo
222 222
 				PRIMARY KEY  (EXJ_ID),
223 223
 				KEY first_model (EXJ_first_model_name,EXJ_first_model_id),
224 224
 				KEY second_model (EXJ_second_model_name,EXJ_second_model_id)";
225
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
226
-        $table_name = 'esp_line_item';
227
-        $sql = "LIN_ID int(11) NOT NULL AUTO_INCREMENT,
225
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
226
+		$table_name = 'esp_line_item';
227
+		$sql = "LIN_ID int(11) NOT NULL AUTO_INCREMENT,
228 228
 				LIN_code varchar(245) NOT NULL DEFAULT '',
229 229
 				TXN_ID int(11) DEFAULT NULL,
230 230
 				LIN_name varchar(245) NOT NULL DEFAULT '',
@@ -243,9 +243,9 @@  discard block
 block discarded – undo
243 243
 				PRIMARY KEY  (LIN_ID),
244 244
 				KEY LIN_code (LIN_code(191)),
245 245
 				KEY TXN_ID (TXN_ID)";
246
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
247
-        $table_name = 'esp_log';
248
-        $sql = "LOG_ID int(11) NOT NULL AUTO_INCREMENT,
246
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
247
+		$table_name = 'esp_log';
248
+		$sql = "LOG_ID int(11) NOT NULL AUTO_INCREMENT,
249 249
 				LOG_time datetime DEFAULT NULL,
250 250
 				OBJ_ID varchar(45) DEFAULT NULL,
251 251
 				OBJ_type varchar(45) DEFAULT NULL,
@@ -256,18 +256,18 @@  discard block
 block discarded – undo
256 256
 				KEY LOG_time (LOG_time),
257 257
 				KEY OBJ (OBJ_type,OBJ_ID),
258 258
 				KEY LOG_type (LOG_type)";
259
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
260
-        $table_name = 'esp_message_template';
261
-        $sql = "MTP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
259
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
260
+		$table_name = 'esp_message_template';
261
+		$sql = "MTP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
262 262
 					GRP_ID int(10) unsigned NOT NULL,
263 263
 					MTP_context varchar(50) NOT NULL,
264 264
 					MTP_template_field varchar(30) NOT NULL,
265 265
 					MTP_content text NOT NULL,
266 266
 					PRIMARY KEY  (MTP_ID),
267 267
 					KEY GRP_ID (GRP_ID)";
268
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
269
-        $table_name = 'esp_message_template_group';
270
-        $sql = "GRP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
268
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
269
+		$table_name = 'esp_message_template_group';
270
+		$sql = "GRP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
271 271
 					MTP_user_id int(10) NOT NULL DEFAULT '1',
272 272
 					MTP_name varchar(245) NOT NULL DEFAULT '',
273 273
 					MTP_description varchar(245) NOT NULL DEFAULT '',
@@ -279,17 +279,17 @@  discard block
 block discarded – undo
279 279
 					MTP_is_active tinyint(1) NOT NULL DEFAULT '1',
280 280
 					PRIMARY KEY  (GRP_ID),
281 281
 					KEY MTP_user_id (MTP_user_id)";
282
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
283
-        $table_name = 'esp_event_message_template';
284
-        $sql = "EMT_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
282
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
283
+		$table_name = 'esp_event_message_template';
284
+		$sql = "EMT_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
285 285
 					EVT_ID bigint(20) unsigned NOT NULL DEFAULT 0,
286 286
 					GRP_ID int(10) unsigned NOT NULL DEFAULT 0,
287 287
 					PRIMARY KEY  (EMT_ID),
288 288
 					KEY EVT_ID (EVT_ID),
289 289
 					KEY GRP_ID (GRP_ID)";
290
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
291
-        $table_name = 'esp_payment';
292
-        $sql = "PAY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
290
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
291
+		$table_name = 'esp_payment';
292
+		$sql = "PAY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
293 293
 					TXN_ID int(10) unsigned DEFAULT NULL,
294 294
 					STS_ID varchar(3) collate utf8_bin DEFAULT NULL,
295 295
 					PAY_timestamp datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
@@ -306,9 +306,9 @@  discard block
 block discarded – undo
306 306
 					PRIMARY KEY  (PAY_ID),
307 307
 					KEY PAY_timestamp (PAY_timestamp),
308 308
 					KEY TXN_ID (TXN_ID)";
309
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
310
-        $table_name = 'esp_payment_method';
311
-        $sql = "PMD_ID int(11) NOT NULL AUTO_INCREMENT,
309
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
310
+		$table_name = 'esp_payment_method';
311
+		$sql = "PMD_ID int(11) NOT NULL AUTO_INCREMENT,
312 312
 				PMD_type varchar(124) DEFAULT NULL,
313 313
 				PMD_name varchar(255) DEFAULT NULL,
314 314
 				PMD_desc text,
@@ -324,32 +324,32 @@  discard block
 block discarded – undo
324 324
 				PRIMARY KEY  (PMD_ID),
325 325
 				UNIQUE KEY PMD_slug_UNIQUE (PMD_slug),
326 326
 				KEY PMD_type (PMD_type)";
327
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
328
-        $table_name = "esp_ticket_price";
329
-        $sql = "TKP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
327
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
328
+		$table_name = "esp_ticket_price";
329
+		$sql = "TKP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
330 330
 					  TKT_ID int(10) unsigned NOT NULL,
331 331
 					  PRC_ID int(10) unsigned NOT NULL,
332 332
 					  PRIMARY KEY  (TKP_ID),
333 333
 					  KEY TKT_ID (TKT_ID),
334 334
 					  KEY PRC_ID (PRC_ID)";
335
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
336
-        $table_name = "esp_datetime_ticket";
337
-        $sql = "DTK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
335
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
336
+		$table_name = "esp_datetime_ticket";
337
+		$sql = "DTK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
338 338
 					  DTT_ID int(10) unsigned NOT NULL,
339 339
 					  TKT_ID int(10) unsigned NOT NULL,
340 340
 					  PRIMARY KEY  (DTK_ID),
341 341
 					  KEY DTT_ID (DTT_ID),
342 342
 					  KEY TKT_ID (TKT_ID)";
343
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
344
-        $table_name = "esp_ticket_template";
345
-        $sql = "TTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
343
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
344
+		$table_name = "esp_ticket_template";
345
+		$sql = "TTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
346 346
 					  TTM_name varchar(45) NOT NULL,
347 347
 					  TTM_description text,
348 348
 					  TTM_file varchar(45),
349 349
 					  PRIMARY KEY  (TTM_ID)";
350
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
351
-        $table_name = 'esp_question';
352
-        $sql = 'QST_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
350
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
351
+		$table_name = 'esp_question';
352
+		$sql = 'QST_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
353 353
 					QST_display_text text NOT NULL,
354 354
 					QST_admin_label varchar(255) NOT NULL,
355 355
 					QST_system varchar(25) NOT NULL DEFAULT "",
@@ -363,18 +363,18 @@  discard block
 block discarded – undo
363 363
 					QST_deleted tinyint(2) unsigned NOT NULL DEFAULT 0,
364 364
 					PRIMARY KEY  (QST_ID),
365 365
 					KEY QST_order (QST_order)';
366
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
367
-        $table_name = 'esp_question_group_question';
368
-        $sql = "QGQ_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
366
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
367
+		$table_name = 'esp_question_group_question';
368
+		$sql = "QGQ_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
369 369
 					QSG_ID int(10) unsigned NOT NULL,
370 370
 					QST_ID int(10) unsigned NOT NULL,
371 371
 					QGQ_order int(10) unsigned NOT NULL DEFAULT 0,
372 372
 					PRIMARY KEY  (QGQ_ID),
373 373
 					KEY QST_ID (QST_ID),
374 374
 					KEY QSG_ID_order (QSG_ID,QGQ_order)";
375
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
376
-        $table_name = 'esp_question_option';
377
-        $sql = "QSO_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
375
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
376
+		$table_name = 'esp_question_option';
377
+		$sql = "QSO_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
378 378
 					QSO_value varchar(255) NOT NULL,
379 379
 					QSO_desc text NOT NULL,
380 380
 					QST_ID int(10) unsigned NOT NULL,
@@ -384,9 +384,9 @@  discard block
 block discarded – undo
384 384
 					PRIMARY KEY  (QSO_ID),
385 385
 					KEY QST_ID (QST_ID),
386 386
 					KEY QSO_order (QSO_order)";
387
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
388
-        $table_name = 'esp_registration';
389
-        $sql = "REG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
387
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
388
+		$table_name = 'esp_registration';
389
+		$sql = "REG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
390 390
 					  EVT_ID bigint(20) unsigned NOT NULL,
391 391
 					  ATT_ID bigint(20) unsigned NOT NULL,
392 392
 					  TXN_ID int(10) unsigned NOT NULL,
@@ -410,18 +410,18 @@  discard block
 block discarded – undo
410 410
 					  KEY TKT_ID (TKT_ID),
411 411
 					  KEY EVT_ID (EVT_ID),
412 412
 					  KEY STS_ID (STS_ID)";
413
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
414
-        $table_name = 'esp_registration_payment';
415
-        $sql = "RPY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
413
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
414
+		$table_name = 'esp_registration_payment';
415
+		$sql = "RPY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
416 416
 					  REG_ID int(10) unsigned NOT NULL,
417 417
 					  PAY_ID int(10) unsigned NULL,
418 418
 					  RPY_amount decimal(10,3) NOT NULL DEFAULT '0.00',
419 419
 					  PRIMARY KEY  (RPY_ID),
420 420
 					  KEY REG_ID (REG_ID),
421 421
 					  KEY PAY_ID (PAY_ID)";
422
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
423
-        $table_name = 'esp_checkin';
424
-        $sql = "CHK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
422
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
423
+		$table_name = 'esp_checkin';
424
+		$sql = "CHK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
425 425
 					REG_ID int(10) unsigned NOT NULL,
426 426
 					DTT_ID int(10) unsigned NOT NULL,
427 427
 					CHK_in tinyint(1) unsigned NOT NULL DEFAULT 1,
@@ -429,9 +429,9 @@  discard block
 block discarded – undo
429 429
 					PRIMARY KEY  (CHK_ID),
430 430
 					KEY REG_ID (REG_ID),
431 431
 					KEY DTT_ID (DTT_ID)";
432
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
433
-        $table_name = 'esp_state';
434
-        $sql = "STA_ID smallint(5) unsigned NOT NULL AUTO_INCREMENT,
432
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
433
+		$table_name = 'esp_state';
434
+		$sql = "STA_ID smallint(5) unsigned NOT NULL AUTO_INCREMENT,
435 435
 					  CNT_ISO varchar(2) collate utf8_bin NOT NULL,
436 436
 					  STA_abbrev varchar(24) collate utf8_bin NOT NULL,
437 437
 					  STA_name varchar(100) collate utf8_bin NOT NULL,
@@ -439,9 +439,9 @@  discard block
 block discarded – undo
439 439
 					  PRIMARY KEY  (STA_ID),
440 440
 					  KEY STA_abbrev (STA_abbrev),
441 441
 					  KEY CNT_ISO (CNT_ISO)";
442
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
443
-        $table_name = 'esp_status';
444
-        $sql = "STS_ID varchar(3) NOT NULL,
442
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
443
+		$table_name = 'esp_status';
444
+		$sql = "STS_ID varchar(3) NOT NULL,
445 445
 					  STS_code varchar(45) NOT NULL,
446 446
 					  STS_type varchar(45) NOT NULL,
447 447
 					  STS_can_edit tinyint(1) NOT NULL DEFAULT 0,
@@ -449,9 +449,9 @@  discard block
 block discarded – undo
449 449
 					  STS_open tinyint(1) NOT NULL DEFAULT 1,
450 450
 					  UNIQUE KEY STS_ID_UNIQUE (STS_ID),
451 451
 					  KEY STS_type (STS_type)";
452
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
453
-        $table_name = 'esp_transaction';
454
-        $sql = "TXN_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
452
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
453
+		$table_name = 'esp_transaction';
454
+		$sql = "TXN_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
455 455
 					  TXN_timestamp datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
456 456
 					  TXN_total decimal(10,3) DEFAULT '0.00',
457 457
 					  TXN_paid decimal(10,3) NOT NULL DEFAULT '0.00',
@@ -463,9 +463,9 @@  discard block
 block discarded – undo
463 463
 					  PRIMARY KEY  (TXN_ID),
464 464
 					  KEY TXN_timestamp (TXN_timestamp),
465 465
 					  KEY STS_ID (STS_ID)";
466
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
467
-        $table_name = 'esp_venue_meta';
468
-        $sql = "VNUM_ID int(11) NOT NULL AUTO_INCREMENT,
466
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
467
+		$table_name = 'esp_venue_meta';
468
+		$sql = "VNUM_ID int(11) NOT NULL AUTO_INCREMENT,
469 469
 			VNU_ID bigint(20) unsigned NOT NULL DEFAULT 0,
470 470
 			VNU_address varchar(255) DEFAULT NULL,
471 471
 			VNU_address2 varchar(255) DEFAULT NULL,
@@ -484,10 +484,10 @@  discard block
 block discarded – undo
484 484
 			KEY VNU_ID (VNU_ID),
485 485
 			KEY STA_ID (STA_ID),
486 486
 			KEY CNT_ISO (CNT_ISO)";
487
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
488
-        // modified tables
489
-        $table_name = "esp_price";
490
-        $sql = "PRC_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
487
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
488
+		// modified tables
489
+		$table_name = "esp_price";
490
+		$sql = "PRC_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
491 491
 					  PRT_ID tinyint(3) unsigned NOT NULL,
492 492
 					  PRC_amount decimal(10,3) NOT NULL DEFAULT '0.00',
493 493
 					  PRC_name varchar(245) NOT NULL,
@@ -500,9 +500,9 @@  discard block
 block discarded – undo
500 500
 					  PRC_parent int(10) unsigned DEFAULT 0,
501 501
 					  PRIMARY KEY  (PRC_ID),
502 502
 					  KEY PRT_ID (PRT_ID)";
503
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
504
-        $table_name = "esp_price_type";
505
-        $sql = "PRT_ID tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
503
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
504
+		$table_name = "esp_price_type";
505
+		$sql = "PRT_ID tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
506 506
 				  PRT_name varchar(45) NOT NULL,
507 507
 				  PBT_ID tinyint(3) unsigned NOT NULL DEFAULT '1',
508 508
 				  PRT_is_percent tinyint(1) NOT NULL DEFAULT '0',
@@ -511,9 +511,9 @@  discard block
 block discarded – undo
511 511
 				  PRT_deleted tinyint(1) NOT NULL DEFAULT '0',
512 512
 				  UNIQUE KEY PRT_name_UNIQUE (PRT_name),
513 513
 				  PRIMARY KEY  (PRT_ID)";
514
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
515
-        $table_name = "esp_ticket";
516
-        $sql = "TKT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
514
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
515
+		$table_name = "esp_ticket";
516
+		$sql = "TKT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
517 517
 					  TTM_ID int(10) unsigned NOT NULL,
518 518
 					  TKT_name varchar(245) NOT NULL DEFAULT '',
519 519
 					  TKT_description text NOT NULL,
@@ -535,9 +535,9 @@  discard block
 block discarded – undo
535 535
 					  TKT_deleted tinyint(1) NOT NULL DEFAULT '0',
536 536
 					  PRIMARY KEY  (TKT_ID),
537 537
 					  KEY TKT_start_date (TKT_start_date)";
538
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
539
-        $table_name = 'esp_question_group';
540
-        $sql = 'QSG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
538
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
539
+		$table_name = 'esp_question_group';
540
+		$sql = 'QSG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
541 541
 					QSG_name varchar(255) NOT NULL,
542 542
 					QSG_identifier varchar(100) NOT NULL,
543 543
 					QSG_desc text NULL,
@@ -550,223 +550,223 @@  discard block
 block discarded – undo
550 550
 					PRIMARY KEY  (QSG_ID),
551 551
 					UNIQUE KEY QSG_identifier_UNIQUE (QSG_identifier),
552 552
 					KEY QSG_order (QSG_order)';
553
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
554
-        /** @var EE_DMS_Core_4_1_0 $script_4_1_defaults */
555
-        $script_4_1_defaults = EE_Registry::instance()->load_dms('Core_4_1_0');
556
-        // (because many need to convert old string states to foreign keys into the states table)
557
-        $script_4_1_defaults->insert_default_states();
558
-        $script_4_1_defaults->insert_default_countries();
559
-        /** @var EE_DMS_Core_4_5_0 $script_4_5_defaults */
560
-        $script_4_5_defaults = EE_Registry::instance()->load_dms('Core_4_5_0');
561
-        $script_4_5_defaults->insert_default_price_types();
562
-        $script_4_5_defaults->insert_default_prices();
563
-        $script_4_5_defaults->insert_default_tickets();
564
-        /** @var EE_DMS_Core_4_6_0 $script_4_6_defaults */
565
-        $script_4_6_defaults = EE_Registry::instance()->load_dms('Core_4_6_0');
566
-        $script_4_6_defaults->add_default_admin_only_payments();
567
-        $script_4_6_defaults->insert_default_currencies();
568
-        $this->verify_new_countries();
569
-        $this->verify_new_currencies();
570
-        return true;
571
-    }
553
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
554
+		/** @var EE_DMS_Core_4_1_0 $script_4_1_defaults */
555
+		$script_4_1_defaults = EE_Registry::instance()->load_dms('Core_4_1_0');
556
+		// (because many need to convert old string states to foreign keys into the states table)
557
+		$script_4_1_defaults->insert_default_states();
558
+		$script_4_1_defaults->insert_default_countries();
559
+		/** @var EE_DMS_Core_4_5_0 $script_4_5_defaults */
560
+		$script_4_5_defaults = EE_Registry::instance()->load_dms('Core_4_5_0');
561
+		$script_4_5_defaults->insert_default_price_types();
562
+		$script_4_5_defaults->insert_default_prices();
563
+		$script_4_5_defaults->insert_default_tickets();
564
+		/** @var EE_DMS_Core_4_6_0 $script_4_6_defaults */
565
+		$script_4_6_defaults = EE_Registry::instance()->load_dms('Core_4_6_0');
566
+		$script_4_6_defaults->add_default_admin_only_payments();
567
+		$script_4_6_defaults->insert_default_currencies();
568
+		$this->verify_new_countries();
569
+		$this->verify_new_currencies();
570
+		return true;
571
+	}
572 572
 
573 573
 
574 574
 
575
-    /**
576
-     * @return boolean
577
-     */
578
-    public function schema_changes_after_migration()
579
-    {
580
-        $this->fix_non_default_taxes();
581
-        // this is actually the same as the last DMS
582
-        /** @var EE_DMS_Core_4_7_0 $script_4_7_defaults */
583
-        $script_4_7_defaults = EE_Registry::instance()->load_dms('Core_4_7_0');
584
-        return $script_4_7_defaults->schema_changes_after_migration();
585
-    }
575
+	/**
576
+	 * @return boolean
577
+	 */
578
+	public function schema_changes_after_migration()
579
+	{
580
+		$this->fix_non_default_taxes();
581
+		// this is actually the same as the last DMS
582
+		/** @var EE_DMS_Core_4_7_0 $script_4_7_defaults */
583
+		$script_4_7_defaults = EE_Registry::instance()->load_dms('Core_4_7_0');
584
+		return $script_4_7_defaults->schema_changes_after_migration();
585
+	}
586 586
 
587 587
 
588 588
 
589
-    public function migration_page_hooks()
590
-    {
591
-    }
589
+	public function migration_page_hooks()
590
+	{
591
+	}
592 592
 
593 593
 
594 594
 
595
-    /**
596
-     * verifies each of the new countries exists that somehow we missed in 4.1
597
-     */
598
-    public function verify_new_countries()
599
-    {
600
-        // a list of countries (and specifically some which were missed in another list):https://gist.github.com/adhipg/1600028
601
-        // how many decimal places? https://en.wikipedia.org/wiki/ISO_4217
602
-        // currency symbols: http://www.xe.com/symbols.php
603
-        // 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
604
-        // ('AD', 'AND', 0, 'Andorra', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+376', 0, 0),
605
-        $newer_countries = array(
606
-            array('AX', 'ALA', 0, 'Åland Islands', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+358', 1, 0),
607
-            array('BL', 'BLM', 0, 'Saint Barthelemy', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+590', 1, 0),
608
-            array('CW', 'CUW', 0, 'Curacao', 'ANG', 'Guilder', 'Guilders', 'ƒ', 1, 2, '+599', 1, 0),
609
-            array('GG', 'GGY', 0, 'Guernsey', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+44', 0, 0),
610
-            array('IM', 'IMN', 0, 'Isle of Man', 'GBP', 'Pound', 'Pounds', '£', 1, 2, '+44', 0, 0),
611
-            array('JE', 'JEY', 0, 'Jersey', 'GBP', 'Pound', 'Pounds', '£', 1, 2, '+44', 0, 0),
612
-            array('MF', 'MAF', 0, 'Saint Martin', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+590', 1, 0),
613
-            array('ME', 'MNE', 0, 'Montenegro', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+382', 0, 0),
614
-            array('RS', 'SRB', 0, 'Serbia', 'RSD', 'Dinar', 'Dinars', '', 0, 2, '+381', 1, 0),
615
-            array('SS', 'SSD', 0, 'South Sudan', 'SSP', 'Pound', 'Pounds', '£', 1, 2, '+211', 0, 0),
616
-            array('SX', 'SXM', 0, 'Sint Maarten', 'ANG', 'Guilder', 'Guilders', 'ƒ', 1, 2, '+1', 1, 0),
617
-            array('XK', 'XKX', 0, 'Kosovo', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+383', 0, 0),
618
-            array('YT', 'MYT', 0, 'Mayotte', 'EUR', 'Euro', 'Euros', '€', 0, 2, '+262', 1, 0),
619
-            array(
620
-                'BQ',
621
-                'BES',
622
-                0,
623
-                'Bonaire, Saint Eustatius and Saba',
624
-                'USD',
625
-                'Dollar',
626
-                'Dollars',
627
-                '$',
628
-                1,
629
-                2,
630
-                '+599',
631
-                0,
632
-                0,
633
-            ),
634
-            array('BV', 'BVT', 0, 'Bouvet Island', 'NOK', 'Krone', 'Krones', 'kr', 1, 2, '+47', 0, 0),
635
-            array('IO', 'IOT', 0, 'British Indian Ocean Territory', 'GBP', 'Pound', 'Pounds', '£', 1, 2, '+246', 0, 0),
636
-            array('CX', 'CXR', 0, 'Christmas Island', 'AUD', 'Dollar', 'Dollars', '$', 1, 2, '+61', 0, 0),
637
-            array('CC', 'CCK', 0, 'Cocos (Keeling) Islands', 'AUD', 'Dollar', 'Dollars', '$', 1, 2, '+891', 0, 0),
638
-            array(
639
-                'HM',
640
-                'HMD',
641
-                0,
642
-                'Heard Island and McDonald Islands',
643
-                'AUD',
644
-                'Dollar',
645
-                'Dollars',
646
-                '$',
647
-                1,
648
-                2,
649
-                '+891',
650
-                0,
651
-                0,
652
-            ),
653
-            array('PS', 'PSE', 0, 'Palestinian Territory', 'ILS', 'Shekel', 'Shekels', '₪', 1, 2, '+970', 0, 0),
654
-            array(
655
-                'GS',
656
-                'SGS',
657
-                0,
658
-                'South Georgia and the South Sandwich Islands',
659
-                'GBP',
660
-                'Pound',
661
-                'Pounds',
662
-                '£',
663
-                1,
664
-                2,
665
-                '+500',
666
-                0,
667
-                0,
668
-            ),
669
-            array('TL', 'TLS', 0, 'Timor-Leste', 'USD', 'Dollar', 'Dollars', '$', 1, 2, '+670', 0, 0),
670
-            array('TF', 'ATF', 0, 'French Southern Territories', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+262', 0, 0),
671
-            array(
672
-                'UM',
673
-                'UMI',
674
-                0,
675
-                'United States Minor Outlying Islands',
676
-                'USD',
677
-                'Dollar',
678
-                'Dollars',
679
-                '$',
680
-                1,
681
-                2,
682
-                '+1',
683
-                0,
684
-                0,
685
-            ),
686
-        );
687
-        global $wpdb;
688
-        $country_table = $wpdb->prefix . "esp_country";
689
-        $country_format = array(
690
-            "CNT_ISO"         => '%s',
691
-            "CNT_ISO3"        => '%s',
692
-            "RGN_ID"          => '%d',
693
-            "CNT_name"        => '%s',
694
-            "CNT_cur_code"    => '%s',
695
-            "CNT_cur_single"  => '%s',
696
-            "CNT_cur_plural"  => '%s',
697
-            "CNT_cur_sign"    => '%s',
698
-            "CNT_cur_sign_b4" => '%d',
699
-            "CNT_cur_dec_plc" => '%d',
700
-            "CNT_tel_code"    => '%s',
701
-            "CNT_is_EU"       => '%d',
702
-            "CNT_active"      => '%d',
703
-        );
704
-        if ($this->_get_table_analysis()->tableExists($country_table)) {
705
-            foreach ($newer_countries as $country) {
706
-                $SQL = "SELECT COUNT('CNT_ISO') FROM {$country_table} WHERE CNT_ISO='{$country[0]}' LIMIT 1";
707
-                $countries = $wpdb->get_var($SQL);
708
-                if (! $countries) {
709
-                    $wpdb->insert(
710
-                        $country_table,
711
-                        array_combine(array_keys($country_format), $country),
712
-                        $country_format
713
-                    );
714
-                }
715
-            }
716
-        }
717
-    }
595
+	/**
596
+	 * verifies each of the new countries exists that somehow we missed in 4.1
597
+	 */
598
+	public function verify_new_countries()
599
+	{
600
+		// a list of countries (and specifically some which were missed in another list):https://gist.github.com/adhipg/1600028
601
+		// how many decimal places? https://en.wikipedia.org/wiki/ISO_4217
602
+		// currency symbols: http://www.xe.com/symbols.php
603
+		// 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
604
+		// ('AD', 'AND', 0, 'Andorra', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+376', 0, 0),
605
+		$newer_countries = array(
606
+			array('AX', 'ALA', 0, 'Åland Islands', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+358', 1, 0),
607
+			array('BL', 'BLM', 0, 'Saint Barthelemy', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+590', 1, 0),
608
+			array('CW', 'CUW', 0, 'Curacao', 'ANG', 'Guilder', 'Guilders', 'ƒ', 1, 2, '+599', 1, 0),
609
+			array('GG', 'GGY', 0, 'Guernsey', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+44', 0, 0),
610
+			array('IM', 'IMN', 0, 'Isle of Man', 'GBP', 'Pound', 'Pounds', '£', 1, 2, '+44', 0, 0),
611
+			array('JE', 'JEY', 0, 'Jersey', 'GBP', 'Pound', 'Pounds', '£', 1, 2, '+44', 0, 0),
612
+			array('MF', 'MAF', 0, 'Saint Martin', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+590', 1, 0),
613
+			array('ME', 'MNE', 0, 'Montenegro', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+382', 0, 0),
614
+			array('RS', 'SRB', 0, 'Serbia', 'RSD', 'Dinar', 'Dinars', '', 0, 2, '+381', 1, 0),
615
+			array('SS', 'SSD', 0, 'South Sudan', 'SSP', 'Pound', 'Pounds', '£', 1, 2, '+211', 0, 0),
616
+			array('SX', 'SXM', 0, 'Sint Maarten', 'ANG', 'Guilder', 'Guilders', 'ƒ', 1, 2, '+1', 1, 0),
617
+			array('XK', 'XKX', 0, 'Kosovo', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+383', 0, 0),
618
+			array('YT', 'MYT', 0, 'Mayotte', 'EUR', 'Euro', 'Euros', '€', 0, 2, '+262', 1, 0),
619
+			array(
620
+				'BQ',
621
+				'BES',
622
+				0,
623
+				'Bonaire, Saint Eustatius and Saba',
624
+				'USD',
625
+				'Dollar',
626
+				'Dollars',
627
+				'$',
628
+				1,
629
+				2,
630
+				'+599',
631
+				0,
632
+				0,
633
+			),
634
+			array('BV', 'BVT', 0, 'Bouvet Island', 'NOK', 'Krone', 'Krones', 'kr', 1, 2, '+47', 0, 0),
635
+			array('IO', 'IOT', 0, 'British Indian Ocean Territory', 'GBP', 'Pound', 'Pounds', '£', 1, 2, '+246', 0, 0),
636
+			array('CX', 'CXR', 0, 'Christmas Island', 'AUD', 'Dollar', 'Dollars', '$', 1, 2, '+61', 0, 0),
637
+			array('CC', 'CCK', 0, 'Cocos (Keeling) Islands', 'AUD', 'Dollar', 'Dollars', '$', 1, 2, '+891', 0, 0),
638
+			array(
639
+				'HM',
640
+				'HMD',
641
+				0,
642
+				'Heard Island and McDonald Islands',
643
+				'AUD',
644
+				'Dollar',
645
+				'Dollars',
646
+				'$',
647
+				1,
648
+				2,
649
+				'+891',
650
+				0,
651
+				0,
652
+			),
653
+			array('PS', 'PSE', 0, 'Palestinian Territory', 'ILS', 'Shekel', 'Shekels', '₪', 1, 2, '+970', 0, 0),
654
+			array(
655
+				'GS',
656
+				'SGS',
657
+				0,
658
+				'South Georgia and the South Sandwich Islands',
659
+				'GBP',
660
+				'Pound',
661
+				'Pounds',
662
+				'£',
663
+				1,
664
+				2,
665
+				'+500',
666
+				0,
667
+				0,
668
+			),
669
+			array('TL', 'TLS', 0, 'Timor-Leste', 'USD', 'Dollar', 'Dollars', '$', 1, 2, '+670', 0, 0),
670
+			array('TF', 'ATF', 0, 'French Southern Territories', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+262', 0, 0),
671
+			array(
672
+				'UM',
673
+				'UMI',
674
+				0,
675
+				'United States Minor Outlying Islands',
676
+				'USD',
677
+				'Dollar',
678
+				'Dollars',
679
+				'$',
680
+				1,
681
+				2,
682
+				'+1',
683
+				0,
684
+				0,
685
+			),
686
+		);
687
+		global $wpdb;
688
+		$country_table = $wpdb->prefix . "esp_country";
689
+		$country_format = array(
690
+			"CNT_ISO"         => '%s',
691
+			"CNT_ISO3"        => '%s',
692
+			"RGN_ID"          => '%d',
693
+			"CNT_name"        => '%s',
694
+			"CNT_cur_code"    => '%s',
695
+			"CNT_cur_single"  => '%s',
696
+			"CNT_cur_plural"  => '%s',
697
+			"CNT_cur_sign"    => '%s',
698
+			"CNT_cur_sign_b4" => '%d',
699
+			"CNT_cur_dec_plc" => '%d',
700
+			"CNT_tel_code"    => '%s',
701
+			"CNT_is_EU"       => '%d',
702
+			"CNT_active"      => '%d',
703
+		);
704
+		if ($this->_get_table_analysis()->tableExists($country_table)) {
705
+			foreach ($newer_countries as $country) {
706
+				$SQL = "SELECT COUNT('CNT_ISO') FROM {$country_table} WHERE CNT_ISO='{$country[0]}' LIMIT 1";
707
+				$countries = $wpdb->get_var($SQL);
708
+				if (! $countries) {
709
+					$wpdb->insert(
710
+						$country_table,
711
+						array_combine(array_keys($country_format), $country),
712
+						$country_format
713
+					);
714
+				}
715
+			}
716
+		}
717
+	}
718 718
 
719 719
 
720 720
 
721
-    /**
722
-     * verifies each of the new currencies exists that somehow we missed in 4.6
723
-     */
724
-    public function verify_new_currencies()
725
-    {
726
-        // a list of countries (and specifically some which were missed in another list):https://gist.github.com/adhipg/1600028
727
-        // how many decimal places? https://en.wikipedia.org/wiki/ISO_4217
728
-        // currency symbols: http://www.xe.com/symbols.php
729
-        // CUR_code, CUR_single, CUR_plural, CUR_sign, CUR_dec_plc, CUR_active
730
-        // ( 'EUR',  'Euro',  'Euros',  '€',  2,1),
731
-        $newer_currencies = array(
732
-            array('RSD', 'Dinar', 'Dinars', '', 3, 1),
733
-        );
734
-        global $wpdb;
735
-        $currency_table = $wpdb->prefix . "esp_currency";
736
-        $currency_format = array(
737
-            "CUR_code"    => '%s',
738
-            "CUR_single"  => '%s',
739
-            "CUR_plural"  => '%s',
740
-            "CUR_sign"    => '%s',
741
-            "CUR_dec_plc" => '%d',
742
-            "CUR_active"  => '%d',
743
-        );
744
-        if ($this->_get_table_analysis()->tableExists($currency_table)) {
745
-            foreach ($newer_currencies as $currency) {
746
-                $SQL = "SELECT COUNT('CUR_code') FROM {$currency_table} WHERE CUR_code='{$currency[0]}' LIMIT 1";
747
-                $countries = $wpdb->get_var($SQL);
748
-                if (! $countries) {
749
-                    $wpdb->insert(
750
-                        $currency_table,
751
-                        array_combine(array_keys($currency_format), $currency),
752
-                        $currency_format
753
-                    );
754
-                }
755
-            }
756
-        }
757
-    }
721
+	/**
722
+	 * verifies each of the new currencies exists that somehow we missed in 4.6
723
+	 */
724
+	public function verify_new_currencies()
725
+	{
726
+		// a list of countries (and specifically some which were missed in another list):https://gist.github.com/adhipg/1600028
727
+		// how many decimal places? https://en.wikipedia.org/wiki/ISO_4217
728
+		// currency symbols: http://www.xe.com/symbols.php
729
+		// CUR_code, CUR_single, CUR_plural, CUR_sign, CUR_dec_plc, CUR_active
730
+		// ( 'EUR',  'Euro',  'Euros',  '€',  2,1),
731
+		$newer_currencies = array(
732
+			array('RSD', 'Dinar', 'Dinars', '', 3, 1),
733
+		);
734
+		global $wpdb;
735
+		$currency_table = $wpdb->prefix . "esp_currency";
736
+		$currency_format = array(
737
+			"CUR_code"    => '%s',
738
+			"CUR_single"  => '%s',
739
+			"CUR_plural"  => '%s',
740
+			"CUR_sign"    => '%s',
741
+			"CUR_dec_plc" => '%d',
742
+			"CUR_active"  => '%d',
743
+		);
744
+		if ($this->_get_table_analysis()->tableExists($currency_table)) {
745
+			foreach ($newer_currencies as $currency) {
746
+				$SQL = "SELECT COUNT('CUR_code') FROM {$currency_table} WHERE CUR_code='{$currency[0]}' LIMIT 1";
747
+				$countries = $wpdb->get_var($SQL);
748
+				if (! $countries) {
749
+					$wpdb->insert(
750
+						$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/general_settings/OrganizationSettings.php 1 patch
Indentation   +473 added lines, -473 removed lines patch added patch discarded remove patch
@@ -40,498 +40,498 @@
 block discarded – undo
40 40
 class OrganizationSettings extends FormHandler
41 41
 {
42 42
 
43
-    /**
44
-     * @var EE_Organization_Config
45
-     */
46
-    protected $organization_config;
43
+	/**
44
+	 * @var EE_Organization_Config
45
+	 */
46
+	protected $organization_config;
47 47
 
48
-    /**
49
-     * @var EE_Core_Config
50
-     */
51
-    protected $core_config;
48
+	/**
49
+	 * @var EE_Core_Config
50
+	 */
51
+	protected $core_config;
52 52
 
53 53
 
54
-    /**
55
-     * @var EE_Network_Core_Config
56
-     */
57
-    protected $network_core_config;
54
+	/**
55
+	 * @var EE_Network_Core_Config
56
+	 */
57
+	protected $network_core_config;
58 58
 
59
-    /**
60
-     * Form constructor.
61
-     *
62
-     * @param EE_Registry             $registry
63
-     * @param EE_Organization_Config  $organization_config
64
-     * @param EE_Core_Config          $core_config
65
-     * @param EE_Network_Core_Config $network_core_config
66
-     * @throws InvalidArgumentException
67
-     * @throws InvalidDataTypeException
68
-     * @throws DomainException
69
-     */
70
-    public function __construct(
71
-        EE_Registry $registry,
72
-        EE_Organization_Config $organization_config,
73
-        EE_Core_Config $core_config,
74
-        EE_Network_Core_Config $network_core_config
75
-    ) {
76
-        $this->organization_config = $organization_config;
77
-        $this->core_config = $core_config;
78
-        $this->network_core_config = $network_core_config;
79
-        parent::__construct(
80
-            esc_html__('Your Organization Settings', 'event_espresso'),
81
-            esc_html__('Your Organization Settings', 'event_espresso'),
82
-            'organization_settings',
83
-            '',
84
-            FormHandler::DO_NOT_SETUP_FORM,
85
-            $registry
86
-        );
87
-    }
59
+	/**
60
+	 * Form constructor.
61
+	 *
62
+	 * @param EE_Registry             $registry
63
+	 * @param EE_Organization_Config  $organization_config
64
+	 * @param EE_Core_Config          $core_config
65
+	 * @param EE_Network_Core_Config $network_core_config
66
+	 * @throws InvalidArgumentException
67
+	 * @throws InvalidDataTypeException
68
+	 * @throws DomainException
69
+	 */
70
+	public function __construct(
71
+		EE_Registry $registry,
72
+		EE_Organization_Config $organization_config,
73
+		EE_Core_Config $core_config,
74
+		EE_Network_Core_Config $network_core_config
75
+	) {
76
+		$this->organization_config = $organization_config;
77
+		$this->core_config = $core_config;
78
+		$this->network_core_config = $network_core_config;
79
+		parent::__construct(
80
+			esc_html__('Your Organization Settings', 'event_espresso'),
81
+			esc_html__('Your Organization Settings', 'event_espresso'),
82
+			'organization_settings',
83
+			'',
84
+			FormHandler::DO_NOT_SETUP_FORM,
85
+			$registry
86
+		);
87
+	}
88 88
 
89 89
 
90 90
 
91
-    /**
92
-     * creates and returns the actual form
93
-     *
94
-     * @return EE_Form_Section_Proper
95
-     * @throws EE_Error
96
-     */
97
-    public function generate()
98
-    {
99
-        $form = new EE_Form_Section_Proper(
100
-            array(
101
-                'name'            => 'organization_settings',
102
-                'html_id'         => 'organization_settings',
103
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
104
-                'subsections'     => array(
105
-                    'contact_information_hdr'        => new EE_Form_Section_HTML(
106
-                        EEH_HTML::h2(
107
-                            esc_html__('Contact Information', 'event_espresso')
108
-                            . ' '
109
-                            . EEH_HTML::span(EEH_Template::get_help_tab_link('contact_info_info')),
110
-                            '',
111
-                            'contact-information-hdr'
112
-                        )
113
-                    ),
114
-                    'organization_name'      => new EE_Text_Input(
115
-                        array(
116
-                            'html_name' => 'organization_name',
117
-                            'html_label_text' => esc_html__('Organization Name', 'event_espresso'),
118
-                            'html_help_text'  => esc_html__(
119
-                                'Displayed on all emails and invoices.',
120
-                                'event_espresso'
121
-                            ),
122
-                            'default'         => $this->organization_config->get_pretty('name'),
123
-                            'required'        => false,
124
-                        )
125
-                    ),
126
-                    'organization_address_1'      => new EE_Text_Input(
127
-                        array(
128
-                            'html_name' => 'organization_address_1',
129
-                            'html_label_text' => esc_html__('Street Address', 'event_espresso'),
130
-                            'default'         => $this->organization_config->get_pretty('address_1'),
131
-                            'required'        => false,
132
-                        )
133
-                    ),
134
-                    'organization_address_2'      => new EE_Text_Input(
135
-                        array(
136
-                            'html_name' => 'organization_address_2',
137
-                            'html_label_text' => esc_html__('Street Address 2', 'event_espresso'),
138
-                            'default'         => $this->organization_config->get_pretty('address_2'),
139
-                            'required'        => false,
140
-                        )
141
-                    ),
142
-                    'organization_city'      => new EE_Text_Input(
143
-                        array(
144
-                            'html_name' => 'organization_city',
145
-                            'html_label_text' => esc_html__('City', 'event_espresso'),
146
-                            'default'         => $this->organization_config->get_pretty('city'),
147
-                            'required'        => false,
148
-                        )
149
-                    ),
150
-                    'organization_state'      => new EE_State_Select_Input(
151
-                        null,
152
-                        array(
153
-                            'html_name' => 'organization_state',
154
-                            'html_label_text' => esc_html__('State/Province', 'event_espresso'),
155
-                            'default'         => $this->organization_config->STA_ID,
156
-                            'required'        => false,
157
-                        )
158
-                    ),
159
-                    'organization_country'      => new EE_Country_Select_Input(
160
-                        null,
161
-                        array(
162
-                            'html_name' => 'organization_country',
163
-                            'html_label_text' => esc_html__('Country', 'event_espresso'),
164
-                            'default'         => $this->organization_config->CNT_ISO,
165
-                            'required'        => false,
166
-                        )
167
-                    ),
168
-                    'organization_zip'      => new EE_Text_Input(
169
-                        array(
170
-                            'html_name' => 'organization_zip',
171
-                            'html_label_text' => esc_html__('Zip/Postal Code', 'event_espresso'),
172
-                            'default'         => $this->organization_config->get_pretty('zip'),
173
-                            'required'        => false,
174
-                        )
175
-                    ),
176
-                    'organization_email'      => new EE_Text_Input(
177
-                        array(
178
-                            'html_name' => 'organization_email',
179
-                            'html_label_text' => esc_html__('Primary Contact Email', 'event_espresso'),
180
-                            'html_help_text'  => sprintf(
181
-                                esc_html__(
182
-                                    'This is where notifications go to when you use the %1$s and %2$s shortcodes in the message templates.',
183
-                                    'event_espresso'
184
-                                ),
185
-                                '<code>[CO_FORMATTED_EMAIL]</code>',
186
-                                '<code>[CO_EMAIL]</code>'
187
-                            ),
188
-                            'default'         => $this->organization_config->get_pretty('email'),
189
-                            'required'        => false,
190
-                        )
191
-                    ),
192
-                    'organization_phone'      => new EE_Text_Input(
193
-                        array(
194
-                            'html_name' => 'organization_phone',
195
-                            'html_label_text' => esc_html__('Phone Number', 'event_espresso'),
196
-                            'html_help_text'  => esc_html__(
197
-                                'The phone number for your organization.',
198
-                                'event_espresso'
199
-                            ),
200
-                            'default'         => $this->organization_config->get_pretty('phone'),
201
-                            'required'        => false,
202
-                        )
203
-                    ),
204
-                    'organization_vat'      => new EE_Text_Input(
205
-                        array(
206
-                            'html_name' => 'organization_vat',
207
-                            'html_label_text' => esc_html__('VAT/Tax Number', 'event_espresso'),
208
-                            'html_help_text'  => esc_html__(
209
-                                'The VAT/Tax Number may be displayed on invoices and receipts.',
210
-                                'event_espresso'
211
-                            ),
212
-                            'default'         => $this->organization_config->get_pretty('vat'),
213
-                            'required'        => false,
214
-                        )
215
-                    ),
216
-                    'company_logo_hdr'        => new EE_Form_Section_HTML(
217
-                        EEH_HTML::h2(
218
-                            esc_html__('Company Logo', 'event_espresso')
219
-                            . ' '
220
-                            . EEH_HTML::span(EEH_Template::get_help_tab_link('organization_logo_info')),
221
-                            '',
222
-                            'company-logo-hdr'
223
-                        )
224
-                    ),
225
-                    'organization_logo_url'      => new EE_Admin_File_Uploader_Input(
226
-                        array(
227
-                            'html_name' => 'organization_logo_url',
228
-                            'html_label_text' => esc_html__('Upload New Logo', 'event_espresso'),
229
-                            'html_help_text'  => esc_html__(
230
-                                'Your logo will be used on custom invoices, tickets, certificates, and payment templates.',
231
-                                'event_espresso'
232
-                            ),
233
-                            'default'         => $this->organization_config->get_pretty('logo_url'),
234
-                            'required'        => false,
235
-                        )
236
-                    ),
237
-                    'social_links_hdr'        => new EE_Form_Section_HTML(
238
-                        EEH_HTML::h2(
239
-                            esc_html__('Social Links', 'event_espresso')
240
-                            . ' '
241
-                            . EEH_HTML::span(EEH_Template::get_help_tab_link('social_links_info'))
242
-                            . EEH_HTML::br()
243
-                            . EEH_HTML::p(
244
-                                esc_html__(
245
-                                    'Enter any links to social accounts for your organization here',
246
-                                    'event_espresso'
247
-                                ),
248
-                                '',
249
-                                'description'
250
-                            ),
251
-                            '',
252
-                            'social-links-hdr'
253
-                        )
254
-                    ),
255
-                    'organization_facebook'      => new EE_Text_Input(
256
-                        array(
257
-                            'html_name' => 'organization_facebook',
258
-                            'html_label_text' => esc_html__('Facebook', 'event_espresso'),
259
-                            'other_html_attributes' => ' placeholder="facebook.com/profile.name"',
260
-                            'default'         => $this->organization_config->get_pretty('facebook'),
261
-                            'required'        => false,
262
-                        )
263
-                    ),
264
-                    'organization_twitter'      => new EE_Text_Input(
265
-                        array(
266
-                            'html_name' => 'organization_twitter',
267
-                            'html_label_text' => esc_html__('Twitter', 'event_espresso'),
268
-                            'other_html_attributes' => ' placeholder="twitter.com/twitterhandle"',
269
-                            'default'         => $this->organization_config->get_pretty('twitter'),
270
-                            'required'        => false,
271
-                        )
272
-                    ),
273
-                    'organization_linkedin'      => new EE_Text_Input(
274
-                        array(
275
-                            'html_name' => 'organization_linkedin',
276
-                            'html_label_text' => esc_html__('LinkedIn', 'event_espresso'),
277
-                            'other_html_attributes' => ' placeholder="linkedin.com/in/profilename"',
278
-                            'default'         => $this->organization_config->get_pretty('linkedin'),
279
-                            'required'        => false,
280
-                        )
281
-                    ),
282
-                    'organization_pinterest'      => new EE_Text_Input(
283
-                        array(
284
-                            'html_name' => 'organization_pinterest',
285
-                            'html_label_text' => esc_html__('Pinterest', 'event_espresso'),
286
-                            'other_html_attributes' => ' placeholder="pinterest.com/profilename"',
287
-                            'default'         => $this->organization_config->get_pretty('pinterest'),
288
-                            'required'        => false,
289
-                        )
290
-                    ),
291
-                    'organization_google'      => new EE_Text_Input(
292
-                        array(
293
-                            'html_name' => 'organization_google',
294
-                            'html_label_text' => esc_html__('Google+', 'event_espresso'),
295
-                            'other_html_attributes' => ' placeholder="google.com/+profilename"',
296
-                            'default'         => $this->organization_config->get_pretty('google'),
297
-                            'required'        => false,
298
-                        )
299
-                    ),
300
-                    'organization_instagram'      => new EE_Text_Input(
301
-                        array(
302
-                            'html_name' => 'organization_instagram',
303
-                            'html_label_text' => esc_html__('Instagram', 'event_espresso'),
304
-                            'other_html_attributes' => ' placeholder="instagram.com/handle"',
305
-                            'default'         => $this->organization_config->get_pretty('instagram'),
306
-                            'required'        => false,
307
-                        )
308
-                    ),
309
-                ),
310
-            )
311
-        );
312
-        if (is_main_site()) {
313
-            $form->add_subsections(
314
-                array(
315
-                    'site_license_key_hdr' => new EE_Form_Section_HTML(
316
-                        EEH_HTML::h2(
317
-                            esc_html__('Your Event Espresso License Key', 'event_espresso')
318
-                            . ' '
319
-                            . EEH_HTML::span(
320
-                                EEH_Template::get_help_tab_link('site_license_key_info'),
321
-                                'help_tour_activation'
322
-                            ),
323
-                            '',
324
-                            'site-license-key-hdr'
325
-                        )
326
-                    ),
327
-                    'site_license_key' => $this->getSiteLicenseKeyField()
328
-                )
329
-            );
330
-            $form->add_subsections(
331
-                array(
332
-                    'uxip_optin_hdr' => new EE_Form_Section_HTML(
333
-                        $this->uxipOptinText()
334
-                    ),
335
-                    'ueip_optin' => new EE_Checkbox_Multi_Input(
336
-                        array(
337
-                            true => __('Yes! I want to help improve Event Espresso!', 'event_espresso')
338
-                        ),
339
-                        array(
340
-                            'html_name' => EE_Core_Config::OPTION_NAME_UXIP,
341
-                            'html_label_text' => esc_html__(
342
-                                'UXIP Opt In?',
343
-                                'event_espresso'
344
-                            ),
345
-                            'default'         => isset($this->core_config->ee_ueip_optin)
346
-                                ? filter_var($this->core_config->ee_ueip_optin, FILTER_VALIDATE_BOOLEAN)
347
-                                : false,
348
-                            'required'        => false,
349
-                        )
350
-                    ),
351
-                ),
352
-                'organization_instagram',
353
-                false
354
-            );
355
-        }
356
-        return $form;
357
-    }
91
+	/**
92
+	 * creates and returns the actual form
93
+	 *
94
+	 * @return EE_Form_Section_Proper
95
+	 * @throws EE_Error
96
+	 */
97
+	public function generate()
98
+	{
99
+		$form = new EE_Form_Section_Proper(
100
+			array(
101
+				'name'            => 'organization_settings',
102
+				'html_id'         => 'organization_settings',
103
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
104
+				'subsections'     => array(
105
+					'contact_information_hdr'        => new EE_Form_Section_HTML(
106
+						EEH_HTML::h2(
107
+							esc_html__('Contact Information', 'event_espresso')
108
+							. ' '
109
+							. EEH_HTML::span(EEH_Template::get_help_tab_link('contact_info_info')),
110
+							'',
111
+							'contact-information-hdr'
112
+						)
113
+					),
114
+					'organization_name'      => new EE_Text_Input(
115
+						array(
116
+							'html_name' => 'organization_name',
117
+							'html_label_text' => esc_html__('Organization Name', 'event_espresso'),
118
+							'html_help_text'  => esc_html__(
119
+								'Displayed on all emails and invoices.',
120
+								'event_espresso'
121
+							),
122
+							'default'         => $this->organization_config->get_pretty('name'),
123
+							'required'        => false,
124
+						)
125
+					),
126
+					'organization_address_1'      => new EE_Text_Input(
127
+						array(
128
+							'html_name' => 'organization_address_1',
129
+							'html_label_text' => esc_html__('Street Address', 'event_espresso'),
130
+							'default'         => $this->organization_config->get_pretty('address_1'),
131
+							'required'        => false,
132
+						)
133
+					),
134
+					'organization_address_2'      => new EE_Text_Input(
135
+						array(
136
+							'html_name' => 'organization_address_2',
137
+							'html_label_text' => esc_html__('Street Address 2', 'event_espresso'),
138
+							'default'         => $this->organization_config->get_pretty('address_2'),
139
+							'required'        => false,
140
+						)
141
+					),
142
+					'organization_city'      => new EE_Text_Input(
143
+						array(
144
+							'html_name' => 'organization_city',
145
+							'html_label_text' => esc_html__('City', 'event_espresso'),
146
+							'default'         => $this->organization_config->get_pretty('city'),
147
+							'required'        => false,
148
+						)
149
+					),
150
+					'organization_state'      => new EE_State_Select_Input(
151
+						null,
152
+						array(
153
+							'html_name' => 'organization_state',
154
+							'html_label_text' => esc_html__('State/Province', 'event_espresso'),
155
+							'default'         => $this->organization_config->STA_ID,
156
+							'required'        => false,
157
+						)
158
+					),
159
+					'organization_country'      => new EE_Country_Select_Input(
160
+						null,
161
+						array(
162
+							'html_name' => 'organization_country',
163
+							'html_label_text' => esc_html__('Country', 'event_espresso'),
164
+							'default'         => $this->organization_config->CNT_ISO,
165
+							'required'        => false,
166
+						)
167
+					),
168
+					'organization_zip'      => new EE_Text_Input(
169
+						array(
170
+							'html_name' => 'organization_zip',
171
+							'html_label_text' => esc_html__('Zip/Postal Code', 'event_espresso'),
172
+							'default'         => $this->organization_config->get_pretty('zip'),
173
+							'required'        => false,
174
+						)
175
+					),
176
+					'organization_email'      => new EE_Text_Input(
177
+						array(
178
+							'html_name' => 'organization_email',
179
+							'html_label_text' => esc_html__('Primary Contact Email', 'event_espresso'),
180
+							'html_help_text'  => sprintf(
181
+								esc_html__(
182
+									'This is where notifications go to when you use the %1$s and %2$s shortcodes in the message templates.',
183
+									'event_espresso'
184
+								),
185
+								'<code>[CO_FORMATTED_EMAIL]</code>',
186
+								'<code>[CO_EMAIL]</code>'
187
+							),
188
+							'default'         => $this->organization_config->get_pretty('email'),
189
+							'required'        => false,
190
+						)
191
+					),
192
+					'organization_phone'      => new EE_Text_Input(
193
+						array(
194
+							'html_name' => 'organization_phone',
195
+							'html_label_text' => esc_html__('Phone Number', 'event_espresso'),
196
+							'html_help_text'  => esc_html__(
197
+								'The phone number for your organization.',
198
+								'event_espresso'
199
+							),
200
+							'default'         => $this->organization_config->get_pretty('phone'),
201
+							'required'        => false,
202
+						)
203
+					),
204
+					'organization_vat'      => new EE_Text_Input(
205
+						array(
206
+							'html_name' => 'organization_vat',
207
+							'html_label_text' => esc_html__('VAT/Tax Number', 'event_espresso'),
208
+							'html_help_text'  => esc_html__(
209
+								'The VAT/Tax Number may be displayed on invoices and receipts.',
210
+								'event_espresso'
211
+							),
212
+							'default'         => $this->organization_config->get_pretty('vat'),
213
+							'required'        => false,
214
+						)
215
+					),
216
+					'company_logo_hdr'        => new EE_Form_Section_HTML(
217
+						EEH_HTML::h2(
218
+							esc_html__('Company Logo', 'event_espresso')
219
+							. ' '
220
+							. EEH_HTML::span(EEH_Template::get_help_tab_link('organization_logo_info')),
221
+							'',
222
+							'company-logo-hdr'
223
+						)
224
+					),
225
+					'organization_logo_url'      => new EE_Admin_File_Uploader_Input(
226
+						array(
227
+							'html_name' => 'organization_logo_url',
228
+							'html_label_text' => esc_html__('Upload New Logo', 'event_espresso'),
229
+							'html_help_text'  => esc_html__(
230
+								'Your logo will be used on custom invoices, tickets, certificates, and payment templates.',
231
+								'event_espresso'
232
+							),
233
+							'default'         => $this->organization_config->get_pretty('logo_url'),
234
+							'required'        => false,
235
+						)
236
+					),
237
+					'social_links_hdr'        => new EE_Form_Section_HTML(
238
+						EEH_HTML::h2(
239
+							esc_html__('Social Links', 'event_espresso')
240
+							. ' '
241
+							. EEH_HTML::span(EEH_Template::get_help_tab_link('social_links_info'))
242
+							. EEH_HTML::br()
243
+							. EEH_HTML::p(
244
+								esc_html__(
245
+									'Enter any links to social accounts for your organization here',
246
+									'event_espresso'
247
+								),
248
+								'',
249
+								'description'
250
+							),
251
+							'',
252
+							'social-links-hdr'
253
+						)
254
+					),
255
+					'organization_facebook'      => new EE_Text_Input(
256
+						array(
257
+							'html_name' => 'organization_facebook',
258
+							'html_label_text' => esc_html__('Facebook', 'event_espresso'),
259
+							'other_html_attributes' => ' placeholder="facebook.com/profile.name"',
260
+							'default'         => $this->organization_config->get_pretty('facebook'),
261
+							'required'        => false,
262
+						)
263
+					),
264
+					'organization_twitter'      => new EE_Text_Input(
265
+						array(
266
+							'html_name' => 'organization_twitter',
267
+							'html_label_text' => esc_html__('Twitter', 'event_espresso'),
268
+							'other_html_attributes' => ' placeholder="twitter.com/twitterhandle"',
269
+							'default'         => $this->organization_config->get_pretty('twitter'),
270
+							'required'        => false,
271
+						)
272
+					),
273
+					'organization_linkedin'      => new EE_Text_Input(
274
+						array(
275
+							'html_name' => 'organization_linkedin',
276
+							'html_label_text' => esc_html__('LinkedIn', 'event_espresso'),
277
+							'other_html_attributes' => ' placeholder="linkedin.com/in/profilename"',
278
+							'default'         => $this->organization_config->get_pretty('linkedin'),
279
+							'required'        => false,
280
+						)
281
+					),
282
+					'organization_pinterest'      => new EE_Text_Input(
283
+						array(
284
+							'html_name' => 'organization_pinterest',
285
+							'html_label_text' => esc_html__('Pinterest', 'event_espresso'),
286
+							'other_html_attributes' => ' placeholder="pinterest.com/profilename"',
287
+							'default'         => $this->organization_config->get_pretty('pinterest'),
288
+							'required'        => false,
289
+						)
290
+					),
291
+					'organization_google'      => new EE_Text_Input(
292
+						array(
293
+							'html_name' => 'organization_google',
294
+							'html_label_text' => esc_html__('Google+', 'event_espresso'),
295
+							'other_html_attributes' => ' placeholder="google.com/+profilename"',
296
+							'default'         => $this->organization_config->get_pretty('google'),
297
+							'required'        => false,
298
+						)
299
+					),
300
+					'organization_instagram'      => new EE_Text_Input(
301
+						array(
302
+							'html_name' => 'organization_instagram',
303
+							'html_label_text' => esc_html__('Instagram', 'event_espresso'),
304
+							'other_html_attributes' => ' placeholder="instagram.com/handle"',
305
+							'default'         => $this->organization_config->get_pretty('instagram'),
306
+							'required'        => false,
307
+						)
308
+					),
309
+				),
310
+			)
311
+		);
312
+		if (is_main_site()) {
313
+			$form->add_subsections(
314
+				array(
315
+					'site_license_key_hdr' => new EE_Form_Section_HTML(
316
+						EEH_HTML::h2(
317
+							esc_html__('Your Event Espresso License Key', 'event_espresso')
318
+							. ' '
319
+							. EEH_HTML::span(
320
+								EEH_Template::get_help_tab_link('site_license_key_info'),
321
+								'help_tour_activation'
322
+							),
323
+							'',
324
+							'site-license-key-hdr'
325
+						)
326
+					),
327
+					'site_license_key' => $this->getSiteLicenseKeyField()
328
+				)
329
+			);
330
+			$form->add_subsections(
331
+				array(
332
+					'uxip_optin_hdr' => new EE_Form_Section_HTML(
333
+						$this->uxipOptinText()
334
+					),
335
+					'ueip_optin' => new EE_Checkbox_Multi_Input(
336
+						array(
337
+							true => __('Yes! I want to help improve Event Espresso!', 'event_espresso')
338
+						),
339
+						array(
340
+							'html_name' => EE_Core_Config::OPTION_NAME_UXIP,
341
+							'html_label_text' => esc_html__(
342
+								'UXIP Opt In?',
343
+								'event_espresso'
344
+							),
345
+							'default'         => isset($this->core_config->ee_ueip_optin)
346
+								? filter_var($this->core_config->ee_ueip_optin, FILTER_VALIDATE_BOOLEAN)
347
+								: false,
348
+							'required'        => false,
349
+						)
350
+					),
351
+				),
352
+				'organization_instagram',
353
+				false
354
+			);
355
+		}
356
+		return $form;
357
+	}
358 358
 
359 359
 
360
-    /**
361
-     * takes the generated form and displays it along with ony other non-form HTML that may be required
362
-     * returns a string of HTML that can be directly echoed in a template
363
-     *
364
-     * @return string
365
-     * @throws EE_Error
366
-     * @throws InvalidArgumentException
367
-     * @throws InvalidDataTypeException
368
-     * @throws InvalidInterfaceException
369
-     * @throws LogicException
370
-     */
371
-    public function display()
372
-    {
373
-        $this->form()->enqueue_js();
374
-        return parent::display();
375
-    }
360
+	/**
361
+	 * takes the generated form and displays it along with ony other non-form HTML that may be required
362
+	 * returns a string of HTML that can be directly echoed in a template
363
+	 *
364
+	 * @return string
365
+	 * @throws EE_Error
366
+	 * @throws InvalidArgumentException
367
+	 * @throws InvalidDataTypeException
368
+	 * @throws InvalidInterfaceException
369
+	 * @throws LogicException
370
+	 */
371
+	public function display()
372
+	{
373
+		$this->form()->enqueue_js();
374
+		return parent::display();
375
+	}
376 376
 
377 377
 
378
-    /**
379
-     * handles processing the form submission
380
-     * returns true or false depending on whether the form was processed successfully or not
381
-     *
382
-     * @param array $form_data
383
-     * @return bool
384
-     * @throws InvalidFormSubmissionException
385
-     * @throws EE_Error
386
-     * @throws LogicException
387
-     * @throws InvalidArgumentException
388
-     * @throws InvalidDataTypeException
389
-     */
390
-    public function process($form_data = array())
391
-    {
392
-        // process form
393
-        $valid_data = (array) parent::process($form_data);
394
-        if (empty($valid_data)) {
395
-            return false;
396
-        }
378
+	/**
379
+	 * handles processing the form submission
380
+	 * returns true or false depending on whether the form was processed successfully or not
381
+	 *
382
+	 * @param array $form_data
383
+	 * @return bool
384
+	 * @throws InvalidFormSubmissionException
385
+	 * @throws EE_Error
386
+	 * @throws LogicException
387
+	 * @throws InvalidArgumentException
388
+	 * @throws InvalidDataTypeException
389
+	 */
390
+	public function process($form_data = array())
391
+	{
392
+		// process form
393
+		$valid_data = (array) parent::process($form_data);
394
+		if (empty($valid_data)) {
395
+			return false;
396
+		}
397 397
 
398
-        if (is_main_site()) {
399
-            $this->network_core_config->site_license_key = isset($form_data['ee_site_license_key'])
400
-                ? sanitize_text_field($form_data['ee_site_license_key'])
401
-                : $this->network_core_config->site_license_key;
402
-        }
403
-        $this->organization_config->name = isset($form_data['organization_name'])
404
-            ? sanitize_text_field($form_data['organization_name'])
405
-            : $this->organization_config->name;
406
-        $this->organization_config->address_1 = isset($form_data['organization_address_1'])
407
-            ? sanitize_text_field($form_data['organization_address_1'])
408
-            : $this->organization_config->address_1;
409
-        $this->organization_config->address_2 = isset($form_data['organization_address_2'])
410
-            ? sanitize_text_field($form_data['organization_address_2'])
411
-            : $this->organization_config->address_2;
412
-        $this->organization_config->city = isset($form_data['organization_city'])
413
-            ? sanitize_text_field($form_data['organization_city'])
414
-            : $this->organization_config->city;
415
-        $this->organization_config->STA_ID = isset($form_data['organization_state'])
416
-            ? absint($form_data['organization_state'])
417
-            : $this->organization_config->STA_ID;
418
-        $this->organization_config->CNT_ISO = isset($form_data['organization_country'])
419
-            ? sanitize_text_field($form_data['organization_country'])
420
-            : $this->organization_config->CNT_ISO;
421
-        $this->organization_config->zip = isset($form_data['organization_zip'])
422
-            ? sanitize_text_field($form_data['organization_zip'])
423
-            : $this->organization_config->zip;
424
-        $this->organization_config->email = isset($form_data['organization_email'])
425
-            ? sanitize_email($form_data['organization_email'])
426
-            : $this->organization_config->email;
427
-        $this->organization_config->vat = isset($form_data['organization_vat'])
428
-            ? sanitize_text_field($form_data['organization_vat'])
429
-            : $this->organization_config->vat;
430
-        $this->organization_config->phone = isset($form_data['organization_phone'])
431
-            ? sanitize_text_field($form_data['organization_phone'])
432
-            : $this->organization_config->phone;
433
-        $this->organization_config->logo_url = isset($form_data['organization_logo_url'])
434
-            ? esc_url_raw($form_data['organization_logo_url'])
435
-            : $this->organization_config->logo_url;
436
-        $this->organization_config->facebook = isset($form_data['organization_facebook'])
437
-            ? esc_url_raw($form_data['organization_facebook'])
438
-            : $this->organization_config->facebook;
439
-        $this->organization_config->twitter = isset($form_data['organization_twitter'])
440
-            ? esc_url_raw($form_data['organization_twitter'])
441
-            : $this->organization_config->twitter;
442
-        $this->organization_config->linkedin = isset($form_data['organization_linkedin'])
443
-            ? esc_url_raw($form_data['organization_linkedin'])
444
-            : $this->organization_config->linkedin;
445
-        $this->organization_config->pinterest = isset($form_data['organization_pinterest'])
446
-            ? esc_url_raw($form_data['organization_pinterest'])
447
-            : $this->organization_config->pinterest;
448
-        $this->organization_config->google = isset($form_data['organization_google'])
449
-            ? esc_url_raw($form_data['organization_google'])
450
-            : $this->organization_config->google;
451
-        $this->organization_config->instagram = isset($form_data['organization_instagram'])
452
-            ? esc_url_raw($form_data['organization_instagram'])
453
-            : $this->organization_config->instagram;
454
-        $this->core_config->ee_ueip_optin = isset($form_data[ EE_Core_Config::OPTION_NAME_UXIP ][0])
455
-            ? filter_var($form_data[ EE_Core_Config::OPTION_NAME_UXIP ][0], FILTER_VALIDATE_BOOLEAN)
456
-            : false;
457
-        $this->core_config->ee_ueip_has_notified = true;
398
+		if (is_main_site()) {
399
+			$this->network_core_config->site_license_key = isset($form_data['ee_site_license_key'])
400
+				? sanitize_text_field($form_data['ee_site_license_key'])
401
+				: $this->network_core_config->site_license_key;
402
+		}
403
+		$this->organization_config->name = isset($form_data['organization_name'])
404
+			? sanitize_text_field($form_data['organization_name'])
405
+			: $this->organization_config->name;
406
+		$this->organization_config->address_1 = isset($form_data['organization_address_1'])
407
+			? sanitize_text_field($form_data['organization_address_1'])
408
+			: $this->organization_config->address_1;
409
+		$this->organization_config->address_2 = isset($form_data['organization_address_2'])
410
+			? sanitize_text_field($form_data['organization_address_2'])
411
+			: $this->organization_config->address_2;
412
+		$this->organization_config->city = isset($form_data['organization_city'])
413
+			? sanitize_text_field($form_data['organization_city'])
414
+			: $this->organization_config->city;
415
+		$this->organization_config->STA_ID = isset($form_data['organization_state'])
416
+			? absint($form_data['organization_state'])
417
+			: $this->organization_config->STA_ID;
418
+		$this->organization_config->CNT_ISO = isset($form_data['organization_country'])
419
+			? sanitize_text_field($form_data['organization_country'])
420
+			: $this->organization_config->CNT_ISO;
421
+		$this->organization_config->zip = isset($form_data['organization_zip'])
422
+			? sanitize_text_field($form_data['organization_zip'])
423
+			: $this->organization_config->zip;
424
+		$this->organization_config->email = isset($form_data['organization_email'])
425
+			? sanitize_email($form_data['organization_email'])
426
+			: $this->organization_config->email;
427
+		$this->organization_config->vat = isset($form_data['organization_vat'])
428
+			? sanitize_text_field($form_data['organization_vat'])
429
+			: $this->organization_config->vat;
430
+		$this->organization_config->phone = isset($form_data['organization_phone'])
431
+			? sanitize_text_field($form_data['organization_phone'])
432
+			: $this->organization_config->phone;
433
+		$this->organization_config->logo_url = isset($form_data['organization_logo_url'])
434
+			? esc_url_raw($form_data['organization_logo_url'])
435
+			: $this->organization_config->logo_url;
436
+		$this->organization_config->facebook = isset($form_data['organization_facebook'])
437
+			? esc_url_raw($form_data['organization_facebook'])
438
+			: $this->organization_config->facebook;
439
+		$this->organization_config->twitter = isset($form_data['organization_twitter'])
440
+			? esc_url_raw($form_data['organization_twitter'])
441
+			: $this->organization_config->twitter;
442
+		$this->organization_config->linkedin = isset($form_data['organization_linkedin'])
443
+			? esc_url_raw($form_data['organization_linkedin'])
444
+			: $this->organization_config->linkedin;
445
+		$this->organization_config->pinterest = isset($form_data['organization_pinterest'])
446
+			? esc_url_raw($form_data['organization_pinterest'])
447
+			: $this->organization_config->pinterest;
448
+		$this->organization_config->google = isset($form_data['organization_google'])
449
+			? esc_url_raw($form_data['organization_google'])
450
+			: $this->organization_config->google;
451
+		$this->organization_config->instagram = isset($form_data['organization_instagram'])
452
+			? esc_url_raw($form_data['organization_instagram'])
453
+			: $this->organization_config->instagram;
454
+		$this->core_config->ee_ueip_optin = isset($form_data[ EE_Core_Config::OPTION_NAME_UXIP ][0])
455
+			? filter_var($form_data[ EE_Core_Config::OPTION_NAME_UXIP ][0], FILTER_VALIDATE_BOOLEAN)
456
+			: false;
457
+		$this->core_config->ee_ueip_has_notified = true;
458 458
 
459
-        $this->registry->CFG->currency = new EE_Currency_Config(
460
-            $this->organization_config->CNT_ISO
461
-        );
462
-        return true;
463
-    }
459
+		$this->registry->CFG->currency = new EE_Currency_Config(
460
+			$this->organization_config->CNT_ISO
461
+		);
462
+		return true;
463
+	}
464 464
 
465 465
 
466
-    /**
467
-     * @return string
468
-     */
469
-    private function uxipOptinText()
470
-    {
471
-        ob_start();
472
-        Stats::optinText(false);
473
-        return ob_get_clean();
474
-    }
466
+	/**
467
+	 * @return string
468
+	 */
469
+	private function uxipOptinText()
470
+	{
471
+		ob_start();
472
+		Stats::optinText(false);
473
+		return ob_get_clean();
474
+	}
475 475
 
476 476
 
477
-    /**
478
-     * Return whether the site license key has been verified or not.
479
-     * @return bool
480
-     */
481
-    private function licenseKeyVerified()
482
-    {
483
-        if (empty($this->network_core_config->site_license_key)) {
484
-            return false;
485
-        }
486
-        $ver_option_key = 'puvererr_' . basename(EE_PLUGIN_BASENAME);
487
-        $verify_fail = get_option($ver_option_key, false);
488
-        return $verify_fail === false
489
-                  || (! empty($this->network_core_config->site_license_key)
490
-                        && $verify_fail === false
491
-                  );
492
-    }
477
+	/**
478
+	 * Return whether the site license key has been verified or not.
479
+	 * @return bool
480
+	 */
481
+	private function licenseKeyVerified()
482
+	{
483
+		if (empty($this->network_core_config->site_license_key)) {
484
+			return false;
485
+		}
486
+		$ver_option_key = 'puvererr_' . basename(EE_PLUGIN_BASENAME);
487
+		$verify_fail = get_option($ver_option_key, false);
488
+		return $verify_fail === false
489
+				  || (! empty($this->network_core_config->site_license_key)
490
+						&& $verify_fail === false
491
+				  );
492
+	}
493 493
 
494 494
 
495
-    /**
496
-     * @return EE_Text_Input
497
-     */
498
-    private function getSiteLicenseKeyField()
499
-    {
500
-        $text_input = new EE_Text_Input(
501
-            array(
502
-                'html_name' => 'ee_site_license_key',
503
-                'html_id' => 'site_license_key',
504
-                'html_label_text' => esc_html__('Support License Key', 'event_espresso'),
505
-                /** phpcs:disable WordPress.WP.I18n.UnorderedPlaceholdersText */
506
-                'html_help_text'  => sprintf(
507
-                    esc_html__(
508
-                        'Adding a valid Support License Key will enable automatic update notifications and backend updates for Event Espresso Core and any installed add-ons. If this is a Development or Test site, %sDO NOT%s enter your Support License Key.',
509
-                        'event_espresso'
510
-                    ),
511
-                    '<strong>',
512
-                    '</strong>'
513
-                ),
514
-                /** phpcs:enable */
515
-                'default'         => isset($this->network_core_config->site_license_key)
516
-                    ? $this->network_core_config->site_license_key
517
-                    : '',
518
-                'required'        => false,
519
-                'form_html_filter' => new VsprintfFilter(
520
-                    '%2$s %1$s',
521
-                    array($this->getValidationIndicator())
522
-                )
523
-            )
524
-        );
525
-        return $text_input;
526
-    }
495
+	/**
496
+	 * @return EE_Text_Input
497
+	 */
498
+	private function getSiteLicenseKeyField()
499
+	{
500
+		$text_input = new EE_Text_Input(
501
+			array(
502
+				'html_name' => 'ee_site_license_key',
503
+				'html_id' => 'site_license_key',
504
+				'html_label_text' => esc_html__('Support License Key', 'event_espresso'),
505
+				/** phpcs:disable WordPress.WP.I18n.UnorderedPlaceholdersText */
506
+				'html_help_text'  => sprintf(
507
+					esc_html__(
508
+						'Adding a valid Support License Key will enable automatic update notifications and backend updates for Event Espresso Core and any installed add-ons. If this is a Development or Test site, %sDO NOT%s enter your Support License Key.',
509
+						'event_espresso'
510
+					),
511
+					'<strong>',
512
+					'</strong>'
513
+				),
514
+				/** phpcs:enable */
515
+				'default'         => isset($this->network_core_config->site_license_key)
516
+					? $this->network_core_config->site_license_key
517
+					: '',
518
+				'required'        => false,
519
+				'form_html_filter' => new VsprintfFilter(
520
+					'%2$s %1$s',
521
+					array($this->getValidationIndicator())
522
+				)
523
+			)
524
+		);
525
+		return $text_input;
526
+	}
527 527
 
528 528
 
529
-    /**
530
-     * @return string
531
-     */
532
-    private function getValidationIndicator()
533
-    {
534
-        $verified_class = $this->licenseKeyVerified() ? 'ee-icon-color-ee-green' : 'ee-icon-color-ee-red';
535
-        return '<span class="dashicons dashicons-admin-network ' . $verified_class . ' ee-icon-size-20"></span>';
536
-    }
529
+	/**
530
+	 * @return string
531
+	 */
532
+	private function getValidationIndicator()
533
+	{
534
+		$verified_class = $this->licenseKeyVerified() ? 'ee-icon-color-ee-green' : 'ee-icon-color-ee-red';
535
+		return '<span class="dashicons dashicons-admin-network ' . $verified_class . ' ee-icon-size-20"></span>';
536
+	}
537 537
 }
Please login to merge, or discard this patch.
admin_pages/transactions/Transactions_Admin_Page.core.php 2 patches
Indentation   +2464 added lines, -2464 removed lines patch added patch discarded remove patch
@@ -14,2468 +14,2468 @@
 block discarded – undo
14 14
 class Transactions_Admin_Page extends EE_Admin_Page
15 15
 {
16 16
 
17
-    /**
18
-     * @var EE_Transaction
19
-     */
20
-    private $_transaction;
21
-
22
-    /**
23
-     * @var EE_Session
24
-     */
25
-    private $_session;
26
-
27
-    /**
28
-     * @var array $_txn_status
29
-     */
30
-    private static $_txn_status;
31
-
32
-    /**
33
-     * @var array $_pay_status
34
-     */
35
-    private static $_pay_status;
36
-
37
-    /**
38
-     * @var array $_existing_reg_payment_REG_IDs
39
-     */
40
-    protected $_existing_reg_payment_REG_IDs = null;
41
-
42
-
43
-    /**
44
-     * @Constructor
45
-     * @access public
46
-     * @param bool $routing
47
-     * @throws EE_Error
48
-     * @throws InvalidArgumentException
49
-     * @throws ReflectionException
50
-     * @throws InvalidDataTypeException
51
-     * @throws InvalidInterfaceException
52
-     */
53
-    public function __construct($routing = true)
54
-    {
55
-        parent::__construct($routing);
56
-    }
57
-
58
-
59
-    /**
60
-     *    _init_page_props
61
-     *
62
-     * @return void
63
-     */
64
-    protected function _init_page_props()
65
-    {
66
-        $this->page_slug = TXN_PG_SLUG;
67
-        $this->page_label = esc_html__('Transactions', 'event_espresso');
68
-        $this->_admin_base_url = TXN_ADMIN_URL;
69
-        $this->_admin_base_path = TXN_ADMIN;
70
-    }
71
-
72
-
73
-    /**
74
-     *    _ajax_hooks
75
-     *
76
-     * @return void
77
-     */
78
-    protected function _ajax_hooks()
79
-    {
80
-        add_action('wp_ajax_espresso_apply_payment', array($this, 'apply_payments_or_refunds'));
81
-        add_action('wp_ajax_espresso_apply_refund', array($this, 'apply_payments_or_refunds'));
82
-        add_action('wp_ajax_espresso_delete_payment', array($this, 'delete_payment'));
83
-    }
84
-
85
-
86
-    /**
87
-     *    _define_page_props
88
-     *
89
-     * @return void
90
-     */
91
-    protected function _define_page_props()
92
-    {
93
-        $this->_admin_page_title = $this->page_label;
94
-        $this->_labels = array(
95
-            'buttons' => array(
96
-                'add'    => esc_html__('Add New Transaction', 'event_espresso'),
97
-                'edit'   => esc_html__('Edit Transaction', 'event_espresso'),
98
-                'delete' => esc_html__('Delete Transaction', 'event_espresso'),
99
-            ),
100
-        );
101
-    }
102
-
103
-
104
-    /**
105
-     *        grab url requests and route them
106
-     *
107
-     * @access private
108
-     * @return void
109
-     * @throws EE_Error
110
-     * @throws InvalidArgumentException
111
-     * @throws InvalidDataTypeException
112
-     * @throws InvalidInterfaceException
113
-     */
114
-    public function _set_page_routes()
115
-    {
116
-
117
-        $this->_set_transaction_status_array();
118
-
119
-        $txn_id = ! empty($this->_req_data['TXN_ID'])
120
-                  && ! is_array($this->_req_data['TXN_ID'])
121
-            ? $this->_req_data['TXN_ID']
122
-            : 0;
123
-
124
-        $this->_page_routes = array(
125
-
126
-            'default' => array(
127
-                'func'       => '_transactions_overview_list_table',
128
-                'capability' => 'ee_read_transactions',
129
-            ),
130
-
131
-            'view_transaction' => array(
132
-                'func'       => '_transaction_details',
133
-                'capability' => 'ee_read_transaction',
134
-                'obj_id'     => $txn_id,
135
-            ),
136
-
137
-            'send_payment_reminder' => array(
138
-                'func'       => '_send_payment_reminder',
139
-                'noheader'   => true,
140
-                'capability' => 'ee_send_message',
141
-            ),
142
-
143
-            'espresso_apply_payment' => array(
144
-                'func'       => 'apply_payments_or_refunds',
145
-                'noheader'   => true,
146
-                'capability' => 'ee_edit_payments',
147
-            ),
148
-
149
-            'espresso_apply_refund' => array(
150
-                'func'       => 'apply_payments_or_refunds',
151
-                'noheader'   => true,
152
-                'capability' => 'ee_edit_payments',
153
-            ),
154
-
155
-            'espresso_delete_payment' => array(
156
-                'func'       => 'delete_payment',
157
-                'noheader'   => true,
158
-                'capability' => 'ee_delete_payments',
159
-            ),
160
-
161
-        );
162
-    }
163
-
164
-
165
-    protected function _set_page_config()
166
-    {
167
-        $this->_page_config = array(
168
-            'default'          => array(
169
-                'nav'           => array(
170
-                    'label' => esc_html__('Overview', 'event_espresso'),
171
-                    'order' => 10,
172
-                ),
173
-                'list_table'    => 'EE_Admin_Transactions_List_Table',
174
-                'help_tabs'     => array(
175
-                    'transactions_overview_help_tab'                       => array(
176
-                        'title'    => esc_html__('Transactions Overview', 'event_espresso'),
177
-                        'filename' => 'transactions_overview',
178
-                    ),
179
-                    'transactions_overview_table_column_headings_help_tab' => array(
180
-                        'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'),
181
-                        'filename' => 'transactions_overview_table_column_headings',
182
-                    ),
183
-                    'transactions_overview_views_filters_help_tab'         => array(
184
-                        'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'),
185
-                        'filename' => 'transactions_overview_views_filters_search',
186
-                    ),
187
-                ),
188
-                'help_tour'     => array('Transactions_Overview_Help_Tour'),
189
-                /**
190
-                 * commented out because currently we are not displaying tips for transaction list table status but this
191
-                 * may change in a later iteration so want to keep the code for then.
192
-                 */
193
-                // 'qtips' => array( 'Transactions_List_Table_Tips' ),
194
-                'require_nonce' => false,
195
-            ),
196
-            'view_transaction' => array(
197
-                'nav'       => array(
198
-                    'label'      => esc_html__('View Transaction', 'event_espresso'),
199
-                    'order'      => 5,
200
-                    'url'        => isset($this->_req_data['TXN_ID'])
201
-                        ? add_query_arg(array('TXN_ID' => $this->_req_data['TXN_ID']), $this->_current_page_view_url)
202
-                        : $this->_admin_base_url,
203
-                    'persistent' => false,
204
-                ),
205
-                'help_tabs' => array(
206
-                    'transactions_view_transaction_help_tab'                                              => array(
207
-                        'title'    => esc_html__('View Transaction', 'event_espresso'),
208
-                        'filename' => 'transactions_view_transaction',
209
-                    ),
210
-                    'transactions_view_transaction_transaction_details_table_help_tab'                    => array(
211
-                        'title'    => esc_html__('Transaction Details Table', 'event_espresso'),
212
-                        'filename' => 'transactions_view_transaction_transaction_details_table',
213
-                    ),
214
-                    'transactions_view_transaction_attendees_registered_help_tab'                         => array(
215
-                        'title'    => esc_html__('Attendees Registered', 'event_espresso'),
216
-                        'filename' => 'transactions_view_transaction_attendees_registered',
217
-                    ),
218
-                    'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => array(
219
-                        'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'),
220
-                        'filename' => 'transactions_view_transaction_primary_registrant_billing_information',
221
-                    ),
222
-                ),
223
-                'qtips'     => array('Transaction_Details_Tips'),
224
-                'help_tour' => array('Transaction_Details_Help_Tour'),
225
-                'metaboxes' => array('_transaction_details_metaboxes'),
226
-
227
-                'require_nonce' => false,
228
-            ),
229
-        );
230
-    }
231
-
232
-
233
-    /**
234
-     * The below methods aren't used by this class currently
235
-     */
236
-    protected function _add_screen_options()
237
-    {
238
-        // noop
239
-    }
240
-
241
-    protected function _add_feature_pointers()
242
-    {
243
-        // noop
244
-    }
245
-
246
-    public function admin_init()
247
-    {
248
-        // IF a registration was JUST added via the admin...
249
-        if (isset(
250
-            $this->_req_data['redirect_from'],
251
-            $this->_req_data['EVT_ID'],
252
-            $this->_req_data['event_name']
253
-        )) {
254
-            // then set a cookie so that we can block any attempts to use
255
-            // the back button as a way to enter another registration.
256
-            setcookie(
257
-                'ee_registration_added',
258
-                $this->_req_data['EVT_ID'],
259
-                time() + WEEK_IN_SECONDS,
260
-                '/'
261
-            );
262
-            // and update the global
263
-            $_COOKIE['ee_registration_added'] = $this->_req_data['EVT_ID'];
264
-        }
265
-        EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__(
266
-            'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.',
267
-            'event_espresso'
268
-        );
269
-        EE_Registry::$i18n_js_strings['error_occurred'] = esc_html__(
270
-            'An error occurred! Please refresh the page and try again.',
271
-            'event_espresso'
272
-        );
273
-        EE_Registry::$i18n_js_strings['txn_status_array'] = self::$_txn_status;
274
-        EE_Registry::$i18n_js_strings['pay_status_array'] = self::$_pay_status;
275
-        EE_Registry::$i18n_js_strings['payments_total'] = esc_html__('Payments Total', 'event_espresso');
276
-        EE_Registry::$i18n_js_strings['transaction_overpaid'] = esc_html__(
277
-            'This transaction has been overpaid ! Payments Total',
278
-            'event_espresso'
279
-        );
280
-    }
281
-
282
-    public function admin_notices()
283
-    {
284
-        // noop
285
-    }
286
-
287
-    public function admin_footer_scripts()
288
-    {
289
-        // noop
290
-    }
291
-
292
-
293
-    /**
294
-     * _set_transaction_status_array
295
-     * sets list of transaction statuses
296
-     *
297
-     * @access private
298
-     * @return void
299
-     * @throws EE_Error
300
-     * @throws InvalidArgumentException
301
-     * @throws InvalidDataTypeException
302
-     * @throws InvalidInterfaceException
303
-     */
304
-    private function _set_transaction_status_array()
305
-    {
306
-        self::$_txn_status = EEM_Transaction::instance()->status_array(true);
307
-    }
308
-
309
-
310
-    /**
311
-     * get_transaction_status_array
312
-     * return the transaction status array for wp_list_table
313
-     *
314
-     * @access public
315
-     * @return array
316
-     */
317
-    public function get_transaction_status_array()
318
-    {
319
-        return self::$_txn_status;
320
-    }
321
-
322
-
323
-    /**
324
-     *    get list of payment statuses
325
-     *
326
-     * @access private
327
-     * @return void
328
-     * @throws EE_Error
329
-     * @throws InvalidArgumentException
330
-     * @throws InvalidDataTypeException
331
-     * @throws InvalidInterfaceException
332
-     */
333
-    private function _get_payment_status_array()
334
-    {
335
-        self::$_pay_status = EEM_Payment::instance()->status_array(true);
336
-        $this->_template_args['payment_status'] = self::$_pay_status;
337
-    }
338
-
339
-
340
-    /**
341
-     *    _add_screen_options_default
342
-     *
343
-     * @access protected
344
-     * @return void
345
-     * @throws InvalidArgumentException
346
-     * @throws InvalidDataTypeException
347
-     * @throws InvalidInterfaceException
348
-     */
349
-    protected function _add_screen_options_default()
350
-    {
351
-        $this->_per_page_screen_option();
352
-    }
353
-
354
-
355
-    /**
356
-     * load_scripts_styles
357
-     *
358
-     * @access public
359
-     * @return void
360
-     */
361
-    public function load_scripts_styles()
362
-    {
363
-        // enqueue style
364
-        wp_register_style(
365
-            'espresso_txn',
366
-            TXN_ASSETS_URL . 'espresso_transactions_admin.css',
367
-            array(),
368
-            EVENT_ESPRESSO_VERSION
369
-        );
370
-        wp_enqueue_style('espresso_txn');
371
-        // scripts
372
-        wp_register_script(
373
-            'espresso_txn',
374
-            TXN_ASSETS_URL . 'espresso_transactions_admin.js',
375
-            array(
376
-                'ee_admin_js',
377
-                'ee-datepicker',
378
-                'jquery-ui-datepicker',
379
-                'jquery-ui-draggable',
380
-                'ee-dialog',
381
-                'ee-accounting',
382
-                'ee-serialize-full-array',
383
-            ),
384
-            EVENT_ESPRESSO_VERSION,
385
-            true
386
-        );
387
-        wp_enqueue_script('espresso_txn');
388
-    }
389
-
390
-
391
-    /**
392
-     *    load_scripts_styles_view_transaction
393
-     *
394
-     * @access public
395
-     * @return void
396
-     */
397
-    public function load_scripts_styles_view_transaction()
398
-    {
399
-        // styles
400
-        wp_enqueue_style('espresso-ui-theme');
401
-    }
402
-
403
-
404
-    /**
405
-     *    load_scripts_styles_default
406
-     *
407
-     * @access public
408
-     * @return void
409
-     */
410
-    public function load_scripts_styles_default()
411
-    {
412
-        // styles
413
-        wp_enqueue_style('espresso-ui-theme');
414
-    }
415
-
416
-
417
-    /**
418
-     *    _set_list_table_views_default
419
-     *
420
-     * @access protected
421
-     * @return void
422
-     */
423
-    protected function _set_list_table_views_default()
424
-    {
425
-        $this->_views = array(
426
-            'all'       => array(
427
-                'slug'  => 'all',
428
-                'label' => esc_html__('View All Transactions', 'event_espresso'),
429
-                'count' => 0,
430
-            ),
431
-            'abandoned' => array(
432
-                'slug'  => 'abandoned',
433
-                'label' => esc_html__('Abandoned Transactions', 'event_espresso'),
434
-                'count' => 0,
435
-            ),
436
-            'failed'    => array(
437
-                'slug'  => 'failed',
438
-                'label' => esc_html__('Failed Transactions', 'event_espresso'),
439
-                'count' => 0,
440
-            ),
441
-        );
442
-    }
443
-
444
-
445
-    /**
446
-     * _set_transaction_object
447
-     * This sets the _transaction property for the transaction details screen
448
-     *
449
-     * @access private
450
-     * @return void
451
-     * @throws EE_Error
452
-     * @throws InvalidArgumentException
453
-     * @throws RuntimeException
454
-     * @throws InvalidDataTypeException
455
-     * @throws InvalidInterfaceException
456
-     * @throws ReflectionException
457
-     */
458
-    private function _set_transaction_object()
459
-    {
460
-        if ($this->_transaction instanceof EE_Transaction) {
461
-            return;
462
-        } //get out we've already set the object
463
-
464
-        $TXN_ID = ! empty($this->_req_data['TXN_ID'])
465
-            ? absint($this->_req_data['TXN_ID'])
466
-            : false;
467
-
468
-        // get transaction object
469
-        $this->_transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
470
-        $this->_session = $this->_transaction instanceof EE_Transaction
471
-            ? $this->_transaction->get('TXN_session_data')
472
-            : null;
473
-        if ($this->_transaction instanceof EE_Transaction) {
474
-            $this->_transaction->verify_abandoned_transaction_status();
475
-        }
476
-
477
-        if (! $this->_transaction instanceof EE_Transaction) {
478
-            $error_msg = sprintf(
479
-                esc_html__(
480
-                    'An error occurred and the details for the transaction with the ID # %d could not be retrieved.',
481
-                    'event_espresso'
482
-                ),
483
-                $TXN_ID
484
-            );
485
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
486
-        }
487
-    }
488
-
489
-
490
-    /**
491
-     *    _transaction_legend_items
492
-     *
493
-     * @access protected
494
-     * @return array
495
-     * @throws EE_Error
496
-     * @throws InvalidArgumentException
497
-     * @throws ReflectionException
498
-     * @throws InvalidDataTypeException
499
-     * @throws InvalidInterfaceException
500
-     */
501
-    protected function _transaction_legend_items()
502
-    {
503
-        EE_Registry::instance()->load_helper('MSG_Template');
504
-        $items = array();
505
-
506
-        if (EE_Registry::instance()->CAP->current_user_can(
507
-            'ee_read_global_messages',
508
-            'view_filtered_messages'
509
-        )) {
510
-            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
511
-            if (is_array($related_for_icon)
512
-                && isset($related_for_icon['css_class'], $related_for_icon['label'])
513
-            ) {
514
-                $items['view_related_messages'] = array(
515
-                    'class' => $related_for_icon['css_class'],
516
-                    'desc'  => $related_for_icon['label'],
517
-                );
518
-            }
519
-        }
520
-
521
-        $items = apply_filters(
522
-            'FHEE__Transactions_Admin_Page___transaction_legend_items__items',
523
-            array_merge(
524
-                $items,
525
-                array(
526
-                    'view_details'          => array(
527
-                        'class' => 'dashicons dashicons-cart',
528
-                        'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
529
-                    ),
530
-                    'view_invoice'          => array(
531
-                        'class' => 'dashicons dashicons-media-spreadsheet',
532
-                        'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
533
-                    ),
534
-                    'view_receipt'          => array(
535
-                        'class' => 'dashicons dashicons-media-default',
536
-                        'desc'  => esc_html__('View Transaction Receipt', 'event_espresso'),
537
-                    ),
538
-                    'view_registration'     => array(
539
-                        'class' => 'dashicons dashicons-clipboard',
540
-                        'desc'  => esc_html__('View Registration Details', 'event_espresso'),
541
-                    ),
542
-                    'payment_overview_link' => array(
543
-                        'class' => 'dashicons dashicons-money',
544
-                        'desc'  => esc_html__('Make Payment on Frontend', 'event_espresso'),
545
-                    ),
546
-                )
547
-            )
548
-        );
549
-
550
-        if (EE_Registry::instance()->CAP->current_user_can(
551
-            'ee_send_message',
552
-            'espresso_transactions_send_payment_reminder'
553
-        )) {
554
-            if (EEH_MSG_Template::is_mt_active('payment_reminder')) {
555
-                $items['send_payment_reminder'] = array(
556
-                    'class' => 'dashicons dashicons-email-alt',
557
-                    'desc'  => esc_html__('Send Payment Reminder', 'event_espresso'),
558
-                );
559
-            } else {
560
-                $items['blank*'] = array(
561
-                    'class' => '',
562
-                    'desc'  => '',
563
-                );
564
-            }
565
-        } else {
566
-            $items['blank*'] = array(
567
-                'class' => '',
568
-                'desc'  => '',
569
-            );
570
-        }
571
-        $more_items = apply_filters(
572
-            'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
573
-            array(
574
-                'overpaid'   => array(
575
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code,
576
-                    'desc'  => EEH_Template::pretty_status(
577
-                        EEM_Transaction::overpaid_status_code,
578
-                        false,
579
-                        'sentence'
580
-                    ),
581
-                ),
582
-                'complete'   => array(
583
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code,
584
-                    'desc'  => EEH_Template::pretty_status(
585
-                        EEM_Transaction::complete_status_code,
586
-                        false,
587
-                        'sentence'
588
-                    ),
589
-                ),
590
-                'incomplete' => array(
591
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code,
592
-                    'desc'  => EEH_Template::pretty_status(
593
-                        EEM_Transaction::incomplete_status_code,
594
-                        false,
595
-                        'sentence'
596
-                    ),
597
-                ),
598
-                'abandoned'  => array(
599
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code,
600
-                    'desc'  => EEH_Template::pretty_status(
601
-                        EEM_Transaction::abandoned_status_code,
602
-                        false,
603
-                        'sentence'
604
-                    ),
605
-                ),
606
-                'failed'     => array(
607
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code,
608
-                    'desc'  => EEH_Template::pretty_status(
609
-                        EEM_Transaction::failed_status_code,
610
-                        false,
611
-                        'sentence'
612
-                    ),
613
-                ),
614
-            )
615
-        );
616
-
617
-        return array_merge($items, $more_items);
618
-    }
619
-
620
-
621
-    /**
622
-     *    _transactions_overview_list_table
623
-     *
624
-     * @access protected
625
-     * @return void
626
-     * @throws DomainException
627
-     * @throws EE_Error
628
-     * @throws InvalidArgumentException
629
-     * @throws InvalidDataTypeException
630
-     * @throws InvalidInterfaceException
631
-     * @throws ReflectionException
632
-     */
633
-    protected function _transactions_overview_list_table()
634
-    {
635
-        $this->_admin_page_title = esc_html__('Transactions', 'event_espresso');
636
-        $event = isset($this->_req_data['EVT_ID'])
637
-            ? EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID'])
638
-            : null;
639
-        $this->_template_args['admin_page_header'] = $event instanceof EE_Event
640
-            ? sprintf(
641
-                esc_html__(
642
-                    '%sViewing Transactions for the Event: %s%s',
643
-                    'event_espresso'
644
-                ),
645
-                '<h3>',
646
-                '<a href="'
647
-                . EE_Admin_Page::add_query_args_and_nonce(
648
-                    array('action' => 'edit', 'post' => $event->ID()),
649
-                    EVENTS_ADMIN_URL
650
-                )
651
-                . '" title="'
652
-                . esc_attr__(
653
-                    'Click to Edit event',
654
-                    'event_espresso'
655
-                )
656
-                . '">' . $event->get('EVT_name') . '</a>',
657
-                '</h3>'
658
-            )
659
-            : '';
660
-        $this->_template_args['after_list_table'] = $this->_display_legend($this->_transaction_legend_items());
661
-        $this->display_admin_list_table_page_with_no_sidebar();
662
-    }
663
-
664
-
665
-    /**
666
-     *    _transaction_details
667
-     * generates HTML for the View Transaction Details Admin page
668
-     *
669
-     * @access protected
670
-     * @return void
671
-     * @throws DomainException
672
-     * @throws EE_Error
673
-     * @throws InvalidArgumentException
674
-     * @throws InvalidDataTypeException
675
-     * @throws InvalidInterfaceException
676
-     * @throws RuntimeException
677
-     * @throws ReflectionException
678
-     */
679
-    protected function _transaction_details()
680
-    {
681
-        do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction);
682
-
683
-        $this->_set_transaction_status_array();
684
-
685
-        $this->_template_args = array();
686
-        $this->_template_args['transactions_page'] = $this->_wp_page_slug;
687
-
688
-        $this->_set_transaction_object();
689
-
690
-        if (! $this->_transaction instanceof EE_Transaction) {
691
-            return;
692
-        }
693
-        $primary_registration = $this->_transaction->primary_registration();
694
-        $attendee = $primary_registration instanceof EE_Registration
695
-            ? $primary_registration->attendee()
696
-            : null;
697
-
698
-        $this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID();
699
-        $this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso');
700
-
701
-        $this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
702
-        $this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
703
-
704
-        $this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->get('STS_ID') ];
705
-        $this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
706
-        $this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->get('STS_ID');
707
-
708
-        $this->_template_args['grand_total'] = $this->_transaction->get('TXN_total');
709
-        $this->_template_args['total_paid'] = $this->_transaction->get('TXN_paid');
710
-
711
-        $amount_due = $this->_transaction->get('TXN_total') - $this->_transaction->get('TXN_paid');
712
-        $this->_template_args['amount_due'] = EEH_Template::format_currency(
713
-            $amount_due,
714
-            true
715
-        );
716
-        if (EE_Registry::instance()->CFG->currency->sign_b4) {
717
-            $this->_template_args['amount_due'] = EE_Registry::instance()->CFG->currency->sign
718
-                                                  . $this->_template_args['amount_due'];
719
-        } else {
720
-            $this->_template_args['amount_due'] .= EE_Registry::instance()->CFG->currency->sign;
721
-        }
722
-        $this->_template_args['amount_due_class'] = '';
723
-
724
-        if ($this->_transaction->get('TXN_paid') == $this->_transaction->get('TXN_total')) {
725
-            // paid in full
726
-            $this->_template_args['amount_due'] = false;
727
-        } elseif ($this->_transaction->get('TXN_paid') > $this->_transaction->get('TXN_total')) {
728
-            // overpaid
729
-            $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
730
-        } elseif ($this->_transaction->get('TXN_total') > 0
731
-                  && $this->_transaction->get('TXN_paid') > 0
732
-        ) {
733
-            // monies owing
734
-            $this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn';
735
-        } elseif ($this->_transaction->get('TXN_total') > 0
736
-                  && $this->_transaction->get('TXN_paid') == 0
737
-        ) {
738
-            // no payments made yet
739
-            $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
740
-        } elseif ($this->_transaction->get('TXN_total') == 0) {
741
-            // free event
742
-            $this->_template_args['amount_due'] = false;
743
-        }
744
-
745
-        $payment_method = $this->_transaction->payment_method();
746
-
747
-        $this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method
748
-            ? $payment_method->admin_name()
749
-            : esc_html__('Unknown', 'event_espresso');
750
-
751
-        $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
752
-        // link back to overview
753
-        $this->_template_args['txn_overview_url'] = ! empty($_SERVER['HTTP_REFERER'])
754
-            ? $_SERVER['HTTP_REFERER']
755
-            : TXN_ADMIN_URL;
756
-
757
-
758
-        // next link
759
-        $next_txn = $this->_transaction->next(
760
-            null,
761
-            array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
762
-            'TXN_ID'
763
-        );
764
-        $this->_template_args['next_transaction'] = $next_txn
765
-            ? $this->_next_link(
766
-                EE_Admin_Page::add_query_args_and_nonce(
767
-                    array('action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']),
768
-                    TXN_ADMIN_URL
769
-                ),
770
-                'dashicons dashicons-arrow-right ee-icon-size-22'
771
-            )
772
-            : '';
773
-        // previous link
774
-        $previous_txn = $this->_transaction->previous(
775
-            null,
776
-            array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
777
-            'TXN_ID'
778
-        );
779
-        $this->_template_args['previous_transaction'] = $previous_txn
780
-            ? $this->_previous_link(
781
-                EE_Admin_Page::add_query_args_and_nonce(
782
-                    array('action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']),
783
-                    TXN_ADMIN_URL
784
-                ),
785
-                'dashicons dashicons-arrow-left ee-icon-size-22'
786
-            )
787
-            : '';
788
-
789
-        // were we just redirected here after adding a new registration ???
790
-        if (isset(
791
-            $this->_req_data['redirect_from'],
792
-            $this->_req_data['EVT_ID'],
793
-            $this->_req_data['event_name']
794
-        )) {
795
-            if (EE_Registry::instance()->CAP->current_user_can(
796
-                'ee_edit_registrations',
797
-                'espresso_registrations_new_registration',
798
-                $this->_req_data['EVT_ID']
799
-            )) {
800
-                $this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button-primary" href="';
801
-                $this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce(
802
-                    array(
803
-                        'page'     => 'espresso_registrations',
804
-                        'action'   => 'new_registration',
805
-                        'return'   => 'default',
806
-                        'TXN_ID'   => $this->_transaction->ID(),
807
-                        'event_id' => $this->_req_data['EVT_ID'],
808
-                    ),
809
-                    REG_ADMIN_URL
810
-                );
811
-                $this->_admin_page_title .= '">';
812
-
813
-                $this->_admin_page_title .= sprintf(
814
-                    esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'),
815
-                    htmlentities(urldecode($this->_req_data['event_name']), ENT_QUOTES, 'UTF-8')
816
-                );
817
-                $this->_admin_page_title .= '</a>';
818
-            }
819
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
820
-        }
821
-        // grab messages at the last second
822
-        $this->_template_args['notices'] = EE_Error::get_notices();
823
-        // path to template
824
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
825
-        $this->_template_args['admin_page_header'] = EEH_Template::display_template(
826
-            $template_path,
827
-            $this->_template_args,
828
-            true
829
-        );
830
-
831
-        // the details template wrapper
832
-        $this->display_admin_page_with_sidebar();
833
-    }
834
-
835
-
836
-    /**
837
-     *        _transaction_details_metaboxes
838
-     *
839
-     * @access protected
840
-     * @return void
841
-     * @throws EE_Error
842
-     * @throws InvalidArgumentException
843
-     * @throws InvalidDataTypeException
844
-     * @throws InvalidInterfaceException
845
-     * @throws RuntimeException
846
-     * @throws ReflectionException
847
-     */
848
-    protected function _transaction_details_metaboxes()
849
-    {
850
-
851
-        $this->_set_transaction_object();
852
-
853
-        if (! $this->_transaction instanceof EE_Transaction) {
854
-            return;
855
-        }
856
-        add_meta_box(
857
-            'edit-txn-details-mbox',
858
-            esc_html__('Transaction Details', 'event_espresso'),
859
-            array($this, 'txn_details_meta_box'),
860
-            $this->_wp_page_slug,
861
-            'normal',
862
-            'high'
863
-        );
864
-        add_meta_box(
865
-            'edit-txn-attendees-mbox',
866
-            esc_html__('Attendees Registered in this Transaction', 'event_espresso'),
867
-            array($this, 'txn_attendees_meta_box'),
868
-            $this->_wp_page_slug,
869
-            'normal',
870
-            'high',
871
-            array('TXN_ID' => $this->_transaction->ID())
872
-        );
873
-        add_meta_box(
874
-            'edit-txn-registrant-mbox',
875
-            esc_html__('Primary Contact', 'event_espresso'),
876
-            array($this, 'txn_registrant_side_meta_box'),
877
-            $this->_wp_page_slug,
878
-            'side',
879
-            'high'
880
-        );
881
-        add_meta_box(
882
-            'edit-txn-billing-info-mbox',
883
-            esc_html__('Billing Information', 'event_espresso'),
884
-            array($this, 'txn_billing_info_side_meta_box'),
885
-            $this->_wp_page_slug,
886
-            'side',
887
-            'high'
888
-        );
889
-    }
890
-
891
-
892
-    /**
893
-     * Callback for transaction actions metabox.
894
-     *
895
-     * @param EE_Transaction|null $transaction
896
-     * @throws DomainException
897
-     * @throws EE_Error
898
-     * @throws InvalidArgumentException
899
-     * @throws InvalidDataTypeException
900
-     * @throws InvalidInterfaceException
901
-     * @throws ReflectionException
902
-     * @throws RuntimeException
903
-     */
904
-    public function getActionButtons(EE_Transaction $transaction = null)
905
-    {
906
-        $content = '';
907
-        $actions = array();
908
-        if (! $transaction instanceof EE_Transaction) {
909
-            return $content;
910
-        }
911
-        /** @var EE_Registration $primary_registration */
912
-        $primary_registration = $transaction->primary_registration();
913
-        $attendee = $primary_registration instanceof EE_Registration
914
-            ? $primary_registration->attendee()
915
-            : null;
916
-
917
-        if ($attendee instanceof EE_Attendee
918
-            && EE_Registry::instance()->CAP->current_user_can(
919
-                'ee_send_message',
920
-                'espresso_transactions_send_payment_reminder'
921
-            )
922
-        ) {
923
-            $actions['payment_reminder'] =
924
-                EEH_MSG_Template::is_mt_active('payment_reminder')
925
-                && $this->_transaction->get('STS_ID') !== EEM_Transaction::complete_status_code
926
-                && $this->_transaction->get('STS_ID') !== EEM_Transaction::overpaid_status_code
927
-                    ? EEH_Template::get_button_or_link(
928
-                        EE_Admin_Page::add_query_args_and_nonce(
929
-                            array(
930
-                                'action'      => 'send_payment_reminder',
931
-                                'TXN_ID'      => $this->_transaction->ID(),
932
-                                'redirect_to' => 'view_transaction',
933
-                            ),
934
-                            TXN_ADMIN_URL
935
-                        ),
936
-                        esc_html__(' Send Payment Reminder', 'event_espresso'),
937
-                        'button secondary-button',
938
-                        'dashicons dashicons-email-alt'
939
-                    )
940
-                    : '';
941
-        }
942
-
943
-        if ($primary_registration instanceof EE_Registration
944
-            && EEH_MSG_Template::is_mt_active('receipt')
945
-        ) {
946
-            $actions['receipt'] = EEH_Template::get_button_or_link(
947
-                $primary_registration->receipt_url(),
948
-                esc_html__('View Receipt', 'event_espresso'),
949
-                'button secondary-button',
950
-                'dashicons dashicons-media-default'
951
-            );
952
-        }
953
-
954
-        if ($primary_registration instanceof EE_Registration
955
-            && EEH_MSG_Template::is_mt_active('invoice')
956
-        ) {
957
-            $actions['invoice'] = EEH_Template::get_button_or_link(
958
-                $primary_registration->invoice_url(),
959
-                esc_html__('View Invoice', 'event_espresso'),
960
-                'button secondary-button',
961
-                'dashicons dashicons-media-spreadsheet'
962
-            );
963
-        }
964
-        $actions = array_filter(
965
-            apply_filters('FHEE__Transactions_Admin_Page__getActionButtons__actions', $actions, $transaction)
966
-        );
967
-        if ($actions) {
968
-            $content = '<ul>';
969
-            $content .= '<li>' . implode('</li><li>', $actions) . '</li>';
970
-            $content .= '</uL>';
971
-        }
972
-        return $content;
973
-    }
974
-
975
-
976
-    /**
977
-     * txn_details_meta_box
978
-     * generates HTML for the Transaction main meta box
979
-     *
980
-     * @return void
981
-     * @throws DomainException
982
-     * @throws EE_Error
983
-     * @throws InvalidArgumentException
984
-     * @throws InvalidDataTypeException
985
-     * @throws InvalidInterfaceException
986
-     * @throws RuntimeException
987
-     * @throws ReflectionException
988
-     */
989
-    public function txn_details_meta_box()
990
-    {
991
-        $this->_set_transaction_object();
992
-        $this->_template_args['TXN_ID'] = $this->_transaction->ID();
993
-        $this->_template_args['attendee'] = $this->_transaction->primary_registration() instanceof EE_Registration
994
-            ? $this->_transaction->primary_registration()->attendee()
995
-            : null;
996
-        $this->_template_args['can_edit_payments'] = EE_Registry::instance()->CAP->current_user_can(
997
-            'ee_edit_payments',
998
-            'apply_payment_or_refund_from_registration_details'
999
-        );
1000
-        $this->_template_args['can_delete_payments'] = EE_Registry::instance()->CAP->current_user_can(
1001
-            'ee_delete_payments',
1002
-            'delete_payment_from_registration_details'
1003
-        );
1004
-
1005
-        // get line table
1006
-        EEH_Autoloader::register_line_item_display_autoloaders();
1007
-        $Line_Item_Display = new EE_Line_Item_Display(
1008
-            'admin_table',
1009
-            'EE_Admin_Table_Line_Item_Display_Strategy'
1010
-        );
1011
-        $this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item(
1012
-            $this->_transaction->total_line_item()
1013
-        );
1014
-        $this->_template_args['REG_code'] = $this->_transaction->get_first_related('Registration')
1015
-                                                               ->get('REG_code');
1016
-
1017
-        // process taxes
1018
-        $taxes = $this->_transaction->get_many_related(
1019
-            'Line_Item',
1020
-            array(array('LIN_type' => EEM_Line_Item::type_tax))
1021
-        );
1022
-        $this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false;
1023
-
1024
-        $this->_template_args['grand_total'] = EEH_Template::format_currency(
1025
-            $this->_transaction->get('TXN_total'),
1026
-            false,
1027
-            false
1028
-        );
1029
-        $this->_template_args['grand_raw_total'] = $this->_transaction->get('TXN_total');
1030
-        $this->_template_args['TXN_status'] = $this->_transaction->get('STS_ID');
1031
-
1032
-        // process payment details
1033
-        $payments = $this->_transaction->get_many_related('Payment');
1034
-        if (! empty($payments)) {
1035
-            $this->_template_args['payments'] = $payments;
1036
-            $this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
1037
-        } else {
1038
-            $this->_template_args['payments'] = false;
1039
-            $this->_template_args['existing_reg_payments'] = array();
1040
-        }
1041
-
1042
-        $this->_template_args['edit_payment_url'] = add_query_arg(array('action' => 'edit_payment'), TXN_ADMIN_URL);
1043
-        $this->_template_args['delete_payment_url'] = add_query_arg(
1044
-            array('action' => 'espresso_delete_payment'),
1045
-            TXN_ADMIN_URL
1046
-        );
1047
-
1048
-        if (isset($txn_details['invoice_number'])) {
1049
-            $this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code'];
1050
-            $this->_template_args['txn_details']['invoice_number']['label'] = esc_html__(
1051
-                'Invoice Number',
1052
-                'event_espresso'
1053
-            );
1054
-        }
1055
-
1056
-        $this->_template_args['txn_details']['registration_session']['value'] = $this->_transaction
1057
-            ->get_first_related('Registration')
1058
-            ->get('REG_session');
1059
-        $this->_template_args['txn_details']['registration_session']['label'] = esc_html__(
1060
-            'Registration Session',
1061
-            'event_espresso'
1062
-        );
1063
-
1064
-        $this->_template_args['txn_details']['ip_address']['value'] = isset($this->_session['ip_address'])
1065
-            ? $this->_session['ip_address']
1066
-            : '';
1067
-        $this->_template_args['txn_details']['ip_address']['label'] = esc_html__(
1068
-            'Transaction placed from IP',
1069
-            'event_espresso'
1070
-        );
1071
-
1072
-        $this->_template_args['txn_details']['user_agent']['value'] = isset($this->_session['user_agent'])
1073
-            ? $this->_session['user_agent']
1074
-            : '';
1075
-        $this->_template_args['txn_details']['user_agent']['label'] = esc_html__(
1076
-            'Registrant User Agent',
1077
-            'event_espresso'
1078
-        );
1079
-
1080
-        $reg_steps = '<ul>';
1081
-        foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) {
1082
-            if ($reg_step_status === true) {
1083
-                $reg_steps .= '<li style="color:#70cc50">'
1084
-                              . sprintf(
1085
-                                  esc_html__('%1$s : Completed', 'event_espresso'),
1086
-                                  ucwords(str_replace('_', ' ', $reg_step))
1087
-                              )
1088
-                              . '</li>';
1089
-            } elseif (is_numeric($reg_step_status) && $reg_step_status !== false) {
1090
-                $reg_steps .= '<li style="color:#2EA2CC">'
1091
-                              . sprintf(
1092
-                                  esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
1093
-                                  ucwords(str_replace('_', ' ', $reg_step)),
1094
-                                  date(
1095
-                                      get_option('date_format') . ' ' . get_option('time_format'),
1096
-                                      ($reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS))
1097
-                                  )
1098
-                              )
1099
-                              . '</li>';
1100
-            } else {
1101
-                $reg_steps .= '<li style="color:#E76700">'
1102
-                              . sprintf(
1103
-                                  esc_html__('%1$s : Never Initiated', 'event_espresso'),
1104
-                                  ucwords(str_replace('_', ' ', $reg_step))
1105
-                              )
1106
-                              . '</li>';
1107
-            }
1108
-        }
1109
-        $reg_steps .= '</ul>';
1110
-        $this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps;
1111
-        $this->_template_args['txn_details']['reg_steps']['label'] = esc_html__(
1112
-            'Registration Step Progress',
1113
-            'event_espresso'
1114
-        );
1115
-
1116
-
1117
-        $this->_get_registrations_to_apply_payment_to();
1118
-        $this->_get_payment_methods($payments);
1119
-        $this->_get_payment_status_array();
1120
-        $this->_get_reg_status_selection(); // sets up the template args for the reg status array for the transaction.
1121
-
1122
-        $this->_template_args['transaction_form_url'] = add_query_arg(
1123
-            array(
1124
-                'action'  => 'edit_transaction',
1125
-                'process' => 'transaction',
1126
-            ),
1127
-            TXN_ADMIN_URL
1128
-        );
1129
-        $this->_template_args['apply_payment_form_url'] = add_query_arg(
1130
-            array(
1131
-                'page'   => 'espresso_transactions',
1132
-                'action' => 'espresso_apply_payment',
1133
-            ),
1134
-            WP_AJAX_URL
1135
-        );
1136
-        $this->_template_args['delete_payment_form_url'] = add_query_arg(
1137
-            array(
1138
-                'page'   => 'espresso_transactions',
1139
-                'action' => 'espresso_delete_payment',
1140
-            ),
1141
-            WP_AJAX_URL
1142
-        );
1143
-
1144
-        $this->_template_args['action_buttons'] = $this->getActionButtons($this->_transaction);
1145
-
1146
-        // 'espresso_delete_payment_nonce'
1147
-
1148
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
1149
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
1150
-    }
1151
-
1152
-
1153
-    /**
1154
-     * _get_registration_payment_IDs
1155
-     *    generates an array of Payment IDs and their corresponding Registration IDs
1156
-     *
1157
-     * @access protected
1158
-     * @param EE_Payment[] $payments
1159
-     * @return array
1160
-     * @throws EE_Error
1161
-     * @throws InvalidArgumentException
1162
-     * @throws InvalidDataTypeException
1163
-     * @throws InvalidInterfaceException
1164
-     * @throws ReflectionException
1165
-     */
1166
-    protected function _get_registration_payment_IDs($payments = array())
1167
-    {
1168
-        $existing_reg_payments = array();
1169
-        // get all reg payments for these payments
1170
-        $reg_payments = EEM_Registration_Payment::instance()->get_all(
1171
-            array(
1172
-                array(
1173
-                    'PAY_ID' => array(
1174
-                        'IN',
1175
-                        array_keys($payments),
1176
-                    ),
1177
-                ),
1178
-            )
1179
-        );
1180
-        if (! empty($reg_payments)) {
1181
-            foreach ($payments as $payment) {
1182
-                if (! $payment instanceof EE_Payment) {
1183
-                    continue;
1184
-                } elseif (! isset($existing_reg_payments[ $payment->ID() ])) {
1185
-                    $existing_reg_payments[ $payment->ID() ] = array();
1186
-                }
1187
-                foreach ($reg_payments as $reg_payment) {
1188
-                    if ($reg_payment instanceof EE_Registration_Payment
1189
-                        && $reg_payment->payment_ID() === $payment->ID()
1190
-                    ) {
1191
-                        $existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID();
1192
-                    }
1193
-                }
1194
-            }
1195
-        }
1196
-
1197
-        return $existing_reg_payments;
1198
-    }
1199
-
1200
-
1201
-    /**
1202
-     * _get_registrations_to_apply_payment_to
1203
-     *    generates HTML for displaying a series of checkboxes in the admin payment modal window
1204
-     * which allows the admin to only apply the payment to the specific registrations
1205
-     *
1206
-     * @access protected
1207
-     * @return void
1208
-     * @throws \EE_Error
1209
-     */
1210
-    protected function _get_registrations_to_apply_payment_to()
1211
-    {
1212
-        // we want any registration with an active status (ie: not deleted or cancelled)
1213
-        $query_params = array(
1214
-            array(
1215
-                'STS_ID' => array(
1216
-                    'IN',
1217
-                    array(
1218
-                        EEM_Registration::status_id_approved,
1219
-                        EEM_Registration::status_id_pending_payment,
1220
-                        EEM_Registration::status_id_not_approved,
1221
-                    ),
1222
-                ),
1223
-            ),
1224
-        );
1225
-        $registrations_to_apply_payment_to = EEH_HTML::br()
1226
-                                             . EEH_HTML::div(
1227
-                                                 '',
1228
-                                                 'txn-admin-apply-payment-to-registrations-dv',
1229
-                                                 '',
1230
-                                                 'clear: both; margin: 1.5em 0 0; display: none;'
1231
-                                             );
1232
-        $registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1233
-        $registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl');
1234
-        $registrations_to_apply_payment_to .= EEH_HTML::thead(
1235
-            EEH_HTML::tr(
1236
-                EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
1237
-                EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
1238
-                EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
1239
-                EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
1240
-                EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
1241
-                EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
1242
-                EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
1243
-            )
1244
-        );
1245
-        $registrations_to_apply_payment_to .= EEH_HTML::tbody();
1246
-        // get registrations for TXN
1247
-        $registrations = $this->_transaction->registrations($query_params);
1248
-        $existing_reg_payments = $this->_template_args['existing_reg_payments'];
1249
-        foreach ($registrations as $registration) {
1250
-            if ($registration instanceof EE_Registration) {
1251
-                $attendee_name = $registration->attendee() instanceof EE_Attendee
1252
-                    ? $registration->attendee()->full_name()
1253
-                    : esc_html__('Unknown Attendee', 'event_espresso');
1254
-                $owing = $registration->final_price() - $registration->paid();
1255
-                $taxable = $registration->ticket()->taxable()
1256
-                    ? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
1257
-                    : '';
1258
-                $checked = empty($existing_reg_payments) || in_array($registration->ID(), $existing_reg_payments)
1259
-                    ? ' checked="checked"'
1260
-                    : '';
1261
-                $disabled = $registration->final_price() > 0 ? '' : ' disabled';
1262
-                $registrations_to_apply_payment_to .= EEH_HTML::tr(
1263
-                    EEH_HTML::td($registration->ID()) .
1264
-                    EEH_HTML::td($attendee_name) .
1265
-                    EEH_HTML::td(
1266
-                        $registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
1267
-                    ) .
1268
-                    EEH_HTML::td($registration->event_name()) .
1269
-                    EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
1270
-                    EEH_HTML::td(EEH_Template::format_currency($owing), '', 'txn-admin-payment-owing-td jst-cntr') .
1271
-                    EEH_HTML::td(
1272
-                        '<input type="checkbox" value="' . $registration->ID()
1273
-                        . '" name="txn_admin_payment[registrations]"'
1274
-                        . $checked . $disabled . '>',
1275
-                        '',
1276
-                        'jst-cntr'
1277
-                    ),
1278
-                    'apply-payment-registration-row-' . $registration->ID()
1279
-                );
1280
-            }
1281
-        }
1282
-        $registrations_to_apply_payment_to .= EEH_HTML::tbodyx();
1283
-        $registrations_to_apply_payment_to .= EEH_HTML::tablex();
1284
-        $registrations_to_apply_payment_to .= EEH_HTML::divx();
1285
-        $registrations_to_apply_payment_to .= EEH_HTML::p(
1286
-            esc_html__(
1287
-                'The payment will only be applied to the registrations that have a check mark in their corresponding check box. Checkboxes for free registrations have been disabled.',
1288
-                'event_espresso'
1289
-            ),
1290
-            '',
1291
-            'clear description'
1292
-        );
1293
-        $registrations_to_apply_payment_to .= EEH_HTML::divx();
1294
-        $this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to;
1295
-    }
1296
-
1297
-
1298
-    /**
1299
-     * _get_reg_status_selection
1300
-     *
1301
-     * @todo   this will need to be adjusted either once MER comes along OR we move default reg status to tickets
1302
-     *         instead of events.
1303
-     * @access protected
1304
-     * @return void
1305
-     * @throws EE_Error
1306
-     */
1307
-    protected function _get_reg_status_selection()
1308
-    {
1309
-        // first get all possible statuses
1310
-        $statuses = EEM_Registration::reg_status_array(array(), true);
1311
-        // let's add a "don't change" option.
1312
-        $status_array['NAN'] = esc_html__('Leave the Same', 'event_espresso');
1313
-        $status_array = array_merge($status_array, $statuses);
1314
-        $this->_template_args['status_change_select'] = EEH_Form_Fields::select_input(
1315
-            'txn_reg_status_change[reg_status]',
1316
-            $status_array,
1317
-            'NAN',
1318
-            'id="txn-admin-payment-reg-status-inp"',
1319
-            'txn-reg-status-change-reg-status'
1320
-        );
1321
-        $this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input(
1322
-            'delete_txn_reg_status_change[reg_status]',
1323
-            $status_array,
1324
-            'NAN',
1325
-            'delete-txn-admin-payment-reg-status-inp',
1326
-            'delete-txn-reg-status-change-reg-status'
1327
-        );
1328
-    }
1329
-
1330
-
1331
-    /**
1332
-     *    _get_payment_methods
1333
-     * Gets all the payment methods available generally, or the ones that are already
1334
-     * selected on these payments (in case their payment methods are no longer active).
1335
-     * Has the side-effect of updating the template args' payment_methods item
1336
-     *
1337
-     * @access private
1338
-     * @param EE_Payment[] to show on this page
1339
-     * @return void
1340
-     * @throws EE_Error
1341
-     * @throws InvalidArgumentException
1342
-     * @throws InvalidDataTypeException
1343
-     * @throws InvalidInterfaceException
1344
-     * @throws ReflectionException
1345
-     */
1346
-    private function _get_payment_methods($payments = array())
1347
-    {
1348
-        $payment_methods_of_payments = array();
1349
-        foreach ($payments as $payment) {
1350
-            if ($payment instanceof EE_Payment) {
1351
-                $payment_methods_of_payments[] = $payment->get('PMD_ID');
1352
-            }
1353
-        }
1354
-        if ($payment_methods_of_payments) {
1355
-            $query_args = array(
1356
-                array(
1357
-                    'OR*payment_method_for_payment' => array(
1358
-                        'PMD_ID'    => array('IN', $payment_methods_of_payments),
1359
-                        'PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'),
1360
-                    ),
1361
-                ),
1362
-            );
1363
-        } else {
1364
-            $query_args = array(array('PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%')));
1365
-        }
1366
-        $this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1367
-    }
1368
-
1369
-
1370
-    /**
1371
-     * txn_attendees_meta_box
1372
-     *    generates HTML for the Attendees Transaction main meta box
1373
-     *
1374
-     * @access public
1375
-     * @param WP_Post $post
1376
-     * @param array   $metabox
1377
-     * @return void
1378
-     * @throws DomainException
1379
-     * @throws EE_Error
1380
-     */
1381
-    public function txn_attendees_meta_box($post, $metabox = array('args' => array()))
1382
-    {
1383
-
1384
-        /** @noinspection NonSecureExtractUsageInspection */
1385
-        extract($metabox['args']);
1386
-        $this->_template_args['post'] = $post;
1387
-        $this->_template_args['event_attendees'] = array();
1388
-        // process items in cart
1389
-        $line_items = $this->_transaction->get_many_related(
1390
-            'Line_Item',
1391
-            array(array('LIN_type' => 'line-item'))
1392
-        );
1393
-        if (! empty($line_items)) {
1394
-            foreach ($line_items as $item) {
1395
-                if ($item instanceof EE_Line_Item) {
1396
-                    switch ($item->OBJ_type()) {
1397
-                        case 'Event':
1398
-                            break;
1399
-                        case 'Ticket':
1400
-                            $ticket = $item->ticket();
1401
-                            // right now we're only handling tickets here.
1402
-                            // Cause its expected that only tickets will have attendees right?
1403
-                            if (! $ticket instanceof EE_Ticket) {
1404
-                                continue;
1405
-                            }
1406
-                            try {
1407
-                                $event_name = $ticket->get_event_name();
1408
-                            } catch (Exception $e) {
1409
-                                EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1410
-                                $event_name = esc_html__('Unknown Event', 'event_espresso');
1411
-                            }
1412
-                            $event_name .= ' - ' . $item->get('LIN_name');
1413
-                            $ticket_price = EEH_Template::format_currency($item->get('LIN_unit_price'));
1414
-                            // now get all of the registrations for this transaction that use this ticket
1415
-                            $registrations = $ticket->get_many_related(
1416
-                                'Registration',
1417
-                                array(array('TXN_ID' => $this->_transaction->ID()))
1418
-                            );
1419
-                            foreach ($registrations as $registration) {
1420
-                                if (! $registration instanceof EE_Registration) {
1421
-                                    continue;
1422
-                                }
1423
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID']
1424
-                                    = $registration->status_ID();
1425
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['att_num']
1426
-                                    = $registration->count();
1427
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name']
1428
-                                    = $event_name;
1429
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price']
1430
-                                    = $ticket_price;
1431
-                                // attendee info
1432
-                                $attendee = $registration->get_first_related('Attendee');
1433
-                                if ($attendee instanceof EE_Attendee) {
1434
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id']
1435
-                                        = $attendee->ID();
1436
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee']
1437
-                                        = $attendee->full_name();
1438
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email']
1439
-                                        = '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name
1440
-                                          . esc_html__(
1441
-                                              ' Event',
1442
-                                              'event_espresso'
1443
-                                          )
1444
-                                          . '">' . $attendee->email() . '</a>';
1445
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address']
1446
-                                        = EEH_Address::format($attendee, 'inline', false, false);
1447
-                                } else {
1448
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id'] = '';
1449
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = '';
1450
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email'] = '';
1451
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address'] = '';
1452
-                                }
1453
-                            }
1454
-                            break;
1455
-                    }
1456
-                }
1457
-            }
1458
-
1459
-            $this->_template_args['transaction_form_url'] = add_query_arg(
1460
-                array(
1461
-                    'action'  => 'edit_transaction',
1462
-                    'process' => 'attendees',
1463
-                ),
1464
-                TXN_ADMIN_URL
1465
-            );
1466
-            echo EEH_Template::display_template(
1467
-                TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1468
-                $this->_template_args,
1469
-                true
1470
-            );
1471
-        } else {
1472
-            echo sprintf(
1473
-                esc_html__(
1474
-                    '%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s',
1475
-                    'event_espresso'
1476
-                ),
1477
-                '<p class="important-notice">',
1478
-                '</p>'
1479
-            );
1480
-        }
1481
-    }
1482
-
1483
-
1484
-    /**
1485
-     * txn_registrant_side_meta_box
1486
-     * generates HTML for the Edit Transaction side meta box
1487
-     *
1488
-     * @access public
1489
-     * @return void
1490
-     * @throws DomainException
1491
-     * @throws EE_Error
1492
-     * @throws InvalidArgumentException
1493
-     * @throws InvalidDataTypeException
1494
-     * @throws InvalidInterfaceException
1495
-     * @throws ReflectionException
1496
-     */
1497
-    public function txn_registrant_side_meta_box()
1498
-    {
1499
-        $primary_att = $this->_transaction->primary_registration() instanceof EE_Registration
1500
-            ? $this->_transaction->primary_registration()->get_first_related('Attendee')
1501
-            : null;
1502
-        if (! $primary_att instanceof EE_Attendee) {
1503
-            $this->_template_args['no_attendee_message'] = esc_html__(
1504
-                'There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1505
-                'event_espresso'
1506
-            );
1507
-            $primary_att = EEM_Attendee::instance()->create_default_object();
1508
-        }
1509
-        $this->_template_args['ATT_ID'] = $primary_att->ID();
1510
-        $this->_template_args['prime_reg_fname'] = $primary_att->fname();
1511
-        $this->_template_args['prime_reg_lname'] = $primary_att->lname();
1512
-        $this->_template_args['prime_reg_email'] = $primary_att->email();
1513
-        $this->_template_args['prime_reg_phone'] = $primary_att->phone();
1514
-        $this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce(
1515
-            array(
1516
-                'action' => 'edit_attendee',
1517
-                'post'   => $primary_att->ID(),
1518
-            ),
1519
-            REG_ADMIN_URL
1520
-        );
1521
-        // get formatted address for registrant
1522
-        $this->_template_args['formatted_address'] = EEH_Address::format($primary_att);
1523
-        echo EEH_Template::display_template(
1524
-            TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1525
-            $this->_template_args,
1526
-            true
1527
-        );
1528
-    }
1529
-
1530
-
1531
-    /**
1532
-     * txn_billing_info_side_meta_box
1533
-     *    generates HTML for the Edit Transaction side meta box
1534
-     *
1535
-     * @access public
1536
-     * @return void
1537
-     * @throws DomainException
1538
-     * @throws EE_Error
1539
-     */
1540
-    public function txn_billing_info_side_meta_box()
1541
-    {
1542
-
1543
-        $this->_template_args['billing_form'] = $this->_transaction->billing_info();
1544
-        $this->_template_args['billing_form_url'] = add_query_arg(
1545
-            array('action' => 'edit_transaction', 'process' => 'billing'),
1546
-            TXN_ADMIN_URL
1547
-        );
1548
-
1549
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1550
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);/**/
1551
-    }
1552
-
1553
-
1554
-    /**
1555
-     * apply_payments_or_refunds
1556
-     *    registers a payment or refund made towards a transaction
1557
-     *
1558
-     * @access public
1559
-     * @return void
1560
-     * @throws EE_Error
1561
-     * @throws InvalidArgumentException
1562
-     * @throws ReflectionException
1563
-     * @throws RuntimeException
1564
-     * @throws InvalidDataTypeException
1565
-     * @throws InvalidInterfaceException
1566
-     */
1567
-    public function apply_payments_or_refunds()
1568
-    {
1569
-        $json_response_data = array('return_data' => false);
1570
-        $valid_data = $this->_validate_payment_request_data();
1571
-        $has_access = EE_Registry::instance()->CAP->current_user_can(
1572
-            'ee_edit_payments',
1573
-            'apply_payment_or_refund_from_registration_details'
1574
-        );
1575
-        if (! empty($valid_data) && $has_access) {
1576
-            $PAY_ID = $valid_data['PAY_ID'];
1577
-            // save  the new payment
1578
-            $payment = $this->_create_payment_from_request_data($valid_data);
1579
-            // get the TXN for this payment
1580
-            $transaction = $payment->transaction();
1581
-            // verify transaction
1582
-            if ($transaction instanceof EE_Transaction) {
1583
-                // calculate_total_payments_and_update_status
1584
-                $this->_process_transaction_payments($transaction);
1585
-                $REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1586
-                $this->_remove_existing_registration_payments($payment, $PAY_ID);
1587
-                // apply payment to registrations (if applicable)
1588
-                if (! empty($REG_IDs)) {
1589
-                    $this->_update_registration_payments($transaction, $payment, $REG_IDs);
1590
-                    $this->_maybe_send_notifications();
1591
-                    // now process status changes for the same registrations
1592
-                    $this->_process_registration_status_change($transaction, $REG_IDs);
1593
-                }
1594
-                $this->_maybe_send_notifications($payment);
1595
-                // prepare to render page
1596
-                $json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs);
1597
-                do_action(
1598
-                    'AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording',
1599
-                    $transaction,
1600
-                    $payment
1601
-                );
1602
-            } else {
1603
-                EE_Error::add_error(
1604
-                    esc_html__(
1605
-                        'A valid Transaction for this payment could not be retrieved.',
1606
-                        'event_espresso'
1607
-                    ),
1608
-                    __FILE__,
1609
-                    __FUNCTION__,
1610
-                    __LINE__
1611
-                );
1612
-            }
1613
-        } else {
1614
-            if ($has_access) {
1615
-                EE_Error::add_error(
1616
-                    esc_html__(
1617
-                        'The payment form data could not be processed. Please try again.',
1618
-                        'event_espresso'
1619
-                    ),
1620
-                    __FILE__,
1621
-                    __FUNCTION__,
1622
-                    __LINE__
1623
-                );
1624
-            } else {
1625
-                EE_Error::add_error(
1626
-                    esc_html__(
1627
-                        'You do not have access to apply payments or refunds to a registration.',
1628
-                        'event_espresso'
1629
-                    ),
1630
-                    __FILE__,
1631
-                    __FUNCTION__,
1632
-                    __LINE__
1633
-                );
1634
-            }
1635
-        }
1636
-        $notices = EE_Error::get_notices(
1637
-            false,
1638
-            false,
1639
-            false
1640
-        );
1641
-        $this->_template_args = array(
1642
-            'data'    => $json_response_data,
1643
-            'error'   => $notices['errors'],
1644
-            'success' => $notices['success'],
1645
-        );
1646
-        $this->_return_json();
1647
-    }
1648
-
1649
-
1650
-    /**
1651
-     * _validate_payment_request_data
1652
-     *
1653
-     * @return array
1654
-     * @throws EE_Error
1655
-     */
1656
-    protected function _validate_payment_request_data()
1657
-    {
1658
-        if (! isset($this->_req_data['txn_admin_payment'])) {
1659
-            return false;
1660
-        }
1661
-        $payment_form = $this->_generate_payment_form_section();
1662
-        try {
1663
-            if ($payment_form->was_submitted()) {
1664
-                $payment_form->receive_form_submission();
1665
-                if (! $payment_form->is_valid()) {
1666
-                    $submission_error_messages = array();
1667
-                    foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1668
-                        if ($validation_error instanceof EE_Validation_Error) {
1669
-                            $submission_error_messages[] = sprintf(
1670
-                                _x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'),
1671
-                                $validation_error->get_form_section()->html_label_text(),
1672
-                                $validation_error->getMessage()
1673
-                            );
1674
-                        }
1675
-                    }
1676
-                    EE_Error::add_error(
1677
-                        implode('<br />', $submission_error_messages),
1678
-                        __FILE__,
1679
-                        __FUNCTION__,
1680
-                        __LINE__
1681
-                    );
1682
-
1683
-                    return array();
1684
-                }
1685
-            }
1686
-        } catch (EE_Error $e) {
1687
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1688
-
1689
-            return array();
1690
-        }
1691
-
1692
-        return $payment_form->valid_data();
1693
-    }
1694
-
1695
-
1696
-    /**
1697
-     * _generate_payment_form_section
1698
-     *
1699
-     * @return EE_Form_Section_Proper
1700
-     * @throws EE_Error
1701
-     */
1702
-    protected function _generate_payment_form_section()
1703
-    {
1704
-        return new EE_Form_Section_Proper(
1705
-            array(
1706
-                'name'        => 'txn_admin_payment',
1707
-                'subsections' => array(
1708
-                    'PAY_ID'          => new EE_Text_Input(
1709
-                        array(
1710
-                            'default'               => 0,
1711
-                            'required'              => false,
1712
-                            'html_label_text'       => esc_html__('Payment ID', 'event_espresso'),
1713
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1714
-                        )
1715
-                    ),
1716
-                    'TXN_ID'          => new EE_Text_Input(
1717
-                        array(
1718
-                            'default'               => 0,
1719
-                            'required'              => true,
1720
-                            'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'),
1721
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1722
-                        )
1723
-                    ),
1724
-                    'type'            => new EE_Text_Input(
1725
-                        array(
1726
-                            'default'               => 1,
1727
-                            'required'              => true,
1728
-                            'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'),
1729
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1730
-                        )
1731
-                    ),
1732
-                    'amount'          => new EE_Text_Input(
1733
-                        array(
1734
-                            'default'               => 0,
1735
-                            'required'              => true,
1736
-                            'html_label_text'       => esc_html__('Payment amount', 'event_espresso'),
1737
-                            'validation_strategies' => array(new EE_Float_Normalization()),
1738
-                        )
1739
-                    ),
1740
-                    'status'          => new EE_Text_Input(
1741
-                        array(
1742
-                            'default'         => EEM_Payment::status_id_approved,
1743
-                            'required'        => true,
1744
-                            'html_label_text' => esc_html__('Payment status', 'event_espresso'),
1745
-                        )
1746
-                    ),
1747
-                    'PMD_ID'          => new EE_Text_Input(
1748
-                        array(
1749
-                            'default'               => 2,
1750
-                            'required'              => true,
1751
-                            'html_label_text'       => esc_html__('Payment Method', 'event_espresso'),
1752
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1753
-                        )
1754
-                    ),
1755
-                    'date'            => new EE_Text_Input(
1756
-                        array(
1757
-                            'default'         => time(),
1758
-                            'required'        => true,
1759
-                            'html_label_text' => esc_html__('Payment date', 'event_espresso'),
1760
-                        )
1761
-                    ),
1762
-                    'txn_id_chq_nmbr' => new EE_Text_Input(
1763
-                        array(
1764
-                            'default'               => '',
1765
-                            'required'              => false,
1766
-                            'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'),
1767
-                            'validation_strategies' => array(
1768
-                                new EE_Max_Length_Validation_Strategy(
1769
-                                    esc_html__('Input too long', 'event_espresso'),
1770
-                                    100
1771
-                                ),
1772
-                            ),
1773
-                        )
1774
-                    ),
1775
-                    'po_number'       => new EE_Text_Input(
1776
-                        array(
1777
-                            'default'               => '',
1778
-                            'required'              => false,
1779
-                            'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'),
1780
-                            'validation_strategies' => array(
1781
-                                new EE_Max_Length_Validation_Strategy(
1782
-                                    esc_html__('Input too long', 'event_espresso'),
1783
-                                    100
1784
-                                ),
1785
-                            ),
1786
-                        )
1787
-                    ),
1788
-                    'accounting'      => new EE_Text_Input(
1789
-                        array(
1790
-                            'default'               => '',
1791
-                            'required'              => false,
1792
-                            'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'),
1793
-                            'validation_strategies' => array(
1794
-                                new EE_Max_Length_Validation_Strategy(
1795
-                                    esc_html__('Input too long', 'event_espresso'),
1796
-                                    100
1797
-                                ),
1798
-                            ),
1799
-                        )
1800
-                    ),
1801
-                ),
1802
-            )
1803
-        );
1804
-    }
1805
-
1806
-
1807
-    /**
1808
-     * _create_payment_from_request_data
1809
-     *
1810
-     * @param array $valid_data
1811
-     * @return EE_Payment
1812
-     * @throws EE_Error
1813
-     */
1814
-    protected function _create_payment_from_request_data($valid_data)
1815
-    {
1816
-        $PAY_ID = $valid_data['PAY_ID'];
1817
-        // get payment amount
1818
-        $amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0;
1819
-        // payments have a type value of 1 and refunds have a type value of -1
1820
-        // so multiplying amount by type will give a positive value for payments, and negative values for refunds
1821
-        $amount = $valid_data['type'] < 0 ? $amount * -1 : $amount;
1822
-        // for some reason the date string coming in has extra spaces between the date and time.  This fixes that.
1823
-        $date = $valid_data['date']
1824
-            ? preg_replace('/\s+/', ' ', $valid_data['date'])
1825
-            : date('Y-m-d g:i a', current_time('timestamp'));
1826
-        $payment = EE_Payment::new_instance(
1827
-            array(
1828
-                'TXN_ID'              => $valid_data['TXN_ID'],
1829
-                'STS_ID'              => $valid_data['status'],
1830
-                'PAY_timestamp'       => $date,
1831
-                'PAY_source'          => EEM_Payment_Method::scope_admin,
1832
-                'PMD_ID'              => $valid_data['PMD_ID'],
1833
-                'PAY_amount'          => $amount,
1834
-                'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'],
1835
-                'PAY_po_number'       => $valid_data['po_number'],
1836
-                'PAY_extra_accntng'   => $valid_data['accounting'],
1837
-                'PAY_details'         => $valid_data,
1838
-                'PAY_ID'              => $PAY_ID,
1839
-            ),
1840
-            '',
1841
-            array('Y-m-d', 'g:i a')
1842
-        );
1843
-
1844
-        if (! $payment->save()) {
1845
-            EE_Error::add_error(
1846
-                sprintf(
1847
-                    esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
1848
-                    $payment->ID()
1849
-                ),
1850
-                __FILE__,
1851
-                __FUNCTION__,
1852
-                __LINE__
1853
-            );
1854
-        }
1855
-
1856
-        return $payment;
1857
-    }
1858
-
1859
-
1860
-    /**
1861
-     * _process_transaction_payments
1862
-     *
1863
-     * @param \EE_Transaction $transaction
1864
-     * @return void
1865
-     * @throws EE_Error
1866
-     * @throws InvalidArgumentException
1867
-     * @throws ReflectionException
1868
-     * @throws InvalidDataTypeException
1869
-     * @throws InvalidInterfaceException
1870
-     */
1871
-    protected function _process_transaction_payments(EE_Transaction $transaction)
1872
-    {
1873
-        /** @type EE_Transaction_Payments $transaction_payments */
1874
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1875
-        // update the transaction with this payment
1876
-        if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) {
1877
-            EE_Error::add_success(
1878
-                esc_html__(
1879
-                    'The payment has been processed successfully.',
1880
-                    'event_espresso'
1881
-                ),
1882
-                __FILE__,
1883
-                __FUNCTION__,
1884
-                __LINE__
1885
-            );
1886
-        } else {
1887
-            EE_Error::add_error(
1888
-                esc_html__(
1889
-                    'The payment was processed successfully but the amount paid for the transaction was not updated.',
1890
-                    'event_espresso'
1891
-                ),
1892
-                __FILE__,
1893
-                __FUNCTION__,
1894
-                __LINE__
1895
-            );
1896
-        }
1897
-    }
1898
-
1899
-
1900
-    /**
1901
-     * _get_REG_IDs_to_apply_payment_to
1902
-     * returns a list of registration IDs that the payment will apply to
1903
-     *
1904
-     * @param \EE_Payment $payment
1905
-     * @return array
1906
-     * @throws EE_Error
1907
-     */
1908
-    protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment)
1909
-    {
1910
-        $REG_IDs = array();
1911
-        // grab array of IDs for specific registrations to apply changes to
1912
-        if (isset($this->_req_data['txn_admin_payment']['registrations'])) {
1913
-            $REG_IDs = (array) $this->_req_data['txn_admin_payment']['registrations'];
1914
-        }
1915
-        // nothing specified ? then get all reg IDs
1916
-        if (empty($REG_IDs)) {
1917
-            $registrations = $payment->transaction()->registrations();
1918
-            $REG_IDs = ! empty($registrations)
1919
-                ? array_keys($registrations)
1920
-                : $this->_get_existing_reg_payment_REG_IDs($payment);
1921
-        }
1922
-
1923
-        // ensure that REG_IDs are integers and NOT strings
1924
-        return array_map('intval', $REG_IDs);
1925
-    }
1926
-
1927
-
1928
-    /**
1929
-     * @return array
1930
-     */
1931
-    public function existing_reg_payment_REG_IDs()
1932
-    {
1933
-        return $this->_existing_reg_payment_REG_IDs;
1934
-    }
1935
-
1936
-
1937
-    /**
1938
-     * @param array $existing_reg_payment_REG_IDs
1939
-     */
1940
-    public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null)
1941
-    {
1942
-        $this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs;
1943
-    }
1944
-
1945
-
1946
-    /**
1947
-     * _get_existing_reg_payment_REG_IDs
1948
-     * returns a list of registration IDs that the payment is currently related to
1949
-     * as recorded in the database
1950
-     *
1951
-     * @param \EE_Payment $payment
1952
-     * @return array
1953
-     * @throws EE_Error
1954
-     */
1955
-    protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment)
1956
-    {
1957
-        if ($this->existing_reg_payment_REG_IDs() === null) {
1958
-            // let's get any existing reg payment records for this payment
1959
-            $existing_reg_payment_REG_IDs = $payment->get_many_related('Registration');
1960
-            // but we only want the REG IDs, so grab the array keys
1961
-            $existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs)
1962
-                ? array_keys($existing_reg_payment_REG_IDs)
1963
-                : array();
1964
-            $this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs);
1965
-        }
1966
-
1967
-        return $this->existing_reg_payment_REG_IDs();
1968
-    }
1969
-
1970
-
1971
-    /**
1972
-     * _remove_existing_registration_payments
1973
-     * this calculates the difference between existing relations
1974
-     * to the supplied payment and the new list registration IDs,
1975
-     * removes any related registrations that no longer apply,
1976
-     * and then updates the registration paid fields
1977
-     *
1978
-     * @param \EE_Payment $payment
1979
-     * @param int         $PAY_ID
1980
-     * @return bool;
1981
-     * @throws EE_Error
1982
-     * @throws InvalidArgumentException
1983
-     * @throws ReflectionException
1984
-     * @throws InvalidDataTypeException
1985
-     * @throws InvalidInterfaceException
1986
-     */
1987
-    protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0)
1988
-    {
1989
-        // newly created payments will have nothing recorded for $PAY_ID
1990
-        if ($PAY_ID == 0) {
1991
-            return false;
1992
-        }
1993
-        $existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
1994
-        if (empty($existing_reg_payment_REG_IDs)) {
1995
-            return false;
1996
-        }
1997
-        /** @type EE_Transaction_Payments $transaction_payments */
1998
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1999
-
2000
-        return $transaction_payments->delete_registration_payments_and_update_registrations(
2001
-            $payment,
2002
-            array(
2003
-                array(
2004
-                    'PAY_ID' => $payment->ID(),
2005
-                    'REG_ID' => array('IN', $existing_reg_payment_REG_IDs),
2006
-                ),
2007
-            )
2008
-        );
2009
-    }
2010
-
2011
-
2012
-    /**
2013
-     * _update_registration_payments
2014
-     * this applies the payments to the selected registrations
2015
-     * but only if they have not already been paid for
2016
-     *
2017
-     * @param  EE_Transaction $transaction
2018
-     * @param \EE_Payment     $payment
2019
-     * @param array           $REG_IDs
2020
-     * @return void
2021
-     * @throws EE_Error
2022
-     * @throws InvalidArgumentException
2023
-     * @throws ReflectionException
2024
-     * @throws RuntimeException
2025
-     * @throws InvalidDataTypeException
2026
-     * @throws InvalidInterfaceException
2027
-     */
2028
-    protected function _update_registration_payments(
2029
-        EE_Transaction $transaction,
2030
-        EE_Payment $payment,
2031
-        $REG_IDs = array()
2032
-    ) {
2033
-        // we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments()
2034
-        // so let's do that using our set of REG_IDs from the form
2035
-        $registration_query_where_params = array(
2036
-            'REG_ID' => array('IN', $REG_IDs),
2037
-        );
2038
-        // but add in some conditions regarding payment,
2039
-        // so that we don't apply payments to registrations that are free or have already been paid for
2040
-        // but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
2041
-        if (! $payment->is_a_refund()) {
2042
-            $registration_query_where_params['REG_final_price'] = array('!=', 0);
2043
-            $registration_query_where_params['REG_final_price*'] = array('!=', 'REG_paid', true);
2044
-        }
2045
-        $registrations = $transaction->registrations(array($registration_query_where_params));
2046
-        if (! empty($registrations)) {
2047
-            /** @type EE_Payment_Processor $payment_processor */
2048
-            $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2049
-            $payment_processor->process_registration_payments($transaction, $payment, $registrations);
2050
-        }
2051
-    }
2052
-
2053
-
2054
-    /**
2055
-     * _process_registration_status_change
2056
-     * This processes requested registration status changes for all the registrations
2057
-     * on a given transaction and (optionally) sends out notifications for the changes.
2058
-     *
2059
-     * @param  EE_Transaction $transaction
2060
-     * @param array           $REG_IDs
2061
-     * @return bool
2062
-     * @throws EE_Error
2063
-     * @throws InvalidArgumentException
2064
-     * @throws ReflectionException
2065
-     * @throws InvalidDataTypeException
2066
-     * @throws InvalidInterfaceException
2067
-     */
2068
-    protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = array())
2069
-    {
2070
-        // first if there is no change in status then we get out.
2071
-        if (! isset($this->_req_data['txn_reg_status_change']['reg_status'])
2072
-            || $this->_req_data['txn_reg_status_change']['reg_status'] === 'NAN'
2073
-        ) {
2074
-            // no error message, no change requested, just nothing to do man.
2075
-            return false;
2076
-        }
2077
-        /** @type EE_Transaction_Processor $transaction_processor */
2078
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
2079
-
2080
-        // made it here dude?  Oh WOW.  K, let's take care of changing the statuses
2081
-        return $transaction_processor->manually_update_registration_statuses(
2082
-            $transaction,
2083
-            sanitize_text_field($this->_req_data['txn_reg_status_change']['reg_status']),
2084
-            array(array('REG_ID' => array('IN', $REG_IDs)))
2085
-        );
2086
-    }
2087
-
2088
-
2089
-    /**
2090
-     * _build_payment_json_response
2091
-     *
2092
-     * @access public
2093
-     * @param \EE_Payment $payment
2094
-     * @param array       $REG_IDs
2095
-     * @param bool | null $delete_txn_reg_status_change
2096
-     * @return array
2097
-     * @throws EE_Error
2098
-     * @throws InvalidArgumentException
2099
-     * @throws InvalidDataTypeException
2100
-     * @throws InvalidInterfaceException
2101
-     * @throws ReflectionException
2102
-     */
2103
-    protected function _build_payment_json_response(
2104
-        EE_Payment $payment,
2105
-        $REG_IDs = array(),
2106
-        $delete_txn_reg_status_change = null
2107
-    ) {
2108
-        // was the payment deleted ?
2109
-        if (is_bool($delete_txn_reg_status_change)) {
2110
-            return array(
2111
-                'PAY_ID'                       => $payment->ID(),
2112
-                'amount'                       => $payment->amount(),
2113
-                'total_paid'                   => $payment->transaction()->paid(),
2114
-                'txn_status'                   => $payment->transaction()->status_ID(),
2115
-                'pay_status'                   => $payment->STS_ID(),
2116
-                'registrations'                => $this->_registration_payment_data_array($REG_IDs),
2117
-                'delete_txn_reg_status_change' => $delete_txn_reg_status_change,
2118
-            );
2119
-        } else {
2120
-            $this->_get_payment_status_array();
2121
-
2122
-            return array(
2123
-                'amount'           => $payment->amount(),
2124
-                'total_paid'       => $payment->transaction()->paid(),
2125
-                'txn_status'       => $payment->transaction()->status_ID(),
2126
-                'pay_status'       => $payment->STS_ID(),
2127
-                'PAY_ID'           => $payment->ID(),
2128
-                'STS_ID'           => $payment->STS_ID(),
2129
-                'status'           => self::$_pay_status[ $payment->STS_ID() ],
2130
-                'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
2131
-                'method'           => strtoupper($payment->source()),
2132
-                'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
2133
-                'gateway'          => $payment->payment_method()
2134
-                    ? $payment->payment_method()->admin_name()
2135
-                    : esc_html__("Unknown", 'event_espresso'),
2136
-                'gateway_response' => $payment->gateway_response(),
2137
-                'txn_id_chq_nmbr'  => $payment->txn_id_chq_nmbr(),
2138
-                'po_number'        => $payment->po_number(),
2139
-                'extra_accntng'    => $payment->extra_accntng(),
2140
-                'registrations'    => $this->_registration_payment_data_array($REG_IDs),
2141
-            );
2142
-        }
2143
-    }
2144
-
2145
-
2146
-    /**
2147
-     * delete_payment
2148
-     *    delete a payment or refund made towards a transaction
2149
-     *
2150
-     * @access public
2151
-     * @return void
2152
-     * @throws EE_Error
2153
-     * @throws InvalidArgumentException
2154
-     * @throws ReflectionException
2155
-     * @throws InvalidDataTypeException
2156
-     * @throws InvalidInterfaceException
2157
-     */
2158
-    public function delete_payment()
2159
-    {
2160
-        $json_response_data = array('return_data' => false);
2161
-        $PAY_ID = isset($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2162
-            ? absint($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2163
-            : 0;
2164
-        $can_delete = EE_Registry::instance()->CAP->current_user_can(
2165
-            'ee_delete_payments',
2166
-            'delete_payment_from_registration_details'
2167
-        );
2168
-        if ($PAY_ID && $can_delete) {
2169
-            $delete_txn_reg_status_change = isset($this->_req_data['delete_txn_reg_status_change'])
2170
-                ? $this->_req_data['delete_txn_reg_status_change']
2171
-                : false;
2172
-            $payment = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
2173
-            if ($payment instanceof EE_Payment) {
2174
-                $REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2175
-                /** @type EE_Transaction_Payments $transaction_payments */
2176
-                $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2177
-                if ($transaction_payments->delete_payment_and_update_transaction($payment)) {
2178
-                    $json_response_data['return_data'] = $this->_build_payment_json_response(
2179
-                        $payment,
2180
-                        $REG_IDs,
2181
-                        $delete_txn_reg_status_change
2182
-                    );
2183
-                    if ($delete_txn_reg_status_change) {
2184
-                        $this->_req_data['txn_reg_status_change'] = $delete_txn_reg_status_change;
2185
-                        // MAKE sure we also add the delete_txn_req_status_change to the
2186
-                        // $_REQUEST global because that's how messages will be looking for it.
2187
-                        $_REQUEST['txn_reg_status_change'] = $delete_txn_reg_status_change;
2188
-                        $this->_maybe_send_notifications();
2189
-                        $this->_process_registration_status_change($payment->transaction(), $REG_IDs);
2190
-                    }
2191
-                }
2192
-            } else {
2193
-                EE_Error::add_error(
2194
-                    esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'),
2195
-                    __FILE__,
2196
-                    __FUNCTION__,
2197
-                    __LINE__
2198
-                );
2199
-            }
2200
-        } else {
2201
-            if ($can_delete) {
2202
-                EE_Error::add_error(
2203
-                    esc_html__(
2204
-                        'A valid Payment ID was not received, therefore payment form data could not be loaded.',
2205
-                        'event_espresso'
2206
-                    ),
2207
-                    __FILE__,
2208
-                    __FUNCTION__,
2209
-                    __LINE__
2210
-                );
2211
-            } else {
2212
-                EE_Error::add_error(
2213
-                    esc_html__(
2214
-                        'You do not have access to delete a payment.',
2215
-                        'event_espresso'
2216
-                    ),
2217
-                    __FILE__,
2218
-                    __FUNCTION__,
2219
-                    __LINE__
2220
-                );
2221
-            }
2222
-        }
2223
-        $notices = EE_Error::get_notices(false, false, false);
2224
-        $this->_template_args = array(
2225
-            'data'      => $json_response_data,
2226
-            'success'   => $notices['success'],
2227
-            'error'     => $notices['errors'],
2228
-            'attention' => $notices['attention'],
2229
-        );
2230
-        $this->_return_json();
2231
-    }
2232
-
2233
-
2234
-    /**
2235
-     * _registration_payment_data_array
2236
-     * adds info for 'owing' and 'paid' for each registration to the json response
2237
-     *
2238
-     * @access protected
2239
-     * @param array $REG_IDs
2240
-     * @return array
2241
-     * @throws EE_Error
2242
-     * @throws InvalidArgumentException
2243
-     * @throws InvalidDataTypeException
2244
-     * @throws InvalidInterfaceException
2245
-     * @throws ReflectionException
2246
-     */
2247
-    protected function _registration_payment_data_array($REG_IDs)
2248
-    {
2249
-        $registration_payment_data = array();
2250
-        // if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
2251
-        if (! empty($REG_IDs)) {
2252
-            $registrations = EEM_Registration::instance()->get_all(array(array('REG_ID' => array('IN', $REG_IDs))));
2253
-            foreach ($registrations as $registration) {
2254
-                if ($registration instanceof EE_Registration) {
2255
-                    $registration_payment_data[ $registration->ID() ] = array(
2256
-                        'paid'  => $registration->pretty_paid(),
2257
-                        'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
2258
-                    );
2259
-                }
2260
-            }
2261
-        }
2262
-
2263
-        return $registration_payment_data;
2264
-    }
2265
-
2266
-
2267
-    /**
2268
-     * _maybe_send_notifications
2269
-     * determines whether or not the admin has indicated that notifications should be sent.
2270
-     * If so, will toggle a filter switch for delivering registration notices.
2271
-     * If passed an EE_Payment object, then it will trigger payment notifications instead.
2272
-     *
2273
-     * @access protected
2274
-     * @param \EE_Payment | null $payment
2275
-     */
2276
-    protected function _maybe_send_notifications($payment = null)
2277
-    {
2278
-        switch ($payment instanceof EE_Payment) {
2279
-            // payment notifications
2280
-            case true:
2281
-                if (isset(
2282
-                    $this->_req_data['txn_payments'],
2283
-                    $this->_req_data['txn_payments']['send_notifications']
2284
-                )
2285
-                    && filter_var($this->_req_data['txn_payments']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
2286
-                ) {
2287
-                    $this->_process_payment_notification($payment);
2288
-                }
2289
-                break;
2290
-            // registration notifications
2291
-            case false:
2292
-                if (isset(
2293
-                    $this->_req_data['txn_reg_status_change'],
2294
-                    $this->_req_data['txn_reg_status_change']['send_notifications']
2295
-                )
2296
-                    && filter_var($this->_req_data['txn_reg_status_change']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
2297
-                ) {
2298
-                    add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
2299
-                }
2300
-                break;
2301
-        }
2302
-    }
2303
-
2304
-
2305
-    /**
2306
-     * _send_payment_reminder
2307
-     *    generates HTML for the View Transaction Details Admin page
2308
-     *
2309
-     * @access protected
2310
-     * @return void
2311
-     * @throws EE_Error
2312
-     * @throws InvalidArgumentException
2313
-     * @throws InvalidDataTypeException
2314
-     * @throws InvalidInterfaceException
2315
-     */
2316
-    protected function _send_payment_reminder()
2317
-    {
2318
-        $TXN_ID = ! empty($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : false;
2319
-        $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2320
-        $query_args = isset($this->_req_data['redirect_to']) ? array(
2321
-            'action' => $this->_req_data['redirect_to'],
2322
-            'TXN_ID' => $this->_req_data['TXN_ID'],
2323
-        ) : array();
2324
-        do_action(
2325
-            'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
2326
-            $transaction
2327
-        );
2328
-        $this->_redirect_after_action(
2329
-            false,
2330
-            esc_html__('payment reminder', 'event_espresso'),
2331
-            esc_html__('sent', 'event_espresso'),
2332
-            $query_args,
2333
-            true
2334
-        );
2335
-    }
2336
-
2337
-
2338
-    /**
2339
-     *  get_transactions
2340
-     *    get transactions for given parameters (used by list table)
2341
-     *
2342
-     * @param  int     $perpage how many transactions displayed per page
2343
-     * @param  boolean $count   return the count or objects
2344
-     * @param string   $view
2345
-     * @return mixed int = count || array of transaction objects
2346
-     * @throws EE_Error
2347
-     * @throws InvalidArgumentException
2348
-     * @throws InvalidDataTypeException
2349
-     * @throws InvalidInterfaceException
2350
-     */
2351
-    public function get_transactions($perpage, $count = false, $view = '')
2352
-    {
2353
-
2354
-        $TXN = EEM_Transaction::instance();
2355
-
2356
-        $start_date = isset($this->_req_data['txn-filter-start-date'])
2357
-            ? wp_strip_all_tags($this->_req_data['txn-filter-start-date'])
2358
-            : date(
2359
-                'm/d/Y',
2360
-                strtotime('-10 year')
2361
-            );
2362
-        $end_date = isset($this->_req_data['txn-filter-end-date'])
2363
-            ? wp_strip_all_tags($this->_req_data['txn-filter-end-date'])
2364
-            : date('m/d/Y');
2365
-
2366
-        // make sure our timestamps start and end right at the boundaries for each day
2367
-        $start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
2368
-        $end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
2369
-
2370
-
2371
-        // convert to timestamps
2372
-        $start_date = strtotime($start_date);
2373
-        $end_date = strtotime($end_date);
2374
-
2375
-        // makes sure start date is the lowest value and vice versa
2376
-        $start_date = min($start_date, $end_date);
2377
-        $end_date = max($start_date, $end_date);
2378
-
2379
-        // convert to correct format for query
2380
-        $start_date = EEM_Transaction::instance()->convert_datetime_for_query(
2381
-            'TXN_timestamp',
2382
-            date('Y-m-d H:i:s', $start_date),
2383
-            'Y-m-d H:i:s'
2384
-        );
2385
-        $end_date = EEM_Transaction::instance()->convert_datetime_for_query(
2386
-            'TXN_timestamp',
2387
-            date('Y-m-d H:i:s', $end_date),
2388
-            'Y-m-d H:i:s'
2389
-        );
2390
-
2391
-
2392
-        // set orderby
2393
-        $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2394
-
2395
-        switch ($this->_req_data['orderby']) {
2396
-            case 'TXN_ID':
2397
-                $orderby = 'TXN_ID';
2398
-                break;
2399
-            case 'ATT_fname':
2400
-                $orderby = 'Registration.Attendee.ATT_fname';
2401
-                break;
2402
-            case 'event_name':
2403
-                $orderby = 'Registration.Event.EVT_name';
2404
-                break;
2405
-            default: // 'TXN_timestamp'
2406
-                $orderby = 'TXN_timestamp';
2407
-        }
2408
-
2409
-        $sort = ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'DESC';
2410
-        $current_page = ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
2411
-        $per_page = ! empty($perpage) ? $perpage : 10;
2412
-        $per_page = ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $per_page;
2413
-
2414
-        $offset = ($current_page - 1) * $per_page;
2415
-        $limit = array($offset, $per_page);
2416
-
2417
-        $_where = array(
2418
-            'TXN_timestamp'          => array('BETWEEN', array($start_date, $end_date)),
2419
-            'Registration.REG_count' => 1,
2420
-        );
2421
-
2422
-        if (isset($this->_req_data['EVT_ID'])) {
2423
-            $_where['Registration.EVT_ID'] = $this->_req_data['EVT_ID'];
2424
-        }
2425
-
2426
-        if (isset($this->_req_data['s'])) {
2427
-            $search_string = '%' . $this->_req_data['s'] . '%';
2428
-            $_where['OR'] = array(
2429
-                'Registration.Event.EVT_name'         => array('LIKE', $search_string),
2430
-                'Registration.Event.EVT_desc'         => array('LIKE', $search_string),
2431
-                'Registration.Event.EVT_short_desc'   => array('LIKE', $search_string),
2432
-                'Registration.Attendee.ATT_full_name' => array('LIKE', $search_string),
2433
-                'Registration.Attendee.ATT_fname'     => array('LIKE', $search_string),
2434
-                'Registration.Attendee.ATT_lname'     => array('LIKE', $search_string),
2435
-                'Registration.Attendee.ATT_short_bio' => array('LIKE', $search_string),
2436
-                'Registration.Attendee.ATT_email'     => array('LIKE', $search_string),
2437
-                'Registration.Attendee.ATT_address'   => array('LIKE', $search_string),
2438
-                'Registration.Attendee.ATT_address2'  => array('LIKE', $search_string),
2439
-                'Registration.Attendee.ATT_city'      => array('LIKE', $search_string),
2440
-                'Registration.REG_final_price'        => array('LIKE', $search_string),
2441
-                'Registration.REG_code'               => array('LIKE', $search_string),
2442
-                'Registration.REG_count'              => array('LIKE', $search_string),
2443
-                'Registration.REG_group_size'         => array('LIKE', $search_string),
2444
-                'Registration.Ticket.TKT_name'        => array('LIKE', $search_string),
2445
-                'Registration.Ticket.TKT_description' => array('LIKE', $search_string),
2446
-                'Payment.PAY_source'                  => array('LIKE', $search_string),
2447
-                'Payment.Payment_Method.PMD_name'     => array('LIKE', $search_string),
2448
-                'TXN_session_data'                    => array('LIKE', $search_string),
2449
-                'Payment.PAY_txn_id_chq_nmbr'         => array('LIKE', $search_string),
2450
-            );
2451
-        }
2452
-
2453
-        // failed transactions
2454
-        $failed = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count)
2455
-                  || ($count && $view === 'failed');
2456
-        $abandoned = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count)
2457
-                     || ($count && $view === 'abandoned');
2458
-
2459
-        if ($failed) {
2460
-            $_where['STS_ID'] = EEM_Transaction::failed_status_code;
2461
-        } elseif ($abandoned) {
2462
-            $_where['STS_ID'] = EEM_Transaction::abandoned_status_code;
2463
-        } else {
2464
-            $_where['STS_ID'] = array('!=', EEM_Transaction::failed_status_code);
2465
-            $_where['STS_ID*'] = array('!=', EEM_Transaction::abandoned_status_code);
2466
-        }
2467
-
2468
-        $query_params = array(
2469
-            $_where,
2470
-            'order_by'                 => array($orderby => $sort),
2471
-            'limit'                    => $limit,
2472
-            'default_where_conditions' => EEM_Base::default_where_conditions_this_only,
2473
-        );
2474
-
2475
-        $transactions = $count
2476
-            ? $TXN->count(array($_where), 'TXN_ID', true)
2477
-            : $TXN->get_all($query_params);
2478
-
2479
-        return $transactions;
2480
-    }
17
+	/**
18
+	 * @var EE_Transaction
19
+	 */
20
+	private $_transaction;
21
+
22
+	/**
23
+	 * @var EE_Session
24
+	 */
25
+	private $_session;
26
+
27
+	/**
28
+	 * @var array $_txn_status
29
+	 */
30
+	private static $_txn_status;
31
+
32
+	/**
33
+	 * @var array $_pay_status
34
+	 */
35
+	private static $_pay_status;
36
+
37
+	/**
38
+	 * @var array $_existing_reg_payment_REG_IDs
39
+	 */
40
+	protected $_existing_reg_payment_REG_IDs = null;
41
+
42
+
43
+	/**
44
+	 * @Constructor
45
+	 * @access public
46
+	 * @param bool $routing
47
+	 * @throws EE_Error
48
+	 * @throws InvalidArgumentException
49
+	 * @throws ReflectionException
50
+	 * @throws InvalidDataTypeException
51
+	 * @throws InvalidInterfaceException
52
+	 */
53
+	public function __construct($routing = true)
54
+	{
55
+		parent::__construct($routing);
56
+	}
57
+
58
+
59
+	/**
60
+	 *    _init_page_props
61
+	 *
62
+	 * @return void
63
+	 */
64
+	protected function _init_page_props()
65
+	{
66
+		$this->page_slug = TXN_PG_SLUG;
67
+		$this->page_label = esc_html__('Transactions', 'event_espresso');
68
+		$this->_admin_base_url = TXN_ADMIN_URL;
69
+		$this->_admin_base_path = TXN_ADMIN;
70
+	}
71
+
72
+
73
+	/**
74
+	 *    _ajax_hooks
75
+	 *
76
+	 * @return void
77
+	 */
78
+	protected function _ajax_hooks()
79
+	{
80
+		add_action('wp_ajax_espresso_apply_payment', array($this, 'apply_payments_or_refunds'));
81
+		add_action('wp_ajax_espresso_apply_refund', array($this, 'apply_payments_or_refunds'));
82
+		add_action('wp_ajax_espresso_delete_payment', array($this, 'delete_payment'));
83
+	}
84
+
85
+
86
+	/**
87
+	 *    _define_page_props
88
+	 *
89
+	 * @return void
90
+	 */
91
+	protected function _define_page_props()
92
+	{
93
+		$this->_admin_page_title = $this->page_label;
94
+		$this->_labels = array(
95
+			'buttons' => array(
96
+				'add'    => esc_html__('Add New Transaction', 'event_espresso'),
97
+				'edit'   => esc_html__('Edit Transaction', 'event_espresso'),
98
+				'delete' => esc_html__('Delete Transaction', 'event_espresso'),
99
+			),
100
+		);
101
+	}
102
+
103
+
104
+	/**
105
+	 *        grab url requests and route them
106
+	 *
107
+	 * @access private
108
+	 * @return void
109
+	 * @throws EE_Error
110
+	 * @throws InvalidArgumentException
111
+	 * @throws InvalidDataTypeException
112
+	 * @throws InvalidInterfaceException
113
+	 */
114
+	public function _set_page_routes()
115
+	{
116
+
117
+		$this->_set_transaction_status_array();
118
+
119
+		$txn_id = ! empty($this->_req_data['TXN_ID'])
120
+				  && ! is_array($this->_req_data['TXN_ID'])
121
+			? $this->_req_data['TXN_ID']
122
+			: 0;
123
+
124
+		$this->_page_routes = array(
125
+
126
+			'default' => array(
127
+				'func'       => '_transactions_overview_list_table',
128
+				'capability' => 'ee_read_transactions',
129
+			),
130
+
131
+			'view_transaction' => array(
132
+				'func'       => '_transaction_details',
133
+				'capability' => 'ee_read_transaction',
134
+				'obj_id'     => $txn_id,
135
+			),
136
+
137
+			'send_payment_reminder' => array(
138
+				'func'       => '_send_payment_reminder',
139
+				'noheader'   => true,
140
+				'capability' => 'ee_send_message',
141
+			),
142
+
143
+			'espresso_apply_payment' => array(
144
+				'func'       => 'apply_payments_or_refunds',
145
+				'noheader'   => true,
146
+				'capability' => 'ee_edit_payments',
147
+			),
148
+
149
+			'espresso_apply_refund' => array(
150
+				'func'       => 'apply_payments_or_refunds',
151
+				'noheader'   => true,
152
+				'capability' => 'ee_edit_payments',
153
+			),
154
+
155
+			'espresso_delete_payment' => array(
156
+				'func'       => 'delete_payment',
157
+				'noheader'   => true,
158
+				'capability' => 'ee_delete_payments',
159
+			),
160
+
161
+		);
162
+	}
163
+
164
+
165
+	protected function _set_page_config()
166
+	{
167
+		$this->_page_config = array(
168
+			'default'          => array(
169
+				'nav'           => array(
170
+					'label' => esc_html__('Overview', 'event_espresso'),
171
+					'order' => 10,
172
+				),
173
+				'list_table'    => 'EE_Admin_Transactions_List_Table',
174
+				'help_tabs'     => array(
175
+					'transactions_overview_help_tab'                       => array(
176
+						'title'    => esc_html__('Transactions Overview', 'event_espresso'),
177
+						'filename' => 'transactions_overview',
178
+					),
179
+					'transactions_overview_table_column_headings_help_tab' => array(
180
+						'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'),
181
+						'filename' => 'transactions_overview_table_column_headings',
182
+					),
183
+					'transactions_overview_views_filters_help_tab'         => array(
184
+						'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'),
185
+						'filename' => 'transactions_overview_views_filters_search',
186
+					),
187
+				),
188
+				'help_tour'     => array('Transactions_Overview_Help_Tour'),
189
+				/**
190
+				 * commented out because currently we are not displaying tips for transaction list table status but this
191
+				 * may change in a later iteration so want to keep the code for then.
192
+				 */
193
+				// 'qtips' => array( 'Transactions_List_Table_Tips' ),
194
+				'require_nonce' => false,
195
+			),
196
+			'view_transaction' => array(
197
+				'nav'       => array(
198
+					'label'      => esc_html__('View Transaction', 'event_espresso'),
199
+					'order'      => 5,
200
+					'url'        => isset($this->_req_data['TXN_ID'])
201
+						? add_query_arg(array('TXN_ID' => $this->_req_data['TXN_ID']), $this->_current_page_view_url)
202
+						: $this->_admin_base_url,
203
+					'persistent' => false,
204
+				),
205
+				'help_tabs' => array(
206
+					'transactions_view_transaction_help_tab'                                              => array(
207
+						'title'    => esc_html__('View Transaction', 'event_espresso'),
208
+						'filename' => 'transactions_view_transaction',
209
+					),
210
+					'transactions_view_transaction_transaction_details_table_help_tab'                    => array(
211
+						'title'    => esc_html__('Transaction Details Table', 'event_espresso'),
212
+						'filename' => 'transactions_view_transaction_transaction_details_table',
213
+					),
214
+					'transactions_view_transaction_attendees_registered_help_tab'                         => array(
215
+						'title'    => esc_html__('Attendees Registered', 'event_espresso'),
216
+						'filename' => 'transactions_view_transaction_attendees_registered',
217
+					),
218
+					'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => array(
219
+						'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'),
220
+						'filename' => 'transactions_view_transaction_primary_registrant_billing_information',
221
+					),
222
+				),
223
+				'qtips'     => array('Transaction_Details_Tips'),
224
+				'help_tour' => array('Transaction_Details_Help_Tour'),
225
+				'metaboxes' => array('_transaction_details_metaboxes'),
226
+
227
+				'require_nonce' => false,
228
+			),
229
+		);
230
+	}
231
+
232
+
233
+	/**
234
+	 * The below methods aren't used by this class currently
235
+	 */
236
+	protected function _add_screen_options()
237
+	{
238
+		// noop
239
+	}
240
+
241
+	protected function _add_feature_pointers()
242
+	{
243
+		// noop
244
+	}
245
+
246
+	public function admin_init()
247
+	{
248
+		// IF a registration was JUST added via the admin...
249
+		if (isset(
250
+			$this->_req_data['redirect_from'],
251
+			$this->_req_data['EVT_ID'],
252
+			$this->_req_data['event_name']
253
+		)) {
254
+			// then set a cookie so that we can block any attempts to use
255
+			// the back button as a way to enter another registration.
256
+			setcookie(
257
+				'ee_registration_added',
258
+				$this->_req_data['EVT_ID'],
259
+				time() + WEEK_IN_SECONDS,
260
+				'/'
261
+			);
262
+			// and update the global
263
+			$_COOKIE['ee_registration_added'] = $this->_req_data['EVT_ID'];
264
+		}
265
+		EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__(
266
+			'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.',
267
+			'event_espresso'
268
+		);
269
+		EE_Registry::$i18n_js_strings['error_occurred'] = esc_html__(
270
+			'An error occurred! Please refresh the page and try again.',
271
+			'event_espresso'
272
+		);
273
+		EE_Registry::$i18n_js_strings['txn_status_array'] = self::$_txn_status;
274
+		EE_Registry::$i18n_js_strings['pay_status_array'] = self::$_pay_status;
275
+		EE_Registry::$i18n_js_strings['payments_total'] = esc_html__('Payments Total', 'event_espresso');
276
+		EE_Registry::$i18n_js_strings['transaction_overpaid'] = esc_html__(
277
+			'This transaction has been overpaid ! Payments Total',
278
+			'event_espresso'
279
+		);
280
+	}
281
+
282
+	public function admin_notices()
283
+	{
284
+		// noop
285
+	}
286
+
287
+	public function admin_footer_scripts()
288
+	{
289
+		// noop
290
+	}
291
+
292
+
293
+	/**
294
+	 * _set_transaction_status_array
295
+	 * sets list of transaction statuses
296
+	 *
297
+	 * @access private
298
+	 * @return void
299
+	 * @throws EE_Error
300
+	 * @throws InvalidArgumentException
301
+	 * @throws InvalidDataTypeException
302
+	 * @throws InvalidInterfaceException
303
+	 */
304
+	private function _set_transaction_status_array()
305
+	{
306
+		self::$_txn_status = EEM_Transaction::instance()->status_array(true);
307
+	}
308
+
309
+
310
+	/**
311
+	 * get_transaction_status_array
312
+	 * return the transaction status array for wp_list_table
313
+	 *
314
+	 * @access public
315
+	 * @return array
316
+	 */
317
+	public function get_transaction_status_array()
318
+	{
319
+		return self::$_txn_status;
320
+	}
321
+
322
+
323
+	/**
324
+	 *    get list of payment statuses
325
+	 *
326
+	 * @access private
327
+	 * @return void
328
+	 * @throws EE_Error
329
+	 * @throws InvalidArgumentException
330
+	 * @throws InvalidDataTypeException
331
+	 * @throws InvalidInterfaceException
332
+	 */
333
+	private function _get_payment_status_array()
334
+	{
335
+		self::$_pay_status = EEM_Payment::instance()->status_array(true);
336
+		$this->_template_args['payment_status'] = self::$_pay_status;
337
+	}
338
+
339
+
340
+	/**
341
+	 *    _add_screen_options_default
342
+	 *
343
+	 * @access protected
344
+	 * @return void
345
+	 * @throws InvalidArgumentException
346
+	 * @throws InvalidDataTypeException
347
+	 * @throws InvalidInterfaceException
348
+	 */
349
+	protected function _add_screen_options_default()
350
+	{
351
+		$this->_per_page_screen_option();
352
+	}
353
+
354
+
355
+	/**
356
+	 * load_scripts_styles
357
+	 *
358
+	 * @access public
359
+	 * @return void
360
+	 */
361
+	public function load_scripts_styles()
362
+	{
363
+		// enqueue style
364
+		wp_register_style(
365
+			'espresso_txn',
366
+			TXN_ASSETS_URL . 'espresso_transactions_admin.css',
367
+			array(),
368
+			EVENT_ESPRESSO_VERSION
369
+		);
370
+		wp_enqueue_style('espresso_txn');
371
+		// scripts
372
+		wp_register_script(
373
+			'espresso_txn',
374
+			TXN_ASSETS_URL . 'espresso_transactions_admin.js',
375
+			array(
376
+				'ee_admin_js',
377
+				'ee-datepicker',
378
+				'jquery-ui-datepicker',
379
+				'jquery-ui-draggable',
380
+				'ee-dialog',
381
+				'ee-accounting',
382
+				'ee-serialize-full-array',
383
+			),
384
+			EVENT_ESPRESSO_VERSION,
385
+			true
386
+		);
387
+		wp_enqueue_script('espresso_txn');
388
+	}
389
+
390
+
391
+	/**
392
+	 *    load_scripts_styles_view_transaction
393
+	 *
394
+	 * @access public
395
+	 * @return void
396
+	 */
397
+	public function load_scripts_styles_view_transaction()
398
+	{
399
+		// styles
400
+		wp_enqueue_style('espresso-ui-theme');
401
+	}
402
+
403
+
404
+	/**
405
+	 *    load_scripts_styles_default
406
+	 *
407
+	 * @access public
408
+	 * @return void
409
+	 */
410
+	public function load_scripts_styles_default()
411
+	{
412
+		// styles
413
+		wp_enqueue_style('espresso-ui-theme');
414
+	}
415
+
416
+
417
+	/**
418
+	 *    _set_list_table_views_default
419
+	 *
420
+	 * @access protected
421
+	 * @return void
422
+	 */
423
+	protected function _set_list_table_views_default()
424
+	{
425
+		$this->_views = array(
426
+			'all'       => array(
427
+				'slug'  => 'all',
428
+				'label' => esc_html__('View All Transactions', 'event_espresso'),
429
+				'count' => 0,
430
+			),
431
+			'abandoned' => array(
432
+				'slug'  => 'abandoned',
433
+				'label' => esc_html__('Abandoned Transactions', 'event_espresso'),
434
+				'count' => 0,
435
+			),
436
+			'failed'    => array(
437
+				'slug'  => 'failed',
438
+				'label' => esc_html__('Failed Transactions', 'event_espresso'),
439
+				'count' => 0,
440
+			),
441
+		);
442
+	}
443
+
444
+
445
+	/**
446
+	 * _set_transaction_object
447
+	 * This sets the _transaction property for the transaction details screen
448
+	 *
449
+	 * @access private
450
+	 * @return void
451
+	 * @throws EE_Error
452
+	 * @throws InvalidArgumentException
453
+	 * @throws RuntimeException
454
+	 * @throws InvalidDataTypeException
455
+	 * @throws InvalidInterfaceException
456
+	 * @throws ReflectionException
457
+	 */
458
+	private function _set_transaction_object()
459
+	{
460
+		if ($this->_transaction instanceof EE_Transaction) {
461
+			return;
462
+		} //get out we've already set the object
463
+
464
+		$TXN_ID = ! empty($this->_req_data['TXN_ID'])
465
+			? absint($this->_req_data['TXN_ID'])
466
+			: false;
467
+
468
+		// get transaction object
469
+		$this->_transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
470
+		$this->_session = $this->_transaction instanceof EE_Transaction
471
+			? $this->_transaction->get('TXN_session_data')
472
+			: null;
473
+		if ($this->_transaction instanceof EE_Transaction) {
474
+			$this->_transaction->verify_abandoned_transaction_status();
475
+		}
476
+
477
+		if (! $this->_transaction instanceof EE_Transaction) {
478
+			$error_msg = sprintf(
479
+				esc_html__(
480
+					'An error occurred and the details for the transaction with the ID # %d could not be retrieved.',
481
+					'event_espresso'
482
+				),
483
+				$TXN_ID
484
+			);
485
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
486
+		}
487
+	}
488
+
489
+
490
+	/**
491
+	 *    _transaction_legend_items
492
+	 *
493
+	 * @access protected
494
+	 * @return array
495
+	 * @throws EE_Error
496
+	 * @throws InvalidArgumentException
497
+	 * @throws ReflectionException
498
+	 * @throws InvalidDataTypeException
499
+	 * @throws InvalidInterfaceException
500
+	 */
501
+	protected function _transaction_legend_items()
502
+	{
503
+		EE_Registry::instance()->load_helper('MSG_Template');
504
+		$items = array();
505
+
506
+		if (EE_Registry::instance()->CAP->current_user_can(
507
+			'ee_read_global_messages',
508
+			'view_filtered_messages'
509
+		)) {
510
+			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
511
+			if (is_array($related_for_icon)
512
+				&& isset($related_for_icon['css_class'], $related_for_icon['label'])
513
+			) {
514
+				$items['view_related_messages'] = array(
515
+					'class' => $related_for_icon['css_class'],
516
+					'desc'  => $related_for_icon['label'],
517
+				);
518
+			}
519
+		}
520
+
521
+		$items = apply_filters(
522
+			'FHEE__Transactions_Admin_Page___transaction_legend_items__items',
523
+			array_merge(
524
+				$items,
525
+				array(
526
+					'view_details'          => array(
527
+						'class' => 'dashicons dashicons-cart',
528
+						'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
529
+					),
530
+					'view_invoice'          => array(
531
+						'class' => 'dashicons dashicons-media-spreadsheet',
532
+						'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
533
+					),
534
+					'view_receipt'          => array(
535
+						'class' => 'dashicons dashicons-media-default',
536
+						'desc'  => esc_html__('View Transaction Receipt', 'event_espresso'),
537
+					),
538
+					'view_registration'     => array(
539
+						'class' => 'dashicons dashicons-clipboard',
540
+						'desc'  => esc_html__('View Registration Details', 'event_espresso'),
541
+					),
542
+					'payment_overview_link' => array(
543
+						'class' => 'dashicons dashicons-money',
544
+						'desc'  => esc_html__('Make Payment on Frontend', 'event_espresso'),
545
+					),
546
+				)
547
+			)
548
+		);
549
+
550
+		if (EE_Registry::instance()->CAP->current_user_can(
551
+			'ee_send_message',
552
+			'espresso_transactions_send_payment_reminder'
553
+		)) {
554
+			if (EEH_MSG_Template::is_mt_active('payment_reminder')) {
555
+				$items['send_payment_reminder'] = array(
556
+					'class' => 'dashicons dashicons-email-alt',
557
+					'desc'  => esc_html__('Send Payment Reminder', 'event_espresso'),
558
+				);
559
+			} else {
560
+				$items['blank*'] = array(
561
+					'class' => '',
562
+					'desc'  => '',
563
+				);
564
+			}
565
+		} else {
566
+			$items['blank*'] = array(
567
+				'class' => '',
568
+				'desc'  => '',
569
+			);
570
+		}
571
+		$more_items = apply_filters(
572
+			'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
573
+			array(
574
+				'overpaid'   => array(
575
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code,
576
+					'desc'  => EEH_Template::pretty_status(
577
+						EEM_Transaction::overpaid_status_code,
578
+						false,
579
+						'sentence'
580
+					),
581
+				),
582
+				'complete'   => array(
583
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code,
584
+					'desc'  => EEH_Template::pretty_status(
585
+						EEM_Transaction::complete_status_code,
586
+						false,
587
+						'sentence'
588
+					),
589
+				),
590
+				'incomplete' => array(
591
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code,
592
+					'desc'  => EEH_Template::pretty_status(
593
+						EEM_Transaction::incomplete_status_code,
594
+						false,
595
+						'sentence'
596
+					),
597
+				),
598
+				'abandoned'  => array(
599
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code,
600
+					'desc'  => EEH_Template::pretty_status(
601
+						EEM_Transaction::abandoned_status_code,
602
+						false,
603
+						'sentence'
604
+					),
605
+				),
606
+				'failed'     => array(
607
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code,
608
+					'desc'  => EEH_Template::pretty_status(
609
+						EEM_Transaction::failed_status_code,
610
+						false,
611
+						'sentence'
612
+					),
613
+				),
614
+			)
615
+		);
616
+
617
+		return array_merge($items, $more_items);
618
+	}
619
+
620
+
621
+	/**
622
+	 *    _transactions_overview_list_table
623
+	 *
624
+	 * @access protected
625
+	 * @return void
626
+	 * @throws DomainException
627
+	 * @throws EE_Error
628
+	 * @throws InvalidArgumentException
629
+	 * @throws InvalidDataTypeException
630
+	 * @throws InvalidInterfaceException
631
+	 * @throws ReflectionException
632
+	 */
633
+	protected function _transactions_overview_list_table()
634
+	{
635
+		$this->_admin_page_title = esc_html__('Transactions', 'event_espresso');
636
+		$event = isset($this->_req_data['EVT_ID'])
637
+			? EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID'])
638
+			: null;
639
+		$this->_template_args['admin_page_header'] = $event instanceof EE_Event
640
+			? sprintf(
641
+				esc_html__(
642
+					'%sViewing Transactions for the Event: %s%s',
643
+					'event_espresso'
644
+				),
645
+				'<h3>',
646
+				'<a href="'
647
+				. EE_Admin_Page::add_query_args_and_nonce(
648
+					array('action' => 'edit', 'post' => $event->ID()),
649
+					EVENTS_ADMIN_URL
650
+				)
651
+				. '" title="'
652
+				. esc_attr__(
653
+					'Click to Edit event',
654
+					'event_espresso'
655
+				)
656
+				. '">' . $event->get('EVT_name') . '</a>',
657
+				'</h3>'
658
+			)
659
+			: '';
660
+		$this->_template_args['after_list_table'] = $this->_display_legend($this->_transaction_legend_items());
661
+		$this->display_admin_list_table_page_with_no_sidebar();
662
+	}
663
+
664
+
665
+	/**
666
+	 *    _transaction_details
667
+	 * generates HTML for the View Transaction Details Admin page
668
+	 *
669
+	 * @access protected
670
+	 * @return void
671
+	 * @throws DomainException
672
+	 * @throws EE_Error
673
+	 * @throws InvalidArgumentException
674
+	 * @throws InvalidDataTypeException
675
+	 * @throws InvalidInterfaceException
676
+	 * @throws RuntimeException
677
+	 * @throws ReflectionException
678
+	 */
679
+	protected function _transaction_details()
680
+	{
681
+		do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction);
682
+
683
+		$this->_set_transaction_status_array();
684
+
685
+		$this->_template_args = array();
686
+		$this->_template_args['transactions_page'] = $this->_wp_page_slug;
687
+
688
+		$this->_set_transaction_object();
689
+
690
+		if (! $this->_transaction instanceof EE_Transaction) {
691
+			return;
692
+		}
693
+		$primary_registration = $this->_transaction->primary_registration();
694
+		$attendee = $primary_registration instanceof EE_Registration
695
+			? $primary_registration->attendee()
696
+			: null;
697
+
698
+		$this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID();
699
+		$this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso');
700
+
701
+		$this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
702
+		$this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
703
+
704
+		$this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->get('STS_ID') ];
705
+		$this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
706
+		$this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->get('STS_ID');
707
+
708
+		$this->_template_args['grand_total'] = $this->_transaction->get('TXN_total');
709
+		$this->_template_args['total_paid'] = $this->_transaction->get('TXN_paid');
710
+
711
+		$amount_due = $this->_transaction->get('TXN_total') - $this->_transaction->get('TXN_paid');
712
+		$this->_template_args['amount_due'] = EEH_Template::format_currency(
713
+			$amount_due,
714
+			true
715
+		);
716
+		if (EE_Registry::instance()->CFG->currency->sign_b4) {
717
+			$this->_template_args['amount_due'] = EE_Registry::instance()->CFG->currency->sign
718
+												  . $this->_template_args['amount_due'];
719
+		} else {
720
+			$this->_template_args['amount_due'] .= EE_Registry::instance()->CFG->currency->sign;
721
+		}
722
+		$this->_template_args['amount_due_class'] = '';
723
+
724
+		if ($this->_transaction->get('TXN_paid') == $this->_transaction->get('TXN_total')) {
725
+			// paid in full
726
+			$this->_template_args['amount_due'] = false;
727
+		} elseif ($this->_transaction->get('TXN_paid') > $this->_transaction->get('TXN_total')) {
728
+			// overpaid
729
+			$this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
730
+		} elseif ($this->_transaction->get('TXN_total') > 0
731
+				  && $this->_transaction->get('TXN_paid') > 0
732
+		) {
733
+			// monies owing
734
+			$this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn';
735
+		} elseif ($this->_transaction->get('TXN_total') > 0
736
+				  && $this->_transaction->get('TXN_paid') == 0
737
+		) {
738
+			// no payments made yet
739
+			$this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
740
+		} elseif ($this->_transaction->get('TXN_total') == 0) {
741
+			// free event
742
+			$this->_template_args['amount_due'] = false;
743
+		}
744
+
745
+		$payment_method = $this->_transaction->payment_method();
746
+
747
+		$this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method
748
+			? $payment_method->admin_name()
749
+			: esc_html__('Unknown', 'event_espresso');
750
+
751
+		$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
752
+		// link back to overview
753
+		$this->_template_args['txn_overview_url'] = ! empty($_SERVER['HTTP_REFERER'])
754
+			? $_SERVER['HTTP_REFERER']
755
+			: TXN_ADMIN_URL;
756
+
757
+
758
+		// next link
759
+		$next_txn = $this->_transaction->next(
760
+			null,
761
+			array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
762
+			'TXN_ID'
763
+		);
764
+		$this->_template_args['next_transaction'] = $next_txn
765
+			? $this->_next_link(
766
+				EE_Admin_Page::add_query_args_and_nonce(
767
+					array('action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']),
768
+					TXN_ADMIN_URL
769
+				),
770
+				'dashicons dashicons-arrow-right ee-icon-size-22'
771
+			)
772
+			: '';
773
+		// previous link
774
+		$previous_txn = $this->_transaction->previous(
775
+			null,
776
+			array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
777
+			'TXN_ID'
778
+		);
779
+		$this->_template_args['previous_transaction'] = $previous_txn
780
+			? $this->_previous_link(
781
+				EE_Admin_Page::add_query_args_and_nonce(
782
+					array('action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']),
783
+					TXN_ADMIN_URL
784
+				),
785
+				'dashicons dashicons-arrow-left ee-icon-size-22'
786
+			)
787
+			: '';
788
+
789
+		// were we just redirected here after adding a new registration ???
790
+		if (isset(
791
+			$this->_req_data['redirect_from'],
792
+			$this->_req_data['EVT_ID'],
793
+			$this->_req_data['event_name']
794
+		)) {
795
+			if (EE_Registry::instance()->CAP->current_user_can(
796
+				'ee_edit_registrations',
797
+				'espresso_registrations_new_registration',
798
+				$this->_req_data['EVT_ID']
799
+			)) {
800
+				$this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button-primary" href="';
801
+				$this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce(
802
+					array(
803
+						'page'     => 'espresso_registrations',
804
+						'action'   => 'new_registration',
805
+						'return'   => 'default',
806
+						'TXN_ID'   => $this->_transaction->ID(),
807
+						'event_id' => $this->_req_data['EVT_ID'],
808
+					),
809
+					REG_ADMIN_URL
810
+				);
811
+				$this->_admin_page_title .= '">';
812
+
813
+				$this->_admin_page_title .= sprintf(
814
+					esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'),
815
+					htmlentities(urldecode($this->_req_data['event_name']), ENT_QUOTES, 'UTF-8')
816
+				);
817
+				$this->_admin_page_title .= '</a>';
818
+			}
819
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
820
+		}
821
+		// grab messages at the last second
822
+		$this->_template_args['notices'] = EE_Error::get_notices();
823
+		// path to template
824
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
825
+		$this->_template_args['admin_page_header'] = EEH_Template::display_template(
826
+			$template_path,
827
+			$this->_template_args,
828
+			true
829
+		);
830
+
831
+		// the details template wrapper
832
+		$this->display_admin_page_with_sidebar();
833
+	}
834
+
835
+
836
+	/**
837
+	 *        _transaction_details_metaboxes
838
+	 *
839
+	 * @access protected
840
+	 * @return void
841
+	 * @throws EE_Error
842
+	 * @throws InvalidArgumentException
843
+	 * @throws InvalidDataTypeException
844
+	 * @throws InvalidInterfaceException
845
+	 * @throws RuntimeException
846
+	 * @throws ReflectionException
847
+	 */
848
+	protected function _transaction_details_metaboxes()
849
+	{
850
+
851
+		$this->_set_transaction_object();
852
+
853
+		if (! $this->_transaction instanceof EE_Transaction) {
854
+			return;
855
+		}
856
+		add_meta_box(
857
+			'edit-txn-details-mbox',
858
+			esc_html__('Transaction Details', 'event_espresso'),
859
+			array($this, 'txn_details_meta_box'),
860
+			$this->_wp_page_slug,
861
+			'normal',
862
+			'high'
863
+		);
864
+		add_meta_box(
865
+			'edit-txn-attendees-mbox',
866
+			esc_html__('Attendees Registered in this Transaction', 'event_espresso'),
867
+			array($this, 'txn_attendees_meta_box'),
868
+			$this->_wp_page_slug,
869
+			'normal',
870
+			'high',
871
+			array('TXN_ID' => $this->_transaction->ID())
872
+		);
873
+		add_meta_box(
874
+			'edit-txn-registrant-mbox',
875
+			esc_html__('Primary Contact', 'event_espresso'),
876
+			array($this, 'txn_registrant_side_meta_box'),
877
+			$this->_wp_page_slug,
878
+			'side',
879
+			'high'
880
+		);
881
+		add_meta_box(
882
+			'edit-txn-billing-info-mbox',
883
+			esc_html__('Billing Information', 'event_espresso'),
884
+			array($this, 'txn_billing_info_side_meta_box'),
885
+			$this->_wp_page_slug,
886
+			'side',
887
+			'high'
888
+		);
889
+	}
890
+
891
+
892
+	/**
893
+	 * Callback for transaction actions metabox.
894
+	 *
895
+	 * @param EE_Transaction|null $transaction
896
+	 * @throws DomainException
897
+	 * @throws EE_Error
898
+	 * @throws InvalidArgumentException
899
+	 * @throws InvalidDataTypeException
900
+	 * @throws InvalidInterfaceException
901
+	 * @throws ReflectionException
902
+	 * @throws RuntimeException
903
+	 */
904
+	public function getActionButtons(EE_Transaction $transaction = null)
905
+	{
906
+		$content = '';
907
+		$actions = array();
908
+		if (! $transaction instanceof EE_Transaction) {
909
+			return $content;
910
+		}
911
+		/** @var EE_Registration $primary_registration */
912
+		$primary_registration = $transaction->primary_registration();
913
+		$attendee = $primary_registration instanceof EE_Registration
914
+			? $primary_registration->attendee()
915
+			: null;
916
+
917
+		if ($attendee instanceof EE_Attendee
918
+			&& EE_Registry::instance()->CAP->current_user_can(
919
+				'ee_send_message',
920
+				'espresso_transactions_send_payment_reminder'
921
+			)
922
+		) {
923
+			$actions['payment_reminder'] =
924
+				EEH_MSG_Template::is_mt_active('payment_reminder')
925
+				&& $this->_transaction->get('STS_ID') !== EEM_Transaction::complete_status_code
926
+				&& $this->_transaction->get('STS_ID') !== EEM_Transaction::overpaid_status_code
927
+					? EEH_Template::get_button_or_link(
928
+						EE_Admin_Page::add_query_args_and_nonce(
929
+							array(
930
+								'action'      => 'send_payment_reminder',
931
+								'TXN_ID'      => $this->_transaction->ID(),
932
+								'redirect_to' => 'view_transaction',
933
+							),
934
+							TXN_ADMIN_URL
935
+						),
936
+						esc_html__(' Send Payment Reminder', 'event_espresso'),
937
+						'button secondary-button',
938
+						'dashicons dashicons-email-alt'
939
+					)
940
+					: '';
941
+		}
942
+
943
+		if ($primary_registration instanceof EE_Registration
944
+			&& EEH_MSG_Template::is_mt_active('receipt')
945
+		) {
946
+			$actions['receipt'] = EEH_Template::get_button_or_link(
947
+				$primary_registration->receipt_url(),
948
+				esc_html__('View Receipt', 'event_espresso'),
949
+				'button secondary-button',
950
+				'dashicons dashicons-media-default'
951
+			);
952
+		}
953
+
954
+		if ($primary_registration instanceof EE_Registration
955
+			&& EEH_MSG_Template::is_mt_active('invoice')
956
+		) {
957
+			$actions['invoice'] = EEH_Template::get_button_or_link(
958
+				$primary_registration->invoice_url(),
959
+				esc_html__('View Invoice', 'event_espresso'),
960
+				'button secondary-button',
961
+				'dashicons dashicons-media-spreadsheet'
962
+			);
963
+		}
964
+		$actions = array_filter(
965
+			apply_filters('FHEE__Transactions_Admin_Page__getActionButtons__actions', $actions, $transaction)
966
+		);
967
+		if ($actions) {
968
+			$content = '<ul>';
969
+			$content .= '<li>' . implode('</li><li>', $actions) . '</li>';
970
+			$content .= '</uL>';
971
+		}
972
+		return $content;
973
+	}
974
+
975
+
976
+	/**
977
+	 * txn_details_meta_box
978
+	 * generates HTML for the Transaction main meta box
979
+	 *
980
+	 * @return void
981
+	 * @throws DomainException
982
+	 * @throws EE_Error
983
+	 * @throws InvalidArgumentException
984
+	 * @throws InvalidDataTypeException
985
+	 * @throws InvalidInterfaceException
986
+	 * @throws RuntimeException
987
+	 * @throws ReflectionException
988
+	 */
989
+	public function txn_details_meta_box()
990
+	{
991
+		$this->_set_transaction_object();
992
+		$this->_template_args['TXN_ID'] = $this->_transaction->ID();
993
+		$this->_template_args['attendee'] = $this->_transaction->primary_registration() instanceof EE_Registration
994
+			? $this->_transaction->primary_registration()->attendee()
995
+			: null;
996
+		$this->_template_args['can_edit_payments'] = EE_Registry::instance()->CAP->current_user_can(
997
+			'ee_edit_payments',
998
+			'apply_payment_or_refund_from_registration_details'
999
+		);
1000
+		$this->_template_args['can_delete_payments'] = EE_Registry::instance()->CAP->current_user_can(
1001
+			'ee_delete_payments',
1002
+			'delete_payment_from_registration_details'
1003
+		);
1004
+
1005
+		// get line table
1006
+		EEH_Autoloader::register_line_item_display_autoloaders();
1007
+		$Line_Item_Display = new EE_Line_Item_Display(
1008
+			'admin_table',
1009
+			'EE_Admin_Table_Line_Item_Display_Strategy'
1010
+		);
1011
+		$this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item(
1012
+			$this->_transaction->total_line_item()
1013
+		);
1014
+		$this->_template_args['REG_code'] = $this->_transaction->get_first_related('Registration')
1015
+															   ->get('REG_code');
1016
+
1017
+		// process taxes
1018
+		$taxes = $this->_transaction->get_many_related(
1019
+			'Line_Item',
1020
+			array(array('LIN_type' => EEM_Line_Item::type_tax))
1021
+		);
1022
+		$this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false;
1023
+
1024
+		$this->_template_args['grand_total'] = EEH_Template::format_currency(
1025
+			$this->_transaction->get('TXN_total'),
1026
+			false,
1027
+			false
1028
+		);
1029
+		$this->_template_args['grand_raw_total'] = $this->_transaction->get('TXN_total');
1030
+		$this->_template_args['TXN_status'] = $this->_transaction->get('STS_ID');
1031
+
1032
+		// process payment details
1033
+		$payments = $this->_transaction->get_many_related('Payment');
1034
+		if (! empty($payments)) {
1035
+			$this->_template_args['payments'] = $payments;
1036
+			$this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
1037
+		} else {
1038
+			$this->_template_args['payments'] = false;
1039
+			$this->_template_args['existing_reg_payments'] = array();
1040
+		}
1041
+
1042
+		$this->_template_args['edit_payment_url'] = add_query_arg(array('action' => 'edit_payment'), TXN_ADMIN_URL);
1043
+		$this->_template_args['delete_payment_url'] = add_query_arg(
1044
+			array('action' => 'espresso_delete_payment'),
1045
+			TXN_ADMIN_URL
1046
+		);
1047
+
1048
+		if (isset($txn_details['invoice_number'])) {
1049
+			$this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code'];
1050
+			$this->_template_args['txn_details']['invoice_number']['label'] = esc_html__(
1051
+				'Invoice Number',
1052
+				'event_espresso'
1053
+			);
1054
+		}
1055
+
1056
+		$this->_template_args['txn_details']['registration_session']['value'] = $this->_transaction
1057
+			->get_first_related('Registration')
1058
+			->get('REG_session');
1059
+		$this->_template_args['txn_details']['registration_session']['label'] = esc_html__(
1060
+			'Registration Session',
1061
+			'event_espresso'
1062
+		);
1063
+
1064
+		$this->_template_args['txn_details']['ip_address']['value'] = isset($this->_session['ip_address'])
1065
+			? $this->_session['ip_address']
1066
+			: '';
1067
+		$this->_template_args['txn_details']['ip_address']['label'] = esc_html__(
1068
+			'Transaction placed from IP',
1069
+			'event_espresso'
1070
+		);
1071
+
1072
+		$this->_template_args['txn_details']['user_agent']['value'] = isset($this->_session['user_agent'])
1073
+			? $this->_session['user_agent']
1074
+			: '';
1075
+		$this->_template_args['txn_details']['user_agent']['label'] = esc_html__(
1076
+			'Registrant User Agent',
1077
+			'event_espresso'
1078
+		);
1079
+
1080
+		$reg_steps = '<ul>';
1081
+		foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) {
1082
+			if ($reg_step_status === true) {
1083
+				$reg_steps .= '<li style="color:#70cc50">'
1084
+							  . sprintf(
1085
+								  esc_html__('%1$s : Completed', 'event_espresso'),
1086
+								  ucwords(str_replace('_', ' ', $reg_step))
1087
+							  )
1088
+							  . '</li>';
1089
+			} elseif (is_numeric($reg_step_status) && $reg_step_status !== false) {
1090
+				$reg_steps .= '<li style="color:#2EA2CC">'
1091
+							  . sprintf(
1092
+								  esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
1093
+								  ucwords(str_replace('_', ' ', $reg_step)),
1094
+								  date(
1095
+									  get_option('date_format') . ' ' . get_option('time_format'),
1096
+									  ($reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS))
1097
+								  )
1098
+							  )
1099
+							  . '</li>';
1100
+			} else {
1101
+				$reg_steps .= '<li style="color:#E76700">'
1102
+							  . sprintf(
1103
+								  esc_html__('%1$s : Never Initiated', 'event_espresso'),
1104
+								  ucwords(str_replace('_', ' ', $reg_step))
1105
+							  )
1106
+							  . '</li>';
1107
+			}
1108
+		}
1109
+		$reg_steps .= '</ul>';
1110
+		$this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps;
1111
+		$this->_template_args['txn_details']['reg_steps']['label'] = esc_html__(
1112
+			'Registration Step Progress',
1113
+			'event_espresso'
1114
+		);
1115
+
1116
+
1117
+		$this->_get_registrations_to_apply_payment_to();
1118
+		$this->_get_payment_methods($payments);
1119
+		$this->_get_payment_status_array();
1120
+		$this->_get_reg_status_selection(); // sets up the template args for the reg status array for the transaction.
1121
+
1122
+		$this->_template_args['transaction_form_url'] = add_query_arg(
1123
+			array(
1124
+				'action'  => 'edit_transaction',
1125
+				'process' => 'transaction',
1126
+			),
1127
+			TXN_ADMIN_URL
1128
+		);
1129
+		$this->_template_args['apply_payment_form_url'] = add_query_arg(
1130
+			array(
1131
+				'page'   => 'espresso_transactions',
1132
+				'action' => 'espresso_apply_payment',
1133
+			),
1134
+			WP_AJAX_URL
1135
+		);
1136
+		$this->_template_args['delete_payment_form_url'] = add_query_arg(
1137
+			array(
1138
+				'page'   => 'espresso_transactions',
1139
+				'action' => 'espresso_delete_payment',
1140
+			),
1141
+			WP_AJAX_URL
1142
+		);
1143
+
1144
+		$this->_template_args['action_buttons'] = $this->getActionButtons($this->_transaction);
1145
+
1146
+		// 'espresso_delete_payment_nonce'
1147
+
1148
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
1149
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
1150
+	}
1151
+
1152
+
1153
+	/**
1154
+	 * _get_registration_payment_IDs
1155
+	 *    generates an array of Payment IDs and their corresponding Registration IDs
1156
+	 *
1157
+	 * @access protected
1158
+	 * @param EE_Payment[] $payments
1159
+	 * @return array
1160
+	 * @throws EE_Error
1161
+	 * @throws InvalidArgumentException
1162
+	 * @throws InvalidDataTypeException
1163
+	 * @throws InvalidInterfaceException
1164
+	 * @throws ReflectionException
1165
+	 */
1166
+	protected function _get_registration_payment_IDs($payments = array())
1167
+	{
1168
+		$existing_reg_payments = array();
1169
+		// get all reg payments for these payments
1170
+		$reg_payments = EEM_Registration_Payment::instance()->get_all(
1171
+			array(
1172
+				array(
1173
+					'PAY_ID' => array(
1174
+						'IN',
1175
+						array_keys($payments),
1176
+					),
1177
+				),
1178
+			)
1179
+		);
1180
+		if (! empty($reg_payments)) {
1181
+			foreach ($payments as $payment) {
1182
+				if (! $payment instanceof EE_Payment) {
1183
+					continue;
1184
+				} elseif (! isset($existing_reg_payments[ $payment->ID() ])) {
1185
+					$existing_reg_payments[ $payment->ID() ] = array();
1186
+				}
1187
+				foreach ($reg_payments as $reg_payment) {
1188
+					if ($reg_payment instanceof EE_Registration_Payment
1189
+						&& $reg_payment->payment_ID() === $payment->ID()
1190
+					) {
1191
+						$existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID();
1192
+					}
1193
+				}
1194
+			}
1195
+		}
1196
+
1197
+		return $existing_reg_payments;
1198
+	}
1199
+
1200
+
1201
+	/**
1202
+	 * _get_registrations_to_apply_payment_to
1203
+	 *    generates HTML for displaying a series of checkboxes in the admin payment modal window
1204
+	 * which allows the admin to only apply the payment to the specific registrations
1205
+	 *
1206
+	 * @access protected
1207
+	 * @return void
1208
+	 * @throws \EE_Error
1209
+	 */
1210
+	protected function _get_registrations_to_apply_payment_to()
1211
+	{
1212
+		// we want any registration with an active status (ie: not deleted or cancelled)
1213
+		$query_params = array(
1214
+			array(
1215
+				'STS_ID' => array(
1216
+					'IN',
1217
+					array(
1218
+						EEM_Registration::status_id_approved,
1219
+						EEM_Registration::status_id_pending_payment,
1220
+						EEM_Registration::status_id_not_approved,
1221
+					),
1222
+				),
1223
+			),
1224
+		);
1225
+		$registrations_to_apply_payment_to = EEH_HTML::br()
1226
+											 . EEH_HTML::div(
1227
+												 '',
1228
+												 'txn-admin-apply-payment-to-registrations-dv',
1229
+												 '',
1230
+												 'clear: both; margin: 1.5em 0 0; display: none;'
1231
+											 );
1232
+		$registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1233
+		$registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl');
1234
+		$registrations_to_apply_payment_to .= EEH_HTML::thead(
1235
+			EEH_HTML::tr(
1236
+				EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
1237
+				EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
1238
+				EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
1239
+				EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
1240
+				EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
1241
+				EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
1242
+				EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
1243
+			)
1244
+		);
1245
+		$registrations_to_apply_payment_to .= EEH_HTML::tbody();
1246
+		// get registrations for TXN
1247
+		$registrations = $this->_transaction->registrations($query_params);
1248
+		$existing_reg_payments = $this->_template_args['existing_reg_payments'];
1249
+		foreach ($registrations as $registration) {
1250
+			if ($registration instanceof EE_Registration) {
1251
+				$attendee_name = $registration->attendee() instanceof EE_Attendee
1252
+					? $registration->attendee()->full_name()
1253
+					: esc_html__('Unknown Attendee', 'event_espresso');
1254
+				$owing = $registration->final_price() - $registration->paid();
1255
+				$taxable = $registration->ticket()->taxable()
1256
+					? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
1257
+					: '';
1258
+				$checked = empty($existing_reg_payments) || in_array($registration->ID(), $existing_reg_payments)
1259
+					? ' checked="checked"'
1260
+					: '';
1261
+				$disabled = $registration->final_price() > 0 ? '' : ' disabled';
1262
+				$registrations_to_apply_payment_to .= EEH_HTML::tr(
1263
+					EEH_HTML::td($registration->ID()) .
1264
+					EEH_HTML::td($attendee_name) .
1265
+					EEH_HTML::td(
1266
+						$registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
1267
+					) .
1268
+					EEH_HTML::td($registration->event_name()) .
1269
+					EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
1270
+					EEH_HTML::td(EEH_Template::format_currency($owing), '', 'txn-admin-payment-owing-td jst-cntr') .
1271
+					EEH_HTML::td(
1272
+						'<input type="checkbox" value="' . $registration->ID()
1273
+						. '" name="txn_admin_payment[registrations]"'
1274
+						. $checked . $disabled . '>',
1275
+						'',
1276
+						'jst-cntr'
1277
+					),
1278
+					'apply-payment-registration-row-' . $registration->ID()
1279
+				);
1280
+			}
1281
+		}
1282
+		$registrations_to_apply_payment_to .= EEH_HTML::tbodyx();
1283
+		$registrations_to_apply_payment_to .= EEH_HTML::tablex();
1284
+		$registrations_to_apply_payment_to .= EEH_HTML::divx();
1285
+		$registrations_to_apply_payment_to .= EEH_HTML::p(
1286
+			esc_html__(
1287
+				'The payment will only be applied to the registrations that have a check mark in their corresponding check box. Checkboxes for free registrations have been disabled.',
1288
+				'event_espresso'
1289
+			),
1290
+			'',
1291
+			'clear description'
1292
+		);
1293
+		$registrations_to_apply_payment_to .= EEH_HTML::divx();
1294
+		$this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to;
1295
+	}
1296
+
1297
+
1298
+	/**
1299
+	 * _get_reg_status_selection
1300
+	 *
1301
+	 * @todo   this will need to be adjusted either once MER comes along OR we move default reg status to tickets
1302
+	 *         instead of events.
1303
+	 * @access protected
1304
+	 * @return void
1305
+	 * @throws EE_Error
1306
+	 */
1307
+	protected function _get_reg_status_selection()
1308
+	{
1309
+		// first get all possible statuses
1310
+		$statuses = EEM_Registration::reg_status_array(array(), true);
1311
+		// let's add a "don't change" option.
1312
+		$status_array['NAN'] = esc_html__('Leave the Same', 'event_espresso');
1313
+		$status_array = array_merge($status_array, $statuses);
1314
+		$this->_template_args['status_change_select'] = EEH_Form_Fields::select_input(
1315
+			'txn_reg_status_change[reg_status]',
1316
+			$status_array,
1317
+			'NAN',
1318
+			'id="txn-admin-payment-reg-status-inp"',
1319
+			'txn-reg-status-change-reg-status'
1320
+		);
1321
+		$this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input(
1322
+			'delete_txn_reg_status_change[reg_status]',
1323
+			$status_array,
1324
+			'NAN',
1325
+			'delete-txn-admin-payment-reg-status-inp',
1326
+			'delete-txn-reg-status-change-reg-status'
1327
+		);
1328
+	}
1329
+
1330
+
1331
+	/**
1332
+	 *    _get_payment_methods
1333
+	 * Gets all the payment methods available generally, or the ones that are already
1334
+	 * selected on these payments (in case their payment methods are no longer active).
1335
+	 * Has the side-effect of updating the template args' payment_methods item
1336
+	 *
1337
+	 * @access private
1338
+	 * @param EE_Payment[] to show on this page
1339
+	 * @return void
1340
+	 * @throws EE_Error
1341
+	 * @throws InvalidArgumentException
1342
+	 * @throws InvalidDataTypeException
1343
+	 * @throws InvalidInterfaceException
1344
+	 * @throws ReflectionException
1345
+	 */
1346
+	private function _get_payment_methods($payments = array())
1347
+	{
1348
+		$payment_methods_of_payments = array();
1349
+		foreach ($payments as $payment) {
1350
+			if ($payment instanceof EE_Payment) {
1351
+				$payment_methods_of_payments[] = $payment->get('PMD_ID');
1352
+			}
1353
+		}
1354
+		if ($payment_methods_of_payments) {
1355
+			$query_args = array(
1356
+				array(
1357
+					'OR*payment_method_for_payment' => array(
1358
+						'PMD_ID'    => array('IN', $payment_methods_of_payments),
1359
+						'PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'),
1360
+					),
1361
+				),
1362
+			);
1363
+		} else {
1364
+			$query_args = array(array('PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%')));
1365
+		}
1366
+		$this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1367
+	}
1368
+
1369
+
1370
+	/**
1371
+	 * txn_attendees_meta_box
1372
+	 *    generates HTML for the Attendees Transaction main meta box
1373
+	 *
1374
+	 * @access public
1375
+	 * @param WP_Post $post
1376
+	 * @param array   $metabox
1377
+	 * @return void
1378
+	 * @throws DomainException
1379
+	 * @throws EE_Error
1380
+	 */
1381
+	public function txn_attendees_meta_box($post, $metabox = array('args' => array()))
1382
+	{
1383
+
1384
+		/** @noinspection NonSecureExtractUsageInspection */
1385
+		extract($metabox['args']);
1386
+		$this->_template_args['post'] = $post;
1387
+		$this->_template_args['event_attendees'] = array();
1388
+		// process items in cart
1389
+		$line_items = $this->_transaction->get_many_related(
1390
+			'Line_Item',
1391
+			array(array('LIN_type' => 'line-item'))
1392
+		);
1393
+		if (! empty($line_items)) {
1394
+			foreach ($line_items as $item) {
1395
+				if ($item instanceof EE_Line_Item) {
1396
+					switch ($item->OBJ_type()) {
1397
+						case 'Event':
1398
+							break;
1399
+						case 'Ticket':
1400
+							$ticket = $item->ticket();
1401
+							// right now we're only handling tickets here.
1402
+							// Cause its expected that only tickets will have attendees right?
1403
+							if (! $ticket instanceof EE_Ticket) {
1404
+								continue;
1405
+							}
1406
+							try {
1407
+								$event_name = $ticket->get_event_name();
1408
+							} catch (Exception $e) {
1409
+								EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1410
+								$event_name = esc_html__('Unknown Event', 'event_espresso');
1411
+							}
1412
+							$event_name .= ' - ' . $item->get('LIN_name');
1413
+							$ticket_price = EEH_Template::format_currency($item->get('LIN_unit_price'));
1414
+							// now get all of the registrations for this transaction that use this ticket
1415
+							$registrations = $ticket->get_many_related(
1416
+								'Registration',
1417
+								array(array('TXN_ID' => $this->_transaction->ID()))
1418
+							);
1419
+							foreach ($registrations as $registration) {
1420
+								if (! $registration instanceof EE_Registration) {
1421
+									continue;
1422
+								}
1423
+								$this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID']
1424
+									= $registration->status_ID();
1425
+								$this->_template_args['event_attendees'][ $registration->ID() ]['att_num']
1426
+									= $registration->count();
1427
+								$this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name']
1428
+									= $event_name;
1429
+								$this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price']
1430
+									= $ticket_price;
1431
+								// attendee info
1432
+								$attendee = $registration->get_first_related('Attendee');
1433
+								if ($attendee instanceof EE_Attendee) {
1434
+									$this->_template_args['event_attendees'][ $registration->ID() ]['att_id']
1435
+										= $attendee->ID();
1436
+									$this->_template_args['event_attendees'][ $registration->ID() ]['attendee']
1437
+										= $attendee->full_name();
1438
+									$this->_template_args['event_attendees'][ $registration->ID() ]['email']
1439
+										= '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name
1440
+										  . esc_html__(
1441
+											  ' Event',
1442
+											  'event_espresso'
1443
+										  )
1444
+										  . '">' . $attendee->email() . '</a>';
1445
+									$this->_template_args['event_attendees'][ $registration->ID() ]['address']
1446
+										= EEH_Address::format($attendee, 'inline', false, false);
1447
+								} else {
1448
+									$this->_template_args['event_attendees'][ $registration->ID() ]['att_id'] = '';
1449
+									$this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = '';
1450
+									$this->_template_args['event_attendees'][ $registration->ID() ]['email'] = '';
1451
+									$this->_template_args['event_attendees'][ $registration->ID() ]['address'] = '';
1452
+								}
1453
+							}
1454
+							break;
1455
+					}
1456
+				}
1457
+			}
1458
+
1459
+			$this->_template_args['transaction_form_url'] = add_query_arg(
1460
+				array(
1461
+					'action'  => 'edit_transaction',
1462
+					'process' => 'attendees',
1463
+				),
1464
+				TXN_ADMIN_URL
1465
+			);
1466
+			echo EEH_Template::display_template(
1467
+				TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1468
+				$this->_template_args,
1469
+				true
1470
+			);
1471
+		} else {
1472
+			echo sprintf(
1473
+				esc_html__(
1474
+					'%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s',
1475
+					'event_espresso'
1476
+				),
1477
+				'<p class="important-notice">',
1478
+				'</p>'
1479
+			);
1480
+		}
1481
+	}
1482
+
1483
+
1484
+	/**
1485
+	 * txn_registrant_side_meta_box
1486
+	 * generates HTML for the Edit Transaction side meta box
1487
+	 *
1488
+	 * @access public
1489
+	 * @return void
1490
+	 * @throws DomainException
1491
+	 * @throws EE_Error
1492
+	 * @throws InvalidArgumentException
1493
+	 * @throws InvalidDataTypeException
1494
+	 * @throws InvalidInterfaceException
1495
+	 * @throws ReflectionException
1496
+	 */
1497
+	public function txn_registrant_side_meta_box()
1498
+	{
1499
+		$primary_att = $this->_transaction->primary_registration() instanceof EE_Registration
1500
+			? $this->_transaction->primary_registration()->get_first_related('Attendee')
1501
+			: null;
1502
+		if (! $primary_att instanceof EE_Attendee) {
1503
+			$this->_template_args['no_attendee_message'] = esc_html__(
1504
+				'There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1505
+				'event_espresso'
1506
+			);
1507
+			$primary_att = EEM_Attendee::instance()->create_default_object();
1508
+		}
1509
+		$this->_template_args['ATT_ID'] = $primary_att->ID();
1510
+		$this->_template_args['prime_reg_fname'] = $primary_att->fname();
1511
+		$this->_template_args['prime_reg_lname'] = $primary_att->lname();
1512
+		$this->_template_args['prime_reg_email'] = $primary_att->email();
1513
+		$this->_template_args['prime_reg_phone'] = $primary_att->phone();
1514
+		$this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce(
1515
+			array(
1516
+				'action' => 'edit_attendee',
1517
+				'post'   => $primary_att->ID(),
1518
+			),
1519
+			REG_ADMIN_URL
1520
+		);
1521
+		// get formatted address for registrant
1522
+		$this->_template_args['formatted_address'] = EEH_Address::format($primary_att);
1523
+		echo EEH_Template::display_template(
1524
+			TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1525
+			$this->_template_args,
1526
+			true
1527
+		);
1528
+	}
1529
+
1530
+
1531
+	/**
1532
+	 * txn_billing_info_side_meta_box
1533
+	 *    generates HTML for the Edit Transaction side meta box
1534
+	 *
1535
+	 * @access public
1536
+	 * @return void
1537
+	 * @throws DomainException
1538
+	 * @throws EE_Error
1539
+	 */
1540
+	public function txn_billing_info_side_meta_box()
1541
+	{
1542
+
1543
+		$this->_template_args['billing_form'] = $this->_transaction->billing_info();
1544
+		$this->_template_args['billing_form_url'] = add_query_arg(
1545
+			array('action' => 'edit_transaction', 'process' => 'billing'),
1546
+			TXN_ADMIN_URL
1547
+		);
1548
+
1549
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1550
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);/**/
1551
+	}
1552
+
1553
+
1554
+	/**
1555
+	 * apply_payments_or_refunds
1556
+	 *    registers a payment or refund made towards a transaction
1557
+	 *
1558
+	 * @access public
1559
+	 * @return void
1560
+	 * @throws EE_Error
1561
+	 * @throws InvalidArgumentException
1562
+	 * @throws ReflectionException
1563
+	 * @throws RuntimeException
1564
+	 * @throws InvalidDataTypeException
1565
+	 * @throws InvalidInterfaceException
1566
+	 */
1567
+	public function apply_payments_or_refunds()
1568
+	{
1569
+		$json_response_data = array('return_data' => false);
1570
+		$valid_data = $this->_validate_payment_request_data();
1571
+		$has_access = EE_Registry::instance()->CAP->current_user_can(
1572
+			'ee_edit_payments',
1573
+			'apply_payment_or_refund_from_registration_details'
1574
+		);
1575
+		if (! empty($valid_data) && $has_access) {
1576
+			$PAY_ID = $valid_data['PAY_ID'];
1577
+			// save  the new payment
1578
+			$payment = $this->_create_payment_from_request_data($valid_data);
1579
+			// get the TXN for this payment
1580
+			$transaction = $payment->transaction();
1581
+			// verify transaction
1582
+			if ($transaction instanceof EE_Transaction) {
1583
+				// calculate_total_payments_and_update_status
1584
+				$this->_process_transaction_payments($transaction);
1585
+				$REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1586
+				$this->_remove_existing_registration_payments($payment, $PAY_ID);
1587
+				// apply payment to registrations (if applicable)
1588
+				if (! empty($REG_IDs)) {
1589
+					$this->_update_registration_payments($transaction, $payment, $REG_IDs);
1590
+					$this->_maybe_send_notifications();
1591
+					// now process status changes for the same registrations
1592
+					$this->_process_registration_status_change($transaction, $REG_IDs);
1593
+				}
1594
+				$this->_maybe_send_notifications($payment);
1595
+				// prepare to render page
1596
+				$json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs);
1597
+				do_action(
1598
+					'AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording',
1599
+					$transaction,
1600
+					$payment
1601
+				);
1602
+			} else {
1603
+				EE_Error::add_error(
1604
+					esc_html__(
1605
+						'A valid Transaction for this payment could not be retrieved.',
1606
+						'event_espresso'
1607
+					),
1608
+					__FILE__,
1609
+					__FUNCTION__,
1610
+					__LINE__
1611
+				);
1612
+			}
1613
+		} else {
1614
+			if ($has_access) {
1615
+				EE_Error::add_error(
1616
+					esc_html__(
1617
+						'The payment form data could not be processed. Please try again.',
1618
+						'event_espresso'
1619
+					),
1620
+					__FILE__,
1621
+					__FUNCTION__,
1622
+					__LINE__
1623
+				);
1624
+			} else {
1625
+				EE_Error::add_error(
1626
+					esc_html__(
1627
+						'You do not have access to apply payments or refunds to a registration.',
1628
+						'event_espresso'
1629
+					),
1630
+					__FILE__,
1631
+					__FUNCTION__,
1632
+					__LINE__
1633
+				);
1634
+			}
1635
+		}
1636
+		$notices = EE_Error::get_notices(
1637
+			false,
1638
+			false,
1639
+			false
1640
+		);
1641
+		$this->_template_args = array(
1642
+			'data'    => $json_response_data,
1643
+			'error'   => $notices['errors'],
1644
+			'success' => $notices['success'],
1645
+		);
1646
+		$this->_return_json();
1647
+	}
1648
+
1649
+
1650
+	/**
1651
+	 * _validate_payment_request_data
1652
+	 *
1653
+	 * @return array
1654
+	 * @throws EE_Error
1655
+	 */
1656
+	protected function _validate_payment_request_data()
1657
+	{
1658
+		if (! isset($this->_req_data['txn_admin_payment'])) {
1659
+			return false;
1660
+		}
1661
+		$payment_form = $this->_generate_payment_form_section();
1662
+		try {
1663
+			if ($payment_form->was_submitted()) {
1664
+				$payment_form->receive_form_submission();
1665
+				if (! $payment_form->is_valid()) {
1666
+					$submission_error_messages = array();
1667
+					foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1668
+						if ($validation_error instanceof EE_Validation_Error) {
1669
+							$submission_error_messages[] = sprintf(
1670
+								_x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'),
1671
+								$validation_error->get_form_section()->html_label_text(),
1672
+								$validation_error->getMessage()
1673
+							);
1674
+						}
1675
+					}
1676
+					EE_Error::add_error(
1677
+						implode('<br />', $submission_error_messages),
1678
+						__FILE__,
1679
+						__FUNCTION__,
1680
+						__LINE__
1681
+					);
1682
+
1683
+					return array();
1684
+				}
1685
+			}
1686
+		} catch (EE_Error $e) {
1687
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1688
+
1689
+			return array();
1690
+		}
1691
+
1692
+		return $payment_form->valid_data();
1693
+	}
1694
+
1695
+
1696
+	/**
1697
+	 * _generate_payment_form_section
1698
+	 *
1699
+	 * @return EE_Form_Section_Proper
1700
+	 * @throws EE_Error
1701
+	 */
1702
+	protected function _generate_payment_form_section()
1703
+	{
1704
+		return new EE_Form_Section_Proper(
1705
+			array(
1706
+				'name'        => 'txn_admin_payment',
1707
+				'subsections' => array(
1708
+					'PAY_ID'          => new EE_Text_Input(
1709
+						array(
1710
+							'default'               => 0,
1711
+							'required'              => false,
1712
+							'html_label_text'       => esc_html__('Payment ID', 'event_espresso'),
1713
+							'validation_strategies' => array(new EE_Int_Normalization()),
1714
+						)
1715
+					),
1716
+					'TXN_ID'          => new EE_Text_Input(
1717
+						array(
1718
+							'default'               => 0,
1719
+							'required'              => true,
1720
+							'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'),
1721
+							'validation_strategies' => array(new EE_Int_Normalization()),
1722
+						)
1723
+					),
1724
+					'type'            => new EE_Text_Input(
1725
+						array(
1726
+							'default'               => 1,
1727
+							'required'              => true,
1728
+							'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'),
1729
+							'validation_strategies' => array(new EE_Int_Normalization()),
1730
+						)
1731
+					),
1732
+					'amount'          => new EE_Text_Input(
1733
+						array(
1734
+							'default'               => 0,
1735
+							'required'              => true,
1736
+							'html_label_text'       => esc_html__('Payment amount', 'event_espresso'),
1737
+							'validation_strategies' => array(new EE_Float_Normalization()),
1738
+						)
1739
+					),
1740
+					'status'          => new EE_Text_Input(
1741
+						array(
1742
+							'default'         => EEM_Payment::status_id_approved,
1743
+							'required'        => true,
1744
+							'html_label_text' => esc_html__('Payment status', 'event_espresso'),
1745
+						)
1746
+					),
1747
+					'PMD_ID'          => new EE_Text_Input(
1748
+						array(
1749
+							'default'               => 2,
1750
+							'required'              => true,
1751
+							'html_label_text'       => esc_html__('Payment Method', 'event_espresso'),
1752
+							'validation_strategies' => array(new EE_Int_Normalization()),
1753
+						)
1754
+					),
1755
+					'date'            => new EE_Text_Input(
1756
+						array(
1757
+							'default'         => time(),
1758
+							'required'        => true,
1759
+							'html_label_text' => esc_html__('Payment date', 'event_espresso'),
1760
+						)
1761
+					),
1762
+					'txn_id_chq_nmbr' => new EE_Text_Input(
1763
+						array(
1764
+							'default'               => '',
1765
+							'required'              => false,
1766
+							'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'),
1767
+							'validation_strategies' => array(
1768
+								new EE_Max_Length_Validation_Strategy(
1769
+									esc_html__('Input too long', 'event_espresso'),
1770
+									100
1771
+								),
1772
+							),
1773
+						)
1774
+					),
1775
+					'po_number'       => new EE_Text_Input(
1776
+						array(
1777
+							'default'               => '',
1778
+							'required'              => false,
1779
+							'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'),
1780
+							'validation_strategies' => array(
1781
+								new EE_Max_Length_Validation_Strategy(
1782
+									esc_html__('Input too long', 'event_espresso'),
1783
+									100
1784
+								),
1785
+							),
1786
+						)
1787
+					),
1788
+					'accounting'      => new EE_Text_Input(
1789
+						array(
1790
+							'default'               => '',
1791
+							'required'              => false,
1792
+							'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'),
1793
+							'validation_strategies' => array(
1794
+								new EE_Max_Length_Validation_Strategy(
1795
+									esc_html__('Input too long', 'event_espresso'),
1796
+									100
1797
+								),
1798
+							),
1799
+						)
1800
+					),
1801
+				),
1802
+			)
1803
+		);
1804
+	}
1805
+
1806
+
1807
+	/**
1808
+	 * _create_payment_from_request_data
1809
+	 *
1810
+	 * @param array $valid_data
1811
+	 * @return EE_Payment
1812
+	 * @throws EE_Error
1813
+	 */
1814
+	protected function _create_payment_from_request_data($valid_data)
1815
+	{
1816
+		$PAY_ID = $valid_data['PAY_ID'];
1817
+		// get payment amount
1818
+		$amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0;
1819
+		// payments have a type value of 1 and refunds have a type value of -1
1820
+		// so multiplying amount by type will give a positive value for payments, and negative values for refunds
1821
+		$amount = $valid_data['type'] < 0 ? $amount * -1 : $amount;
1822
+		// for some reason the date string coming in has extra spaces between the date and time.  This fixes that.
1823
+		$date = $valid_data['date']
1824
+			? preg_replace('/\s+/', ' ', $valid_data['date'])
1825
+			: date('Y-m-d g:i a', current_time('timestamp'));
1826
+		$payment = EE_Payment::new_instance(
1827
+			array(
1828
+				'TXN_ID'              => $valid_data['TXN_ID'],
1829
+				'STS_ID'              => $valid_data['status'],
1830
+				'PAY_timestamp'       => $date,
1831
+				'PAY_source'          => EEM_Payment_Method::scope_admin,
1832
+				'PMD_ID'              => $valid_data['PMD_ID'],
1833
+				'PAY_amount'          => $amount,
1834
+				'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'],
1835
+				'PAY_po_number'       => $valid_data['po_number'],
1836
+				'PAY_extra_accntng'   => $valid_data['accounting'],
1837
+				'PAY_details'         => $valid_data,
1838
+				'PAY_ID'              => $PAY_ID,
1839
+			),
1840
+			'',
1841
+			array('Y-m-d', 'g:i a')
1842
+		);
1843
+
1844
+		if (! $payment->save()) {
1845
+			EE_Error::add_error(
1846
+				sprintf(
1847
+					esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
1848
+					$payment->ID()
1849
+				),
1850
+				__FILE__,
1851
+				__FUNCTION__,
1852
+				__LINE__
1853
+			);
1854
+		}
1855
+
1856
+		return $payment;
1857
+	}
1858
+
1859
+
1860
+	/**
1861
+	 * _process_transaction_payments
1862
+	 *
1863
+	 * @param \EE_Transaction $transaction
1864
+	 * @return void
1865
+	 * @throws EE_Error
1866
+	 * @throws InvalidArgumentException
1867
+	 * @throws ReflectionException
1868
+	 * @throws InvalidDataTypeException
1869
+	 * @throws InvalidInterfaceException
1870
+	 */
1871
+	protected function _process_transaction_payments(EE_Transaction $transaction)
1872
+	{
1873
+		/** @type EE_Transaction_Payments $transaction_payments */
1874
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1875
+		// update the transaction with this payment
1876
+		if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) {
1877
+			EE_Error::add_success(
1878
+				esc_html__(
1879
+					'The payment has been processed successfully.',
1880
+					'event_espresso'
1881
+				),
1882
+				__FILE__,
1883
+				__FUNCTION__,
1884
+				__LINE__
1885
+			);
1886
+		} else {
1887
+			EE_Error::add_error(
1888
+				esc_html__(
1889
+					'The payment was processed successfully but the amount paid for the transaction was not updated.',
1890
+					'event_espresso'
1891
+				),
1892
+				__FILE__,
1893
+				__FUNCTION__,
1894
+				__LINE__
1895
+			);
1896
+		}
1897
+	}
1898
+
1899
+
1900
+	/**
1901
+	 * _get_REG_IDs_to_apply_payment_to
1902
+	 * returns a list of registration IDs that the payment will apply to
1903
+	 *
1904
+	 * @param \EE_Payment $payment
1905
+	 * @return array
1906
+	 * @throws EE_Error
1907
+	 */
1908
+	protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment)
1909
+	{
1910
+		$REG_IDs = array();
1911
+		// grab array of IDs for specific registrations to apply changes to
1912
+		if (isset($this->_req_data['txn_admin_payment']['registrations'])) {
1913
+			$REG_IDs = (array) $this->_req_data['txn_admin_payment']['registrations'];
1914
+		}
1915
+		// nothing specified ? then get all reg IDs
1916
+		if (empty($REG_IDs)) {
1917
+			$registrations = $payment->transaction()->registrations();
1918
+			$REG_IDs = ! empty($registrations)
1919
+				? array_keys($registrations)
1920
+				: $this->_get_existing_reg_payment_REG_IDs($payment);
1921
+		}
1922
+
1923
+		// ensure that REG_IDs are integers and NOT strings
1924
+		return array_map('intval', $REG_IDs);
1925
+	}
1926
+
1927
+
1928
+	/**
1929
+	 * @return array
1930
+	 */
1931
+	public function existing_reg_payment_REG_IDs()
1932
+	{
1933
+		return $this->_existing_reg_payment_REG_IDs;
1934
+	}
1935
+
1936
+
1937
+	/**
1938
+	 * @param array $existing_reg_payment_REG_IDs
1939
+	 */
1940
+	public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null)
1941
+	{
1942
+		$this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs;
1943
+	}
1944
+
1945
+
1946
+	/**
1947
+	 * _get_existing_reg_payment_REG_IDs
1948
+	 * returns a list of registration IDs that the payment is currently related to
1949
+	 * as recorded in the database
1950
+	 *
1951
+	 * @param \EE_Payment $payment
1952
+	 * @return array
1953
+	 * @throws EE_Error
1954
+	 */
1955
+	protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment)
1956
+	{
1957
+		if ($this->existing_reg_payment_REG_IDs() === null) {
1958
+			// let's get any existing reg payment records for this payment
1959
+			$existing_reg_payment_REG_IDs = $payment->get_many_related('Registration');
1960
+			// but we only want the REG IDs, so grab the array keys
1961
+			$existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs)
1962
+				? array_keys($existing_reg_payment_REG_IDs)
1963
+				: array();
1964
+			$this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs);
1965
+		}
1966
+
1967
+		return $this->existing_reg_payment_REG_IDs();
1968
+	}
1969
+
1970
+
1971
+	/**
1972
+	 * _remove_existing_registration_payments
1973
+	 * this calculates the difference between existing relations
1974
+	 * to the supplied payment and the new list registration IDs,
1975
+	 * removes any related registrations that no longer apply,
1976
+	 * and then updates the registration paid fields
1977
+	 *
1978
+	 * @param \EE_Payment $payment
1979
+	 * @param int         $PAY_ID
1980
+	 * @return bool;
1981
+	 * @throws EE_Error
1982
+	 * @throws InvalidArgumentException
1983
+	 * @throws ReflectionException
1984
+	 * @throws InvalidDataTypeException
1985
+	 * @throws InvalidInterfaceException
1986
+	 */
1987
+	protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0)
1988
+	{
1989
+		// newly created payments will have nothing recorded for $PAY_ID
1990
+		if ($PAY_ID == 0) {
1991
+			return false;
1992
+		}
1993
+		$existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
1994
+		if (empty($existing_reg_payment_REG_IDs)) {
1995
+			return false;
1996
+		}
1997
+		/** @type EE_Transaction_Payments $transaction_payments */
1998
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1999
+
2000
+		return $transaction_payments->delete_registration_payments_and_update_registrations(
2001
+			$payment,
2002
+			array(
2003
+				array(
2004
+					'PAY_ID' => $payment->ID(),
2005
+					'REG_ID' => array('IN', $existing_reg_payment_REG_IDs),
2006
+				),
2007
+			)
2008
+		);
2009
+	}
2010
+
2011
+
2012
+	/**
2013
+	 * _update_registration_payments
2014
+	 * this applies the payments to the selected registrations
2015
+	 * but only if they have not already been paid for
2016
+	 *
2017
+	 * @param  EE_Transaction $transaction
2018
+	 * @param \EE_Payment     $payment
2019
+	 * @param array           $REG_IDs
2020
+	 * @return void
2021
+	 * @throws EE_Error
2022
+	 * @throws InvalidArgumentException
2023
+	 * @throws ReflectionException
2024
+	 * @throws RuntimeException
2025
+	 * @throws InvalidDataTypeException
2026
+	 * @throws InvalidInterfaceException
2027
+	 */
2028
+	protected function _update_registration_payments(
2029
+		EE_Transaction $transaction,
2030
+		EE_Payment $payment,
2031
+		$REG_IDs = array()
2032
+	) {
2033
+		// we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments()
2034
+		// so let's do that using our set of REG_IDs from the form
2035
+		$registration_query_where_params = array(
2036
+			'REG_ID' => array('IN', $REG_IDs),
2037
+		);
2038
+		// but add in some conditions regarding payment,
2039
+		// so that we don't apply payments to registrations that are free or have already been paid for
2040
+		// but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
2041
+		if (! $payment->is_a_refund()) {
2042
+			$registration_query_where_params['REG_final_price'] = array('!=', 0);
2043
+			$registration_query_where_params['REG_final_price*'] = array('!=', 'REG_paid', true);
2044
+		}
2045
+		$registrations = $transaction->registrations(array($registration_query_where_params));
2046
+		if (! empty($registrations)) {
2047
+			/** @type EE_Payment_Processor $payment_processor */
2048
+			$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2049
+			$payment_processor->process_registration_payments($transaction, $payment, $registrations);
2050
+		}
2051
+	}
2052
+
2053
+
2054
+	/**
2055
+	 * _process_registration_status_change
2056
+	 * This processes requested registration status changes for all the registrations
2057
+	 * on a given transaction and (optionally) sends out notifications for the changes.
2058
+	 *
2059
+	 * @param  EE_Transaction $transaction
2060
+	 * @param array           $REG_IDs
2061
+	 * @return bool
2062
+	 * @throws EE_Error
2063
+	 * @throws InvalidArgumentException
2064
+	 * @throws ReflectionException
2065
+	 * @throws InvalidDataTypeException
2066
+	 * @throws InvalidInterfaceException
2067
+	 */
2068
+	protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = array())
2069
+	{
2070
+		// first if there is no change in status then we get out.
2071
+		if (! isset($this->_req_data['txn_reg_status_change']['reg_status'])
2072
+			|| $this->_req_data['txn_reg_status_change']['reg_status'] === 'NAN'
2073
+		) {
2074
+			// no error message, no change requested, just nothing to do man.
2075
+			return false;
2076
+		}
2077
+		/** @type EE_Transaction_Processor $transaction_processor */
2078
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
2079
+
2080
+		// made it here dude?  Oh WOW.  K, let's take care of changing the statuses
2081
+		return $transaction_processor->manually_update_registration_statuses(
2082
+			$transaction,
2083
+			sanitize_text_field($this->_req_data['txn_reg_status_change']['reg_status']),
2084
+			array(array('REG_ID' => array('IN', $REG_IDs)))
2085
+		);
2086
+	}
2087
+
2088
+
2089
+	/**
2090
+	 * _build_payment_json_response
2091
+	 *
2092
+	 * @access public
2093
+	 * @param \EE_Payment $payment
2094
+	 * @param array       $REG_IDs
2095
+	 * @param bool | null $delete_txn_reg_status_change
2096
+	 * @return array
2097
+	 * @throws EE_Error
2098
+	 * @throws InvalidArgumentException
2099
+	 * @throws InvalidDataTypeException
2100
+	 * @throws InvalidInterfaceException
2101
+	 * @throws ReflectionException
2102
+	 */
2103
+	protected function _build_payment_json_response(
2104
+		EE_Payment $payment,
2105
+		$REG_IDs = array(),
2106
+		$delete_txn_reg_status_change = null
2107
+	) {
2108
+		// was the payment deleted ?
2109
+		if (is_bool($delete_txn_reg_status_change)) {
2110
+			return array(
2111
+				'PAY_ID'                       => $payment->ID(),
2112
+				'amount'                       => $payment->amount(),
2113
+				'total_paid'                   => $payment->transaction()->paid(),
2114
+				'txn_status'                   => $payment->transaction()->status_ID(),
2115
+				'pay_status'                   => $payment->STS_ID(),
2116
+				'registrations'                => $this->_registration_payment_data_array($REG_IDs),
2117
+				'delete_txn_reg_status_change' => $delete_txn_reg_status_change,
2118
+			);
2119
+		} else {
2120
+			$this->_get_payment_status_array();
2121
+
2122
+			return array(
2123
+				'amount'           => $payment->amount(),
2124
+				'total_paid'       => $payment->transaction()->paid(),
2125
+				'txn_status'       => $payment->transaction()->status_ID(),
2126
+				'pay_status'       => $payment->STS_ID(),
2127
+				'PAY_ID'           => $payment->ID(),
2128
+				'STS_ID'           => $payment->STS_ID(),
2129
+				'status'           => self::$_pay_status[ $payment->STS_ID() ],
2130
+				'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
2131
+				'method'           => strtoupper($payment->source()),
2132
+				'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
2133
+				'gateway'          => $payment->payment_method()
2134
+					? $payment->payment_method()->admin_name()
2135
+					: esc_html__("Unknown", 'event_espresso'),
2136
+				'gateway_response' => $payment->gateway_response(),
2137
+				'txn_id_chq_nmbr'  => $payment->txn_id_chq_nmbr(),
2138
+				'po_number'        => $payment->po_number(),
2139
+				'extra_accntng'    => $payment->extra_accntng(),
2140
+				'registrations'    => $this->_registration_payment_data_array($REG_IDs),
2141
+			);
2142
+		}
2143
+	}
2144
+
2145
+
2146
+	/**
2147
+	 * delete_payment
2148
+	 *    delete a payment or refund made towards a transaction
2149
+	 *
2150
+	 * @access public
2151
+	 * @return void
2152
+	 * @throws EE_Error
2153
+	 * @throws InvalidArgumentException
2154
+	 * @throws ReflectionException
2155
+	 * @throws InvalidDataTypeException
2156
+	 * @throws InvalidInterfaceException
2157
+	 */
2158
+	public function delete_payment()
2159
+	{
2160
+		$json_response_data = array('return_data' => false);
2161
+		$PAY_ID = isset($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2162
+			? absint($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2163
+			: 0;
2164
+		$can_delete = EE_Registry::instance()->CAP->current_user_can(
2165
+			'ee_delete_payments',
2166
+			'delete_payment_from_registration_details'
2167
+		);
2168
+		if ($PAY_ID && $can_delete) {
2169
+			$delete_txn_reg_status_change = isset($this->_req_data['delete_txn_reg_status_change'])
2170
+				? $this->_req_data['delete_txn_reg_status_change']
2171
+				: false;
2172
+			$payment = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
2173
+			if ($payment instanceof EE_Payment) {
2174
+				$REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2175
+				/** @type EE_Transaction_Payments $transaction_payments */
2176
+				$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2177
+				if ($transaction_payments->delete_payment_and_update_transaction($payment)) {
2178
+					$json_response_data['return_data'] = $this->_build_payment_json_response(
2179
+						$payment,
2180
+						$REG_IDs,
2181
+						$delete_txn_reg_status_change
2182
+					);
2183
+					if ($delete_txn_reg_status_change) {
2184
+						$this->_req_data['txn_reg_status_change'] = $delete_txn_reg_status_change;
2185
+						// MAKE sure we also add the delete_txn_req_status_change to the
2186
+						// $_REQUEST global because that's how messages will be looking for it.
2187
+						$_REQUEST['txn_reg_status_change'] = $delete_txn_reg_status_change;
2188
+						$this->_maybe_send_notifications();
2189
+						$this->_process_registration_status_change($payment->transaction(), $REG_IDs);
2190
+					}
2191
+				}
2192
+			} else {
2193
+				EE_Error::add_error(
2194
+					esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'),
2195
+					__FILE__,
2196
+					__FUNCTION__,
2197
+					__LINE__
2198
+				);
2199
+			}
2200
+		} else {
2201
+			if ($can_delete) {
2202
+				EE_Error::add_error(
2203
+					esc_html__(
2204
+						'A valid Payment ID was not received, therefore payment form data could not be loaded.',
2205
+						'event_espresso'
2206
+					),
2207
+					__FILE__,
2208
+					__FUNCTION__,
2209
+					__LINE__
2210
+				);
2211
+			} else {
2212
+				EE_Error::add_error(
2213
+					esc_html__(
2214
+						'You do not have access to delete a payment.',
2215
+						'event_espresso'
2216
+					),
2217
+					__FILE__,
2218
+					__FUNCTION__,
2219
+					__LINE__
2220
+				);
2221
+			}
2222
+		}
2223
+		$notices = EE_Error::get_notices(false, false, false);
2224
+		$this->_template_args = array(
2225
+			'data'      => $json_response_data,
2226
+			'success'   => $notices['success'],
2227
+			'error'     => $notices['errors'],
2228
+			'attention' => $notices['attention'],
2229
+		);
2230
+		$this->_return_json();
2231
+	}
2232
+
2233
+
2234
+	/**
2235
+	 * _registration_payment_data_array
2236
+	 * adds info for 'owing' and 'paid' for each registration to the json response
2237
+	 *
2238
+	 * @access protected
2239
+	 * @param array $REG_IDs
2240
+	 * @return array
2241
+	 * @throws EE_Error
2242
+	 * @throws InvalidArgumentException
2243
+	 * @throws InvalidDataTypeException
2244
+	 * @throws InvalidInterfaceException
2245
+	 * @throws ReflectionException
2246
+	 */
2247
+	protected function _registration_payment_data_array($REG_IDs)
2248
+	{
2249
+		$registration_payment_data = array();
2250
+		// if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
2251
+		if (! empty($REG_IDs)) {
2252
+			$registrations = EEM_Registration::instance()->get_all(array(array('REG_ID' => array('IN', $REG_IDs))));
2253
+			foreach ($registrations as $registration) {
2254
+				if ($registration instanceof EE_Registration) {
2255
+					$registration_payment_data[ $registration->ID() ] = array(
2256
+						'paid'  => $registration->pretty_paid(),
2257
+						'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
2258
+					);
2259
+				}
2260
+			}
2261
+		}
2262
+
2263
+		return $registration_payment_data;
2264
+	}
2265
+
2266
+
2267
+	/**
2268
+	 * _maybe_send_notifications
2269
+	 * determines whether or not the admin has indicated that notifications should be sent.
2270
+	 * If so, will toggle a filter switch for delivering registration notices.
2271
+	 * If passed an EE_Payment object, then it will trigger payment notifications instead.
2272
+	 *
2273
+	 * @access protected
2274
+	 * @param \EE_Payment | null $payment
2275
+	 */
2276
+	protected function _maybe_send_notifications($payment = null)
2277
+	{
2278
+		switch ($payment instanceof EE_Payment) {
2279
+			// payment notifications
2280
+			case true:
2281
+				if (isset(
2282
+					$this->_req_data['txn_payments'],
2283
+					$this->_req_data['txn_payments']['send_notifications']
2284
+				)
2285
+					&& filter_var($this->_req_data['txn_payments']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
2286
+				) {
2287
+					$this->_process_payment_notification($payment);
2288
+				}
2289
+				break;
2290
+			// registration notifications
2291
+			case false:
2292
+				if (isset(
2293
+					$this->_req_data['txn_reg_status_change'],
2294
+					$this->_req_data['txn_reg_status_change']['send_notifications']
2295
+				)
2296
+					&& filter_var($this->_req_data['txn_reg_status_change']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
2297
+				) {
2298
+					add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
2299
+				}
2300
+				break;
2301
+		}
2302
+	}
2303
+
2304
+
2305
+	/**
2306
+	 * _send_payment_reminder
2307
+	 *    generates HTML for the View Transaction Details Admin page
2308
+	 *
2309
+	 * @access protected
2310
+	 * @return void
2311
+	 * @throws EE_Error
2312
+	 * @throws InvalidArgumentException
2313
+	 * @throws InvalidDataTypeException
2314
+	 * @throws InvalidInterfaceException
2315
+	 */
2316
+	protected function _send_payment_reminder()
2317
+	{
2318
+		$TXN_ID = ! empty($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : false;
2319
+		$transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2320
+		$query_args = isset($this->_req_data['redirect_to']) ? array(
2321
+			'action' => $this->_req_data['redirect_to'],
2322
+			'TXN_ID' => $this->_req_data['TXN_ID'],
2323
+		) : array();
2324
+		do_action(
2325
+			'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
2326
+			$transaction
2327
+		);
2328
+		$this->_redirect_after_action(
2329
+			false,
2330
+			esc_html__('payment reminder', 'event_espresso'),
2331
+			esc_html__('sent', 'event_espresso'),
2332
+			$query_args,
2333
+			true
2334
+		);
2335
+	}
2336
+
2337
+
2338
+	/**
2339
+	 *  get_transactions
2340
+	 *    get transactions for given parameters (used by list table)
2341
+	 *
2342
+	 * @param  int     $perpage how many transactions displayed per page
2343
+	 * @param  boolean $count   return the count or objects
2344
+	 * @param string   $view
2345
+	 * @return mixed int = count || array of transaction objects
2346
+	 * @throws EE_Error
2347
+	 * @throws InvalidArgumentException
2348
+	 * @throws InvalidDataTypeException
2349
+	 * @throws InvalidInterfaceException
2350
+	 */
2351
+	public function get_transactions($perpage, $count = false, $view = '')
2352
+	{
2353
+
2354
+		$TXN = EEM_Transaction::instance();
2355
+
2356
+		$start_date = isset($this->_req_data['txn-filter-start-date'])
2357
+			? wp_strip_all_tags($this->_req_data['txn-filter-start-date'])
2358
+			: date(
2359
+				'm/d/Y',
2360
+				strtotime('-10 year')
2361
+			);
2362
+		$end_date = isset($this->_req_data['txn-filter-end-date'])
2363
+			? wp_strip_all_tags($this->_req_data['txn-filter-end-date'])
2364
+			: date('m/d/Y');
2365
+
2366
+		// make sure our timestamps start and end right at the boundaries for each day
2367
+		$start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
2368
+		$end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
2369
+
2370
+
2371
+		// convert to timestamps
2372
+		$start_date = strtotime($start_date);
2373
+		$end_date = strtotime($end_date);
2374
+
2375
+		// makes sure start date is the lowest value and vice versa
2376
+		$start_date = min($start_date, $end_date);
2377
+		$end_date = max($start_date, $end_date);
2378
+
2379
+		// convert to correct format for query
2380
+		$start_date = EEM_Transaction::instance()->convert_datetime_for_query(
2381
+			'TXN_timestamp',
2382
+			date('Y-m-d H:i:s', $start_date),
2383
+			'Y-m-d H:i:s'
2384
+		);
2385
+		$end_date = EEM_Transaction::instance()->convert_datetime_for_query(
2386
+			'TXN_timestamp',
2387
+			date('Y-m-d H:i:s', $end_date),
2388
+			'Y-m-d H:i:s'
2389
+		);
2390
+
2391
+
2392
+		// set orderby
2393
+		$this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2394
+
2395
+		switch ($this->_req_data['orderby']) {
2396
+			case 'TXN_ID':
2397
+				$orderby = 'TXN_ID';
2398
+				break;
2399
+			case 'ATT_fname':
2400
+				$orderby = 'Registration.Attendee.ATT_fname';
2401
+				break;
2402
+			case 'event_name':
2403
+				$orderby = 'Registration.Event.EVT_name';
2404
+				break;
2405
+			default: // 'TXN_timestamp'
2406
+				$orderby = 'TXN_timestamp';
2407
+		}
2408
+
2409
+		$sort = ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'DESC';
2410
+		$current_page = ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
2411
+		$per_page = ! empty($perpage) ? $perpage : 10;
2412
+		$per_page = ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $per_page;
2413
+
2414
+		$offset = ($current_page - 1) * $per_page;
2415
+		$limit = array($offset, $per_page);
2416
+
2417
+		$_where = array(
2418
+			'TXN_timestamp'          => array('BETWEEN', array($start_date, $end_date)),
2419
+			'Registration.REG_count' => 1,
2420
+		);
2421
+
2422
+		if (isset($this->_req_data['EVT_ID'])) {
2423
+			$_where['Registration.EVT_ID'] = $this->_req_data['EVT_ID'];
2424
+		}
2425
+
2426
+		if (isset($this->_req_data['s'])) {
2427
+			$search_string = '%' . $this->_req_data['s'] . '%';
2428
+			$_where['OR'] = array(
2429
+				'Registration.Event.EVT_name'         => array('LIKE', $search_string),
2430
+				'Registration.Event.EVT_desc'         => array('LIKE', $search_string),
2431
+				'Registration.Event.EVT_short_desc'   => array('LIKE', $search_string),
2432
+				'Registration.Attendee.ATT_full_name' => array('LIKE', $search_string),
2433
+				'Registration.Attendee.ATT_fname'     => array('LIKE', $search_string),
2434
+				'Registration.Attendee.ATT_lname'     => array('LIKE', $search_string),
2435
+				'Registration.Attendee.ATT_short_bio' => array('LIKE', $search_string),
2436
+				'Registration.Attendee.ATT_email'     => array('LIKE', $search_string),
2437
+				'Registration.Attendee.ATT_address'   => array('LIKE', $search_string),
2438
+				'Registration.Attendee.ATT_address2'  => array('LIKE', $search_string),
2439
+				'Registration.Attendee.ATT_city'      => array('LIKE', $search_string),
2440
+				'Registration.REG_final_price'        => array('LIKE', $search_string),
2441
+				'Registration.REG_code'               => array('LIKE', $search_string),
2442
+				'Registration.REG_count'              => array('LIKE', $search_string),
2443
+				'Registration.REG_group_size'         => array('LIKE', $search_string),
2444
+				'Registration.Ticket.TKT_name'        => array('LIKE', $search_string),
2445
+				'Registration.Ticket.TKT_description' => array('LIKE', $search_string),
2446
+				'Payment.PAY_source'                  => array('LIKE', $search_string),
2447
+				'Payment.Payment_Method.PMD_name'     => array('LIKE', $search_string),
2448
+				'TXN_session_data'                    => array('LIKE', $search_string),
2449
+				'Payment.PAY_txn_id_chq_nmbr'         => array('LIKE', $search_string),
2450
+			);
2451
+		}
2452
+
2453
+		// failed transactions
2454
+		$failed = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count)
2455
+				  || ($count && $view === 'failed');
2456
+		$abandoned = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count)
2457
+					 || ($count && $view === 'abandoned');
2458
+
2459
+		if ($failed) {
2460
+			$_where['STS_ID'] = EEM_Transaction::failed_status_code;
2461
+		} elseif ($abandoned) {
2462
+			$_where['STS_ID'] = EEM_Transaction::abandoned_status_code;
2463
+		} else {
2464
+			$_where['STS_ID'] = array('!=', EEM_Transaction::failed_status_code);
2465
+			$_where['STS_ID*'] = array('!=', EEM_Transaction::abandoned_status_code);
2466
+		}
2467
+
2468
+		$query_params = array(
2469
+			$_where,
2470
+			'order_by'                 => array($orderby => $sort),
2471
+			'limit'                    => $limit,
2472
+			'default_where_conditions' => EEM_Base::default_where_conditions_this_only,
2473
+		);
2474
+
2475
+		$transactions = $count
2476
+			? $TXN->count(array($_where), 'TXN_ID', true)
2477
+			: $TXN->get_all($query_params);
2478
+
2479
+		return $transactions;
2480
+	}
2481 2481
 }
Please login to merge, or discard this patch.
Spacing   +83 added lines, -83 removed lines patch added patch discarded remove patch
@@ -363,7 +363,7 @@  discard block
 block discarded – undo
363 363
         // enqueue style
364 364
         wp_register_style(
365 365
             'espresso_txn',
366
-            TXN_ASSETS_URL . 'espresso_transactions_admin.css',
366
+            TXN_ASSETS_URL.'espresso_transactions_admin.css',
367 367
             array(),
368 368
             EVENT_ESPRESSO_VERSION
369 369
         );
@@ -371,7 +371,7 @@  discard block
 block discarded – undo
371 371
         // scripts
372 372
         wp_register_script(
373 373
             'espresso_txn',
374
-            TXN_ASSETS_URL . 'espresso_transactions_admin.js',
374
+            TXN_ASSETS_URL.'espresso_transactions_admin.js',
375 375
             array(
376 376
                 'ee_admin_js',
377 377
                 'ee-datepicker',
@@ -474,7 +474,7 @@  discard block
 block discarded – undo
474 474
             $this->_transaction->verify_abandoned_transaction_status();
475 475
         }
476 476
 
477
-        if (! $this->_transaction instanceof EE_Transaction) {
477
+        if ( ! $this->_transaction instanceof EE_Transaction) {
478 478
             $error_msg = sprintf(
479 479
                 esc_html__(
480 480
                     'An error occurred and the details for the transaction with the ID # %d could not be retrieved.',
@@ -572,7 +572,7 @@  discard block
 block discarded – undo
572 572
             'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
573 573
             array(
574 574
                 'overpaid'   => array(
575
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code,
575
+                    'class' => 'ee-status-legend ee-status-legend-'.EEM_Transaction::overpaid_status_code,
576 576
                     'desc'  => EEH_Template::pretty_status(
577 577
                         EEM_Transaction::overpaid_status_code,
578 578
                         false,
@@ -580,7 +580,7 @@  discard block
 block discarded – undo
580 580
                     ),
581 581
                 ),
582 582
                 'complete'   => array(
583
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code,
583
+                    'class' => 'ee-status-legend ee-status-legend-'.EEM_Transaction::complete_status_code,
584 584
                     'desc'  => EEH_Template::pretty_status(
585 585
                         EEM_Transaction::complete_status_code,
586 586
                         false,
@@ -588,7 +588,7 @@  discard block
 block discarded – undo
588 588
                     ),
589 589
                 ),
590 590
                 'incomplete' => array(
591
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code,
591
+                    'class' => 'ee-status-legend ee-status-legend-'.EEM_Transaction::incomplete_status_code,
592 592
                     'desc'  => EEH_Template::pretty_status(
593 593
                         EEM_Transaction::incomplete_status_code,
594 594
                         false,
@@ -596,7 +596,7 @@  discard block
 block discarded – undo
596 596
                     ),
597 597
                 ),
598 598
                 'abandoned'  => array(
599
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code,
599
+                    'class' => 'ee-status-legend ee-status-legend-'.EEM_Transaction::abandoned_status_code,
600 600
                     'desc'  => EEH_Template::pretty_status(
601 601
                         EEM_Transaction::abandoned_status_code,
602 602
                         false,
@@ -604,7 +604,7 @@  discard block
 block discarded – undo
604 604
                     ),
605 605
                 ),
606 606
                 'failed'     => array(
607
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code,
607
+                    'class' => 'ee-status-legend ee-status-legend-'.EEM_Transaction::failed_status_code,
608 608
                     'desc'  => EEH_Template::pretty_status(
609 609
                         EEM_Transaction::failed_status_code,
610 610
                         false,
@@ -653,7 +653,7 @@  discard block
 block discarded – undo
653 653
                     'Click to Edit event',
654 654
                     'event_espresso'
655 655
                 )
656
-                . '">' . $event->get('EVT_name') . '</a>',
656
+                . '">'.$event->get('EVT_name').'</a>',
657 657
                 '</h3>'
658 658
             )
659 659
             : '';
@@ -687,7 +687,7 @@  discard block
 block discarded – undo
687 687
 
688 688
         $this->_set_transaction_object();
689 689
 
690
-        if (! $this->_transaction instanceof EE_Transaction) {
690
+        if ( ! $this->_transaction instanceof EE_Transaction) {
691 691
             return;
692 692
         }
693 693
         $primary_registration = $this->_transaction->primary_registration();
@@ -701,9 +701,9 @@  discard block
 block discarded – undo
701 701
         $this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
702 702
         $this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
703 703
 
704
-        $this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->get('STS_ID') ];
704
+        $this->_template_args['txn_status']['value'] = self::$_txn_status[$this->_transaction->get('STS_ID')];
705 705
         $this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
706
-        $this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->get('STS_ID');
706
+        $this->_template_args['txn_status']['class'] = 'status-'.$this->_transaction->get('STS_ID');
707 707
 
708 708
         $this->_template_args['grand_total'] = $this->_transaction->get('TXN_total');
709 709
         $this->_template_args['total_paid'] = $this->_transaction->get('TXN_paid');
@@ -821,7 +821,7 @@  discard block
 block discarded – undo
821 821
         // grab messages at the last second
822 822
         $this->_template_args['notices'] = EE_Error::get_notices();
823 823
         // path to template
824
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
824
+        $template_path = TXN_TEMPLATE_PATH.'txn_admin_details_header.template.php';
825 825
         $this->_template_args['admin_page_header'] = EEH_Template::display_template(
826 826
             $template_path,
827 827
             $this->_template_args,
@@ -850,7 +850,7 @@  discard block
 block discarded – undo
850 850
 
851 851
         $this->_set_transaction_object();
852 852
 
853
-        if (! $this->_transaction instanceof EE_Transaction) {
853
+        if ( ! $this->_transaction instanceof EE_Transaction) {
854 854
             return;
855 855
         }
856 856
         add_meta_box(
@@ -905,7 +905,7 @@  discard block
 block discarded – undo
905 905
     {
906 906
         $content = '';
907 907
         $actions = array();
908
-        if (! $transaction instanceof EE_Transaction) {
908
+        if ( ! $transaction instanceof EE_Transaction) {
909 909
             return $content;
910 910
         }
911 911
         /** @var EE_Registration $primary_registration */
@@ -966,7 +966,7 @@  discard block
 block discarded – undo
966 966
         );
967 967
         if ($actions) {
968 968
             $content = '<ul>';
969
-            $content .= '<li>' . implode('</li><li>', $actions) . '</li>';
969
+            $content .= '<li>'.implode('</li><li>', $actions).'</li>';
970 970
             $content .= '</uL>';
971 971
         }
972 972
         return $content;
@@ -1031,7 +1031,7 @@  discard block
 block discarded – undo
1031 1031
 
1032 1032
         // process payment details
1033 1033
         $payments = $this->_transaction->get_many_related('Payment');
1034
-        if (! empty($payments)) {
1034
+        if ( ! empty($payments)) {
1035 1035
             $this->_template_args['payments'] = $payments;
1036 1036
             $this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
1037 1037
         } else {
@@ -1092,7 +1092,7 @@  discard block
 block discarded – undo
1092 1092
                                   esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
1093 1093
                                   ucwords(str_replace('_', ' ', $reg_step)),
1094 1094
                                   date(
1095
-                                      get_option('date_format') . ' ' . get_option('time_format'),
1095
+                                      get_option('date_format').' '.get_option('time_format'),
1096 1096
                                       ($reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS))
1097 1097
                                   )
1098 1098
                               )
@@ -1145,7 +1145,7 @@  discard block
 block discarded – undo
1145 1145
 
1146 1146
         // 'espresso_delete_payment_nonce'
1147 1147
 
1148
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
1148
+        $template_path = TXN_TEMPLATE_PATH.'txn_admin_details_main_meta_box_txn_details.template.php';
1149 1149
         echo EEH_Template::display_template($template_path, $this->_template_args, true);
1150 1150
     }
1151 1151
 
@@ -1177,18 +1177,18 @@  discard block
 block discarded – undo
1177 1177
                 ),
1178 1178
             )
1179 1179
         );
1180
-        if (! empty($reg_payments)) {
1180
+        if ( ! empty($reg_payments)) {
1181 1181
             foreach ($payments as $payment) {
1182
-                if (! $payment instanceof EE_Payment) {
1182
+                if ( ! $payment instanceof EE_Payment) {
1183 1183
                     continue;
1184
-                } elseif (! isset($existing_reg_payments[ $payment->ID() ])) {
1185
-                    $existing_reg_payments[ $payment->ID() ] = array();
1184
+                } elseif ( ! isset($existing_reg_payments[$payment->ID()])) {
1185
+                    $existing_reg_payments[$payment->ID()] = array();
1186 1186
                 }
1187 1187
                 foreach ($reg_payments as $reg_payment) {
1188 1188
                     if ($reg_payment instanceof EE_Registration_Payment
1189 1189
                         && $reg_payment->payment_ID() === $payment->ID()
1190 1190
                     ) {
1191
-                        $existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID();
1191
+                        $existing_reg_payments[$payment->ID()][] = $reg_payment->registration_ID();
1192 1192
                     }
1193 1193
                 }
1194 1194
             }
@@ -1229,16 +1229,16 @@  discard block
 block discarded – undo
1229 1229
                                                  '',
1230 1230
                                                  'clear: both; margin: 1.5em 0 0; display: none;'
1231 1231
                                              );
1232
-        $registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1232
+        $registrations_to_apply_payment_to .= EEH_HTML::br().EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1233 1233
         $registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl');
1234 1234
         $registrations_to_apply_payment_to .= EEH_HTML::thead(
1235 1235
             EEH_HTML::tr(
1236
-                EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
1237
-                EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
1238
-                EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
1239
-                EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
1240
-                EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
1241
-                EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
1236
+                EEH_HTML::th(esc_html__('ID', 'event_espresso')).
1237
+                EEH_HTML::th(esc_html__('Registrant', 'event_espresso')).
1238
+                EEH_HTML::th(esc_html__('Ticket', 'event_espresso')).
1239
+                EEH_HTML::th(esc_html__('Event', 'event_espresso')).
1240
+                EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr').
1241
+                EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr').
1242 1242
                 EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
1243 1243
             )
1244 1244
         );
@@ -1253,29 +1253,29 @@  discard block
 block discarded – undo
1253 1253
                     : esc_html__('Unknown Attendee', 'event_espresso');
1254 1254
                 $owing = $registration->final_price() - $registration->paid();
1255 1255
                 $taxable = $registration->ticket()->taxable()
1256
-                    ? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
1256
+                    ? ' <span class="smaller-text lt-grey-text"> '.esc_html__('+ tax', 'event_espresso').'</span>'
1257 1257
                     : '';
1258 1258
                 $checked = empty($existing_reg_payments) || in_array($registration->ID(), $existing_reg_payments)
1259 1259
                     ? ' checked="checked"'
1260 1260
                     : '';
1261 1261
                 $disabled = $registration->final_price() > 0 ? '' : ' disabled';
1262 1262
                 $registrations_to_apply_payment_to .= EEH_HTML::tr(
1263
-                    EEH_HTML::td($registration->ID()) .
1264
-                    EEH_HTML::td($attendee_name) .
1263
+                    EEH_HTML::td($registration->ID()).
1264
+                    EEH_HTML::td($attendee_name).
1265 1265
                     EEH_HTML::td(
1266
-                        $registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
1267
-                    ) .
1268
-                    EEH_HTML::td($registration->event_name()) .
1269
-                    EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
1270
-                    EEH_HTML::td(EEH_Template::format_currency($owing), '', 'txn-admin-payment-owing-td jst-cntr') .
1266
+                        $registration->ticket()->name().' : '.$registration->ticket()->pretty_price().$taxable
1267
+                    ).
1268
+                    EEH_HTML::td($registration->event_name()).
1269
+                    EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr').
1270
+                    EEH_HTML::td(EEH_Template::format_currency($owing), '', 'txn-admin-payment-owing-td jst-cntr').
1271 1271
                     EEH_HTML::td(
1272
-                        '<input type="checkbox" value="' . $registration->ID()
1272
+                        '<input type="checkbox" value="'.$registration->ID()
1273 1273
                         . '" name="txn_admin_payment[registrations]"'
1274
-                        . $checked . $disabled . '>',
1274
+                        . $checked.$disabled.'>',
1275 1275
                         '',
1276 1276
                         'jst-cntr'
1277 1277
                     ),
1278
-                    'apply-payment-registration-row-' . $registration->ID()
1278
+                    'apply-payment-registration-row-'.$registration->ID()
1279 1279
                 );
1280 1280
             }
1281 1281
         }
@@ -1356,12 +1356,12 @@  discard block
 block discarded – undo
1356 1356
                 array(
1357 1357
                     'OR*payment_method_for_payment' => array(
1358 1358
                         'PMD_ID'    => array('IN', $payment_methods_of_payments),
1359
-                        'PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'),
1359
+                        'PMD_scope' => array('LIKE', '%'.EEM_Payment_Method::scope_admin.'%'),
1360 1360
                     ),
1361 1361
                 ),
1362 1362
             );
1363 1363
         } else {
1364
-            $query_args = array(array('PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%')));
1364
+            $query_args = array(array('PMD_scope' => array('LIKE', '%'.EEM_Payment_Method::scope_admin.'%')));
1365 1365
         }
1366 1366
         $this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1367 1367
     }
@@ -1390,7 +1390,7 @@  discard block
 block discarded – undo
1390 1390
             'Line_Item',
1391 1391
             array(array('LIN_type' => 'line-item'))
1392 1392
         );
1393
-        if (! empty($line_items)) {
1393
+        if ( ! empty($line_items)) {
1394 1394
             foreach ($line_items as $item) {
1395 1395
                 if ($item instanceof EE_Line_Item) {
1396 1396
                     switch ($item->OBJ_type()) {
@@ -1400,7 +1400,7 @@  discard block
 block discarded – undo
1400 1400
                             $ticket = $item->ticket();
1401 1401
                             // right now we're only handling tickets here.
1402 1402
                             // Cause its expected that only tickets will have attendees right?
1403
-                            if (! $ticket instanceof EE_Ticket) {
1403
+                            if ( ! $ticket instanceof EE_Ticket) {
1404 1404
                                 continue;
1405 1405
                             }
1406 1406
                             try {
@@ -1409,7 +1409,7 @@  discard block
 block discarded – undo
1409 1409
                                 EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1410 1410
                                 $event_name = esc_html__('Unknown Event', 'event_espresso');
1411 1411
                             }
1412
-                            $event_name .= ' - ' . $item->get('LIN_name');
1412
+                            $event_name .= ' - '.$item->get('LIN_name');
1413 1413
                             $ticket_price = EEH_Template::format_currency($item->get('LIN_unit_price'));
1414 1414
                             // now get all of the registrations for this transaction that use this ticket
1415 1415
                             $registrations = $ticket->get_many_related(
@@ -1417,38 +1417,38 @@  discard block
 block discarded – undo
1417 1417
                                 array(array('TXN_ID' => $this->_transaction->ID()))
1418 1418
                             );
1419 1419
                             foreach ($registrations as $registration) {
1420
-                                if (! $registration instanceof EE_Registration) {
1420
+                                if ( ! $registration instanceof EE_Registration) {
1421 1421
                                     continue;
1422 1422
                                 }
1423
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID']
1423
+                                $this->_template_args['event_attendees'][$registration->ID()]['STS_ID']
1424 1424
                                     = $registration->status_ID();
1425
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['att_num']
1425
+                                $this->_template_args['event_attendees'][$registration->ID()]['att_num']
1426 1426
                                     = $registration->count();
1427
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name']
1427
+                                $this->_template_args['event_attendees'][$registration->ID()]['event_ticket_name']
1428 1428
                                     = $event_name;
1429
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price']
1429
+                                $this->_template_args['event_attendees'][$registration->ID()]['ticket_price']
1430 1430
                                     = $ticket_price;
1431 1431
                                 // attendee info
1432 1432
                                 $attendee = $registration->get_first_related('Attendee');
1433 1433
                                 if ($attendee instanceof EE_Attendee) {
1434
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id']
1434
+                                    $this->_template_args['event_attendees'][$registration->ID()]['att_id']
1435 1435
                                         = $attendee->ID();
1436
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee']
1436
+                                    $this->_template_args['event_attendees'][$registration->ID()]['attendee']
1437 1437
                                         = $attendee->full_name();
1438
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email']
1439
-                                        = '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name
1438
+                                    $this->_template_args['event_attendees'][$registration->ID()]['email']
1439
+                                        = '<a href="mailto:'.$attendee->email().'?subject='.$event_name
1440 1440
                                           . esc_html__(
1441 1441
                                               ' Event',
1442 1442
                                               'event_espresso'
1443 1443
                                           )
1444
-                                          . '">' . $attendee->email() . '</a>';
1445
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address']
1444
+                                          . '">'.$attendee->email().'</a>';
1445
+                                    $this->_template_args['event_attendees'][$registration->ID()]['address']
1446 1446
                                         = EEH_Address::format($attendee, 'inline', false, false);
1447 1447
                                 } else {
1448
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id'] = '';
1449
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = '';
1450
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email'] = '';
1451
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address'] = '';
1448
+                                    $this->_template_args['event_attendees'][$registration->ID()]['att_id'] = '';
1449
+                                    $this->_template_args['event_attendees'][$registration->ID()]['attendee'] = '';
1450
+                                    $this->_template_args['event_attendees'][$registration->ID()]['email'] = '';
1451
+                                    $this->_template_args['event_attendees'][$registration->ID()]['address'] = '';
1452 1452
                                 }
1453 1453
                             }
1454 1454
                             break;
@@ -1464,7 +1464,7 @@  discard block
 block discarded – undo
1464 1464
                 TXN_ADMIN_URL
1465 1465
             );
1466 1466
             echo EEH_Template::display_template(
1467
-                TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1467
+                TXN_TEMPLATE_PATH.'txn_admin_details_main_meta_box_attendees.template.php',
1468 1468
                 $this->_template_args,
1469 1469
                 true
1470 1470
             );
@@ -1499,7 +1499,7 @@  discard block
 block discarded – undo
1499 1499
         $primary_att = $this->_transaction->primary_registration() instanceof EE_Registration
1500 1500
             ? $this->_transaction->primary_registration()->get_first_related('Attendee')
1501 1501
             : null;
1502
-        if (! $primary_att instanceof EE_Attendee) {
1502
+        if ( ! $primary_att instanceof EE_Attendee) {
1503 1503
             $this->_template_args['no_attendee_message'] = esc_html__(
1504 1504
                 'There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1505 1505
                 'event_espresso'
@@ -1521,7 +1521,7 @@  discard block
 block discarded – undo
1521 1521
         // get formatted address for registrant
1522 1522
         $this->_template_args['formatted_address'] = EEH_Address::format($primary_att);
1523 1523
         echo EEH_Template::display_template(
1524
-            TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1524
+            TXN_TEMPLATE_PATH.'txn_admin_details_side_meta_box_registrant.template.php',
1525 1525
             $this->_template_args,
1526 1526
             true
1527 1527
         );
@@ -1546,8 +1546,8 @@  discard block
 block discarded – undo
1546 1546
             TXN_ADMIN_URL
1547 1547
         );
1548 1548
 
1549
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1550
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);/**/
1549
+        $template_path = TXN_TEMPLATE_PATH.'txn_admin_details_side_meta_box_billing_info.template.php';
1550
+        echo EEH_Template::display_template($template_path, $this->_template_args, true); /**/
1551 1551
     }
1552 1552
 
1553 1553
 
@@ -1572,7 +1572,7 @@  discard block
 block discarded – undo
1572 1572
             'ee_edit_payments',
1573 1573
             'apply_payment_or_refund_from_registration_details'
1574 1574
         );
1575
-        if (! empty($valid_data) && $has_access) {
1575
+        if ( ! empty($valid_data) && $has_access) {
1576 1576
             $PAY_ID = $valid_data['PAY_ID'];
1577 1577
             // save  the new payment
1578 1578
             $payment = $this->_create_payment_from_request_data($valid_data);
@@ -1585,7 +1585,7 @@  discard block
 block discarded – undo
1585 1585
                 $REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1586 1586
                 $this->_remove_existing_registration_payments($payment, $PAY_ID);
1587 1587
                 // apply payment to registrations (if applicable)
1588
-                if (! empty($REG_IDs)) {
1588
+                if ( ! empty($REG_IDs)) {
1589 1589
                     $this->_update_registration_payments($transaction, $payment, $REG_IDs);
1590 1590
                     $this->_maybe_send_notifications();
1591 1591
                     // now process status changes for the same registrations
@@ -1655,14 +1655,14 @@  discard block
 block discarded – undo
1655 1655
      */
1656 1656
     protected function _validate_payment_request_data()
1657 1657
     {
1658
-        if (! isset($this->_req_data['txn_admin_payment'])) {
1658
+        if ( ! isset($this->_req_data['txn_admin_payment'])) {
1659 1659
             return false;
1660 1660
         }
1661 1661
         $payment_form = $this->_generate_payment_form_section();
1662 1662
         try {
1663 1663
             if ($payment_form->was_submitted()) {
1664 1664
                 $payment_form->receive_form_submission();
1665
-                if (! $payment_form->is_valid()) {
1665
+                if ( ! $payment_form->is_valid()) {
1666 1666
                     $submission_error_messages = array();
1667 1667
                     foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1668 1668
                         if ($validation_error instanceof EE_Validation_Error) {
@@ -1841,7 +1841,7 @@  discard block
 block discarded – undo
1841 1841
             array('Y-m-d', 'g:i a')
1842 1842
         );
1843 1843
 
1844
-        if (! $payment->save()) {
1844
+        if ( ! $payment->save()) {
1845 1845
             EE_Error::add_error(
1846 1846
                 sprintf(
1847 1847
                     esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
@@ -2038,12 +2038,12 @@  discard block
 block discarded – undo
2038 2038
         // but add in some conditions regarding payment,
2039 2039
         // so that we don't apply payments to registrations that are free or have already been paid for
2040 2040
         // but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
2041
-        if (! $payment->is_a_refund()) {
2041
+        if ( ! $payment->is_a_refund()) {
2042 2042
             $registration_query_where_params['REG_final_price'] = array('!=', 0);
2043 2043
             $registration_query_where_params['REG_final_price*'] = array('!=', 'REG_paid', true);
2044 2044
         }
2045 2045
         $registrations = $transaction->registrations(array($registration_query_where_params));
2046
-        if (! empty($registrations)) {
2046
+        if ( ! empty($registrations)) {
2047 2047
             /** @type EE_Payment_Processor $payment_processor */
2048 2048
             $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2049 2049
             $payment_processor->process_registration_payments($transaction, $payment, $registrations);
@@ -2068,7 +2068,7 @@  discard block
 block discarded – undo
2068 2068
     protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = array())
2069 2069
     {
2070 2070
         // first if there is no change in status then we get out.
2071
-        if (! isset($this->_req_data['txn_reg_status_change']['reg_status'])
2071
+        if ( ! isset($this->_req_data['txn_reg_status_change']['reg_status'])
2072 2072
             || $this->_req_data['txn_reg_status_change']['reg_status'] === 'NAN'
2073 2073
         ) {
2074 2074
             // no error message, no change requested, just nothing to do man.
@@ -2126,7 +2126,7 @@  discard block
 block discarded – undo
2126 2126
                 'pay_status'       => $payment->STS_ID(),
2127 2127
                 'PAY_ID'           => $payment->ID(),
2128 2128
                 'STS_ID'           => $payment->STS_ID(),
2129
-                'status'           => self::$_pay_status[ $payment->STS_ID() ],
2129
+                'status'           => self::$_pay_status[$payment->STS_ID()],
2130 2130
                 'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
2131 2131
                 'method'           => strtoupper($payment->source()),
2132 2132
                 'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
@@ -2248,11 +2248,11 @@  discard block
 block discarded – undo
2248 2248
     {
2249 2249
         $registration_payment_data = array();
2250 2250
         // if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
2251
-        if (! empty($REG_IDs)) {
2251
+        if ( ! empty($REG_IDs)) {
2252 2252
             $registrations = EEM_Registration::instance()->get_all(array(array('REG_ID' => array('IN', $REG_IDs))));
2253 2253
             foreach ($registrations as $registration) {
2254 2254
                 if ($registration instanceof EE_Registration) {
2255
-                    $registration_payment_data[ $registration->ID() ] = array(
2255
+                    $registration_payment_data[$registration->ID()] = array(
2256 2256
                         'paid'  => $registration->pretty_paid(),
2257 2257
                         'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
2258 2258
                     );
@@ -2364,8 +2364,8 @@  discard block
 block discarded – undo
2364 2364
             : date('m/d/Y');
2365 2365
 
2366 2366
         // make sure our timestamps start and end right at the boundaries for each day
2367
-        $start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
2368
-        $end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
2367
+        $start_date = date('Y-m-d', strtotime($start_date)).' 00:00:00';
2368
+        $end_date = date('Y-m-d', strtotime($end_date)).' 23:59:59';
2369 2369
 
2370 2370
 
2371 2371
         // convert to timestamps
@@ -2424,7 +2424,7 @@  discard block
 block discarded – undo
2424 2424
         }
2425 2425
 
2426 2426
         if (isset($this->_req_data['s'])) {
2427
-            $search_string = '%' . $this->_req_data['s'] . '%';
2427
+            $search_string = '%'.$this->_req_data['s'].'%';
2428 2428
             $_where['OR'] = array(
2429 2429
                 'Registration.Event.EVT_name'         => array('LIKE', $search_string),
2430 2430
                 'Registration.Event.EVT_desc'         => array('LIKE', $search_string),
@@ -2451,9 +2451,9 @@  discard block
 block discarded – undo
2451 2451
         }
2452 2452
 
2453 2453
         // failed transactions
2454
-        $failed = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count)
2454
+        $failed = ( ! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count)
2455 2455
                   || ($count && $view === 'failed');
2456
-        $abandoned = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count)
2456
+        $abandoned = ( ! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count)
2457 2457
                      || ($count && $view === 'abandoned');
2458 2458
 
2459 2459
         if ($failed) {
Please login to merge, or discard this patch.
modules/messages/EED_Messages.module.php 1 patch
Indentation   +1322 added lines, -1322 removed lines patch added patch discarded remove patch
@@ -16,1335 +16,1335 @@
 block discarded – undo
16 16
 class EED_Messages extends EED_Module
17 17
 {
18 18
 
19
-    /**
20
-     * This holds the EE_messages controller
21
-     *
22
-     * @deprecated 4.9.0
23
-     * @var EE_messages $_EEMSG
24
-     */
25
-    protected static $_EEMSG;
26
-
27
-    /**
28
-     * @type EE_Message_Resource_Manager $_message_resource_manager
29
-     */
30
-    protected static $_message_resource_manager;
31
-
32
-    /**
33
-     * This holds the EE_Messages_Processor business class.
34
-     *
35
-     * @type EE_Messages_Processor
36
-     */
37
-    protected static $_MSG_PROCESSOR;
38
-
39
-    /**
40
-     * holds all the paths for various messages components.
41
-     * Utilized by autoloader registry
42
-     *
43
-     * @var array
44
-     */
45
-    protected static $_MSG_PATHS;
46
-
47
-
48
-    /**
49
-     * This will hold an array of messages template packs that are registered in the messages system.
50
-     * Format is:
51
-     * array(
52
-     *    'template_pack_dbref' => EE_Messages_Template_Pack (instance)
53
-     * )
54
-     *
55
-     * @var EE_Messages_Template_Pack[]
56
-     */
57
-    protected static $_TMP_PACKS = array();
58
-
59
-
60
-    /**
61
-     * @return EED_Messages
62
-     */
63
-    public static function instance()
64
-    {
65
-        return parent::get_instance(__CLASS__);
66
-    }
67
-
68
-
69
-    /**
70
-     *  set_hooks - for hooking into EE Core, other modules, etc
71
-     *
72
-     * @since 4.5.0
73
-     * @return    void
74
-     */
75
-    public static function set_hooks()
76
-    {
77
-        // actions
78
-        add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
79
-        add_action(
80
-            'AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
81
-            array('EED_Messages', 'maybe_registration'),
82
-            10,
83
-            2
84
-        );
85
-        // filters
86
-        add_filter(
87
-            'FHEE__EE_Registration__receipt_url__receipt_url',
88
-            array('EED_Messages', 'registration_message_trigger_url'),
89
-            10,
90
-            4
91
-        );
92
-        add_filter(
93
-            'FHEE__EE_Registration__invoice_url__invoice_url',
94
-            array('EED_Messages', 'registration_message_trigger_url'),
95
-            10,
96
-            4
97
-        );
98
-        // register routes
99
-        self::_register_routes();
100
-    }
101
-
102
-    /**
103
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
104
-     *
105
-     * @access    public
106
-     * @return    void
107
-     */
108
-    public static function set_hooks_admin()
109
-    {
110
-        // actions
111
-        add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
112
-        add_action(
113
-            'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
114
-            array('EED_Messages', 'payment_reminder'),
115
-            10
116
-        );
117
-        add_action(
118
-            'AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
119
-            array('EED_Messages', 'maybe_registration'),
120
-            10,
121
-            3
122
-        );
123
-        add_action(
124
-            'AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send__with_registrations',
125
-            array('EED_Messages', 'send_newsletter_message'),
126
-            10,
127
-            2
128
-        );
129
-        add_action(
130
-            'AHEE__EES_Espresso_Cancelled__process_shortcode__transaction',
131
-            array('EED_Messages', 'cancelled_registration'),
132
-            10
133
-        );
134
-        add_action(
135
-            'AHEE__EE_Admin_Page___process_admin_payment_notification',
136
-            array('EED_Messages', 'process_admin_payment'),
137
-            10,
138
-            1
139
-        );
140
-        // filters
141
-        add_filter(
142
-            'FHEE__EE_Admin_Page___process_resend_registration__success',
143
-            array('EED_Messages', 'process_resend'),
144
-            10,
145
-            2
146
-        );
147
-        add_filter(
148
-            'FHEE__EE_Registration__receipt_url__receipt_url',
149
-            array('EED_Messages', 'registration_message_trigger_url'),
150
-            10,
151
-            4
152
-        );
153
-        add_filter(
154
-            'FHEE__EE_Registration__invoice_url__invoice_url',
155
-            array('EED_Messages', 'registration_message_trigger_url'),
156
-            10,
157
-            4
158
-        );
159
-    }
160
-
161
-
162
-    /**
163
-     * All the message triggers done by route go in here.
164
-     *
165
-     * @since 4.5.0
166
-     * @return void
167
-     */
168
-    protected static function _register_routes()
169
-    {
170
-        EE_Config::register_route('msg_url_trigger', 'Messages', 'run');
171
-        EE_Config::register_route('msg_cron_trigger', 'Messages', 'execute_batch_request');
172
-        EE_Config::register_route('msg_browser_trigger', 'Messages', 'browser_trigger');
173
-        EE_Config::register_route('msg_browser_error_trigger', 'Messages', 'browser_error_trigger');
174
-        do_action('AHEE__EED_Messages___register_routes');
175
-    }
176
-
177
-
178
-    /**
179
-     * This is called when a browser display trigger is executed.
180
-     * The browser display trigger is typically used when a already generated message is displayed directly in the
181
-     * browser.
182
-     *
183
-     * @since 4.9.0
184
-     * @param WP $WP
185
-     * @throws EE_Error
186
-     * @throws InvalidArgumentException
187
-     * @throws ReflectionException
188
-     * @throws InvalidDataTypeException
189
-     * @throws InvalidInterfaceException
190
-     */
191
-    public function browser_trigger($WP)
192
-    {
193
-        // ensure controller is loaded
194
-        self::_load_controller();
195
-        $token = EE_Registry::instance()->REQ->get('token');
196
-        try {
197
-            $mtg = new EE_Message_Generated_From_Token($token, 'html', self::$_message_resource_manager);
198
-            self::$_MSG_PROCESSOR->generate_and_send_now($mtg);
199
-        } catch (EE_Error $e) {
200
-            $error_msg = __(
201
-                'Please note that a system message failed to send due to a technical issue.',
202
-                'event_espresso'
203
-            );
204
-            // add specific message for developers if WP_DEBUG in on
205
-            $error_msg .= '||' . $e->getMessage();
206
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
207
-        }
208
-    }
209
-
210
-
211
-    /**
212
-     * This is called when a browser error trigger is executed.
213
-     * When triggered this will grab the EE_Message matching the token in the request and use that to get the error
214
-     * message and display it.
215
-     *
216
-     * @since 4.9.0
217
-     * @param $WP
218
-     * @throws EE_Error
219
-     * @throws InvalidArgumentException
220
-     * @throws InvalidDataTypeException
221
-     * @throws InvalidInterfaceException
222
-     */
223
-    public function browser_error_trigger($WP)
224
-    {
225
-        $token = EE_Registry::instance()->REQ->get('token');
226
-        if ($token) {
227
-            $message = EEM_Message::instance()->get_one_by_token($token);
228
-            if ($message instanceof EE_Message) {
229
-                header('HTTP/1.1 200 OK');
230
-                $error_msg = nl2br($message->error_message());
231
-                ?>
19
+	/**
20
+	 * This holds the EE_messages controller
21
+	 *
22
+	 * @deprecated 4.9.0
23
+	 * @var EE_messages $_EEMSG
24
+	 */
25
+	protected static $_EEMSG;
26
+
27
+	/**
28
+	 * @type EE_Message_Resource_Manager $_message_resource_manager
29
+	 */
30
+	protected static $_message_resource_manager;
31
+
32
+	/**
33
+	 * This holds the EE_Messages_Processor business class.
34
+	 *
35
+	 * @type EE_Messages_Processor
36
+	 */
37
+	protected static $_MSG_PROCESSOR;
38
+
39
+	/**
40
+	 * holds all the paths for various messages components.
41
+	 * Utilized by autoloader registry
42
+	 *
43
+	 * @var array
44
+	 */
45
+	protected static $_MSG_PATHS;
46
+
47
+
48
+	/**
49
+	 * This will hold an array of messages template packs that are registered in the messages system.
50
+	 * Format is:
51
+	 * array(
52
+	 *    'template_pack_dbref' => EE_Messages_Template_Pack (instance)
53
+	 * )
54
+	 *
55
+	 * @var EE_Messages_Template_Pack[]
56
+	 */
57
+	protected static $_TMP_PACKS = array();
58
+
59
+
60
+	/**
61
+	 * @return EED_Messages
62
+	 */
63
+	public static function instance()
64
+	{
65
+		return parent::get_instance(__CLASS__);
66
+	}
67
+
68
+
69
+	/**
70
+	 *  set_hooks - for hooking into EE Core, other modules, etc
71
+	 *
72
+	 * @since 4.5.0
73
+	 * @return    void
74
+	 */
75
+	public static function set_hooks()
76
+	{
77
+		// actions
78
+		add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
79
+		add_action(
80
+			'AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
81
+			array('EED_Messages', 'maybe_registration'),
82
+			10,
83
+			2
84
+		);
85
+		// filters
86
+		add_filter(
87
+			'FHEE__EE_Registration__receipt_url__receipt_url',
88
+			array('EED_Messages', 'registration_message_trigger_url'),
89
+			10,
90
+			4
91
+		);
92
+		add_filter(
93
+			'FHEE__EE_Registration__invoice_url__invoice_url',
94
+			array('EED_Messages', 'registration_message_trigger_url'),
95
+			10,
96
+			4
97
+		);
98
+		// register routes
99
+		self::_register_routes();
100
+	}
101
+
102
+	/**
103
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
104
+	 *
105
+	 * @access    public
106
+	 * @return    void
107
+	 */
108
+	public static function set_hooks_admin()
109
+	{
110
+		// actions
111
+		add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
112
+		add_action(
113
+			'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
114
+			array('EED_Messages', 'payment_reminder'),
115
+			10
116
+		);
117
+		add_action(
118
+			'AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
119
+			array('EED_Messages', 'maybe_registration'),
120
+			10,
121
+			3
122
+		);
123
+		add_action(
124
+			'AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send__with_registrations',
125
+			array('EED_Messages', 'send_newsletter_message'),
126
+			10,
127
+			2
128
+		);
129
+		add_action(
130
+			'AHEE__EES_Espresso_Cancelled__process_shortcode__transaction',
131
+			array('EED_Messages', 'cancelled_registration'),
132
+			10
133
+		);
134
+		add_action(
135
+			'AHEE__EE_Admin_Page___process_admin_payment_notification',
136
+			array('EED_Messages', 'process_admin_payment'),
137
+			10,
138
+			1
139
+		);
140
+		// filters
141
+		add_filter(
142
+			'FHEE__EE_Admin_Page___process_resend_registration__success',
143
+			array('EED_Messages', 'process_resend'),
144
+			10,
145
+			2
146
+		);
147
+		add_filter(
148
+			'FHEE__EE_Registration__receipt_url__receipt_url',
149
+			array('EED_Messages', 'registration_message_trigger_url'),
150
+			10,
151
+			4
152
+		);
153
+		add_filter(
154
+			'FHEE__EE_Registration__invoice_url__invoice_url',
155
+			array('EED_Messages', 'registration_message_trigger_url'),
156
+			10,
157
+			4
158
+		);
159
+	}
160
+
161
+
162
+	/**
163
+	 * All the message triggers done by route go in here.
164
+	 *
165
+	 * @since 4.5.0
166
+	 * @return void
167
+	 */
168
+	protected static function _register_routes()
169
+	{
170
+		EE_Config::register_route('msg_url_trigger', 'Messages', 'run');
171
+		EE_Config::register_route('msg_cron_trigger', 'Messages', 'execute_batch_request');
172
+		EE_Config::register_route('msg_browser_trigger', 'Messages', 'browser_trigger');
173
+		EE_Config::register_route('msg_browser_error_trigger', 'Messages', 'browser_error_trigger');
174
+		do_action('AHEE__EED_Messages___register_routes');
175
+	}
176
+
177
+
178
+	/**
179
+	 * This is called when a browser display trigger is executed.
180
+	 * The browser display trigger is typically used when a already generated message is displayed directly in the
181
+	 * browser.
182
+	 *
183
+	 * @since 4.9.0
184
+	 * @param WP $WP
185
+	 * @throws EE_Error
186
+	 * @throws InvalidArgumentException
187
+	 * @throws ReflectionException
188
+	 * @throws InvalidDataTypeException
189
+	 * @throws InvalidInterfaceException
190
+	 */
191
+	public function browser_trigger($WP)
192
+	{
193
+		// ensure controller is loaded
194
+		self::_load_controller();
195
+		$token = EE_Registry::instance()->REQ->get('token');
196
+		try {
197
+			$mtg = new EE_Message_Generated_From_Token($token, 'html', self::$_message_resource_manager);
198
+			self::$_MSG_PROCESSOR->generate_and_send_now($mtg);
199
+		} catch (EE_Error $e) {
200
+			$error_msg = __(
201
+				'Please note that a system message failed to send due to a technical issue.',
202
+				'event_espresso'
203
+			);
204
+			// add specific message for developers if WP_DEBUG in on
205
+			$error_msg .= '||' . $e->getMessage();
206
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
207
+		}
208
+	}
209
+
210
+
211
+	/**
212
+	 * This is called when a browser error trigger is executed.
213
+	 * When triggered this will grab the EE_Message matching the token in the request and use that to get the error
214
+	 * message and display it.
215
+	 *
216
+	 * @since 4.9.0
217
+	 * @param $WP
218
+	 * @throws EE_Error
219
+	 * @throws InvalidArgumentException
220
+	 * @throws InvalidDataTypeException
221
+	 * @throws InvalidInterfaceException
222
+	 */
223
+	public function browser_error_trigger($WP)
224
+	{
225
+		$token = EE_Registry::instance()->REQ->get('token');
226
+		if ($token) {
227
+			$message = EEM_Message::instance()->get_one_by_token($token);
228
+			if ($message instanceof EE_Message) {
229
+				header('HTTP/1.1 200 OK');
230
+				$error_msg = nl2br($message->error_message());
231
+				?>
232 232
                 <!DOCTYPE html>
233 233
                 <html>
234 234
                 <head></head>
235 235
                 <body>
236 236
                 <?php echo empty($error_msg)
237
-                    ? esc_html__(
238
-                        'Unfortunately, we were unable to capture the error message for this message.',
239
-                        'event_espresso'
240
-                    )
241
-                    : wp_kses(
242
-                        $error_msg,
243
-                        array(
244
-                            'a'      => array(
245
-                                'href'  => array(),
246
-                                'title' => array(),
247
-                            ),
248
-                            'span'   => array(),
249
-                            'div'    => array(),
250
-                            'p'      => array(),
251
-                            'strong' => array(),
252
-                            'em'     => array(),
253
-                            'br'     => array(),
254
-                        )
255
-                    ); ?>
237
+					? esc_html__(
238
+						'Unfortunately, we were unable to capture the error message for this message.',
239
+						'event_espresso'
240
+					)
241
+					: wp_kses(
242
+						$error_msg,
243
+						array(
244
+							'a'      => array(
245
+								'href'  => array(),
246
+								'title' => array(),
247
+							),
248
+							'span'   => array(),
249
+							'div'    => array(),
250
+							'p'      => array(),
251
+							'strong' => array(),
252
+							'em'     => array(),
253
+							'br'     => array(),
254
+						)
255
+					); ?>
256 256
                 </body>
257 257
                 </html>
258 258
                 <?php
259
-                exit;
260
-            }
261
-        }
262
-        return;
263
-    }
264
-
265
-
266
-    /**
267
-     *  This runs when the msg_url_trigger route has initiated.
268
-     *
269
-     * @since 4.5.0
270
-     * @param WP $WP
271
-     * @throws EE_Error
272
-     * @throws InvalidArgumentException
273
-     * @throws ReflectionException
274
-     * @throws InvalidDataTypeException
275
-     * @throws InvalidInterfaceException
276
-     */
277
-    public function run($WP)
278
-    {
279
-        // ensure controller is loaded
280
-        self::_load_controller();
281
-        // attempt to process message
282
-        try {
283
-            /** @type EE_Message_To_Generate_From_Request $message_to_generate */
284
-            $message_to_generate = EE_Registry::instance()->load_lib('Message_To_Generate_From_Request');
285
-            self::$_MSG_PROCESSOR->generate_and_send_now($message_to_generate);
286
-        } catch (EE_Error $e) {
287
-            $error_msg = __(
288
-                'Please note that a system message failed to send due to a technical issue.',
289
-                'event_espresso'
290
-            );
291
-            // add specific message for developers if WP_DEBUG in on
292
-            $error_msg .= '||' . $e->getMessage();
293
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
294
-        }
295
-    }
296
-
297
-
298
-    /**
299
-     * This is triggered by the 'msg_cron_trigger' route.
300
-     *
301
-     * @param WP $WP
302
-     */
303
-    public function execute_batch_request($WP)
304
-    {
305
-        $this->run_cron();
306
-        header('HTTP/1.1 200 OK');
307
-        exit();
308
-    }
309
-
310
-
311
-    /**
312
-     * This gets executed on wp_cron jobs or when a batch request is initiated on its own separate non regular wp
313
-     * request.
314
-     */
315
-    public function run_cron()
316
-    {
317
-        self::_load_controller();
318
-        // get required vars
319
-        $cron_type = EE_Registry::instance()->REQ->get('type');
320
-        $transient_key = EE_Registry::instance()->REQ->get('key');
321
-
322
-        // now let's verify transient, if not valid exit immediately
323
-        if (! get_transient($transient_key)) {
324
-            /**
325
-             * trigger error so this gets in the error logs.  This is important because it happens on a non-user
326
-             * request.
327
-             */
328
-            trigger_error(esc_attr__('Invalid Request (Transient does not exist)', 'event_espresso'));
329
-        }
330
-
331
-        // if made it here, lets' delete the transient to keep the db clean
332
-        delete_transient($transient_key);
333
-
334
-        if (apply_filters('FHEE__EED_Messages__run_cron__use_wp_cron', true)) {
335
-            $method = 'batch_' . $cron_type . '_from_queue';
336
-            if (method_exists(self::$_MSG_PROCESSOR, $method)) {
337
-                self::$_MSG_PROCESSOR->$method();
338
-            } else {
339
-                // no matching task
340
-                /**
341
-                 * trigger error so this gets in the error logs.  This is important because it happens on a non user
342
-                 * request.
343
-                 */
344
-                trigger_error(
345
-                    esc_attr(
346
-                        sprintf(
347
-                            __('There is no task corresponding to this route %s', 'event_espresso'),
348
-                            $cron_type
349
-                        )
350
-                    )
351
-                );
352
-            }
353
-        }
354
-
355
-        do_action('FHEE__EED_Messages__run_cron__end');
356
-    }
357
-
358
-
359
-    /**
360
-     * This is used to retrieve the template pack for the given name.
361
-     * Retrieved packs are cached on the static $_TMP_PACKS array.  If there is no class matching the given name then
362
-     * the default template pack is returned.
363
-     *
364
-     * @deprecated 4.9.0  @see EEH_MSG_Template::get_template_pack()
365
-     * @param string $template_pack_name This should correspond to the dbref of the template pack (which is also used
366
-     *                                   in generating the Pack class name).
367
-     * @return EE_Messages_Template_Pack
368
-     * @throws EE_Error
369
-     * @throws InvalidArgumentException
370
-     * @throws ReflectionException
371
-     * @throws InvalidDataTypeException
372
-     * @throws InvalidInterfaceException
373
-     */
374
-    public static function get_template_pack($template_pack_name)
375
-    {
376
-        EE_Registry::instance()->load_helper('MSG_Template');
377
-        return EEH_MSG_Template::get_template_pack($template_pack_name);
378
-    }
379
-
380
-
381
-    /**
382
-     * Retrieves an array of all template packs.
383
-     * Array is in the format array( 'dbref' => EE_Messages_Template_Pack )
384
-     *
385
-     * @deprecated 4.9.0  @see EEH_MSG_Template_Pack::get_template_pack_collection
386
-     * @return EE_Messages_Template_Pack[]
387
-     * @throws EE_Error
388
-     * @throws InvalidArgumentException
389
-     * @throws ReflectionException
390
-     * @throws InvalidDataTypeException
391
-     * @throws InvalidInterfaceException
392
-     */
393
-    public static function get_template_packs()
394
-    {
395
-        EE_Registry::instance()->load_helper('MSG_Template');
396
-
397
-        // for backward compat, let's make sure this returns in the same format as originally.
398
-        $template_pack_collection = EEH_MSG_Template::get_template_pack_collection();
399
-        $template_pack_collection->rewind();
400
-        $template_packs = array();
401
-        while ($template_pack_collection->valid()) {
402
-            $template_packs[ $template_pack_collection->current()->dbref ] = $template_pack_collection->current();
403
-            $template_pack_collection->next();
404
-        }
405
-        return $template_packs;
406
-    }
407
-
408
-
409
-    /**
410
-     * This simply makes sure the autoloaders are registered for the EE_messages system.
411
-     *
412
-     * @since 4.5.0
413
-     * @return void
414
-     * @throws EE_Error
415
-     */
416
-    public static function set_autoloaders()
417
-    {
418
-        if (empty(self::$_MSG_PATHS)) {
419
-            self::_set_messages_paths();
420
-            foreach (self::$_MSG_PATHS as $path) {
421
-                EEH_Autoloader::register_autoloaders_for_each_file_in_folder($path);
422
-            }
423
-            // add aliases
424
-            EEH_Autoloader::add_alias('EE_messages', 'EE_messages');
425
-            EEH_Autoloader::add_alias('EE_messenger', 'EE_messenger');
426
-        }
427
-    }
428
-
429
-
430
-    /**
431
-     * Take care of adding all the paths for the messages components to the $_MSG_PATHS property
432
-     * for use by the Messages Autoloaders
433
-     *
434
-     * @since 4.5.0
435
-     * @return void.
436
-     */
437
-    protected static function _set_messages_paths()
438
-    {
439
-        $dir_ref = array(
440
-            'messages/message_type',
441
-            'messages/messenger',
442
-            'messages/defaults',
443
-            'messages/defaults/email',
444
-            'messages/data_class',
445
-            'messages/validators',
446
-            'messages/validators/email',
447
-            'messages/validators/html',
448
-            'shortcodes',
449
-        );
450
-        $paths = array();
451
-        foreach ($dir_ref as $index => $dir) {
452
-            $paths[ $index ] = EE_LIBRARIES . $dir;
453
-        }
454
-        self::$_MSG_PATHS = apply_filters('FHEE__EED_Messages___set_messages_paths___MSG_PATHS', $paths);
455
-    }
456
-
457
-
458
-    /**
459
-     * Takes care of loading dependencies
460
-     *
461
-     * @since 4.5.0
462
-     * @return void
463
-     * @throws EE_Error
464
-     * @throws InvalidArgumentException
465
-     * @throws ReflectionException
466
-     * @throws InvalidDataTypeException
467
-     * @throws InvalidInterfaceException
468
-     */
469
-    protected static function _load_controller()
470
-    {
471
-        if (! self::$_MSG_PROCESSOR instanceof EE_Messages_Processor) {
472
-            EE_Registry::instance()->load_core('Request_Handler');
473
-            self::set_autoloaders();
474
-            self::$_EEMSG = EE_Registry::instance()->load_lib('messages');
475
-            self::$_MSG_PROCESSOR = EE_Registry::instance()->load_lib('Messages_Processor');
476
-            self::$_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
477
-        }
478
-    }
479
-
480
-
481
-    /**
482
-     * @param EE_Transaction $transaction
483
-     * @throws EE_Error
484
-     * @throws InvalidArgumentException
485
-     * @throws InvalidDataTypeException
486
-     * @throws InvalidInterfaceException
487
-     * @throws ReflectionException
488
-     */
489
-    public static function payment_reminder(EE_Transaction $transaction)
490
-    {
491
-        self::_load_controller();
492
-        $data = array($transaction, null);
493
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('payment_reminder', $data);
494
-    }
495
-
496
-
497
-    /**
498
-     * Any messages triggers for after successful gateway payments should go in here.
499
-     *
500
-     * @param EE_Transaction  $transaction object
501
-     * @param EE_Payment|null $payment     object
502
-     * @return void
503
-     * @throws EE_Error
504
-     * @throws InvalidArgumentException
505
-     * @throws ReflectionException
506
-     * @throws InvalidDataTypeException
507
-     * @throws InvalidInterfaceException
508
-     */
509
-    public static function payment(EE_Transaction $transaction, EE_Payment $payment = null)
510
-    {
511
-        // if there's no payment object, then we cannot do a payment type message!
512
-        if (! $payment instanceof EE_Payment) {
513
-            return;
514
-        }
515
-        self::_load_controller();
516
-        $data = array($transaction, $payment);
517
-        EE_Registry::instance()->load_helper('MSG_Template');
518
-        $message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
519
-        // if payment amount is less than 0 then switch to payment_refund message type.
520
-        $message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
521
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
522
-    }
523
-
524
-
525
-    /**
526
-     * @param EE_Transaction $transaction
527
-     * @throws EE_Error
528
-     * @throws InvalidArgumentException
529
-     * @throws InvalidDataTypeException
530
-     * @throws InvalidInterfaceException
531
-     * @throws ReflectionException
532
-     */
533
-    public static function cancelled_registration(EE_Transaction $transaction)
534
-    {
535
-        self::_load_controller();
536
-        $data = array($transaction, null);
537
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('cancelled_registration', $data);
538
-    }
539
-
540
-
541
-    /**
542
-     * Trigger for Registration messages
543
-     * Note that what registration message type is sent depends on what the reg status is for the registrations on the
544
-     * incoming transaction.
545
-     *
546
-     * @param EE_Registration $registration
547
-     * @param array           $extra_details
548
-     * @return void
549
-     * @throws EE_Error
550
-     * @throws InvalidArgumentException
551
-     * @throws InvalidDataTypeException
552
-     * @throws InvalidInterfaceException
553
-     * @throws ReflectionException
554
-     * @throws EntityNotFoundException
555
-     */
556
-    public static function maybe_registration(EE_Registration $registration, $extra_details = array())
557
-    {
558
-
559
-        if (! self::_verify_registration_notification_send($registration, $extra_details)) {
560
-            // no messages please
561
-            return;
562
-        }
563
-
564
-        // get all non-trashed registrations so we make sure we send messages for the right status.
565
-        $all_registrations = $registration->transaction()->registrations(
566
-            array(
567
-                array('REG_deleted' => false),
568
-                'order_by' => array(
569
-                    'Event.EVT_name'     => 'ASC',
570
-                    'Attendee.ATT_lname' => 'ASC',
571
-                    'Attendee.ATT_fname' => 'ASC',
572
-                ),
573
-            )
574
-        );
575
-        // cached array of statuses so we only trigger messages once per status.
576
-        $statuses_sent = array();
577
-        self::_load_controller();
578
-        $mtgs = array();
579
-
580
-        // loop through registrations and trigger messages once per status.
581
-        foreach ($all_registrations as $reg) {
582
-            // already triggered?
583
-            if (in_array($reg->status_ID(), $statuses_sent)) {
584
-                continue;
585
-            }
586
-
587
-            $message_type = EEH_MSG_Template::convert_reg_status_to_message_type($reg->status_ID());
588
-            $mtgs = array_merge(
589
-                $mtgs,
590
-                self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
591
-                    $message_type,
592
-                    array($registration->transaction(), null, $reg->status_ID())
593
-                )
594
-            );
595
-            $statuses_sent[] = $reg->status_ID();
596
-        }
597
-
598
-        if (count($statuses_sent) > 1) {
599
-            $mtgs = array_merge(
600
-                $mtgs,
601
-                self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
602
-                    'registration_summary',
603
-                    array($registration->transaction(), null)
604
-                )
605
-            );
606
-        }
607
-
608
-        // batch queue and initiate request
609
-        self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($mtgs);
610
-        self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
611
-    }
612
-
613
-
614
-    /**
615
-     * This is a helper method used to very whether a registration notification should be sent or
616
-     * not.  Prevents duplicate notifications going out for registration context notifications.
617
-     *
618
-     * @param EE_Registration $registration  [description]
619
-     * @param array           $extra_details [description]
620
-     * @return bool          true = send away, false = nope halt the presses.
621
-     */
622
-    protected static function _verify_registration_notification_send(
623
-        EE_Registration $registration,
624
-        $extra_details = array()
625
-    ) {
626
-        if (! $registration->is_primary_registrant()) {
627
-            return false;
628
-        }
629
-        // first we check if we're in admin and not doing front ajax
630
-        if (is_admin() && ! EE_FRONT_AJAX) {
631
-            // make sure appropriate admin params are set for sending messages
632
-            if (empty($_REQUEST['txn_reg_status_change']['send_notifications'])
633
-                || ! absint($_REQUEST['txn_reg_status_change']['send_notifications'])
634
-            ) {
635
-                // no messages sent please.
636
-                return false;
637
-            }
638
-        } else {
639
-            // frontend request (either regular or via AJAX)
640
-            // TXN is NOT finalized ?
641
-            if (! isset($extra_details['finalized']) || $extra_details['finalized'] === false) {
642
-                return false;
643
-            }
644
-            // return visit but nothing changed ???
645
-            if (isset($extra_details['revisit'], $extra_details['status_updates']) &&
646
-                $extra_details['revisit'] && ! $extra_details['status_updates']
647
-            ) {
648
-                return false;
649
-            }
650
-            // NOT sending messages && reg status is something other than "Not-Approved"
651
-            if (! apply_filters('FHEE__EED_Messages___maybe_registration__deliver_notifications', false) &&
652
-                $registration->status_ID() !== EEM_Registration::status_id_not_approved
653
-            ) {
654
-                return false;
655
-            }
656
-        }
657
-        // release the kraken
658
-        return true;
659
-    }
660
-
661
-
662
-    /**
663
-     * Simply returns an array indexed by Registration Status ID and the related message_type name associated with that
664
-     * status id.
665
-     *
666
-     * @deprecated 4.9.0  Use EEH_MSG_Template::reg_status_to_message_type_array()
667
-     *                    or EEH_MSG_Template::convert_reg_status_to_message_type
668
-     * @param string $reg_status
669
-     * @return array
670
-     * @throws EE_Error
671
-     * @throws InvalidArgumentException
672
-     * @throws ReflectionException
673
-     * @throws InvalidDataTypeException
674
-     * @throws InvalidInterfaceException
675
-     */
676
-    protected static function _get_reg_status_array($reg_status = '')
677
-    {
678
-        EE_Registry::instance()->load_helper('MSG_Template');
679
-        return EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
680
-            ? EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
681
-            : EEH_MSG_Template::reg_status_to_message_type_array();
682
-    }
683
-
684
-
685
-    /**
686
-     * Simply returns the payment message type for the given payment status.
687
-     *
688
-     * @deprecated 4.9.0 Use EEH_MSG_Template::payment_status_to_message_type_array
689
-     *                   or EEH_MSG_Template::convert_payment_status_to_message_type
690
-     * @param string $payment_status The payment status being matched.
691
-     * @return bool|string The payment message type slug matching the status or false if no match.
692
-     * @throws EE_Error
693
-     * @throws InvalidArgumentException
694
-     * @throws ReflectionException
695
-     * @throws InvalidDataTypeException
696
-     * @throws InvalidInterfaceException
697
-     */
698
-    protected static function _get_payment_message_type($payment_status)
699
-    {
700
-        EE_Registry::instance()->load_helper('MSG_Template');
701
-        return EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
702
-            ? EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
703
-            : false;
704
-    }
705
-
706
-
707
-    /**
708
-     * Message triggers for a resending already sent message(s) (via EE_Message list table)
709
-     *
710
-     * @access public
711
-     * @param array $req_data This is the $_POST & $_GET data sent from EE_Admin Pages
712
-     * @return bool success/fail
713
-     * @throws EE_Error
714
-     * @throws InvalidArgumentException
715
-     * @throws InvalidDataTypeException
716
-     * @throws InvalidInterfaceException
717
-     * @throws ReflectionException
718
-     */
719
-    public static function process_resend($req_data)
720
-    {
721
-        self::_load_controller();
722
-
723
-        // if $msgID in this request then skip to the new resend_message
724
-        if (EE_Registry::instance()->REQ->get('MSG_ID')) {
725
-            return self::resend_message();
726
-        }
727
-
728
-        // make sure any incoming request data is set on the REQ so that it gets picked up later.
729
-        $req_data = (array) $req_data;
730
-        foreach ($req_data as $request_key => $request_value) {
731
-            EE_Registry::instance()->REQ->set($request_key, $request_value);
732
-        }
733
-
734
-        if (! $messages_to_send = self::$_MSG_PROCESSOR->setup_messages_to_generate_from_registration_ids_in_request(
735
-        )) {
736
-            return false;
737
-        }
738
-
739
-        try {
740
-            self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($messages_to_send);
741
-            self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
742
-        } catch (EE_Error $e) {
743
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
744
-            return false;
745
-        }
746
-        EE_Error::add_success(
747
-            __('Messages have been successfully queued for generation and sending.', 'event_espresso')
748
-        );
749
-        return true; // everything got queued.
750
-    }
751
-
752
-
753
-    /**
754
-     * Message triggers for a resending already sent message(s) (via EE_Message list table)
755
-     *
756
-     * @return bool
757
-     * @throws EE_Error
758
-     * @throws InvalidArgumentException
759
-     * @throws InvalidDataTypeException
760
-     * @throws InvalidInterfaceException
761
-     * @throws ReflectionException
762
-     */
763
-    public static function resend_message()
764
-    {
765
-        self::_load_controller();
766
-
767
-        $msgID = EE_Registry::instance()->REQ->get('MSG_ID');
768
-        if (! $msgID) {
769
-            EE_Error::add_error(
770
-                __(
771
-                    'Something went wrong because there is no "MSG_ID" value in the request',
772
-                    'event_espresso'
773
-                ),
774
-                __FILE__,
775
-                __FUNCTION__,
776
-                __LINE__
777
-            );
778
-            return false;
779
-        }
780
-
781
-        self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send((array) $msgID);
782
-
783
-        // setup success message.
784
-        $count_ready_for_resend = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
785
-        EE_Error::add_success(
786
-            sprintf(
787
-                _n(
788
-                    'There was %d message queued for resending.',
789
-                    'There were %d messages queued for resending.',
790
-                    $count_ready_for_resend,
791
-                    'event_espresso'
792
-                ),
793
-                $count_ready_for_resend
794
-            )
795
-        );
796
-        return true;
797
-    }
798
-
799
-
800
-    /**
801
-     * Message triggers for manual payment applied by admin
802
-     *
803
-     * @param  EE_Payment $payment EE_payment object
804
-     * @return bool success/fail
805
-     * @throws EE_Error
806
-     * @throws InvalidArgumentException
807
-     * @throws ReflectionException
808
-     * @throws InvalidDataTypeException
809
-     * @throws InvalidInterfaceException
810
-     */
811
-    public static function process_admin_payment(EE_Payment $payment)
812
-    {
813
-        EE_Registry::instance()->load_helper('MSG_Template');
814
-        // we need to get the transaction object
815
-        $transaction = $payment->transaction();
816
-        if ($transaction instanceof EE_Transaction) {
817
-            $data = array($transaction, $payment);
818
-            $message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
819
-
820
-            // if payment amount is less than 0 then switch to payment_refund message type.
821
-            $message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
822
-
823
-            // if payment_refund is selected, but the status is NOT accepted.  Then change message type to false so NO message notification goes out.
824
-            $message_type = $message_type == 'payment_refund' && $payment->STS_ID() != EEM_Payment::status_id_approved
825
-                ? false : $message_type;
826
-
827
-            self::_load_controller();
828
-
829
-            self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
830
-
831
-            // get count of queued for generation
832
-            $count_to_generate = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(
833
-                array(
834
-                    EEM_Message::status_incomplete,
835
-                    EEM_Message::status_idle,
836
-                )
837
-            );
838
-
839
-            if ($count_to_generate > 0 && self::$_MSG_PROCESSOR->get_queue()->get_message_repository()->count() !== 0) {
840
-                add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
841
-                return true;
842
-            } else {
843
-                $count_failed = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(
844
-                    EEM_Message::instance()->stati_indicating_failed_sending()
845
-                );
846
-                /**
847
-                 * Verify that there are actually errors.  If not then we return a success message because the queue might have been emptied due to successful
848
-                 * IMMEDIATE generation.
849
-                 */
850
-                if ($count_failed > 0) {
851
-                    EE_Error::add_error(
852
-                        sprintf(
853
-                            _n(
854
-                                'The payment notification generation failed.',
855
-                                '%d payment notifications failed being sent.',
856
-                                $count_failed,
857
-                                'event_espresso'
858
-                            ),
859
-                            $count_failed
860
-                        ),
861
-                        __FILE__,
862
-                        __FUNCTION__,
863
-                        __LINE__
864
-                    );
865
-
866
-                    return false;
867
-                } else {
868
-                    add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
869
-                    return true;
870
-                }
871
-            }
872
-        } else {
873
-            EE_Error::add_error(
874
-                'Unable to generate the payment notification because the given value for the transaction is invalid.',
875
-                'event_espresso'
876
-            );
877
-            return false;
878
-        }
879
-    }
880
-
881
-
882
-    /**
883
-     * Callback for AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send_with_registrations trigger
884
-     *
885
-     * @since   4.3.0
886
-     * @param  EE_Registration[] $registrations an array of EE_Registration objects
887
-     * @param  int               $grp_id        a specific message template group id.
888
-     * @return void
889
-     * @throws EE_Error
890
-     * @throws InvalidArgumentException
891
-     * @throws InvalidDataTypeException
892
-     * @throws InvalidInterfaceException
893
-     * @throws ReflectionException
894
-     */
895
-    public static function send_newsletter_message($registrations, $grp_id)
896
-    {
897
-        // make sure mtp is id and set it in the EE_Request Handler later messages setup.
898
-        EE_Registry::instance()->REQ->set('GRP_ID', (int) $grp_id);
899
-        self::_load_controller();
900
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('newsletter', $registrations);
901
-    }
902
-
903
-
904
-    /**
905
-     * Callback for FHEE__EE_Registration__invoice_url__invoice_url or FHEE__EE_Registration__receipt_url__receipt_url
906
-     *
907
-     * @since   4.3.0
908
-     * @param    string          $registration_message_trigger_url
909
-     * @param    EE_Registration $registration
910
-     * @param string             $messenger
911
-     * @param string             $message_type
912
-     * @return string
913
-     * @throws EE_Error
914
-     * @throws InvalidArgumentException
915
-     * @throws InvalidDataTypeException
916
-     * @throws InvalidInterfaceException
917
-     */
918
-    public static function registration_message_trigger_url(
919
-        $registration_message_trigger_url,
920
-        EE_Registration $registration,
921
-        $messenger = 'html',
922
-        $message_type = 'invoice'
923
-    ) {
924
-        // whitelist $messenger
925
-        switch ($messenger) {
926
-            case 'pdf':
927
-                $sending_messenger = 'pdf';
928
-                $generating_messenger = 'html';
929
-                break;
930
-            case 'html':
931
-            default:
932
-                $sending_messenger = 'html';
933
-                $generating_messenger = 'html';
934
-                break;
935
-        }
936
-        // whitelist $message_type
937
-        switch ($message_type) {
938
-            case 'receipt':
939
-                $message_type = 'receipt';
940
-                break;
941
-            case 'invoice':
942
-            default:
943
-                $message_type = 'invoice';
944
-                break;
945
-        }
946
-        // verify that both the messenger AND the message type are active
947
-        if (EEH_MSG_Template::is_messenger_active($sending_messenger)
948
-            && EEH_MSG_Template::is_mt_active($message_type)
949
-        ) {
950
-            // need to get the correct message template group for this (i.e. is there a custom invoice for the event this registration is registered for?)
951
-            $template_query_params = array(
952
-                'MTP_is_active'    => true,
953
-                'MTP_messenger'    => $generating_messenger,
954
-                'MTP_message_type' => $message_type,
955
-                'Event.EVT_ID'     => $registration->event_ID(),
956
-            );
957
-            // get the message template group.
958
-            $msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
959
-            // if we don't have an EE_Message_Template_Group then return
960
-            if (! $msg_template_group instanceof EE_Message_Template_Group) {
961
-                // remove EVT_ID from query params so that global templates get picked up
962
-                unset($template_query_params['Event.EVT_ID']);
963
-                // get global template as the fallback
964
-                $msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
965
-            }
966
-            // if we don't have an EE_Message_Template_Group then return
967
-            if (! $msg_template_group instanceof EE_Message_Template_Group) {
968
-                return '';
969
-            }
970
-            // generate the URL
971
-            $registration_message_trigger_url = EEH_MSG_Template::generate_url_trigger(
972
-                $sending_messenger,
973
-                $generating_messenger,
974
-                'purchaser',
975
-                $message_type,
976
-                $registration,
977
-                $msg_template_group->ID(),
978
-                $registration->transaction_ID()
979
-            );
980
-        }
981
-        return $registration_message_trigger_url;
982
-    }
983
-
984
-
985
-    /**
986
-     * Use to generate and return a message preview!
987
-     *
988
-     * @param  string $type      This should correspond with a valid message type
989
-     * @param  string $context   This should correspond with a valid context for the message type
990
-     * @param  string $messenger This should correspond with a valid messenger.
991
-     * @param bool    $send      true we will do a test send using the messenger delivery, false we just do a regular
992
-     *                           preview
993
-     * @return bool|string The body of the message or if send is requested, sends.
994
-     * @throws EE_Error
995
-     * @throws InvalidArgumentException
996
-     * @throws InvalidDataTypeException
997
-     * @throws InvalidInterfaceException
998
-     * @throws ReflectionException
999
-     */
1000
-    public static function preview_message($type, $context, $messenger, $send = false)
1001
-    {
1002
-        self::_load_controller();
1003
-        $mtg = new EE_Message_To_Generate(
1004
-            $messenger,
1005
-            $type,
1006
-            array(),
1007
-            $context,
1008
-            true
1009
-        );
1010
-        $generated_preview_queue = self::$_MSG_PROCESSOR->generate_for_preview($mtg, $send);
1011
-        if ($generated_preview_queue instanceof EE_Messages_Queue) {
1012
-            // loop through all content for the preview and remove any persisted records.
1013
-            $content = '';
1014
-            foreach ($generated_preview_queue->get_message_repository() as $message) {
1015
-                $content = $message->content();
1016
-                if ($message->ID() > 0 && $message->STS_ID() !== EEM_Message::status_failed) {
1017
-                    $message->delete();
1018
-                }
1019
-            }
1020
-            return $content;
1021
-        } else {
1022
-            return $generated_preview_queue;
1023
-        }
1024
-    }
1025
-
1026
-
1027
-    /**
1028
-     * This is a method that allows for sending a message using a messenger matching the string given and the provided
1029
-     * EE_Message_Queue object.  The EE_Message_Queue object is used to create a single aggregate EE_Message via the
1030
-     * content found in the EE_Message objects in the queue.
1031
-     *
1032
-     * @since 4.9.0
1033
-     * @param string            $messenger            a string matching a valid active messenger in the system
1034
-     * @param string            $message_type         Although it seems contrary to the name of the method, a message
1035
-     *                                                type name is still required to send along the message type to the
1036
-     *                                                messenger because this is used for determining what specific
1037
-     *                                                variations might be loaded for the generated message.
1038
-     * @param EE_Messages_Queue $queue
1039
-     * @param string            $custom_subject       Can be used to set what the custom subject string will be on the
1040
-     *                                                aggregate EE_Message object.
1041
-     * @return bool success or fail.
1042
-     * @throws EE_Error
1043
-     * @throws InvalidArgumentException
1044
-     * @throws ReflectionException
1045
-     * @throws InvalidDataTypeException
1046
-     * @throws InvalidInterfaceException
1047
-     */
1048
-    public static function send_message_with_messenger_only(
1049
-        $messenger,
1050
-        $message_type,
1051
-        EE_Messages_Queue $queue,
1052
-        $custom_subject = ''
1053
-    ) {
1054
-        self::_load_controller();
1055
-        /** @type EE_Message_To_Generate_From_Queue $message_to_generate */
1056
-        $message_to_generate = EE_Registry::instance()->load_lib(
1057
-            'Message_To_Generate_From_Queue',
1058
-            array(
1059
-                $messenger,
1060
-                $message_type,
1061
-                $queue,
1062
-                $custom_subject,
1063
-            )
1064
-        );
1065
-        return self::$_MSG_PROCESSOR->queue_for_sending($message_to_generate);
1066
-    }
1067
-
1068
-
1069
-    /**
1070
-     * Generates Messages immediately for EE_Message IDs (but only for the correct status for generation)
1071
-     *
1072
-     * @since 4.9.0
1073
-     * @param array $message_ids An array of message ids
1074
-     * @return bool|EE_Messages_Queue false if nothing was generated, EE_Messages_Queue containing generated
1075
-     *                           messages.
1076
-     * @throws EE_Error
1077
-     * @throws InvalidArgumentException
1078
-     * @throws InvalidDataTypeException
1079
-     * @throws InvalidInterfaceException
1080
-     * @throws ReflectionException
1081
-     */
1082
-    public static function generate_now($message_ids)
1083
-    {
1084
-        self::_load_controller();
1085
-        $messages = EEM_Message::instance()->get_all(
1086
-            array(
1087
-                0 => array(
1088
-                    'MSG_ID' => array('IN', $message_ids),
1089
-                    'STS_ID' => EEM_Message::status_incomplete,
1090
-                ),
1091
-            )
1092
-        );
1093
-        $generated_queue = false;
1094
-        if ($messages) {
1095
-            $generated_queue = self::$_MSG_PROCESSOR->batch_generate_from_queue($messages);
1096
-        }
1097
-
1098
-        if (! $generated_queue instanceof EE_Messages_Queue) {
1099
-            EE_Error::add_error(
1100
-                __(
1101
-                    'The messages were not generated. This could mean there is already a batch being generated on a separate request, or because the selected messages are not ready for generation. Please wait a minute or two and try again.',
1102
-                    'event_espresso'
1103
-                ),
1104
-                __FILE__,
1105
-                __FUNCTION__,
1106
-                __LINE__
1107
-            );
1108
-        }
1109
-        return $generated_queue;
1110
-    }
1111
-
1112
-
1113
-    /**
1114
-     * Sends messages immediately for the incoming message_ids that have the status of EEM_Message::status_resend or,
1115
-     * EEM_Message::status_idle
1116
-     *
1117
-     * @since 4.9.0
1118
-     * @param $message_ids
1119
-     * @return bool|EE_Messages_Queue false if no messages sent.
1120
-     * @throws EE_Error
1121
-     * @throws InvalidArgumentException
1122
-     * @throws InvalidDataTypeException
1123
-     * @throws InvalidInterfaceException
1124
-     * @throws ReflectionException
1125
-     */
1126
-    public static function send_now($message_ids)
1127
-    {
1128
-        self::_load_controller();
1129
-        $messages = EEM_Message::instance()->get_all(
1130
-            array(
1131
-                0 => array(
1132
-                    'MSG_ID' => array('IN', $message_ids),
1133
-                    'STS_ID' => array(
1134
-                        'IN',
1135
-                        array(EEM_Message::status_idle, EEM_Message::status_resend, EEM_Message::status_retry),
1136
-                    ),
1137
-                ),
1138
-            )
1139
-        );
1140
-        $sent_queue = false;
1141
-        if ($messages) {
1142
-            $sent_queue = self::$_MSG_PROCESSOR->batch_send_from_queue($messages);
1143
-        }
1144
-
1145
-        if (! $sent_queue instanceof EE_Messages_Queue) {
1146
-            EE_Error::add_error(
1147
-                __(
1148
-                    'The messages were not sent. This could mean there is already a batch being sent on a separate request, or because the selected messages are not sendable. Please wait a minute or two and try again.',
1149
-                    'event_espresso'
1150
-                ),
1151
-                __FILE__,
1152
-                __FUNCTION__,
1153
-                __LINE__
1154
-            );
1155
-        } else {
1156
-            // can count how many sent by using the messages in the queue
1157
-            $sent_count = $sent_queue->count_STS_in_queue(EEM_Message::instance()->stati_indicating_sent());
1158
-            if ($sent_count > 0) {
1159
-                EE_Error::add_success(
1160
-                    sprintf(
1161
-                        _n(
1162
-                            'There was %d message successfully sent.',
1163
-                            'There were %d messages successfully sent.',
1164
-                            $sent_count,
1165
-                            'event_espresso'
1166
-                        ),
1167
-                        $sent_count
1168
-                    )
1169
-                );
1170
-            } else {
1171
-                EE_Error::overwrite_errors();
1172
-                EE_Error::add_error(
1173
-                    __(
1174
-                        'No message was sent because of problems with sending. Either all the messages you selected were not a sendable message, they were ALREADY sent on a different scheduled task, or there was an error.
259
+				exit;
260
+			}
261
+		}
262
+		return;
263
+	}
264
+
265
+
266
+	/**
267
+	 *  This runs when the msg_url_trigger route has initiated.
268
+	 *
269
+	 * @since 4.5.0
270
+	 * @param WP $WP
271
+	 * @throws EE_Error
272
+	 * @throws InvalidArgumentException
273
+	 * @throws ReflectionException
274
+	 * @throws InvalidDataTypeException
275
+	 * @throws InvalidInterfaceException
276
+	 */
277
+	public function run($WP)
278
+	{
279
+		// ensure controller is loaded
280
+		self::_load_controller();
281
+		// attempt to process message
282
+		try {
283
+			/** @type EE_Message_To_Generate_From_Request $message_to_generate */
284
+			$message_to_generate = EE_Registry::instance()->load_lib('Message_To_Generate_From_Request');
285
+			self::$_MSG_PROCESSOR->generate_and_send_now($message_to_generate);
286
+		} catch (EE_Error $e) {
287
+			$error_msg = __(
288
+				'Please note that a system message failed to send due to a technical issue.',
289
+				'event_espresso'
290
+			);
291
+			// add specific message for developers if WP_DEBUG in on
292
+			$error_msg .= '||' . $e->getMessage();
293
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
294
+		}
295
+	}
296
+
297
+
298
+	/**
299
+	 * This is triggered by the 'msg_cron_trigger' route.
300
+	 *
301
+	 * @param WP $WP
302
+	 */
303
+	public function execute_batch_request($WP)
304
+	{
305
+		$this->run_cron();
306
+		header('HTTP/1.1 200 OK');
307
+		exit();
308
+	}
309
+
310
+
311
+	/**
312
+	 * This gets executed on wp_cron jobs or when a batch request is initiated on its own separate non regular wp
313
+	 * request.
314
+	 */
315
+	public function run_cron()
316
+	{
317
+		self::_load_controller();
318
+		// get required vars
319
+		$cron_type = EE_Registry::instance()->REQ->get('type');
320
+		$transient_key = EE_Registry::instance()->REQ->get('key');
321
+
322
+		// now let's verify transient, if not valid exit immediately
323
+		if (! get_transient($transient_key)) {
324
+			/**
325
+			 * trigger error so this gets in the error logs.  This is important because it happens on a non-user
326
+			 * request.
327
+			 */
328
+			trigger_error(esc_attr__('Invalid Request (Transient does not exist)', 'event_espresso'));
329
+		}
330
+
331
+		// if made it here, lets' delete the transient to keep the db clean
332
+		delete_transient($transient_key);
333
+
334
+		if (apply_filters('FHEE__EED_Messages__run_cron__use_wp_cron', true)) {
335
+			$method = 'batch_' . $cron_type . '_from_queue';
336
+			if (method_exists(self::$_MSG_PROCESSOR, $method)) {
337
+				self::$_MSG_PROCESSOR->$method();
338
+			} else {
339
+				// no matching task
340
+				/**
341
+				 * trigger error so this gets in the error logs.  This is important because it happens on a non user
342
+				 * request.
343
+				 */
344
+				trigger_error(
345
+					esc_attr(
346
+						sprintf(
347
+							__('There is no task corresponding to this route %s', 'event_espresso'),
348
+							$cron_type
349
+						)
350
+					)
351
+				);
352
+			}
353
+		}
354
+
355
+		do_action('FHEE__EED_Messages__run_cron__end');
356
+	}
357
+
358
+
359
+	/**
360
+	 * This is used to retrieve the template pack for the given name.
361
+	 * Retrieved packs are cached on the static $_TMP_PACKS array.  If there is no class matching the given name then
362
+	 * the default template pack is returned.
363
+	 *
364
+	 * @deprecated 4.9.0  @see EEH_MSG_Template::get_template_pack()
365
+	 * @param string $template_pack_name This should correspond to the dbref of the template pack (which is also used
366
+	 *                                   in generating the Pack class name).
367
+	 * @return EE_Messages_Template_Pack
368
+	 * @throws EE_Error
369
+	 * @throws InvalidArgumentException
370
+	 * @throws ReflectionException
371
+	 * @throws InvalidDataTypeException
372
+	 * @throws InvalidInterfaceException
373
+	 */
374
+	public static function get_template_pack($template_pack_name)
375
+	{
376
+		EE_Registry::instance()->load_helper('MSG_Template');
377
+		return EEH_MSG_Template::get_template_pack($template_pack_name);
378
+	}
379
+
380
+
381
+	/**
382
+	 * Retrieves an array of all template packs.
383
+	 * Array is in the format array( 'dbref' => EE_Messages_Template_Pack )
384
+	 *
385
+	 * @deprecated 4.9.0  @see EEH_MSG_Template_Pack::get_template_pack_collection
386
+	 * @return EE_Messages_Template_Pack[]
387
+	 * @throws EE_Error
388
+	 * @throws InvalidArgumentException
389
+	 * @throws ReflectionException
390
+	 * @throws InvalidDataTypeException
391
+	 * @throws InvalidInterfaceException
392
+	 */
393
+	public static function get_template_packs()
394
+	{
395
+		EE_Registry::instance()->load_helper('MSG_Template');
396
+
397
+		// for backward compat, let's make sure this returns in the same format as originally.
398
+		$template_pack_collection = EEH_MSG_Template::get_template_pack_collection();
399
+		$template_pack_collection->rewind();
400
+		$template_packs = array();
401
+		while ($template_pack_collection->valid()) {
402
+			$template_packs[ $template_pack_collection->current()->dbref ] = $template_pack_collection->current();
403
+			$template_pack_collection->next();
404
+		}
405
+		return $template_packs;
406
+	}
407
+
408
+
409
+	/**
410
+	 * This simply makes sure the autoloaders are registered for the EE_messages system.
411
+	 *
412
+	 * @since 4.5.0
413
+	 * @return void
414
+	 * @throws EE_Error
415
+	 */
416
+	public static function set_autoloaders()
417
+	{
418
+		if (empty(self::$_MSG_PATHS)) {
419
+			self::_set_messages_paths();
420
+			foreach (self::$_MSG_PATHS as $path) {
421
+				EEH_Autoloader::register_autoloaders_for_each_file_in_folder($path);
422
+			}
423
+			// add aliases
424
+			EEH_Autoloader::add_alias('EE_messages', 'EE_messages');
425
+			EEH_Autoloader::add_alias('EE_messenger', 'EE_messenger');
426
+		}
427
+	}
428
+
429
+
430
+	/**
431
+	 * Take care of adding all the paths for the messages components to the $_MSG_PATHS property
432
+	 * for use by the Messages Autoloaders
433
+	 *
434
+	 * @since 4.5.0
435
+	 * @return void.
436
+	 */
437
+	protected static function _set_messages_paths()
438
+	{
439
+		$dir_ref = array(
440
+			'messages/message_type',
441
+			'messages/messenger',
442
+			'messages/defaults',
443
+			'messages/defaults/email',
444
+			'messages/data_class',
445
+			'messages/validators',
446
+			'messages/validators/email',
447
+			'messages/validators/html',
448
+			'shortcodes',
449
+		);
450
+		$paths = array();
451
+		foreach ($dir_ref as $index => $dir) {
452
+			$paths[ $index ] = EE_LIBRARIES . $dir;
453
+		}
454
+		self::$_MSG_PATHS = apply_filters('FHEE__EED_Messages___set_messages_paths___MSG_PATHS', $paths);
455
+	}
456
+
457
+
458
+	/**
459
+	 * Takes care of loading dependencies
460
+	 *
461
+	 * @since 4.5.0
462
+	 * @return void
463
+	 * @throws EE_Error
464
+	 * @throws InvalidArgumentException
465
+	 * @throws ReflectionException
466
+	 * @throws InvalidDataTypeException
467
+	 * @throws InvalidInterfaceException
468
+	 */
469
+	protected static function _load_controller()
470
+	{
471
+		if (! self::$_MSG_PROCESSOR instanceof EE_Messages_Processor) {
472
+			EE_Registry::instance()->load_core('Request_Handler');
473
+			self::set_autoloaders();
474
+			self::$_EEMSG = EE_Registry::instance()->load_lib('messages');
475
+			self::$_MSG_PROCESSOR = EE_Registry::instance()->load_lib('Messages_Processor');
476
+			self::$_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
477
+		}
478
+	}
479
+
480
+
481
+	/**
482
+	 * @param EE_Transaction $transaction
483
+	 * @throws EE_Error
484
+	 * @throws InvalidArgumentException
485
+	 * @throws InvalidDataTypeException
486
+	 * @throws InvalidInterfaceException
487
+	 * @throws ReflectionException
488
+	 */
489
+	public static function payment_reminder(EE_Transaction $transaction)
490
+	{
491
+		self::_load_controller();
492
+		$data = array($transaction, null);
493
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('payment_reminder', $data);
494
+	}
495
+
496
+
497
+	/**
498
+	 * Any messages triggers for after successful gateway payments should go in here.
499
+	 *
500
+	 * @param EE_Transaction  $transaction object
501
+	 * @param EE_Payment|null $payment     object
502
+	 * @return void
503
+	 * @throws EE_Error
504
+	 * @throws InvalidArgumentException
505
+	 * @throws ReflectionException
506
+	 * @throws InvalidDataTypeException
507
+	 * @throws InvalidInterfaceException
508
+	 */
509
+	public static function payment(EE_Transaction $transaction, EE_Payment $payment = null)
510
+	{
511
+		// if there's no payment object, then we cannot do a payment type message!
512
+		if (! $payment instanceof EE_Payment) {
513
+			return;
514
+		}
515
+		self::_load_controller();
516
+		$data = array($transaction, $payment);
517
+		EE_Registry::instance()->load_helper('MSG_Template');
518
+		$message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
519
+		// if payment amount is less than 0 then switch to payment_refund message type.
520
+		$message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
521
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
522
+	}
523
+
524
+
525
+	/**
526
+	 * @param EE_Transaction $transaction
527
+	 * @throws EE_Error
528
+	 * @throws InvalidArgumentException
529
+	 * @throws InvalidDataTypeException
530
+	 * @throws InvalidInterfaceException
531
+	 * @throws ReflectionException
532
+	 */
533
+	public static function cancelled_registration(EE_Transaction $transaction)
534
+	{
535
+		self::_load_controller();
536
+		$data = array($transaction, null);
537
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('cancelled_registration', $data);
538
+	}
539
+
540
+
541
+	/**
542
+	 * Trigger for Registration messages
543
+	 * Note that what registration message type is sent depends on what the reg status is for the registrations on the
544
+	 * incoming transaction.
545
+	 *
546
+	 * @param EE_Registration $registration
547
+	 * @param array           $extra_details
548
+	 * @return void
549
+	 * @throws EE_Error
550
+	 * @throws InvalidArgumentException
551
+	 * @throws InvalidDataTypeException
552
+	 * @throws InvalidInterfaceException
553
+	 * @throws ReflectionException
554
+	 * @throws EntityNotFoundException
555
+	 */
556
+	public static function maybe_registration(EE_Registration $registration, $extra_details = array())
557
+	{
558
+
559
+		if (! self::_verify_registration_notification_send($registration, $extra_details)) {
560
+			// no messages please
561
+			return;
562
+		}
563
+
564
+		// get all non-trashed registrations so we make sure we send messages for the right status.
565
+		$all_registrations = $registration->transaction()->registrations(
566
+			array(
567
+				array('REG_deleted' => false),
568
+				'order_by' => array(
569
+					'Event.EVT_name'     => 'ASC',
570
+					'Attendee.ATT_lname' => 'ASC',
571
+					'Attendee.ATT_fname' => 'ASC',
572
+				),
573
+			)
574
+		);
575
+		// cached array of statuses so we only trigger messages once per status.
576
+		$statuses_sent = array();
577
+		self::_load_controller();
578
+		$mtgs = array();
579
+
580
+		// loop through registrations and trigger messages once per status.
581
+		foreach ($all_registrations as $reg) {
582
+			// already triggered?
583
+			if (in_array($reg->status_ID(), $statuses_sent)) {
584
+				continue;
585
+			}
586
+
587
+			$message_type = EEH_MSG_Template::convert_reg_status_to_message_type($reg->status_ID());
588
+			$mtgs = array_merge(
589
+				$mtgs,
590
+				self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
591
+					$message_type,
592
+					array($registration->transaction(), null, $reg->status_ID())
593
+				)
594
+			);
595
+			$statuses_sent[] = $reg->status_ID();
596
+		}
597
+
598
+		if (count($statuses_sent) > 1) {
599
+			$mtgs = array_merge(
600
+				$mtgs,
601
+				self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
602
+					'registration_summary',
603
+					array($registration->transaction(), null)
604
+				)
605
+			);
606
+		}
607
+
608
+		// batch queue and initiate request
609
+		self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($mtgs);
610
+		self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
611
+	}
612
+
613
+
614
+	/**
615
+	 * This is a helper method used to very whether a registration notification should be sent or
616
+	 * not.  Prevents duplicate notifications going out for registration context notifications.
617
+	 *
618
+	 * @param EE_Registration $registration  [description]
619
+	 * @param array           $extra_details [description]
620
+	 * @return bool          true = send away, false = nope halt the presses.
621
+	 */
622
+	protected static function _verify_registration_notification_send(
623
+		EE_Registration $registration,
624
+		$extra_details = array()
625
+	) {
626
+		if (! $registration->is_primary_registrant()) {
627
+			return false;
628
+		}
629
+		// first we check if we're in admin and not doing front ajax
630
+		if (is_admin() && ! EE_FRONT_AJAX) {
631
+			// make sure appropriate admin params are set for sending messages
632
+			if (empty($_REQUEST['txn_reg_status_change']['send_notifications'])
633
+				|| ! absint($_REQUEST['txn_reg_status_change']['send_notifications'])
634
+			) {
635
+				// no messages sent please.
636
+				return false;
637
+			}
638
+		} else {
639
+			// frontend request (either regular or via AJAX)
640
+			// TXN is NOT finalized ?
641
+			if (! isset($extra_details['finalized']) || $extra_details['finalized'] === false) {
642
+				return false;
643
+			}
644
+			// return visit but nothing changed ???
645
+			if (isset($extra_details['revisit'], $extra_details['status_updates']) &&
646
+				$extra_details['revisit'] && ! $extra_details['status_updates']
647
+			) {
648
+				return false;
649
+			}
650
+			// NOT sending messages && reg status is something other than "Not-Approved"
651
+			if (! apply_filters('FHEE__EED_Messages___maybe_registration__deliver_notifications', false) &&
652
+				$registration->status_ID() !== EEM_Registration::status_id_not_approved
653
+			) {
654
+				return false;
655
+			}
656
+		}
657
+		// release the kraken
658
+		return true;
659
+	}
660
+
661
+
662
+	/**
663
+	 * Simply returns an array indexed by Registration Status ID and the related message_type name associated with that
664
+	 * status id.
665
+	 *
666
+	 * @deprecated 4.9.0  Use EEH_MSG_Template::reg_status_to_message_type_array()
667
+	 *                    or EEH_MSG_Template::convert_reg_status_to_message_type
668
+	 * @param string $reg_status
669
+	 * @return array
670
+	 * @throws EE_Error
671
+	 * @throws InvalidArgumentException
672
+	 * @throws ReflectionException
673
+	 * @throws InvalidDataTypeException
674
+	 * @throws InvalidInterfaceException
675
+	 */
676
+	protected static function _get_reg_status_array($reg_status = '')
677
+	{
678
+		EE_Registry::instance()->load_helper('MSG_Template');
679
+		return EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
680
+			? EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
681
+			: EEH_MSG_Template::reg_status_to_message_type_array();
682
+	}
683
+
684
+
685
+	/**
686
+	 * Simply returns the payment message type for the given payment status.
687
+	 *
688
+	 * @deprecated 4.9.0 Use EEH_MSG_Template::payment_status_to_message_type_array
689
+	 *                   or EEH_MSG_Template::convert_payment_status_to_message_type
690
+	 * @param string $payment_status The payment status being matched.
691
+	 * @return bool|string The payment message type slug matching the status or false if no match.
692
+	 * @throws EE_Error
693
+	 * @throws InvalidArgumentException
694
+	 * @throws ReflectionException
695
+	 * @throws InvalidDataTypeException
696
+	 * @throws InvalidInterfaceException
697
+	 */
698
+	protected static function _get_payment_message_type($payment_status)
699
+	{
700
+		EE_Registry::instance()->load_helper('MSG_Template');
701
+		return EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
702
+			? EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
703
+			: false;
704
+	}
705
+
706
+
707
+	/**
708
+	 * Message triggers for a resending already sent message(s) (via EE_Message list table)
709
+	 *
710
+	 * @access public
711
+	 * @param array $req_data This is the $_POST & $_GET data sent from EE_Admin Pages
712
+	 * @return bool success/fail
713
+	 * @throws EE_Error
714
+	 * @throws InvalidArgumentException
715
+	 * @throws InvalidDataTypeException
716
+	 * @throws InvalidInterfaceException
717
+	 * @throws ReflectionException
718
+	 */
719
+	public static function process_resend($req_data)
720
+	{
721
+		self::_load_controller();
722
+
723
+		// if $msgID in this request then skip to the new resend_message
724
+		if (EE_Registry::instance()->REQ->get('MSG_ID')) {
725
+			return self::resend_message();
726
+		}
727
+
728
+		// make sure any incoming request data is set on the REQ so that it gets picked up later.
729
+		$req_data = (array) $req_data;
730
+		foreach ($req_data as $request_key => $request_value) {
731
+			EE_Registry::instance()->REQ->set($request_key, $request_value);
732
+		}
733
+
734
+		if (! $messages_to_send = self::$_MSG_PROCESSOR->setup_messages_to_generate_from_registration_ids_in_request(
735
+		)) {
736
+			return false;
737
+		}
738
+
739
+		try {
740
+			self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($messages_to_send);
741
+			self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
742
+		} catch (EE_Error $e) {
743
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
744
+			return false;
745
+		}
746
+		EE_Error::add_success(
747
+			__('Messages have been successfully queued for generation and sending.', 'event_espresso')
748
+		);
749
+		return true; // everything got queued.
750
+	}
751
+
752
+
753
+	/**
754
+	 * Message triggers for a resending already sent message(s) (via EE_Message list table)
755
+	 *
756
+	 * @return bool
757
+	 * @throws EE_Error
758
+	 * @throws InvalidArgumentException
759
+	 * @throws InvalidDataTypeException
760
+	 * @throws InvalidInterfaceException
761
+	 * @throws ReflectionException
762
+	 */
763
+	public static function resend_message()
764
+	{
765
+		self::_load_controller();
766
+
767
+		$msgID = EE_Registry::instance()->REQ->get('MSG_ID');
768
+		if (! $msgID) {
769
+			EE_Error::add_error(
770
+				__(
771
+					'Something went wrong because there is no "MSG_ID" value in the request',
772
+					'event_espresso'
773
+				),
774
+				__FILE__,
775
+				__FUNCTION__,
776
+				__LINE__
777
+			);
778
+			return false;
779
+		}
780
+
781
+		self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send((array) $msgID);
782
+
783
+		// setup success message.
784
+		$count_ready_for_resend = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
785
+		EE_Error::add_success(
786
+			sprintf(
787
+				_n(
788
+					'There was %d message queued for resending.',
789
+					'There were %d messages queued for resending.',
790
+					$count_ready_for_resend,
791
+					'event_espresso'
792
+				),
793
+				$count_ready_for_resend
794
+			)
795
+		);
796
+		return true;
797
+	}
798
+
799
+
800
+	/**
801
+	 * Message triggers for manual payment applied by admin
802
+	 *
803
+	 * @param  EE_Payment $payment EE_payment object
804
+	 * @return bool success/fail
805
+	 * @throws EE_Error
806
+	 * @throws InvalidArgumentException
807
+	 * @throws ReflectionException
808
+	 * @throws InvalidDataTypeException
809
+	 * @throws InvalidInterfaceException
810
+	 */
811
+	public static function process_admin_payment(EE_Payment $payment)
812
+	{
813
+		EE_Registry::instance()->load_helper('MSG_Template');
814
+		// we need to get the transaction object
815
+		$transaction = $payment->transaction();
816
+		if ($transaction instanceof EE_Transaction) {
817
+			$data = array($transaction, $payment);
818
+			$message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
819
+
820
+			// if payment amount is less than 0 then switch to payment_refund message type.
821
+			$message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
822
+
823
+			// if payment_refund is selected, but the status is NOT accepted.  Then change message type to false so NO message notification goes out.
824
+			$message_type = $message_type == 'payment_refund' && $payment->STS_ID() != EEM_Payment::status_id_approved
825
+				? false : $message_type;
826
+
827
+			self::_load_controller();
828
+
829
+			self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
830
+
831
+			// get count of queued for generation
832
+			$count_to_generate = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(
833
+				array(
834
+					EEM_Message::status_incomplete,
835
+					EEM_Message::status_idle,
836
+				)
837
+			);
838
+
839
+			if ($count_to_generate > 0 && self::$_MSG_PROCESSOR->get_queue()->get_message_repository()->count() !== 0) {
840
+				add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
841
+				return true;
842
+			} else {
843
+				$count_failed = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(
844
+					EEM_Message::instance()->stati_indicating_failed_sending()
845
+				);
846
+				/**
847
+				 * Verify that there are actually errors.  If not then we return a success message because the queue might have been emptied due to successful
848
+				 * IMMEDIATE generation.
849
+				 */
850
+				if ($count_failed > 0) {
851
+					EE_Error::add_error(
852
+						sprintf(
853
+							_n(
854
+								'The payment notification generation failed.',
855
+								'%d payment notifications failed being sent.',
856
+								$count_failed,
857
+								'event_espresso'
858
+							),
859
+							$count_failed
860
+						),
861
+						__FILE__,
862
+						__FUNCTION__,
863
+						__LINE__
864
+					);
865
+
866
+					return false;
867
+				} else {
868
+					add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
869
+					return true;
870
+				}
871
+			}
872
+		} else {
873
+			EE_Error::add_error(
874
+				'Unable to generate the payment notification because the given value for the transaction is invalid.',
875
+				'event_espresso'
876
+			);
877
+			return false;
878
+		}
879
+	}
880
+
881
+
882
+	/**
883
+	 * Callback for AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send_with_registrations trigger
884
+	 *
885
+	 * @since   4.3.0
886
+	 * @param  EE_Registration[] $registrations an array of EE_Registration objects
887
+	 * @param  int               $grp_id        a specific message template group id.
888
+	 * @return void
889
+	 * @throws EE_Error
890
+	 * @throws InvalidArgumentException
891
+	 * @throws InvalidDataTypeException
892
+	 * @throws InvalidInterfaceException
893
+	 * @throws ReflectionException
894
+	 */
895
+	public static function send_newsletter_message($registrations, $grp_id)
896
+	{
897
+		// make sure mtp is id and set it in the EE_Request Handler later messages setup.
898
+		EE_Registry::instance()->REQ->set('GRP_ID', (int) $grp_id);
899
+		self::_load_controller();
900
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('newsletter', $registrations);
901
+	}
902
+
903
+
904
+	/**
905
+	 * Callback for FHEE__EE_Registration__invoice_url__invoice_url or FHEE__EE_Registration__receipt_url__receipt_url
906
+	 *
907
+	 * @since   4.3.0
908
+	 * @param    string          $registration_message_trigger_url
909
+	 * @param    EE_Registration $registration
910
+	 * @param string             $messenger
911
+	 * @param string             $message_type
912
+	 * @return string
913
+	 * @throws EE_Error
914
+	 * @throws InvalidArgumentException
915
+	 * @throws InvalidDataTypeException
916
+	 * @throws InvalidInterfaceException
917
+	 */
918
+	public static function registration_message_trigger_url(
919
+		$registration_message_trigger_url,
920
+		EE_Registration $registration,
921
+		$messenger = 'html',
922
+		$message_type = 'invoice'
923
+	) {
924
+		// whitelist $messenger
925
+		switch ($messenger) {
926
+			case 'pdf':
927
+				$sending_messenger = 'pdf';
928
+				$generating_messenger = 'html';
929
+				break;
930
+			case 'html':
931
+			default:
932
+				$sending_messenger = 'html';
933
+				$generating_messenger = 'html';
934
+				break;
935
+		}
936
+		// whitelist $message_type
937
+		switch ($message_type) {
938
+			case 'receipt':
939
+				$message_type = 'receipt';
940
+				break;
941
+			case 'invoice':
942
+			default:
943
+				$message_type = 'invoice';
944
+				break;
945
+		}
946
+		// verify that both the messenger AND the message type are active
947
+		if (EEH_MSG_Template::is_messenger_active($sending_messenger)
948
+			&& EEH_MSG_Template::is_mt_active($message_type)
949
+		) {
950
+			// need to get the correct message template group for this (i.e. is there a custom invoice for the event this registration is registered for?)
951
+			$template_query_params = array(
952
+				'MTP_is_active'    => true,
953
+				'MTP_messenger'    => $generating_messenger,
954
+				'MTP_message_type' => $message_type,
955
+				'Event.EVT_ID'     => $registration->event_ID(),
956
+			);
957
+			// get the message template group.
958
+			$msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
959
+			// if we don't have an EE_Message_Template_Group then return
960
+			if (! $msg_template_group instanceof EE_Message_Template_Group) {
961
+				// remove EVT_ID from query params so that global templates get picked up
962
+				unset($template_query_params['Event.EVT_ID']);
963
+				// get global template as the fallback
964
+				$msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
965
+			}
966
+			// if we don't have an EE_Message_Template_Group then return
967
+			if (! $msg_template_group instanceof EE_Message_Template_Group) {
968
+				return '';
969
+			}
970
+			// generate the URL
971
+			$registration_message_trigger_url = EEH_MSG_Template::generate_url_trigger(
972
+				$sending_messenger,
973
+				$generating_messenger,
974
+				'purchaser',
975
+				$message_type,
976
+				$registration,
977
+				$msg_template_group->ID(),
978
+				$registration->transaction_ID()
979
+			);
980
+		}
981
+		return $registration_message_trigger_url;
982
+	}
983
+
984
+
985
+	/**
986
+	 * Use to generate and return a message preview!
987
+	 *
988
+	 * @param  string $type      This should correspond with a valid message type
989
+	 * @param  string $context   This should correspond with a valid context for the message type
990
+	 * @param  string $messenger This should correspond with a valid messenger.
991
+	 * @param bool    $send      true we will do a test send using the messenger delivery, false we just do a regular
992
+	 *                           preview
993
+	 * @return bool|string The body of the message or if send is requested, sends.
994
+	 * @throws EE_Error
995
+	 * @throws InvalidArgumentException
996
+	 * @throws InvalidDataTypeException
997
+	 * @throws InvalidInterfaceException
998
+	 * @throws ReflectionException
999
+	 */
1000
+	public static function preview_message($type, $context, $messenger, $send = false)
1001
+	{
1002
+		self::_load_controller();
1003
+		$mtg = new EE_Message_To_Generate(
1004
+			$messenger,
1005
+			$type,
1006
+			array(),
1007
+			$context,
1008
+			true
1009
+		);
1010
+		$generated_preview_queue = self::$_MSG_PROCESSOR->generate_for_preview($mtg, $send);
1011
+		if ($generated_preview_queue instanceof EE_Messages_Queue) {
1012
+			// loop through all content for the preview and remove any persisted records.
1013
+			$content = '';
1014
+			foreach ($generated_preview_queue->get_message_repository() as $message) {
1015
+				$content = $message->content();
1016
+				if ($message->ID() > 0 && $message->STS_ID() !== EEM_Message::status_failed) {
1017
+					$message->delete();
1018
+				}
1019
+			}
1020
+			return $content;
1021
+		} else {
1022
+			return $generated_preview_queue;
1023
+		}
1024
+	}
1025
+
1026
+
1027
+	/**
1028
+	 * This is a method that allows for sending a message using a messenger matching the string given and the provided
1029
+	 * EE_Message_Queue object.  The EE_Message_Queue object is used to create a single aggregate EE_Message via the
1030
+	 * content found in the EE_Message objects in the queue.
1031
+	 *
1032
+	 * @since 4.9.0
1033
+	 * @param string            $messenger            a string matching a valid active messenger in the system
1034
+	 * @param string            $message_type         Although it seems contrary to the name of the method, a message
1035
+	 *                                                type name is still required to send along the message type to the
1036
+	 *                                                messenger because this is used for determining what specific
1037
+	 *                                                variations might be loaded for the generated message.
1038
+	 * @param EE_Messages_Queue $queue
1039
+	 * @param string            $custom_subject       Can be used to set what the custom subject string will be on the
1040
+	 *                                                aggregate EE_Message object.
1041
+	 * @return bool success or fail.
1042
+	 * @throws EE_Error
1043
+	 * @throws InvalidArgumentException
1044
+	 * @throws ReflectionException
1045
+	 * @throws InvalidDataTypeException
1046
+	 * @throws InvalidInterfaceException
1047
+	 */
1048
+	public static function send_message_with_messenger_only(
1049
+		$messenger,
1050
+		$message_type,
1051
+		EE_Messages_Queue $queue,
1052
+		$custom_subject = ''
1053
+	) {
1054
+		self::_load_controller();
1055
+		/** @type EE_Message_To_Generate_From_Queue $message_to_generate */
1056
+		$message_to_generate = EE_Registry::instance()->load_lib(
1057
+			'Message_To_Generate_From_Queue',
1058
+			array(
1059
+				$messenger,
1060
+				$message_type,
1061
+				$queue,
1062
+				$custom_subject,
1063
+			)
1064
+		);
1065
+		return self::$_MSG_PROCESSOR->queue_for_sending($message_to_generate);
1066
+	}
1067
+
1068
+
1069
+	/**
1070
+	 * Generates Messages immediately for EE_Message IDs (but only for the correct status for generation)
1071
+	 *
1072
+	 * @since 4.9.0
1073
+	 * @param array $message_ids An array of message ids
1074
+	 * @return bool|EE_Messages_Queue false if nothing was generated, EE_Messages_Queue containing generated
1075
+	 *                           messages.
1076
+	 * @throws EE_Error
1077
+	 * @throws InvalidArgumentException
1078
+	 * @throws InvalidDataTypeException
1079
+	 * @throws InvalidInterfaceException
1080
+	 * @throws ReflectionException
1081
+	 */
1082
+	public static function generate_now($message_ids)
1083
+	{
1084
+		self::_load_controller();
1085
+		$messages = EEM_Message::instance()->get_all(
1086
+			array(
1087
+				0 => array(
1088
+					'MSG_ID' => array('IN', $message_ids),
1089
+					'STS_ID' => EEM_Message::status_incomplete,
1090
+				),
1091
+			)
1092
+		);
1093
+		$generated_queue = false;
1094
+		if ($messages) {
1095
+			$generated_queue = self::$_MSG_PROCESSOR->batch_generate_from_queue($messages);
1096
+		}
1097
+
1098
+		if (! $generated_queue instanceof EE_Messages_Queue) {
1099
+			EE_Error::add_error(
1100
+				__(
1101
+					'The messages were not generated. This could mean there is already a batch being generated on a separate request, or because the selected messages are not ready for generation. Please wait a minute or two and try again.',
1102
+					'event_espresso'
1103
+				),
1104
+				__FILE__,
1105
+				__FUNCTION__,
1106
+				__LINE__
1107
+			);
1108
+		}
1109
+		return $generated_queue;
1110
+	}
1111
+
1112
+
1113
+	/**
1114
+	 * Sends messages immediately for the incoming message_ids that have the status of EEM_Message::status_resend or,
1115
+	 * EEM_Message::status_idle
1116
+	 *
1117
+	 * @since 4.9.0
1118
+	 * @param $message_ids
1119
+	 * @return bool|EE_Messages_Queue false if no messages sent.
1120
+	 * @throws EE_Error
1121
+	 * @throws InvalidArgumentException
1122
+	 * @throws InvalidDataTypeException
1123
+	 * @throws InvalidInterfaceException
1124
+	 * @throws ReflectionException
1125
+	 */
1126
+	public static function send_now($message_ids)
1127
+	{
1128
+		self::_load_controller();
1129
+		$messages = EEM_Message::instance()->get_all(
1130
+			array(
1131
+				0 => array(
1132
+					'MSG_ID' => array('IN', $message_ids),
1133
+					'STS_ID' => array(
1134
+						'IN',
1135
+						array(EEM_Message::status_idle, EEM_Message::status_resend, EEM_Message::status_retry),
1136
+					),
1137
+				),
1138
+			)
1139
+		);
1140
+		$sent_queue = false;
1141
+		if ($messages) {
1142
+			$sent_queue = self::$_MSG_PROCESSOR->batch_send_from_queue($messages);
1143
+		}
1144
+
1145
+		if (! $sent_queue instanceof EE_Messages_Queue) {
1146
+			EE_Error::add_error(
1147
+				__(
1148
+					'The messages were not sent. This could mean there is already a batch being sent on a separate request, or because the selected messages are not sendable. Please wait a minute or two and try again.',
1149
+					'event_espresso'
1150
+				),
1151
+				__FILE__,
1152
+				__FUNCTION__,
1153
+				__LINE__
1154
+			);
1155
+		} else {
1156
+			// can count how many sent by using the messages in the queue
1157
+			$sent_count = $sent_queue->count_STS_in_queue(EEM_Message::instance()->stati_indicating_sent());
1158
+			if ($sent_count > 0) {
1159
+				EE_Error::add_success(
1160
+					sprintf(
1161
+						_n(
1162
+							'There was %d message successfully sent.',
1163
+							'There were %d messages successfully sent.',
1164
+							$sent_count,
1165
+							'event_espresso'
1166
+						),
1167
+						$sent_count
1168
+					)
1169
+				);
1170
+			} else {
1171
+				EE_Error::overwrite_errors();
1172
+				EE_Error::add_error(
1173
+					__(
1174
+						'No message was sent because of problems with sending. Either all the messages you selected were not a sendable message, they were ALREADY sent on a different scheduled task, or there was an error.
1175 1175
 					If there was an error, you can look at the messages in the message activity list table for any error messages.',
1176
-                        'event_espresso'
1177
-                    ),
1178
-                    __FILE__,
1179
-                    __FUNCTION__,
1180
-                    __LINE__
1181
-                );
1182
-            }
1183
-        }
1184
-        return $sent_queue;
1185
-    }
1186
-
1187
-
1188
-    /**
1189
-     * Generate and send immediately from the given $message_ids
1190
-     *
1191
-     * @param array $message_ids EE_Message entity ids.
1192
-     * @throws EE_Error
1193
-     * @throws InvalidArgumentException
1194
-     * @throws InvalidDataTypeException
1195
-     * @throws InvalidInterfaceException
1196
-     * @throws ReflectionException
1197
-     */
1198
-    public static function generate_and_send_now(array $message_ids)
1199
-    {
1200
-        $generated_queue = self::generate_now($message_ids);
1201
-        // now let's just trigger sending immediately from this queue.
1202
-        $messages_sent = $generated_queue instanceof EE_Messages_Queue
1203
-            ? $generated_queue->execute()
1204
-            : 0;
1205
-        if ($messages_sent) {
1206
-            EE_Error::add_success(
1207
-                esc_html(
1208
-                    sprintf(
1209
-                        _n(
1210
-                            'There was %d message successfully generated and sent.',
1211
-                            'There were %d messages successfully generated and sent.',
1212
-                            $messages_sent,
1213
-                            'event_espresso'
1214
-                        ),
1215
-                        $messages_sent
1216
-                    )
1217
-                )
1218
-            );
1219
-            // errors would be added via the generate_now method.
1220
-        }
1221
-    }
1222
-
1223
-
1224
-    /**
1225
-     * This will queue the incoming message ids for resending.
1226
-     * Note, only message_ids corresponding to messages with the status of EEM_Message::sent will be queued.
1227
-     *
1228
-     * @since 4.9.0
1229
-     * @param array $message_ids An array of EE_Message IDs
1230
-     * @return bool true means messages were successfully queued for resending, false means none were queued for
1231
-     *                           resending.
1232
-     * @throws EE_Error
1233
-     * @throws InvalidArgumentException
1234
-     * @throws InvalidDataTypeException
1235
-     * @throws InvalidInterfaceException
1236
-     * @throws ReflectionException
1237
-     */
1238
-    public static function queue_for_resending($message_ids)
1239
-    {
1240
-        self::_load_controller();
1241
-        self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send($message_ids);
1242
-
1243
-        // get queue and count
1244
-        $queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
1245
-
1246
-        if ($queue_count > 0
1247
-        ) {
1248
-            EE_Error::add_success(
1249
-                sprintf(
1250
-                    _n(
1251
-                        '%d message successfully queued for resending.',
1252
-                        '%d messages successfully queued for resending.',
1253
-                        $queue_count,
1254
-                        'event_espresso'
1255
-                    ),
1256
-                    $queue_count
1257
-                )
1258
-            );
1259
-            /**
1260
-             * @see filter usage in EE_Messages_Queue::initiate_request_by_priority
1261
-             */
1262
-        } elseif (apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', true)
1263
-            || EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
1264
-        ) {
1265
-            $queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_sent);
1266
-            if ($queue_count > 0) {
1267
-                EE_Error::add_success(
1268
-                    sprintf(
1269
-                        _n(
1270
-                            '%d message successfully sent.',
1271
-                            '%d messages successfully sent.',
1272
-                            $queue_count,
1273
-                            'event_espresso'
1274
-                        ),
1275
-                        $queue_count
1276
-                    )
1277
-                );
1278
-            } else {
1279
-                EE_Error::add_error(
1280
-                    __(
1281
-                        'No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1282
-                        'event_espresso'
1283
-                    ),
1284
-                    __FILE__,
1285
-                    __FUNCTION__,
1286
-                    __LINE__
1287
-                );
1288
-            }
1289
-        } else {
1290
-            EE_Error::add_error(
1291
-                __(
1292
-                    'No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1293
-                    'event_espresso'
1294
-                ),
1295
-                __FILE__,
1296
-                __FUNCTION__,
1297
-                __LINE__
1298
-            );
1299
-        }
1300
-        return (bool) $queue_count;
1301
-    }
1302
-
1303
-
1304
-    /**
1305
-     * debug
1306
-     *
1307
-     * @param string          $class
1308
-     * @param string          $func
1309
-     * @param string          $line
1310
-     * @param \EE_Transaction $transaction
1311
-     * @param array           $info
1312
-     * @param bool            $display_request
1313
-     * @throws EE_Error
1314
-     * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
1315
-     */
1316
-    protected static function log(
1317
-        $class = '',
1318
-        $func = '',
1319
-        $line = '',
1320
-        EE_Transaction $transaction,
1321
-        $info = array(),
1322
-        $display_request = false
1323
-    ) {
1324
-        if (defined('EE_DEBUG') && EE_DEBUG) {
1325
-            if ($transaction instanceof EE_Transaction) {
1326
-                // don't serialize objects
1327
-                $info = EEH_Debug_Tools::strip_objects($info);
1328
-                $info['TXN_status'] = $transaction->status_ID();
1329
-                $info['TXN_reg_steps'] = $transaction->reg_steps();
1330
-                if ($transaction->ID()) {
1331
-                    $index = 'EE_Transaction: ' . $transaction->ID();
1332
-                    EEH_Debug_Tools::log($class, $func, $line, $info, $display_request, $index);
1333
-                }
1334
-            }
1335
-        }
1336
-    }
1337
-
1338
-
1339
-    /**
1340
-     *  Resets all the static properties in this class when called.
1341
-     */
1342
-    public static function reset()
1343
-    {
1344
-        self::$_EEMSG = null;
1345
-        self::$_message_resource_manager = null;
1346
-        self::$_MSG_PROCESSOR = null;
1347
-        self::$_MSG_PATHS = null;
1348
-        self::$_TMP_PACKS = array();
1349
-    }
1176
+						'event_espresso'
1177
+					),
1178
+					__FILE__,
1179
+					__FUNCTION__,
1180
+					__LINE__
1181
+				);
1182
+			}
1183
+		}
1184
+		return $sent_queue;
1185
+	}
1186
+
1187
+
1188
+	/**
1189
+	 * Generate and send immediately from the given $message_ids
1190
+	 *
1191
+	 * @param array $message_ids EE_Message entity ids.
1192
+	 * @throws EE_Error
1193
+	 * @throws InvalidArgumentException
1194
+	 * @throws InvalidDataTypeException
1195
+	 * @throws InvalidInterfaceException
1196
+	 * @throws ReflectionException
1197
+	 */
1198
+	public static function generate_and_send_now(array $message_ids)
1199
+	{
1200
+		$generated_queue = self::generate_now($message_ids);
1201
+		// now let's just trigger sending immediately from this queue.
1202
+		$messages_sent = $generated_queue instanceof EE_Messages_Queue
1203
+			? $generated_queue->execute()
1204
+			: 0;
1205
+		if ($messages_sent) {
1206
+			EE_Error::add_success(
1207
+				esc_html(
1208
+					sprintf(
1209
+						_n(
1210
+							'There was %d message successfully generated and sent.',
1211
+							'There were %d messages successfully generated and sent.',
1212
+							$messages_sent,
1213
+							'event_espresso'
1214
+						),
1215
+						$messages_sent
1216
+					)
1217
+				)
1218
+			);
1219
+			// errors would be added via the generate_now method.
1220
+		}
1221
+	}
1222
+
1223
+
1224
+	/**
1225
+	 * This will queue the incoming message ids for resending.
1226
+	 * Note, only message_ids corresponding to messages with the status of EEM_Message::sent will be queued.
1227
+	 *
1228
+	 * @since 4.9.0
1229
+	 * @param array $message_ids An array of EE_Message IDs
1230
+	 * @return bool true means messages were successfully queued for resending, false means none were queued for
1231
+	 *                           resending.
1232
+	 * @throws EE_Error
1233
+	 * @throws InvalidArgumentException
1234
+	 * @throws InvalidDataTypeException
1235
+	 * @throws InvalidInterfaceException
1236
+	 * @throws ReflectionException
1237
+	 */
1238
+	public static function queue_for_resending($message_ids)
1239
+	{
1240
+		self::_load_controller();
1241
+		self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send($message_ids);
1242
+
1243
+		// get queue and count
1244
+		$queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
1245
+
1246
+		if ($queue_count > 0
1247
+		) {
1248
+			EE_Error::add_success(
1249
+				sprintf(
1250
+					_n(
1251
+						'%d message successfully queued for resending.',
1252
+						'%d messages successfully queued for resending.',
1253
+						$queue_count,
1254
+						'event_espresso'
1255
+					),
1256
+					$queue_count
1257
+				)
1258
+			);
1259
+			/**
1260
+			 * @see filter usage in EE_Messages_Queue::initiate_request_by_priority
1261
+			 */
1262
+		} elseif (apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', true)
1263
+			|| EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
1264
+		) {
1265
+			$queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_sent);
1266
+			if ($queue_count > 0) {
1267
+				EE_Error::add_success(
1268
+					sprintf(
1269
+						_n(
1270
+							'%d message successfully sent.',
1271
+							'%d messages successfully sent.',
1272
+							$queue_count,
1273
+							'event_espresso'
1274
+						),
1275
+						$queue_count
1276
+					)
1277
+				);
1278
+			} else {
1279
+				EE_Error::add_error(
1280
+					__(
1281
+						'No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1282
+						'event_espresso'
1283
+					),
1284
+					__FILE__,
1285
+					__FUNCTION__,
1286
+					__LINE__
1287
+				);
1288
+			}
1289
+		} else {
1290
+			EE_Error::add_error(
1291
+				__(
1292
+					'No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1293
+					'event_espresso'
1294
+				),
1295
+				__FILE__,
1296
+				__FUNCTION__,
1297
+				__LINE__
1298
+			);
1299
+		}
1300
+		return (bool) $queue_count;
1301
+	}
1302
+
1303
+
1304
+	/**
1305
+	 * debug
1306
+	 *
1307
+	 * @param string          $class
1308
+	 * @param string          $func
1309
+	 * @param string          $line
1310
+	 * @param \EE_Transaction $transaction
1311
+	 * @param array           $info
1312
+	 * @param bool            $display_request
1313
+	 * @throws EE_Error
1314
+	 * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
1315
+	 */
1316
+	protected static function log(
1317
+		$class = '',
1318
+		$func = '',
1319
+		$line = '',
1320
+		EE_Transaction $transaction,
1321
+		$info = array(),
1322
+		$display_request = false
1323
+	) {
1324
+		if (defined('EE_DEBUG') && EE_DEBUG) {
1325
+			if ($transaction instanceof EE_Transaction) {
1326
+				// don't serialize objects
1327
+				$info = EEH_Debug_Tools::strip_objects($info);
1328
+				$info['TXN_status'] = $transaction->status_ID();
1329
+				$info['TXN_reg_steps'] = $transaction->reg_steps();
1330
+				if ($transaction->ID()) {
1331
+					$index = 'EE_Transaction: ' . $transaction->ID();
1332
+					EEH_Debug_Tools::log($class, $func, $line, $info, $display_request, $index);
1333
+				}
1334
+			}
1335
+		}
1336
+	}
1337
+
1338
+
1339
+	/**
1340
+	 *  Resets all the static properties in this class when called.
1341
+	 */
1342
+	public static function reset()
1343
+	{
1344
+		self::$_EEMSG = null;
1345
+		self::$_message_resource_manager = null;
1346
+		self::$_MSG_PROCESSOR = null;
1347
+		self::$_MSG_PATHS = null;
1348
+		self::$_TMP_PACKS = array();
1349
+	}
1350 1350
 }
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +80 added lines, -80 removed lines patch added patch discarded remove patch
@@ -38,103 +38,103 @@
 block discarded – undo
38 38
  * @since           4.0
39 39
  */
40 40
 if (function_exists('espresso_version')) {
41
-    if (! function_exists('espresso_duplicate_plugin_error')) {
42
-        /**
43
-         *    espresso_duplicate_plugin_error
44
-         *    displays if more than one version of EE is activated at the same time
45
-         */
46
-        function espresso_duplicate_plugin_error()
47
-        {
48
-            ?>
41
+	if (! function_exists('espresso_duplicate_plugin_error')) {
42
+		/**
43
+		 *    espresso_duplicate_plugin_error
44
+		 *    displays if more than one version of EE is activated at the same time
45
+		 */
46
+		function espresso_duplicate_plugin_error()
47
+		{
48
+			?>
49 49
             <div class="error">
50 50
                 <p>
51 51
                     <?php
52
-                    echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                    ); ?>
52
+					echo esc_html__(
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+					); ?>
56 56
                 </p>
57 57
             </div>
58 58
             <?php
59
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-        }
61
-    }
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
59
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+		}
61
+	}
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 } else {
64
-    define('EE_MIN_PHP_VER_REQUIRED', '5.4.0');
65
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
-        /**
67
-         * espresso_minimum_php_version_error
68
-         *
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
64
+	define('EE_MIN_PHP_VER_REQUIRED', '5.4.0');
65
+	if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+		/**
67
+		 * espresso_minimum_php_version_error
68
+		 *
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                        esc_html__(
79
-                            'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. 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.',
80
-                            'event_espresso'
81
-                        ),
82
-                        EE_MIN_PHP_VER_REQUIRED,
83
-                        PHP_VERSION,
84
-                        '<br/>',
85
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+						esc_html__(
79
+							'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. 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.',
80
+							'event_espresso'
81
+						),
82
+						EE_MIN_PHP_VER_REQUIRED,
83
+						PHP_VERSION,
84
+						'<br/>',
85
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
-        /**
98
-         * espresso_version
99
-         * Returns the plugin version
100
-         *
101
-         * @return string
102
-         */
103
-        function espresso_version()
104
-        {
105
-            return apply_filters('FHEE__espresso__espresso_version', '4.9.68.rc.008');
106
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
+		/**
98
+		 * espresso_version
99
+		 * Returns the plugin version
100
+		 *
101
+		 * @return string
102
+		 */
103
+		function espresso_version()
104
+		{
105
+			return apply_filters('FHEE__espresso__espresso_version', '4.9.68.rc.008');
106
+		}
107 107
 
108
-        /**
109
-         * espresso_plugin_activation
110
-         * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
111
-         */
112
-        function espresso_plugin_activation()
113
-        {
114
-            update_option('ee_espresso_activation', true);
115
-        }
108
+		/**
109
+		 * espresso_plugin_activation
110
+		 * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
111
+		 */
112
+		function espresso_plugin_activation()
113
+		{
114
+			update_option('ee_espresso_activation', true);
115
+		}
116 116
 
117
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
117
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
118 118
 
119
-        require_once __DIR__ . '/core/bootstrap_espresso.php';
120
-        bootstrap_espresso();
121
-    }
119
+		require_once __DIR__ . '/core/bootstrap_espresso.php';
120
+		bootstrap_espresso();
121
+	}
122 122
 }
123 123
 if (! function_exists('espresso_deactivate_plugin')) {
124
-    /**
125
-     *    deactivate_plugin
126
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
127
-     *
128
-     * @access public
129
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
130
-     * @return    void
131
-     */
132
-    function espresso_deactivate_plugin($plugin_basename = '')
133
-    {
134
-        if (! function_exists('deactivate_plugins')) {
135
-            require_once ABSPATH . 'wp-admin/includes/plugin.php';
136
-        }
137
-        unset($_GET['activate'], $_REQUEST['activate']);
138
-        deactivate_plugins($plugin_basename);
139
-    }
124
+	/**
125
+	 *    deactivate_plugin
126
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
127
+	 *
128
+	 * @access public
129
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
130
+	 * @return    void
131
+	 */
132
+	function espresso_deactivate_plugin($plugin_basename = '')
133
+	{
134
+		if (! function_exists('deactivate_plugins')) {
135
+			require_once ABSPATH . 'wp-admin/includes/plugin.php';
136
+		}
137
+		unset($_GET['activate'], $_REQUEST['activate']);
138
+		deactivate_plugins($plugin_basename);
139
+	}
140 140
 }
Please login to merge, or discard this patch.
core/EE_Session.core.php 2 patches
Indentation   +1261 added lines, -1261 removed lines patch added patch discarded remove patch
@@ -25,1259 +25,1259 @@  discard block
 block discarded – undo
25 25
 class EE_Session implements SessionIdentifierInterface
26 26
 {
27 27
 
28
-    const session_id_prefix = 'ee_ssn_';
29
-
30
-    const hash_check_prefix = 'ee_shc_';
31
-
32
-    const OPTION_NAME_SETTINGS = 'ee_session_settings';
33
-
34
-    const STATUS_CLOSED = 0;
35
-
36
-    const STATUS_OPEN = 1;
37
-
38
-    /**
39
-     * instance of the EE_Session object
40
-     *
41
-     * @var EE_Session
42
-     */
43
-    private static $_instance;
44
-
45
-    /**
46
-     * @var CacheStorageInterface $cache_storage
47
-     */
48
-    protected $cache_storage;
49
-
50
-    /**
51
-     * @var EE_Encryption $encryption
52
-     */
53
-    protected $encryption;
54
-
55
-    /**
56
-     * @var SessionStartHandler $session_start_handler
57
-     */
58
-    protected $session_start_handler;
59
-
60
-    /**
61
-     * the session id
62
-     *
63
-     * @var string
64
-     */
65
-    private $_sid;
66
-
67
-    /**
68
-     * session id salt
69
-     *
70
-     * @var string
71
-     */
72
-    private $_sid_salt;
73
-
74
-    /**
75
-     * session data
76
-     *
77
-     * @var array
78
-     */
79
-    private $_session_data = array();
80
-
81
-    /**
82
-     * how long an EE session lasts
83
-     * default session lifespan of 1 hour (for not so instant IPNs)
84
-     *
85
-     * @var SessionLifespan $session_lifespan
86
-     */
87
-    private $session_lifespan;
88
-
89
-    /**
90
-     * session expiration time as Unix timestamp in GMT
91
-     *
92
-     * @var int
93
-     */
94
-    private $_expiration;
95
-
96
-    /**
97
-     * whether or not session has expired at some point
98
-     *
99
-     * @var boolean
100
-     */
101
-    private $_expired = false;
102
-
103
-    /**
104
-     * current time as Unix timestamp in GMT
105
-     *
106
-     * @var int
107
-     */
108
-    private $_time;
109
-
110
-    /**
111
-     * whether to encrypt session data
112
-     *
113
-     * @var bool
114
-     */
115
-    private $_use_encryption;
116
-
117
-    /**
118
-     * well... according to the server...
119
-     *
120
-     * @var null
121
-     */
122
-    private $_user_agent;
123
-
124
-    /**
125
-     * do you really trust the server ?
126
-     *
127
-     * @var null
128
-     */
129
-    private $_ip_address;
130
-
131
-    /**
132
-     * current WP user_id
133
-     *
134
-     * @var null
135
-     */
136
-    private $_wp_user_id;
137
-
138
-    /**
139
-     * array for defining default session vars
140
-     *
141
-     * @var array
142
-     */
143
-    private $_default_session_vars = array(
144
-        'id'            => null,
145
-        'user_id'       => null,
146
-        'ip_address'    => null,
147
-        'user_agent'    => null,
148
-        'init_access'   => null,
149
-        'last_access'   => null,
150
-        'expiration'    => null,
151
-        'pages_visited' => array(),
152
-    );
153
-
154
-    /**
155
-     * timestamp for when last garbage collection cycle was performed
156
-     *
157
-     * @var int $_last_gc
158
-     */
159
-    private $_last_gc;
160
-
161
-    /**
162
-     * @var RequestInterface $request
163
-     */
164
-    protected $request;
165
-
166
-    /**
167
-     * whether session is active or not
168
-     *
169
-     * @var int $status
170
-     */
171
-    private $status = EE_Session::STATUS_CLOSED;
172
-
173
-
174
-    /**
175
-     * @singleton method used to instantiate class object
176
-     * @param CacheStorageInterface $cache_storage
177
-     * @param SessionLifespan|null  $lifespan
178
-     * @param RequestInterface      $request
179
-     * @param SessionStartHandler   $session_start_handler
180
-     * @param EE_Encryption         $encryption
181
-     * @return EE_Session
182
-     * @throws InvalidArgumentException
183
-     * @throws InvalidDataTypeException
184
-     * @throws InvalidInterfaceException
185
-     */
186
-    public static function instance(
187
-        CacheStorageInterface $cache_storage = null,
188
-        SessionLifespan $lifespan = null,
189
-        RequestInterface $request = null,
190
-        SessionStartHandler $session_start_handler = null,
191
-        EE_Encryption $encryption = null
192
-    ) {
193
-        // check if class object is instantiated
194
-        // session loading is turned ON by default, but prior to the init hook, can be turned back OFF via:
195
-        // add_filter( 'FHEE_load_EE_Session', '__return_false' );
196
-        if (! self::$_instance instanceof EE_Session && apply_filters('FHEE_load_EE_Session', true)) {
197
-            self::$_instance = new self(
198
-                $cache_storage,
199
-                $lifespan,
200
-                $request,
201
-                $session_start_handler,
202
-                $encryption
203
-            );
204
-        }
205
-        return self::$_instance;
206
-    }
207
-
208
-
209
-    /**
210
-     * protected constructor to prevent direct creation
211
-     *
212
-     * @param CacheStorageInterface $cache_storage
213
-     * @param SessionLifespan       $lifespan
214
-     * @param RequestInterface      $request
215
-     * @param SessionStartHandler   $session_start_handler
216
-     * @param EE_Encryption         $encryption
217
-     * @throws InvalidArgumentException
218
-     * @throws InvalidDataTypeException
219
-     * @throws InvalidInterfaceException
220
-     */
221
-    protected function __construct(
222
-        CacheStorageInterface $cache_storage,
223
-        SessionLifespan $lifespan,
224
-        RequestInterface $request,
225
-        SessionStartHandler $session_start_handler,
226
-        EE_Encryption $encryption = null
227
-    ) {
228
-        // session loading is turned ON by default,
229
-        // but prior to the 'AHEE__EE_System__core_loaded_and_ready' hook
230
-        // (which currently fires on the init hook at priority 9),
231
-        // can be turned back OFF via: add_filter( 'FHEE_load_EE_Session', '__return_false' );
232
-        if (! apply_filters('FHEE_load_EE_Session', true)) {
233
-            return;
234
-        }
235
-        $this->session_start_handler = $session_start_handler;
236
-        $this->session_lifespan = $lifespan;
237
-        $this->request = $request;
238
-        if (! defined('ESPRESSO_SESSION')) {
239
-            define('ESPRESSO_SESSION', true);
240
-        }
241
-        // retrieve session options from db
242
-        $session_settings = (array) get_option(EE_Session::OPTION_NAME_SETTINGS, array());
243
-        if (! empty($session_settings)) {
244
-            // cycle though existing session options
245
-            foreach ($session_settings as $var_name => $session_setting) {
246
-                // set values for class properties
247
-                $var_name = '_' . $var_name;
248
-                $this->{$var_name} = $session_setting;
249
-            }
250
-        }
251
-        $this->cache_storage = $cache_storage;
252
-        // are we using encryption?
253
-        $this->_use_encryption = $encryption instanceof EE_Encryption
254
-                                 && EE_Registry::instance()->CFG->admin->encode_session_data();
255
-        // encrypt data via: $this->encryption->encrypt();
256
-        $this->encryption = $encryption;
257
-        // filter hook allows outside functions/classes/plugins to change default empty cart
258
-        $extra_default_session_vars = apply_filters('FHEE__EE_Session__construct__extra_default_session_vars', array());
259
-        array_merge($this->_default_session_vars, $extra_default_session_vars);
260
-        // apply default session vars
261
-        $this->_set_defaults();
262
-        add_action('AHEE__EE_System__initialize', array($this, 'open_session'));
263
-        // check request for 'clear_session' param
264
-        add_action('AHEE__EE_Request_Handler__construct__complete', array($this, 'wp_loaded'));
265
-        // once everything is all said and done,
266
-        add_action('shutdown', array($this, 'update'), 100);
267
-        add_action('shutdown', array($this, 'garbageCollection'), 1000);
268
-        $this->configure_garbage_collection_filters();
269
-    }
270
-
271
-
272
-    /**
273
-     * @return bool
274
-     * @throws InvalidArgumentException
275
-     * @throws InvalidDataTypeException
276
-     * @throws InvalidInterfaceException
277
-     */
278
-    public static function isLoadedAndActive()
279
-    {
280
-        return did_action('AHEE__EE_System__core_loaded_and_ready')
281
-               && EE_Session::instance() instanceof EE_Session
282
-               && EE_Session::instance()->isActive();
283
-    }
284
-
285
-
286
-    /**
287
-     * @return bool
288
-     */
289
-    public function isActive()
290
-    {
291
-        return $this->status === EE_Session::STATUS_OPEN;
292
-    }
293
-
294
-
295
-    /**
296
-     * @return void
297
-     * @throws EE_Error
298
-     * @throws InvalidArgumentException
299
-     * @throws InvalidDataTypeException
300
-     * @throws InvalidInterfaceException
301
-     * @throws InvalidSessionDataException
302
-     */
303
-    public function open_session()
304
-    {
305
-        // check for existing session and retrieve it from db
306
-        if (! $this->_espresso_session()) {
307
-            // or just start a new one
308
-            $this->_create_espresso_session();
309
-        }
310
-    }
311
-
312
-
313
-    /**
314
-     * @return bool
315
-     */
316
-    public function expired()
317
-    {
318
-        return $this->_expired;
319
-    }
320
-
321
-
322
-    /**
323
-     * @return void
324
-     */
325
-    public function reset_expired()
326
-    {
327
-        $this->_expired = false;
328
-    }
329
-
330
-
331
-    /**
332
-     * @return int
333
-     */
334
-    public function expiration()
335
-    {
336
-        return $this->_expiration;
337
-    }
338
-
339
-
340
-    /**
341
-     * @return int
342
-     */
343
-    public function extension()
344
-    {
345
-        return apply_filters('FHEE__EE_Session__extend_expiration__seconds_added', 10 * MINUTE_IN_SECONDS);
346
-    }
347
-
348
-
349
-    /**
350
-     * @param int $time number of seconds to add to session expiration
351
-     */
352
-    public function extend_expiration($time = 0)
353
-    {
354
-        $time = $time ? $time : $this->extension();
355
-        $this->_expiration += absint($time);
356
-    }
357
-
358
-
359
-    /**
360
-     * @return int
361
-     */
362
-    public function lifespan()
363
-    {
364
-        return $this->session_lifespan->inSeconds();
365
-    }
366
-
367
-
368
-    /**
369
-     * This just sets some defaults for the _session data property
370
-     *
371
-     * @access private
372
-     * @return void
373
-     */
374
-    private function _set_defaults()
375
-    {
376
-        // set some defaults
377
-        foreach ($this->_default_session_vars as $key => $default_var) {
378
-            if (is_array($default_var)) {
379
-                $this->_session_data[ $key ] = array();
380
-            } else {
381
-                $this->_session_data[ $key ] = '';
382
-            }
383
-        }
384
-    }
385
-
386
-
387
-    /**
388
-     * @retrieve  session data
389
-     * @access    public
390
-     * @return    string
391
-     */
392
-    public function id()
393
-    {
394
-        return $this->_sid;
395
-    }
396
-
397
-
398
-    /**
399
-     * @param \EE_Cart $cart
400
-     * @return bool
401
-     */
402
-    public function set_cart(EE_Cart $cart)
403
-    {
404
-        $this->_session_data['cart'] = $cart;
405
-        return true;
406
-    }
407
-
408
-
409
-    /**
410
-     * reset_cart
411
-     */
412
-    public function reset_cart()
413
-    {
414
-        do_action('AHEE__EE_Session__reset_cart__before_reset', $this);
415
-        $this->_session_data['cart'] = null;
416
-    }
417
-
418
-
419
-    /**
420
-     * @return \EE_Cart
421
-     */
422
-    public function cart()
423
-    {
424
-        return isset($this->_session_data['cart']) && $this->_session_data['cart'] instanceof EE_Cart
425
-            ? $this->_session_data['cart']
426
-            : null;
427
-    }
428
-
429
-
430
-    /**
431
-     * @param \EE_Checkout $checkout
432
-     * @return bool
433
-     */
434
-    public function set_checkout(EE_Checkout $checkout)
435
-    {
436
-        $this->_session_data['checkout'] = $checkout;
437
-        return true;
438
-    }
439
-
440
-
441
-    /**
442
-     * reset_checkout
443
-     */
444
-    public function reset_checkout()
445
-    {
446
-        do_action('AHEE__EE_Session__reset_checkout__before_reset', $this);
447
-        $this->_session_data['checkout'] = null;
448
-    }
449
-
450
-
451
-    /**
452
-     * @return \EE_Checkout
453
-     */
454
-    public function checkout()
455
-    {
456
-        return isset($this->_session_data['checkout']) && $this->_session_data['checkout'] instanceof EE_Checkout
457
-            ? $this->_session_data['checkout']
458
-            : null;
459
-    }
460
-
461
-
462
-    /**
463
-     * @param \EE_Transaction $transaction
464
-     * @return bool
465
-     * @throws EE_Error
466
-     */
467
-    public function set_transaction(EE_Transaction $transaction)
468
-    {
469
-        // first remove the session from the transaction before we save the transaction in the session
470
-        $transaction->set_txn_session_data(null);
471
-        $this->_session_data['transaction'] = $transaction;
472
-        return true;
473
-    }
474
-
475
-
476
-    /**
477
-     * reset_transaction
478
-     */
479
-    public function reset_transaction()
480
-    {
481
-        do_action('AHEE__EE_Session__reset_transaction__before_reset', $this);
482
-        $this->_session_data['transaction'] = null;
483
-    }
484
-
485
-
486
-    /**
487
-     * @return \EE_Transaction
488
-     */
489
-    public function transaction()
490
-    {
491
-        return isset($this->_session_data['transaction'])
492
-               && $this->_session_data['transaction'] instanceof EE_Transaction
493
-            ? $this->_session_data['transaction']
494
-            : null;
495
-    }
496
-
497
-
498
-    /**
499
-     * retrieve session data
500
-     *
501
-     * @param null $key
502
-     * @param bool $reset_cache
503
-     * @return array
504
-     */
505
-    public function get_session_data($key = null, $reset_cache = false)
506
-    {
507
-        if ($reset_cache) {
508
-            $this->reset_cart();
509
-            $this->reset_checkout();
510
-            $this->reset_transaction();
511
-        }
512
-        if (! empty($key)) {
513
-            return isset($this->_session_data[ $key ]) ? $this->_session_data[ $key ] : null;
514
-        }
515
-        return $this->_session_data;
516
-    }
517
-
518
-
519
-    /**
520
-     * Returns TRUE on success, FALSE on fail
521
-     *
522
-     * @param array $data
523
-     * @return bool
524
-     */
525
-    public function set_session_data($data)
526
-    {
527
-        // nothing ??? bad data ??? go home!
528
-        if (empty($data) || ! is_array($data)) {
529
-            EE_Error::add_error(
530
-                esc_html__(
531
-                    'No session data or invalid session data was provided.',
532
-                    'event_espresso'
533
-                ),
534
-                __FILE__,
535
-                __FUNCTION__,
536
-                __LINE__
537
-            );
538
-            return false;
539
-        }
540
-        foreach ($data as $key => $value) {
541
-            if (isset($this->_default_session_vars[ $key ])) {
542
-                EE_Error::add_error(
543
-                    sprintf(
544
-                        esc_html__(
545
-                            'Sorry! %s is a default session datum and can not be reset.',
546
-                            'event_espresso'
547
-                        ),
548
-                        $key
549
-                    ),
550
-                    __FILE__,
551
-                    __FUNCTION__,
552
-                    __LINE__
553
-                );
554
-                return false;
555
-            }
556
-            $this->_session_data[ $key ] = $value;
557
-        }
558
-        return true;
559
-    }
560
-
561
-
562
-    /**
563
-     * @initiate session
564
-     * @access   private
565
-     * @return TRUE on success, FALSE on fail
566
-     * @throws EE_Error
567
-     * @throws InvalidArgumentException
568
-     * @throws InvalidDataTypeException
569
-     * @throws InvalidInterfaceException
570
-     * @throws InvalidSessionDataException
571
-     */
572
-    private function _espresso_session()
573
-    {
574
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
575
-        $this->session_start_handler->startSession();
576
-        $this->status = EE_Session::STATUS_OPEN;
577
-        // get our modified session ID
578
-        $this->_sid = $this->_generate_session_id();
579
-        // and the visitors IP
580
-        $this->_ip_address = $this->request->ipAddress();
581
-        // set the "user agent"
582
-        $this->_user_agent = $this->request->userAgent();
583
-        // now let's retrieve what's in the db
584
-        $session_data = $this->_retrieve_session_data();
585
-        if (! empty($session_data)) {
586
-            // get the current time in UTC
587
-            $this->_time = $this->_time !== null ? $this->_time : time();
588
-            // and reset the session expiration
589
-            $this->_expiration = isset($session_data['expiration'])
590
-                ? $session_data['expiration']
591
-                : $this->_time + $this->session_lifespan->inSeconds();
592
-        } else {
593
-            // set initial site access time and the session expiration
594
-            $this->_set_init_access_and_expiration();
595
-            // set referer
596
-            $this->_session_data['pages_visited'][ $this->_session_data['init_access'] ] = isset($_SERVER['HTTP_REFERER'])
597
-                ? esc_attr($_SERVER['HTTP_REFERER'])
598
-                : '';
599
-            // no previous session = go back and create one (on top of the data above)
600
-            return false;
601
-        }
602
-        // now the user agent
603
-        if ($session_data['user_agent'] !== $this->_user_agent) {
604
-            return false;
605
-        }
606
-        // wait a minute... how old are you?
607
-        if ($this->_time > $this->_expiration) {
608
-            // yer too old fer me!
609
-            $this->_expired = true;
610
-            // wipe out everything that isn't a default session datum
611
-            $this->clear_session(__CLASS__, __FUNCTION__);
612
-        }
613
-        // make event espresso session data available to plugin
614
-        $this->_session_data = array_merge($this->_session_data, $session_data);
615
-        return true;
616
-    }
617
-
618
-
619
-    /**
620
-     * _get_session_data
621
-     * Retrieves the session data, and attempts to correct any encoding issues that can occur due to improperly setup
622
-     * databases
623
-     *
624
-     * @return array
625
-     * @throws EE_Error
626
-     * @throws InvalidArgumentException
627
-     * @throws InvalidSessionDataException
628
-     * @throws InvalidDataTypeException
629
-     * @throws InvalidInterfaceException
630
-     */
631
-    protected function _retrieve_session_data()
632
-    {
633
-        $ssn_key = EE_Session::session_id_prefix . $this->_sid;
634
-        try {
635
-            // we're using WP's Transient API to store session data using the PHP session ID as the option name
636
-            $session_data = $this->cache_storage->get($ssn_key, false);
637
-            if (empty($session_data)) {
638
-                return array();
639
-            }
640
-            if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
641
-                $hash_check = $this->cache_storage->get(
642
-                    EE_Session::hash_check_prefix . $this->_sid,
643
-                    false
644
-                );
645
-                if ($hash_check && $hash_check !== md5($session_data)) {
646
-                    EE_Error::add_error(
647
-                        sprintf(
648
-                            __(
649
-                                'The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.',
650
-                                'event_espresso'
651
-                            ),
652
-                            EE_Session::session_id_prefix . $this->_sid
653
-                        ),
654
-                        __FILE__,
655
-                        __FUNCTION__,
656
-                        __LINE__
657
-                    );
658
-                }
659
-            }
660
-        } catch (Exception $e) {
661
-            // let's just eat that error for now and attempt to correct any corrupted data
662
-            global $wpdb;
663
-            $row = $wpdb->get_row(
664
-                $wpdb->prepare(
665
-                    "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
666
-                    '_transient_' . $ssn_key
667
-                )
668
-            );
669
-            $session_data = is_object($row) ? $row->option_value : null;
670
-            if ($session_data) {
671
-                $session_data = preg_replace_callback(
672
-                    '!s:(d+):"(.*?)";!',
673
-                    function ($match) {
674
-                        return $match[1] === strlen($match[2])
675
-                            ? $match[0]
676
-                            : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
677
-                    },
678
-                    $session_data
679
-                );
680
-            }
681
-            $session_data = maybe_unserialize($session_data);
682
-        }
683
-        // in case the data is encoded... try to decode it
684
-        $session_data = $this->encryption instanceof EE_Encryption
685
-            ? $this->encryption->base64_string_decode($session_data)
686
-            : $session_data;
687
-        if (! is_array($session_data)) {
688
-            try {
689
-                $session_data = maybe_unserialize($session_data);
690
-            } catch (Exception $e) {
691
-                $msg = esc_html__(
692
-                    'An error occurred while attempting to unserialize the session data.',
693
-                    'event_espresso'
694
-                );
695
-                $msg .= WP_DEBUG
696
-                    ? '<br><pre>'
697
-                      . print_r($session_data, true)
698
-                      . '</pre><br>'
699
-                      . $this->find_serialize_error($session_data)
700
-                    : '';
701
-                $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
702
-                throw new InvalidSessionDataException($msg, 0, $e);
703
-            }
704
-        }
705
-        // just a check to make sure the session array is indeed an array
706
-        if (! is_array($session_data)) {
707
-            // no?!?! then something is wrong
708
-            $msg = esc_html__(
709
-                'The session data is missing, invalid, or corrupted.',
710
-                'event_espresso'
711
-            );
712
-            $msg .= WP_DEBUG
713
-                ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
714
-                : '';
715
-            $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
716
-            throw new InvalidSessionDataException($msg);
717
-        }
718
-        if (isset($session_data['transaction']) && absint($session_data['transaction']) !== 0) {
719
-            $session_data['transaction'] = EEM_Transaction::instance()->get_one_by_ID(
720
-                $session_data['transaction']
721
-            );
722
-        }
723
-        return $session_data;
724
-    }
725
-
726
-
727
-    /**
728
-     * _generate_session_id
729
-     * Retrieves the PHP session id either directly from the PHP session,
730
-     * or from the $_REQUEST array if it was passed in from an AJAX request.
731
-     * The session id is then salted and hashed (mmm sounds tasty)
732
-     * so that it can be safely used as a $_REQUEST param
733
-     *
734
-     * @return string
735
-     */
736
-    protected function _generate_session_id()
737
-    {
738
-        // check if the SID was passed explicitly, otherwise get from session, then add salt and hash it to reduce length
739
-        if (isset($_REQUEST['EESID'])) {
740
-            $session_id = sanitize_text_field($_REQUEST['EESID']);
741
-        } else {
742
-            $session_id = md5(session_id() . get_current_blog_id() . $this->_get_sid_salt());
743
-        }
744
-        return apply_filters('FHEE__EE_Session___generate_session_id__session_id', $session_id);
745
-    }
746
-
747
-
748
-    /**
749
-     * _get_sid_salt
750
-     *
751
-     * @return string
752
-     */
753
-    protected function _get_sid_salt()
754
-    {
755
-        // was session id salt already saved to db ?
756
-        if (empty($this->_sid_salt)) {
757
-            // no?  then maybe use WP defined constant
758
-            if (defined('AUTH_SALT')) {
759
-                $this->_sid_salt = AUTH_SALT;
760
-            }
761
-            // if salt doesn't exist or is too short
762
-            if (strlen($this->_sid_salt) < 32) {
763
-                // create a new one
764
-                $this->_sid_salt = wp_generate_password(64);
765
-            }
766
-            // and save it as a permanent session setting
767
-            $this->updateSessionSettings(array('sid_salt' => $this->_sid_salt));
768
-        }
769
-        return $this->_sid_salt;
770
-    }
771
-
772
-
773
-    /**
774
-     * _set_init_access_and_expiration
775
-     *
776
-     * @return void
777
-     */
778
-    protected function _set_init_access_and_expiration()
779
-    {
780
-        $this->_time = time();
781
-        $this->_expiration = $this->_time + $this->session_lifespan->inSeconds();
782
-        // set initial site access time
783
-        $this->_session_data['init_access'] = $this->_time;
784
-        // and the session expiration
785
-        $this->_session_data['expiration'] = $this->_expiration;
786
-    }
787
-
788
-
789
-    /**
790
-     * @update session data  prior to saving to the db
791
-     * @access public
792
-     * @param bool $new_session
793
-     * @return TRUE on success, FALSE on fail
794
-     * @throws EE_Error
795
-     * @throws InvalidArgumentException
796
-     * @throws InvalidDataTypeException
797
-     * @throws InvalidInterfaceException
798
-     */
799
-    public function update($new_session = false)
800
-    {
801
-        $this->_session_data = $this->_session_data !== null
802
-                               && is_array($this->_session_data)
803
-                               && isset($this->_session_data['id'])
804
-            ? $this->_session_data
805
-            : array();
806
-        if (empty($this->_session_data)) {
807
-            $this->_set_defaults();
808
-        }
809
-        $session_data = array();
810
-        foreach ($this->_session_data as $key => $value) {
811
-            switch ($key) {
812
-                case 'id':
813
-                    // session ID
814
-                    $session_data['id'] = $this->_sid;
815
-                    break;
816
-                case 'ip_address':
817
-                    // visitor ip address
818
-                    $session_data['ip_address'] = $this->request->ipAddress();
819
-                    break;
820
-                case 'user_agent':
821
-                    // visitor user_agent
822
-                    $session_data['user_agent'] = $this->_user_agent;
823
-                    break;
824
-                case 'init_access':
825
-                    $session_data['init_access'] = absint($value);
826
-                    break;
827
-                case 'last_access':
828
-                    // current access time
829
-                    $session_data['last_access'] = $this->_time;
830
-                    break;
831
-                case 'expiration':
832
-                    // when the session expires
833
-                    $session_data['expiration'] = ! empty($this->_expiration)
834
-                        ? $this->_expiration
835
-                        : $session_data['init_access'] + $this->session_lifespan->inSeconds();
836
-                    break;
837
-                case 'user_id':
838
-                    // current user if logged in
839
-                    $session_data['user_id'] = $this->_wp_user_id();
840
-                    break;
841
-                case 'pages_visited':
842
-                    $page_visit = $this->_get_page_visit();
843
-                    if ($page_visit) {
844
-                        // set pages visited where the first will be the http referrer
845
-                        $this->_session_data['pages_visited'][ $this->_time ] = $page_visit;
846
-                        // we'll only save the last 10 page visits.
847
-                        $session_data['pages_visited'] = array_slice($this->_session_data['pages_visited'], -10);
848
-                    }
849
-                    break;
850
-                default:
851
-                    // carry any other data over
852
-                    $session_data[ $key ] = $this->_session_data[ $key ];
853
-            }
854
-        }
855
-        $this->_session_data = $session_data;
856
-        // creating a new session does not require saving to the db just yet
857
-        if (! $new_session) {
858
-            // ready? let's save
859
-            if ($this->_save_session_to_db()) {
860
-                return true;
861
-            }
862
-            return false;
863
-        }
864
-        // meh, why not?
865
-        return true;
866
-    }
867
-
868
-
869
-    /**
870
-     * @create session data array
871
-     * @access public
872
-     * @return bool
873
-     * @throws EE_Error
874
-     * @throws InvalidArgumentException
875
-     * @throws InvalidDataTypeException
876
-     * @throws InvalidInterfaceException
877
-     */
878
-    private function _create_espresso_session()
879
-    {
880
-        do_action('AHEE_log', __CLASS__, __FUNCTION__, '');
881
-        // use the update function for now with $new_session arg set to TRUE
882
-        return $this->update(true) ? true : false;
883
-    }
884
-
885
-    /**
886
-     * Detects if there is anything worth saving in the session (eg the cart is a good one, notices are pretty good
887
-     * too). This is used when determining if we want to save the session or not.
888
-     * @since 4.9.67.p
889
-     * @return bool
890
-     */
891
-    private function sessionHasStuffWorthSaving()
892
-    {
893
-        return $this->cart() instanceof EE_Cart
894
-            || (
895
-                isset($this->_session_data['ee_notices'])
896
-                && (
897
-                    ! empty($this->_session_data['ee_notices']['attention'])
898
-                    || !empty($this->_session_data['ee_notices']['errors'])
899
-                    || !empty($this->_session_data['ee_notices']['success'])
900
-                )
901
-            );
902
-    }
903
-    /**
904
-     * _save_session_to_db
905
-     *
906
-     * @param bool $clear_session
907
-     * @return string
908
-     * @throws EE_Error
909
-     * @throws InvalidArgumentException
910
-     * @throws InvalidDataTypeException
911
-     * @throws InvalidInterfaceException
912
-     */
913
-    private function _save_session_to_db($clear_session = false)
914
-    {
915
-        // don't save sessions for crawlers
916
-        // and unless we're deleting the session data, don't save anything if there isn't a cart
917
-        if ($this->request->isBot()
918
-            || (
919
-                ! $clear_session
920
-                && ! $this->sessionHasStuffWorthSaving()
921
-                && apply_filters('FHEE__EE_Session___save_session_to_db__abort_session_save', true)
922
-            )
923
-        ) {
924
-            return false;
925
-        }
926
-        $transaction = $this->transaction();
927
-        if ($transaction instanceof EE_Transaction) {
928
-            if (! $transaction->ID()) {
929
-                $transaction->save();
930
-            }
931
-            $this->_session_data['transaction'] = $transaction->ID();
932
-        }
933
-        // then serialize all of our session data
934
-        $session_data = serialize($this->_session_data);
935
-        // do we need to also encode it to avoid corrupted data when saved to the db?
936
-        $session_data = $this->_use_encryption
937
-            ? $this->encryption->base64_string_encode($session_data)
938
-            : $session_data;
939
-        // maybe save hash check
940
-        if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
941
-            $this->cache_storage->add(
942
-                EE_Session::hash_check_prefix . $this->_sid,
943
-                md5($session_data),
944
-                $this->session_lifespan->inSeconds()
945
-            );
946
-        }
947
-        // we're using the Transient API for storing session data,
948
-        return $this->cache_storage->add(
949
-            EE_Session::session_id_prefix . $this->_sid,
950
-            $session_data,
951
-            $this->session_lifespan->inSeconds()
952
-        );
953
-    }
954
-
955
-
956
-    /**
957
-     * @get    the full page request the visitor is accessing
958
-     * @access public
959
-     * @return string
960
-     */
961
-    public function _get_page_visit()
962
-    {
963
-        $page_visit = home_url('/') . 'wp-admin/admin-ajax.php';
964
-        // check for request url
965
-        if (isset($_SERVER['REQUEST_URI'])) {
966
-            $http_host = '';
967
-            $page_id = '?';
968
-            $e_reg = '';
969
-            $request_uri = esc_url($_SERVER['REQUEST_URI']);
970
-            $ru_bits = explode('?', $request_uri);
971
-            $request_uri = $ru_bits[0];
972
-            // check for and grab host as well
973
-            if (isset($_SERVER['HTTP_HOST'])) {
974
-                $http_host = esc_url($_SERVER['HTTP_HOST']);
975
-            }
976
-            // check for page_id in SERVER REQUEST
977
-            if (isset($_REQUEST['page_id'])) {
978
-                // rebuild $e_reg without any of the extra parameters
979
-                $page_id = '?page_id=' . esc_attr($_REQUEST['page_id']) . '&amp;';
980
-            }
981
-            // check for $e_reg in SERVER REQUEST
982
-            if (isset($_REQUEST['ee'])) {
983
-                // rebuild $e_reg without any of the extra parameters
984
-                $e_reg = 'ee=' . esc_attr($_REQUEST['ee']);
985
-            }
986
-            $page_visit = rtrim($http_host . $request_uri . $page_id . $e_reg, '?');
987
-        }
988
-        return $page_visit !== home_url('/wp-admin/admin-ajax.php') ? $page_visit : '';
989
-    }
990
-
991
-
992
-    /**
993
-     * @the    current wp user id
994
-     * @access public
995
-     * @return int
996
-     */
997
-    public function _wp_user_id()
998
-    {
999
-        // if I need to explain the following lines of code, then you shouldn't be looking at this!
1000
-        $this->_wp_user_id = get_current_user_id();
1001
-        return $this->_wp_user_id;
1002
-    }
1003
-
1004
-
1005
-    /**
1006
-     * Clear EE_Session data
1007
-     *
1008
-     * @access public
1009
-     * @param string $class
1010
-     * @param string $function
1011
-     * @return void
1012
-     * @throws EE_Error
1013
-     * @throws InvalidArgumentException
1014
-     * @throws InvalidDataTypeException
1015
-     * @throws InvalidInterfaceException
1016
-     */
1017
-    public function clear_session($class = '', $function = '')
1018
-    {
28
+	const session_id_prefix = 'ee_ssn_';
29
+
30
+	const hash_check_prefix = 'ee_shc_';
31
+
32
+	const OPTION_NAME_SETTINGS = 'ee_session_settings';
33
+
34
+	const STATUS_CLOSED = 0;
35
+
36
+	const STATUS_OPEN = 1;
37
+
38
+	/**
39
+	 * instance of the EE_Session object
40
+	 *
41
+	 * @var EE_Session
42
+	 */
43
+	private static $_instance;
44
+
45
+	/**
46
+	 * @var CacheStorageInterface $cache_storage
47
+	 */
48
+	protected $cache_storage;
49
+
50
+	/**
51
+	 * @var EE_Encryption $encryption
52
+	 */
53
+	protected $encryption;
54
+
55
+	/**
56
+	 * @var SessionStartHandler $session_start_handler
57
+	 */
58
+	protected $session_start_handler;
59
+
60
+	/**
61
+	 * the session id
62
+	 *
63
+	 * @var string
64
+	 */
65
+	private $_sid;
66
+
67
+	/**
68
+	 * session id salt
69
+	 *
70
+	 * @var string
71
+	 */
72
+	private $_sid_salt;
73
+
74
+	/**
75
+	 * session data
76
+	 *
77
+	 * @var array
78
+	 */
79
+	private $_session_data = array();
80
+
81
+	/**
82
+	 * how long an EE session lasts
83
+	 * default session lifespan of 1 hour (for not so instant IPNs)
84
+	 *
85
+	 * @var SessionLifespan $session_lifespan
86
+	 */
87
+	private $session_lifespan;
88
+
89
+	/**
90
+	 * session expiration time as Unix timestamp in GMT
91
+	 *
92
+	 * @var int
93
+	 */
94
+	private $_expiration;
95
+
96
+	/**
97
+	 * whether or not session has expired at some point
98
+	 *
99
+	 * @var boolean
100
+	 */
101
+	private $_expired = false;
102
+
103
+	/**
104
+	 * current time as Unix timestamp in GMT
105
+	 *
106
+	 * @var int
107
+	 */
108
+	private $_time;
109
+
110
+	/**
111
+	 * whether to encrypt session data
112
+	 *
113
+	 * @var bool
114
+	 */
115
+	private $_use_encryption;
116
+
117
+	/**
118
+	 * well... according to the server...
119
+	 *
120
+	 * @var null
121
+	 */
122
+	private $_user_agent;
123
+
124
+	/**
125
+	 * do you really trust the server ?
126
+	 *
127
+	 * @var null
128
+	 */
129
+	private $_ip_address;
130
+
131
+	/**
132
+	 * current WP user_id
133
+	 *
134
+	 * @var null
135
+	 */
136
+	private $_wp_user_id;
137
+
138
+	/**
139
+	 * array for defining default session vars
140
+	 *
141
+	 * @var array
142
+	 */
143
+	private $_default_session_vars = array(
144
+		'id'            => null,
145
+		'user_id'       => null,
146
+		'ip_address'    => null,
147
+		'user_agent'    => null,
148
+		'init_access'   => null,
149
+		'last_access'   => null,
150
+		'expiration'    => null,
151
+		'pages_visited' => array(),
152
+	);
153
+
154
+	/**
155
+	 * timestamp for when last garbage collection cycle was performed
156
+	 *
157
+	 * @var int $_last_gc
158
+	 */
159
+	private $_last_gc;
160
+
161
+	/**
162
+	 * @var RequestInterface $request
163
+	 */
164
+	protected $request;
165
+
166
+	/**
167
+	 * whether session is active or not
168
+	 *
169
+	 * @var int $status
170
+	 */
171
+	private $status = EE_Session::STATUS_CLOSED;
172
+
173
+
174
+	/**
175
+	 * @singleton method used to instantiate class object
176
+	 * @param CacheStorageInterface $cache_storage
177
+	 * @param SessionLifespan|null  $lifespan
178
+	 * @param RequestInterface      $request
179
+	 * @param SessionStartHandler   $session_start_handler
180
+	 * @param EE_Encryption         $encryption
181
+	 * @return EE_Session
182
+	 * @throws InvalidArgumentException
183
+	 * @throws InvalidDataTypeException
184
+	 * @throws InvalidInterfaceException
185
+	 */
186
+	public static function instance(
187
+		CacheStorageInterface $cache_storage = null,
188
+		SessionLifespan $lifespan = null,
189
+		RequestInterface $request = null,
190
+		SessionStartHandler $session_start_handler = null,
191
+		EE_Encryption $encryption = null
192
+	) {
193
+		// check if class object is instantiated
194
+		// session loading is turned ON by default, but prior to the init hook, can be turned back OFF via:
195
+		// add_filter( 'FHEE_load_EE_Session', '__return_false' );
196
+		if (! self::$_instance instanceof EE_Session && apply_filters('FHEE_load_EE_Session', true)) {
197
+			self::$_instance = new self(
198
+				$cache_storage,
199
+				$lifespan,
200
+				$request,
201
+				$session_start_handler,
202
+				$encryption
203
+			);
204
+		}
205
+		return self::$_instance;
206
+	}
207
+
208
+
209
+	/**
210
+	 * protected constructor to prevent direct creation
211
+	 *
212
+	 * @param CacheStorageInterface $cache_storage
213
+	 * @param SessionLifespan       $lifespan
214
+	 * @param RequestInterface      $request
215
+	 * @param SessionStartHandler   $session_start_handler
216
+	 * @param EE_Encryption         $encryption
217
+	 * @throws InvalidArgumentException
218
+	 * @throws InvalidDataTypeException
219
+	 * @throws InvalidInterfaceException
220
+	 */
221
+	protected function __construct(
222
+		CacheStorageInterface $cache_storage,
223
+		SessionLifespan $lifespan,
224
+		RequestInterface $request,
225
+		SessionStartHandler $session_start_handler,
226
+		EE_Encryption $encryption = null
227
+	) {
228
+		// session loading is turned ON by default,
229
+		// but prior to the 'AHEE__EE_System__core_loaded_and_ready' hook
230
+		// (which currently fires on the init hook at priority 9),
231
+		// can be turned back OFF via: add_filter( 'FHEE_load_EE_Session', '__return_false' );
232
+		if (! apply_filters('FHEE_load_EE_Session', true)) {
233
+			return;
234
+		}
235
+		$this->session_start_handler = $session_start_handler;
236
+		$this->session_lifespan = $lifespan;
237
+		$this->request = $request;
238
+		if (! defined('ESPRESSO_SESSION')) {
239
+			define('ESPRESSO_SESSION', true);
240
+		}
241
+		// retrieve session options from db
242
+		$session_settings = (array) get_option(EE_Session::OPTION_NAME_SETTINGS, array());
243
+		if (! empty($session_settings)) {
244
+			// cycle though existing session options
245
+			foreach ($session_settings as $var_name => $session_setting) {
246
+				// set values for class properties
247
+				$var_name = '_' . $var_name;
248
+				$this->{$var_name} = $session_setting;
249
+			}
250
+		}
251
+		$this->cache_storage = $cache_storage;
252
+		// are we using encryption?
253
+		$this->_use_encryption = $encryption instanceof EE_Encryption
254
+								 && EE_Registry::instance()->CFG->admin->encode_session_data();
255
+		// encrypt data via: $this->encryption->encrypt();
256
+		$this->encryption = $encryption;
257
+		// filter hook allows outside functions/classes/plugins to change default empty cart
258
+		$extra_default_session_vars = apply_filters('FHEE__EE_Session__construct__extra_default_session_vars', array());
259
+		array_merge($this->_default_session_vars, $extra_default_session_vars);
260
+		// apply default session vars
261
+		$this->_set_defaults();
262
+		add_action('AHEE__EE_System__initialize', array($this, 'open_session'));
263
+		// check request for 'clear_session' param
264
+		add_action('AHEE__EE_Request_Handler__construct__complete', array($this, 'wp_loaded'));
265
+		// once everything is all said and done,
266
+		add_action('shutdown', array($this, 'update'), 100);
267
+		add_action('shutdown', array($this, 'garbageCollection'), 1000);
268
+		$this->configure_garbage_collection_filters();
269
+	}
270
+
271
+
272
+	/**
273
+	 * @return bool
274
+	 * @throws InvalidArgumentException
275
+	 * @throws InvalidDataTypeException
276
+	 * @throws InvalidInterfaceException
277
+	 */
278
+	public static function isLoadedAndActive()
279
+	{
280
+		return did_action('AHEE__EE_System__core_loaded_and_ready')
281
+			   && EE_Session::instance() instanceof EE_Session
282
+			   && EE_Session::instance()->isActive();
283
+	}
284
+
285
+
286
+	/**
287
+	 * @return bool
288
+	 */
289
+	public function isActive()
290
+	{
291
+		return $this->status === EE_Session::STATUS_OPEN;
292
+	}
293
+
294
+
295
+	/**
296
+	 * @return void
297
+	 * @throws EE_Error
298
+	 * @throws InvalidArgumentException
299
+	 * @throws InvalidDataTypeException
300
+	 * @throws InvalidInterfaceException
301
+	 * @throws InvalidSessionDataException
302
+	 */
303
+	public function open_session()
304
+	{
305
+		// check for existing session and retrieve it from db
306
+		if (! $this->_espresso_session()) {
307
+			// or just start a new one
308
+			$this->_create_espresso_session();
309
+		}
310
+	}
311
+
312
+
313
+	/**
314
+	 * @return bool
315
+	 */
316
+	public function expired()
317
+	{
318
+		return $this->_expired;
319
+	}
320
+
321
+
322
+	/**
323
+	 * @return void
324
+	 */
325
+	public function reset_expired()
326
+	{
327
+		$this->_expired = false;
328
+	}
329
+
330
+
331
+	/**
332
+	 * @return int
333
+	 */
334
+	public function expiration()
335
+	{
336
+		return $this->_expiration;
337
+	}
338
+
339
+
340
+	/**
341
+	 * @return int
342
+	 */
343
+	public function extension()
344
+	{
345
+		return apply_filters('FHEE__EE_Session__extend_expiration__seconds_added', 10 * MINUTE_IN_SECONDS);
346
+	}
347
+
348
+
349
+	/**
350
+	 * @param int $time number of seconds to add to session expiration
351
+	 */
352
+	public function extend_expiration($time = 0)
353
+	{
354
+		$time = $time ? $time : $this->extension();
355
+		$this->_expiration += absint($time);
356
+	}
357
+
358
+
359
+	/**
360
+	 * @return int
361
+	 */
362
+	public function lifespan()
363
+	{
364
+		return $this->session_lifespan->inSeconds();
365
+	}
366
+
367
+
368
+	/**
369
+	 * This just sets some defaults for the _session data property
370
+	 *
371
+	 * @access private
372
+	 * @return void
373
+	 */
374
+	private function _set_defaults()
375
+	{
376
+		// set some defaults
377
+		foreach ($this->_default_session_vars as $key => $default_var) {
378
+			if (is_array($default_var)) {
379
+				$this->_session_data[ $key ] = array();
380
+			} else {
381
+				$this->_session_data[ $key ] = '';
382
+			}
383
+		}
384
+	}
385
+
386
+
387
+	/**
388
+	 * @retrieve  session data
389
+	 * @access    public
390
+	 * @return    string
391
+	 */
392
+	public function id()
393
+	{
394
+		return $this->_sid;
395
+	}
396
+
397
+
398
+	/**
399
+	 * @param \EE_Cart $cart
400
+	 * @return bool
401
+	 */
402
+	public function set_cart(EE_Cart $cart)
403
+	{
404
+		$this->_session_data['cart'] = $cart;
405
+		return true;
406
+	}
407
+
408
+
409
+	/**
410
+	 * reset_cart
411
+	 */
412
+	public function reset_cart()
413
+	{
414
+		do_action('AHEE__EE_Session__reset_cart__before_reset', $this);
415
+		$this->_session_data['cart'] = null;
416
+	}
417
+
418
+
419
+	/**
420
+	 * @return \EE_Cart
421
+	 */
422
+	public function cart()
423
+	{
424
+		return isset($this->_session_data['cart']) && $this->_session_data['cart'] instanceof EE_Cart
425
+			? $this->_session_data['cart']
426
+			: null;
427
+	}
428
+
429
+
430
+	/**
431
+	 * @param \EE_Checkout $checkout
432
+	 * @return bool
433
+	 */
434
+	public function set_checkout(EE_Checkout $checkout)
435
+	{
436
+		$this->_session_data['checkout'] = $checkout;
437
+		return true;
438
+	}
439
+
440
+
441
+	/**
442
+	 * reset_checkout
443
+	 */
444
+	public function reset_checkout()
445
+	{
446
+		do_action('AHEE__EE_Session__reset_checkout__before_reset', $this);
447
+		$this->_session_data['checkout'] = null;
448
+	}
449
+
450
+
451
+	/**
452
+	 * @return \EE_Checkout
453
+	 */
454
+	public function checkout()
455
+	{
456
+		return isset($this->_session_data['checkout']) && $this->_session_data['checkout'] instanceof EE_Checkout
457
+			? $this->_session_data['checkout']
458
+			: null;
459
+	}
460
+
461
+
462
+	/**
463
+	 * @param \EE_Transaction $transaction
464
+	 * @return bool
465
+	 * @throws EE_Error
466
+	 */
467
+	public function set_transaction(EE_Transaction $transaction)
468
+	{
469
+		// first remove the session from the transaction before we save the transaction in the session
470
+		$transaction->set_txn_session_data(null);
471
+		$this->_session_data['transaction'] = $transaction;
472
+		return true;
473
+	}
474
+
475
+
476
+	/**
477
+	 * reset_transaction
478
+	 */
479
+	public function reset_transaction()
480
+	{
481
+		do_action('AHEE__EE_Session__reset_transaction__before_reset', $this);
482
+		$this->_session_data['transaction'] = null;
483
+	}
484
+
485
+
486
+	/**
487
+	 * @return \EE_Transaction
488
+	 */
489
+	public function transaction()
490
+	{
491
+		return isset($this->_session_data['transaction'])
492
+			   && $this->_session_data['transaction'] instanceof EE_Transaction
493
+			? $this->_session_data['transaction']
494
+			: null;
495
+	}
496
+
497
+
498
+	/**
499
+	 * retrieve session data
500
+	 *
501
+	 * @param null $key
502
+	 * @param bool $reset_cache
503
+	 * @return array
504
+	 */
505
+	public function get_session_data($key = null, $reset_cache = false)
506
+	{
507
+		if ($reset_cache) {
508
+			$this->reset_cart();
509
+			$this->reset_checkout();
510
+			$this->reset_transaction();
511
+		}
512
+		if (! empty($key)) {
513
+			return isset($this->_session_data[ $key ]) ? $this->_session_data[ $key ] : null;
514
+		}
515
+		return $this->_session_data;
516
+	}
517
+
518
+
519
+	/**
520
+	 * Returns TRUE on success, FALSE on fail
521
+	 *
522
+	 * @param array $data
523
+	 * @return bool
524
+	 */
525
+	public function set_session_data($data)
526
+	{
527
+		// nothing ??? bad data ??? go home!
528
+		if (empty($data) || ! is_array($data)) {
529
+			EE_Error::add_error(
530
+				esc_html__(
531
+					'No session data or invalid session data was provided.',
532
+					'event_espresso'
533
+				),
534
+				__FILE__,
535
+				__FUNCTION__,
536
+				__LINE__
537
+			);
538
+			return false;
539
+		}
540
+		foreach ($data as $key => $value) {
541
+			if (isset($this->_default_session_vars[ $key ])) {
542
+				EE_Error::add_error(
543
+					sprintf(
544
+						esc_html__(
545
+							'Sorry! %s is a default session datum and can not be reset.',
546
+							'event_espresso'
547
+						),
548
+						$key
549
+					),
550
+					__FILE__,
551
+					__FUNCTION__,
552
+					__LINE__
553
+				);
554
+				return false;
555
+			}
556
+			$this->_session_data[ $key ] = $value;
557
+		}
558
+		return true;
559
+	}
560
+
561
+
562
+	/**
563
+	 * @initiate session
564
+	 * @access   private
565
+	 * @return TRUE on success, FALSE on fail
566
+	 * @throws EE_Error
567
+	 * @throws InvalidArgumentException
568
+	 * @throws InvalidDataTypeException
569
+	 * @throws InvalidInterfaceException
570
+	 * @throws InvalidSessionDataException
571
+	 */
572
+	private function _espresso_session()
573
+	{
574
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
575
+		$this->session_start_handler->startSession();
576
+		$this->status = EE_Session::STATUS_OPEN;
577
+		// get our modified session ID
578
+		$this->_sid = $this->_generate_session_id();
579
+		// and the visitors IP
580
+		$this->_ip_address = $this->request->ipAddress();
581
+		// set the "user agent"
582
+		$this->_user_agent = $this->request->userAgent();
583
+		// now let's retrieve what's in the db
584
+		$session_data = $this->_retrieve_session_data();
585
+		if (! empty($session_data)) {
586
+			// get the current time in UTC
587
+			$this->_time = $this->_time !== null ? $this->_time : time();
588
+			// and reset the session expiration
589
+			$this->_expiration = isset($session_data['expiration'])
590
+				? $session_data['expiration']
591
+				: $this->_time + $this->session_lifespan->inSeconds();
592
+		} else {
593
+			// set initial site access time and the session expiration
594
+			$this->_set_init_access_and_expiration();
595
+			// set referer
596
+			$this->_session_data['pages_visited'][ $this->_session_data['init_access'] ] = isset($_SERVER['HTTP_REFERER'])
597
+				? esc_attr($_SERVER['HTTP_REFERER'])
598
+				: '';
599
+			// no previous session = go back and create one (on top of the data above)
600
+			return false;
601
+		}
602
+		// now the user agent
603
+		if ($session_data['user_agent'] !== $this->_user_agent) {
604
+			return false;
605
+		}
606
+		// wait a minute... how old are you?
607
+		if ($this->_time > $this->_expiration) {
608
+			// yer too old fer me!
609
+			$this->_expired = true;
610
+			// wipe out everything that isn't a default session datum
611
+			$this->clear_session(__CLASS__, __FUNCTION__);
612
+		}
613
+		// make event espresso session data available to plugin
614
+		$this->_session_data = array_merge($this->_session_data, $session_data);
615
+		return true;
616
+	}
617
+
618
+
619
+	/**
620
+	 * _get_session_data
621
+	 * Retrieves the session data, and attempts to correct any encoding issues that can occur due to improperly setup
622
+	 * databases
623
+	 *
624
+	 * @return array
625
+	 * @throws EE_Error
626
+	 * @throws InvalidArgumentException
627
+	 * @throws InvalidSessionDataException
628
+	 * @throws InvalidDataTypeException
629
+	 * @throws InvalidInterfaceException
630
+	 */
631
+	protected function _retrieve_session_data()
632
+	{
633
+		$ssn_key = EE_Session::session_id_prefix . $this->_sid;
634
+		try {
635
+			// we're using WP's Transient API to store session data using the PHP session ID as the option name
636
+			$session_data = $this->cache_storage->get($ssn_key, false);
637
+			if (empty($session_data)) {
638
+				return array();
639
+			}
640
+			if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
641
+				$hash_check = $this->cache_storage->get(
642
+					EE_Session::hash_check_prefix . $this->_sid,
643
+					false
644
+				);
645
+				if ($hash_check && $hash_check !== md5($session_data)) {
646
+					EE_Error::add_error(
647
+						sprintf(
648
+							__(
649
+								'The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.',
650
+								'event_espresso'
651
+							),
652
+							EE_Session::session_id_prefix . $this->_sid
653
+						),
654
+						__FILE__,
655
+						__FUNCTION__,
656
+						__LINE__
657
+					);
658
+				}
659
+			}
660
+		} catch (Exception $e) {
661
+			// let's just eat that error for now and attempt to correct any corrupted data
662
+			global $wpdb;
663
+			$row = $wpdb->get_row(
664
+				$wpdb->prepare(
665
+					"SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
666
+					'_transient_' . $ssn_key
667
+				)
668
+			);
669
+			$session_data = is_object($row) ? $row->option_value : null;
670
+			if ($session_data) {
671
+				$session_data = preg_replace_callback(
672
+					'!s:(d+):"(.*?)";!',
673
+					function ($match) {
674
+						return $match[1] === strlen($match[2])
675
+							? $match[0]
676
+							: 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
677
+					},
678
+					$session_data
679
+				);
680
+			}
681
+			$session_data = maybe_unserialize($session_data);
682
+		}
683
+		// in case the data is encoded... try to decode it
684
+		$session_data = $this->encryption instanceof EE_Encryption
685
+			? $this->encryption->base64_string_decode($session_data)
686
+			: $session_data;
687
+		if (! is_array($session_data)) {
688
+			try {
689
+				$session_data = maybe_unserialize($session_data);
690
+			} catch (Exception $e) {
691
+				$msg = esc_html__(
692
+					'An error occurred while attempting to unserialize the session data.',
693
+					'event_espresso'
694
+				);
695
+				$msg .= WP_DEBUG
696
+					? '<br><pre>'
697
+					  . print_r($session_data, true)
698
+					  . '</pre><br>'
699
+					  . $this->find_serialize_error($session_data)
700
+					: '';
701
+				$this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
702
+				throw new InvalidSessionDataException($msg, 0, $e);
703
+			}
704
+		}
705
+		// just a check to make sure the session array is indeed an array
706
+		if (! is_array($session_data)) {
707
+			// no?!?! then something is wrong
708
+			$msg = esc_html__(
709
+				'The session data is missing, invalid, or corrupted.',
710
+				'event_espresso'
711
+			);
712
+			$msg .= WP_DEBUG
713
+				? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
714
+				: '';
715
+			$this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
716
+			throw new InvalidSessionDataException($msg);
717
+		}
718
+		if (isset($session_data['transaction']) && absint($session_data['transaction']) !== 0) {
719
+			$session_data['transaction'] = EEM_Transaction::instance()->get_one_by_ID(
720
+				$session_data['transaction']
721
+			);
722
+		}
723
+		return $session_data;
724
+	}
725
+
726
+
727
+	/**
728
+	 * _generate_session_id
729
+	 * Retrieves the PHP session id either directly from the PHP session,
730
+	 * or from the $_REQUEST array if it was passed in from an AJAX request.
731
+	 * The session id is then salted and hashed (mmm sounds tasty)
732
+	 * so that it can be safely used as a $_REQUEST param
733
+	 *
734
+	 * @return string
735
+	 */
736
+	protected function _generate_session_id()
737
+	{
738
+		// check if the SID was passed explicitly, otherwise get from session, then add salt and hash it to reduce length
739
+		if (isset($_REQUEST['EESID'])) {
740
+			$session_id = sanitize_text_field($_REQUEST['EESID']);
741
+		} else {
742
+			$session_id = md5(session_id() . get_current_blog_id() . $this->_get_sid_salt());
743
+		}
744
+		return apply_filters('FHEE__EE_Session___generate_session_id__session_id', $session_id);
745
+	}
746
+
747
+
748
+	/**
749
+	 * _get_sid_salt
750
+	 *
751
+	 * @return string
752
+	 */
753
+	protected function _get_sid_salt()
754
+	{
755
+		// was session id salt already saved to db ?
756
+		if (empty($this->_sid_salt)) {
757
+			// no?  then maybe use WP defined constant
758
+			if (defined('AUTH_SALT')) {
759
+				$this->_sid_salt = AUTH_SALT;
760
+			}
761
+			// if salt doesn't exist or is too short
762
+			if (strlen($this->_sid_salt) < 32) {
763
+				// create a new one
764
+				$this->_sid_salt = wp_generate_password(64);
765
+			}
766
+			// and save it as a permanent session setting
767
+			$this->updateSessionSettings(array('sid_salt' => $this->_sid_salt));
768
+		}
769
+		return $this->_sid_salt;
770
+	}
771
+
772
+
773
+	/**
774
+	 * _set_init_access_and_expiration
775
+	 *
776
+	 * @return void
777
+	 */
778
+	protected function _set_init_access_and_expiration()
779
+	{
780
+		$this->_time = time();
781
+		$this->_expiration = $this->_time + $this->session_lifespan->inSeconds();
782
+		// set initial site access time
783
+		$this->_session_data['init_access'] = $this->_time;
784
+		// and the session expiration
785
+		$this->_session_data['expiration'] = $this->_expiration;
786
+	}
787
+
788
+
789
+	/**
790
+	 * @update session data  prior to saving to the db
791
+	 * @access public
792
+	 * @param bool $new_session
793
+	 * @return TRUE on success, FALSE on fail
794
+	 * @throws EE_Error
795
+	 * @throws InvalidArgumentException
796
+	 * @throws InvalidDataTypeException
797
+	 * @throws InvalidInterfaceException
798
+	 */
799
+	public function update($new_session = false)
800
+	{
801
+		$this->_session_data = $this->_session_data !== null
802
+							   && is_array($this->_session_data)
803
+							   && isset($this->_session_data['id'])
804
+			? $this->_session_data
805
+			: array();
806
+		if (empty($this->_session_data)) {
807
+			$this->_set_defaults();
808
+		}
809
+		$session_data = array();
810
+		foreach ($this->_session_data as $key => $value) {
811
+			switch ($key) {
812
+				case 'id':
813
+					// session ID
814
+					$session_data['id'] = $this->_sid;
815
+					break;
816
+				case 'ip_address':
817
+					// visitor ip address
818
+					$session_data['ip_address'] = $this->request->ipAddress();
819
+					break;
820
+				case 'user_agent':
821
+					// visitor user_agent
822
+					$session_data['user_agent'] = $this->_user_agent;
823
+					break;
824
+				case 'init_access':
825
+					$session_data['init_access'] = absint($value);
826
+					break;
827
+				case 'last_access':
828
+					// current access time
829
+					$session_data['last_access'] = $this->_time;
830
+					break;
831
+				case 'expiration':
832
+					// when the session expires
833
+					$session_data['expiration'] = ! empty($this->_expiration)
834
+						? $this->_expiration
835
+						: $session_data['init_access'] + $this->session_lifespan->inSeconds();
836
+					break;
837
+				case 'user_id':
838
+					// current user if logged in
839
+					$session_data['user_id'] = $this->_wp_user_id();
840
+					break;
841
+				case 'pages_visited':
842
+					$page_visit = $this->_get_page_visit();
843
+					if ($page_visit) {
844
+						// set pages visited where the first will be the http referrer
845
+						$this->_session_data['pages_visited'][ $this->_time ] = $page_visit;
846
+						// we'll only save the last 10 page visits.
847
+						$session_data['pages_visited'] = array_slice($this->_session_data['pages_visited'], -10);
848
+					}
849
+					break;
850
+				default:
851
+					// carry any other data over
852
+					$session_data[ $key ] = $this->_session_data[ $key ];
853
+			}
854
+		}
855
+		$this->_session_data = $session_data;
856
+		// creating a new session does not require saving to the db just yet
857
+		if (! $new_session) {
858
+			// ready? let's save
859
+			if ($this->_save_session_to_db()) {
860
+				return true;
861
+			}
862
+			return false;
863
+		}
864
+		// meh, why not?
865
+		return true;
866
+	}
867
+
868
+
869
+	/**
870
+	 * @create session data array
871
+	 * @access public
872
+	 * @return bool
873
+	 * @throws EE_Error
874
+	 * @throws InvalidArgumentException
875
+	 * @throws InvalidDataTypeException
876
+	 * @throws InvalidInterfaceException
877
+	 */
878
+	private function _create_espresso_session()
879
+	{
880
+		do_action('AHEE_log', __CLASS__, __FUNCTION__, '');
881
+		// use the update function for now with $new_session arg set to TRUE
882
+		return $this->update(true) ? true : false;
883
+	}
884
+
885
+	/**
886
+	 * Detects if there is anything worth saving in the session (eg the cart is a good one, notices are pretty good
887
+	 * too). This is used when determining if we want to save the session or not.
888
+	 * @since 4.9.67.p
889
+	 * @return bool
890
+	 */
891
+	private function sessionHasStuffWorthSaving()
892
+	{
893
+		return $this->cart() instanceof EE_Cart
894
+			|| (
895
+				isset($this->_session_data['ee_notices'])
896
+				&& (
897
+					! empty($this->_session_data['ee_notices']['attention'])
898
+					|| !empty($this->_session_data['ee_notices']['errors'])
899
+					|| !empty($this->_session_data['ee_notices']['success'])
900
+				)
901
+			);
902
+	}
903
+	/**
904
+	 * _save_session_to_db
905
+	 *
906
+	 * @param bool $clear_session
907
+	 * @return string
908
+	 * @throws EE_Error
909
+	 * @throws InvalidArgumentException
910
+	 * @throws InvalidDataTypeException
911
+	 * @throws InvalidInterfaceException
912
+	 */
913
+	private function _save_session_to_db($clear_session = false)
914
+	{
915
+		// don't save sessions for crawlers
916
+		// and unless we're deleting the session data, don't save anything if there isn't a cart
917
+		if ($this->request->isBot()
918
+			|| (
919
+				! $clear_session
920
+				&& ! $this->sessionHasStuffWorthSaving()
921
+				&& apply_filters('FHEE__EE_Session___save_session_to_db__abort_session_save', true)
922
+			)
923
+		) {
924
+			return false;
925
+		}
926
+		$transaction = $this->transaction();
927
+		if ($transaction instanceof EE_Transaction) {
928
+			if (! $transaction->ID()) {
929
+				$transaction->save();
930
+			}
931
+			$this->_session_data['transaction'] = $transaction->ID();
932
+		}
933
+		// then serialize all of our session data
934
+		$session_data = serialize($this->_session_data);
935
+		// do we need to also encode it to avoid corrupted data when saved to the db?
936
+		$session_data = $this->_use_encryption
937
+			? $this->encryption->base64_string_encode($session_data)
938
+			: $session_data;
939
+		// maybe save hash check
940
+		if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
941
+			$this->cache_storage->add(
942
+				EE_Session::hash_check_prefix . $this->_sid,
943
+				md5($session_data),
944
+				$this->session_lifespan->inSeconds()
945
+			);
946
+		}
947
+		// we're using the Transient API for storing session data,
948
+		return $this->cache_storage->add(
949
+			EE_Session::session_id_prefix . $this->_sid,
950
+			$session_data,
951
+			$this->session_lifespan->inSeconds()
952
+		);
953
+	}
954
+
955
+
956
+	/**
957
+	 * @get    the full page request the visitor is accessing
958
+	 * @access public
959
+	 * @return string
960
+	 */
961
+	public function _get_page_visit()
962
+	{
963
+		$page_visit = home_url('/') . 'wp-admin/admin-ajax.php';
964
+		// check for request url
965
+		if (isset($_SERVER['REQUEST_URI'])) {
966
+			$http_host = '';
967
+			$page_id = '?';
968
+			$e_reg = '';
969
+			$request_uri = esc_url($_SERVER['REQUEST_URI']);
970
+			$ru_bits = explode('?', $request_uri);
971
+			$request_uri = $ru_bits[0];
972
+			// check for and grab host as well
973
+			if (isset($_SERVER['HTTP_HOST'])) {
974
+				$http_host = esc_url($_SERVER['HTTP_HOST']);
975
+			}
976
+			// check for page_id in SERVER REQUEST
977
+			if (isset($_REQUEST['page_id'])) {
978
+				// rebuild $e_reg without any of the extra parameters
979
+				$page_id = '?page_id=' . esc_attr($_REQUEST['page_id']) . '&amp;';
980
+			}
981
+			// check for $e_reg in SERVER REQUEST
982
+			if (isset($_REQUEST['ee'])) {
983
+				// rebuild $e_reg without any of the extra parameters
984
+				$e_reg = 'ee=' . esc_attr($_REQUEST['ee']);
985
+			}
986
+			$page_visit = rtrim($http_host . $request_uri . $page_id . $e_reg, '?');
987
+		}
988
+		return $page_visit !== home_url('/wp-admin/admin-ajax.php') ? $page_visit : '';
989
+	}
990
+
991
+
992
+	/**
993
+	 * @the    current wp user id
994
+	 * @access public
995
+	 * @return int
996
+	 */
997
+	public function _wp_user_id()
998
+	{
999
+		// if I need to explain the following lines of code, then you shouldn't be looking at this!
1000
+		$this->_wp_user_id = get_current_user_id();
1001
+		return $this->_wp_user_id;
1002
+	}
1003
+
1004
+
1005
+	/**
1006
+	 * Clear EE_Session data
1007
+	 *
1008
+	 * @access public
1009
+	 * @param string $class
1010
+	 * @param string $function
1011
+	 * @return void
1012
+	 * @throws EE_Error
1013
+	 * @throws InvalidArgumentException
1014
+	 * @throws InvalidDataTypeException
1015
+	 * @throws InvalidInterfaceException
1016
+	 */
1017
+	public function clear_session($class = '', $function = '')
1018
+	{
1019 1019
 //         echo '
1020 1020
 // <h3 style="color:#999;line-height:.9em;">
1021 1021
 // <span style="color:#2EA2CC">' . __CLASS__ . '</span>::<span style="color:#E76700">' . __FUNCTION__ . '( ' . $class . '::' . $function . '() )</span><br/>
1022 1022
 // <span style="font-size:9px;font-weight:normal;">' . __FILE__ . '</span>    <b style="font-size:10px;">  ' . __LINE__ . ' </b>
1023 1023
 // </h3>';
1024
-        do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : ' . $class . '::' . $function . '()');
1025
-        $this->reset_cart();
1026
-        $this->reset_checkout();
1027
-        $this->reset_transaction();
1028
-        // wipe out everything that isn't a default session datum
1029
-        $this->reset_data(array_keys($this->_session_data));
1030
-        // reset initial site access time and the session expiration
1031
-        $this->_set_init_access_and_expiration();
1032
-        $this->_save_session_to_db(true);
1033
-    }
1034
-
1035
-
1036
-    /**
1037
-     * resets all non-default session vars. Returns TRUE on success, FALSE on fail
1038
-     *
1039
-     * @param array|mixed $data_to_reset
1040
-     * @param bool        $show_all_notices
1041
-     * @return bool
1042
-     */
1043
-    public function reset_data($data_to_reset = array(), $show_all_notices = false)
1044
-    {
1045
-        // if $data_to_reset is not in an array, then put it in one
1046
-        if (! is_array($data_to_reset)) {
1047
-            $data_to_reset = array($data_to_reset);
1048
-        }
1049
-        // nothing ??? go home!
1050
-        if (empty($data_to_reset)) {
1051
-            EE_Error::add_error(
1052
-                __(
1053
-                    'No session data could be reset, because no session var name was provided.',
1054
-                    'event_espresso'
1055
-                ),
1056
-                __FILE__,
1057
-                __FUNCTION__,
1058
-                __LINE__
1059
-            );
1060
-            return false;
1061
-        }
1062
-        $return_value = true;
1063
-        // since $data_to_reset is an array, cycle through the values
1064
-        foreach ($data_to_reset as $reset) {
1065
-            // first check to make sure it is a valid session var
1066
-            if (isset($this->_session_data[ $reset ])) {
1067
-                // then check to make sure it is not a default var
1068
-                if (! array_key_exists($reset, $this->_default_session_vars)) {
1069
-                    // remove session var
1070
-                    unset($this->_session_data[ $reset ]);
1071
-                    if ($show_all_notices) {
1072
-                        EE_Error::add_success(
1073
-                            sprintf(
1074
-                                __('The session variable %s was removed.', 'event_espresso'),
1075
-                                $reset
1076
-                            ),
1077
-                            __FILE__,
1078
-                            __FUNCTION__,
1079
-                            __LINE__
1080
-                        );
1081
-                    }
1082
-                } else {
1083
-                    // yeeeeeeeeerrrrrrrrrrr OUT !!!!
1084
-                    if ($show_all_notices) {
1085
-                        EE_Error::add_error(
1086
-                            sprintf(
1087
-                                __(
1088
-                                    'Sorry! %s is a default session datum and can not be reset.',
1089
-                                    'event_espresso'
1090
-                                ),
1091
-                                $reset
1092
-                            ),
1093
-                            __FILE__,
1094
-                            __FUNCTION__,
1095
-                            __LINE__
1096
-                        );
1097
-                    }
1098
-                    $return_value = false;
1099
-                }
1100
-            } elseif ($show_all_notices) {
1101
-                // oops! that session var does not exist!
1102
-                EE_Error::add_error(
1103
-                    sprintf(
1104
-                        __(
1105
-                            'The session item provided, %s, is invalid or does not exist.',
1106
-                            'event_espresso'
1107
-                        ),
1108
-                        $reset
1109
-                    ),
1110
-                    __FILE__,
1111
-                    __FUNCTION__,
1112
-                    __LINE__
1113
-                );
1114
-                $return_value = false;
1115
-            }
1116
-        } // end of foreach
1117
-        return $return_value;
1118
-    }
1119
-
1120
-
1121
-    /**
1122
-     *   wp_loaded
1123
-     *
1124
-     * @access public
1125
-     * @throws EE_Error
1126
-     * @throws InvalidDataTypeException
1127
-     * @throws InvalidInterfaceException
1128
-     * @throws InvalidArgumentException
1129
-     */
1130
-    public function wp_loaded()
1131
-    {
1132
-        if ($this->request->requestParamIsSet('clear_session')) {
1133
-            $this->clear_session(__CLASS__, __FUNCTION__);
1134
-        }
1135
-    }
1136
-
1137
-
1138
-    /**
1139
-     * Used to reset the entire object (for tests).
1140
-     *
1141
-     * @since 4.3.0
1142
-     * @throws EE_Error
1143
-     * @throws InvalidDataTypeException
1144
-     * @throws InvalidInterfaceException
1145
-     * @throws InvalidArgumentException
1146
-     */
1147
-    public function reset_instance()
1148
-    {
1149
-        $this->clear_session();
1150
-        self::$_instance = null;
1151
-    }
1152
-
1153
-
1154
-    public function configure_garbage_collection_filters()
1155
-    {
1156
-        // run old filter we had for controlling session cleanup
1157
-        $expired_session_transient_delete_query_limit = absint(
1158
-            apply_filters(
1159
-                'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1160
-                50
1161
-            )
1162
-        );
1163
-        // is there a value? or one that is different than the default 50 records?
1164
-        if ($expired_session_transient_delete_query_limit === 0) {
1165
-            // hook into TransientCacheStorage in case Session cleanup was turned off
1166
-            add_filter('FHEE__TransientCacheStorage__transient_cleanup_schedule', '__return_zero');
1167
-        } elseif ($expired_session_transient_delete_query_limit !== 50) {
1168
-            // or use that for the new transient cleanup query limit
1169
-            add_filter(
1170
-                'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
1171
-                function () use ($expired_session_transient_delete_query_limit) {
1172
-                    return $expired_session_transient_delete_query_limit;
1173
-                }
1174
-            );
1175
-        }
1176
-    }
1177
-
1178
-
1179
-    /**
1180
-     * @see http://stackoverflow.com/questions/10152904/unserialize-function-unserialize-error-at-offset/21389439#10152996
1181
-     * @param $data1
1182
-     * @return string
1183
-     */
1184
-    private function find_serialize_error($data1)
1185
-    {
1186
-        $error = '<pre>';
1187
-        $data2 = preg_replace_callback(
1188
-            '!s:(\d+):"(.*?)";!',
1189
-            function ($match) {
1190
-                return ($match[1] === strlen($match[2]))
1191
-                    ? $match[0]
1192
-                    : 's:'
1193
-                      . strlen($match[2])
1194
-                      . ':"'
1195
-                      . $match[2]
1196
-                      . '";';
1197
-            },
1198
-            $data1
1199
-        );
1200
-        $max = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1201
-        $error .= $data1 . PHP_EOL;
1202
-        $error .= $data2 . PHP_EOL;
1203
-        for ($i = 0; $i < $max; $i++) {
1204
-            if (@$data1[ $i ] !== @$data2[ $i ]) {
1205
-                $error .= 'Difference ' . @$data1[ $i ] . ' != ' . @$data2[ $i ] . PHP_EOL;
1206
-                $error .= "\t-> ORD number " . ord(@$data1[ $i ]) . ' != ' . ord(@$data2[ $i ]) . PHP_EOL;
1207
-                $error .= "\t-> Line Number = $i" . PHP_EOL;
1208
-                $start = ($i - 20);
1209
-                $start = ($start < 0) ? 0 : $start;
1210
-                $length = 40;
1211
-                $point = $max - $i;
1212
-                if ($point < 20) {
1213
-                    $rlength = 1;
1214
-                    $rpoint = -$point;
1215
-                } else {
1216
-                    $rpoint = $length - 20;
1217
-                    $rlength = 1;
1218
-                }
1219
-                $error .= "\t-> Section Data1  = ";
1220
-                $error .= substr_replace(
1221
-                    substr($data1, $start, $length),
1222
-                    "<b style=\"color:green\">{$data1[ $i ]}</b>",
1223
-                    $rpoint,
1224
-                    $rlength
1225
-                );
1226
-                $error .= PHP_EOL;
1227
-                $error .= "\t-> Section Data2  = ";
1228
-                $error .= substr_replace(
1229
-                    substr($data2, $start, $length),
1230
-                    "<b style=\"color:red\">{$data2[ $i ]}</b>",
1231
-                    $rpoint,
1232
-                    $rlength
1233
-                );
1234
-                $error .= PHP_EOL;
1235
-            }
1236
-        }
1237
-        $error .= '</pre>';
1238
-        return $error;
1239
-    }
1240
-
1241
-
1242
-    /**
1243
-     * Saves an  array of settings used for configuring aspects of session behaviour
1244
-     *
1245
-     * @param array $updated_settings
1246
-     */
1247
-    private function updateSessionSettings(array $updated_settings = array())
1248
-    {
1249
-        // add existing settings, but only if not included in incoming $updated_settings array
1250
-        $updated_settings += get_option(EE_Session::OPTION_NAME_SETTINGS, array());
1251
-        update_option(EE_Session::OPTION_NAME_SETTINGS, $updated_settings);
1252
-    }
1253
-
1254
-
1255
-    /**
1256
-     * garbage_collection
1257
-     */
1258
-    public function garbageCollection()
1259
-    {
1260
-        // only perform during regular requests if last garbage collection was over an hour ago
1261
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1262
-            $this->_last_gc = time();
1263
-            $this->updateSessionSettings(array('last_gc' => $this->_last_gc));
1264
-            /** @type WPDB $wpdb */
1265
-            global $wpdb;
1266
-            // filter the query limit. Set to 0 to turn off garbage collection
1267
-            $expired_session_transient_delete_query_limit = absint(
1268
-                apply_filters(
1269
-                    'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1270
-                    50
1271
-                )
1272
-            );
1273
-            // non-zero LIMIT means take out the trash
1274
-            if ($expired_session_transient_delete_query_limit) {
1275
-                $session_key = str_replace('_', '\_', EE_Session::session_id_prefix);
1276
-                $hash_check_key = str_replace('_', '\_', EE_Session::hash_check_prefix);
1277
-                // since transient expiration timestamps are set in the future, we can compare against NOW
1278
-                // but we only want to pick up any trash that's been around for more than a day
1279
-                $expiration = time() - DAY_IN_SECONDS;
1280
-                $SQL = "
1024
+		do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : ' . $class . '::' . $function . '()');
1025
+		$this->reset_cart();
1026
+		$this->reset_checkout();
1027
+		$this->reset_transaction();
1028
+		// wipe out everything that isn't a default session datum
1029
+		$this->reset_data(array_keys($this->_session_data));
1030
+		// reset initial site access time and the session expiration
1031
+		$this->_set_init_access_and_expiration();
1032
+		$this->_save_session_to_db(true);
1033
+	}
1034
+
1035
+
1036
+	/**
1037
+	 * resets all non-default session vars. Returns TRUE on success, FALSE on fail
1038
+	 *
1039
+	 * @param array|mixed $data_to_reset
1040
+	 * @param bool        $show_all_notices
1041
+	 * @return bool
1042
+	 */
1043
+	public function reset_data($data_to_reset = array(), $show_all_notices = false)
1044
+	{
1045
+		// if $data_to_reset is not in an array, then put it in one
1046
+		if (! is_array($data_to_reset)) {
1047
+			$data_to_reset = array($data_to_reset);
1048
+		}
1049
+		// nothing ??? go home!
1050
+		if (empty($data_to_reset)) {
1051
+			EE_Error::add_error(
1052
+				__(
1053
+					'No session data could be reset, because no session var name was provided.',
1054
+					'event_espresso'
1055
+				),
1056
+				__FILE__,
1057
+				__FUNCTION__,
1058
+				__LINE__
1059
+			);
1060
+			return false;
1061
+		}
1062
+		$return_value = true;
1063
+		// since $data_to_reset is an array, cycle through the values
1064
+		foreach ($data_to_reset as $reset) {
1065
+			// first check to make sure it is a valid session var
1066
+			if (isset($this->_session_data[ $reset ])) {
1067
+				// then check to make sure it is not a default var
1068
+				if (! array_key_exists($reset, $this->_default_session_vars)) {
1069
+					// remove session var
1070
+					unset($this->_session_data[ $reset ]);
1071
+					if ($show_all_notices) {
1072
+						EE_Error::add_success(
1073
+							sprintf(
1074
+								__('The session variable %s was removed.', 'event_espresso'),
1075
+								$reset
1076
+							),
1077
+							__FILE__,
1078
+							__FUNCTION__,
1079
+							__LINE__
1080
+						);
1081
+					}
1082
+				} else {
1083
+					// yeeeeeeeeerrrrrrrrrrr OUT !!!!
1084
+					if ($show_all_notices) {
1085
+						EE_Error::add_error(
1086
+							sprintf(
1087
+								__(
1088
+									'Sorry! %s is a default session datum and can not be reset.',
1089
+									'event_espresso'
1090
+								),
1091
+								$reset
1092
+							),
1093
+							__FILE__,
1094
+							__FUNCTION__,
1095
+							__LINE__
1096
+						);
1097
+					}
1098
+					$return_value = false;
1099
+				}
1100
+			} elseif ($show_all_notices) {
1101
+				// oops! that session var does not exist!
1102
+				EE_Error::add_error(
1103
+					sprintf(
1104
+						__(
1105
+							'The session item provided, %s, is invalid or does not exist.',
1106
+							'event_espresso'
1107
+						),
1108
+						$reset
1109
+					),
1110
+					__FILE__,
1111
+					__FUNCTION__,
1112
+					__LINE__
1113
+				);
1114
+				$return_value = false;
1115
+			}
1116
+		} // end of foreach
1117
+		return $return_value;
1118
+	}
1119
+
1120
+
1121
+	/**
1122
+	 *   wp_loaded
1123
+	 *
1124
+	 * @access public
1125
+	 * @throws EE_Error
1126
+	 * @throws InvalidDataTypeException
1127
+	 * @throws InvalidInterfaceException
1128
+	 * @throws InvalidArgumentException
1129
+	 */
1130
+	public function wp_loaded()
1131
+	{
1132
+		if ($this->request->requestParamIsSet('clear_session')) {
1133
+			$this->clear_session(__CLASS__, __FUNCTION__);
1134
+		}
1135
+	}
1136
+
1137
+
1138
+	/**
1139
+	 * Used to reset the entire object (for tests).
1140
+	 *
1141
+	 * @since 4.3.0
1142
+	 * @throws EE_Error
1143
+	 * @throws InvalidDataTypeException
1144
+	 * @throws InvalidInterfaceException
1145
+	 * @throws InvalidArgumentException
1146
+	 */
1147
+	public function reset_instance()
1148
+	{
1149
+		$this->clear_session();
1150
+		self::$_instance = null;
1151
+	}
1152
+
1153
+
1154
+	public function configure_garbage_collection_filters()
1155
+	{
1156
+		// run old filter we had for controlling session cleanup
1157
+		$expired_session_transient_delete_query_limit = absint(
1158
+			apply_filters(
1159
+				'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1160
+				50
1161
+			)
1162
+		);
1163
+		// is there a value? or one that is different than the default 50 records?
1164
+		if ($expired_session_transient_delete_query_limit === 0) {
1165
+			// hook into TransientCacheStorage in case Session cleanup was turned off
1166
+			add_filter('FHEE__TransientCacheStorage__transient_cleanup_schedule', '__return_zero');
1167
+		} elseif ($expired_session_transient_delete_query_limit !== 50) {
1168
+			// or use that for the new transient cleanup query limit
1169
+			add_filter(
1170
+				'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
1171
+				function () use ($expired_session_transient_delete_query_limit) {
1172
+					return $expired_session_transient_delete_query_limit;
1173
+				}
1174
+			);
1175
+		}
1176
+	}
1177
+
1178
+
1179
+	/**
1180
+	 * @see http://stackoverflow.com/questions/10152904/unserialize-function-unserialize-error-at-offset/21389439#10152996
1181
+	 * @param $data1
1182
+	 * @return string
1183
+	 */
1184
+	private function find_serialize_error($data1)
1185
+	{
1186
+		$error = '<pre>';
1187
+		$data2 = preg_replace_callback(
1188
+			'!s:(\d+):"(.*?)";!',
1189
+			function ($match) {
1190
+				return ($match[1] === strlen($match[2]))
1191
+					? $match[0]
1192
+					: 's:'
1193
+					  . strlen($match[2])
1194
+					  . ':"'
1195
+					  . $match[2]
1196
+					  . '";';
1197
+			},
1198
+			$data1
1199
+		);
1200
+		$max = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1201
+		$error .= $data1 . PHP_EOL;
1202
+		$error .= $data2 . PHP_EOL;
1203
+		for ($i = 0; $i < $max; $i++) {
1204
+			if (@$data1[ $i ] !== @$data2[ $i ]) {
1205
+				$error .= 'Difference ' . @$data1[ $i ] . ' != ' . @$data2[ $i ] . PHP_EOL;
1206
+				$error .= "\t-> ORD number " . ord(@$data1[ $i ]) . ' != ' . ord(@$data2[ $i ]) . PHP_EOL;
1207
+				$error .= "\t-> Line Number = $i" . PHP_EOL;
1208
+				$start = ($i - 20);
1209
+				$start = ($start < 0) ? 0 : $start;
1210
+				$length = 40;
1211
+				$point = $max - $i;
1212
+				if ($point < 20) {
1213
+					$rlength = 1;
1214
+					$rpoint = -$point;
1215
+				} else {
1216
+					$rpoint = $length - 20;
1217
+					$rlength = 1;
1218
+				}
1219
+				$error .= "\t-> Section Data1  = ";
1220
+				$error .= substr_replace(
1221
+					substr($data1, $start, $length),
1222
+					"<b style=\"color:green\">{$data1[ $i ]}</b>",
1223
+					$rpoint,
1224
+					$rlength
1225
+				);
1226
+				$error .= PHP_EOL;
1227
+				$error .= "\t-> Section Data2  = ";
1228
+				$error .= substr_replace(
1229
+					substr($data2, $start, $length),
1230
+					"<b style=\"color:red\">{$data2[ $i ]}</b>",
1231
+					$rpoint,
1232
+					$rlength
1233
+				);
1234
+				$error .= PHP_EOL;
1235
+			}
1236
+		}
1237
+		$error .= '</pre>';
1238
+		return $error;
1239
+	}
1240
+
1241
+
1242
+	/**
1243
+	 * Saves an  array of settings used for configuring aspects of session behaviour
1244
+	 *
1245
+	 * @param array $updated_settings
1246
+	 */
1247
+	private function updateSessionSettings(array $updated_settings = array())
1248
+	{
1249
+		// add existing settings, but only if not included in incoming $updated_settings array
1250
+		$updated_settings += get_option(EE_Session::OPTION_NAME_SETTINGS, array());
1251
+		update_option(EE_Session::OPTION_NAME_SETTINGS, $updated_settings);
1252
+	}
1253
+
1254
+
1255
+	/**
1256
+	 * garbage_collection
1257
+	 */
1258
+	public function garbageCollection()
1259
+	{
1260
+		// only perform during regular requests if last garbage collection was over an hour ago
1261
+		if (! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1262
+			$this->_last_gc = time();
1263
+			$this->updateSessionSettings(array('last_gc' => $this->_last_gc));
1264
+			/** @type WPDB $wpdb */
1265
+			global $wpdb;
1266
+			// filter the query limit. Set to 0 to turn off garbage collection
1267
+			$expired_session_transient_delete_query_limit = absint(
1268
+				apply_filters(
1269
+					'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1270
+					50
1271
+				)
1272
+			);
1273
+			// non-zero LIMIT means take out the trash
1274
+			if ($expired_session_transient_delete_query_limit) {
1275
+				$session_key = str_replace('_', '\_', EE_Session::session_id_prefix);
1276
+				$hash_check_key = str_replace('_', '\_', EE_Session::hash_check_prefix);
1277
+				// since transient expiration timestamps are set in the future, we can compare against NOW
1278
+				// but we only want to pick up any trash that's been around for more than a day
1279
+				$expiration = time() - DAY_IN_SECONDS;
1280
+				$SQL = "
1281 1281
                     SELECT option_name
1282 1282
                     FROM {$wpdb->options}
1283 1283
                     WHERE
@@ -1286,17 +1286,17 @@  discard block
 block discarded – undo
1286 1286
                     AND option_value < {$expiration}
1287 1287
                     LIMIT {$expired_session_transient_delete_query_limit}
1288 1288
                 ";
1289
-                // produces something like:
1290
-                // SELECT option_name FROM wp_options
1291
-                // WHERE ( option_name LIKE '\_transient\_timeout\_ee\_ssn\_%'
1292
-                // OR option_name LIKE '\_transient\_timeout\_ee\_shc\_%' )
1293
-                // AND option_value < 1508368198 LIMIT 50
1294
-                $expired_sessions = $wpdb->get_col($SQL);
1295
-                // valid results?
1296
-                if (! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1297
-                    $this->cache_storage->deleteMany($expired_sessions, true);
1298
-                }
1299
-            }
1300
-        }
1301
-    }
1289
+				// produces something like:
1290
+				// SELECT option_name FROM wp_options
1291
+				// WHERE ( option_name LIKE '\_transient\_timeout\_ee\_ssn\_%'
1292
+				// OR option_name LIKE '\_transient\_timeout\_ee\_shc\_%' )
1293
+				// AND option_value < 1508368198 LIMIT 50
1294
+				$expired_sessions = $wpdb->get_col($SQL);
1295
+				// valid results?
1296
+				if (! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1297
+					$this->cache_storage->deleteMany($expired_sessions, true);
1298
+				}
1299
+			}
1300
+		}
1301
+	}
1302 1302
 }
Please login to merge, or discard this patch.
Spacing   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -193,7 +193,7 @@  discard block
 block discarded – undo
193 193
         // check if class object is instantiated
194 194
         // session loading is turned ON by default, but prior to the init hook, can be turned back OFF via:
195 195
         // add_filter( 'FHEE_load_EE_Session', '__return_false' );
196
-        if (! self::$_instance instanceof EE_Session && apply_filters('FHEE_load_EE_Session', true)) {
196
+        if ( ! self::$_instance instanceof EE_Session && apply_filters('FHEE_load_EE_Session', true)) {
197 197
             self::$_instance = new self(
198 198
                 $cache_storage,
199 199
                 $lifespan,
@@ -229,22 +229,22 @@  discard block
 block discarded – undo
229 229
         // but prior to the 'AHEE__EE_System__core_loaded_and_ready' hook
230 230
         // (which currently fires on the init hook at priority 9),
231 231
         // can be turned back OFF via: add_filter( 'FHEE_load_EE_Session', '__return_false' );
232
-        if (! apply_filters('FHEE_load_EE_Session', true)) {
232
+        if ( ! apply_filters('FHEE_load_EE_Session', true)) {
233 233
             return;
234 234
         }
235 235
         $this->session_start_handler = $session_start_handler;
236 236
         $this->session_lifespan = $lifespan;
237 237
         $this->request = $request;
238
-        if (! defined('ESPRESSO_SESSION')) {
238
+        if ( ! defined('ESPRESSO_SESSION')) {
239 239
             define('ESPRESSO_SESSION', true);
240 240
         }
241 241
         // retrieve session options from db
242 242
         $session_settings = (array) get_option(EE_Session::OPTION_NAME_SETTINGS, array());
243
-        if (! empty($session_settings)) {
243
+        if ( ! empty($session_settings)) {
244 244
             // cycle though existing session options
245 245
             foreach ($session_settings as $var_name => $session_setting) {
246 246
                 // set values for class properties
247
-                $var_name = '_' . $var_name;
247
+                $var_name = '_'.$var_name;
248 248
                 $this->{$var_name} = $session_setting;
249 249
             }
250 250
         }
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
     public function open_session()
304 304
     {
305 305
         // check for existing session and retrieve it from db
306
-        if (! $this->_espresso_session()) {
306
+        if ( ! $this->_espresso_session()) {
307 307
             // or just start a new one
308 308
             $this->_create_espresso_session();
309 309
         }
@@ -376,9 +376,9 @@  discard block
 block discarded – undo
376 376
         // set some defaults
377 377
         foreach ($this->_default_session_vars as $key => $default_var) {
378 378
             if (is_array($default_var)) {
379
-                $this->_session_data[ $key ] = array();
379
+                $this->_session_data[$key] = array();
380 380
             } else {
381
-                $this->_session_data[ $key ] = '';
381
+                $this->_session_data[$key] = '';
382 382
             }
383 383
         }
384 384
     }
@@ -509,8 +509,8 @@  discard block
 block discarded – undo
509 509
             $this->reset_checkout();
510 510
             $this->reset_transaction();
511 511
         }
512
-        if (! empty($key)) {
513
-            return isset($this->_session_data[ $key ]) ? $this->_session_data[ $key ] : null;
512
+        if ( ! empty($key)) {
513
+            return isset($this->_session_data[$key]) ? $this->_session_data[$key] : null;
514 514
         }
515 515
         return $this->_session_data;
516 516
     }
@@ -538,7 +538,7 @@  discard block
 block discarded – undo
538 538
             return false;
539 539
         }
540 540
         foreach ($data as $key => $value) {
541
-            if (isset($this->_default_session_vars[ $key ])) {
541
+            if (isset($this->_default_session_vars[$key])) {
542 542
                 EE_Error::add_error(
543 543
                     sprintf(
544 544
                         esc_html__(
@@ -553,7 +553,7 @@  discard block
 block discarded – undo
553 553
                 );
554 554
                 return false;
555 555
             }
556
-            $this->_session_data[ $key ] = $value;
556
+            $this->_session_data[$key] = $value;
557 557
         }
558 558
         return true;
559 559
     }
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
         $this->_user_agent = $this->request->userAgent();
583 583
         // now let's retrieve what's in the db
584 584
         $session_data = $this->_retrieve_session_data();
585
-        if (! empty($session_data)) {
585
+        if ( ! empty($session_data)) {
586 586
             // get the current time in UTC
587 587
             $this->_time = $this->_time !== null ? $this->_time : time();
588 588
             // and reset the session expiration
@@ -593,7 +593,7 @@  discard block
 block discarded – undo
593 593
             // set initial site access time and the session expiration
594 594
             $this->_set_init_access_and_expiration();
595 595
             // set referer
596
-            $this->_session_data['pages_visited'][ $this->_session_data['init_access'] ] = isset($_SERVER['HTTP_REFERER'])
596
+            $this->_session_data['pages_visited'][$this->_session_data['init_access']] = isset($_SERVER['HTTP_REFERER'])
597 597
                 ? esc_attr($_SERVER['HTTP_REFERER'])
598 598
                 : '';
599 599
             // no previous session = go back and create one (on top of the data above)
@@ -630,7 +630,7 @@  discard block
 block discarded – undo
630 630
      */
631 631
     protected function _retrieve_session_data()
632 632
     {
633
-        $ssn_key = EE_Session::session_id_prefix . $this->_sid;
633
+        $ssn_key = EE_Session::session_id_prefix.$this->_sid;
634 634
         try {
635 635
             // we're using WP's Transient API to store session data using the PHP session ID as the option name
636 636
             $session_data = $this->cache_storage->get($ssn_key, false);
@@ -639,7 +639,7 @@  discard block
 block discarded – undo
639 639
             }
640 640
             if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
641 641
                 $hash_check = $this->cache_storage->get(
642
-                    EE_Session::hash_check_prefix . $this->_sid,
642
+                    EE_Session::hash_check_prefix.$this->_sid,
643 643
                     false
644 644
                 );
645 645
                 if ($hash_check && $hash_check !== md5($session_data)) {
@@ -649,7 +649,7 @@  discard block
 block discarded – undo
649 649
                                 'The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.',
650 650
                                 'event_espresso'
651 651
                             ),
652
-                            EE_Session::session_id_prefix . $this->_sid
652
+                            EE_Session::session_id_prefix.$this->_sid
653 653
                         ),
654 654
                         __FILE__,
655 655
                         __FUNCTION__,
@@ -663,17 +663,17 @@  discard block
 block discarded – undo
663 663
             $row = $wpdb->get_row(
664 664
                 $wpdb->prepare(
665 665
                     "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
666
-                    '_transient_' . $ssn_key
666
+                    '_transient_'.$ssn_key
667 667
                 )
668 668
             );
669 669
             $session_data = is_object($row) ? $row->option_value : null;
670 670
             if ($session_data) {
671 671
                 $session_data = preg_replace_callback(
672 672
                     '!s:(d+):"(.*?)";!',
673
-                    function ($match) {
673
+                    function($match) {
674 674
                         return $match[1] === strlen($match[2])
675 675
                             ? $match[0]
676
-                            : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
676
+                            : 's:'.strlen($match[2]).':"'.$match[2].'";';
677 677
                     },
678 678
                     $session_data
679 679
                 );
@@ -684,7 +684,7 @@  discard block
 block discarded – undo
684 684
         $session_data = $this->encryption instanceof EE_Encryption
685 685
             ? $this->encryption->base64_string_decode($session_data)
686 686
             : $session_data;
687
-        if (! is_array($session_data)) {
687
+        if ( ! is_array($session_data)) {
688 688
             try {
689 689
                 $session_data = maybe_unserialize($session_data);
690 690
             } catch (Exception $e) {
@@ -698,21 +698,21 @@  discard block
 block discarded – undo
698 698
                       . '</pre><br>'
699 699
                       . $this->find_serialize_error($session_data)
700 700
                     : '';
701
-                $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
701
+                $this->cache_storage->delete(EE_Session::session_id_prefix.$this->_sid);
702 702
                 throw new InvalidSessionDataException($msg, 0, $e);
703 703
             }
704 704
         }
705 705
         // just a check to make sure the session array is indeed an array
706
-        if (! is_array($session_data)) {
706
+        if ( ! is_array($session_data)) {
707 707
             // no?!?! then something is wrong
708 708
             $msg = esc_html__(
709 709
                 'The session data is missing, invalid, or corrupted.',
710 710
                 'event_espresso'
711 711
             );
712 712
             $msg .= WP_DEBUG
713
-                ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
713
+                ? '<br><pre>'.print_r($session_data, true).'</pre><br>'.$this->find_serialize_error($session_data)
714 714
                 : '';
715
-            $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
715
+            $this->cache_storage->delete(EE_Session::session_id_prefix.$this->_sid);
716 716
             throw new InvalidSessionDataException($msg);
717 717
         }
718 718
         if (isset($session_data['transaction']) && absint($session_data['transaction']) !== 0) {
@@ -739,7 +739,7 @@  discard block
 block discarded – undo
739 739
         if (isset($_REQUEST['EESID'])) {
740 740
             $session_id = sanitize_text_field($_REQUEST['EESID']);
741 741
         } else {
742
-            $session_id = md5(session_id() . get_current_blog_id() . $this->_get_sid_salt());
742
+            $session_id = md5(session_id().get_current_blog_id().$this->_get_sid_salt());
743 743
         }
744 744
         return apply_filters('FHEE__EE_Session___generate_session_id__session_id', $session_id);
745 745
     }
@@ -842,19 +842,19 @@  discard block
 block discarded – undo
842 842
                     $page_visit = $this->_get_page_visit();
843 843
                     if ($page_visit) {
844 844
                         // set pages visited where the first will be the http referrer
845
-                        $this->_session_data['pages_visited'][ $this->_time ] = $page_visit;
845
+                        $this->_session_data['pages_visited'][$this->_time] = $page_visit;
846 846
                         // we'll only save the last 10 page visits.
847 847
                         $session_data['pages_visited'] = array_slice($this->_session_data['pages_visited'], -10);
848 848
                     }
849 849
                     break;
850 850
                 default:
851 851
                     // carry any other data over
852
-                    $session_data[ $key ] = $this->_session_data[ $key ];
852
+                    $session_data[$key] = $this->_session_data[$key];
853 853
             }
854 854
         }
855 855
         $this->_session_data = $session_data;
856 856
         // creating a new session does not require saving to the db just yet
857
-        if (! $new_session) {
857
+        if ( ! $new_session) {
858 858
             // ready? let's save
859 859
             if ($this->_save_session_to_db()) {
860 860
                 return true;
@@ -895,8 +895,8 @@  discard block
 block discarded – undo
895 895
                 isset($this->_session_data['ee_notices'])
896 896
                 && (
897 897
                     ! empty($this->_session_data['ee_notices']['attention'])
898
-                    || !empty($this->_session_data['ee_notices']['errors'])
899
-                    || !empty($this->_session_data['ee_notices']['success'])
898
+                    || ! empty($this->_session_data['ee_notices']['errors'])
899
+                    || ! empty($this->_session_data['ee_notices']['success'])
900 900
                 )
901 901
             );
902 902
     }
@@ -925,7 +925,7 @@  discard block
 block discarded – undo
925 925
         }
926 926
         $transaction = $this->transaction();
927 927
         if ($transaction instanceof EE_Transaction) {
928
-            if (! $transaction->ID()) {
928
+            if ( ! $transaction->ID()) {
929 929
                 $transaction->save();
930 930
             }
931 931
             $this->_session_data['transaction'] = $transaction->ID();
@@ -939,14 +939,14 @@  discard block
 block discarded – undo
939 939
         // maybe save hash check
940 940
         if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
941 941
             $this->cache_storage->add(
942
-                EE_Session::hash_check_prefix . $this->_sid,
942
+                EE_Session::hash_check_prefix.$this->_sid,
943 943
                 md5($session_data),
944 944
                 $this->session_lifespan->inSeconds()
945 945
             );
946 946
         }
947 947
         // we're using the Transient API for storing session data,
948 948
         return $this->cache_storage->add(
949
-            EE_Session::session_id_prefix . $this->_sid,
949
+            EE_Session::session_id_prefix.$this->_sid,
950 950
             $session_data,
951 951
             $this->session_lifespan->inSeconds()
952 952
         );
@@ -960,7 +960,7 @@  discard block
 block discarded – undo
960 960
      */
961 961
     public function _get_page_visit()
962 962
     {
963
-        $page_visit = home_url('/') . 'wp-admin/admin-ajax.php';
963
+        $page_visit = home_url('/').'wp-admin/admin-ajax.php';
964 964
         // check for request url
965 965
         if (isset($_SERVER['REQUEST_URI'])) {
966 966
             $http_host = '';
@@ -976,14 +976,14 @@  discard block
 block discarded – undo
976 976
             // check for page_id in SERVER REQUEST
977 977
             if (isset($_REQUEST['page_id'])) {
978 978
                 // rebuild $e_reg without any of the extra parameters
979
-                $page_id = '?page_id=' . esc_attr($_REQUEST['page_id']) . '&amp;';
979
+                $page_id = '?page_id='.esc_attr($_REQUEST['page_id']).'&amp;';
980 980
             }
981 981
             // check for $e_reg in SERVER REQUEST
982 982
             if (isset($_REQUEST['ee'])) {
983 983
                 // rebuild $e_reg without any of the extra parameters
984
-                $e_reg = 'ee=' . esc_attr($_REQUEST['ee']);
984
+                $e_reg = 'ee='.esc_attr($_REQUEST['ee']);
985 985
             }
986
-            $page_visit = rtrim($http_host . $request_uri . $page_id . $e_reg, '?');
986
+            $page_visit = rtrim($http_host.$request_uri.$page_id.$e_reg, '?');
987 987
         }
988 988
         return $page_visit !== home_url('/wp-admin/admin-ajax.php') ? $page_visit : '';
989 989
     }
@@ -1021,7 +1021,7 @@  discard block
 block discarded – undo
1021 1021
 // <span style="color:#2EA2CC">' . __CLASS__ . '</span>::<span style="color:#E76700">' . __FUNCTION__ . '( ' . $class . '::' . $function . '() )</span><br/>
1022 1022
 // <span style="font-size:9px;font-weight:normal;">' . __FILE__ . '</span>    <b style="font-size:10px;">  ' . __LINE__ . ' </b>
1023 1023
 // </h3>';
1024
-        do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : ' . $class . '::' . $function . '()');
1024
+        do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : '.$class.'::'.$function.'()');
1025 1025
         $this->reset_cart();
1026 1026
         $this->reset_checkout();
1027 1027
         $this->reset_transaction();
@@ -1043,7 +1043,7 @@  discard block
 block discarded – undo
1043 1043
     public function reset_data($data_to_reset = array(), $show_all_notices = false)
1044 1044
     {
1045 1045
         // if $data_to_reset is not in an array, then put it in one
1046
-        if (! is_array($data_to_reset)) {
1046
+        if ( ! is_array($data_to_reset)) {
1047 1047
             $data_to_reset = array($data_to_reset);
1048 1048
         }
1049 1049
         // nothing ??? go home!
@@ -1063,11 +1063,11 @@  discard block
 block discarded – undo
1063 1063
         // since $data_to_reset is an array, cycle through the values
1064 1064
         foreach ($data_to_reset as $reset) {
1065 1065
             // first check to make sure it is a valid session var
1066
-            if (isset($this->_session_data[ $reset ])) {
1066
+            if (isset($this->_session_data[$reset])) {
1067 1067
                 // then check to make sure it is not a default var
1068
-                if (! array_key_exists($reset, $this->_default_session_vars)) {
1068
+                if ( ! array_key_exists($reset, $this->_default_session_vars)) {
1069 1069
                     // remove session var
1070
-                    unset($this->_session_data[ $reset ]);
1070
+                    unset($this->_session_data[$reset]);
1071 1071
                     if ($show_all_notices) {
1072 1072
                         EE_Error::add_success(
1073 1073
                             sprintf(
@@ -1168,7 +1168,7 @@  discard block
 block discarded – undo
1168 1168
             // or use that for the new transient cleanup query limit
1169 1169
             add_filter(
1170 1170
                 'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
1171
-                function () use ($expired_session_transient_delete_query_limit) {
1171
+                function() use ($expired_session_transient_delete_query_limit) {
1172 1172
                     return $expired_session_transient_delete_query_limit;
1173 1173
                 }
1174 1174
             );
@@ -1186,7 +1186,7 @@  discard block
 block discarded – undo
1186 1186
         $error = '<pre>';
1187 1187
         $data2 = preg_replace_callback(
1188 1188
             '!s:(\d+):"(.*?)";!',
1189
-            function ($match) {
1189
+            function($match) {
1190 1190
                 return ($match[1] === strlen($match[2]))
1191 1191
                     ? $match[0]
1192 1192
                     : 's:'
@@ -1198,13 +1198,13 @@  discard block
 block discarded – undo
1198 1198
             $data1
1199 1199
         );
1200 1200
         $max = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1201
-        $error .= $data1 . PHP_EOL;
1202
-        $error .= $data2 . PHP_EOL;
1201
+        $error .= $data1.PHP_EOL;
1202
+        $error .= $data2.PHP_EOL;
1203 1203
         for ($i = 0; $i < $max; $i++) {
1204
-            if (@$data1[ $i ] !== @$data2[ $i ]) {
1205
-                $error .= 'Difference ' . @$data1[ $i ] . ' != ' . @$data2[ $i ] . PHP_EOL;
1206
-                $error .= "\t-> ORD number " . ord(@$data1[ $i ]) . ' != ' . ord(@$data2[ $i ]) . PHP_EOL;
1207
-                $error .= "\t-> Line Number = $i" . PHP_EOL;
1204
+            if (@$data1[$i] !== @$data2[$i]) {
1205
+                $error .= 'Difference '.@$data1[$i].' != '.@$data2[$i].PHP_EOL;
1206
+                $error .= "\t-> ORD number ".ord(@$data1[$i]).' != '.ord(@$data2[$i]).PHP_EOL;
1207
+                $error .= "\t-> Line Number = $i".PHP_EOL;
1208 1208
                 $start = ($i - 20);
1209 1209
                 $start = ($start < 0) ? 0 : $start;
1210 1210
                 $length = 40;
@@ -1219,7 +1219,7 @@  discard block
 block discarded – undo
1219 1219
                 $error .= "\t-> Section Data1  = ";
1220 1220
                 $error .= substr_replace(
1221 1221
                     substr($data1, $start, $length),
1222
-                    "<b style=\"color:green\">{$data1[ $i ]}</b>",
1222
+                    "<b style=\"color:green\">{$data1[$i]}</b>",
1223 1223
                     $rpoint,
1224 1224
                     $rlength
1225 1225
                 );
@@ -1227,7 +1227,7 @@  discard block
 block discarded – undo
1227 1227
                 $error .= "\t-> Section Data2  = ";
1228 1228
                 $error .= substr_replace(
1229 1229
                     substr($data2, $start, $length),
1230
-                    "<b style=\"color:red\">{$data2[ $i ]}</b>",
1230
+                    "<b style=\"color:red\">{$data2[$i]}</b>",
1231 1231
                     $rpoint,
1232 1232
                     $rlength
1233 1233
                 );
@@ -1258,7 +1258,7 @@  discard block
 block discarded – undo
1258 1258
     public function garbageCollection()
1259 1259
     {
1260 1260
         // only perform during regular requests if last garbage collection was over an hour ago
1261
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1261
+        if ( ! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1262 1262
             $this->_last_gc = time();
1263 1263
             $this->updateSessionSettings(array('last_gc' => $this->_last_gc));
1264 1264
             /** @type WPDB $wpdb */
@@ -1293,7 +1293,7 @@  discard block
 block discarded – undo
1293 1293
                 // AND option_value < 1508368198 LIMIT 50
1294 1294
                 $expired_sessions = $wpdb->get_col($SQL);
1295 1295
                 // valid results?
1296
-                if (! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1296
+                if ( ! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1297 1297
                     $this->cache_storage->deleteMany($expired_sessions, true);
1298 1298
                 }
1299 1299
             }
Please login to merge, or discard this patch.