Completed
Branch FET/11450/reserved-instance-in... (0b2d22)
by
unknown
32:10 queued 12:45
created
core/EE_Deprecated.core.php 2 patches
Spacing   +178 added lines, -178 removed lines patch added patch discarded remove patch
@@ -4,8 +4,8 @@  discard block
 block discarded – undo
4 4
 use EventEspresso\core\interfaces\InterminableInterface;
5 5
 use EventEspresso\core\services\licensing\LicenseService;
6 6
 
7
-if ( ! defined( 'EVENT_ESPRESSO_VERSION' ) ) {
8
-	exit( 'No direct script access allowed' );
7
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
8
+	exit('No direct script access allowed');
9 9
 }
10 10
 /**
11 11
  * ************************************************************************
@@ -48,8 +48,8 @@  discard block
 block discarded – undo
48 48
 	$action_or_filter = 'action'
49 49
 ) {
50 50
 	$action_or_filter = $action_or_filter === 'action'
51
-		? esc_html__( 'action', 'event_espresso' )
52
-		: esc_html__( 'filter', 'event_espresso' );
51
+		? esc_html__('action', 'event_espresso')
52
+		: esc_html__('filter', 'event_espresso');
53 53
 	EE_Error::doing_it_wrong(
54 54
 		$deprecated_filter,
55 55
 		sprintf(
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
  * @param \EE_Checkout $checkout
74 74
  * @return string
75 75
  */
76
-function ee_deprecated__registration_checkout__button_text( $submit_button_text, EE_Checkout $checkout ) {
76
+function ee_deprecated__registration_checkout__button_text($submit_button_text, EE_Checkout $checkout) {
77 77
 	// list of old filters
78 78
 	$deprecated_filters = array(
79 79
 		'update_registration_details' => true,
@@ -83,16 +83,16 @@  discard block
 block discarded – undo
83 83
 		'proceed_to' => true,
84 84
 	);
85 85
 	// loop thru and call doing_it_wrong() or remove any that aren't being used
86
-	foreach ( $deprecated_filters as $deprecated_filter => $on ) {
86
+	foreach ($deprecated_filters as $deprecated_filter => $on) {
87 87
 		// was this filter called ?
88
-		if ( has_action( 'FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__' . $deprecated_filter )) {
88
+		if (has_action('FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__'.$deprecated_filter)) {
89 89
 			// only display doing_it_wrong() notice to Event Admins during non-AJAX requests
90
-			if ( EE_Registry::instance()->CAP->current_user_can( 'ee_read_ee', 'hide_doing_it_wrong_for_deprecated_SPCO_filter' ) && ! defined( 'DOING_AJAX' ) ) {
90
+			if (EE_Registry::instance()->CAP->current_user_can('ee_read_ee', 'hide_doing_it_wrong_for_deprecated_SPCO_filter') && ! defined('DOING_AJAX')) {
91 91
 				EE_Error::doing_it_wrong(
92
-					'FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__' . $deprecated_filter,
92
+					'FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__'.$deprecated_filter,
93 93
 					sprintf(
94
-						__( 'The %1$s filter is deprecated.  It *may* work as an attempt to build in backwards compatibility.  However, it is recommended to use the following new filter: %2$s"%3$s" found in "%4$s"', 'event_espresso' ),
95
-						'FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__' . $deprecated_filter,
94
+						__('The %1$s filter is deprecated.  It *may* work as an attempt to build in backwards compatibility.  However, it is recommended to use the following new filter: %2$s"%3$s" found in "%4$s"', 'event_espresso'),
95
+						'FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__'.$deprecated_filter,
96 96
 						'<br />',
97 97
 						'FHEE__EE_SPCO_Reg_Step__set_submit_button_text___submit_button_text',
98 98
 						'/modules/single_page_checkout/inc/EE_SPCO_Reg_Step.class.php'
@@ -101,24 +101,24 @@  discard block
 block discarded – undo
101 101
 				);
102 102
 			}
103 103
 		} else {
104
-			unset( $deprecated_filters[ $deprecated_filter ] );
104
+			unset($deprecated_filters[$deprecated_filter]);
105 105
 		}
106 106
 	}
107
-	if ( ! empty( $deprecated_filters )) {
108
-
109
-		if ( $checkout->current_step->slug() == 'attendee_information' && $checkout->revisit && isset( $deprecated_filters[ 'update_registration_details' ] )) {
110
-			$submit_button_text = apply_filters( 'FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__update_registration_details', $submit_button_text );
111
-		} else if ( $checkout->current_step->slug() == 'payment_options' && $checkout->revisit && isset( $deprecated_filters[ 'process_payment' ] ) ) {
112
-			$submit_button_text = apply_filters( 'FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__process_payment', $submit_button_text );
113
-		} else if ( $checkout->next_step instanceof EE_SPCO_Reg_Step && $checkout->next_step->slug() == 'finalize_registration' && isset( $deprecated_filters[ 'finalize_registration' ] ) ) {
114
-			$submit_button_text = apply_filters( 'FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__finalize_registration', $submit_button_text );
107
+	if ( ! empty($deprecated_filters)) {
108
+
109
+		if ($checkout->current_step->slug() == 'attendee_information' && $checkout->revisit && isset($deprecated_filters['update_registration_details'])) {
110
+			$submit_button_text = apply_filters('FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__update_registration_details', $submit_button_text);
111
+		} else if ($checkout->current_step->slug() == 'payment_options' && $checkout->revisit && isset($deprecated_filters['process_payment'])) {
112
+			$submit_button_text = apply_filters('FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__process_payment', $submit_button_text);
113
+		} else if ($checkout->next_step instanceof EE_SPCO_Reg_Step && $checkout->next_step->slug() == 'finalize_registration' && isset($deprecated_filters['finalize_registration'])) {
114
+			$submit_button_text = apply_filters('FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__finalize_registration', $submit_button_text);
115 115
 		}
116
-		if ( $checkout->next_step instanceof EE_SPCO_Reg_Step ) {
117
-			if ( $checkout->payment_required() && $checkout->next_step->slug() == 'payment_options' && isset( $deprecated_filters[ 'and_proceed_to_payment' ] ) ) {
118
-				$submit_button_text .= apply_filters( 'FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__and_proceed_to_payment', $submit_button_text );
116
+		if ($checkout->next_step instanceof EE_SPCO_Reg_Step) {
117
+			if ($checkout->payment_required() && $checkout->next_step->slug() == 'payment_options' && isset($deprecated_filters['and_proceed_to_payment'])) {
118
+				$submit_button_text .= apply_filters('FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__and_proceed_to_payment', $submit_button_text);
119 119
 			}
120
-			if ( $checkout->next_step->slug() != 'finalize_registration' && ! $checkout->revisit && isset( $deprecated_filters[ 'proceed_to' ] ) ) {
121
-				$submit_button_text = apply_filters( 'FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__proceed_to', $submit_button_text ) . $checkout->next_step->name();
120
+			if ($checkout->next_step->slug() != 'finalize_registration' && ! $checkout->revisit && isset($deprecated_filters['proceed_to'])) {
121
+				$submit_button_text = apply_filters('FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__proceed_to', $submit_button_text).$checkout->next_step->name();
122 122
 			}
123 123
 		}
124 124
 
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 	return $submit_button_text;
127 127
 
128 128
 }
129
-add_filter( 'FHEE__EE_SPCO_Reg_Step__set_submit_button_text___submit_button_text', 'ee_deprecated__registration_checkout__button_text', 10, 2 );
129
+add_filter('FHEE__EE_SPCO_Reg_Step__set_submit_button_text___submit_button_text', 'ee_deprecated__registration_checkout__button_text', 10, 2);
130 130
 
131 131
 
132 132
 
@@ -137,16 +137,16 @@  discard block
 block discarded – undo
137 137
  * @param \EE_Checkout $checkout
138 138
  * @param boolean $status_updates
139 139
  */
140
-function ee_deprecated_finalize_transaction( EE_Checkout $checkout, $status_updates ) {
140
+function ee_deprecated_finalize_transaction(EE_Checkout $checkout, $status_updates) {
141 141
 	$action_ref = NULL;
142
-	$action_ref = has_action( 'AHEE__EE_Transaction__finalize__new_transaction' ) ? 'AHEE__EE_Transaction__finalize__new_transaction' : $action_ref;
143
-	$action_ref = has_action( 'AHEE__EE_Transaction__finalize__all_transaction' ) ? 'AHEE__EE_Transaction__finalize__all_transaction' : $action_ref;
144
-	if ( $action_ref ) {
142
+	$action_ref = has_action('AHEE__EE_Transaction__finalize__new_transaction') ? 'AHEE__EE_Transaction__finalize__new_transaction' : $action_ref;
143
+	$action_ref = has_action('AHEE__EE_Transaction__finalize__all_transaction') ? 'AHEE__EE_Transaction__finalize__all_transaction' : $action_ref;
144
+	if ($action_ref) {
145 145
 
146 146
 		EE_Error::doing_it_wrong(
147 147
 			$action_ref,
148 148
 			sprintf(
149
-				__( 'This action is deprecated.  It *may* work as an attempt to build in backwards compatibility.  However, it is recommended to use one of the following new actions: %1$s"%3$s" found in "%2$s" %1$s"%4$s" found in "%2$s" %1$s"%5$s" found in "%2$s" %1$s"%6$s" found in "%2$s"', 'event_espresso' ),
149
+				__('This action is deprecated.  It *may* work as an attempt to build in backwards compatibility.  However, it is recommended to use one of the following new actions: %1$s"%3$s" found in "%2$s" %1$s"%4$s" found in "%2$s" %1$s"%5$s" found in "%2$s" %1$s"%6$s" found in "%2$s"', 'event_espresso'),
150 150
 				'<br />',
151 151
 				'/core/business/EE_Transaction_Processor.class.php',
152 152
 				'AHEE__EE_Transaction_Processor__finalize',
@@ -156,39 +156,39 @@  discard block
 block discarded – undo
156 156
 			),
157 157
 			'4.6.0'
158 158
 		);
159
-		switch ( $action_ref ) {
159
+		switch ($action_ref) {
160 160
 			case 'AHEE__EE_Transaction__finalize__new_transaction' :
161
-				do_action( 'AHEE__EE_Transaction__finalize__new_transaction', $checkout->transaction, $checkout->admin_request );
161
+				do_action('AHEE__EE_Transaction__finalize__new_transaction', $checkout->transaction, $checkout->admin_request);
162 162
 				break;
163 163
 			case 'AHEE__EE_Transaction__finalize__all_transaction' :
164
-				do_action( 'AHEE__EE_Transaction__finalize__new_transaction', $checkout->transaction, array( 'new_reg' => ! $checkout->revisit, 'to_approved' => $status_updates ), $checkout->admin_request );
164
+				do_action('AHEE__EE_Transaction__finalize__new_transaction', $checkout->transaction, array('new_reg' => ! $checkout->revisit, 'to_approved' => $status_updates), $checkout->admin_request);
165 165
 				break;
166 166
 		}
167 167
 	}
168 168
 }
169
-add_action( 'AHEE__EE_SPCO_Reg_Step_Finalize_Registration__process_reg_step__completed', 'ee_deprecated_finalize_transaction', 10, 2 );
169
+add_action('AHEE__EE_SPCO_Reg_Step_Finalize_Registration__process_reg_step__completed', 'ee_deprecated_finalize_transaction', 10, 2);
170 170
 /**
171 171
  * ee_deprecated_finalize_registration
172 172
  *
173 173
  * @param EE_Registration $registration
174 174
  */
175
-function ee_deprecated_finalize_registration( EE_Registration $registration ) {
176
-	$action_ref = has_action( 'AHEE__EE_Registration__finalize__update_and_new_reg' ) ? 'AHEE__EE_Registration__finalize__update_and_new_reg' : NULL;
177
-	if ( $action_ref ) {
175
+function ee_deprecated_finalize_registration(EE_Registration $registration) {
176
+	$action_ref = has_action('AHEE__EE_Registration__finalize__update_and_new_reg') ? 'AHEE__EE_Registration__finalize__update_and_new_reg' : NULL;
177
+	if ($action_ref) {
178 178
 		EE_Error::doing_it_wrong(
179 179
 			$action_ref,
180 180
 			sprintf(
181
-				__( 'This action is deprecated.  It *may* work as an attempt to build in backwards compatibility.  However, it is recommended to use the following new action: %1$s"%3$s" found in "%2$s"', 'event_espresso' ),
181
+				__('This action is deprecated.  It *may* work as an attempt to build in backwards compatibility.  However, it is recommended to use the following new action: %1$s"%3$s" found in "%2$s"', 'event_espresso'),
182 182
 				'<br />',
183 183
 				'/core/business/EE_Registration_Processor.class.php',
184 184
 				'AHEE__EE_Registration_Processor__trigger_registration_status_changed_hook'
185 185
 			),
186 186
 			'4.6.0'
187 187
 		);
188
-		do_action( 'AHEE__EE_Registration__finalize__update_and_new_reg', $registration, ( is_admin() && ! ( defined( 'DOING_AJAX' ) && DOING_AJAX )));
188
+		do_action('AHEE__EE_Registration__finalize__update_and_new_reg', $registration, (is_admin() && ! (defined('DOING_AJAX') && DOING_AJAX)));
189 189
 	}
190 190
 }
191
-add_action( 'AHEE__EE_Registration_Processor__trigger_registration_update_notifications', 'ee_deprecated_finalize_registration', 10, 1 );
191
+add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications', 'ee_deprecated_finalize_registration', 10, 1);
192 192
 
193 193
 
194 194
 
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
  * Called after EED_Module::set_hooks() and EED_Module::set_admin_hooks() was called.
197 197
  * Checks if any deprecated hooks were hooked-into and provide doing_it_wrong messages appropriately.
198 198
  */
199
-function ee_deprecated_hooks(){
199
+function ee_deprecated_hooks() {
200 200
 	/**
201 201
 	 * @var $hooks array where keys are hook names, and their values are array{
202 202
 	 *			@type string $version  when deprecated
@@ -207,25 +207,25 @@  discard block
 block discarded – undo
207 207
 	$hooks = array(
208 208
 		'AHEE__EE_System___do_setup_validations' => array(
209 209
 			'version' => '4.6.0',
210
-			'alternative' => __( 'Instead use "AHEE__EEH_Activation__validate_messages_system" which is called after validating messages (done on every new install, upgrade, reactivation, and downgrade)', 'event_espresso' ),
210
+			'alternative' => __('Instead use "AHEE__EEH_Activation__validate_messages_system" which is called after validating messages (done on every new install, upgrade, reactivation, and downgrade)', 'event_espresso'),
211 211
 			'still_works' => FALSE
212 212
 		)
213 213
 	);
214
-	foreach( $hooks as $name => $deprecation_info ){
215
-		if( has_action( $name ) ){
214
+	foreach ($hooks as $name => $deprecation_info) {
215
+		if (has_action($name)) {
216 216
 			EE_Error::doing_it_wrong(
217 217
 				$name,
218 218
 				sprintf(
219
-					__('This filter is deprecated. %1$s%2$s','event_espresso'),
220
-					$deprecation_info[ 'still_works' ] ?  __('It *may* work as an attempt to build in backwards compatibility.', 'event_espresso') : __( 'It has been completely removed.', 'event_espresso' ),
221
-					isset( $deprecation_info[ 'alternative' ] ) ? $deprecation_info[ 'alternative' ] : __( 'Please read the current EE4 documentation further or contact Support.', 'event_espresso' )
219
+					__('This filter is deprecated. %1$s%2$s', 'event_espresso'),
220
+					$deprecation_info['still_works'] ?  __('It *may* work as an attempt to build in backwards compatibility.', 'event_espresso') : __('It has been completely removed.', 'event_espresso'),
221
+					isset($deprecation_info['alternative']) ? $deprecation_info['alternative'] : __('Please read the current EE4 documentation further or contact Support.', 'event_espresso')
222 222
 				),
223
-				isset( $deprecation_info[ 'version' ] ) ? $deprecation_info[ 'version' ] : __( 'recently', 'event_espresso' )
223
+				isset($deprecation_info['version']) ? $deprecation_info['version'] : __('recently', 'event_espresso')
224 224
 			);
225 225
 		}
226 226
 	}
227 227
 }
228
-add_action( 'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons', 'ee_deprecated_hooks' );
228
+add_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons', 'ee_deprecated_hooks');
229 229
 
230 230
 
231 231
 
@@ -236,9 +236,9 @@  discard block
 block discarded – undo
236 236
  * @return boolean
237 237
  */
238 238
 function ee_deprecated_using_old_registration_admin_custom_questions_form_hooks() {
239
-	$in_use =  has_filter( 'FHEE__Registrations_Admin_Page___update_attendee_registration_form__qstns' )
240
-			|| has_action( 'AHEE__Registrations_Admin_Page___save_attendee_registration_form__after_reg_and_attendee_save' );
241
-	if( $in_use ) {
239
+	$in_use = has_filter('FHEE__Registrations_Admin_Page___update_attendee_registration_form__qstns')
240
+			|| has_action('AHEE__Registrations_Admin_Page___save_attendee_registration_form__after_reg_and_attendee_save');
241
+	if ($in_use) {
242 242
 		$msg = __(
243 243
 			'We detected you are using the filter FHEE__Registrations_Admin_Page___update_attendee_registration_form__qstns or AHEE__Registrations_Admin_Page___save_attendee_registration_form__after_reg_and_attendee_save.'
244 244
 			. 'Both of these have been deprecated and should not be used anymore. You should instead use FHEE__EE_Form_Section_Proper___construct__options_array to customize the contents of the form,'
@@ -247,18 +247,18 @@  discard block
 block discarded – undo
247 247
 			'event_espresso' )
248 248
 		;
249 249
 		EE_Error::doing_it_wrong(
250
-			__CLASS__ . '::' . __FUNCTION__,
250
+			__CLASS__.'::'.__FUNCTION__,
251 251
 			$msg,
252 252
 			'4.8.32.rc.000'
253 253
 		);
254 254
 		//it seems the doing_it_wrong messages get output during some hidden html tags, so add an error to make sure this gets noticed
255
-		if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
256
-			EE_Error::add_error( $msg, __FILE__, __FUNCTION__, __LINE__ );
255
+		if (is_admin() && ! defined('DOING_AJAX')) {
256
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
257 257
 		}
258 258
 	}
259 259
 	return $in_use;
260 260
 }
261
-add_action( 'AHEE__Registrations_Admin_Page___registration_details_metabox__start', 'ee_deprecated_using_old_registration_admin_custom_questions_form_hooks' );
261
+add_action('AHEE__Registrations_Admin_Page___registration_details_metabox__start', 'ee_deprecated_using_old_registration_admin_custom_questions_form_hooks');
262 262
 
263 263
 /**
264 264
  * @deprecated since 4.8.32.rc.000 because it has issues on https://events.codebasehq.com/projects/event-espresso/tickets/9165
@@ -267,34 +267,34 @@  discard block
 block discarded – undo
267 267
  * @param EE_Admin_Page $admin_page
268 268
  * @return void
269 269
  */
270
-function ee_deprecated_update_attendee_registration_form_old( $admin_page ) {
270
+function ee_deprecated_update_attendee_registration_form_old($admin_page) {
271 271
 	//check if the old hooks are in use. If not, do the default
272
-	if( ! ee_deprecated_using_old_registration_admin_custom_questions_form_hooks()
273
-		|| ! $admin_page instanceof EE_Admin_Page ) {
272
+	if ( ! ee_deprecated_using_old_registration_admin_custom_questions_form_hooks()
273
+		|| ! $admin_page instanceof EE_Admin_Page) {
274 274
 		return;
275 275
 	}
276 276
 	$req_data = $admin_page->get_request_data();
277
-	$qstns = isset( $req_data['qstn'] ) ? $req_data['qstn'] : FALSE;
278
-	$REG_ID = isset( $req_data['_REG_ID'] ) ? absint( $req_data['_REG_ID'] ) : FALSE;
279
-	$qstns = apply_filters( 'FHEE__Registrations_Admin_Page___update_attendee_registration_form__qstns', $qstns );
280
-	if ( ! $REG_ID || ! $qstns ) {
281
-		EE_Error::add_error( __('An error occurred. No registration ID and/or registration questions were received.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__ );
277
+	$qstns = isset($req_data['qstn']) ? $req_data['qstn'] : FALSE;
278
+	$REG_ID = isset($req_data['_REG_ID']) ? absint($req_data['_REG_ID']) : FALSE;
279
+	$qstns = apply_filters('FHEE__Registrations_Admin_Page___update_attendee_registration_form__qstns', $qstns);
280
+	if ( ! $REG_ID || ! $qstns) {
281
+		EE_Error::add_error(__('An error occurred. No registration ID and/or registration questions were received.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
282 282
 	}
283 283
 	$success = TRUE;
284 284
 
285 285
 	// allow others to get in on this awesome fun   :D
286
-	do_action( 'AHEE__Registrations_Admin_Page___save_attendee_registration_form__after_reg_and_attendee_save', $REG_ID, $qstns );
286
+	do_action('AHEE__Registrations_Admin_Page___save_attendee_registration_form__after_reg_and_attendee_save', $REG_ID, $qstns);
287 287
 	// loop thru questions... FINALLY!!!
288 288
 
289
-	foreach ( $qstns as $QST_ID => $qstn ) {
289
+	foreach ($qstns as $QST_ID => $qstn) {
290 290
 		//if $qstn isn't an array then it doesn't already have an answer, so let's create the answer
291
-		if ( !is_array($qstn) ) {
292
-			$success = $this->_save_new_answer( $REG_ID, $QST_ID, $qstn);
291
+		if ( ! is_array($qstn)) {
292
+			$success = $this->_save_new_answer($REG_ID, $QST_ID, $qstn);
293 293
 			continue;
294 294
 		}
295 295
 
296 296
 
297
-		foreach ( $qstn as $ANS_ID => $ANS_value ) {
297
+		foreach ($qstn as $ANS_ID => $ANS_value) {
298 298
 			//get answer
299 299
 			$query_params = array(
300 300
 				0 => array(
@@ -305,7 +305,7 @@  discard block
 block discarded – undo
305 305
 				);
306 306
 			$answer = EEM_Answer::instance()->get_one($query_params);
307 307
 			//this MAY be an array but NOT have an answer because its multi select.  If so then we need to create the answer
308
-			if ( ! $answer instanceof EE_Answer ) {
308
+			if ( ! $answer instanceof EE_Answer) {
309 309
 				$set_values = array(
310 310
 					'QST_ID' => $QST_ID,
311 311
 					'REG_ID' => $REG_ID,
@@ -320,11 +320,11 @@  discard block
 block discarded – undo
320 320
 		}
321 321
 	}
322 322
 	$what = __('Registration Form', 'event_espresso');
323
-	$route = $REG_ID ? array( 'action' => 'view_registration', '_REG_ID' => $REG_ID ) : array( 'action' => 'default' );
324
-	$admin_page->redirect_after_action( $success, $what, __('updated', 'event_espresso'), $route );
323
+	$route = $REG_ID ? array('action' => 'view_registration', '_REG_ID' => $REG_ID) : array('action' => 'default');
324
+	$admin_page->redirect_after_action($success, $what, __('updated', 'event_espresso'), $route);
325 325
 	exit;
326 326
 }
327
-add_action( 'AHEE__Registrations_Admin_Page___update_attendee_registration_form__start', 'ee_deprecated_update_attendee_registration_form_old', 10, 1 );
327
+add_action('AHEE__Registrations_Admin_Page___update_attendee_registration_form__start', 'ee_deprecated_update_attendee_registration_form_old', 10, 1);
328 328
 /**
329 329
  * Render the registration admin page's custom questions area in the old fashion
330 330
  * and firing the old hooks. When this method is removed, we can probably also
@@ -337,31 +337,31 @@  discard block
 block discarded – undo
337 337
  * @return bool
338 338
  * @throws \EE_Error
339 339
  */
340
-function ee_deprecated_reg_questions_meta_box_old( $do_default_action, $admin_page, $registration ) {
340
+function ee_deprecated_reg_questions_meta_box_old($do_default_action, $admin_page, $registration) {
341 341
 	//check if the old hooks are in use. If not, do the default
342
-	if( ! ee_deprecated_using_old_registration_admin_custom_questions_form_hooks()
343
-		|| ! $admin_page instanceof EE_Admin_Page ) {
342
+	if ( ! ee_deprecated_using_old_registration_admin_custom_questions_form_hooks()
343
+		|| ! $admin_page instanceof EE_Admin_Page) {
344 344
 		return $do_default_action;
345 345
 	}
346
-	add_filter( 'FHEE__EEH_Form_Fields__generate_question_groups_html__before_question_group_questions', array( $admin_page, 'form_before_question_group' ), 10, 1 );
347
-	add_filter( 'FHEE__EEH_Form_Fields__generate_question_groups_html__after_question_group_questions', array( $admin_page, 'form_after_question_group' ), 10, 1 );
348
-	add_filter( 'FHEE__EEH_Form_Fields__label_html', array( $admin_page, 'form_form_field_label_wrap' ), 10, 1 );
349
-	add_filter( 'FHEE__EEH_Form_Fields__input_html', array( $admin_page, 'form_form_field_input__wrap' ), 10, 1 );
346
+	add_filter('FHEE__EEH_Form_Fields__generate_question_groups_html__before_question_group_questions', array($admin_page, 'form_before_question_group'), 10, 1);
347
+	add_filter('FHEE__EEH_Form_Fields__generate_question_groups_html__after_question_group_questions', array($admin_page, 'form_after_question_group'), 10, 1);
348
+	add_filter('FHEE__EEH_Form_Fields__label_html', array($admin_page, 'form_form_field_label_wrap'), 10, 1);
349
+	add_filter('FHEE__EEH_Form_Fields__input_html', array($admin_page, 'form_form_field_input__wrap'), 10, 1);
350 350
 
351
-	$question_groups = EEM_Event::instance()->assemble_array_of_groups_questions_and_options( $registration, $registration->get('EVT_ID') );
351
+	$question_groups = EEM_Event::instance()->assemble_array_of_groups_questions_and_options($registration, $registration->get('EVT_ID'));
352 352
 
353
-	EE_Registry::instance()->load_helper( 'Form_Fields' );
353
+	EE_Registry::instance()->load_helper('Form_Fields');
354 354
 	$template_args = array(
355
-		'att_questions' => EEH_Form_Fields::generate_question_groups_html( $question_groups ),
355
+		'att_questions' => EEH_Form_Fields::generate_question_groups_html($question_groups),
356 356
 		'reg_questions_form_action' => 'edit_registration',
357 357
 		'REG_ID' => $registration->ID()
358 358
 	);
359
-	$template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_questions.template.php';
360
-	echo EEH_Template::display_template( $template_path, $template_args, TRUE );
359
+	$template_path = REG_TEMPLATE_PATH.'reg_admin_details_main_meta_box_reg_questions.template.php';
360
+	echo EEH_Template::display_template($template_path, $template_args, TRUE);
361 361
 	//indicate that we should not do the default admin page code
362 362
 	return false;
363 363
 }
364
-add_action( 'FHEE__Registrations_Admin_Page___reg_questions_meta_box__do_default', 'ee_deprecated_reg_questions_meta_box_old', 10, 3 );
364
+add_action('FHEE__Registrations_Admin_Page___reg_questions_meta_box__do_default', 'ee_deprecated_reg_questions_meta_box_old', 10, 3);
365 365
 
366 366
 
367 367
 
@@ -402,9 +402,9 @@  discard block
 block discarded – undo
402 402
 			'4.9.0'
403 403
 		);
404 404
 		/** @var EE_Message_Resource_Manager $message_resource_manager */
405
-		$message_resource_manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' );
406
-		$messenger = $message_resource_manager->get_messenger( $messenger_name );
407
-		$message_type = $message_resource_manager->get_message_type( $message_type_name );
405
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
406
+		$messenger = $message_resource_manager->get_messenger($messenger_name);
407
+		$message_type = $message_resource_manager->get_message_type($message_type_name);
408 408
 		return EE_Registry::instance()->load_lib(
409 409
 			'Messages_Template_Defaults',
410 410
 			array(
@@ -469,15 +469,15 @@  discard block
 block discarded – undo
469 469
 	/**
470 470
 	 * @param string $method
471 471
 	 */
472
-	public function _class_is_deprecated( $method ) {
472
+	public function _class_is_deprecated($method) {
473 473
 		EE_Error::doing_it_wrong(
474
-			'EE_messages::' . $method,
475
-			__( 'EE_messages has been deprecated.  Please use EE_Message_Resource_Manager instead.' ),
474
+			'EE_messages::'.$method,
475
+			__('EE_messages has been deprecated.  Please use EE_Message_Resource_Manager instead.'),
476 476
 			'4.9.0',
477 477
 			'4.10.0.p'
478 478
 		);
479 479
 		// Please use EE_Message_Resource_Manager instead
480
-		$this->_message_resource_manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' );
480
+		$this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
481 481
 	}
482 482
 
483 483
 
@@ -487,10 +487,10 @@  discard block
 block discarded – undo
487 487
 	 * @param string $messenger_name
488 488
 	 * @return boolean TRUE if it was PREVIOUSLY active, and FALSE if it was previously inactive
489 489
 	 */
490
-	public function ensure_messenger_is_active( $messenger_name ) {
490
+	public function ensure_messenger_is_active($messenger_name) {
491 491
 		// EE_messages has been deprecated
492
-		$this->_class_is_deprecated( __FUNCTION__ );
493
-		return $this->_message_resource_manager->ensure_messenger_is_active( $messenger_name );
492
+		$this->_class_is_deprecated(__FUNCTION__);
493
+		return $this->_message_resource_manager->ensure_messenger_is_active($messenger_name);
494 494
 	}
495 495
 
496 496
 
@@ -502,10 +502,10 @@  discard block
 block discarded – undo
502 502
 	 * @return bool true if it got activated (or was active) and false if not.
503 503
 	 * @throws \EE_Error
504 504
 	 */
505
-	public function ensure_message_type_is_active( $message_type, $messenger ) {
505
+	public function ensure_message_type_is_active($message_type, $messenger) {
506 506
 		// EE_messages has been deprecated
507
-		$this->_class_is_deprecated( __FUNCTION__ );
508
-		return $this->_message_resource_manager->ensure_message_type_is_active( $message_type, $messenger );
507
+		$this->_class_is_deprecated(__FUNCTION__);
508
+		return $this->_message_resource_manager->ensure_message_type_is_active($message_type, $messenger);
509 509
 	}
510 510
 
511 511
 
@@ -518,10 +518,10 @@  discard block
 block discarded – undo
518 518
 	 *                                            they are already setup.)
519 519
 	 * @return boolean an array of generated templates or false if nothing generated/activated.
520 520
 	 */
521
-	public function activate_messenger( $messenger_name, $mts_to_activate = array() ) {
521
+	public function activate_messenger($messenger_name, $mts_to_activate = array()) {
522 522
 		// EE_messages has been deprecated
523
-		$this->_class_is_deprecated( __FUNCTION__ );
524
-		return $this->_message_resource_manager->activate_messenger( $messenger_name, $mts_to_activate );
523
+		$this->_class_is_deprecated(__FUNCTION__);
524
+		return $this->_message_resource_manager->activate_messenger($messenger_name, $mts_to_activate);
525 525
 	}
526 526
 
527 527
 
@@ -533,10 +533,10 @@  discard block
 block discarded – undo
533 533
 	 *
534 534
 	 * @return bool true is a generating messenger and can be sent OR FALSE meaning cannot send.
535 535
 	 */
536
-	public function is_generating_messenger_and_active( EE_messenger $messenger, EE_message_type $message_type ) {
536
+	public function is_generating_messenger_and_active(EE_messenger $messenger, EE_message_type $message_type) {
537 537
 		// EE_messages has been deprecated
538
-		$this->_class_is_deprecated( __FUNCTION__ );
539
-		return $this->_message_resource_manager->is_generating_messenger_and_active( $messenger, $message_type );
538
+		$this->_class_is_deprecated(__FUNCTION__);
539
+		return $this->_message_resource_manager->is_generating_messenger_and_active($messenger, $message_type);
540 540
 	}
541 541
 
542 542
 
@@ -546,10 +546,10 @@  discard block
 block discarded – undo
546 546
 	 * @param string $messenger
547 547
 	 * @return EE_messenger | null
548 548
 	 */
549
-	public function get_messenger_if_active( $messenger ) {
549
+	public function get_messenger_if_active($messenger) {
550 550
 		// EE_messages has been deprecated
551
-		$this->_class_is_deprecated( __FUNCTION__ );
552
-		return $this->_message_resource_manager->get_active_messenger( $messenger );
551
+		$this->_class_is_deprecated(__FUNCTION__);
552
+		return $this->_message_resource_manager->get_active_messenger($messenger);
553 553
 	}
554 554
 
555 555
 
@@ -570,9 +570,9 @@  discard block
 block discarded – undo
570 570
 	 *                  'message_type' => null
571 571
 	 *                  )
572 572
 	 */
573
-	public function validate_for_use( EE_Message $message ) {
573
+	public function validate_for_use(EE_Message $message) {
574 574
 		// EE_messages has been deprecated
575
-		$this->_class_is_deprecated( __FUNCTION__ );
575
+		$this->_class_is_deprecated(__FUNCTION__);
576 576
 		return array(
577 577
 			'messenger'    => $message->messenger_object(),
578 578
 			'message_type' => $message->message_type_object(),
@@ -600,41 +600,41 @@  discard block
 block discarded – undo
600 600
 		$send = true
601 601
 	) {
602 602
 		// EE_messages has been deprecated
603
-		$this->_class_is_deprecated( __FUNCTION__ );
603
+		$this->_class_is_deprecated(__FUNCTION__);
604 604
 		/** @type EE_Messages_Processor $processor */
605
-		$processor = EE_Registry::instance()->load_lib( 'Messages_Processor' );
605
+		$processor = EE_Registry::instance()->load_lib('Messages_Processor');
606 606
 		$error = false;
607 607
 		//try to intelligently determine what method we'll call based on the incoming data.
608 608
 		//if generating and sending are different then generate and send immediately.
609
-		if ( ! empty( $sending_messenger ) && $sending_messenger != $generating_messenger && $send ) {
609
+		if ( ! empty($sending_messenger) && $sending_messenger != $generating_messenger && $send) {
610 610
 			//in the legacy system, when generating and sending were different, that means all the
611 611
 			//vars are already in the request object.  So let's just use that.
612 612
 			try {
613 613
 				/** @type EE_Message_To_Generate_From_Request $mtg */
614
-				$mtg = EE_Registry::instance()->load_lib( 'Message_To_Generate_From_Request' );
615
-				$processor->generate_and_send_now( $mtg );
616
-			} catch ( EE_Error $e ) {
614
+				$mtg = EE_Registry::instance()->load_lib('Message_To_Generate_From_Request');
615
+				$processor->generate_and_send_now($mtg);
616
+			} catch (EE_Error $e) {
617 617
 				$error_msg = __(
618 618
 					'Please note that a system message failed to send due to a technical issue.',
619 619
 					'event_espresso'
620 620
 				);
621 621
 				// add specific message for developers if WP_DEBUG in on
622
-				$error_msg .= '||' . $e->getMessage();
623
-				EE_Error::add_error( $error_msg, __FILE__, __FUNCTION__, __LINE__ );
622
+				$error_msg .= '||'.$e->getMessage();
623
+				EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
624 624
 				$error = true;
625 625
 			}
626 626
 		} else {
627
-			$processor->generate_for_all_active_messengers( $type, $vars, $send );
627
+			$processor->generate_for_all_active_messengers($type, $vars, $send);
628 628
 			//let's find out if there were any errors and how many successfully were queued.
629 629
 			$count_errors = $processor->get_queue()->count_STS_in_queue(
630
-				array( EEM_Message::status_failed, EEM_Message::status_debug_only )
630
+				array(EEM_Message::status_failed, EEM_Message::status_debug_only)
631 631
 			);
632
-			$count_queued = $processor->get_queue()->count_STS_in_queue( EEM_Message::status_incomplete );
633
-			$count_retry = $processor->get_queue()->count_STS_in_queue( EEM_Message::status_retry );
632
+			$count_queued = $processor->get_queue()->count_STS_in_queue(EEM_Message::status_incomplete);
633
+			$count_retry = $processor->get_queue()->count_STS_in_queue(EEM_Message::status_retry);
634 634
 			$count_errors = $count_errors + $count_retry;
635
-			if ( $count_errors > 0 ) {
635
+			if ($count_errors > 0) {
636 636
 				$error = true;
637
-				if ( $count_errors > 1 && $count_retry > 1 && $count_queued > 1 ) {
637
+				if ($count_errors > 1 && $count_retry > 1 && $count_queued > 1) {
638 638
 					$message = sprintf(
639 639
 						__(
640 640
 							'There were %d errors and %d messages successfully queued for generation and sending',
@@ -643,7 +643,7 @@  discard block
 block discarded – undo
643 643
 						$count_errors,
644 644
 						$count_queued
645 645
 					);
646
-				} elseif ( $count_errors > 1 && $count_queued === 1 ) {
646
+				} elseif ($count_errors > 1 && $count_queued === 1) {
647 647
 					$message = sprintf(
648 648
 						__(
649 649
 							'There were %d errors and %d message successfully queued for generation.',
@@ -652,7 +652,7 @@  discard block
 block discarded – undo
652 652
 						$count_errors,
653 653
 						$count_queued
654 654
 					);
655
-				} elseif ( $count_errors === 1 && $count_queued > 1 ) {
655
+				} elseif ($count_errors === 1 && $count_queued > 1) {
656 656
 					$message = sprintf(
657 657
 						__(
658 658
 							'There was %d error and %d messages successfully queued for generation.',
@@ -670,9 +670,9 @@  discard block
 block discarded – undo
670 670
 						$count_errors
671 671
 					);
672 672
 				}
673
-				EE_Error::add_error( $message, __FILE__, __FUNCTION__, __LINE__ );
673
+				EE_Error::add_error($message, __FILE__, __FUNCTION__, __LINE__);
674 674
 			} else {
675
-				if ( $count_queued === 1 ) {
675
+				if ($count_queued === 1) {
676 676
 					$message = sprintf(
677 677
 						__(
678 678
 							'%d message successfully queued for generation.',
@@ -689,18 +689,18 @@  discard block
 block discarded – undo
689 689
 						$count_queued
690 690
 					);
691 691
 				}
692
-				EE_Error::add_success( $message );
692
+				EE_Error::add_success($message);
693 693
 			}
694 694
 		}
695 695
 		//if no error then return the generated message(s).
696
-		if ( ! $error && ! $send ) {
697
-			$generated_queue = $processor->generate_queue( false );
696
+		if ( ! $error && ! $send) {
697
+			$generated_queue = $processor->generate_queue(false);
698 698
 			//get message and return.
699 699
 			$generated_queue->get_message_repository()->rewind();
700 700
 			$messages = array();
701
-			while ( $generated_queue->get_message_repository()->valid() ) {
701
+			while ($generated_queue->get_message_repository()->valid()) {
702 702
 				$message = $generated_queue->get_message_repository()->current();
703
-				if ( $message instanceof EE_Message ) {
703
+				if ($message instanceof EE_Message) {
704 704
 					//set properties that might be expected by add-ons (backward compat)
705 705
 					$message->content = $message->content();
706 706
 					$message->template_pack = $message->get_template_pack();
@@ -725,10 +725,10 @@  discard block
 block discarded – undo
725 725
 	 * @param bool    $send      true we will do a test send using the messenger delivery, false we just do a regular preview
726 726
 	 * @return string          The body of the message.
727 727
 	 */
728
-	public function preview_message( $type, $context, $messenger, $send = false ) {
728
+	public function preview_message($type, $context, $messenger, $send = false) {
729 729
 		// EE_messages has been deprecated
730
-		$this->_class_is_deprecated( __FUNCTION__ );
731
-		return EED_Messages::preview_message( $type, $context, $messenger, $send );
730
+		$this->_class_is_deprecated(__FUNCTION__);
731
+		return EED_Messages::preview_message($type, $context, $messenger, $send);
732 732
 	}
733 733
 
734 734
 
@@ -742,14 +742,14 @@  discard block
 block discarded – undo
742 742
 	 *
743 743
 	 * @return bool          success or fail.
744 744
 	 */
745
-	public function send_message_with_messenger_only( $messenger, $message_type, $message ) {
745
+	public function send_message_with_messenger_only($messenger, $message_type, $message) {
746 746
 		// EE_messages has been deprecated
747
-		$this->_class_is_deprecated( __FUNCTION__ );
747
+		$this->_class_is_deprecated(__FUNCTION__);
748 748
 		//setup for sending to new method.
749 749
 		/** @type EE_Messages_Queue $queue */
750
-		$queue = EE_Registry::instance()->load_lib( 'Messages_Queue' );
750
+		$queue = EE_Registry::instance()->load_lib('Messages_Queue');
751 751
 		//make sure we have a proper message object
752
-		if ( ! $message instanceof EE_Message && is_object( $message ) && isset( $message->content ) ) {
752
+		if ( ! $message instanceof EE_Message && is_object($message) && isset($message->content)) {
753 753
 			$msg = EE_Message_Factory::create(
754 754
 				array(
755 755
 					'MSG_messenger'    => $messenger,
@@ -761,15 +761,15 @@  discard block
 block discarded – undo
761 761
 		} else {
762 762
 			$msg = $message;
763 763
 		}
764
-		if ( ! $msg instanceof EE_Message ) {
764
+		if ( ! $msg instanceof EE_Message) {
765 765
 			return false;
766 766
 		}
767 767
 		//make sure any content in a content property (if not empty) is set on the MSG_content.
768
-		if ( ! empty( $msg->content ) ) {
769
-			$msg->set( 'MSG_content', $msg->content );
768
+		if ( ! empty($msg->content)) {
769
+			$msg->set('MSG_content', $msg->content);
770 770
 		}
771
-		$queue->add( $msg );
772
-		return EED_Messages::send_message_with_messenger_only( $messenger, $message_type, $queue );
771
+		$queue->add($msg);
772
+		return EED_Messages::send_message_with_messenger_only($messenger, $message_type, $queue);
773 773
 	}
774 774
 
775 775
 
@@ -783,11 +783,11 @@  discard block
 block discarded – undo
783 783
 	 * @return array|object if creation is successful then we return an array of info, otherwise an error_object is returned.
784 784
 	 * @throws \EE_Error
785 785
 	 */
786
-	public function create_new_templates( $messenger, $message_type, $GRP_ID = 0, $is_global = false ) {
786
+	public function create_new_templates($messenger, $message_type, $GRP_ID = 0, $is_global = false) {
787 787
 		// EE_messages has been deprecated
788
-		$this->_class_is_deprecated( __FUNCTION__ );
789
-		EE_Registry::instance()->load_helper( 'MSG_Template' );
790
-		return EEH_MSG_Template::create_new_templates( $messenger, $message_type, $GRP_ID, $is_global );
788
+		$this->_class_is_deprecated(__FUNCTION__);
789
+		EE_Registry::instance()->load_helper('MSG_Template');
790
+		return EEH_MSG_Template::create_new_templates($messenger, $message_type, $GRP_ID, $is_global);
791 791
 	}
792 792
 
793 793
 
@@ -798,11 +798,11 @@  discard block
 block discarded – undo
798 798
 	 * @param  string $message_type_name name of EE_message_type
799 799
 	 * @return array
800 800
 	 */
801
-	public function get_fields( $messenger_name, $message_type_name ) {
801
+	public function get_fields($messenger_name, $message_type_name) {
802 802
 		// EE_messages has been deprecated
803
-		$this->_class_is_deprecated( __FUNCTION__ );
804
-		EE_Registry::instance()->load_helper( 'MSG_Template' );
805
-		return EEH_MSG_Template::get_fields( $messenger_name, $message_type_name );
803
+		$this->_class_is_deprecated(__FUNCTION__);
804
+		EE_Registry::instance()->load_helper('MSG_Template');
805
+		return EEH_MSG_Template::get_fields($messenger_name, $message_type_name);
806 806
 	}
807 807
 
808 808
 
@@ -816,13 +816,13 @@  discard block
 block discarded – undo
816 816
 	 * @return array                    multidimensional array of messenger and message_type objects
817 817
 	 *                                    (messengers index, and message_type index);
818 818
 	 */
819
-	public function get_installed( $type = 'all', $skip_cache = false ) {
819
+	public function get_installed($type = 'all', $skip_cache = false) {
820 820
 		// EE_messages has been deprecated
821
-		$this->_class_is_deprecated( __FUNCTION__ );
822
-		if ( $skip_cache ) {
821
+		$this->_class_is_deprecated(__FUNCTION__);
822
+		if ($skip_cache) {
823 823
 			$this->_message_resource_manager->reset_active_messengers_and_message_types();
824 824
 		}
825
-		switch ( $type ) {
825
+		switch ($type) {
826 826
 			case 'messengers' :
827 827
 				return array(
828 828
 					'messenger' => $this->_message_resource_manager->installed_messengers(),
@@ -851,7 +851,7 @@  discard block
 block discarded – undo
851 851
 	 */
852 852
 	public function get_active_messengers() {
853 853
 		// EE_messages has been deprecated
854
-		$this->_class_is_deprecated( __FUNCTION__ );
854
+		$this->_class_is_deprecated(__FUNCTION__);
855 855
 		return $this->_message_resource_manager->active_messengers();
856 856
 	}
857 857
 
@@ -863,7 +863,7 @@  discard block
 block discarded – undo
863 863
 	 */
864 864
 	public function get_active_message_types() {
865 865
 		// EE_messages has been deprecated
866
-		$this->_class_is_deprecated( __FUNCTION__ );
866
+		$this->_class_is_deprecated(__FUNCTION__);
867 867
 		return $this->_message_resource_manager->list_of_active_message_types();
868 868
 	}
869 869
 
@@ -875,7 +875,7 @@  discard block
 block discarded – undo
875 875
 	 */
876 876
 	public function get_active_message_type_objects() {
877 877
 		// EE_messages has been deprecated
878
-		$this->_class_is_deprecated( __FUNCTION__ );
878
+		$this->_class_is_deprecated(__FUNCTION__);
879 879
 		return $this->_message_resource_manager->get_active_message_type_objects();
880 880
 	}
881 881
 
@@ -887,10 +887,10 @@  discard block
 block discarded – undo
887 887
 	 * @param string $messenger The messenger being checked
888 888
 	 * @return EE_message_type[]    (or empty array if none present)
889 889
 	 */
890
-	public function get_active_message_types_per_messenger( $messenger ) {
890
+	public function get_active_message_types_per_messenger($messenger) {
891 891
 		// EE_messages has been deprecated
892
-		$this->_class_is_deprecated( __FUNCTION__ );
893
-		return $this->_message_resource_manager->get_active_message_types_for_messenger( $messenger );
892
+		$this->_class_is_deprecated(__FUNCTION__);
893
+		return $this->_message_resource_manager->get_active_message_types_for_messenger($messenger);
894 894
 	}
895 895
 
896 896
 
@@ -901,10 +901,10 @@  discard block
 block discarded – undo
901 901
 	 * @param string $message_type The string should correspond to a message type.
902 902
 	 * @return EE_message_type|null
903 903
 	 */
904
-	public function get_active_message_type( $messenger, $message_type ) {
904
+	public function get_active_message_type($messenger, $message_type) {
905 905
 		// EE_messages has been deprecated
906
-		$this->_class_is_deprecated( __FUNCTION__ );
907
-		return $this->_message_resource_manager->get_active_message_type_for_messenger( $messenger, $message_type );
906
+		$this->_class_is_deprecated(__FUNCTION__);
907
+		return $this->_message_resource_manager->get_active_message_type_for_messenger($messenger, $message_type);
908 908
 	}
909 909
 
910 910
 
@@ -915,7 +915,7 @@  discard block
 block discarded – undo
915 915
 	 */
916 916
 	public function get_installed_message_types() {
917 917
 		// EE_messages has been deprecated
918
-		$this->_class_is_deprecated( __FUNCTION__ );
918
+		$this->_class_is_deprecated(__FUNCTION__);
919 919
 		return $this->_message_resource_manager->installed_message_types();
920 920
 	}
921 921
 
@@ -927,7 +927,7 @@  discard block
 block discarded – undo
927 927
 	 */
928 928
 	public function get_installed_messengers() {
929 929
 		// EE_messages has been deprecated
930
-		$this->_class_is_deprecated( __FUNCTION__ );
930
+		$this->_class_is_deprecated(__FUNCTION__);
931 931
 		return $this->_message_resource_manager->installed_messengers();
932 932
 	}
933 933
 
@@ -938,10 +938,10 @@  discard block
 block discarded – undo
938 938
 	 * @param   bool $slugs_only Whether to return an array of just slugs and labels (true) or all contexts indexed by message type.
939 939
 	 * @return array
940 940
 	 */
941
-	public function get_all_contexts( $slugs_only = true ) {
941
+	public function get_all_contexts($slugs_only = true) {
942 942
 		// EE_messages has been deprecated
943
-		$this->_class_is_deprecated( __FUNCTION__ );
944
-		return $this->_message_resource_manager->get_all_contexts( $slugs_only );
943
+		$this->_class_is_deprecated(__FUNCTION__);
944
+		return $this->_message_resource_manager->get_all_contexts($slugs_only);
945 945
 	}
946 946
 
947 947
 
@@ -1000,7 +1000,7 @@  discard block
 block discarded – undo
1000 1000
 add_filter(
1001 1001
 	'FHEE__EventEspresso_modules_events_archive_EventsArchiveIframe__display__css',
1002 1002
 	function($event_list_iframe_css) {
1003
-		if ( ! has_filter( 'FHEE__EventsArchiveIframe__event_list_iframe__css' )) {
1003
+		if ( ! has_filter('FHEE__EventsArchiveIframe__event_list_iframe__css')) {
1004 1004
 			return $event_list_iframe_css;
1005 1005
 		}
1006 1006
 		deprecated_espresso_action_or_filter_doing_it_wrong(
@@ -1020,7 +1020,7 @@  discard block
 block discarded – undo
1020 1020
 add_filter(
1021 1021
 	'FHEE__EventEspresso_modules_events_archive_EventsArchiveIframe__display__js',
1022 1022
 	function($event_list_iframe_js) {
1023
-		if ( ! has_filter( 'FHEE__EED_Ticket_Selector__ticket_selector_iframe__js' )) {
1023
+		if ( ! has_filter('FHEE__EED_Ticket_Selector__ticket_selector_iframe__js')) {
1024 1024
 			return $event_list_iframe_js;
1025 1025
 		}
1026 1026
 		deprecated_espresso_action_or_filter_doing_it_wrong(
@@ -1040,7 +1040,7 @@  discard block
 block discarded – undo
1040 1040
 add_action(
1041 1041
 	'AHEE__EE_Capabilities__addCaps__complete',
1042 1042
 	function($capabilities_map) {
1043
-		if ( ! has_action( 'AHEE__EE_Capabilities__init_role_caps__complete' )) {
1043
+		if ( ! has_action('AHEE__EE_Capabilities__init_role_caps__complete')) {
1044 1044
 			return;
1045 1045
 		}
1046 1046
 		deprecated_espresso_action_or_filter_doing_it_wrong(
@@ -1060,7 +1060,7 @@  discard block
 block discarded – undo
1060 1060
 add_filter(
1061 1061
 	'FHEE_EventEspresso_core_services_commands_attendee_CreateAttendeeCommandHandler__findExistingAttendee__existing_attendee',
1062 1062
 	function($existing_attendee, $registration, $attendee_data) {
1063
-		if ( ! has_filter( 'FHEE_EE_Single_Page_Checkout__save_registration_items__find_existing_attendee' )) {
1063
+		if ( ! has_filter('FHEE_EE_Single_Page_Checkout__save_registration_items__find_existing_attendee')) {
1064 1064
 			return $existing_attendee;
1065 1065
 		}
1066 1066
 		deprecated_espresso_action_or_filter_doing_it_wrong(
@@ -1076,7 +1076,7 @@  discard block
 block discarded – undo
1076 1076
             $existing_attendee, $registration, $attendee_data
1077 1077
         );
1078 1078
 	},
1079
-	10,3
1079
+	10, 3
1080 1080
 );
1081 1081
 
1082 1082
 /**
@@ -1140,7 +1140,7 @@  discard block
 block discarded – undo
1140 1140
      */
1141 1141
     public function event_list_title($event_list_title = '')
1142 1142
     {
1143
-        if (! empty($this->title)) {
1143
+        if ( ! empty($this->title)) {
1144 1144
             return $this->title;
1145 1145
         }
1146 1146
         return $event_list_title;
Please login to merge, or discard this patch.
Indentation   +149 added lines, -149 removed lines patch added patch discarded remove patch
@@ -1052,7 +1052,7 @@  discard block
 block discarded – undo
1052 1052
 		);
1053 1053
 		do_action(
1054 1054
 			'AHEE__EE_Capabilities__init_role_caps__complete',
1055
-            $capabilities_map
1055
+			$capabilities_map
1056 1056
 		);
1057 1057
 	}
1058 1058
 );
@@ -1072,9 +1072,9 @@  discard block
 block discarded – undo
1072 1072
 			'filter'
1073 1073
 		);
1074 1074
 		return apply_filters(
1075
-            'FHEE_EE_Single_Page_Checkout__save_registration_items__find_existing_attendee',
1076
-            $existing_attendee, $registration, $attendee_data
1077
-        );
1075
+			'FHEE_EE_Single_Page_Checkout__save_registration_items__find_existing_attendee',
1076
+			$existing_attendee, $registration, $attendee_data
1077
+		);
1078 1078
 	},
1079 1079
 	10,3
1080 1080
 );
@@ -1087,89 +1087,89 @@  discard block
 block discarded – undo
1087 1087
 class EE_Event_List_Query extends WP_Query
1088 1088
 {
1089 1089
 
1090
-    private $title;
1091
-
1092
-    private $css_class;
1093
-
1094
-    private $category_slug;
1095
-
1096
-    /**
1097
-     * EE_Event_List_Query constructor.
1098
-     *
1099
-     * @param array $args
1100
-     */
1101
-    public function __construct($args = array())
1102
-    {
1103
-        \EE_Error::doing_it_wrong(
1104
-            __METHOD__,
1105
-            __(
1106
-                'Usage is deprecated. Please use \EventEspresso\core\domain\services\wp_queries\EventListQuery instead.',
1107
-                'event_espresso'
1108
-            ),
1109
-            '4.9.27',
1110
-            '5.0.0'
1111
-        );
1112
-        $this->title = isset($args['title']) ? $args['title'] : '';
1113
-        $this->css_class = isset($args['css_class']) ? $args['css_class'] : '';
1114
-        $this->category_slug = isset($args['category_slug']) ? $args['category_slug'] : '';
1115
-        $limit = isset($args['limit']) && absint($args['limit']) ? $args['limit'] : 10;
1116
-        // the current "page" we are viewing
1117
-        $paged = max(1, get_query_var('paged'));
1118
-        // Force these args
1119
-        $args = array_merge(
1120
-            $args, array(
1121
-            'post_type'              => 'espresso_events',
1122
-            'posts_per_page'         => $limit,
1123
-            'update_post_term_cache' => false,
1124
-            'update_post_meta_cache' => false,
1125
-            'paged'                  => $paged,
1126
-            'offset'                 => ($paged - 1) * $limit
1127
-        )
1128
-        );
1129
-        // run the query
1130
-        parent::__construct($args);
1131
-    }
1132
-
1133
-
1134
-
1135
-    /**
1136
-     * event_list_title
1137
-     *
1138
-     * @param string $event_list_title
1139
-     * @return string
1140
-     */
1141
-    public function event_list_title($event_list_title = '')
1142
-    {
1143
-        if (! empty($this->title)) {
1144
-            return $this->title;
1145
-        }
1146
-        return $event_list_title;
1147
-    }
1148
-
1149
-
1150
-
1151
-    /**
1152
-     * event_list_css
1153
-     *
1154
-     * @param string $event_list_css
1155
-     * @return string
1156
-     */
1157
-    public function event_list_css($event_list_css = '')
1158
-    {
1159
-        $event_list_css .= ! empty($event_list_css)
1160
-            ? ' '
1161
-            : '';
1162
-        $event_list_css .= ! empty($this->css_class)
1163
-            ? $this->css_class
1164
-            : '';
1165
-        $event_list_css .= ! empty($event_list_css)
1166
-            ? ' '
1167
-            : '';
1168
-        $event_list_css .= ! empty($this->category_slug)
1169
-            ? $this->category_slug
1170
-            : '';
1171
-        return $event_list_css;
1172
-    }
1090
+	private $title;
1091
+
1092
+	private $css_class;
1093
+
1094
+	private $category_slug;
1095
+
1096
+	/**
1097
+	 * EE_Event_List_Query constructor.
1098
+	 *
1099
+	 * @param array $args
1100
+	 */
1101
+	public function __construct($args = array())
1102
+	{
1103
+		\EE_Error::doing_it_wrong(
1104
+			__METHOD__,
1105
+			__(
1106
+				'Usage is deprecated. Please use \EventEspresso\core\domain\services\wp_queries\EventListQuery instead.',
1107
+				'event_espresso'
1108
+			),
1109
+			'4.9.27',
1110
+			'5.0.0'
1111
+		);
1112
+		$this->title = isset($args['title']) ? $args['title'] : '';
1113
+		$this->css_class = isset($args['css_class']) ? $args['css_class'] : '';
1114
+		$this->category_slug = isset($args['category_slug']) ? $args['category_slug'] : '';
1115
+		$limit = isset($args['limit']) && absint($args['limit']) ? $args['limit'] : 10;
1116
+		// the current "page" we are viewing
1117
+		$paged = max(1, get_query_var('paged'));
1118
+		// Force these args
1119
+		$args = array_merge(
1120
+			$args, array(
1121
+			'post_type'              => 'espresso_events',
1122
+			'posts_per_page'         => $limit,
1123
+			'update_post_term_cache' => false,
1124
+			'update_post_meta_cache' => false,
1125
+			'paged'                  => $paged,
1126
+			'offset'                 => ($paged - 1) * $limit
1127
+		)
1128
+		);
1129
+		// run the query
1130
+		parent::__construct($args);
1131
+	}
1132
+
1133
+
1134
+
1135
+	/**
1136
+	 * event_list_title
1137
+	 *
1138
+	 * @param string $event_list_title
1139
+	 * @return string
1140
+	 */
1141
+	public function event_list_title($event_list_title = '')
1142
+	{
1143
+		if (! empty($this->title)) {
1144
+			return $this->title;
1145
+		}
1146
+		return $event_list_title;
1147
+	}
1148
+
1149
+
1150
+
1151
+	/**
1152
+	 * event_list_css
1153
+	 *
1154
+	 * @param string $event_list_css
1155
+	 * @return string
1156
+	 */
1157
+	public function event_list_css($event_list_css = '')
1158
+	{
1159
+		$event_list_css .= ! empty($event_list_css)
1160
+			? ' '
1161
+			: '';
1162
+		$event_list_css .= ! empty($this->css_class)
1163
+			? $this->css_class
1164
+			: '';
1165
+		$event_list_css .= ! empty($event_list_css)
1166
+			? ' '
1167
+			: '';
1168
+		$event_list_css .= ! empty($this->category_slug)
1169
+			? $this->category_slug
1170
+			: '';
1171
+		return $event_list_css;
1172
+	}
1173 1173
 
1174 1174
 }
1175 1175
 
@@ -1186,66 +1186,66 @@  discard block
 block discarded – undo
1186 1186
 {
1187 1187
 
1188 1188
 
1189
-    /**
1190
-     *    class constructor
1191
-     *
1192
-     * @deprecated 4.9.59.p
1193
-     */
1194
-    public function __construct()
1195
-    {
1196
-        EE_Error::doing_it_wrong(
1197
-            __METHOD__,
1198
-            sprintf(
1199
-                esc_html__('%1$s has been replaced by %2$s.', 'event_espresso'),
1200
-                __CLASS__,
1201
-                'EventEspresso\core\services\licensing\LicenseServices'
1202
-            ),
1203
-            '4.9.59.p'
1204
-        );
1205
-    }
1206
-
1207
-
1208
-    /**
1209
-     * The purpose of this function is to display information about Event Espresso data collection
1210
-     * and a optin selection for extra data collecting by users.
1211
-     *
1212
-     * @param bool $extra
1213
-     * @return string html.
1214
-     * @deprecated 4.9.59.p
1215
-     */
1216
-    public static function espresso_data_collection_optin_text($extra = true)
1217
-    {
1218
-        EE_Error::doing_it_wrong(
1219
-            __METHOD__,
1220
-            sprintf(
1221
-                esc_html__('%1$s has been replaced by %2$s.', 'event_espresso'),
1222
-                __METHOD__,
1223
-                'EventEspresso\core\domain\services\Stats::optinText'
1224
-            ),
1225
-            '4.9.59.p'
1226
-        );
1227
-        Stats::optinText($extra);
1228
-    }
1229
-
1230
-    /**
1231
-     * This is a handy helper method for retrieving whether there is an update available for the given plugin.
1232
-     *
1233
-     * @param  string $basename Use the equivalent result from plugin_basename() for this param as WP uses that to
1234
-     *                          identify plugins. Defaults to core update
1235
-     * @return boolean           True if update available, false if not.
1236
-     * @deprecated 4.9.59.p
1237
-     */
1238
-    public static function is_update_available($basename = '')
1239
-    {
1240
-        EE_Error::doing_it_wrong(
1241
-            __METHOD__,
1242
-            sprintf(
1243
-                esc_html__('%1$s has been replaced by %2$s.', 'event_espresso'),
1244
-                __METHOD__,
1245
-                'EventEspresso\core\services\licensing\LicenseService::isUpdateAvailable'
1246
-            ),
1247
-            '4.9.59.p'
1248
-        );
1249
-        return LicenseService::isUpdateAvailable($basename);
1250
-    }
1189
+	/**
1190
+	 *    class constructor
1191
+	 *
1192
+	 * @deprecated 4.9.59.p
1193
+	 */
1194
+	public function __construct()
1195
+	{
1196
+		EE_Error::doing_it_wrong(
1197
+			__METHOD__,
1198
+			sprintf(
1199
+				esc_html__('%1$s has been replaced by %2$s.', 'event_espresso'),
1200
+				__CLASS__,
1201
+				'EventEspresso\core\services\licensing\LicenseServices'
1202
+			),
1203
+			'4.9.59.p'
1204
+		);
1205
+	}
1206
+
1207
+
1208
+	/**
1209
+	 * The purpose of this function is to display information about Event Espresso data collection
1210
+	 * and a optin selection for extra data collecting by users.
1211
+	 *
1212
+	 * @param bool $extra
1213
+	 * @return string html.
1214
+	 * @deprecated 4.9.59.p
1215
+	 */
1216
+	public static function espresso_data_collection_optin_text($extra = true)
1217
+	{
1218
+		EE_Error::doing_it_wrong(
1219
+			__METHOD__,
1220
+			sprintf(
1221
+				esc_html__('%1$s has been replaced by %2$s.', 'event_espresso'),
1222
+				__METHOD__,
1223
+				'EventEspresso\core\domain\services\Stats::optinText'
1224
+			),
1225
+			'4.9.59.p'
1226
+		);
1227
+		Stats::optinText($extra);
1228
+	}
1229
+
1230
+	/**
1231
+	 * This is a handy helper method for retrieving whether there is an update available for the given plugin.
1232
+	 *
1233
+	 * @param  string $basename Use the equivalent result from plugin_basename() for this param as WP uses that to
1234
+	 *                          identify plugins. Defaults to core update
1235
+	 * @return boolean           True if update available, false if not.
1236
+	 * @deprecated 4.9.59.p
1237
+	 */
1238
+	public static function is_update_available($basename = '')
1239
+	{
1240
+		EE_Error::doing_it_wrong(
1241
+			__METHOD__,
1242
+			sprintf(
1243
+				esc_html__('%1$s has been replaced by %2$s.', 'event_espresso'),
1244
+				__METHOD__,
1245
+				'EventEspresso\core\services\licensing\LicenseService::isUpdateAvailable'
1246
+			),
1247
+			'4.9.59.p'
1248
+		);
1249
+		return LicenseService::isUpdateAvailable($basename);
1250
+	}
1251 1251
 }
1252 1252
\ No newline at end of file
Please login to merge, or discard this patch.
general_settings/templates/your_organization_settings.template.php 2 patches
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -6,7 +6,7 @@
 block discarded – undo
6 6
 	<?php
7 7
 		//we'll only show site-license keys if this is main_site() (which works for both multi-site and single-site wp installations)
8 8
 
9
-    if ( is_main_site() ) { ?>
9
+	if ( is_main_site() ) { ?>
10 10
 		<h2 class="ee-admin-settings-hdr" style="width:300px;">
11 11
 			<?php _e('Your Event Espresso License Key', 'event_espresso'); ?>
12 12
 		</h2>
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -6,7 +6,7 @@  discard block
 block discarded – undo
6 6
 	<?php
7 7
 		//we'll only show site-license keys if this is main_site() (which works for both multi-site and single-site wp installations)
8 8
 
9
-    if ( is_main_site() ) { ?>
9
+    if (is_main_site()) { ?>
10 10
 		<h2 class="ee-admin-settings-hdr" style="width:300px;">
11 11
 			<?php _e('Your Event Espresso License Key', 'event_espresso'); ?>
12 12
 		</h2>
@@ -16,13 +16,13 @@  discard block
 block discarded – undo
16 16
 				<tr <?php echo isset($_REQUEST['license_key']) && $_REQUEST['license_key'] == true ? 'class="yellow_alert"' : '' ?>>
17 17
 					<th>
18 18
 						<label for="site_license_key">
19
-							<?php _e('Support License Key', 'event_espresso'); ?> <?php echo EEH_Template::get_help_tab_link('site_license_key_info');?>
19
+							<?php _e('Support License Key', 'event_espresso'); ?> <?php echo EEH_Template::get_help_tab_link('site_license_key_info'); ?>
20 20
 						</label>
21 21
 					</th>
22 22
 					<td>
23 23
 						<input name="site_license_key" id="site_license_key" size="10" class="regular-text" type="text" value="<?php echo esc_attr($site_license_key); ?>" /><?php echo $site_license_key_verified; ?><br/>
24 24
 						<p class="description">
25
-							<?php printf( __('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.', 'event_espresso'), '<strong>', '</strong>' ); ?>
25
+							<?php printf(__('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.', 'event_espresso'), '<strong>', '</strong>'); ?>
26 26
 						</p>
27 27
 					</td>
28 28
 				</tr>
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 
36 36
 
37 37
 	<h2 id="contact_info_h4" class="ee-admin-settings-hdr">
38
-		<?php _e('Contact Information', 'event_espresso'); ?> <?php echo EEH_Template::get_help_tab_link('contact_info_info');?>
38
+		<?php _e('Contact Information', 'event_espresso'); ?> <?php echo EEH_Template::get_help_tab_link('contact_info_info'); ?>
39 39
 	</h2>
40 40
 
41 41
 	<table class="form-table">
@@ -83,8 +83,8 @@  discard block
 block discarded – undo
83 83
 					<input id="organization_city" class="regular-text" type="text" name="organization_city" value="<?php echo esc_textarea($organization_city); ?>" />
84 84
 				</td>
85 85
 			</tr>
86
-			<?php echo EEH_Form_Fields::generate_form_input( $states ); ?>
87
-			<?php echo EEH_Form_Fields::generate_form_input( $countries ); ?>
86
+			<?php echo EEH_Form_Fields::generate_form_input($states); ?>
87
+			<?php echo EEH_Form_Fields::generate_form_input($countries); ?>
88 88
 			<tr>
89 89
 				<th>
90 90
 					<label for="organization_zip">
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 				<td>
105 105
 					<input class="regular-text" type="text" name="organization_email" value="<?php echo esc_textarea($organization_email); ?>" />
106 106
 					<p class="description">
107
-						<?php echo sprintf( esc_html__('This is where notifications go to when you use the %1$s and %2$s shortcodes in the message templates.', 'event_espresso'), '<code>[CO_FORMATTED_EMAIL]</code>', '<code>[CO_EMAIL]</code>' ); ?>
107
+						<?php echo sprintf(esc_html__('This is where notifications go to when you use the %1$s and %2$s shortcodes in the message templates.', 'event_espresso'), '<code>[CO_FORMATTED_EMAIL]</code>', '<code>[CO_EMAIL]</code>'); ?>
108 108
 					</p>
109 109
 				</td>
110 110
 			</tr>
@@ -138,7 +138,7 @@  discard block
 block discarded – undo
138 138
 	</table>
139 139
 
140 140
 	<h2 class="ee-admin-settings-hdr">
141
-		<?php _e('Company Logo', 'event_espresso'); ?> <?php echo EEH_Template::get_help_tab_link('organization_logo_info');?>
141
+		<?php _e('Company Logo', 'event_espresso'); ?> <?php echo EEH_Template::get_help_tab_link('organization_logo_info'); ?>
142 142
 	</h2>
143 143
 
144 144
 	<table class="form-table">
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
 				</th>
167 167
 				<td>
168 168
 					<?php
169
-					if ( $organization_logo_url ) {
169
+					if ($organization_logo_url) {
170 170
 						?>
171 171
 						<p id="default-logo-thumb">
172 172
 							<img id="current-image-thumb" src="<?php echo esc_url($organization_logo_url) ?>" alt="" /><br />
@@ -184,7 +184,7 @@  discard block
 block discarded – undo
184 184
 	<br/><br/>
185 185
 
186 186
 	<h2 class="ee-admin-settings-hdr">
187
-		<?php _e('Social Links', 'event_espresso'); ?> <?php echo EEH_Template::get_help_tab_link('social_links_info');?>
187
+		<?php _e('Social Links', 'event_espresso'); ?> <?php echo EEH_Template::get_help_tab_link('social_links_info'); ?>
188 188
 	</h2>
189 189
 	<p class="description"><?php _e('Enter any links to social accounts for your organization here', 'event_espresso'); ?></p>
190 190
 
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 	<br/><br/>
262 262
 
263 263
 
264
-	<?php if ( is_main_site() ) : ?>
264
+	<?php if (is_main_site()) : ?>
265 265
 		<p>
266 266
 			<?php Stats::optinText(false); ?>
267 267
 		</p>
@@ -277,11 +277,11 @@  discard block
 block discarded – undo
277 277
 					</th>
278 278
 					<td>
279 279
 						<?php
280
-							$values=array(
281
-								array('id'=>'yes','text'=> __('Yes! I want to help improve Event Espresso!','event_espresso')),
282
-								array('id'=>'no','text'=> __('Not at this time. Maybe later.','event_espresso'))
280
+							$values = array(
281
+								array('id'=>'yes', 'text'=> __('Yes! I want to help improve Event Espresso!', 'event_espresso')),
282
+								array('id'=>'no', 'text'=> __('Not at this time. Maybe later.', 'event_espresso'))
283 283
 							);
284
-							echo EEH_Form_Fields::select_input('ueip_optin', $values, !empty($ee_ueip_optin) ? $ee_ueip_optin : 'yes');
284
+							echo EEH_Form_Fields::select_input('ueip_optin', $values, ! empty($ee_ueip_optin) ? $ee_ueip_optin : 'yes');
285 285
 						?>
286 286
 					</td>
287 287
 				</tr>
Please login to merge, or discard this patch.
admin_pages/general_settings/General_Settings_Admin_Page.core.php 1 patch
Indentation   +1371 added lines, -1371 removed lines patch added patch discarded remove patch
@@ -17,1386 +17,1386 @@
 block discarded – undo
17 17
 {
18 18
 
19 19
 
20
-    /**
21
-     * _question_group
22
-     * holds the specific question group object for the question group details screen
23
-     *
24
-     * @var object
25
-     */
26
-    protected $_question_group;
27
-
28
-
29
-    /**
30
-     * Initialize basic properties.
31
-     */
32
-    protected function _init_page_props()
33
-    {
34
-        $this->page_slug        = GEN_SET_PG_SLUG;
35
-        $this->page_label       = GEN_SET_LABEL;
36
-        $this->_admin_base_url  = GEN_SET_ADMIN_URL;
37
-        $this->_admin_base_path = GEN_SET_ADMIN;
38
-    }
39
-
40
-
41
-    /**
42
-     * Set ajax hooks
43
-     */
44
-    protected function _ajax_hooks()
45
-    {
46
-        add_action('wp_ajax_espresso_display_country_settings', array($this, 'display_country_settings'));
47
-        add_action('wp_ajax_espresso_display_country_states', array($this, 'display_country_states'));
48
-        add_action('wp_ajax_espresso_delete_state', array($this, 'delete_state'), 10, 3);
49
-        add_action('wp_ajax_espresso_add_new_state', array($this, 'add_new_state'));
50
-    }
51
-
52
-
53
-    /**
54
-     * More page properties initialization.
55
-     */
56
-    protected function _define_page_props()
57
-    {
58
-        $this->_admin_page_title = GEN_SET_LABEL;
59
-        $this->_labels           = array(
60
-            'publishbox' => __('Update Settings', 'event_espresso'),
61
-        );
62
-    }
63
-
64
-
65
-    /**
66
-     * Set page routes property.
67
-     */
68
-    protected function _set_page_routes()
69
-    {
70
-        $this->_page_routes = array(
71
-
72
-            'critical_pages'                => array(
73
-                'func'       => '_espresso_page_settings',
74
-                'capability' => 'manage_options',
75
-            ),
76
-            'update_espresso_page_settings' => array(
77
-                'func'       => '_update_espresso_page_settings',
78
-                'capability' => 'manage_options',
79
-                'noheader'   => true,
80
-            ),
81
-            'default'                       => array(
82
-                'func'       => '_your_organization_settings',
83
-                'capability' => 'manage_options',
84
-            ),
85
-
86
-            'update_your_organization_settings' => array(
87
-                'func'       => '_update_your_organization_settings',
88
-                'capability' => 'manage_options',
89
-                'noheader'   => true,
90
-            ),
91
-
92
-            'admin_option_settings' => array(
93
-                'func'       => '_admin_option_settings',
94
-                'capability' => 'manage_options',
95
-            ),
96
-
97
-            'update_admin_option_settings' => array(
98
-                'func'       => '_update_admin_option_settings',
99
-                'capability' => 'manage_options',
100
-                'noheader'   => true,
101
-            ),
102
-
103
-            'country_settings' => array(
104
-                'func'       => '_country_settings',
105
-                'capability' => 'manage_options',
106
-            ),
107
-
108
-            'update_country_settings' => array(
109
-                'func'       => '_update_country_settings',
110
-                'capability' => 'manage_options',
111
-                'noheader'   => true,
112
-            ),
113
-
114
-            'display_country_settings' => array(
115
-                'func'       => 'display_country_settings',
116
-                'capability' => 'manage_options',
117
-                'noheader'   => true,
118
-            ),
119
-
120
-            'add_new_state' => array(
121
-                'func'       => 'add_new_state',
122
-                'capability' => 'manage_options',
123
-                'noheader'   => true,
124
-            ),
125
-
126
-            'delete_state' => array(
127
-                'func'       => 'delete_state',
128
-                'capability' => 'manage_options',
129
-                'noheader'   => true,
130
-            ),
131
-        );
132
-    }
133
-
134
-
135
-    /**
136
-     * Set page configuration property
137
-     */
138
-    protected function _set_page_config()
139
-    {
140
-        $this->_page_config = array(
141
-            'critical_pages'        => array(
142
-                'nav'           => array(
143
-                    'label' => __('Critical Pages', 'event_espresso'),
144
-                    'order' => 50,
145
-                ),
146
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
147
-                'help_tabs'     => array(
148
-                    'general_settings_critical_pages_help_tab' => array(
149
-                        'title'    => __('Critical Pages', 'event_espresso'),
150
-                        'filename' => 'general_settings_critical_pages',
151
-                    ),
152
-                ),
153
-                'help_tour'     => array('Critical_Pages_Help_Tour'),
154
-                'require_nonce' => false,
155
-            ),
156
-            'default'               => array(
157
-                'nav'           => array(
158
-                    'label' => __('Your Organization', 'event_espresso'),
159
-                    'order' => 20,
160
-                ),
161
-                'help_tabs'     => array(
162
-                    'general_settings_your_organization_help_tab' => array(
163
-                        'title'    => __('Your Organization', 'event_espresso'),
164
-                        'filename' => 'general_settings_your_organization',
165
-                    ),
166
-                ),
167
-                'help_tour'     => array('Your_Organization_Help_Tour'),
168
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
169
-                'require_nonce' => false,
170
-            ),
171
-            'admin_option_settings' => array(
172
-                'nav'           => array(
173
-                    'label' => __('Admin Options', 'event_espresso'),
174
-                    'order' => 60,
175
-                ),
176
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
177
-                'help_tabs'     => array(
178
-                    'general_settings_admin_options_help_tab' => array(
179
-                        'title'    => __('Admin Options', 'event_espresso'),
180
-                        'filename' => 'general_settings_admin_options',
181
-                    ),
182
-                ),
183
-                'help_tour'     => array('Admin_Options_Help_Tour'),
184
-                'require_nonce' => false,
185
-            ),
186
-            'country_settings'      => array(
187
-                'nav'           => array(
188
-                    'label' => __('Countries', 'event_espresso'),
189
-                    'order' => 70,
190
-                ),
191
-                'help_tabs'     => array(
192
-                    'general_settings_countries_help_tab' => array(
193
-                        'title'    => __('Countries', 'event_espresso'),
194
-                        'filename' => 'general_settings_countries',
195
-                    ),
196
-                ),
197
-                'help_tour'     => array('Countries_Help_Tour'),
198
-                'require_nonce' => false,
199
-            ),
200
-        );
201
-    }
202
-
203
-
204
-
205
-    protected function _add_screen_options()
206
-    {
207
-    }
208
-
209
-    protected function _add_feature_pointers()
210
-    {
211
-    }
212
-
213
-
214
-    /**
215
-     * Enqueue global scripts and styles for all routes in the General Settings Admin Pages.
216
-     */
217
-    public function load_scripts_styles()
218
-    {
219
-        //styles
220
-        wp_enqueue_style('espresso-ui-theme');
221
-        //scripts
222
-        wp_enqueue_script('ee_admin_js');
223
-    }
224
-
225
-
226
-    /**
227
-     * Execute logic running on `admin_init`
228
-     */
229
-    public function admin_init()
230
-    {
231
-        EE_Registry::$i18n_js_strings['invalid_server_response'] = __(
232
-            '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.',
233
-            'event_espresso'
234
-        );
235
-        EE_Registry::$i18n_js_strings['error_occurred']          = __(
236
-            'An error occurred! Please refresh the page and try again.',
237
-            'event_espresso'
238
-        );
239
-        EE_Registry::$i18n_js_strings['confirm_delete_state']    = __(
240
-            'Are you sure you want to delete this State / Province?',
241
-            'event_espresso'
242
-        );
243
-        $protocol                                                = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
244
-        EE_Registry::$i18n_js_strings['ajax_url']                = admin_url(
245
-            'admin-ajax.php?page=espresso_general_settings',
246
-            $protocol
247
-        );
248
-    }
249
-
250
-    public function admin_notices()
251
-    {
252
-    }
253
-
254
-    public function admin_footer_scripts()
255
-    {
256
-    }
257
-
258
-
259
-    /**
260
-     * Enqueue scripts and styles for the default route.
261
-     */
262
-    public function load_scripts_styles_default()
263
-    {
264
-        //styles
265
-        wp_enqueue_style('thickbox');
266
-        //scripts
267
-        wp_enqueue_script('media-upload');
268
-        wp_enqueue_script('thickbox');
269
-        wp_register_script(
270
-            'organization_settings',
271
-            GEN_SET_ASSETS_URL . 'your_organization_settings.js',
272
-            array('jquery', 'media-upload', 'thickbox'),
273
-            EVENT_ESPRESSO_VERSION,
274
-            true
275
-        );
276
-        wp_register_style('organization-css', GEN_SET_ASSETS_URL . 'organization.css', array(), EVENT_ESPRESSO_VERSION);
277
-        wp_enqueue_script('organization_settings');
278
-        wp_enqueue_style('organization-css');
279
-        $confirm_image_delete = array(
280
-            'text' => __(
281
-                'Do you really want to delete this image? Please remember to save your settings to complete the removal.',
282
-                'event_espresso'
283
-            ),
284
-        );
285
-        wp_localize_script('organization_settings', 'confirm_image_delete', $confirm_image_delete);
286
-    }
287
-
288
-
289
-    /**
290
-     * Enqueue scripts and styles for the country settings route.
291
-     */
292
-    public function load_scripts_styles_country_settings()
293
-    {
294
-        //scripts
295
-        wp_register_script(
296
-            'gen_settings_countries',
297
-            GEN_SET_ASSETS_URL . 'gen_settings_countries.js',
298
-            array('ee_admin_js'),
299
-            EVENT_ESPRESSO_VERSION,
300
-            true
301
-        );
302
-        wp_register_style('organization-css', GEN_SET_ASSETS_URL . 'organization.css', array(), EVENT_ESPRESSO_VERSION);
303
-        wp_enqueue_script('gen_settings_countries');
304
-        wp_enqueue_style('organization-css');
305
-    }
306
-
307
-
308
-    /*************        Espresso Pages        *************/
309
-    /**
310
-     * _espresso_page_settings
311
-     *
312
-     * @throws \EE_Error
313
-     */
314
-    protected function _espresso_page_settings()
315
-    {
316
-        // Check to make sure all of the main pages are setup properly,
317
-        // if not create the default pages and display an admin notice
318
-        EEH_Activation::verify_default_pages_exist();
319
-        $this->_transient_garbage_collection();
320
-        $this->_template_args['values']             = $this->_yes_no_values;
321
-        $this->_template_args['reg_page_id']        = isset(EE_Registry::instance()->CFG->core->reg_page_id)
322
-            ? EE_Registry::instance()->CFG->core->reg_page_id
323
-            : null;
324
-        $this->_template_args['reg_page_obj']       = isset(EE_Registry::instance()->CFG->core->reg_page_id)
325
-            ? get_page(EE_Registry::instance()->CFG->core->reg_page_id)
326
-            : false;
327
-        $this->_template_args['txn_page_id']        = isset(EE_Registry::instance()->CFG->core->txn_page_id)
328
-            ? EE_Registry::instance()->CFG->core->txn_page_id
329
-            : null;
330
-        $this->_template_args['txn_page_obj']       = isset(EE_Registry::instance()->CFG->core->txn_page_id)
331
-            ? get_page(EE_Registry::instance()->CFG->core->txn_page_id)
332
-            : false;
333
-        $this->_template_args['thank_you_page_id']  = isset(EE_Registry::instance()->CFG->core->thank_you_page_id)
334
-            ? EE_Registry::instance()->CFG->core->thank_you_page_id
335
-            : null;
336
-        $this->_template_args['thank_you_page_obj'] = isset(EE_Registry::instance()->CFG->core->thank_you_page_id)
337
-            ? get_page(EE_Registry::instance()->CFG->core->thank_you_page_id)
338
-            : false;
339
-        $this->_template_args['cancel_page_id']     = isset(EE_Registry::instance()->CFG->core->cancel_page_id)
340
-            ? EE_Registry::instance()->CFG->core->cancel_page_id
341
-            : null;
342
-        $this->_template_args['cancel_page_obj']    = isset(EE_Registry::instance()->CFG->core->cancel_page_id)
343
-            ? get_page(EE_Registry::instance()->CFG->core->cancel_page_id)
344
-            : false;
345
-        $this->_set_add_edit_form_tags('update_espresso_page_settings');
346
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
347
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
348
-            GEN_SET_TEMPLATE_PATH . 'espresso_page_settings.template.php',
349
-            $this->_template_args,
350
-            true
351
-        );
352
-        $this->display_admin_page_with_sidebar();
353
-    }
354
-
355
-
356
-    /**
357
-     * Handler for updating espresso page settings.
358
-     */
359
-    protected function _update_espresso_page_settings()
360
-    {
361
-        // capture incoming request data && set page IDs
362
-        EE_Registry::instance()->CFG->core->reg_page_id       = isset($this->_req_data['reg_page_id'])
363
-            ? absint($this->_req_data['reg_page_id'])
364
-            : EE_Registry::instance()->CFG->core->reg_page_id;
365
-        EE_Registry::instance()->CFG->core->txn_page_id       = isset($this->_req_data['txn_page_id'])
366
-            ? absint($this->_req_data['txn_page_id'])
367
-            : EE_Registry::instance()->CFG->core->txn_page_id;
368
-        EE_Registry::instance()->CFG->core->thank_you_page_id = isset($this->_req_data['thank_you_page_id'])
369
-            ? absint($this->_req_data['thank_you_page_id'])
370
-            : EE_Registry::instance()->CFG->core->thank_you_page_id;
371
-        EE_Registry::instance()->CFG->core->cancel_page_id    = isset($this->_req_data['cancel_page_id'])
372
-            ? absint($this->_req_data['cancel_page_id'])
373
-            : EE_Registry::instance()->CFG->core->cancel_page_id;
374
-
375
-        EE_Registry::instance()->CFG->core = apply_filters(
376
-            'FHEE__General_Settings_Admin_Page___update_espresso_page_settings__CFG_core',
377
-            EE_Registry::instance()->CFG->core,
378
-            $this->_req_data
379
-        );
380
-        $what                              = __('Critical Pages & Shortcodes', 'event_espresso');
381
-        $this->_redirect_after_action(
382
-            $this->_update_espresso_configuration(
383
-                $what,
384
-                EE_Registry::instance()->CFG->core,
385
-                __FILE__,
386
-                __FUNCTION__,
387
-                __LINE__
388
-            ),
389
-            $what,
390
-            '',
391
-            array(
392
-                'action' => 'critical_pages',
393
-            ),
394
-            true
395
-        );
396
-    }
397
-
398
-
399
-    /*************        Your Organization        *************/
400
-
401
-
402
-    /**
403
-     * Output for the Your Organization settings route.
404
-     * @throws DomainException
405
-     * @throws EE_Error
406
-     */
407
-    protected function _your_organization_settings()
408
-    {
409
-
410
-        $this->_template_args['site_license_key']       = isset(
411
-            EE_Registry::instance()->NET_CFG->core->site_license_key
412
-        )
413
-            ? EE_Registry::instance()->NET_CFG->core->get_pretty('site_license_key')
414
-            : '';
415
-        $this->_template_args['organization_name']      = isset(EE_Registry::instance()->CFG->organization->name)
416
-            ? EE_Registry::instance()->CFG->organization->get_pretty('name')
417
-            : '';
418
-        $this->_template_args['organization_address_1'] = isset(EE_Registry::instance()->CFG->organization->address_1)
419
-            ? EE_Registry::instance()->CFG->organization->get_pretty('address_1')
420
-            : '';
421
-        $this->_template_args['organization_address_2'] = isset(EE_Registry::instance()->CFG->organization->address_2)
422
-            ? EE_Registry::instance()->CFG->organization->get_pretty('address_2')
423
-            : '';
424
-        $this->_template_args['organization_city']      = isset(EE_Registry::instance()->CFG->organization->city)
425
-            ? EE_Registry::instance()->CFG->organization->get_pretty('city')
426
-            : '';
427
-        $this->_template_args['organization_zip']       = isset(EE_Registry::instance()->CFG->organization->zip)
428
-            ? EE_Registry::instance()->CFG->organization->get_pretty('zip')
429
-            : '';
430
-        $this->_template_args['organization_email']     = isset(EE_Registry::instance()->CFG->organization->email)
431
-            ? EE_Registry::instance()->CFG->organization->get_pretty('email')
432
-            : '';
433
-        $this->_template_args['organization_phone']     = isset(EE_Registry::instance()->CFG->organization->phone)
434
-            ? EE_Registry::instance()->CFG->organization->get_pretty('phone')
435
-            : '';
436
-        $this->_template_args['organization_vat']       = isset(EE_Registry::instance()->CFG->organization->vat)
437
-            ? EE_Registry::instance()->CFG->organization->get_pretty('vat')
438
-            : '';
439
-        $this->_template_args['currency_sign']          = isset(EE_Registry::instance()->CFG->currency->sign)
440
-            ? EE_Registry::instance()->CFG->currency->get_pretty('sign')
441
-            : '$';
442
-        $this->_template_args['organization_logo_url']  = isset(EE_Registry::instance()->CFG->organization->logo_url)
443
-            ? EE_Registry::instance()->CFG->organization->get_pretty('logo_url')
444
-            : false;
445
-        $this->_template_args['organization_facebook']  = isset(EE_Registry::instance()->CFG->organization->facebook)
446
-            ? EE_Registry::instance()->CFG->organization->get_pretty('facebook')
447
-            : '';
448
-        $this->_template_args['organization_twitter']   = isset(EE_Registry::instance()->CFG->organization->twitter)
449
-            ? EE_Registry::instance()->CFG->organization->get_pretty('twitter')
450
-            : '';
451
-        $this->_template_args['organization_linkedin']  = isset(EE_Registry::instance()->CFG->organization->linkedin)
452
-            ? EE_Registry::instance()->CFG->organization->get_pretty('linkedin')
453
-            : '';
454
-        $this->_template_args['organization_pinterest'] = isset(EE_Registry::instance()->CFG->organization->pinterest)
455
-            ? EE_Registry::instance()->CFG->organization->get_pretty('pinterest')
456
-            : '';
457
-        $this->_template_args['organization_google']    = isset(EE_Registry::instance()->CFG->organization->google)
458
-            ? EE_Registry::instance()->CFG->organization->get_pretty('google')
459
-            : '';
460
-        $this->_template_args['organization_instagram'] = isset(EE_Registry::instance()->CFG->organization->instagram)
461
-            ? EE_Registry::instance()->CFG->organization->get_pretty('instagram')
462
-            : '';
463
-        //UXIP settings
464
-        $this->_template_args['ee_ueip_optin'] = isset(EE_Registry::instance()->CFG->core->ee_ueip_optin)
465
-            ? EE_Registry::instance()->CFG->core->get_pretty('ee_ueip_optin')
466
-            : 'yes';
467
-
468
-        $STA_ID                         = isset(EE_Registry::instance()->CFG->organization->STA_ID)
469
-            ? EE_Registry::instance()->CFG->organization->STA_ID
470
-            : 4;
471
-        $this->_template_args['states'] = new EE_Question_Form_Input(
472
-            EE_Question::new_instance(array(
473
-                'QST_ID'           => 0,
474
-                'QST_display_text' => __('State/Province', 'event_espresso'),
475
-                'QST_system'       => 'admin-state',
476
-            )),
477
-            EE_Answer::new_instance(array(
478
-                'ANS_ID'    => 0,
479
-                'ANS_value' => $STA_ID,
480
-            )),
481
-            array(
482
-                'input_id'       => 'organization_state',
483
-                'input_name'     => 'organization_state',
484
-                'input_prefix'   => '',
485
-                'append_qstn_id' => false,
486
-            )
487
-        );
488
-
489
-        $CNT_ISO                           = isset(EE_Registry::instance()->CFG->organization->CNT_ISO)
490
-            ? EE_Registry::instance()->CFG->organization->CNT_ISO
491
-            : 'US';
492
-        $this->_template_args['countries'] = new EE_Question_Form_Input(
493
-            EE_Question::new_instance(array(
494
-                'QST_ID'           => 0,
495
-                'QST_display_text' => __('Country', 'event_espresso'),
496
-                'QST_system'       => 'admin-country',
497
-            )),
498
-            EE_Answer::new_instance(array(
499
-                'ANS_ID'    => 0,
500
-                'ANS_value' => $CNT_ISO,
501
-            )),
502
-            array(
503
-                'input_id'       => 'organization_country',
504
-                'input_name'     => 'organization_country',
505
-                'input_prefix'   => '',
506
-                'append_qstn_id' => false,
507
-            )
508
-        );
509
-
510
-        add_filter('FHEE__EEH_Form_Fields__label_html', array($this, 'country_form_field_label_wrap'), 10, 2);
511
-        add_filter('FHEE__EEH_Form_Fields__input_html', array($this, 'country_form_field_input__wrap'), 10, 2);
512
-
513
-        //PUE verification stuff
514
-        $ver_option_key                                    = 'puvererr_' . basename(EE_PLUGIN_BASENAME);
515
-        $verify_fail                                       = get_option($ver_option_key);
516
-        $this->_template_args['site_license_key_verified'] = $verify_fail
517
-                                                             || ! empty($verify_fail)
518
-                                                             || (empty($this->_template_args['site_license_key'])
519
-                                                                 && empty($verify_fail)
520
-                                                             )
521
-            ? '<span class="dashicons dashicons-admin-network ee-icon-color-ee-red ee-icon-size-20"></span>'
522
-            : '<span class="dashicons dashicons-admin-network ee-icon-color-ee-green ee-icon-size-20"></span>';
523
-
524
-        $this->_set_add_edit_form_tags('update_your_organization_settings');
525
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
526
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
527
-            GEN_SET_TEMPLATE_PATH . 'your_organization_settings.template.php',
528
-            $this->_template_args,
529
-            true
530
-        );
531
-
532
-        $this->display_admin_page_with_sidebar();
533
-    }
534
-
535
-
536
-    /**
537
-     * Handler for updating organziation settings.
538
-     */
539
-    protected function _update_your_organization_settings()
540
-    {
541
-        if (is_main_site()) {
542
-            EE_Registry::instance()->NET_CFG->core->site_license_key = isset($this->_req_data['site_license_key'])
543
-                ? sanitize_text_field($this->_req_data['site_license_key'])
544
-                : EE_Registry::instance()->NET_CFG->core->site_license_key;
545
-        }
546
-        EE_Registry::instance()->CFG->organization->name      = isset($this->_req_data['organization_name'])
547
-            ? sanitize_text_field($this->_req_data['organization_name'])
548
-            : EE_Registry::instance()->CFG->organization->name;
549
-        EE_Registry::instance()->CFG->organization->address_1 = isset($this->_req_data['organization_address_1'])
550
-            ? sanitize_text_field($this->_req_data['organization_address_1'])
551
-            : EE_Registry::instance()->CFG->organization->address_1;
552
-        EE_Registry::instance()->CFG->organization->address_2 = isset($this->_req_data['organization_address_2'])
553
-            ? sanitize_text_field($this->_req_data['organization_address_2'])
554
-            : EE_Registry::instance()->CFG->organization->address_2;
555
-        EE_Registry::instance()->CFG->organization->city      = isset($this->_req_data['organization_city'])
556
-            ? sanitize_text_field($this->_req_data['organization_city'])
557
-            : EE_Registry::instance()->CFG->organization->city;
558
-        EE_Registry::instance()->CFG->organization->STA_ID    = isset($this->_req_data['organization_state'])
559
-            ? absint($this->_req_data['organization_state'])
560
-            : EE_Registry::instance()->CFG->organization->STA_ID;
561
-        EE_Registry::instance()->CFG->organization->CNT_ISO   = isset($this->_req_data['organization_country'])
562
-            ? sanitize_text_field($this->_req_data['organization_country'])
563
-            : EE_Registry::instance()->CFG->organization->CNT_ISO;
564
-        EE_Registry::instance()->CFG->organization->zip       = isset($this->_req_data['organization_zip'])
565
-            ? sanitize_text_field($this->_req_data['organization_zip'])
566
-            : EE_Registry::instance()->CFG->organization->zip;
567
-        EE_Registry::instance()->CFG->organization->email     = isset($this->_req_data['organization_email'])
568
-            ? sanitize_email($this->_req_data['organization_email'])
569
-            : EE_Registry::instance()->CFG->organization->email;
570
-        EE_Registry::instance()->CFG->organization->vat       = isset($this->_req_data['organization_vat'])
571
-            ? sanitize_text_field($this->_req_data['organization_vat'])
572
-            : EE_Registry::instance()->CFG->organization->vat;
573
-        EE_Registry::instance()->CFG->organization->phone     = isset($this->_req_data['organization_phone'])
574
-            ? sanitize_text_field($this->_req_data['organization_phone'])
575
-            : EE_Registry::instance()->CFG->organization->phone;
576
-        EE_Registry::instance()->CFG->organization->logo_url  = isset($this->_req_data['organization_logo_url'])
577
-            ? esc_url_raw($this->_req_data['organization_logo_url'])
578
-            : EE_Registry::instance()->CFG->organization->logo_url;
579
-        EE_Registry::instance()->CFG->organization->facebook  = isset($this->_req_data['organization_facebook'])
580
-            ? esc_url_raw($this->_req_data['organization_facebook'])
581
-            : EE_Registry::instance()->CFG->organization->facebook;
582
-        EE_Registry::instance()->CFG->organization->twitter   = isset($this->_req_data['organization_twitter'])
583
-            ? esc_url_raw($this->_req_data['organization_twitter'])
584
-            : EE_Registry::instance()->CFG->organization->twitter;
585
-        EE_Registry::instance()->CFG->organization->linkedin  = isset($this->_req_data['organization_linkedin'])
586
-            ? esc_url_raw($this->_req_data['organization_linkedin'])
587
-            : EE_Registry::instance()->CFG->organization->linkedin;
588
-        EE_Registry::instance()->CFG->organization->pinterest = isset($this->_req_data['organization_pinterest'])
589
-            ? esc_url_raw($this->_req_data['organization_pinterest'])
590
-            : EE_Registry::instance()->CFG->organization->pinterest;
591
-        EE_Registry::instance()->CFG->organization->google    = isset($this->_req_data['organization_google'])
592
-            ? esc_url_raw($this->_req_data['organization_google'])
593
-            : EE_Registry::instance()->CFG->organization->google;
594
-        EE_Registry::instance()->CFG->organization->instagram = isset($this->_req_data['organization_instagram'])
595
-            ? esc_url_raw($this->_req_data['organization_instagram'])
596
-            : EE_Registry::instance()->CFG->organization->instagram;
597
-        EE_Registry::instance()->CFG->core->ee_ueip_optin     = isset($this->_req_data['ueip_optin'])
598
-                                                                && ! empty($this->_req_data['ueip_optin'])
599
-            ? filter_var($this->_req_data['ueip_optin'], FILTER_VALIDATE_BOOLEAN)
600
-            : EE_Registry::instance()->CFG->core->ee_ueip_optin;
601
-
602
-        EE_Registry::instance()->CFG->currency = new EE_Currency_Config(
603
-            EE_Registry::instance()->CFG->organization->CNT_ISO
604
-        );
605
-
606
-        EE_Registry::instance()->CFG = apply_filters(
607
-            'FHEE__General_Settings_Admin_Page___update_your_organization_settings__CFG',
608
-            EE_Registry::instance()->CFG
609
-        );
610
-
611
-        $what    = 'Your Organization Settings';
612
-        $success = $this->_update_espresso_configuration(
613
-            $what,
614
-            EE_Registry::instance()->CFG,
615
-            __FILE__,
616
-            __FUNCTION__,
617
-            __LINE__
618
-        );
619
-
620
-        $this->_redirect_after_action($success, $what, 'updated', array('action' => 'default'));
621
-    }
622
-
623
-
624
-
625
-    /*************        Admin Options        *************/
626
-
627
-
628
-    /**
629
-     * _admin_option_settings
630
-     *
631
-     * @throws \EE_Error
632
-     * @throws \LogicException
633
-     */
634
-    protected function _admin_option_settings()
635
-    {
636
-        $this->_template_args['admin_page_content'] = '';
637
-        try {
638
-            $admin_options_settings_form = new AdminOptionsSettings(EE_Registry::instance());
639
-            // still need this for the old school form in Extend_General_Settings_Admin_Page
640
-            $this->_template_args['values'] = $this->_yes_no_values;
641
-            // also need to account for the do_action that was in the old template
642
-            $admin_options_settings_form->setTemplateArgs($this->_template_args);
643
-            $this->_template_args['admin_page_content'] = $admin_options_settings_form->display();
644
-        } catch (Exception $e) {
645
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
646
-        }
647
-        $this->_set_add_edit_form_tags('update_admin_option_settings');
648
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
649
-        $this->display_admin_page_with_sidebar();
650
-    }
651
-
652
-
653
-    /**
654
-     * _update_admin_option_settings
655
-     *
656
-     * @throws \EE_Error
657
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
658
-     * @throws \EventEspresso\core\exceptions\InvalidFormSubmissionException
659
-     * @throws \InvalidArgumentException
660
-     * @throws \LogicException
661
-     */
662
-    protected function _update_admin_option_settings()
663
-    {
664
-        try {
665
-            $admin_options_settings_form = new AdminOptionsSettings(EE_Registry::instance());
666
-            $admin_options_settings_form->process($this->_req_data[$admin_options_settings_form->slug()]);
667
-            EE_Registry::instance()->CFG->admin = apply_filters(
668
-                'FHEE__General_Settings_Admin_Page___update_admin_option_settings__CFG_admin',
669
-                EE_Registry::instance()->CFG->admin
670
-            );
671
-        } catch (Exception $e) {
672
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
673
-        }
674
-        $this->_redirect_after_action(
675
-            apply_filters(
676
-                'FHEE__General_Settings_Admin_Page___update_admin_option_settings__success',
677
-                $this->_update_espresso_configuration(
678
-                    'Admin Options',
679
-                    EE_Registry::instance()->CFG->admin,
680
-                    __FILE__, __FUNCTION__, __LINE__
681
-                )
682
-            ),
683
-            'Admin Options',
684
-            'updated',
685
-            array('action' => 'admin_option_settings')
686
-        );
687
-
688
-    }
689
-
690
-
691
-    /*************        Countries        *************/
692
-
693
-
694
-    /**
695
-     * Output Country Settings view.
696
-     * @throws DomainException
697
-     * @throws EE_Error
698
-     */
699
-    protected function _country_settings()
700
-    {
701
-        $CNT_ISO = isset(EE_Registry::instance()->CFG->organization->CNT_ISO)
702
-            ? EE_Registry::instance()->CFG->organization->CNT_ISO
703
-            : 'US';
704
-        $CNT_ISO = isset($this->_req_data['country'])
705
-            ? strtoupper(sanitize_text_field($this->_req_data['country']))
706
-            : $CNT_ISO;
707
-
708
-        //load field generator helper
709
-
710
-        $this->_template_args['values'] = $this->_yes_no_values;
711
-
712
-        $this->_template_args['countries'] = new EE_Question_Form_Input(
713
-            EE_Question::new_instance(array(
714
-                'QST_ID'           => 0,
715
-                'QST_display_text' => __('Select Country', 'event_espresso'),
716
-                'QST_system'       => 'admin-country',
717
-            )),
718
-            EE_Answer::new_instance(array(
719
-                'ANS_ID'    => 0,
720
-                'ANS_value' => $CNT_ISO,
721
-            )),
722
-            array(
723
-                'input_id'       => 'country',
724
-                'input_name'     => 'country',
725
-                'input_prefix'   => '',
726
-                'append_qstn_id' => false,
727
-            )
728
-        );
729
-
730
-        add_filter('FHEE__EEH_Form_Fields__label_html', array($this, 'country_form_field_label_wrap'), 10, 2);
731
-        add_filter('FHEE__EEH_Form_Fields__input_html', array($this, 'country_form_field_input__wrap'), 10, 2);
732
-        $this->_template_args['country_details_settings'] = $this->display_country_settings();
733
-        $this->_template_args['country_states_settings']  = $this->display_country_states();
734
-
735
-        $this->_set_add_edit_form_tags('update_country_settings');
736
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
737
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
738
-            GEN_SET_TEMPLATE_PATH . 'countries_settings.template.php',
739
-            $this->_template_args,
740
-            true
741
-        );
742
-        $this->display_admin_page_with_no_sidebar();
743
-    }
744
-
745
-
746
-    /**
747
-     *        display_country_settings
748
-     *
749
-     * @access    public
750
-     * @param    string $CNT_ISO
751
-     * @return mixed string | array
752
-     * @throws DomainException
753
-     */
754
-    public function display_country_settings($CNT_ISO = '')
755
-    {
756
-
757
-        $CNT_ISO = isset($this->_req_data['country'])
758
-            ? strtoupper(sanitize_text_field($this->_req_data['country']))
759
-            : $CNT_ISO;
760
-        if (! $CNT_ISO) {
761
-            return '';
762
-        }
763
-
764
-        // for ajax
765
-        remove_all_filters('FHEE__EEH_Form_Fields__label_html');
766
-        remove_all_filters('FHEE__EEH_Form_Fields__input_html');
767
-        add_filter('FHEE__EEH_Form_Fields__label_html', array($this, 'country_form_field_label_wrap'), 10, 2);
768
-        add_filter('FHEE__EEH_Form_Fields__input_html', array($this, 'country_form_field_input__wrap'), 10, 2);
769
-        $country = EEM_Country::instance()->get_one_by_ID($CNT_ISO);
770
-
771
-        $country_input_types            = array(
772
-            'CNT_active'      => array(
773
-                'type'             => 'RADIO_BTN',
774
-                'input_name'       => 'cntry[' . $CNT_ISO . ']',
775
-                'class'            => '',
776
-                'options'          => $this->_yes_no_values,
777
-                'use_desc_4_label' => true,
778
-            ),
779
-            'CNT_ISO'         => array(
780
-                'type'       => 'TEXT',
781
-                'input_name' => 'cntry[' . $CNT_ISO . ']',
782
-                'class'      => 'small-text',
783
-            ),
784
-            'CNT_ISO3'        => array(
785
-                'type'       => 'TEXT',
786
-                'input_name' => 'cntry[' . $CNT_ISO . ']',
787
-                'class'      => 'small-text',
788
-            ),
789
-            'RGN_ID'          => array(
790
-                'type'       => 'TEXT',
791
-                'input_name' => 'cntry[' . $CNT_ISO . ']',
792
-                'class'      => 'small-text',
793
-            ),
794
-            'CNT_name'        => array(
795
-                'type'       => 'TEXT',
796
-                'input_name' => 'cntry[' . $CNT_ISO . ']',
797
-                'class'      => 'regular-text',
798
-            ),
799
-            'CNT_cur_code'    => array(
800
-                'type'       => 'TEXT',
801
-                'input_name' => 'cntry[' . $CNT_ISO . ']',
802
-                'class'      => 'small-text',
803
-            ),
804
-            'CNT_cur_single'  => array(
805
-                'type'       => 'TEXT',
806
-                'input_name' => 'cntry[' . $CNT_ISO . ']',
807
-                'class'      => 'medium-text',
808
-            ),
809
-            'CNT_cur_plural'  => array(
810
-                'type'       => 'TEXT',
811
-                'input_name' => 'cntry[' . $CNT_ISO . ']',
812
-                'class'      => 'medium-text',
813
-            ),
814
-            'CNT_cur_sign'    => array(
815
-                'type'         => 'TEXT',
816
-                'input_name'   => 'cntry[' . $CNT_ISO . ']',
817
-                'class'        => 'small-text',
818
-                'htmlentities' => false,
819
-            ),
820
-            'CNT_cur_sign_b4' => array(
821
-                'type'             => 'RADIO_BTN',
822
-                'input_name'       => 'cntry[' . $CNT_ISO . ']',
823
-                'class'            => '',
824
-                'options'          => $this->_yes_no_values,
825
-                'use_desc_4_label' => true,
826
-            ),
827
-            'CNT_cur_dec_plc' => array(
828
-                'type'       => 'RADIO_BTN',
829
-                'input_name' => 'cntry[' . $CNT_ISO . ']',
830
-                'class'      => '',
831
-                'options'    => array(
832
-                    array('id' => 0, 'text' => ''),
833
-                    array('id' => 1, 'text' => ''),
834
-                    array('id' => 2, 'text' => ''),
835
-                    array('id' => 3, 'text' => ''),
836
-                ),
837
-            ),
838
-            'CNT_cur_dec_mrk' => array(
839
-                'type'             => 'RADIO_BTN',
840
-                'input_name'       => 'cntry[' . $CNT_ISO . ']',
841
-                'class'            => '',
842
-                'options'          => array(
843
-                    array(
844
-                        'id'   => ',',
845
-                        'text' => __(', (comma)', 'event_espresso'),
846
-                    ),
847
-                    array('id' => '.', 'text' => __('. (decimal)', 'event_espresso')),
848
-                ),
849
-                'use_desc_4_label' => true,
850
-            ),
851
-            'CNT_cur_thsnds'  => array(
852
-                'type'             => 'RADIO_BTN',
853
-                'input_name'       => 'cntry[' . $CNT_ISO . ']',
854
-                'class'            => '',
855
-                'options'          => array(
856
-                    array(
857
-                        'id'   => ',',
858
-                        'text' => __(', (comma)', 'event_espresso'),
859
-                    ),
860
-                    array('id' => '.', 'text' => __('. (decimal)', 'event_espresso')),
861
-                ),
862
-                'use_desc_4_label' => true,
863
-            ),
864
-            'CNT_tel_code'    => array(
865
-                'type'       => 'TEXT',
866
-                'input_name' => 'cntry[' . $CNT_ISO . ']',
867
-                'class'      => 'small-text',
868
-            ),
869
-            'CNT_is_EU'       => array(
870
-                'type'             => 'RADIO_BTN',
871
-                'input_name'       => 'cntry[' . $CNT_ISO . ']',
872
-                'class'            => '',
873
-                'options'          => $this->_yes_no_values,
874
-                'use_desc_4_label' => true,
875
-            ),
876
-        );
877
-        $this->_template_args['inputs'] = EE_Question_Form_Input::generate_question_form_inputs_for_object(
878
-            $country,
879
-            $country_input_types
880
-        );
881
-        $country_details_settings       = EEH_Template::display_template(
882
-            GEN_SET_TEMPLATE_PATH . 'country_details_settings.template.php',
883
-            $this->_template_args,
884
-            true
885
-        );
886
-
887
-        if (defined('DOING_AJAX')) {
888
-            $notices = EE_Error::get_notices(false, false, false);
889
-            echo wp_json_encode(array(
890
-                'return_data' => $country_details_settings,
891
-                'success'     => $notices['success'],
892
-                'errors'      => $notices['errors'],
893
-            ));
894
-            die();
895
-        } else {
896
-            return $country_details_settings;
897
-        }
898
-    }
899
-
900
-
901
-    /**
902
-     *        display_country_states
903
-     *
904
-     * @access    public
905
-     * @param    string $CNT_ISO
906
-     * @return string
907
-     * @throws DomainException
908
-     */
909
-    public function display_country_states($CNT_ISO = '')
910
-    {
911
-
912
-        $CNT_ISO = isset($this->_req_data['country']) ? sanitize_text_field($this->_req_data['country']) : $CNT_ISO;
913
-
914
-        if (! $CNT_ISO) {
915
-            return '';
916
-        }
917
-        // for ajax
918
-        remove_all_filters('FHEE__EEH_Form_Fields__label_html');
919
-        remove_all_filters('FHEE__EEH_Form_Fields__input_html');
920
-        add_filter('FHEE__EEH_Form_Fields__label_html', array($this, 'state_form_field_label_wrap'), 10, 2);
921
-        add_filter('FHEE__EEH_Form_Fields__input_html', array($this, 'state_form_field_input__wrap'), 10, 2);
922
-        $states = EEM_State::instance()->get_all_states_for_these_countries(array($CNT_ISO => $CNT_ISO));
923
-
924
-        if ($states) {
925
-            foreach ($states as $STA_ID => $state) {
926
-                if ($state instanceof EE_State) {
927
-                    //STA_abbrev 	STA_name 	STA_active
928
-                    $state_input_types                                           = array(
929
-                        'STA_abbrev' => array(
930
-                            'type'       => 'TEXT',
931
-                            'input_name' => 'states[' . $STA_ID . ']',
932
-                            'class'      => 'mid-text',
933
-                        ),
934
-                        'STA_name'   => array(
935
-                            'type'       => 'TEXT',
936
-                            'input_name' => 'states[' . $STA_ID . ']',
937
-                            'class'      => 'regular-text',
938
-                        ),
939
-                        'STA_active' => array(
940
-                            'type'             => 'RADIO_BTN',
941
-                            'input_name'       => 'states[' . $STA_ID . ']',
942
-                            'options'          => $this->_yes_no_values,
943
-                            'use_desc_4_label' => true,
944
-                        ),
945
-                    );
946
-                    $this->_template_args['states'][$STA_ID]['inputs'] =
947
-                        EE_Question_Form_Input::generate_question_form_inputs_for_object(
948
-                            $state,
949
-                            $state_input_types
950
-                        );
951
-                    $query_args                                                  = array(
952
-                        'action'     => 'delete_state',
953
-                        'STA_ID'     => $STA_ID,
954
-                        'CNT_ISO'    => $CNT_ISO,
955
-                        'STA_abbrev' => $state->abbrev(),
956
-                    );
957
-                    $this->_template_args['states'][$STA_ID]['delete_state_url'] =
958
-                        EE_Admin_Page::add_query_args_and_nonce(
959
-                            $query_args,
960
-                            GEN_SET_ADMIN_URL
961
-                        );
962
-                }
963
-            }
964
-        } else {
965
-            $this->_template_args['states'] = false;
966
-        }
967
-
968
-        $this->_template_args['add_new_state_url'] = EE_Admin_Page::add_query_args_and_nonce(
969
-            array('action' => 'add_new_state'),
970
-            GEN_SET_ADMIN_URL
971
-        );
972
-
973
-        $state_details_settings = EEH_Template::display_template(
974
-            GEN_SET_TEMPLATE_PATH . 'state_details_settings.template.php',
975
-            $this->_template_args,
976
-            true
977
-        );
978
-
979
-        if (defined('DOING_AJAX')) {
980
-            $notices = EE_Error::get_notices(false, false, false);
981
-            echo wp_json_encode(array(
982
-                'return_data' => $state_details_settings,
983
-                'success'     => $notices['success'],
984
-                'errors'      => $notices['errors'],
985
-            ));
986
-            die();
987
-        } else {
988
-            return $state_details_settings;
989
-        }
990
-    }
991
-
992
-
993
-    /**
994
-     *        add_new_state
995
-     *
996
-     * @access    public
997
-     * @return void
998
-     * @throws EE_Error
999
-     */
1000
-    public function add_new_state()
1001
-    {
1002
-
1003
-        $success = true;
1004
-
1005
-        $CNT_ISO = isset($this->_req_data['CNT_ISO'])
1006
-            ? strtoupper(sanitize_text_field($this->_req_data['CNT_ISO']))
1007
-            : false;
1008
-        if (! $CNT_ISO) {
1009
-            EE_Error::add_error(
1010
-                __('No Country ISO code or an invalid Country ISO code was received.', 'event_espresso'),
1011
-                __FILE__,
1012
-                __FUNCTION__,
1013
-                __LINE__
1014
-            );
1015
-            $success = false;
1016
-        }
1017
-        $STA_abbrev = isset($this->_req_data['STA_abbrev'])
1018
-            ? sanitize_text_field($this->_req_data['STA_abbrev'])
1019
-            : false;
1020
-        if (! $STA_abbrev) {
1021
-            EE_Error::add_error(
1022
-                __('No State ISO code or an invalid State ISO code was received.', 'event_espresso'),
1023
-                __FILE__,
1024
-                __FUNCTION__,
1025
-                __LINE__
1026
-            );
1027
-            $success = false;
1028
-        }
1029
-        $STA_name = isset($this->_req_data['STA_name'])
1030
-            ? sanitize_text_field($this->_req_data['STA_name'])
1031
-            : false;
1032
-        if (! $STA_name) {
1033
-            EE_Error::add_error(
1034
-                __('No State name or an invalid State name was received.', 'event_espresso'),
1035
-                __FILE__,
1036
-                __FUNCTION__,
1037
-                __LINE__
1038
-            );
1039
-            $success = false;
1040
-        }
1041
-
1042
-        if ($success) {
1043
-            $cols_n_values = array(
1044
-                'CNT_ISO'    => $CNT_ISO,
1045
-                'STA_abbrev' => $STA_abbrev,
1046
-                'STA_name'   => $STA_name,
1047
-                'STA_active' => true,
1048
-            );
1049
-            $success       = EEM_State::instance()->insert($cols_n_values);
1050
-            EE_Error::add_success(__('The State was added successfully.', 'event_espresso'));
1051
-        }
1052
-
1053
-        if (defined('DOING_AJAX')) {
1054
-            $notices = EE_Error::get_notices(false, false, false);
1055
-            echo wp_json_encode(array_merge($notices, array('return_data' => $CNT_ISO)));
1056
-            die();
1057
-        } else {
1058
-            $this->_redirect_after_action($success, 'State', 'added', array('action' => 'country_settings'));
1059
-        }
1060
-    }
1061
-
1062
-
1063
-    /**
1064
-     *        delete_state
1065
-     *
1066
-     * @access    public
1067
-     * @return        boolean
1068
-     */
1069
-    public function delete_state()
1070
-    {
1071
-        $CNT_ISO    = isset($this->_req_data['CNT_ISO'])
1072
-            ? strtoupper(sanitize_text_field($this->_req_data['CNT_ISO']))
1073
-            : false;
1074
-        $STA_ID     = isset($this->_req_data['STA_ID'])
1075
-            ? sanitize_text_field($this->_req_data['STA_ID'])
1076
-            : false;
1077
-        $STA_abbrev = isset($this->_req_data['STA_abbrev'])
1078
-            ? sanitize_text_field($this->_req_data['STA_abbrev'])
1079
-            : false;
1080
-        if (! $STA_ID) {
1081
-            EE_Error::add_error(
1082
-                __('No State ID or an invalid State ID was received.', 'event_espresso'),
1083
-                __FILE__,
1084
-                __FUNCTION__,
1085
-                __LINE__
1086
-            );
1087
-            return false;
1088
-        }
1089
-
1090
-        $success = EEM_State::instance()->delete_by_ID($STA_ID);
1091
-        if ($success !== false) {
1092
-            do_action(
1093
-                'AHEE__General_Settings_Admin_Page__delete_state__state_deleted',
1094
-                $CNT_ISO,
1095
-                $STA_ID,
1096
-                array('STA_abbrev' => $STA_abbrev)
1097
-            );
1098
-            EE_Error::add_success(__('The State was deleted successfully.', 'event_espresso'));
1099
-        }
1100
-        if (defined('DOING_AJAX')) {
1101
-            $notices                = EE_Error::get_notices(false, false);
1102
-            $notices['return_data'] = true;
1103
-            echo wp_json_encode($notices);
1104
-            die();
1105
-        } else {
1106
-            $this->_redirect_after_action(
1107
-                $success,
1108
-                'State',
1109
-                'deleted',
1110
-                array('action' => 'country_settings')
1111
-            );
1112
-        }
1113
-    }
1114
-
1115
-
1116
-    /**
1117
-     *        _update_country_settings
1118
-     *
1119
-     * @access    protected
1120
-     * @return void
1121
-     * @throws EE_Error
1122
-     */
1123
-    protected function _update_country_settings()
1124
-    {
1125
-        // grab the country ISO code
1126
-        $CNT_ISO = isset($this->_req_data['country'])
1127
-            ? strtoupper(sanitize_text_field($this->_req_data['country']))
1128
-            : false;
1129
-        if (! $CNT_ISO) {
1130
-            EE_Error::add_error(
1131
-                __('No Country ISO code or an invalid Country ISO code was received.', 'event_espresso'),
1132
-                __FILE__,
1133
-                __FUNCTION__,
1134
-                __LINE__
1135
-            );
1136
-
1137
-            return;
1138
-        }
1139
-        $cols_n_values                    = array();
1140
-        $cols_n_values['CNT_ISO3']        = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_ISO3'])
1141
-            ? strtoupper(sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_ISO3']))
1142
-            : false;
1143
-        $cols_n_values['RGN_ID']          = isset($this->_req_data['cntry'][$CNT_ISO]['RGN_ID'])
1144
-            ? absint($this->_req_data['cntry'][$CNT_ISO]['RGN_ID'])
1145
-            : null;
1146
-        $cols_n_values['CNT_name']        = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_name'])
1147
-            ? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_name'])
1148
-            : null;
1149
-        $cols_n_values['CNT_cur_code']    = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_code'])
1150
-            ? strtoupper(sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_code']))
1151
-            : 'USD';
1152
-        $cols_n_values['CNT_cur_single']  = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_single'])
1153
-            ? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_single'])
1154
-            : 'dollar';
1155
-        $cols_n_values['CNT_cur_plural']  = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_plural'])
1156
-            ? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_plural'])
1157
-            : 'dollars';
1158
-        $cols_n_values['CNT_cur_sign']    = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_sign'])
1159
-            ? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_sign'])
1160
-            : '$';
1161
-        $cols_n_values['CNT_cur_sign_b4'] = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_sign_b4'])
1162
-            ? absint($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_sign_b4'])
1163
-            : true;
1164
-        $cols_n_values['CNT_cur_dec_plc'] = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_dec_plc'])
1165
-            ? absint($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_dec_plc'])
1166
-            : 2;
1167
-        $cols_n_values['CNT_cur_dec_mrk'] = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_dec_mrk'])
1168
-            ? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_dec_mrk'])
1169
-            : '.';
1170
-        $cols_n_values['CNT_cur_thsnds']  = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_thsnds'])
1171
-            ? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_thsnds'])
1172
-            : ',';
1173
-        $cols_n_values['CNT_tel_code']    = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_tel_code'])
1174
-            ? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_tel_code'])
1175
-            : null;
1176
-        $cols_n_values['CNT_is_EU']       = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_is_EU'])
1177
-            ? absint($this->_req_data['cntry'][$CNT_ISO]['CNT_is_EU'])
1178
-            : false;
1179
-        $cols_n_values['CNT_active']      = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_active'])
1180
-            ? absint($this->_req_data['cntry'][$CNT_ISO]['CNT_active'])
1181
-            : false;
1182
-        // allow filtering of country data
1183
-        $cols_n_values = apply_filters(
1184
-            'FHEE__General_Settings_Admin_Page___update_country_settings__cols_n_values',
1185
-            $cols_n_values
1186
-        );
1187
-
1188
-        // where values
1189
-        $where_cols_n_values = array(array('CNT_ISO' => $CNT_ISO));
1190
-        // run the update
1191
-        $success = EEM_Country::instance()->update($cols_n_values, $where_cols_n_values);
1192
-
1193
-        if (isset($this->_req_data['states']) && is_array($this->_req_data['states']) && $success !== false) {
1194
-            // allow filtering of states data
1195
-            $states = apply_filters(
1196
-                'FHEE__General_Settings_Admin_Page___update_country_settings__states',
1197
-                $this->_req_data['states']
1198
-            );
1199
-
1200
-            // loop thru state data ( looks like : states[75][STA_name] )
1201
-            foreach ($states as $STA_ID => $state) {
1202
-                $cols_n_values = array(
1203
-                    'CNT_ISO'    => $CNT_ISO,
1204
-                    'STA_abbrev' => sanitize_text_field($state['STA_abbrev']),
1205
-                    'STA_name'   => sanitize_text_field($state['STA_name']),
1206
-                    'STA_active' => (bool)absint($state['STA_active']),
1207
-                );
1208
-                // where values
1209
-                $where_cols_n_values = array(array('STA_ID' => $STA_ID));
1210
-                // run the update
1211
-                $success = EEM_State::instance()->update($cols_n_values, $where_cols_n_values);
1212
-                if ($success !== false) {
1213
-                    do_action(
1214
-                        'AHEE__General_Settings_Admin_Page__update_country_settings__state_saved',
1215
-                        $CNT_ISO,
1216
-                        $STA_ID,
1217
-                        $cols_n_values
1218
-                    );
1219
-                }
1220
-            }
1221
-        }
1222
-        // check if country being edited matches org option country, and if so, then  update EE_Config with new settings
1223
-        if (isset(EE_Registry::instance()->CFG->organization->CNT_ISO)
1224
-            && $CNT_ISO == EE_Registry::instance()->CFG->organization->CNT_ISO
1225
-        ) {
1226
-            EE_Registry::instance()->CFG->currency = new EE_Currency_Config($CNT_ISO);
1227
-            EE_Registry::instance()->CFG->update_espresso_config();
1228
-        }
1229
-
1230
-        if ($success !== false) {
1231
-            EE_Error::add_success(
1232
-                esc_html__('Country Settings updated successfully.', 'event_espresso')
1233
-            );
1234
-        }
1235
-        $this->_redirect_after_action(
1236
-            $success,
1237
-            '',
1238
-            '',
1239
-            array('action' => 'country_settings', 'country' => $CNT_ISO),
1240
-            true
1241
-        );
1242
-    }
1243
-
1244
-
1245
-    /**
1246
-     *        form_form_field_label_wrap
1247
-     *
1248
-     * @access        public
1249
-     * @param        string $label
1250
-     * @return        string
1251
-     */
1252
-    public function country_form_field_label_wrap($label, $required_text)
1253
-    {
1254
-        return '
20
+	/**
21
+	 * _question_group
22
+	 * holds the specific question group object for the question group details screen
23
+	 *
24
+	 * @var object
25
+	 */
26
+	protected $_question_group;
27
+
28
+
29
+	/**
30
+	 * Initialize basic properties.
31
+	 */
32
+	protected function _init_page_props()
33
+	{
34
+		$this->page_slug        = GEN_SET_PG_SLUG;
35
+		$this->page_label       = GEN_SET_LABEL;
36
+		$this->_admin_base_url  = GEN_SET_ADMIN_URL;
37
+		$this->_admin_base_path = GEN_SET_ADMIN;
38
+	}
39
+
40
+
41
+	/**
42
+	 * Set ajax hooks
43
+	 */
44
+	protected function _ajax_hooks()
45
+	{
46
+		add_action('wp_ajax_espresso_display_country_settings', array($this, 'display_country_settings'));
47
+		add_action('wp_ajax_espresso_display_country_states', array($this, 'display_country_states'));
48
+		add_action('wp_ajax_espresso_delete_state', array($this, 'delete_state'), 10, 3);
49
+		add_action('wp_ajax_espresso_add_new_state', array($this, 'add_new_state'));
50
+	}
51
+
52
+
53
+	/**
54
+	 * More page properties initialization.
55
+	 */
56
+	protected function _define_page_props()
57
+	{
58
+		$this->_admin_page_title = GEN_SET_LABEL;
59
+		$this->_labels           = array(
60
+			'publishbox' => __('Update Settings', 'event_espresso'),
61
+		);
62
+	}
63
+
64
+
65
+	/**
66
+	 * Set page routes property.
67
+	 */
68
+	protected function _set_page_routes()
69
+	{
70
+		$this->_page_routes = array(
71
+
72
+			'critical_pages'                => array(
73
+				'func'       => '_espresso_page_settings',
74
+				'capability' => 'manage_options',
75
+			),
76
+			'update_espresso_page_settings' => array(
77
+				'func'       => '_update_espresso_page_settings',
78
+				'capability' => 'manage_options',
79
+				'noheader'   => true,
80
+			),
81
+			'default'                       => array(
82
+				'func'       => '_your_organization_settings',
83
+				'capability' => 'manage_options',
84
+			),
85
+
86
+			'update_your_organization_settings' => array(
87
+				'func'       => '_update_your_organization_settings',
88
+				'capability' => 'manage_options',
89
+				'noheader'   => true,
90
+			),
91
+
92
+			'admin_option_settings' => array(
93
+				'func'       => '_admin_option_settings',
94
+				'capability' => 'manage_options',
95
+			),
96
+
97
+			'update_admin_option_settings' => array(
98
+				'func'       => '_update_admin_option_settings',
99
+				'capability' => 'manage_options',
100
+				'noheader'   => true,
101
+			),
102
+
103
+			'country_settings' => array(
104
+				'func'       => '_country_settings',
105
+				'capability' => 'manage_options',
106
+			),
107
+
108
+			'update_country_settings' => array(
109
+				'func'       => '_update_country_settings',
110
+				'capability' => 'manage_options',
111
+				'noheader'   => true,
112
+			),
113
+
114
+			'display_country_settings' => array(
115
+				'func'       => 'display_country_settings',
116
+				'capability' => 'manage_options',
117
+				'noheader'   => true,
118
+			),
119
+
120
+			'add_new_state' => array(
121
+				'func'       => 'add_new_state',
122
+				'capability' => 'manage_options',
123
+				'noheader'   => true,
124
+			),
125
+
126
+			'delete_state' => array(
127
+				'func'       => 'delete_state',
128
+				'capability' => 'manage_options',
129
+				'noheader'   => true,
130
+			),
131
+		);
132
+	}
133
+
134
+
135
+	/**
136
+	 * Set page configuration property
137
+	 */
138
+	protected function _set_page_config()
139
+	{
140
+		$this->_page_config = array(
141
+			'critical_pages'        => array(
142
+				'nav'           => array(
143
+					'label' => __('Critical Pages', 'event_espresso'),
144
+					'order' => 50,
145
+				),
146
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
147
+				'help_tabs'     => array(
148
+					'general_settings_critical_pages_help_tab' => array(
149
+						'title'    => __('Critical Pages', 'event_espresso'),
150
+						'filename' => 'general_settings_critical_pages',
151
+					),
152
+				),
153
+				'help_tour'     => array('Critical_Pages_Help_Tour'),
154
+				'require_nonce' => false,
155
+			),
156
+			'default'               => array(
157
+				'nav'           => array(
158
+					'label' => __('Your Organization', 'event_espresso'),
159
+					'order' => 20,
160
+				),
161
+				'help_tabs'     => array(
162
+					'general_settings_your_organization_help_tab' => array(
163
+						'title'    => __('Your Organization', 'event_espresso'),
164
+						'filename' => 'general_settings_your_organization',
165
+					),
166
+				),
167
+				'help_tour'     => array('Your_Organization_Help_Tour'),
168
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
169
+				'require_nonce' => false,
170
+			),
171
+			'admin_option_settings' => array(
172
+				'nav'           => array(
173
+					'label' => __('Admin Options', 'event_espresso'),
174
+					'order' => 60,
175
+				),
176
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
177
+				'help_tabs'     => array(
178
+					'general_settings_admin_options_help_tab' => array(
179
+						'title'    => __('Admin Options', 'event_espresso'),
180
+						'filename' => 'general_settings_admin_options',
181
+					),
182
+				),
183
+				'help_tour'     => array('Admin_Options_Help_Tour'),
184
+				'require_nonce' => false,
185
+			),
186
+			'country_settings'      => array(
187
+				'nav'           => array(
188
+					'label' => __('Countries', 'event_espresso'),
189
+					'order' => 70,
190
+				),
191
+				'help_tabs'     => array(
192
+					'general_settings_countries_help_tab' => array(
193
+						'title'    => __('Countries', 'event_espresso'),
194
+						'filename' => 'general_settings_countries',
195
+					),
196
+				),
197
+				'help_tour'     => array('Countries_Help_Tour'),
198
+				'require_nonce' => false,
199
+			),
200
+		);
201
+	}
202
+
203
+
204
+
205
+	protected function _add_screen_options()
206
+	{
207
+	}
208
+
209
+	protected function _add_feature_pointers()
210
+	{
211
+	}
212
+
213
+
214
+	/**
215
+	 * Enqueue global scripts and styles for all routes in the General Settings Admin Pages.
216
+	 */
217
+	public function load_scripts_styles()
218
+	{
219
+		//styles
220
+		wp_enqueue_style('espresso-ui-theme');
221
+		//scripts
222
+		wp_enqueue_script('ee_admin_js');
223
+	}
224
+
225
+
226
+	/**
227
+	 * Execute logic running on `admin_init`
228
+	 */
229
+	public function admin_init()
230
+	{
231
+		EE_Registry::$i18n_js_strings['invalid_server_response'] = __(
232
+			'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.',
233
+			'event_espresso'
234
+		);
235
+		EE_Registry::$i18n_js_strings['error_occurred']          = __(
236
+			'An error occurred! Please refresh the page and try again.',
237
+			'event_espresso'
238
+		);
239
+		EE_Registry::$i18n_js_strings['confirm_delete_state']    = __(
240
+			'Are you sure you want to delete this State / Province?',
241
+			'event_espresso'
242
+		);
243
+		$protocol                                                = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
244
+		EE_Registry::$i18n_js_strings['ajax_url']                = admin_url(
245
+			'admin-ajax.php?page=espresso_general_settings',
246
+			$protocol
247
+		);
248
+	}
249
+
250
+	public function admin_notices()
251
+	{
252
+	}
253
+
254
+	public function admin_footer_scripts()
255
+	{
256
+	}
257
+
258
+
259
+	/**
260
+	 * Enqueue scripts and styles for the default route.
261
+	 */
262
+	public function load_scripts_styles_default()
263
+	{
264
+		//styles
265
+		wp_enqueue_style('thickbox');
266
+		//scripts
267
+		wp_enqueue_script('media-upload');
268
+		wp_enqueue_script('thickbox');
269
+		wp_register_script(
270
+			'organization_settings',
271
+			GEN_SET_ASSETS_URL . 'your_organization_settings.js',
272
+			array('jquery', 'media-upload', 'thickbox'),
273
+			EVENT_ESPRESSO_VERSION,
274
+			true
275
+		);
276
+		wp_register_style('organization-css', GEN_SET_ASSETS_URL . 'organization.css', array(), EVENT_ESPRESSO_VERSION);
277
+		wp_enqueue_script('organization_settings');
278
+		wp_enqueue_style('organization-css');
279
+		$confirm_image_delete = array(
280
+			'text' => __(
281
+				'Do you really want to delete this image? Please remember to save your settings to complete the removal.',
282
+				'event_espresso'
283
+			),
284
+		);
285
+		wp_localize_script('organization_settings', 'confirm_image_delete', $confirm_image_delete);
286
+	}
287
+
288
+
289
+	/**
290
+	 * Enqueue scripts and styles for the country settings route.
291
+	 */
292
+	public function load_scripts_styles_country_settings()
293
+	{
294
+		//scripts
295
+		wp_register_script(
296
+			'gen_settings_countries',
297
+			GEN_SET_ASSETS_URL . 'gen_settings_countries.js',
298
+			array('ee_admin_js'),
299
+			EVENT_ESPRESSO_VERSION,
300
+			true
301
+		);
302
+		wp_register_style('organization-css', GEN_SET_ASSETS_URL . 'organization.css', array(), EVENT_ESPRESSO_VERSION);
303
+		wp_enqueue_script('gen_settings_countries');
304
+		wp_enqueue_style('organization-css');
305
+	}
306
+
307
+
308
+	/*************        Espresso Pages        *************/
309
+	/**
310
+	 * _espresso_page_settings
311
+	 *
312
+	 * @throws \EE_Error
313
+	 */
314
+	protected function _espresso_page_settings()
315
+	{
316
+		// Check to make sure all of the main pages are setup properly,
317
+		// if not create the default pages and display an admin notice
318
+		EEH_Activation::verify_default_pages_exist();
319
+		$this->_transient_garbage_collection();
320
+		$this->_template_args['values']             = $this->_yes_no_values;
321
+		$this->_template_args['reg_page_id']        = isset(EE_Registry::instance()->CFG->core->reg_page_id)
322
+			? EE_Registry::instance()->CFG->core->reg_page_id
323
+			: null;
324
+		$this->_template_args['reg_page_obj']       = isset(EE_Registry::instance()->CFG->core->reg_page_id)
325
+			? get_page(EE_Registry::instance()->CFG->core->reg_page_id)
326
+			: false;
327
+		$this->_template_args['txn_page_id']        = isset(EE_Registry::instance()->CFG->core->txn_page_id)
328
+			? EE_Registry::instance()->CFG->core->txn_page_id
329
+			: null;
330
+		$this->_template_args['txn_page_obj']       = isset(EE_Registry::instance()->CFG->core->txn_page_id)
331
+			? get_page(EE_Registry::instance()->CFG->core->txn_page_id)
332
+			: false;
333
+		$this->_template_args['thank_you_page_id']  = isset(EE_Registry::instance()->CFG->core->thank_you_page_id)
334
+			? EE_Registry::instance()->CFG->core->thank_you_page_id
335
+			: null;
336
+		$this->_template_args['thank_you_page_obj'] = isset(EE_Registry::instance()->CFG->core->thank_you_page_id)
337
+			? get_page(EE_Registry::instance()->CFG->core->thank_you_page_id)
338
+			: false;
339
+		$this->_template_args['cancel_page_id']     = isset(EE_Registry::instance()->CFG->core->cancel_page_id)
340
+			? EE_Registry::instance()->CFG->core->cancel_page_id
341
+			: null;
342
+		$this->_template_args['cancel_page_obj']    = isset(EE_Registry::instance()->CFG->core->cancel_page_id)
343
+			? get_page(EE_Registry::instance()->CFG->core->cancel_page_id)
344
+			: false;
345
+		$this->_set_add_edit_form_tags('update_espresso_page_settings');
346
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
347
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
348
+			GEN_SET_TEMPLATE_PATH . 'espresso_page_settings.template.php',
349
+			$this->_template_args,
350
+			true
351
+		);
352
+		$this->display_admin_page_with_sidebar();
353
+	}
354
+
355
+
356
+	/**
357
+	 * Handler for updating espresso page settings.
358
+	 */
359
+	protected function _update_espresso_page_settings()
360
+	{
361
+		// capture incoming request data && set page IDs
362
+		EE_Registry::instance()->CFG->core->reg_page_id       = isset($this->_req_data['reg_page_id'])
363
+			? absint($this->_req_data['reg_page_id'])
364
+			: EE_Registry::instance()->CFG->core->reg_page_id;
365
+		EE_Registry::instance()->CFG->core->txn_page_id       = isset($this->_req_data['txn_page_id'])
366
+			? absint($this->_req_data['txn_page_id'])
367
+			: EE_Registry::instance()->CFG->core->txn_page_id;
368
+		EE_Registry::instance()->CFG->core->thank_you_page_id = isset($this->_req_data['thank_you_page_id'])
369
+			? absint($this->_req_data['thank_you_page_id'])
370
+			: EE_Registry::instance()->CFG->core->thank_you_page_id;
371
+		EE_Registry::instance()->CFG->core->cancel_page_id    = isset($this->_req_data['cancel_page_id'])
372
+			? absint($this->_req_data['cancel_page_id'])
373
+			: EE_Registry::instance()->CFG->core->cancel_page_id;
374
+
375
+		EE_Registry::instance()->CFG->core = apply_filters(
376
+			'FHEE__General_Settings_Admin_Page___update_espresso_page_settings__CFG_core',
377
+			EE_Registry::instance()->CFG->core,
378
+			$this->_req_data
379
+		);
380
+		$what                              = __('Critical Pages & Shortcodes', 'event_espresso');
381
+		$this->_redirect_after_action(
382
+			$this->_update_espresso_configuration(
383
+				$what,
384
+				EE_Registry::instance()->CFG->core,
385
+				__FILE__,
386
+				__FUNCTION__,
387
+				__LINE__
388
+			),
389
+			$what,
390
+			'',
391
+			array(
392
+				'action' => 'critical_pages',
393
+			),
394
+			true
395
+		);
396
+	}
397
+
398
+
399
+	/*************        Your Organization        *************/
400
+
401
+
402
+	/**
403
+	 * Output for the Your Organization settings route.
404
+	 * @throws DomainException
405
+	 * @throws EE_Error
406
+	 */
407
+	protected function _your_organization_settings()
408
+	{
409
+
410
+		$this->_template_args['site_license_key']       = isset(
411
+			EE_Registry::instance()->NET_CFG->core->site_license_key
412
+		)
413
+			? EE_Registry::instance()->NET_CFG->core->get_pretty('site_license_key')
414
+			: '';
415
+		$this->_template_args['organization_name']      = isset(EE_Registry::instance()->CFG->organization->name)
416
+			? EE_Registry::instance()->CFG->organization->get_pretty('name')
417
+			: '';
418
+		$this->_template_args['organization_address_1'] = isset(EE_Registry::instance()->CFG->organization->address_1)
419
+			? EE_Registry::instance()->CFG->organization->get_pretty('address_1')
420
+			: '';
421
+		$this->_template_args['organization_address_2'] = isset(EE_Registry::instance()->CFG->organization->address_2)
422
+			? EE_Registry::instance()->CFG->organization->get_pretty('address_2')
423
+			: '';
424
+		$this->_template_args['organization_city']      = isset(EE_Registry::instance()->CFG->organization->city)
425
+			? EE_Registry::instance()->CFG->organization->get_pretty('city')
426
+			: '';
427
+		$this->_template_args['organization_zip']       = isset(EE_Registry::instance()->CFG->organization->zip)
428
+			? EE_Registry::instance()->CFG->organization->get_pretty('zip')
429
+			: '';
430
+		$this->_template_args['organization_email']     = isset(EE_Registry::instance()->CFG->organization->email)
431
+			? EE_Registry::instance()->CFG->organization->get_pretty('email')
432
+			: '';
433
+		$this->_template_args['organization_phone']     = isset(EE_Registry::instance()->CFG->organization->phone)
434
+			? EE_Registry::instance()->CFG->organization->get_pretty('phone')
435
+			: '';
436
+		$this->_template_args['organization_vat']       = isset(EE_Registry::instance()->CFG->organization->vat)
437
+			? EE_Registry::instance()->CFG->organization->get_pretty('vat')
438
+			: '';
439
+		$this->_template_args['currency_sign']          = isset(EE_Registry::instance()->CFG->currency->sign)
440
+			? EE_Registry::instance()->CFG->currency->get_pretty('sign')
441
+			: '$';
442
+		$this->_template_args['organization_logo_url']  = isset(EE_Registry::instance()->CFG->organization->logo_url)
443
+			? EE_Registry::instance()->CFG->organization->get_pretty('logo_url')
444
+			: false;
445
+		$this->_template_args['organization_facebook']  = isset(EE_Registry::instance()->CFG->organization->facebook)
446
+			? EE_Registry::instance()->CFG->organization->get_pretty('facebook')
447
+			: '';
448
+		$this->_template_args['organization_twitter']   = isset(EE_Registry::instance()->CFG->organization->twitter)
449
+			? EE_Registry::instance()->CFG->organization->get_pretty('twitter')
450
+			: '';
451
+		$this->_template_args['organization_linkedin']  = isset(EE_Registry::instance()->CFG->organization->linkedin)
452
+			? EE_Registry::instance()->CFG->organization->get_pretty('linkedin')
453
+			: '';
454
+		$this->_template_args['organization_pinterest'] = isset(EE_Registry::instance()->CFG->organization->pinterest)
455
+			? EE_Registry::instance()->CFG->organization->get_pretty('pinterest')
456
+			: '';
457
+		$this->_template_args['organization_google']    = isset(EE_Registry::instance()->CFG->organization->google)
458
+			? EE_Registry::instance()->CFG->organization->get_pretty('google')
459
+			: '';
460
+		$this->_template_args['organization_instagram'] = isset(EE_Registry::instance()->CFG->organization->instagram)
461
+			? EE_Registry::instance()->CFG->organization->get_pretty('instagram')
462
+			: '';
463
+		//UXIP settings
464
+		$this->_template_args['ee_ueip_optin'] = isset(EE_Registry::instance()->CFG->core->ee_ueip_optin)
465
+			? EE_Registry::instance()->CFG->core->get_pretty('ee_ueip_optin')
466
+			: 'yes';
467
+
468
+		$STA_ID                         = isset(EE_Registry::instance()->CFG->organization->STA_ID)
469
+			? EE_Registry::instance()->CFG->organization->STA_ID
470
+			: 4;
471
+		$this->_template_args['states'] = new EE_Question_Form_Input(
472
+			EE_Question::new_instance(array(
473
+				'QST_ID'           => 0,
474
+				'QST_display_text' => __('State/Province', 'event_espresso'),
475
+				'QST_system'       => 'admin-state',
476
+			)),
477
+			EE_Answer::new_instance(array(
478
+				'ANS_ID'    => 0,
479
+				'ANS_value' => $STA_ID,
480
+			)),
481
+			array(
482
+				'input_id'       => 'organization_state',
483
+				'input_name'     => 'organization_state',
484
+				'input_prefix'   => '',
485
+				'append_qstn_id' => false,
486
+			)
487
+		);
488
+
489
+		$CNT_ISO                           = isset(EE_Registry::instance()->CFG->organization->CNT_ISO)
490
+			? EE_Registry::instance()->CFG->organization->CNT_ISO
491
+			: 'US';
492
+		$this->_template_args['countries'] = new EE_Question_Form_Input(
493
+			EE_Question::new_instance(array(
494
+				'QST_ID'           => 0,
495
+				'QST_display_text' => __('Country', 'event_espresso'),
496
+				'QST_system'       => 'admin-country',
497
+			)),
498
+			EE_Answer::new_instance(array(
499
+				'ANS_ID'    => 0,
500
+				'ANS_value' => $CNT_ISO,
501
+			)),
502
+			array(
503
+				'input_id'       => 'organization_country',
504
+				'input_name'     => 'organization_country',
505
+				'input_prefix'   => '',
506
+				'append_qstn_id' => false,
507
+			)
508
+		);
509
+
510
+		add_filter('FHEE__EEH_Form_Fields__label_html', array($this, 'country_form_field_label_wrap'), 10, 2);
511
+		add_filter('FHEE__EEH_Form_Fields__input_html', array($this, 'country_form_field_input__wrap'), 10, 2);
512
+
513
+		//PUE verification stuff
514
+		$ver_option_key                                    = 'puvererr_' . basename(EE_PLUGIN_BASENAME);
515
+		$verify_fail                                       = get_option($ver_option_key);
516
+		$this->_template_args['site_license_key_verified'] = $verify_fail
517
+															 || ! empty($verify_fail)
518
+															 || (empty($this->_template_args['site_license_key'])
519
+																 && empty($verify_fail)
520
+															 )
521
+			? '<span class="dashicons dashicons-admin-network ee-icon-color-ee-red ee-icon-size-20"></span>'
522
+			: '<span class="dashicons dashicons-admin-network ee-icon-color-ee-green ee-icon-size-20"></span>';
523
+
524
+		$this->_set_add_edit_form_tags('update_your_organization_settings');
525
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
526
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
527
+			GEN_SET_TEMPLATE_PATH . 'your_organization_settings.template.php',
528
+			$this->_template_args,
529
+			true
530
+		);
531
+
532
+		$this->display_admin_page_with_sidebar();
533
+	}
534
+
535
+
536
+	/**
537
+	 * Handler for updating organziation settings.
538
+	 */
539
+	protected function _update_your_organization_settings()
540
+	{
541
+		if (is_main_site()) {
542
+			EE_Registry::instance()->NET_CFG->core->site_license_key = isset($this->_req_data['site_license_key'])
543
+				? sanitize_text_field($this->_req_data['site_license_key'])
544
+				: EE_Registry::instance()->NET_CFG->core->site_license_key;
545
+		}
546
+		EE_Registry::instance()->CFG->organization->name      = isset($this->_req_data['organization_name'])
547
+			? sanitize_text_field($this->_req_data['organization_name'])
548
+			: EE_Registry::instance()->CFG->organization->name;
549
+		EE_Registry::instance()->CFG->organization->address_1 = isset($this->_req_data['organization_address_1'])
550
+			? sanitize_text_field($this->_req_data['organization_address_1'])
551
+			: EE_Registry::instance()->CFG->organization->address_1;
552
+		EE_Registry::instance()->CFG->organization->address_2 = isset($this->_req_data['organization_address_2'])
553
+			? sanitize_text_field($this->_req_data['organization_address_2'])
554
+			: EE_Registry::instance()->CFG->organization->address_2;
555
+		EE_Registry::instance()->CFG->organization->city      = isset($this->_req_data['organization_city'])
556
+			? sanitize_text_field($this->_req_data['organization_city'])
557
+			: EE_Registry::instance()->CFG->organization->city;
558
+		EE_Registry::instance()->CFG->organization->STA_ID    = isset($this->_req_data['organization_state'])
559
+			? absint($this->_req_data['organization_state'])
560
+			: EE_Registry::instance()->CFG->organization->STA_ID;
561
+		EE_Registry::instance()->CFG->organization->CNT_ISO   = isset($this->_req_data['organization_country'])
562
+			? sanitize_text_field($this->_req_data['organization_country'])
563
+			: EE_Registry::instance()->CFG->organization->CNT_ISO;
564
+		EE_Registry::instance()->CFG->organization->zip       = isset($this->_req_data['organization_zip'])
565
+			? sanitize_text_field($this->_req_data['organization_zip'])
566
+			: EE_Registry::instance()->CFG->organization->zip;
567
+		EE_Registry::instance()->CFG->organization->email     = isset($this->_req_data['organization_email'])
568
+			? sanitize_email($this->_req_data['organization_email'])
569
+			: EE_Registry::instance()->CFG->organization->email;
570
+		EE_Registry::instance()->CFG->organization->vat       = isset($this->_req_data['organization_vat'])
571
+			? sanitize_text_field($this->_req_data['organization_vat'])
572
+			: EE_Registry::instance()->CFG->organization->vat;
573
+		EE_Registry::instance()->CFG->organization->phone     = isset($this->_req_data['organization_phone'])
574
+			? sanitize_text_field($this->_req_data['organization_phone'])
575
+			: EE_Registry::instance()->CFG->organization->phone;
576
+		EE_Registry::instance()->CFG->organization->logo_url  = isset($this->_req_data['organization_logo_url'])
577
+			? esc_url_raw($this->_req_data['organization_logo_url'])
578
+			: EE_Registry::instance()->CFG->organization->logo_url;
579
+		EE_Registry::instance()->CFG->organization->facebook  = isset($this->_req_data['organization_facebook'])
580
+			? esc_url_raw($this->_req_data['organization_facebook'])
581
+			: EE_Registry::instance()->CFG->organization->facebook;
582
+		EE_Registry::instance()->CFG->organization->twitter   = isset($this->_req_data['organization_twitter'])
583
+			? esc_url_raw($this->_req_data['organization_twitter'])
584
+			: EE_Registry::instance()->CFG->organization->twitter;
585
+		EE_Registry::instance()->CFG->organization->linkedin  = isset($this->_req_data['organization_linkedin'])
586
+			? esc_url_raw($this->_req_data['organization_linkedin'])
587
+			: EE_Registry::instance()->CFG->organization->linkedin;
588
+		EE_Registry::instance()->CFG->organization->pinterest = isset($this->_req_data['organization_pinterest'])
589
+			? esc_url_raw($this->_req_data['organization_pinterest'])
590
+			: EE_Registry::instance()->CFG->organization->pinterest;
591
+		EE_Registry::instance()->CFG->organization->google    = isset($this->_req_data['organization_google'])
592
+			? esc_url_raw($this->_req_data['organization_google'])
593
+			: EE_Registry::instance()->CFG->organization->google;
594
+		EE_Registry::instance()->CFG->organization->instagram = isset($this->_req_data['organization_instagram'])
595
+			? esc_url_raw($this->_req_data['organization_instagram'])
596
+			: EE_Registry::instance()->CFG->organization->instagram;
597
+		EE_Registry::instance()->CFG->core->ee_ueip_optin     = isset($this->_req_data['ueip_optin'])
598
+																&& ! empty($this->_req_data['ueip_optin'])
599
+			? filter_var($this->_req_data['ueip_optin'], FILTER_VALIDATE_BOOLEAN)
600
+			: EE_Registry::instance()->CFG->core->ee_ueip_optin;
601
+
602
+		EE_Registry::instance()->CFG->currency = new EE_Currency_Config(
603
+			EE_Registry::instance()->CFG->organization->CNT_ISO
604
+		);
605
+
606
+		EE_Registry::instance()->CFG = apply_filters(
607
+			'FHEE__General_Settings_Admin_Page___update_your_organization_settings__CFG',
608
+			EE_Registry::instance()->CFG
609
+		);
610
+
611
+		$what    = 'Your Organization Settings';
612
+		$success = $this->_update_espresso_configuration(
613
+			$what,
614
+			EE_Registry::instance()->CFG,
615
+			__FILE__,
616
+			__FUNCTION__,
617
+			__LINE__
618
+		);
619
+
620
+		$this->_redirect_after_action($success, $what, 'updated', array('action' => 'default'));
621
+	}
622
+
623
+
624
+
625
+	/*************        Admin Options        *************/
626
+
627
+
628
+	/**
629
+	 * _admin_option_settings
630
+	 *
631
+	 * @throws \EE_Error
632
+	 * @throws \LogicException
633
+	 */
634
+	protected function _admin_option_settings()
635
+	{
636
+		$this->_template_args['admin_page_content'] = '';
637
+		try {
638
+			$admin_options_settings_form = new AdminOptionsSettings(EE_Registry::instance());
639
+			// still need this for the old school form in Extend_General_Settings_Admin_Page
640
+			$this->_template_args['values'] = $this->_yes_no_values;
641
+			// also need to account for the do_action that was in the old template
642
+			$admin_options_settings_form->setTemplateArgs($this->_template_args);
643
+			$this->_template_args['admin_page_content'] = $admin_options_settings_form->display();
644
+		} catch (Exception $e) {
645
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
646
+		}
647
+		$this->_set_add_edit_form_tags('update_admin_option_settings');
648
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
649
+		$this->display_admin_page_with_sidebar();
650
+	}
651
+
652
+
653
+	/**
654
+	 * _update_admin_option_settings
655
+	 *
656
+	 * @throws \EE_Error
657
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
658
+	 * @throws \EventEspresso\core\exceptions\InvalidFormSubmissionException
659
+	 * @throws \InvalidArgumentException
660
+	 * @throws \LogicException
661
+	 */
662
+	protected function _update_admin_option_settings()
663
+	{
664
+		try {
665
+			$admin_options_settings_form = new AdminOptionsSettings(EE_Registry::instance());
666
+			$admin_options_settings_form->process($this->_req_data[$admin_options_settings_form->slug()]);
667
+			EE_Registry::instance()->CFG->admin = apply_filters(
668
+				'FHEE__General_Settings_Admin_Page___update_admin_option_settings__CFG_admin',
669
+				EE_Registry::instance()->CFG->admin
670
+			);
671
+		} catch (Exception $e) {
672
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
673
+		}
674
+		$this->_redirect_after_action(
675
+			apply_filters(
676
+				'FHEE__General_Settings_Admin_Page___update_admin_option_settings__success',
677
+				$this->_update_espresso_configuration(
678
+					'Admin Options',
679
+					EE_Registry::instance()->CFG->admin,
680
+					__FILE__, __FUNCTION__, __LINE__
681
+				)
682
+			),
683
+			'Admin Options',
684
+			'updated',
685
+			array('action' => 'admin_option_settings')
686
+		);
687
+
688
+	}
689
+
690
+
691
+	/*************        Countries        *************/
692
+
693
+
694
+	/**
695
+	 * Output Country Settings view.
696
+	 * @throws DomainException
697
+	 * @throws EE_Error
698
+	 */
699
+	protected function _country_settings()
700
+	{
701
+		$CNT_ISO = isset(EE_Registry::instance()->CFG->organization->CNT_ISO)
702
+			? EE_Registry::instance()->CFG->organization->CNT_ISO
703
+			: 'US';
704
+		$CNT_ISO = isset($this->_req_data['country'])
705
+			? strtoupper(sanitize_text_field($this->_req_data['country']))
706
+			: $CNT_ISO;
707
+
708
+		//load field generator helper
709
+
710
+		$this->_template_args['values'] = $this->_yes_no_values;
711
+
712
+		$this->_template_args['countries'] = new EE_Question_Form_Input(
713
+			EE_Question::new_instance(array(
714
+				'QST_ID'           => 0,
715
+				'QST_display_text' => __('Select Country', 'event_espresso'),
716
+				'QST_system'       => 'admin-country',
717
+			)),
718
+			EE_Answer::new_instance(array(
719
+				'ANS_ID'    => 0,
720
+				'ANS_value' => $CNT_ISO,
721
+			)),
722
+			array(
723
+				'input_id'       => 'country',
724
+				'input_name'     => 'country',
725
+				'input_prefix'   => '',
726
+				'append_qstn_id' => false,
727
+			)
728
+		);
729
+
730
+		add_filter('FHEE__EEH_Form_Fields__label_html', array($this, 'country_form_field_label_wrap'), 10, 2);
731
+		add_filter('FHEE__EEH_Form_Fields__input_html', array($this, 'country_form_field_input__wrap'), 10, 2);
732
+		$this->_template_args['country_details_settings'] = $this->display_country_settings();
733
+		$this->_template_args['country_states_settings']  = $this->display_country_states();
734
+
735
+		$this->_set_add_edit_form_tags('update_country_settings');
736
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
737
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
738
+			GEN_SET_TEMPLATE_PATH . 'countries_settings.template.php',
739
+			$this->_template_args,
740
+			true
741
+		);
742
+		$this->display_admin_page_with_no_sidebar();
743
+	}
744
+
745
+
746
+	/**
747
+	 *        display_country_settings
748
+	 *
749
+	 * @access    public
750
+	 * @param    string $CNT_ISO
751
+	 * @return mixed string | array
752
+	 * @throws DomainException
753
+	 */
754
+	public function display_country_settings($CNT_ISO = '')
755
+	{
756
+
757
+		$CNT_ISO = isset($this->_req_data['country'])
758
+			? strtoupper(sanitize_text_field($this->_req_data['country']))
759
+			: $CNT_ISO;
760
+		if (! $CNT_ISO) {
761
+			return '';
762
+		}
763
+
764
+		// for ajax
765
+		remove_all_filters('FHEE__EEH_Form_Fields__label_html');
766
+		remove_all_filters('FHEE__EEH_Form_Fields__input_html');
767
+		add_filter('FHEE__EEH_Form_Fields__label_html', array($this, 'country_form_field_label_wrap'), 10, 2);
768
+		add_filter('FHEE__EEH_Form_Fields__input_html', array($this, 'country_form_field_input__wrap'), 10, 2);
769
+		$country = EEM_Country::instance()->get_one_by_ID($CNT_ISO);
770
+
771
+		$country_input_types            = array(
772
+			'CNT_active'      => array(
773
+				'type'             => 'RADIO_BTN',
774
+				'input_name'       => 'cntry[' . $CNT_ISO . ']',
775
+				'class'            => '',
776
+				'options'          => $this->_yes_no_values,
777
+				'use_desc_4_label' => true,
778
+			),
779
+			'CNT_ISO'         => array(
780
+				'type'       => 'TEXT',
781
+				'input_name' => 'cntry[' . $CNT_ISO . ']',
782
+				'class'      => 'small-text',
783
+			),
784
+			'CNT_ISO3'        => array(
785
+				'type'       => 'TEXT',
786
+				'input_name' => 'cntry[' . $CNT_ISO . ']',
787
+				'class'      => 'small-text',
788
+			),
789
+			'RGN_ID'          => array(
790
+				'type'       => 'TEXT',
791
+				'input_name' => 'cntry[' . $CNT_ISO . ']',
792
+				'class'      => 'small-text',
793
+			),
794
+			'CNT_name'        => array(
795
+				'type'       => 'TEXT',
796
+				'input_name' => 'cntry[' . $CNT_ISO . ']',
797
+				'class'      => 'regular-text',
798
+			),
799
+			'CNT_cur_code'    => array(
800
+				'type'       => 'TEXT',
801
+				'input_name' => 'cntry[' . $CNT_ISO . ']',
802
+				'class'      => 'small-text',
803
+			),
804
+			'CNT_cur_single'  => array(
805
+				'type'       => 'TEXT',
806
+				'input_name' => 'cntry[' . $CNT_ISO . ']',
807
+				'class'      => 'medium-text',
808
+			),
809
+			'CNT_cur_plural'  => array(
810
+				'type'       => 'TEXT',
811
+				'input_name' => 'cntry[' . $CNT_ISO . ']',
812
+				'class'      => 'medium-text',
813
+			),
814
+			'CNT_cur_sign'    => array(
815
+				'type'         => 'TEXT',
816
+				'input_name'   => 'cntry[' . $CNT_ISO . ']',
817
+				'class'        => 'small-text',
818
+				'htmlentities' => false,
819
+			),
820
+			'CNT_cur_sign_b4' => array(
821
+				'type'             => 'RADIO_BTN',
822
+				'input_name'       => 'cntry[' . $CNT_ISO . ']',
823
+				'class'            => '',
824
+				'options'          => $this->_yes_no_values,
825
+				'use_desc_4_label' => true,
826
+			),
827
+			'CNT_cur_dec_plc' => array(
828
+				'type'       => 'RADIO_BTN',
829
+				'input_name' => 'cntry[' . $CNT_ISO . ']',
830
+				'class'      => '',
831
+				'options'    => array(
832
+					array('id' => 0, 'text' => ''),
833
+					array('id' => 1, 'text' => ''),
834
+					array('id' => 2, 'text' => ''),
835
+					array('id' => 3, 'text' => ''),
836
+				),
837
+			),
838
+			'CNT_cur_dec_mrk' => array(
839
+				'type'             => 'RADIO_BTN',
840
+				'input_name'       => 'cntry[' . $CNT_ISO . ']',
841
+				'class'            => '',
842
+				'options'          => array(
843
+					array(
844
+						'id'   => ',',
845
+						'text' => __(', (comma)', 'event_espresso'),
846
+					),
847
+					array('id' => '.', 'text' => __('. (decimal)', 'event_espresso')),
848
+				),
849
+				'use_desc_4_label' => true,
850
+			),
851
+			'CNT_cur_thsnds'  => array(
852
+				'type'             => 'RADIO_BTN',
853
+				'input_name'       => 'cntry[' . $CNT_ISO . ']',
854
+				'class'            => '',
855
+				'options'          => array(
856
+					array(
857
+						'id'   => ',',
858
+						'text' => __(', (comma)', 'event_espresso'),
859
+					),
860
+					array('id' => '.', 'text' => __('. (decimal)', 'event_espresso')),
861
+				),
862
+				'use_desc_4_label' => true,
863
+			),
864
+			'CNT_tel_code'    => array(
865
+				'type'       => 'TEXT',
866
+				'input_name' => 'cntry[' . $CNT_ISO . ']',
867
+				'class'      => 'small-text',
868
+			),
869
+			'CNT_is_EU'       => array(
870
+				'type'             => 'RADIO_BTN',
871
+				'input_name'       => 'cntry[' . $CNT_ISO . ']',
872
+				'class'            => '',
873
+				'options'          => $this->_yes_no_values,
874
+				'use_desc_4_label' => true,
875
+			),
876
+		);
877
+		$this->_template_args['inputs'] = EE_Question_Form_Input::generate_question_form_inputs_for_object(
878
+			$country,
879
+			$country_input_types
880
+		);
881
+		$country_details_settings       = EEH_Template::display_template(
882
+			GEN_SET_TEMPLATE_PATH . 'country_details_settings.template.php',
883
+			$this->_template_args,
884
+			true
885
+		);
886
+
887
+		if (defined('DOING_AJAX')) {
888
+			$notices = EE_Error::get_notices(false, false, false);
889
+			echo wp_json_encode(array(
890
+				'return_data' => $country_details_settings,
891
+				'success'     => $notices['success'],
892
+				'errors'      => $notices['errors'],
893
+			));
894
+			die();
895
+		} else {
896
+			return $country_details_settings;
897
+		}
898
+	}
899
+
900
+
901
+	/**
902
+	 *        display_country_states
903
+	 *
904
+	 * @access    public
905
+	 * @param    string $CNT_ISO
906
+	 * @return string
907
+	 * @throws DomainException
908
+	 */
909
+	public function display_country_states($CNT_ISO = '')
910
+	{
911
+
912
+		$CNT_ISO = isset($this->_req_data['country']) ? sanitize_text_field($this->_req_data['country']) : $CNT_ISO;
913
+
914
+		if (! $CNT_ISO) {
915
+			return '';
916
+		}
917
+		// for ajax
918
+		remove_all_filters('FHEE__EEH_Form_Fields__label_html');
919
+		remove_all_filters('FHEE__EEH_Form_Fields__input_html');
920
+		add_filter('FHEE__EEH_Form_Fields__label_html', array($this, 'state_form_field_label_wrap'), 10, 2);
921
+		add_filter('FHEE__EEH_Form_Fields__input_html', array($this, 'state_form_field_input__wrap'), 10, 2);
922
+		$states = EEM_State::instance()->get_all_states_for_these_countries(array($CNT_ISO => $CNT_ISO));
923
+
924
+		if ($states) {
925
+			foreach ($states as $STA_ID => $state) {
926
+				if ($state instanceof EE_State) {
927
+					//STA_abbrev 	STA_name 	STA_active
928
+					$state_input_types                                           = array(
929
+						'STA_abbrev' => array(
930
+							'type'       => 'TEXT',
931
+							'input_name' => 'states[' . $STA_ID . ']',
932
+							'class'      => 'mid-text',
933
+						),
934
+						'STA_name'   => array(
935
+							'type'       => 'TEXT',
936
+							'input_name' => 'states[' . $STA_ID . ']',
937
+							'class'      => 'regular-text',
938
+						),
939
+						'STA_active' => array(
940
+							'type'             => 'RADIO_BTN',
941
+							'input_name'       => 'states[' . $STA_ID . ']',
942
+							'options'          => $this->_yes_no_values,
943
+							'use_desc_4_label' => true,
944
+						),
945
+					);
946
+					$this->_template_args['states'][$STA_ID]['inputs'] =
947
+						EE_Question_Form_Input::generate_question_form_inputs_for_object(
948
+							$state,
949
+							$state_input_types
950
+						);
951
+					$query_args                                                  = array(
952
+						'action'     => 'delete_state',
953
+						'STA_ID'     => $STA_ID,
954
+						'CNT_ISO'    => $CNT_ISO,
955
+						'STA_abbrev' => $state->abbrev(),
956
+					);
957
+					$this->_template_args['states'][$STA_ID]['delete_state_url'] =
958
+						EE_Admin_Page::add_query_args_and_nonce(
959
+							$query_args,
960
+							GEN_SET_ADMIN_URL
961
+						);
962
+				}
963
+			}
964
+		} else {
965
+			$this->_template_args['states'] = false;
966
+		}
967
+
968
+		$this->_template_args['add_new_state_url'] = EE_Admin_Page::add_query_args_and_nonce(
969
+			array('action' => 'add_new_state'),
970
+			GEN_SET_ADMIN_URL
971
+		);
972
+
973
+		$state_details_settings = EEH_Template::display_template(
974
+			GEN_SET_TEMPLATE_PATH . 'state_details_settings.template.php',
975
+			$this->_template_args,
976
+			true
977
+		);
978
+
979
+		if (defined('DOING_AJAX')) {
980
+			$notices = EE_Error::get_notices(false, false, false);
981
+			echo wp_json_encode(array(
982
+				'return_data' => $state_details_settings,
983
+				'success'     => $notices['success'],
984
+				'errors'      => $notices['errors'],
985
+			));
986
+			die();
987
+		} else {
988
+			return $state_details_settings;
989
+		}
990
+	}
991
+
992
+
993
+	/**
994
+	 *        add_new_state
995
+	 *
996
+	 * @access    public
997
+	 * @return void
998
+	 * @throws EE_Error
999
+	 */
1000
+	public function add_new_state()
1001
+	{
1002
+
1003
+		$success = true;
1004
+
1005
+		$CNT_ISO = isset($this->_req_data['CNT_ISO'])
1006
+			? strtoupper(sanitize_text_field($this->_req_data['CNT_ISO']))
1007
+			: false;
1008
+		if (! $CNT_ISO) {
1009
+			EE_Error::add_error(
1010
+				__('No Country ISO code or an invalid Country ISO code was received.', 'event_espresso'),
1011
+				__FILE__,
1012
+				__FUNCTION__,
1013
+				__LINE__
1014
+			);
1015
+			$success = false;
1016
+		}
1017
+		$STA_abbrev = isset($this->_req_data['STA_abbrev'])
1018
+			? sanitize_text_field($this->_req_data['STA_abbrev'])
1019
+			: false;
1020
+		if (! $STA_abbrev) {
1021
+			EE_Error::add_error(
1022
+				__('No State ISO code or an invalid State ISO code was received.', 'event_espresso'),
1023
+				__FILE__,
1024
+				__FUNCTION__,
1025
+				__LINE__
1026
+			);
1027
+			$success = false;
1028
+		}
1029
+		$STA_name = isset($this->_req_data['STA_name'])
1030
+			? sanitize_text_field($this->_req_data['STA_name'])
1031
+			: false;
1032
+		if (! $STA_name) {
1033
+			EE_Error::add_error(
1034
+				__('No State name or an invalid State name was received.', 'event_espresso'),
1035
+				__FILE__,
1036
+				__FUNCTION__,
1037
+				__LINE__
1038
+			);
1039
+			$success = false;
1040
+		}
1041
+
1042
+		if ($success) {
1043
+			$cols_n_values = array(
1044
+				'CNT_ISO'    => $CNT_ISO,
1045
+				'STA_abbrev' => $STA_abbrev,
1046
+				'STA_name'   => $STA_name,
1047
+				'STA_active' => true,
1048
+			);
1049
+			$success       = EEM_State::instance()->insert($cols_n_values);
1050
+			EE_Error::add_success(__('The State was added successfully.', 'event_espresso'));
1051
+		}
1052
+
1053
+		if (defined('DOING_AJAX')) {
1054
+			$notices = EE_Error::get_notices(false, false, false);
1055
+			echo wp_json_encode(array_merge($notices, array('return_data' => $CNT_ISO)));
1056
+			die();
1057
+		} else {
1058
+			$this->_redirect_after_action($success, 'State', 'added', array('action' => 'country_settings'));
1059
+		}
1060
+	}
1061
+
1062
+
1063
+	/**
1064
+	 *        delete_state
1065
+	 *
1066
+	 * @access    public
1067
+	 * @return        boolean
1068
+	 */
1069
+	public function delete_state()
1070
+	{
1071
+		$CNT_ISO    = isset($this->_req_data['CNT_ISO'])
1072
+			? strtoupper(sanitize_text_field($this->_req_data['CNT_ISO']))
1073
+			: false;
1074
+		$STA_ID     = isset($this->_req_data['STA_ID'])
1075
+			? sanitize_text_field($this->_req_data['STA_ID'])
1076
+			: false;
1077
+		$STA_abbrev = isset($this->_req_data['STA_abbrev'])
1078
+			? sanitize_text_field($this->_req_data['STA_abbrev'])
1079
+			: false;
1080
+		if (! $STA_ID) {
1081
+			EE_Error::add_error(
1082
+				__('No State ID or an invalid State ID was received.', 'event_espresso'),
1083
+				__FILE__,
1084
+				__FUNCTION__,
1085
+				__LINE__
1086
+			);
1087
+			return false;
1088
+		}
1089
+
1090
+		$success = EEM_State::instance()->delete_by_ID($STA_ID);
1091
+		if ($success !== false) {
1092
+			do_action(
1093
+				'AHEE__General_Settings_Admin_Page__delete_state__state_deleted',
1094
+				$CNT_ISO,
1095
+				$STA_ID,
1096
+				array('STA_abbrev' => $STA_abbrev)
1097
+			);
1098
+			EE_Error::add_success(__('The State was deleted successfully.', 'event_espresso'));
1099
+		}
1100
+		if (defined('DOING_AJAX')) {
1101
+			$notices                = EE_Error::get_notices(false, false);
1102
+			$notices['return_data'] = true;
1103
+			echo wp_json_encode($notices);
1104
+			die();
1105
+		} else {
1106
+			$this->_redirect_after_action(
1107
+				$success,
1108
+				'State',
1109
+				'deleted',
1110
+				array('action' => 'country_settings')
1111
+			);
1112
+		}
1113
+	}
1114
+
1115
+
1116
+	/**
1117
+	 *        _update_country_settings
1118
+	 *
1119
+	 * @access    protected
1120
+	 * @return void
1121
+	 * @throws EE_Error
1122
+	 */
1123
+	protected function _update_country_settings()
1124
+	{
1125
+		// grab the country ISO code
1126
+		$CNT_ISO = isset($this->_req_data['country'])
1127
+			? strtoupper(sanitize_text_field($this->_req_data['country']))
1128
+			: false;
1129
+		if (! $CNT_ISO) {
1130
+			EE_Error::add_error(
1131
+				__('No Country ISO code or an invalid Country ISO code was received.', 'event_espresso'),
1132
+				__FILE__,
1133
+				__FUNCTION__,
1134
+				__LINE__
1135
+			);
1136
+
1137
+			return;
1138
+		}
1139
+		$cols_n_values                    = array();
1140
+		$cols_n_values['CNT_ISO3']        = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_ISO3'])
1141
+			? strtoupper(sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_ISO3']))
1142
+			: false;
1143
+		$cols_n_values['RGN_ID']          = isset($this->_req_data['cntry'][$CNT_ISO]['RGN_ID'])
1144
+			? absint($this->_req_data['cntry'][$CNT_ISO]['RGN_ID'])
1145
+			: null;
1146
+		$cols_n_values['CNT_name']        = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_name'])
1147
+			? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_name'])
1148
+			: null;
1149
+		$cols_n_values['CNT_cur_code']    = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_code'])
1150
+			? strtoupper(sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_code']))
1151
+			: 'USD';
1152
+		$cols_n_values['CNT_cur_single']  = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_single'])
1153
+			? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_single'])
1154
+			: 'dollar';
1155
+		$cols_n_values['CNT_cur_plural']  = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_plural'])
1156
+			? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_plural'])
1157
+			: 'dollars';
1158
+		$cols_n_values['CNT_cur_sign']    = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_sign'])
1159
+			? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_sign'])
1160
+			: '$';
1161
+		$cols_n_values['CNT_cur_sign_b4'] = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_sign_b4'])
1162
+			? absint($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_sign_b4'])
1163
+			: true;
1164
+		$cols_n_values['CNT_cur_dec_plc'] = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_dec_plc'])
1165
+			? absint($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_dec_plc'])
1166
+			: 2;
1167
+		$cols_n_values['CNT_cur_dec_mrk'] = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_dec_mrk'])
1168
+			? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_dec_mrk'])
1169
+			: '.';
1170
+		$cols_n_values['CNT_cur_thsnds']  = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_thsnds'])
1171
+			? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_thsnds'])
1172
+			: ',';
1173
+		$cols_n_values['CNT_tel_code']    = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_tel_code'])
1174
+			? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_tel_code'])
1175
+			: null;
1176
+		$cols_n_values['CNT_is_EU']       = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_is_EU'])
1177
+			? absint($this->_req_data['cntry'][$CNT_ISO]['CNT_is_EU'])
1178
+			: false;
1179
+		$cols_n_values['CNT_active']      = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_active'])
1180
+			? absint($this->_req_data['cntry'][$CNT_ISO]['CNT_active'])
1181
+			: false;
1182
+		// allow filtering of country data
1183
+		$cols_n_values = apply_filters(
1184
+			'FHEE__General_Settings_Admin_Page___update_country_settings__cols_n_values',
1185
+			$cols_n_values
1186
+		);
1187
+
1188
+		// where values
1189
+		$where_cols_n_values = array(array('CNT_ISO' => $CNT_ISO));
1190
+		// run the update
1191
+		$success = EEM_Country::instance()->update($cols_n_values, $where_cols_n_values);
1192
+
1193
+		if (isset($this->_req_data['states']) && is_array($this->_req_data['states']) && $success !== false) {
1194
+			// allow filtering of states data
1195
+			$states = apply_filters(
1196
+				'FHEE__General_Settings_Admin_Page___update_country_settings__states',
1197
+				$this->_req_data['states']
1198
+			);
1199
+
1200
+			// loop thru state data ( looks like : states[75][STA_name] )
1201
+			foreach ($states as $STA_ID => $state) {
1202
+				$cols_n_values = array(
1203
+					'CNT_ISO'    => $CNT_ISO,
1204
+					'STA_abbrev' => sanitize_text_field($state['STA_abbrev']),
1205
+					'STA_name'   => sanitize_text_field($state['STA_name']),
1206
+					'STA_active' => (bool)absint($state['STA_active']),
1207
+				);
1208
+				// where values
1209
+				$where_cols_n_values = array(array('STA_ID' => $STA_ID));
1210
+				// run the update
1211
+				$success = EEM_State::instance()->update($cols_n_values, $where_cols_n_values);
1212
+				if ($success !== false) {
1213
+					do_action(
1214
+						'AHEE__General_Settings_Admin_Page__update_country_settings__state_saved',
1215
+						$CNT_ISO,
1216
+						$STA_ID,
1217
+						$cols_n_values
1218
+					);
1219
+				}
1220
+			}
1221
+		}
1222
+		// check if country being edited matches org option country, and if so, then  update EE_Config with new settings
1223
+		if (isset(EE_Registry::instance()->CFG->organization->CNT_ISO)
1224
+			&& $CNT_ISO == EE_Registry::instance()->CFG->organization->CNT_ISO
1225
+		) {
1226
+			EE_Registry::instance()->CFG->currency = new EE_Currency_Config($CNT_ISO);
1227
+			EE_Registry::instance()->CFG->update_espresso_config();
1228
+		}
1229
+
1230
+		if ($success !== false) {
1231
+			EE_Error::add_success(
1232
+				esc_html__('Country Settings updated successfully.', 'event_espresso')
1233
+			);
1234
+		}
1235
+		$this->_redirect_after_action(
1236
+			$success,
1237
+			'',
1238
+			'',
1239
+			array('action' => 'country_settings', 'country' => $CNT_ISO),
1240
+			true
1241
+		);
1242
+	}
1243
+
1244
+
1245
+	/**
1246
+	 *        form_form_field_label_wrap
1247
+	 *
1248
+	 * @access        public
1249
+	 * @param        string $label
1250
+	 * @return        string
1251
+	 */
1252
+	public function country_form_field_label_wrap($label, $required_text)
1253
+	{
1254
+		return '
1255 1255
 			<tr>
1256 1256
 				<th>
1257 1257
 					' . $label . '
1258 1258
 				</th>';
1259
-    }
1260
-
1261
-
1262
-    /**
1263
-     *        form_form_field_input__wrap
1264
-     *
1265
-     * @access        public
1266
-     * @param        string $label
1267
-     * @return        string
1268
-     */
1269
-    public function country_form_field_input__wrap($input, $label)
1270
-    {
1271
-        return '
1259
+	}
1260
+
1261
+
1262
+	/**
1263
+	 *        form_form_field_input__wrap
1264
+	 *
1265
+	 * @access        public
1266
+	 * @param        string $label
1267
+	 * @return        string
1268
+	 */
1269
+	public function country_form_field_input__wrap($input, $label)
1270
+	{
1271
+		return '
1272 1272
 				<td class="general-settings-country-input-td">
1273 1273
 					' . $input . '
1274 1274
 				</td>
1275 1275
 			</tr>';
1276
-    }
1277
-
1278
-
1279
-    /**
1280
-     *        form_form_field_label_wrap
1281
-     *
1282
-     * @access        public
1283
-     * @param        string $label
1284
-     * @param        string $required_text
1285
-     * @return        string
1286
-     */
1287
-    public function state_form_field_label_wrap($label, $required_text)
1288
-    {
1289
-        return $required_text;
1290
-    }
1291
-
1292
-
1293
-    /**
1294
-     *        form_form_field_input__wrap
1295
-     *
1296
-     * @access        public
1297
-     * @param        string $label
1298
-     * @return        string
1299
-     */
1300
-    public function state_form_field_input__wrap($input, $label)
1301
-    {
1302
-        return '
1276
+	}
1277
+
1278
+
1279
+	/**
1280
+	 *        form_form_field_label_wrap
1281
+	 *
1282
+	 * @access        public
1283
+	 * @param        string $label
1284
+	 * @param        string $required_text
1285
+	 * @return        string
1286
+	 */
1287
+	public function state_form_field_label_wrap($label, $required_text)
1288
+	{
1289
+		return $required_text;
1290
+	}
1291
+
1292
+
1293
+	/**
1294
+	 *        form_form_field_input__wrap
1295
+	 *
1296
+	 * @access        public
1297
+	 * @param        string $label
1298
+	 * @return        string
1299
+	 */
1300
+	public function state_form_field_input__wrap($input, $label)
1301
+	{
1302
+		return '
1303 1303
 				<td class="general-settings-country-state-input-td">
1304 1304
 					' . $input . '
1305 1305
 				</td>';
1306
-    }
1307
-
1308
-
1309
-    /***********/
1310
-
1311
-
1312
-    /**
1313
-     * displays edit and view links for critical EE pages
1314
-     *
1315
-     * @access public
1316
-     * @param int $ee_page_id
1317
-     * @return string
1318
-     */
1319
-    public static function edit_view_links($ee_page_id)
1320
-    {
1321
-        $links = '<a href="'
1322
-                 . add_query_arg(
1323
-                     array('post' => $ee_page_id, 'action' => 'edit'),
1324
-                     admin_url('post.php')
1325
-                 )
1326
-                 . '" >'
1327
-                 . __('Edit', 'event_espresso')
1328
-                 . '</a>';
1329
-        $links .= ' &nbsp;|&nbsp; ';
1330
-        $links .= '<a href="' . get_permalink($ee_page_id) . '" >' . __('View', 'event_espresso') . '</a>';
1331
-
1332
-        return $links;
1333
-    }
1334
-
1335
-
1336
-    /**
1337
-     * displays page and shortcode status for critical EE pages
1338
-     *
1339
-     * @param WP page object $ee_page
1340
-     * @return string
1341
-     */
1342
-    public static function page_and_shortcode_status($ee_page, $shortcode)
1343
-    {
1344
-
1345
-        // page status
1346
-        if (isset($ee_page->post_status) && $ee_page->post_status == 'publish') {
1347
-            $pg_colour = 'green';
1348
-            $pg_status = sprintf(__('Page%sStatus%sOK', 'event_espresso'), '&nbsp;', '&nbsp;');
1349
-        } else {
1350
-            $pg_colour = 'red';
1351
-            $pg_status = sprintf(__('Page%sVisibility%sProblem', 'event_espresso'), '&nbsp;', '&nbsp;');
1352
-        }
1353
-
1354
-        // shortcode status
1355
-        if (isset($ee_page->post_content) && strpos($ee_page->post_content, $shortcode) !== false) {
1356
-            $sc_colour = 'green';
1357
-            $sc_status = sprintf(__('Shortcode%sOK', 'event_espresso'), '&nbsp;');
1358
-        } else {
1359
-            $sc_colour = 'red';
1360
-            $sc_status = sprintf(__('Shortcode%sProblem', 'event_espresso'), '&nbsp;');
1361
-        }
1362
-
1363
-        return '<span style="color:' . $pg_colour . '; margin-right:2em;"><strong>'
1364
-               . $pg_status
1365
-               . '</strong></span><span style="color:' . $sc_colour . '"><strong>' . $sc_status . '</strong></span>';
1366
-    }
1367
-
1368
-
1369
-    /**
1370
-     * generates a dropdown of all parent pages - copied from WP core
1371
-     *
1372
-     * @param int $default
1373
-     * @param int $parent
1374
-     * @param int $level
1375
-     */
1376
-    public static function page_settings_dropdown($default = 0, $parent = 0, $level = 0)
1377
-    {
1378
-        global $wpdb;
1379
-        $items = $wpdb->get_results(
1380
-            $wpdb->prepare(
1381
-                "SELECT ID, post_parent, post_title FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'page' AND post_status != 'trash' ORDER BY menu_order",
1382
-                $parent
1383
-            )
1384
-        );
1385
-
1386
-        if ($items) {
1387
-            foreach ($items as $item) {
1388
-                $pad = str_repeat('&nbsp;', $level * 3);
1389
-                if ($item->ID == $default) {
1390
-                    $current = ' selected="selected"';
1391
-                } else {
1392
-                    $current = '';
1393
-                }
1394
-
1395
-                echo "\n\t<option class='level-$level' value='$item->ID'$current>$pad "
1396
-                     . esc_html($item->post_title)
1397
-                     . "</option>";
1398
-                parent_dropdown($default, $item->ID, $level + 1);
1399
-            }
1400
-        }
1401
-    }
1306
+	}
1307
+
1308
+
1309
+	/***********/
1310
+
1311
+
1312
+	/**
1313
+	 * displays edit and view links for critical EE pages
1314
+	 *
1315
+	 * @access public
1316
+	 * @param int $ee_page_id
1317
+	 * @return string
1318
+	 */
1319
+	public static function edit_view_links($ee_page_id)
1320
+	{
1321
+		$links = '<a href="'
1322
+				 . add_query_arg(
1323
+					 array('post' => $ee_page_id, 'action' => 'edit'),
1324
+					 admin_url('post.php')
1325
+				 )
1326
+				 . '" >'
1327
+				 . __('Edit', 'event_espresso')
1328
+				 . '</a>';
1329
+		$links .= ' &nbsp;|&nbsp; ';
1330
+		$links .= '<a href="' . get_permalink($ee_page_id) . '" >' . __('View', 'event_espresso') . '</a>';
1331
+
1332
+		return $links;
1333
+	}
1334
+
1335
+
1336
+	/**
1337
+	 * displays page and shortcode status for critical EE pages
1338
+	 *
1339
+	 * @param WP page object $ee_page
1340
+	 * @return string
1341
+	 */
1342
+	public static function page_and_shortcode_status($ee_page, $shortcode)
1343
+	{
1344
+
1345
+		// page status
1346
+		if (isset($ee_page->post_status) && $ee_page->post_status == 'publish') {
1347
+			$pg_colour = 'green';
1348
+			$pg_status = sprintf(__('Page%sStatus%sOK', 'event_espresso'), '&nbsp;', '&nbsp;');
1349
+		} else {
1350
+			$pg_colour = 'red';
1351
+			$pg_status = sprintf(__('Page%sVisibility%sProblem', 'event_espresso'), '&nbsp;', '&nbsp;');
1352
+		}
1353
+
1354
+		// shortcode status
1355
+		if (isset($ee_page->post_content) && strpos($ee_page->post_content, $shortcode) !== false) {
1356
+			$sc_colour = 'green';
1357
+			$sc_status = sprintf(__('Shortcode%sOK', 'event_espresso'), '&nbsp;');
1358
+		} else {
1359
+			$sc_colour = 'red';
1360
+			$sc_status = sprintf(__('Shortcode%sProblem', 'event_espresso'), '&nbsp;');
1361
+		}
1362
+
1363
+		return '<span style="color:' . $pg_colour . '; margin-right:2em;"><strong>'
1364
+			   . $pg_status
1365
+			   . '</strong></span><span style="color:' . $sc_colour . '"><strong>' . $sc_status . '</strong></span>';
1366
+	}
1367
+
1368
+
1369
+	/**
1370
+	 * generates a dropdown of all parent pages - copied from WP core
1371
+	 *
1372
+	 * @param int $default
1373
+	 * @param int $parent
1374
+	 * @param int $level
1375
+	 */
1376
+	public static function page_settings_dropdown($default = 0, $parent = 0, $level = 0)
1377
+	{
1378
+		global $wpdb;
1379
+		$items = $wpdb->get_results(
1380
+			$wpdb->prepare(
1381
+				"SELECT ID, post_parent, post_title FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'page' AND post_status != 'trash' ORDER BY menu_order",
1382
+				$parent
1383
+			)
1384
+		);
1385
+
1386
+		if ($items) {
1387
+			foreach ($items as $item) {
1388
+				$pad = str_repeat('&nbsp;', $level * 3);
1389
+				if ($item->ID == $default) {
1390
+					$current = ' selected="selected"';
1391
+				} else {
1392
+					$current = '';
1393
+				}
1394
+
1395
+				echo "\n\t<option class='level-$level' value='$item->ID'$current>$pad "
1396
+					 . esc_html($item->post_title)
1397
+					 . "</option>";
1398
+				parent_dropdown($default, $item->ID, $level + 1);
1399
+			}
1400
+		}
1401
+	}
1402 1402
 }
Please login to merge, or discard this patch.
core/services/Benchmark.php 2 patches
Indentation   +328 added lines, -328 removed lines patch added patch discarded remove patch
@@ -20,334 +20,334 @@
 block discarded – undo
20 20
 class Benchmark
21 21
 {
22 22
 
23
-    /**
24
-     * @var string $output
25
-     */
26
-    private static $output;
27
-
28
-    /**
29
-     * @var array $start_times array containing the start time for the timers
30
-     */
31
-    private static $start_times;
32
-
33
-    /**
34
-     * @var array $times array containing all the timer'd times, which can be outputted via show_times()
35
-     */
36
-    private static $times = array();
37
-
38
-    /**
39
-     * @var array $memory_usage
40
-     */
41
-    protected static $memory_usage = array();
42
-
43
-
44
-    /**
45
-     * @param string $output
46
-     * @param bool   $formatted
47
-     */
48
-    public static function addOutput($output, $formatted = true)
49
-    {
50
-        Benchmark::$output .= $formatted
51
-            ? "<br />{$output}"
52
-            : "\n{$output}";
53
-    }
54
-
55
-
56
-    /**
57
-     * @return void
58
-     */
59
-    public static function resetOutput()
60
-    {
61
-        Benchmark::$output = '';
62
-    }
63
-
64
-    /**
65
-     * whether to benchmark code or not
66
-     */
67
-    public static function doNotRun()
68
-    {
69
-        return ! WP_DEBUG || (defined('DOING_AJAX') && DOING_AJAX);
70
-    }
71
-
72
-
73
-
74
-    /**
75
-     * resetTimes
76
-     */
77
-    public static function resetTimes()
78
-    {
79
-        Benchmark::$times = array();
80
-    }
81
-
82
-
83
-
84
-    /**
85
-     * Add Benchmark::startTimer() before a block of code you want to measure the performance of
86
-     *
87
-     * @param null $timer_name
88
-     */
89
-    public static function startTimer($timer_name = null)
90
-    {
91
-        if (Benchmark::doNotRun()) {
92
-            return;
93
-        }
94
-        $timer_name = $timer_name !== '' ? $timer_name : get_called_class();
95
-        Benchmark::$start_times[$timer_name] = microtime(true);
96
-    }
97
-
98
-
99
-
100
-    /**
101
-     * Add Benchmark::stopTimer() after a block of code you want to measure the performance of
102
-     *
103
-     * @param string $timer_name
104
-     */
105
-    public static function stopTimer($timer_name = '')
106
-    {
107
-        if (Benchmark::doNotRun()) {
108
-            return;
109
-        }
110
-        $timer_name = $timer_name !== '' ? $timer_name : get_called_class();
111
-        if (isset(Benchmark::$start_times[$timer_name])) {
112
-            $start_time = Benchmark::$start_times[$timer_name];
113
-            unset(Benchmark::$start_times[$timer_name]);
114
-        } else {
115
-            $start_time = array_pop(Benchmark::$start_times);
116
-        }
117
-        Benchmark::$times[$timer_name] = number_format(microtime(true) - $start_time, 8);
118
-    }
119
-
120
-
121
-
122
-    /**
123
-     * Measure the memory usage by PHP so far.
124
-     *
125
-     * @param string  $label      The label to show for this time eg "Start of calling Some_Class::some_function"
126
-     * @param boolean $output_now whether to echo now, or wait until EEH_Debug_Tools::show_times() is called
127
-     * @param bool    $formatted
128
-     * @return void
129
-     */
130
-    public static function measureMemory($label = 'memory usage', $output_now = false, $formatted = true)
131
-    {
132
-        if (Benchmark::doNotRun()) {
133
-            return;
134
-        }
135
-        $memory_used = Benchmark::convert(memory_get_usage(true));
136
-        Benchmark::$memory_usage[$label] = $memory_used;
137
-        if ($output_now) {
138
-            echo $formatted
139
-                ? "<br>{$label} : {$memory_used}"
140
-                : "\n {$label} : {$memory_used}";
141
-        }
142
-    }
143
-
144
-
145
-
146
-    /**
147
-     * will display the benchmarking results at shutdown
148
-     *
149
-     * @param bool $formatted
150
-     * @return void
151
-     */
152
-    public static function displayResultsAtShutdown($formatted = true)
153
-    {
154
-        Benchmark::resetOutput();
155
-        add_action(
156
-            'shutdown',
157
-            function () use ($formatted) {
158
-                Benchmark::displayResults(true, $formatted);
159
-            }
160
-        );
161
-    }
162
-
163
-
164
-
165
-    /**
166
-     * will display the benchmarking results at shutdown
167
-     *
168
-     * @param string $filepath
169
-     * @param bool   $formatted
170
-     * @param bool   $append
171
-     * @return void
172
-     */
173
-    public static function writeResultsAtShutdown($filepath = '', $formatted = true, $append = true)
174
-    {
175
-        Benchmark::resetOutput();
176
-        add_action(
177
-            'shutdown',
178
-            function () use ($filepath, $formatted, $append) {
179
-                Benchmark::writeResultsToFile($filepath, $formatted, $append);
180
-            }
181
-        );
182
-    }
183
-
184
-
185
-
186
-    /**
187
-     * @param bool $formatted
188
-     * @return string
189
-     */
190
-    private static function generateResults($formatted = true)
191
-    {
192
-        if (Benchmark::doNotRun()) {
193
-            return '';
194
-        }
195
-        if (! empty(Benchmark::$times)) {
196
-            $total = 0;
197
-            Benchmark::$output .= $formatted
198
-                ? '<span style="color:#999999; font-size:.8em;">( time in milliseconds )</span><br />'
199
-                : '';
200
-            foreach (Benchmark::$times as $timer_name => $total_time) {
201
-                Benchmark::$output .= Benchmark::formatTime($timer_name, $total_time, $formatted);
202
-                Benchmark::$output .= $formatted ? '<br />'  : "\n";
203
-                $total += $total_time;
204
-            }
205
-            if($formatted) {
206
-                Benchmark::$output .= '<br />';
207
-                Benchmark::$output .= '<h4>TOTAL TIME</h4>';
208
-                Benchmark::$output .= Benchmark::formatTime('', $total, $formatted);
209
-                Benchmark::$output .= '<span style="color:#999999; font-size:.8em;"> milliseconds</span><br />';
210
-                Benchmark::$output .= '<br />';
211
-                Benchmark::$output .= '<h5>Performance scale (from best to worse)</h5>';
212
-                Benchmark::$output .= '<span style="color:mediumpurple">Like wow! How about a Scooby snack?</span><br />';
213
-                Benchmark::$output .= '<span style="color:deepskyblue">Like...no way man!</span><br />';
214
-                Benchmark::$output .= '<span style="color:limegreen">Like...groovy!</span><br />';
215
-                Benchmark::$output .= '<span style="color:gold">Ruh Oh</span><br />';
216
-                Benchmark::$output .= '<span style="color:darkorange">Zoinks!</span><br />';
217
-                Benchmark::$output .= '<span style="color:red">Like...HEEELLLP</span><br />';
218
-            }
219
-        }
220
-        if (! empty(Benchmark::$memory_usage)) {
221
-            Benchmark::$output .= $formatted
222
-                ? '<h5>Memory</h5>'
223
-                : "\nMemory";
224
-            foreach (Benchmark::$memory_usage as $label => $memory_usage) {
225
-                Benchmark::$output .= $formatted
226
-                    ? "<br />{$memory_usage} : {$label}"
227
-                    : "\n{$memory_usage} : {$label}";
228
-            }
229
-        }
230
-        if (empty(Benchmark::$output)) {
231
-            return '';
232
-        }
233
-        Benchmark::$output = $formatted
234
-            ? '<div style="border:1px solid #dddddd; background-color:#ffffff;'
235
-              . (is_admin()
236
-                ? ' margin:2em 2em 2em 180px;'
237
-                : ' margin:2em;')
238
-              . ' padding:2em;">'
239
-              . '<h4>BENCHMARKING</h4>'
240
-              . Benchmark::$output
241
-              . '</div>'
242
-            : Benchmark::$output;
243
-        return Benchmark::$output;
244
-    }
245
-
246
-
247
-
248
-    /**
249
-     * @param bool $echo
250
-     * @param bool $formatted
251
-     * @return string
252
-     */
253
-    public static function displayResults($echo = true, $formatted = true)
254
-    {
255
-        $results = Benchmark::generateResults($formatted);
256
-        if ($echo) {
257
-            echo $results;
258
-            $results = '';
259
-        }
260
-        return $results;
261
-    }
262
-
263
-
264
-    /**
265
-     * @param string $filepath
266
-     * @param bool   $formatted
267
-     * @param bool   $append
268
-     * @throws EE_Error
269
-     */
270
-    public static function writeResultsToFile($filepath = '', $formatted = true, $append = true)
271
-    {
272
-        $filepath = ! empty($filepath) && is_readable(dirname($filepath))
273
-            ? $filepath
274
-            : '';
275
-        if( empty($filepath)) {
276
-            $filepath = EVENT_ESPRESSO_UPLOAD_DIR . 'logs/benchmarking-' . date('Y-m-d') . '.html';
277
-        }
278
-        EEH_File::ensure_file_exists_and_is_writable($filepath);
279
-        file_put_contents(
280
-            $filepath,
281
-            "\n" . date('Y-m-d H:i:s') . Benchmark::generateResults($formatted),
282
-            $append ? FILE_APPEND | LOCK_EX : LOCK_EX
283
-        );
284
-    }
285
-
286
-
287
-
288
-    /**
289
-     * Converts a measure of memory bytes into the most logical units (eg kb, mb, etc)
290
-     *
291
-     * @param int $size
292
-     * @return string
293
-     */
294
-    public static function convert($size)
295
-    {
296
-        $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
297
-        return round(
298
-            $size / pow(1024, $i = floor(log($size, 1024))),
299
-            2
300
-        ) . ' ' . $unit[absint($i)];
301
-    }
302
-
303
-
304
-
305
-    /**
306
-     * @param string $timer_name
307
-     * @param float  $total_time
308
-     * @param bool   $formatted
309
-     * @return string
310
-     */
311
-    public static function formatTime($timer_name, $total_time, $formatted = true)
312
-    {
313
-        $total_time *= 1000;
314
-        switch ($total_time) {
315
-            case $total_time > 12500 :
316
-                $color = 'red';
317
-                $bold = 'bold';
318
-                break;
319
-            case $total_time > 2500 :
320
-                $color = 'darkorange';
321
-                $bold = 'bold';
322
-                break;
323
-            case $total_time > 500 :
324
-                $color = 'gold';
325
-                $bold = 'bold';
326
-                break;
327
-            case $total_time > 100 :
328
-                $color = 'limegreen';
329
-                $bold = 'normal';
330
-                break;
331
-            case $total_time > 20 :
332
-                $color = 'deepskyblue';
333
-                $bold = 'normal';
334
-                break;
335
-            default :
336
-                $color = 'mediumpurple';
337
-                $bold = 'normal';
338
-                break;
339
-        }
340
-        return $formatted
341
-            ? '<span style="min-width: 10px; margin:0 1em; color:'
342
-               . $color
343
-               . '; font-weight:'
344
-               . $bold
345
-               . '; font-size:1.2em;">'
346
-               . str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT)
347
-               . '</span> '
348
-               . $timer_name
349
-            :  str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT);
350
-    }
23
+	/**
24
+	 * @var string $output
25
+	 */
26
+	private static $output;
27
+
28
+	/**
29
+	 * @var array $start_times array containing the start time for the timers
30
+	 */
31
+	private static $start_times;
32
+
33
+	/**
34
+	 * @var array $times array containing all the timer'd times, which can be outputted via show_times()
35
+	 */
36
+	private static $times = array();
37
+
38
+	/**
39
+	 * @var array $memory_usage
40
+	 */
41
+	protected static $memory_usage = array();
42
+
43
+
44
+	/**
45
+	 * @param string $output
46
+	 * @param bool   $formatted
47
+	 */
48
+	public static function addOutput($output, $formatted = true)
49
+	{
50
+		Benchmark::$output .= $formatted
51
+			? "<br />{$output}"
52
+			: "\n{$output}";
53
+	}
54
+
55
+
56
+	/**
57
+	 * @return void
58
+	 */
59
+	public static function resetOutput()
60
+	{
61
+		Benchmark::$output = '';
62
+	}
63
+
64
+	/**
65
+	 * whether to benchmark code or not
66
+	 */
67
+	public static function doNotRun()
68
+	{
69
+		return ! WP_DEBUG || (defined('DOING_AJAX') && DOING_AJAX);
70
+	}
71
+
72
+
73
+
74
+	/**
75
+	 * resetTimes
76
+	 */
77
+	public static function resetTimes()
78
+	{
79
+		Benchmark::$times = array();
80
+	}
81
+
82
+
83
+
84
+	/**
85
+	 * Add Benchmark::startTimer() before a block of code you want to measure the performance of
86
+	 *
87
+	 * @param null $timer_name
88
+	 */
89
+	public static function startTimer($timer_name = null)
90
+	{
91
+		if (Benchmark::doNotRun()) {
92
+			return;
93
+		}
94
+		$timer_name = $timer_name !== '' ? $timer_name : get_called_class();
95
+		Benchmark::$start_times[$timer_name] = microtime(true);
96
+	}
97
+
98
+
99
+
100
+	/**
101
+	 * Add Benchmark::stopTimer() after a block of code you want to measure the performance of
102
+	 *
103
+	 * @param string $timer_name
104
+	 */
105
+	public static function stopTimer($timer_name = '')
106
+	{
107
+		if (Benchmark::doNotRun()) {
108
+			return;
109
+		}
110
+		$timer_name = $timer_name !== '' ? $timer_name : get_called_class();
111
+		if (isset(Benchmark::$start_times[$timer_name])) {
112
+			$start_time = Benchmark::$start_times[$timer_name];
113
+			unset(Benchmark::$start_times[$timer_name]);
114
+		} else {
115
+			$start_time = array_pop(Benchmark::$start_times);
116
+		}
117
+		Benchmark::$times[$timer_name] = number_format(microtime(true) - $start_time, 8);
118
+	}
119
+
120
+
121
+
122
+	/**
123
+	 * Measure the memory usage by PHP so far.
124
+	 *
125
+	 * @param string  $label      The label to show for this time eg "Start of calling Some_Class::some_function"
126
+	 * @param boolean $output_now whether to echo now, or wait until EEH_Debug_Tools::show_times() is called
127
+	 * @param bool    $formatted
128
+	 * @return void
129
+	 */
130
+	public static function measureMemory($label = 'memory usage', $output_now = false, $formatted = true)
131
+	{
132
+		if (Benchmark::doNotRun()) {
133
+			return;
134
+		}
135
+		$memory_used = Benchmark::convert(memory_get_usage(true));
136
+		Benchmark::$memory_usage[$label] = $memory_used;
137
+		if ($output_now) {
138
+			echo $formatted
139
+				? "<br>{$label} : {$memory_used}"
140
+				: "\n {$label} : {$memory_used}";
141
+		}
142
+	}
143
+
144
+
145
+
146
+	/**
147
+	 * will display the benchmarking results at shutdown
148
+	 *
149
+	 * @param bool $formatted
150
+	 * @return void
151
+	 */
152
+	public static function displayResultsAtShutdown($formatted = true)
153
+	{
154
+		Benchmark::resetOutput();
155
+		add_action(
156
+			'shutdown',
157
+			function () use ($formatted) {
158
+				Benchmark::displayResults(true, $formatted);
159
+			}
160
+		);
161
+	}
162
+
163
+
164
+
165
+	/**
166
+	 * will display the benchmarking results at shutdown
167
+	 *
168
+	 * @param string $filepath
169
+	 * @param bool   $formatted
170
+	 * @param bool   $append
171
+	 * @return void
172
+	 */
173
+	public static function writeResultsAtShutdown($filepath = '', $formatted = true, $append = true)
174
+	{
175
+		Benchmark::resetOutput();
176
+		add_action(
177
+			'shutdown',
178
+			function () use ($filepath, $formatted, $append) {
179
+				Benchmark::writeResultsToFile($filepath, $formatted, $append);
180
+			}
181
+		);
182
+	}
183
+
184
+
185
+
186
+	/**
187
+	 * @param bool $formatted
188
+	 * @return string
189
+	 */
190
+	private static function generateResults($formatted = true)
191
+	{
192
+		if (Benchmark::doNotRun()) {
193
+			return '';
194
+		}
195
+		if (! empty(Benchmark::$times)) {
196
+			$total = 0;
197
+			Benchmark::$output .= $formatted
198
+				? '<span style="color:#999999; font-size:.8em;">( time in milliseconds )</span><br />'
199
+				: '';
200
+			foreach (Benchmark::$times as $timer_name => $total_time) {
201
+				Benchmark::$output .= Benchmark::formatTime($timer_name, $total_time, $formatted);
202
+				Benchmark::$output .= $formatted ? '<br />'  : "\n";
203
+				$total += $total_time;
204
+			}
205
+			if($formatted) {
206
+				Benchmark::$output .= '<br />';
207
+				Benchmark::$output .= '<h4>TOTAL TIME</h4>';
208
+				Benchmark::$output .= Benchmark::formatTime('', $total, $formatted);
209
+				Benchmark::$output .= '<span style="color:#999999; font-size:.8em;"> milliseconds</span><br />';
210
+				Benchmark::$output .= '<br />';
211
+				Benchmark::$output .= '<h5>Performance scale (from best to worse)</h5>';
212
+				Benchmark::$output .= '<span style="color:mediumpurple">Like wow! How about a Scooby snack?</span><br />';
213
+				Benchmark::$output .= '<span style="color:deepskyblue">Like...no way man!</span><br />';
214
+				Benchmark::$output .= '<span style="color:limegreen">Like...groovy!</span><br />';
215
+				Benchmark::$output .= '<span style="color:gold">Ruh Oh</span><br />';
216
+				Benchmark::$output .= '<span style="color:darkorange">Zoinks!</span><br />';
217
+				Benchmark::$output .= '<span style="color:red">Like...HEEELLLP</span><br />';
218
+			}
219
+		}
220
+		if (! empty(Benchmark::$memory_usage)) {
221
+			Benchmark::$output .= $formatted
222
+				? '<h5>Memory</h5>'
223
+				: "\nMemory";
224
+			foreach (Benchmark::$memory_usage as $label => $memory_usage) {
225
+				Benchmark::$output .= $formatted
226
+					? "<br />{$memory_usage} : {$label}"
227
+					: "\n{$memory_usage} : {$label}";
228
+			}
229
+		}
230
+		if (empty(Benchmark::$output)) {
231
+			return '';
232
+		}
233
+		Benchmark::$output = $formatted
234
+			? '<div style="border:1px solid #dddddd; background-color:#ffffff;'
235
+			  . (is_admin()
236
+				? ' margin:2em 2em 2em 180px;'
237
+				: ' margin:2em;')
238
+			  . ' padding:2em;">'
239
+			  . '<h4>BENCHMARKING</h4>'
240
+			  . Benchmark::$output
241
+			  . '</div>'
242
+			: Benchmark::$output;
243
+		return Benchmark::$output;
244
+	}
245
+
246
+
247
+
248
+	/**
249
+	 * @param bool $echo
250
+	 * @param bool $formatted
251
+	 * @return string
252
+	 */
253
+	public static function displayResults($echo = true, $formatted = true)
254
+	{
255
+		$results = Benchmark::generateResults($formatted);
256
+		if ($echo) {
257
+			echo $results;
258
+			$results = '';
259
+		}
260
+		return $results;
261
+	}
262
+
263
+
264
+	/**
265
+	 * @param string $filepath
266
+	 * @param bool   $formatted
267
+	 * @param bool   $append
268
+	 * @throws EE_Error
269
+	 */
270
+	public static function writeResultsToFile($filepath = '', $formatted = true, $append = true)
271
+	{
272
+		$filepath = ! empty($filepath) && is_readable(dirname($filepath))
273
+			? $filepath
274
+			: '';
275
+		if( empty($filepath)) {
276
+			$filepath = EVENT_ESPRESSO_UPLOAD_DIR . 'logs/benchmarking-' . date('Y-m-d') . '.html';
277
+		}
278
+		EEH_File::ensure_file_exists_and_is_writable($filepath);
279
+		file_put_contents(
280
+			$filepath,
281
+			"\n" . date('Y-m-d H:i:s') . Benchmark::generateResults($formatted),
282
+			$append ? FILE_APPEND | LOCK_EX : LOCK_EX
283
+		);
284
+	}
285
+
286
+
287
+
288
+	/**
289
+	 * Converts a measure of memory bytes into the most logical units (eg kb, mb, etc)
290
+	 *
291
+	 * @param int $size
292
+	 * @return string
293
+	 */
294
+	public static function convert($size)
295
+	{
296
+		$unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
297
+		return round(
298
+			$size / pow(1024, $i = floor(log($size, 1024))),
299
+			2
300
+		) . ' ' . $unit[absint($i)];
301
+	}
302
+
303
+
304
+
305
+	/**
306
+	 * @param string $timer_name
307
+	 * @param float  $total_time
308
+	 * @param bool   $formatted
309
+	 * @return string
310
+	 */
311
+	public static function formatTime($timer_name, $total_time, $formatted = true)
312
+	{
313
+		$total_time *= 1000;
314
+		switch ($total_time) {
315
+			case $total_time > 12500 :
316
+				$color = 'red';
317
+				$bold = 'bold';
318
+				break;
319
+			case $total_time > 2500 :
320
+				$color = 'darkorange';
321
+				$bold = 'bold';
322
+				break;
323
+			case $total_time > 500 :
324
+				$color = 'gold';
325
+				$bold = 'bold';
326
+				break;
327
+			case $total_time > 100 :
328
+				$color = 'limegreen';
329
+				$bold = 'normal';
330
+				break;
331
+			case $total_time > 20 :
332
+				$color = 'deepskyblue';
333
+				$bold = 'normal';
334
+				break;
335
+			default :
336
+				$color = 'mediumpurple';
337
+				$bold = 'normal';
338
+				break;
339
+		}
340
+		return $formatted
341
+			? '<span style="min-width: 10px; margin:0 1em; color:'
342
+			   . $color
343
+			   . '; font-weight:'
344
+			   . $bold
345
+			   . '; font-size:1.2em;">'
346
+			   . str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT)
347
+			   . '</span> '
348
+			   . $timer_name
349
+			:  str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT);
350
+	}
351 351
 
352 352
 
353 353
 
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
         Benchmark::resetOutput();
155 155
         add_action(
156 156
             'shutdown',
157
-            function () use ($formatted) {
157
+            function() use ($formatted) {
158 158
                 Benchmark::displayResults(true, $formatted);
159 159
             }
160 160
         );
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
         Benchmark::resetOutput();
176 176
         add_action(
177 177
             'shutdown',
178
-            function () use ($filepath, $formatted, $append) {
178
+            function() use ($filepath, $formatted, $append) {
179 179
                 Benchmark::writeResultsToFile($filepath, $formatted, $append);
180 180
             }
181 181
         );
@@ -192,17 +192,17 @@  discard block
 block discarded – undo
192 192
         if (Benchmark::doNotRun()) {
193 193
             return '';
194 194
         }
195
-        if (! empty(Benchmark::$times)) {
195
+        if ( ! empty(Benchmark::$times)) {
196 196
             $total = 0;
197 197
             Benchmark::$output .= $formatted
198 198
                 ? '<span style="color:#999999; font-size:.8em;">( time in milliseconds )</span><br />'
199 199
                 : '';
200 200
             foreach (Benchmark::$times as $timer_name => $total_time) {
201 201
                 Benchmark::$output .= Benchmark::formatTime($timer_name, $total_time, $formatted);
202
-                Benchmark::$output .= $formatted ? '<br />'  : "\n";
202
+                Benchmark::$output .= $formatted ? '<br />' : "\n";
203 203
                 $total += $total_time;
204 204
             }
205
-            if($formatted) {
205
+            if ($formatted) {
206 206
                 Benchmark::$output .= '<br />';
207 207
                 Benchmark::$output .= '<h4>TOTAL TIME</h4>';
208 208
                 Benchmark::$output .= Benchmark::formatTime('', $total, $formatted);
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
                 Benchmark::$output .= '<span style="color:red">Like...HEEELLLP</span><br />';
218 218
             }
219 219
         }
220
-        if (! empty(Benchmark::$memory_usage)) {
220
+        if ( ! empty(Benchmark::$memory_usage)) {
221 221
             Benchmark::$output .= $formatted
222 222
                 ? '<h5>Memory</h5>'
223 223
                 : "\nMemory";
@@ -272,13 +272,13 @@  discard block
 block discarded – undo
272 272
         $filepath = ! empty($filepath) && is_readable(dirname($filepath))
273 273
             ? $filepath
274 274
             : '';
275
-        if( empty($filepath)) {
276
-            $filepath = EVENT_ESPRESSO_UPLOAD_DIR . 'logs/benchmarking-' . date('Y-m-d') . '.html';
275
+        if (empty($filepath)) {
276
+            $filepath = EVENT_ESPRESSO_UPLOAD_DIR.'logs/benchmarking-'.date('Y-m-d').'.html';
277 277
         }
278 278
         EEH_File::ensure_file_exists_and_is_writable($filepath);
279 279
         file_put_contents(
280 280
             $filepath,
281
-            "\n" . date('Y-m-d H:i:s') . Benchmark::generateResults($formatted),
281
+            "\n".date('Y-m-d H:i:s').Benchmark::generateResults($formatted),
282 282
             $append ? FILE_APPEND | LOCK_EX : LOCK_EX
283 283
         );
284 284
     }
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
         return round(
298 298
             $size / pow(1024, $i = floor(log($size, 1024))),
299 299
             2
300
-        ) . ' ' . $unit[absint($i)];
300
+        ).' '.$unit[absint($i)];
301 301
     }
302 302
 
303 303
 
Please login to merge, or discard this patch.
core/EE_Encryption.core.php 2 patches
Indentation   +686 added lines, -686 removed lines patch added patch discarded remove patch
@@ -19,692 +19,692 @@
 block discarded – undo
19 19
 class EE_Encryption implements InterminableInterface
20 20
 {
21 21
 
22
-    /**
23
-     * key used for saving the encryption key to the wp_options table
24
-     */
25
-    const ENCRYPTION_OPTION_KEY = 'ee_encryption_key';
26
-
27
-    /**
28
-     * the OPENSSL cipher method used
29
-     */
30
-    const OPENSSL_CIPHER_METHOD = 'AES-128-CBC';
31
-
32
-    /**
33
-     * WP "options_name" used to store a verified available cipher method
34
-     */
35
-    const OPENSSL_CIPHER_METHOD_OPTION_NAME = 'ee_openssl_cipher_method';
36
-
37
-    /**
38
-     * the OPENSSL digest method used
39
-     */
40
-    const OPENSSL_DIGEST_METHOD = 'sha512';
41
-
42
-    /**
43
-     * separates the encrypted text from the initialization vector
44
-     */
45
-    const OPENSSL_IV_DELIMITER = ':iv:';
46
-
47
-    /**
48
-     * appended to text encrypted using the acme encryption
49
-     */
50
-    const ACME_ENCRYPTION_FLAG = '::ae';
51
-
52
-
53
-
54
-    /**
55
-     * instance of the EE_Encryption object
56
-     */
57
-    protected static $_instance;
58
-
59
-    /**
60
-     * @var string $_encryption_key
61
-     */
62
-    protected $_encryption_key;
63
-
64
-    /**
65
-     * @var string $cipher_method
66
-     */
67
-    private $cipher_method = '';
68
-
69
-    /**
70
-     * @var array $cipher_methods
71
-     */
72
-    private $cipher_methods = array();
73
-
74
-    /**
75
-     * @var array $digest_methods
76
-     */
77
-    private $digest_methods = array();
78
-
79
-    /**
80
-     * @var boolean $_use_openssl_encrypt
81
-     */
82
-    protected $_use_openssl_encrypt = false;
83
-
84
-    /**
85
-     * @var boolean $_use_mcrypt
86
-     */
87
-    protected $_use_mcrypt = false;
88
-
89
-    /**
90
-     * @var boolean $_use_base64_encode
91
-     */
92
-    protected $_use_base64_encode = false;
93
-
94
-
95
-
96
-    /**
97
-     * protected constructor to prevent direct creation
98
-     */
99
-    protected function __construct()
100
-    {
101
-        if (! defined('ESPRESSO_ENCRYPT')) {
102
-            define('ESPRESSO_ENCRYPT', true);
103
-        }
104
-        if (extension_loaded('openssl')) {
105
-            $this->_use_openssl_encrypt = true;
106
-        } else if (extension_loaded('mcrypt')) {
107
-            $this->_use_mcrypt = true;
108
-        }
109
-        if (function_exists('base64_encode')) {
110
-            $this->_use_base64_encode = true;
111
-        }
112
-    }
113
-
114
-
115
-
116
-    /**
117
-     * singleton method used to instantiate class object
118
-     *
119
-     * @return EE_Encryption
120
-     */
121
-    public static function instance()
122
-    {
123
-        // check if class object is instantiated
124
-        if (! EE_Encryption::$_instance instanceof EE_Encryption) {
125
-            EE_Encryption::$_instance = new self();
126
-        }
127
-        return EE_Encryption::$_instance;
128
-    }
129
-
130
-
131
-
132
-    /**
133
-     * get encryption key
134
-     *
135
-     * @return string
136
-     */
137
-    public function get_encryption_key()
138
-    {
139
-        // if encryption key has not been set
140
-        if (empty($this->_encryption_key)) {
141
-            // retrieve encryption_key from db
142
-            $this->_encryption_key = get_option(EE_Encryption::ENCRYPTION_OPTION_KEY, '');
143
-            // WHAT?? No encryption_key in the db ??
144
-            if ($this->_encryption_key === '') {
145
-                // let's make one. And md5 it to make it just the right size for a key
146
-                $new_key = md5($this->generate_random_string());
147
-                // now save it to the db for later
148
-                add_option(EE_Encryption::ENCRYPTION_OPTION_KEY, $new_key);
149
-                // here's the key - FINALLY !
150
-                $this->_encryption_key = $new_key;
151
-            }
152
-        }
153
-        return $this->_encryption_key;
154
-    }
155
-
156
-
157
-
158
-    /**
159
-     * encrypts data
160
-     *
161
-     * @param string $text_string - the text to be encrypted
162
-     * @return string
163
-     * @throws RuntimeException
164
-     */
165
-    public function encrypt($text_string = '')
166
-    {
167
-        // you give me nothing??? GET OUT !
168
-        if (empty($text_string)) {
169
-            return $text_string;
170
-        }
171
-        if ($this->_use_openssl_encrypt) {
172
-            $encrypted_text = $this->openssl_encrypt($text_string);
173
-        } else {
174
-            $encrypted_text = $this->acme_encrypt($text_string);
175
-        }
176
-        return $encrypted_text;
177
-    }
178
-
179
-
180
-
181
-    /**
182
-     * decrypts data
183
-     *
184
-     * @param string $encrypted_text - the text to be decrypted
185
-     * @return string
186
-     * @throws RuntimeException
187
-     */
188
-    public function decrypt($encrypted_text = '')
189
-    {
190
-        // you give me nothing??? GET OUT !
191
-        if (empty($encrypted_text)) {
192
-            return $encrypted_text;
193
-        }
194
-        // if PHP's mcrypt functions are installed then we'll use them
195
-        if ($this->_use_openssl_encrypt) {
196
-            $decrypted_text = $this->openssl_decrypt($encrypted_text);
197
-        } else {
198
-            $decrypted_text = $this->acme_decrypt($encrypted_text);
199
-        }
200
-        return $decrypted_text;
201
-    }
202
-
203
-
204
-
205
-    /**
206
-     * encodes string with PHP's base64 encoding
207
-     *
208
-     * @see http://php.net/manual/en/function.base64-encode.php
209
-     * @param string $text_string the text to be encoded
210
-     * @return string
211
-     */
212
-    public function base64_string_encode($text_string = '')
213
-    {
214
-        // you give me nothing??? GET OUT !
215
-        if (empty($text_string) || ! $this->_use_base64_encode) {
216
-            return $text_string;
217
-        }
218
-        // encode
219
-        return base64_encode($text_string);
220
-    }
221
-
222
-
223
-    /**
224
-     * decodes string that has been encoded with PHP's base64 encoding
225
-     *
226
-     * @see http://php.net/manual/en/function.base64-encode.php
227
-     * @param string $encoded_string the text to be decoded
228
-     * @return string
229
-     * @throws RuntimeException
230
-     */
231
-    public function base64_string_decode($encoded_string = '')
232
-    {
233
-        // you give me nothing??? GET OUT !
234
-        if (empty($encoded_string) || ! $this->valid_base_64($encoded_string)) {
235
-            return $encoded_string;
236
-        }
237
-        // decode
238
-        $decoded_string = base64_decode($encoded_string);
239
-        if ($decoded_string === false) {
240
-            throw new RuntimeException(
241
-                esc_html__('Base 64 decoding failed.', 'event_espresso')
242
-            );
243
-        }
244
-        return $decoded_string;
245
-    }
246
-
247
-
248
-
249
-    /**
250
-     * encodes  url string with PHP's base64 encoding
251
-     *
252
-     * @see http://php.net/manual/en/function.base64-encode.php
253
-     * @param string $text_string the text to be encoded
254
-     * @return string
255
-     */
256
-    public function base64_url_encode($text_string = '')
257
-    {
258
-        // you give me nothing??? GET OUT !
259
-        if (empty($text_string) || ! $this->_use_base64_encode) {
260
-            return $text_string;
261
-        }
262
-        // encode
263
-        $encoded_string = base64_encode($text_string);
264
-        // remove chars to make encoding more URL friendly
265
-        return strtr($encoded_string, '+/=', '-_,');
266
-    }
267
-
268
-
269
-    /**
270
-     * decodes  url string that has been encoded with PHP's base64 encoding
271
-     *
272
-     * @see http://php.net/manual/en/function.base64-encode.php
273
-     * @param string $encoded_string the text to be decoded
274
-     * @return string
275
-     * @throws RuntimeException
276
-     */
277
-    public function base64_url_decode($encoded_string = '')
278
-    {
279
-        // you give me nothing??? GET OUT !
280
-        if (empty($encoded_string) || ! $this->valid_base_64($encoded_string)) {
281
-            return $encoded_string;
282
-        }
283
-        // replace previously removed characters
284
-        $encoded_string = strtr($encoded_string, '-_,', '+/=');
285
-        // decode
286
-        $decoded_string = base64_decode($encoded_string);
287
-        if ($decoded_string === false) {
288
-            throw new RuntimeException(
289
-                esc_html__('Base 64 decoding failed.', 'event_espresso')
290
-            );
291
-        }
292
-        return $decoded_string;
293
-    }
294
-
295
-
296
-    /**
297
-     * encrypts data using PHP's openssl functions
298
-     *
299
-     * @param string $text_string the text to be encrypted
300
-     * @param string $cipher_method
301
-     * @param string $encryption_key
302
-     * @return string
303
-     * @throws RuntimeException
304
-     */
305
-    protected function openssl_encrypt(
306
-        $text_string = '',
307
-        $cipher_method = EE_Encryption::OPENSSL_CIPHER_METHOD,
308
-        $encryption_key = ''
309
-    ) {
310
-        // you give me nothing??? GET OUT !
311
-        if (empty($text_string)) {
312
-            return $text_string;
313
-        }
314
-        $this->cipher_method = $this->getCipherMethod($cipher_method);
315
-        // get initialization vector size
316
-        $iv_size = openssl_cipher_iv_length($this->cipher_method);
317
-        // generate initialization vector.
318
-        // The second parameter ("crypto_strong") is passed by reference,
319
-        // and is used to determines if the algorithm used was "cryptographically strong"
320
-        // openssl_random_pseudo_bytes() will toggle it to either true or false
321
-        $iv = openssl_random_pseudo_bytes($iv_size, $is_strong);
322
-        if ($iv === false || $is_strong === false) {
323
-            throw new RuntimeException(
324
-                esc_html__('Failed to generate OpenSSL initialization vector.', 'event_espresso')
325
-            );
326
-        }
327
-        // encrypt it
328
-        $encrypted_text = openssl_encrypt(
329
-            $text_string,
330
-            $this->cipher_method,
331
-            $this->getDigestHashValue(EE_Encryption::OPENSSL_DIGEST_METHOD, $encryption_key),
332
-            0,
333
-            $iv
334
-        );
335
-        // append the initialization vector
336
-        $encrypted_text .= EE_Encryption::OPENSSL_IV_DELIMITER . $iv;
337
-        // trim and maybe encode
338
-        return $this->_use_base64_encode
339
-            ? trim(base64_encode($encrypted_text))
340
-            : trim($encrypted_text);
341
-    }
342
-
343
-
344
-
345
-    /**
346
-     * Returns a cipher method that has been verified to work.
347
-     * First checks if the cached cipher has been set already and if so, returns that.
348
-     * Then tests the incoming default and returns that if it's good.
349
-     * If not, then it retrieves the previously tested and saved cipher method.
350
-     * But if that doesn't exist, then calls getAvailableCipherMethod()
351
-     * to see what is available on the server, and returns the results.
352
-     *
353
-     * @param string $cipher_method
354
-     * @return string
355
-     * @throws RuntimeException
356
-     */
357
-    protected function getCipherMethod($cipher_method = EE_Encryption::OPENSSL_CIPHER_METHOD)
358
-    {
359
-        if($this->cipher_method !== ''){
360
-            return $this->cipher_method;
361
-        }
362
-        // verify that the default cipher method can produce an initialization vector
363
-        if (openssl_cipher_iv_length($cipher_method) === false) {
364
-            // nope? okay let's get what we found in the past to work
365
-            $cipher_method = get_option(EE_Encryption::OPENSSL_CIPHER_METHOD_OPTION_NAME, '');
366
-            // oops... haven't tested available cipher methods yet
367
-            if($cipher_method === '' || openssl_cipher_iv_length($cipher_method) === false) {
368
-                $cipher_method = $this->getAvailableCipherMethod($cipher_method);
369
-            }
370
-        }
371
-        return $cipher_method;
372
-    }
373
-
374
-
375
-
376
-    /**
377
-     * @param string $cipher_method
378
-     * @return string
379
-     * @throws \RuntimeException
380
-     */
381
-    protected function getAvailableCipherMethod($cipher_method)
382
-    {
383
-        // verify that the incoming cipher method can produce an initialization vector
384
-        if (openssl_cipher_iv_length($cipher_method) === false) {
385
-            // nope? then check the next cipher in the list of available cipher methods
386
-            $cipher_method = next($this->cipher_methods);
387
-            // what? there's no list? then generate that list and cache it,
388
-            if (empty($this->cipher_methods)) {
389
-                $this->cipher_methods = openssl_get_cipher_methods();
390
-                // then grab the first item from the list
391
-                $cipher_method = reset($this->cipher_methods);
392
-            }
393
-            if($cipher_method === false){
394
-                throw new RuntimeException(
395
-                    esc_html__(
396
-                        'OpenSSL support appears to be enabled on the server, but no cipher methods are available. Please contact the server administrator.',
397
-                        'event_espresso'
398
-                    )
399
-                );
400
-            }
401
-            // verify that the next cipher method works
402
-            return $this->getAvailableCipherMethod($cipher_method);
403
-        }
404
-        // if we've gotten this far, then we found an available cipher method that works
405
-        // so save that for next time
406
-        update_option(
407
-            EE_Encryption::OPENSSL_CIPHER_METHOD_OPTION_NAME,
408
-            $cipher_method
409
-        );
410
-        return $cipher_method;
411
-    }
412
-
413
-
414
-    /**
415
-     * decrypts data that has been encrypted with PHP's openssl functions
416
-     *
417
-     * @param string $encrypted_text the text to be decrypted
418
-     * @param string $cipher_method
419
-     * @param string $encryption_key
420
-     * @return string
421
-     * @throws RuntimeException
422
-     */
423
-    protected function openssl_decrypt(
424
-        $encrypted_text = '',
425
-        $cipher_method = EE_Encryption::OPENSSL_CIPHER_METHOD,
426
-        $encryption_key = ''
427
-    ) {
428
-        // you give me nothing??? GET OUT !
429
-        if (empty($encrypted_text)) {
430
-            return $encrypted_text;
431
-        }
432
-        // decode
433
-        $encrypted_text = $this->valid_base_64($encrypted_text)
434
-            ? $this->base64_url_decode($encrypted_text)
435
-            : $encrypted_text;
436
-        $encrypted_components = explode(
437
-            EE_Encryption::OPENSSL_IV_DELIMITER,
438
-            $encrypted_text,
439
-            2
440
-        );
441
-        // check that iv exists, and if not, maybe text was encoded using mcrypt?
442
-        if ($this->_use_mcrypt && ! isset($encrypted_components[1])) {
443
-            return $this->m_decrypt($encrypted_text);
444
-        }
445
-        // decrypt it
446
-        $decrypted_text = openssl_decrypt(
447
-            $encrypted_components[0],
448
-            $this->getCipherMethod($cipher_method),
449
-            $this->getDigestHashValue(EE_Encryption::OPENSSL_DIGEST_METHOD,$encryption_key),
450
-            0,
451
-            $encrypted_components[1]
452
-        );
453
-        $decrypted_text = trim($decrypted_text);
454
-        return $decrypted_text;
455
-    }
456
-
457
-
458
-    /**
459
-     * Computes the digest hash value using the specified digest method.
460
-     * If that digest method fails to produce a valid hash value,
461
-     * then we'll grab the next digest method and recursively try again until something works.
462
-     *
463
-     * @param string $digest_method
464
-     * @param string $encryption_key
465
-     * @return string
466
-     * @throws RuntimeException
467
-     */
468
-    protected function getDigestHashValue($digest_method = EE_Encryption::OPENSSL_DIGEST_METHOD, $encryption_key = ''){
469
-        $encryption_key = $encryption_key !== ''
470
-            ? $encryption_key
471
-            : $this->get_encryption_key();
472
-        $digest_hash_value = openssl_digest($encryption_key, $digest_method);
473
-        if ($digest_hash_value === false) {
474
-            return $this->getDigestHashValue($this->getDigestMethod());
475
-        }
476
-        return $digest_hash_value;
477
-    }
478
-
479
-
480
-
481
-    /**
482
-     * Returns the NEXT element in the $digest_methods array.
483
-     * If the $digest_methods array is empty, then we populate it
484
-     * with the available values returned from openssl_get_md_methods().
485
-     *
486
-     * @return string
487
-     * @throws \RuntimeException
488
-     */
489
-    protected function getDigestMethod(){
490
-        $digest_method = prev($this->digest_methods);
491
-        if (empty($this->digest_methods)) {
492
-            $this->digest_methods = openssl_get_md_methods();
493
-            $digest_method = end($this->digest_methods);
494
-        }
495
-        if ($digest_method === false) {
496
-            throw new RuntimeException(
497
-                esc_html__(
498
-                    'OpenSSL support appears to be enabled on the server, but no digest methods are available. Please contact the server administrator.',
499
-                    'event_espresso'
500
-                )
501
-            );
502
-        }
503
-        return $digest_method;
504
-    }
505
-
506
-
507
-    /**
508
-     * encrypts data for acme servers that didn't bother to install PHP mcrypt
509
-     *
510
-     * @see http://stackoverflow.com/questions/800922/how-to-encrypt-string-without-mcrypt-library-in-php
511
-     * @param string $text_string the text to be decrypted
512
-     * @return string
513
-     */
514
-    protected function acme_encrypt($text_string = '')
515
-    {
516
-        // you give me nothing??? GET OUT !
517
-        if (empty($text_string)) {
518
-            return $text_string;
519
-        }
520
-        $key_bits = str_split(
521
-            str_pad(
522
-                '',
523
-                strlen($text_string),
524
-                $this->get_encryption_key(),
525
-                STR_PAD_RIGHT
526
-            )
527
-        );
528
-        $string_bits = str_split($text_string);
529
-        foreach ($string_bits as $k => $v) {
530
-            $temp = ord($v) + ord($key_bits[$k]);
531
-            $string_bits[$k] = chr($temp > 255 ? ($temp - 256) : $temp);
532
-        }
533
-        $encrypted_text = implode('', $string_bits);
534
-        $encrypted_text .= EE_Encryption::ACME_ENCRYPTION_FLAG;
535
-        return $this->_use_base64_encode
536
-            ? base64_encode($encrypted_text)
537
-            : $encrypted_text;
538
-    }
539
-
540
-
541
-
542
-    /**
543
-     * decrypts data for acme servers that didn't bother to install PHP mcrypt
544
-     *
545
-     * @see http://stackoverflow.com/questions/800922/how-to-encrypt-string-without-mcrypt-library-in-php
546
-     * @param string $encrypted_text the text to be decrypted
547
-     * @return string
548
-     * @throws RuntimeException
549
-     */
550
-    protected function acme_decrypt($encrypted_text = '')
551
-    {
552
-        // you give me nothing??? GET OUT !
553
-        if (empty($encrypted_text)) {
554
-            return $encrypted_text;
555
-        }
556
-        // decode the data ?
557
-        $encrypted_text = $this->valid_base_64($encrypted_text)
558
-            ? $this->base64_url_decode($encrypted_text)
559
-            : $encrypted_text;
560
-        if (
561
-            $this->_use_mcrypt
562
-            && strpos($encrypted_text, EE_Encryption::ACME_ENCRYPTION_FLAG) === false
563
-        ){
564
-            return $this->m_decrypt($encrypted_text);
565
-        }
566
-        $encrypted_text = substr($encrypted_text, 0, -4);
567
-        $key_bits = str_split(
568
-            str_pad(
569
-                '',
570
-                strlen($encrypted_text),
571
-                $this->get_encryption_key(),
572
-                STR_PAD_RIGHT
573
-            )
574
-        );
575
-        $string_bits = str_split($encrypted_text);
576
-        foreach ($string_bits as $k => $v) {
577
-            $temp = ord($v) - ord($key_bits[$k]);
578
-            $string_bits[$k] = chr($temp < 0 ? ($temp + 256) : $temp);
579
-        }
580
-        return implode('', $string_bits);
581
-    }
582
-
583
-
584
-
585
-    /**
586
-     * @see http://stackoverflow.com/questions/2556345/detect-base64-encoding-in-php#30231906
587
-     * @param $string
588
-     * @return bool
589
-     */
590
-    protected function valid_base_64($string)
591
-    {
592
-        // ensure data is a string
593
-        if (! is_string($string) || ! $this->_use_base64_encode) {
594
-            return false;
595
-        }
596
-        $decoded = base64_decode($string, true);
597
-        // Check if there is no invalid character in string
598
-        if (! preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string)) {
599
-            return false;
600
-        }
601
-        // Decode the string in strict mode and send the response
602
-        if (! base64_decode($string, true)) {
603
-            return false;
604
-        }
605
-        // Encode and compare it to original one
606
-        return base64_encode($decoded) === $string;
607
-    }
608
-
609
-
610
-
611
-    /**
612
-     * generate random string
613
-     *
614
-     * @see http://stackoverflow.com/questions/637278/what-is-the-best-way-to-generate-a-random-key-within-php
615
-     * @param int $length number of characters for random string
616
-     * @return string
617
-     */
618
-    public function generate_random_string($length = 40)
619
-    {
620
-        $iterations = ceil($length / 40);
621
-        $random_string = '';
622
-        for ($i = 0; $i < $iterations; $i++) {
623
-            $random_string .= sha1(microtime(true) . mt_rand(10000, 90000));
624
-        }
625
-        $random_string = substr($random_string, 0, $length);
626
-        return $random_string;
627
-    }
628
-
629
-
630
-
631
-    /**
632
-     * encrypts data using PHP's mcrypt functions
633
-     *
634
-     * @deprecated 4.9.39
635
-     * @param string $text_string
636
-     * @internal   param $string - the text to be encrypted
637
-     * @return string
638
-     * @throws RuntimeException
639
-     */
640
-    protected function m_encrypt($text_string = '')
641
-    {
642
-        // you give me nothing??? GET OUT !
643
-        if (empty($text_string)) {
644
-            return $text_string;
645
-        }
646
-        // get the initialization vector size
647
-        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
648
-        // initialization vector
649
-        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
650
-        if ($iv === false) {
651
-            throw new RuntimeException(
652
-                esc_html__('Failed to generate mcrypt initialization vector.', 'event_espresso')
653
-            );
654
-        }
655
-        // encrypt it
656
-        $encrypted_text = mcrypt_encrypt(
657
-            MCRYPT_RIJNDAEL_256,
658
-            $this->get_encryption_key(),
659
-            $text_string,
660
-            MCRYPT_MODE_ECB,
661
-            $iv
662
-        );
663
-        // trim and maybe encode
664
-        return $this->_use_base64_encode
665
-            ? trim(base64_encode($encrypted_text))
666
-            : trim($encrypted_text);
667
-    }
668
-
669
-
670
-
671
-    /**
672
-     * decrypts data that has been encrypted with PHP's mcrypt functions
673
-     *
674
-     * @deprecated 4.9.39
675
-     * @param string $encrypted_text the text to be decrypted
676
-     * @return string
677
-     * @throws RuntimeException
678
-     */
679
-    protected function m_decrypt($encrypted_text = '')
680
-    {
681
-        // you give me nothing??? GET OUT !
682
-        if (empty($encrypted_text)) {
683
-            return $encrypted_text;
684
-        }
685
-        // decode
686
-        $encrypted_text = $this->valid_base_64($encrypted_text)
687
-            ? $this->base64_url_decode($encrypted_text)
688
-            : $encrypted_text;
689
-        // get the initialization vector size
690
-        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
691
-        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
692
-        if ($iv === false) {
693
-            throw new RuntimeException(
694
-                esc_html__('Failed to generate mcrypt initialization vector.', 'event_espresso')
695
-            );
696
-        }
697
-        // decrypt it
698
-        $decrypted_text = mcrypt_decrypt(
699
-            MCRYPT_RIJNDAEL_256,
700
-            $this->get_encryption_key(),
701
-            $encrypted_text,
702
-            MCRYPT_MODE_ECB,
703
-            $iv
704
-        );
705
-        $decrypted_text = trim($decrypted_text);
706
-        return $decrypted_text;
707
-    }
22
+	/**
23
+	 * key used for saving the encryption key to the wp_options table
24
+	 */
25
+	const ENCRYPTION_OPTION_KEY = 'ee_encryption_key';
26
+
27
+	/**
28
+	 * the OPENSSL cipher method used
29
+	 */
30
+	const OPENSSL_CIPHER_METHOD = 'AES-128-CBC';
31
+
32
+	/**
33
+	 * WP "options_name" used to store a verified available cipher method
34
+	 */
35
+	const OPENSSL_CIPHER_METHOD_OPTION_NAME = 'ee_openssl_cipher_method';
36
+
37
+	/**
38
+	 * the OPENSSL digest method used
39
+	 */
40
+	const OPENSSL_DIGEST_METHOD = 'sha512';
41
+
42
+	/**
43
+	 * separates the encrypted text from the initialization vector
44
+	 */
45
+	const OPENSSL_IV_DELIMITER = ':iv:';
46
+
47
+	/**
48
+	 * appended to text encrypted using the acme encryption
49
+	 */
50
+	const ACME_ENCRYPTION_FLAG = '::ae';
51
+
52
+
53
+
54
+	/**
55
+	 * instance of the EE_Encryption object
56
+	 */
57
+	protected static $_instance;
58
+
59
+	/**
60
+	 * @var string $_encryption_key
61
+	 */
62
+	protected $_encryption_key;
63
+
64
+	/**
65
+	 * @var string $cipher_method
66
+	 */
67
+	private $cipher_method = '';
68
+
69
+	/**
70
+	 * @var array $cipher_methods
71
+	 */
72
+	private $cipher_methods = array();
73
+
74
+	/**
75
+	 * @var array $digest_methods
76
+	 */
77
+	private $digest_methods = array();
78
+
79
+	/**
80
+	 * @var boolean $_use_openssl_encrypt
81
+	 */
82
+	protected $_use_openssl_encrypt = false;
83
+
84
+	/**
85
+	 * @var boolean $_use_mcrypt
86
+	 */
87
+	protected $_use_mcrypt = false;
88
+
89
+	/**
90
+	 * @var boolean $_use_base64_encode
91
+	 */
92
+	protected $_use_base64_encode = false;
93
+
94
+
95
+
96
+	/**
97
+	 * protected constructor to prevent direct creation
98
+	 */
99
+	protected function __construct()
100
+	{
101
+		if (! defined('ESPRESSO_ENCRYPT')) {
102
+			define('ESPRESSO_ENCRYPT', true);
103
+		}
104
+		if (extension_loaded('openssl')) {
105
+			$this->_use_openssl_encrypt = true;
106
+		} else if (extension_loaded('mcrypt')) {
107
+			$this->_use_mcrypt = true;
108
+		}
109
+		if (function_exists('base64_encode')) {
110
+			$this->_use_base64_encode = true;
111
+		}
112
+	}
113
+
114
+
115
+
116
+	/**
117
+	 * singleton method used to instantiate class object
118
+	 *
119
+	 * @return EE_Encryption
120
+	 */
121
+	public static function instance()
122
+	{
123
+		// check if class object is instantiated
124
+		if (! EE_Encryption::$_instance instanceof EE_Encryption) {
125
+			EE_Encryption::$_instance = new self();
126
+		}
127
+		return EE_Encryption::$_instance;
128
+	}
129
+
130
+
131
+
132
+	/**
133
+	 * get encryption key
134
+	 *
135
+	 * @return string
136
+	 */
137
+	public function get_encryption_key()
138
+	{
139
+		// if encryption key has not been set
140
+		if (empty($this->_encryption_key)) {
141
+			// retrieve encryption_key from db
142
+			$this->_encryption_key = get_option(EE_Encryption::ENCRYPTION_OPTION_KEY, '');
143
+			// WHAT?? No encryption_key in the db ??
144
+			if ($this->_encryption_key === '') {
145
+				// let's make one. And md5 it to make it just the right size for a key
146
+				$new_key = md5($this->generate_random_string());
147
+				// now save it to the db for later
148
+				add_option(EE_Encryption::ENCRYPTION_OPTION_KEY, $new_key);
149
+				// here's the key - FINALLY !
150
+				$this->_encryption_key = $new_key;
151
+			}
152
+		}
153
+		return $this->_encryption_key;
154
+	}
155
+
156
+
157
+
158
+	/**
159
+	 * encrypts data
160
+	 *
161
+	 * @param string $text_string - the text to be encrypted
162
+	 * @return string
163
+	 * @throws RuntimeException
164
+	 */
165
+	public function encrypt($text_string = '')
166
+	{
167
+		// you give me nothing??? GET OUT !
168
+		if (empty($text_string)) {
169
+			return $text_string;
170
+		}
171
+		if ($this->_use_openssl_encrypt) {
172
+			$encrypted_text = $this->openssl_encrypt($text_string);
173
+		} else {
174
+			$encrypted_text = $this->acme_encrypt($text_string);
175
+		}
176
+		return $encrypted_text;
177
+	}
178
+
179
+
180
+
181
+	/**
182
+	 * decrypts data
183
+	 *
184
+	 * @param string $encrypted_text - the text to be decrypted
185
+	 * @return string
186
+	 * @throws RuntimeException
187
+	 */
188
+	public function decrypt($encrypted_text = '')
189
+	{
190
+		// you give me nothing??? GET OUT !
191
+		if (empty($encrypted_text)) {
192
+			return $encrypted_text;
193
+		}
194
+		// if PHP's mcrypt functions are installed then we'll use them
195
+		if ($this->_use_openssl_encrypt) {
196
+			$decrypted_text = $this->openssl_decrypt($encrypted_text);
197
+		} else {
198
+			$decrypted_text = $this->acme_decrypt($encrypted_text);
199
+		}
200
+		return $decrypted_text;
201
+	}
202
+
203
+
204
+
205
+	/**
206
+	 * encodes string with PHP's base64 encoding
207
+	 *
208
+	 * @see http://php.net/manual/en/function.base64-encode.php
209
+	 * @param string $text_string the text to be encoded
210
+	 * @return string
211
+	 */
212
+	public function base64_string_encode($text_string = '')
213
+	{
214
+		// you give me nothing??? GET OUT !
215
+		if (empty($text_string) || ! $this->_use_base64_encode) {
216
+			return $text_string;
217
+		}
218
+		// encode
219
+		return base64_encode($text_string);
220
+	}
221
+
222
+
223
+	/**
224
+	 * decodes string that has been encoded with PHP's base64 encoding
225
+	 *
226
+	 * @see http://php.net/manual/en/function.base64-encode.php
227
+	 * @param string $encoded_string the text to be decoded
228
+	 * @return string
229
+	 * @throws RuntimeException
230
+	 */
231
+	public function base64_string_decode($encoded_string = '')
232
+	{
233
+		// you give me nothing??? GET OUT !
234
+		if (empty($encoded_string) || ! $this->valid_base_64($encoded_string)) {
235
+			return $encoded_string;
236
+		}
237
+		// decode
238
+		$decoded_string = base64_decode($encoded_string);
239
+		if ($decoded_string === false) {
240
+			throw new RuntimeException(
241
+				esc_html__('Base 64 decoding failed.', 'event_espresso')
242
+			);
243
+		}
244
+		return $decoded_string;
245
+	}
246
+
247
+
248
+
249
+	/**
250
+	 * encodes  url string with PHP's base64 encoding
251
+	 *
252
+	 * @see http://php.net/manual/en/function.base64-encode.php
253
+	 * @param string $text_string the text to be encoded
254
+	 * @return string
255
+	 */
256
+	public function base64_url_encode($text_string = '')
257
+	{
258
+		// you give me nothing??? GET OUT !
259
+		if (empty($text_string) || ! $this->_use_base64_encode) {
260
+			return $text_string;
261
+		}
262
+		// encode
263
+		$encoded_string = base64_encode($text_string);
264
+		// remove chars to make encoding more URL friendly
265
+		return strtr($encoded_string, '+/=', '-_,');
266
+	}
267
+
268
+
269
+	/**
270
+	 * decodes  url string that has been encoded with PHP's base64 encoding
271
+	 *
272
+	 * @see http://php.net/manual/en/function.base64-encode.php
273
+	 * @param string $encoded_string the text to be decoded
274
+	 * @return string
275
+	 * @throws RuntimeException
276
+	 */
277
+	public function base64_url_decode($encoded_string = '')
278
+	{
279
+		// you give me nothing??? GET OUT !
280
+		if (empty($encoded_string) || ! $this->valid_base_64($encoded_string)) {
281
+			return $encoded_string;
282
+		}
283
+		// replace previously removed characters
284
+		$encoded_string = strtr($encoded_string, '-_,', '+/=');
285
+		// decode
286
+		$decoded_string = base64_decode($encoded_string);
287
+		if ($decoded_string === false) {
288
+			throw new RuntimeException(
289
+				esc_html__('Base 64 decoding failed.', 'event_espresso')
290
+			);
291
+		}
292
+		return $decoded_string;
293
+	}
294
+
295
+
296
+	/**
297
+	 * encrypts data using PHP's openssl functions
298
+	 *
299
+	 * @param string $text_string the text to be encrypted
300
+	 * @param string $cipher_method
301
+	 * @param string $encryption_key
302
+	 * @return string
303
+	 * @throws RuntimeException
304
+	 */
305
+	protected function openssl_encrypt(
306
+		$text_string = '',
307
+		$cipher_method = EE_Encryption::OPENSSL_CIPHER_METHOD,
308
+		$encryption_key = ''
309
+	) {
310
+		// you give me nothing??? GET OUT !
311
+		if (empty($text_string)) {
312
+			return $text_string;
313
+		}
314
+		$this->cipher_method = $this->getCipherMethod($cipher_method);
315
+		// get initialization vector size
316
+		$iv_size = openssl_cipher_iv_length($this->cipher_method);
317
+		// generate initialization vector.
318
+		// The second parameter ("crypto_strong") is passed by reference,
319
+		// and is used to determines if the algorithm used was "cryptographically strong"
320
+		// openssl_random_pseudo_bytes() will toggle it to either true or false
321
+		$iv = openssl_random_pseudo_bytes($iv_size, $is_strong);
322
+		if ($iv === false || $is_strong === false) {
323
+			throw new RuntimeException(
324
+				esc_html__('Failed to generate OpenSSL initialization vector.', 'event_espresso')
325
+			);
326
+		}
327
+		// encrypt it
328
+		$encrypted_text = openssl_encrypt(
329
+			$text_string,
330
+			$this->cipher_method,
331
+			$this->getDigestHashValue(EE_Encryption::OPENSSL_DIGEST_METHOD, $encryption_key),
332
+			0,
333
+			$iv
334
+		);
335
+		// append the initialization vector
336
+		$encrypted_text .= EE_Encryption::OPENSSL_IV_DELIMITER . $iv;
337
+		// trim and maybe encode
338
+		return $this->_use_base64_encode
339
+			? trim(base64_encode($encrypted_text))
340
+			: trim($encrypted_text);
341
+	}
342
+
343
+
344
+
345
+	/**
346
+	 * Returns a cipher method that has been verified to work.
347
+	 * First checks if the cached cipher has been set already and if so, returns that.
348
+	 * Then tests the incoming default and returns that if it's good.
349
+	 * If not, then it retrieves the previously tested and saved cipher method.
350
+	 * But if that doesn't exist, then calls getAvailableCipherMethod()
351
+	 * to see what is available on the server, and returns the results.
352
+	 *
353
+	 * @param string $cipher_method
354
+	 * @return string
355
+	 * @throws RuntimeException
356
+	 */
357
+	protected function getCipherMethod($cipher_method = EE_Encryption::OPENSSL_CIPHER_METHOD)
358
+	{
359
+		if($this->cipher_method !== ''){
360
+			return $this->cipher_method;
361
+		}
362
+		// verify that the default cipher method can produce an initialization vector
363
+		if (openssl_cipher_iv_length($cipher_method) === false) {
364
+			// nope? okay let's get what we found in the past to work
365
+			$cipher_method = get_option(EE_Encryption::OPENSSL_CIPHER_METHOD_OPTION_NAME, '');
366
+			// oops... haven't tested available cipher methods yet
367
+			if($cipher_method === '' || openssl_cipher_iv_length($cipher_method) === false) {
368
+				$cipher_method = $this->getAvailableCipherMethod($cipher_method);
369
+			}
370
+		}
371
+		return $cipher_method;
372
+	}
373
+
374
+
375
+
376
+	/**
377
+	 * @param string $cipher_method
378
+	 * @return string
379
+	 * @throws \RuntimeException
380
+	 */
381
+	protected function getAvailableCipherMethod($cipher_method)
382
+	{
383
+		// verify that the incoming cipher method can produce an initialization vector
384
+		if (openssl_cipher_iv_length($cipher_method) === false) {
385
+			// nope? then check the next cipher in the list of available cipher methods
386
+			$cipher_method = next($this->cipher_methods);
387
+			// what? there's no list? then generate that list and cache it,
388
+			if (empty($this->cipher_methods)) {
389
+				$this->cipher_methods = openssl_get_cipher_methods();
390
+				// then grab the first item from the list
391
+				$cipher_method = reset($this->cipher_methods);
392
+			}
393
+			if($cipher_method === false){
394
+				throw new RuntimeException(
395
+					esc_html__(
396
+						'OpenSSL support appears to be enabled on the server, but no cipher methods are available. Please contact the server administrator.',
397
+						'event_espresso'
398
+					)
399
+				);
400
+			}
401
+			// verify that the next cipher method works
402
+			return $this->getAvailableCipherMethod($cipher_method);
403
+		}
404
+		// if we've gotten this far, then we found an available cipher method that works
405
+		// so save that for next time
406
+		update_option(
407
+			EE_Encryption::OPENSSL_CIPHER_METHOD_OPTION_NAME,
408
+			$cipher_method
409
+		);
410
+		return $cipher_method;
411
+	}
412
+
413
+
414
+	/**
415
+	 * decrypts data that has been encrypted with PHP's openssl functions
416
+	 *
417
+	 * @param string $encrypted_text the text to be decrypted
418
+	 * @param string $cipher_method
419
+	 * @param string $encryption_key
420
+	 * @return string
421
+	 * @throws RuntimeException
422
+	 */
423
+	protected function openssl_decrypt(
424
+		$encrypted_text = '',
425
+		$cipher_method = EE_Encryption::OPENSSL_CIPHER_METHOD,
426
+		$encryption_key = ''
427
+	) {
428
+		// you give me nothing??? GET OUT !
429
+		if (empty($encrypted_text)) {
430
+			return $encrypted_text;
431
+		}
432
+		// decode
433
+		$encrypted_text = $this->valid_base_64($encrypted_text)
434
+			? $this->base64_url_decode($encrypted_text)
435
+			: $encrypted_text;
436
+		$encrypted_components = explode(
437
+			EE_Encryption::OPENSSL_IV_DELIMITER,
438
+			$encrypted_text,
439
+			2
440
+		);
441
+		// check that iv exists, and if not, maybe text was encoded using mcrypt?
442
+		if ($this->_use_mcrypt && ! isset($encrypted_components[1])) {
443
+			return $this->m_decrypt($encrypted_text);
444
+		}
445
+		// decrypt it
446
+		$decrypted_text = openssl_decrypt(
447
+			$encrypted_components[0],
448
+			$this->getCipherMethod($cipher_method),
449
+			$this->getDigestHashValue(EE_Encryption::OPENSSL_DIGEST_METHOD,$encryption_key),
450
+			0,
451
+			$encrypted_components[1]
452
+		);
453
+		$decrypted_text = trim($decrypted_text);
454
+		return $decrypted_text;
455
+	}
456
+
457
+
458
+	/**
459
+	 * Computes the digest hash value using the specified digest method.
460
+	 * If that digest method fails to produce a valid hash value,
461
+	 * then we'll grab the next digest method and recursively try again until something works.
462
+	 *
463
+	 * @param string $digest_method
464
+	 * @param string $encryption_key
465
+	 * @return string
466
+	 * @throws RuntimeException
467
+	 */
468
+	protected function getDigestHashValue($digest_method = EE_Encryption::OPENSSL_DIGEST_METHOD, $encryption_key = ''){
469
+		$encryption_key = $encryption_key !== ''
470
+			? $encryption_key
471
+			: $this->get_encryption_key();
472
+		$digest_hash_value = openssl_digest($encryption_key, $digest_method);
473
+		if ($digest_hash_value === false) {
474
+			return $this->getDigestHashValue($this->getDigestMethod());
475
+		}
476
+		return $digest_hash_value;
477
+	}
478
+
479
+
480
+
481
+	/**
482
+	 * Returns the NEXT element in the $digest_methods array.
483
+	 * If the $digest_methods array is empty, then we populate it
484
+	 * with the available values returned from openssl_get_md_methods().
485
+	 *
486
+	 * @return string
487
+	 * @throws \RuntimeException
488
+	 */
489
+	protected function getDigestMethod(){
490
+		$digest_method = prev($this->digest_methods);
491
+		if (empty($this->digest_methods)) {
492
+			$this->digest_methods = openssl_get_md_methods();
493
+			$digest_method = end($this->digest_methods);
494
+		}
495
+		if ($digest_method === false) {
496
+			throw new RuntimeException(
497
+				esc_html__(
498
+					'OpenSSL support appears to be enabled on the server, but no digest methods are available. Please contact the server administrator.',
499
+					'event_espresso'
500
+				)
501
+			);
502
+		}
503
+		return $digest_method;
504
+	}
505
+
506
+
507
+	/**
508
+	 * encrypts data for acme servers that didn't bother to install PHP mcrypt
509
+	 *
510
+	 * @see http://stackoverflow.com/questions/800922/how-to-encrypt-string-without-mcrypt-library-in-php
511
+	 * @param string $text_string the text to be decrypted
512
+	 * @return string
513
+	 */
514
+	protected function acme_encrypt($text_string = '')
515
+	{
516
+		// you give me nothing??? GET OUT !
517
+		if (empty($text_string)) {
518
+			return $text_string;
519
+		}
520
+		$key_bits = str_split(
521
+			str_pad(
522
+				'',
523
+				strlen($text_string),
524
+				$this->get_encryption_key(),
525
+				STR_PAD_RIGHT
526
+			)
527
+		);
528
+		$string_bits = str_split($text_string);
529
+		foreach ($string_bits as $k => $v) {
530
+			$temp = ord($v) + ord($key_bits[$k]);
531
+			$string_bits[$k] = chr($temp > 255 ? ($temp - 256) : $temp);
532
+		}
533
+		$encrypted_text = implode('', $string_bits);
534
+		$encrypted_text .= EE_Encryption::ACME_ENCRYPTION_FLAG;
535
+		return $this->_use_base64_encode
536
+			? base64_encode($encrypted_text)
537
+			: $encrypted_text;
538
+	}
539
+
540
+
541
+
542
+	/**
543
+	 * decrypts data for acme servers that didn't bother to install PHP mcrypt
544
+	 *
545
+	 * @see http://stackoverflow.com/questions/800922/how-to-encrypt-string-without-mcrypt-library-in-php
546
+	 * @param string $encrypted_text the text to be decrypted
547
+	 * @return string
548
+	 * @throws RuntimeException
549
+	 */
550
+	protected function acme_decrypt($encrypted_text = '')
551
+	{
552
+		// you give me nothing??? GET OUT !
553
+		if (empty($encrypted_text)) {
554
+			return $encrypted_text;
555
+		}
556
+		// decode the data ?
557
+		$encrypted_text = $this->valid_base_64($encrypted_text)
558
+			? $this->base64_url_decode($encrypted_text)
559
+			: $encrypted_text;
560
+		if (
561
+			$this->_use_mcrypt
562
+			&& strpos($encrypted_text, EE_Encryption::ACME_ENCRYPTION_FLAG) === false
563
+		){
564
+			return $this->m_decrypt($encrypted_text);
565
+		}
566
+		$encrypted_text = substr($encrypted_text, 0, -4);
567
+		$key_bits = str_split(
568
+			str_pad(
569
+				'',
570
+				strlen($encrypted_text),
571
+				$this->get_encryption_key(),
572
+				STR_PAD_RIGHT
573
+			)
574
+		);
575
+		$string_bits = str_split($encrypted_text);
576
+		foreach ($string_bits as $k => $v) {
577
+			$temp = ord($v) - ord($key_bits[$k]);
578
+			$string_bits[$k] = chr($temp < 0 ? ($temp + 256) : $temp);
579
+		}
580
+		return implode('', $string_bits);
581
+	}
582
+
583
+
584
+
585
+	/**
586
+	 * @see http://stackoverflow.com/questions/2556345/detect-base64-encoding-in-php#30231906
587
+	 * @param $string
588
+	 * @return bool
589
+	 */
590
+	protected function valid_base_64($string)
591
+	{
592
+		// ensure data is a string
593
+		if (! is_string($string) || ! $this->_use_base64_encode) {
594
+			return false;
595
+		}
596
+		$decoded = base64_decode($string, true);
597
+		// Check if there is no invalid character in string
598
+		if (! preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string)) {
599
+			return false;
600
+		}
601
+		// Decode the string in strict mode and send the response
602
+		if (! base64_decode($string, true)) {
603
+			return false;
604
+		}
605
+		// Encode and compare it to original one
606
+		return base64_encode($decoded) === $string;
607
+	}
608
+
609
+
610
+
611
+	/**
612
+	 * generate random string
613
+	 *
614
+	 * @see http://stackoverflow.com/questions/637278/what-is-the-best-way-to-generate-a-random-key-within-php
615
+	 * @param int $length number of characters for random string
616
+	 * @return string
617
+	 */
618
+	public function generate_random_string($length = 40)
619
+	{
620
+		$iterations = ceil($length / 40);
621
+		$random_string = '';
622
+		for ($i = 0; $i < $iterations; $i++) {
623
+			$random_string .= sha1(microtime(true) . mt_rand(10000, 90000));
624
+		}
625
+		$random_string = substr($random_string, 0, $length);
626
+		return $random_string;
627
+	}
628
+
629
+
630
+
631
+	/**
632
+	 * encrypts data using PHP's mcrypt functions
633
+	 *
634
+	 * @deprecated 4.9.39
635
+	 * @param string $text_string
636
+	 * @internal   param $string - the text to be encrypted
637
+	 * @return string
638
+	 * @throws RuntimeException
639
+	 */
640
+	protected function m_encrypt($text_string = '')
641
+	{
642
+		// you give me nothing??? GET OUT !
643
+		if (empty($text_string)) {
644
+			return $text_string;
645
+		}
646
+		// get the initialization vector size
647
+		$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
648
+		// initialization vector
649
+		$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
650
+		if ($iv === false) {
651
+			throw new RuntimeException(
652
+				esc_html__('Failed to generate mcrypt initialization vector.', 'event_espresso')
653
+			);
654
+		}
655
+		// encrypt it
656
+		$encrypted_text = mcrypt_encrypt(
657
+			MCRYPT_RIJNDAEL_256,
658
+			$this->get_encryption_key(),
659
+			$text_string,
660
+			MCRYPT_MODE_ECB,
661
+			$iv
662
+		);
663
+		// trim and maybe encode
664
+		return $this->_use_base64_encode
665
+			? trim(base64_encode($encrypted_text))
666
+			: trim($encrypted_text);
667
+	}
668
+
669
+
670
+
671
+	/**
672
+	 * decrypts data that has been encrypted with PHP's mcrypt functions
673
+	 *
674
+	 * @deprecated 4.9.39
675
+	 * @param string $encrypted_text the text to be decrypted
676
+	 * @return string
677
+	 * @throws RuntimeException
678
+	 */
679
+	protected function m_decrypt($encrypted_text = '')
680
+	{
681
+		// you give me nothing??? GET OUT !
682
+		if (empty($encrypted_text)) {
683
+			return $encrypted_text;
684
+		}
685
+		// decode
686
+		$encrypted_text = $this->valid_base_64($encrypted_text)
687
+			? $this->base64_url_decode($encrypted_text)
688
+			: $encrypted_text;
689
+		// get the initialization vector size
690
+		$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
691
+		$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
692
+		if ($iv === false) {
693
+			throw new RuntimeException(
694
+				esc_html__('Failed to generate mcrypt initialization vector.', 'event_espresso')
695
+			);
696
+		}
697
+		// decrypt it
698
+		$decrypted_text = mcrypt_decrypt(
699
+			MCRYPT_RIJNDAEL_256,
700
+			$this->get_encryption_key(),
701
+			$encrypted_text,
702
+			MCRYPT_MODE_ECB,
703
+			$iv
704
+		);
705
+		$decrypted_text = trim($decrypted_text);
706
+		return $decrypted_text;
707
+	}
708 708
 
709 709
 }
710 710
 /* End of file EE_Encryption.class.php */
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
      */
99 99
     protected function __construct()
100 100
     {
101
-        if (! defined('ESPRESSO_ENCRYPT')) {
101
+        if ( ! defined('ESPRESSO_ENCRYPT')) {
102 102
             define('ESPRESSO_ENCRYPT', true);
103 103
         }
104 104
         if (extension_loaded('openssl')) {
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
     public static function instance()
122 122
     {
123 123
         // check if class object is instantiated
124
-        if (! EE_Encryption::$_instance instanceof EE_Encryption) {
124
+        if ( ! EE_Encryption::$_instance instanceof EE_Encryption) {
125 125
             EE_Encryption::$_instance = new self();
126 126
         }
127 127
         return EE_Encryption::$_instance;
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
             $iv
334 334
         );
335 335
         // append the initialization vector
336
-        $encrypted_text .= EE_Encryption::OPENSSL_IV_DELIMITER . $iv;
336
+        $encrypted_text .= EE_Encryption::OPENSSL_IV_DELIMITER.$iv;
337 337
         // trim and maybe encode
338 338
         return $this->_use_base64_encode
339 339
             ? trim(base64_encode($encrypted_text))
@@ -356,7 +356,7 @@  discard block
 block discarded – undo
356 356
      */
357 357
     protected function getCipherMethod($cipher_method = EE_Encryption::OPENSSL_CIPHER_METHOD)
358 358
     {
359
-        if($this->cipher_method !== ''){
359
+        if ($this->cipher_method !== '') {
360 360
             return $this->cipher_method;
361 361
         }
362 362
         // verify that the default cipher method can produce an initialization vector
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
             // nope? okay let's get what we found in the past to work
365 365
             $cipher_method = get_option(EE_Encryption::OPENSSL_CIPHER_METHOD_OPTION_NAME, '');
366 366
             // oops... haven't tested available cipher methods yet
367
-            if($cipher_method === '' || openssl_cipher_iv_length($cipher_method) === false) {
367
+            if ($cipher_method === '' || openssl_cipher_iv_length($cipher_method) === false) {
368 368
                 $cipher_method = $this->getAvailableCipherMethod($cipher_method);
369 369
             }
370 370
         }
@@ -390,7 +390,7 @@  discard block
 block discarded – undo
390 390
                 // then grab the first item from the list
391 391
                 $cipher_method = reset($this->cipher_methods);
392 392
             }
393
-            if($cipher_method === false){
393
+            if ($cipher_method === false) {
394 394
                 throw new RuntimeException(
395 395
                     esc_html__(
396 396
                         'OpenSSL support appears to be enabled on the server, but no cipher methods are available. Please contact the server administrator.',
@@ -446,7 +446,7 @@  discard block
 block discarded – undo
446 446
         $decrypted_text = openssl_decrypt(
447 447
             $encrypted_components[0],
448 448
             $this->getCipherMethod($cipher_method),
449
-            $this->getDigestHashValue(EE_Encryption::OPENSSL_DIGEST_METHOD,$encryption_key),
449
+            $this->getDigestHashValue(EE_Encryption::OPENSSL_DIGEST_METHOD, $encryption_key),
450 450
             0,
451 451
             $encrypted_components[1]
452 452
         );
@@ -465,7 +465,7 @@  discard block
 block discarded – undo
465 465
      * @return string
466 466
      * @throws RuntimeException
467 467
      */
468
-    protected function getDigestHashValue($digest_method = EE_Encryption::OPENSSL_DIGEST_METHOD, $encryption_key = ''){
468
+    protected function getDigestHashValue($digest_method = EE_Encryption::OPENSSL_DIGEST_METHOD, $encryption_key = '') {
469 469
         $encryption_key = $encryption_key !== ''
470 470
             ? $encryption_key
471 471
             : $this->get_encryption_key();
@@ -486,7 +486,7 @@  discard block
 block discarded – undo
486 486
      * @return string
487 487
      * @throws \RuntimeException
488 488
      */
489
-    protected function getDigestMethod(){
489
+    protected function getDigestMethod() {
490 490
         $digest_method = prev($this->digest_methods);
491 491
         if (empty($this->digest_methods)) {
492 492
             $this->digest_methods = openssl_get_md_methods();
@@ -560,7 +560,7 @@  discard block
 block discarded – undo
560 560
         if (
561 561
             $this->_use_mcrypt
562 562
             && strpos($encrypted_text, EE_Encryption::ACME_ENCRYPTION_FLAG) === false
563
-        ){
563
+        ) {
564 564
             return $this->m_decrypt($encrypted_text);
565 565
         }
566 566
         $encrypted_text = substr($encrypted_text, 0, -4);
@@ -590,16 +590,16 @@  discard block
 block discarded – undo
590 590
     protected function valid_base_64($string)
591 591
     {
592 592
         // ensure data is a string
593
-        if (! is_string($string) || ! $this->_use_base64_encode) {
593
+        if ( ! is_string($string) || ! $this->_use_base64_encode) {
594 594
             return false;
595 595
         }
596 596
         $decoded = base64_decode($string, true);
597 597
         // Check if there is no invalid character in string
598
-        if (! preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string)) {
598
+        if ( ! preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string)) {
599 599
             return false;
600 600
         }
601 601
         // Decode the string in strict mode and send the response
602
-        if (! base64_decode($string, true)) {
602
+        if ( ! base64_decode($string, true)) {
603 603
             return false;
604 604
         }
605 605
         // Encode and compare it to original one
@@ -620,7 +620,7 @@  discard block
 block discarded – undo
620 620
         $iterations = ceil($length / 40);
621 621
         $random_string = '';
622 622
         for ($i = 0; $i < $iterations; $i++) {
623
-            $random_string .= sha1(microtime(true) . mt_rand(10000, 90000));
623
+            $random_string .= sha1(microtime(true).mt_rand(10000, 90000));
624 624
         }
625 625
         $random_string = substr($random_string, 0, $length);
626 626
         return $random_string;
Please login to merge, or discard this patch.
core/db_models/EEM_Line_Item.model.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -416,7 +416,7 @@
 block discarded – undo
416 416
      * If $expired is set to true, then only line items for expired sessions will be returned.
417 417
      * If $expired is set to false, then only line items for active sessions will be returned.
418 418
      *
419
-     * @param null $expired
419
+     * @param boolean $expired
420 420
      * @return EE_Base_Class[]|EE_Line_Item[]
421 421
      * @throws EE_Error
422 422
      * @throws InvalidArgumentException
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
 use EventEspresso\core\exceptions\InvalidInterfaceException;
5 5
 use EventEspresso\core\services\loaders\LoaderFactory;
6 6
 
7
-if (!defined('EVENT_ESPRESSO_VERSION')) exit('No direct script access allowed');
7
+if ( ! defined('EVENT_ESPRESSO_VERSION')) exit('No direct script access allowed');
8 8
 
9 9
 /**
10 10
  * Event Espresso
@@ -211,8 +211,8 @@  discard block
 block discarded – undo
211 211
         );
212 212
         $query = $wpdb->prepare(
213 213
             'DELETE li
214
-				FROM ' . $this->table() . ' li
215
-				LEFT JOIN ' . EEM_Transaction::instance()->table() . ' t ON li.TXN_ID = t.TXN_ID
214
+				FROM ' . $this->table().' li
215
+				LEFT JOIN ' . EEM_Transaction::instance()->table().' t ON li.TXN_ID = t.TXN_ID
216 216
 				WHERE t.TXN_ID IS NULL AND li.LIN_timestamp < %s',
217 217
             // use GMT time because that's what TXN_timestamps are in
218 218
             date('Y-m-d H:i:s', time() - $time_to_leave_alone)
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
         $query_params = array(
254 254
             'OBJ_type' => $OBJ_type,
255 255
             // if incoming $OBJ_IDs is an array, then make sure it is formatted correctly for the query
256
-            'OBJ_ID' => is_array($OBJ_IDs) && !isset($OBJ_IDs['IN']) ? array('IN', $OBJ_IDs) : $OBJ_IDs
256
+            'OBJ_ID' => is_array($OBJ_IDs) && ! isset($OBJ_IDs['IN']) ? array('IN', $OBJ_IDs) : $OBJ_IDs
257 257
         );
258 258
         if ($TXN_ID) {
259 259
             $query_params['TXN_ID'] = $TXN_ID;
@@ -456,7 +456,7 @@  discard block
 block discarded – undo
456 456
      */
457 457
     public function getTicketLineItemsForExpiredCarts($timestamp = 0)
458 458
     {
459
-        if(! absint($timestamp)) {
459
+        if ( ! absint($timestamp)) {
460 460
             /** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
461 461
             $session_lifespan = LoaderFactory::getLoader()->getShared(
462 462
                 'EventEspresso\core\domain\values\session\SessionLifespan'
Please login to merge, or discard this patch.
Indentation   +436 added lines, -436 removed lines patch added patch discarded remove patch
@@ -47,444 +47,444 @@
 block discarded – undo
47 47
 class EEM_Line_Item extends EEM_Base
48 48
 {
49 49
 
50
-    /**
51
-     * Tax sub-total is just the total of all the taxes, which should be children
52
-     * of this line item. There should only ever be one tax sub-total, and it should
53
-     * be a direct child of. Its quantity and LIN_unit_price = 1.
54
-     */
55
-    const type_tax_sub_total = 'tax-sub-total';
56
-
57
-    /**
58
-     * Tax line items indicate a tax applied to all the taxable line items.
59
-     * Should not have any children line items. Its LIN_unit_price = 0. Its LIN_percent is a percent, not a decimal
60
-     * (eg 10% tax = 10, not 0.1). Its LIN_total = LIN_unit_price * pre-tax-total. Quantity = 1.
61
-     */
62
-    const type_tax = 'tax';
63
-
64
-    /**
65
-     * Indicating individual items purchased, or discounts or surcharges.
66
-     * The sum of all the regular line items  plus the tax items should equal
67
-     * the grand total.
68
-     * Possible children are sub-line-items and cancellations.
69
-     * For flat items, LIN_unit_price * LIN_quantity = LIN_total. Its LIN_total is the sum of all the children
70
-     * LIN_totals. Its LIN_percent = 0.
71
-     * For percent items, its LIN_unit_price = 0. Its LIN_percent is a percent, not a decimal (eg 10% = 10, not 0.1).
72
-     * Its LIN_total is LIN_percent / 100 * sum of lower-priority sibling line items. Quantity = 1.
73
-     */
74
-    const type_line_item = 'line-item';
75
-
76
-    /**
77
-     * Line item indicating all the factors that make a single line item.
78
-     * Sub-line items should have NO children line items.
79
-     * For flat sub-items, their quantity should match their parent item, their LIN_unit_price should be this sub-item's
80
-     * contribution towards the price of ONE of their parent items, and its LIN_total should be
81
-     *  = LIN_quantity * LIN_unit_price. Its LIN_percent = 0.
82
-     * For percent sub-items, the quantity should be 1, LIN_unit_price should be 0, and its LIN_total should
83
-     * = LIN_percent / 100 * sum of lower-priority sibling line items..
84
-     */
85
-    const type_sub_line_item = 'sub-item';
86
-
87
-    /**
88
-     * Line item indicating a sub-total (eg total for an event, or pre-tax subtotal).
89
-     * Direct children should be event subtotals.
90
-     * Should have quantity of 1, and a LIN_total and LIN_unit_price of the sum of all its sub-items' LIN_totals.
91
-     *
92
-     */
93
-    const type_sub_total = 'sub-total';
94
-
95
-    /**
96
-     * Line item for the grand total of an order. Its direct children
97
-     * should be tax subtotals and (pre-tax) subtotals, and possibly a regular line item
98
-     * indicating a transaction-wide discount/surcharge. Should have a quantity of 1, a LIN_total and LIN_unit_price of
99
-     * the entire order's mount.
100
-     */
101
-    const type_total = 'total';
102
-
103
-    /**
104
-     * When a line item is cancelled, a sub-line-item of type 'cancellation'
105
-     * should be created, indicating the quantity that were cancelled
106
-     * (because a line item could have a quantity of 1, and its cancellation item
107
-     * could be for 3, indicating that originally 4 were purchased, but 3 have been
108
-     * cancelled, and only one remains).
109
-     * When items are refunded, a cancellation line item should be made, which points
110
-     * to teh payment model object which actually refunded the payment.
111
-     * Cancellations should NOT have any children line items; the should NOT affect
112
-     * any calculations, and are only meant as a record that cancellations have occurred.
113
-     * Their LIN_percent should be 0.
114
-     */
115
-    const type_cancellation = 'cancellation';
116
-
117
-    // private instance of the EEM_Line_Item object
118
-    protected static $_instance = NULL;
119
-
120
-
121
-    /**
122
-     *        private constructor to prevent direct creation
123
-     * @Constructor
124
-     * @access protected
125
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any incoming timezone data that gets saved).  Note this just sends the timezone info to the date time model field objects.  Default is NULL (and will be assumed using the set timezone in the 'timezone_string' wp option)
126
-     * @return \EEM_Line_Item
127
-     */
128
-    protected function __construct($timezone)
129
-    {
130
-        $this->singular_item = __('Line Item', 'event_espresso');
131
-        $this->plural_item = __('Line Items', 'event_espresso');
132
-
133
-        $this->_tables = array(
134
-            'Line_Item' => new EE_Primary_Table('esp_line_item', 'LIN_ID')
135
-        );
136
-        $line_items_can_be_for = apply_filters('FHEE__EEM_Line_Item__line_items_can_be_for', array('Ticket', 'Price', 'Event'));
137
-        $this->_fields = array(
138
-            'Line_Item' => array(
139
-                'LIN_ID' => new EE_Primary_Key_Int_Field('LIN_ID', __("ID", "event_espresso")),
140
-                'LIN_code' => new EE_Slug_Field('LIN_code', __("Code for index into Cart", "event_espresso"), TRUE),
141
-                'TXN_ID' => new EE_Foreign_Key_Int_Field('TXN_ID', __("Transaction ID", "event_espresso"), TRUE, NULL, 'Transaction'),
142
-                'LIN_name' => new EE_Full_HTML_Field('LIN_name', __("Line Item Name", "event_espresso"), FALSE, ''),
143
-                'LIN_desc' => new EE_Full_HTML_Field('LIN_desc', __("Line Item Description", "event_espresso"), TRUE),
144
-                'LIN_unit_price' => new EE_Money_Field('LIN_unit_price', __("Unit Price", "event_espresso"), FALSE, 0),
145
-                'LIN_percent' => new EE_Float_Field('LIN_percent', __("Percent", "event_espresso"), FALSE, 0),
146
-                'LIN_is_taxable' => new EE_Boolean_Field('LIN_is_taxable', __("Taxable", "event_espresso"), FALSE, FALSE),
147
-                'LIN_order' => new EE_Integer_Field('LIN_order', __("Order of Application towards total of parent", "event_espresso"), FALSE, 1),
148
-                'LIN_total' => new EE_Money_Field('LIN_total', __("Total (unit price x quantity)", "event_espresso"), FALSE, 0),
149
-                'LIN_quantity' => new EE_Integer_Field('LIN_quantity', __("Quantity", "event_espresso"), TRUE, 1),
150
-                'LIN_parent' => new EE_Integer_Field('LIN_parent', __("Parent ID (this item goes towards that Line Item's total)", "event_espresso"), TRUE, NULL),
151
-                'LIN_type' => new EE_Enum_Text_Field('LIN_type', __("Type", "event_espresso"), FALSE, 'line-item', array(
152
-                        self::type_line_item => __("Line Item", "event_espresso"),
153
-                        self::type_sub_line_item => __("Sub-Item", "event_espresso"),
154
-                        self::type_sub_total => __("Subtotal", "event_espresso"),
155
-                        self::type_tax_sub_total => __("Tax Subtotal", "event_espresso"),
156
-                        self::type_tax => __("Tax", "event_espresso"),
157
-                        self::type_total => __("Total", "event_espresso"),
158
-                        self::type_cancellation => __('Cancellation', 'event_espresso')
159
-                    )
160
-                ),
161
-                'OBJ_ID' => new EE_Foreign_Key_Int_Field('OBJ_ID', __('ID of Item purchased.', 'event_espresso'), TRUE, NULL, $line_items_can_be_for),
162
-                'OBJ_type' => new EE_Any_Foreign_Model_Name_Field('OBJ_type', __("Model Name this Line Item is for", "event_espresso"), TRUE, NULL, $line_items_can_be_for),
163
-                'LIN_timestamp' => new EE_Datetime_Field('LIN_timestamp', __('When the line item was created', 'event_espresso'), false, EE_Datetime_Field::now, $timezone),
164
-            )
165
-        );
166
-        $this->_model_relations = array(
167
-            'Transaction' => new EE_Belongs_To_Relation(),
168
-            'Ticket' => new EE_Belongs_To_Any_Relation(),
169
-            'Price' => new EE_Belongs_To_Any_Relation(),
170
-            'Event' => new EE_Belongs_To_Any_Relation()
171
-        );
172
-        $this->_model_chain_to_wp_user = 'Transaction.Registration.Event';
173
-        $this->_caps_slug = 'transactions';
174
-        parent::__construct($timezone);
175
-    }
176
-
177
-
178
-    /**
179
-     * Gets all the line items for this transaction of the given type
180
-     * @param string $line_item_type like one of EEM_Line_Item::type_*
181
-     * @param EE_Transaction|int $transaction
182
-     * @return EE_Line_Item[]
183
-     */
184
-    public function get_all_of_type_for_transaction($line_item_type, $transaction)
185
-    {
186
-        $transaction = EEM_Transaction::instance()->ensure_is_ID($transaction);
187
-        return $this->get_all(array(array(
188
-            'LIN_type' => $line_item_type,
189
-            'TXN_ID' => $transaction
190
-        )));
191
-    }
192
-
193
-
194
-    /**
195
-     * Gets all line items unrelated to tickets that are normal line items
196
-     * (eg shipping, promotions, and miscellaneous other stuff should probably fit in this category)
197
-     * @param EE_Transaction|int $transaction
198
-     * @return EE_Line_Item[]
199
-     */
200
-    public function get_all_non_ticket_line_items_for_transaction($transaction)
201
-    {
202
-        $transaction = EEM_Transaction::instance()->ensure_is_ID($transaction);
203
-        return $this->get_all(array(array(
204
-            'LIN_type' => self::type_line_item,
205
-            'TXN_ID' => $transaction,
206
-            'OR' => array(
207
-                'OBJ_type*notticket' => array('!=', 'Ticket'),
208
-                'OBJ_type*null' => array('IS_NULL'))
209
-        )));
210
-    }
211
-
212
-    /**
213
-     * Deletes line items with no transaction who have passed the transaction cutoff time.
214
-     * This needs to be very efficient
215
-     * because if there are spam bots afoot there will be LOTS of line items
216
-     * @return int count of how many deleted
217
-     */
218
-    public function delete_line_items_with_no_transaction()
219
-    {
220
-        /** @type WPDB $wpdb */
221
-        global $wpdb;
222
-        $time_to_leave_alone = apply_filters(
223
-            'FHEE__EEM_Line_Item__delete_line_items_with_no_transaction__time_to_leave_alone', WEEK_IN_SECONDS
224
-        );
225
-        $query = $wpdb->prepare(
226
-            'DELETE li
50
+	/**
51
+	 * Tax sub-total is just the total of all the taxes, which should be children
52
+	 * of this line item. There should only ever be one tax sub-total, and it should
53
+	 * be a direct child of. Its quantity and LIN_unit_price = 1.
54
+	 */
55
+	const type_tax_sub_total = 'tax-sub-total';
56
+
57
+	/**
58
+	 * Tax line items indicate a tax applied to all the taxable line items.
59
+	 * Should not have any children line items. Its LIN_unit_price = 0. Its LIN_percent is a percent, not a decimal
60
+	 * (eg 10% tax = 10, not 0.1). Its LIN_total = LIN_unit_price * pre-tax-total. Quantity = 1.
61
+	 */
62
+	const type_tax = 'tax';
63
+
64
+	/**
65
+	 * Indicating individual items purchased, or discounts or surcharges.
66
+	 * The sum of all the regular line items  plus the tax items should equal
67
+	 * the grand total.
68
+	 * Possible children are sub-line-items and cancellations.
69
+	 * For flat items, LIN_unit_price * LIN_quantity = LIN_total. Its LIN_total is the sum of all the children
70
+	 * LIN_totals. Its LIN_percent = 0.
71
+	 * For percent items, its LIN_unit_price = 0. Its LIN_percent is a percent, not a decimal (eg 10% = 10, not 0.1).
72
+	 * Its LIN_total is LIN_percent / 100 * sum of lower-priority sibling line items. Quantity = 1.
73
+	 */
74
+	const type_line_item = 'line-item';
75
+
76
+	/**
77
+	 * Line item indicating all the factors that make a single line item.
78
+	 * Sub-line items should have NO children line items.
79
+	 * For flat sub-items, their quantity should match their parent item, their LIN_unit_price should be this sub-item's
80
+	 * contribution towards the price of ONE of their parent items, and its LIN_total should be
81
+	 *  = LIN_quantity * LIN_unit_price. Its LIN_percent = 0.
82
+	 * For percent sub-items, the quantity should be 1, LIN_unit_price should be 0, and its LIN_total should
83
+	 * = LIN_percent / 100 * sum of lower-priority sibling line items..
84
+	 */
85
+	const type_sub_line_item = 'sub-item';
86
+
87
+	/**
88
+	 * Line item indicating a sub-total (eg total for an event, or pre-tax subtotal).
89
+	 * Direct children should be event subtotals.
90
+	 * Should have quantity of 1, and a LIN_total and LIN_unit_price of the sum of all its sub-items' LIN_totals.
91
+	 *
92
+	 */
93
+	const type_sub_total = 'sub-total';
94
+
95
+	/**
96
+	 * Line item for the grand total of an order. Its direct children
97
+	 * should be tax subtotals and (pre-tax) subtotals, and possibly a regular line item
98
+	 * indicating a transaction-wide discount/surcharge. Should have a quantity of 1, a LIN_total and LIN_unit_price of
99
+	 * the entire order's mount.
100
+	 */
101
+	const type_total = 'total';
102
+
103
+	/**
104
+	 * When a line item is cancelled, a sub-line-item of type 'cancellation'
105
+	 * should be created, indicating the quantity that were cancelled
106
+	 * (because a line item could have a quantity of 1, and its cancellation item
107
+	 * could be for 3, indicating that originally 4 were purchased, but 3 have been
108
+	 * cancelled, and only one remains).
109
+	 * When items are refunded, a cancellation line item should be made, which points
110
+	 * to teh payment model object which actually refunded the payment.
111
+	 * Cancellations should NOT have any children line items; the should NOT affect
112
+	 * any calculations, and are only meant as a record that cancellations have occurred.
113
+	 * Their LIN_percent should be 0.
114
+	 */
115
+	const type_cancellation = 'cancellation';
116
+
117
+	// private instance of the EEM_Line_Item object
118
+	protected static $_instance = NULL;
119
+
120
+
121
+	/**
122
+	 *        private constructor to prevent direct creation
123
+	 * @Constructor
124
+	 * @access protected
125
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any incoming timezone data that gets saved).  Note this just sends the timezone info to the date time model field objects.  Default is NULL (and will be assumed using the set timezone in the 'timezone_string' wp option)
126
+	 * @return \EEM_Line_Item
127
+	 */
128
+	protected function __construct($timezone)
129
+	{
130
+		$this->singular_item = __('Line Item', 'event_espresso');
131
+		$this->plural_item = __('Line Items', 'event_espresso');
132
+
133
+		$this->_tables = array(
134
+			'Line_Item' => new EE_Primary_Table('esp_line_item', 'LIN_ID')
135
+		);
136
+		$line_items_can_be_for = apply_filters('FHEE__EEM_Line_Item__line_items_can_be_for', array('Ticket', 'Price', 'Event'));
137
+		$this->_fields = array(
138
+			'Line_Item' => array(
139
+				'LIN_ID' => new EE_Primary_Key_Int_Field('LIN_ID', __("ID", "event_espresso")),
140
+				'LIN_code' => new EE_Slug_Field('LIN_code', __("Code for index into Cart", "event_espresso"), TRUE),
141
+				'TXN_ID' => new EE_Foreign_Key_Int_Field('TXN_ID', __("Transaction ID", "event_espresso"), TRUE, NULL, 'Transaction'),
142
+				'LIN_name' => new EE_Full_HTML_Field('LIN_name', __("Line Item Name", "event_espresso"), FALSE, ''),
143
+				'LIN_desc' => new EE_Full_HTML_Field('LIN_desc', __("Line Item Description", "event_espresso"), TRUE),
144
+				'LIN_unit_price' => new EE_Money_Field('LIN_unit_price', __("Unit Price", "event_espresso"), FALSE, 0),
145
+				'LIN_percent' => new EE_Float_Field('LIN_percent', __("Percent", "event_espresso"), FALSE, 0),
146
+				'LIN_is_taxable' => new EE_Boolean_Field('LIN_is_taxable', __("Taxable", "event_espresso"), FALSE, FALSE),
147
+				'LIN_order' => new EE_Integer_Field('LIN_order', __("Order of Application towards total of parent", "event_espresso"), FALSE, 1),
148
+				'LIN_total' => new EE_Money_Field('LIN_total', __("Total (unit price x quantity)", "event_espresso"), FALSE, 0),
149
+				'LIN_quantity' => new EE_Integer_Field('LIN_quantity', __("Quantity", "event_espresso"), TRUE, 1),
150
+				'LIN_parent' => new EE_Integer_Field('LIN_parent', __("Parent ID (this item goes towards that Line Item's total)", "event_espresso"), TRUE, NULL),
151
+				'LIN_type' => new EE_Enum_Text_Field('LIN_type', __("Type", "event_espresso"), FALSE, 'line-item', array(
152
+						self::type_line_item => __("Line Item", "event_espresso"),
153
+						self::type_sub_line_item => __("Sub-Item", "event_espresso"),
154
+						self::type_sub_total => __("Subtotal", "event_espresso"),
155
+						self::type_tax_sub_total => __("Tax Subtotal", "event_espresso"),
156
+						self::type_tax => __("Tax", "event_espresso"),
157
+						self::type_total => __("Total", "event_espresso"),
158
+						self::type_cancellation => __('Cancellation', 'event_espresso')
159
+					)
160
+				),
161
+				'OBJ_ID' => new EE_Foreign_Key_Int_Field('OBJ_ID', __('ID of Item purchased.', 'event_espresso'), TRUE, NULL, $line_items_can_be_for),
162
+				'OBJ_type' => new EE_Any_Foreign_Model_Name_Field('OBJ_type', __("Model Name this Line Item is for", "event_espresso"), TRUE, NULL, $line_items_can_be_for),
163
+				'LIN_timestamp' => new EE_Datetime_Field('LIN_timestamp', __('When the line item was created', 'event_espresso'), false, EE_Datetime_Field::now, $timezone),
164
+			)
165
+		);
166
+		$this->_model_relations = array(
167
+			'Transaction' => new EE_Belongs_To_Relation(),
168
+			'Ticket' => new EE_Belongs_To_Any_Relation(),
169
+			'Price' => new EE_Belongs_To_Any_Relation(),
170
+			'Event' => new EE_Belongs_To_Any_Relation()
171
+		);
172
+		$this->_model_chain_to_wp_user = 'Transaction.Registration.Event';
173
+		$this->_caps_slug = 'transactions';
174
+		parent::__construct($timezone);
175
+	}
176
+
177
+
178
+	/**
179
+	 * Gets all the line items for this transaction of the given type
180
+	 * @param string $line_item_type like one of EEM_Line_Item::type_*
181
+	 * @param EE_Transaction|int $transaction
182
+	 * @return EE_Line_Item[]
183
+	 */
184
+	public function get_all_of_type_for_transaction($line_item_type, $transaction)
185
+	{
186
+		$transaction = EEM_Transaction::instance()->ensure_is_ID($transaction);
187
+		return $this->get_all(array(array(
188
+			'LIN_type' => $line_item_type,
189
+			'TXN_ID' => $transaction
190
+		)));
191
+	}
192
+
193
+
194
+	/**
195
+	 * Gets all line items unrelated to tickets that are normal line items
196
+	 * (eg shipping, promotions, and miscellaneous other stuff should probably fit in this category)
197
+	 * @param EE_Transaction|int $transaction
198
+	 * @return EE_Line_Item[]
199
+	 */
200
+	public function get_all_non_ticket_line_items_for_transaction($transaction)
201
+	{
202
+		$transaction = EEM_Transaction::instance()->ensure_is_ID($transaction);
203
+		return $this->get_all(array(array(
204
+			'LIN_type' => self::type_line_item,
205
+			'TXN_ID' => $transaction,
206
+			'OR' => array(
207
+				'OBJ_type*notticket' => array('!=', 'Ticket'),
208
+				'OBJ_type*null' => array('IS_NULL'))
209
+		)));
210
+	}
211
+
212
+	/**
213
+	 * Deletes line items with no transaction who have passed the transaction cutoff time.
214
+	 * This needs to be very efficient
215
+	 * because if there are spam bots afoot there will be LOTS of line items
216
+	 * @return int count of how many deleted
217
+	 */
218
+	public function delete_line_items_with_no_transaction()
219
+	{
220
+		/** @type WPDB $wpdb */
221
+		global $wpdb;
222
+		$time_to_leave_alone = apply_filters(
223
+			'FHEE__EEM_Line_Item__delete_line_items_with_no_transaction__time_to_leave_alone', WEEK_IN_SECONDS
224
+		);
225
+		$query = $wpdb->prepare(
226
+			'DELETE li
227 227
 				FROM ' . $this->table() . ' li
228 228
 				LEFT JOIN ' . EEM_Transaction::instance()->table() . ' t ON li.TXN_ID = t.TXN_ID
229 229
 				WHERE t.TXN_ID IS NULL AND li.LIN_timestamp < %s',
230
-            // use GMT time because that's what TXN_timestamps are in
231
-            date('Y-m-d H:i:s', time() - $time_to_leave_alone)
232
-        );
233
-        return $wpdb->query($query);
234
-    }
235
-
236
-
237
-    /**
238
-     * get_line_item_for_transaction_object
239
-     * Gets a transaction's line item record for a specific object such as a EE_Event or EE_Ticket
240
-     *
241
-     * @param int $TXN_ID
242
-     * @param \EE_Base_Class $object
243
-     * @return EE_Line_Item[]
244
-     */
245
-    public function get_line_item_for_transaction_object($TXN_ID, EE_Base_Class $object)
246
-    {
247
-        return $this->get_all(array(array(
248
-            'TXN_ID' => $TXN_ID,
249
-            'OBJ_type' => str_replace('EE_', '', get_class($object)),
250
-            'OBJ_ID' => $object->ID()
251
-        )));
252
-    }
253
-
254
-
255
-    /**
256
-     * get_object_line_items_for_transaction
257
-     * Gets all of the the object line items for a transaction, based on an object type plus an array of object IDs
258
-     *
259
-     * @param int $TXN_ID
260
-     * @param string $OBJ_type
261
-     * @param array $OBJ_IDs
262
-     * @return EE_Line_Item[]
263
-     */
264
-    public function get_object_line_items_for_transaction($TXN_ID, $OBJ_type = 'Event', $OBJ_IDs = array())
265
-    {
266
-        $query_params = array(
267
-            'OBJ_type' => $OBJ_type,
268
-            // if incoming $OBJ_IDs is an array, then make sure it is formatted correctly for the query
269
-            'OBJ_ID' => is_array($OBJ_IDs) && !isset($OBJ_IDs['IN']) ? array('IN', $OBJ_IDs) : $OBJ_IDs
270
-        );
271
-        if ($TXN_ID) {
272
-            $query_params['TXN_ID'] = $TXN_ID;
273
-        }
274
-        return $this->get_all(array($query_params));
275
-    }
276
-
277
-
278
-    /**
279
-     * get_all_ticket_line_items_for_transaction
280
-     *
281
-     * @param EE_Transaction $transaction
282
-     * @return EE_Line_Item[]
283
-     */
284
-    public function get_all_ticket_line_items_for_transaction(EE_Transaction $transaction)
285
-    {
286
-        return $this->get_all(array(
287
-            array(
288
-                'TXN_ID' => $transaction->ID(),
289
-                'OBJ_type' => 'Ticket',
290
-            )
291
-        ));
292
-    }
293
-
294
-
295
-    /**
296
-     * get_ticket_line_item_for_transaction
297
-     *
298
-     * @param int $TXN_ID
299
-     * @param int $TKT_ID
300
-     * @return \EE_Line_Item
301
-     */
302
-    public function get_ticket_line_item_for_transaction($TXN_ID, $TKT_ID)
303
-    {
304
-        return $this->get_one(array(
305
-            array(
306
-                'TXN_ID' => EEM_Transaction::instance()->ensure_is_ID($TXN_ID),
307
-                'OBJ_ID' => $TKT_ID,
308
-                'OBJ_type' => 'Ticket',
309
-            )
310
-        ));
311
-    }
312
-
313
-
314
-    /**
315
-     * get_existing_promotion_line_item
316
-     * searches the cart for existing line items for the specified promotion
317
-     *
318
-     * @since   1.0.0
319
-     *
320
-     * @param EE_Line_Item $parent_line_item
321
-     * @param EE_Promotion $promotion
322
-     * @return EE_Line_Item
323
-     */
324
-    public function get_existing_promotion_line_item(EE_Line_Item $parent_line_item, EE_Promotion $promotion)
325
-    {
326
-        return $this->get_one(array(
327
-            array(
328
-                'TXN_ID' => $parent_line_item->TXN_ID(),
329
-                'LIN_parent' => $parent_line_item->ID(),
330
-                'OBJ_type' => 'Promotion',
331
-                'OBJ_ID' => $promotion->ID()
332
-            )
333
-        ));
334
-    }
335
-
336
-
337
-    /**
338
-     * get_all_promotion_line_items
339
-     * searches the cart for any and all existing promotion line items
340
-     *
341
-     * @since   1.0.0
342
-     *
343
-     * @param EE_Line_Item $parent_line_item
344
-     * @return EE_Line_Item[]
345
-     */
346
-    public function get_all_promotion_line_items(EE_Line_Item $parent_line_item)
347
-    {
348
-        return $this->get_all(array(
349
-            array(
350
-                'TXN_ID' => $parent_line_item->TXN_ID(),
351
-                'LIN_parent' => $parent_line_item->ID(),
352
-                'OBJ_type' => 'Promotion'
353
-            )
354
-        ));
355
-    }
356
-
357
-    /**
358
-     * Gets the registration's corresponding line item.
359
-     * Note: basically does NOT support having multiple line items for a single ticket,
360
-     * which would happen if some of the registrations had a price modifier while others didn't.
361
-     * In order to support that, we'd probably need a LIN_ID on registrations or something.
362
-     * @param EE_Registration $registration
363
-     * @return EE_Line_ITem
364
-     */
365
-    public function get_line_item_for_registration(EE_Registration $registration)
366
-    {
367
-        return $this->get_one($this->line_item_for_registration_query_params($registration));
368
-    }
369
-
370
-    /**
371
-     * Gets the query params used to retrieve a specific line item for the given registration
372
-     * @param EE_Registration $registration
373
-     * @param array $original_query_params any extra query params you'd like to be merged with
374
-     * @return array like EEM_Base::get_all()'s $query_params
375
-     */
376
-    public function line_item_for_registration_query_params(EE_Registration $registration, $original_query_params = array())
377
-    {
378
-        return array_replace_recursive($original_query_params, array(
379
-            array(
380
-                'OBJ_ID' => $registration->ticket_ID(),
381
-                'OBJ_type' => 'Ticket',
382
-                'TXN_ID' => $registration->transaction_ID()
383
-            )
384
-        ));
385
-    }
386
-
387
-
388
-    /**
389
-     * @return EE_Base_Class[]|EE_Line_Item[]
390
-     * @throws InvalidInterfaceException
391
-     * @throws InvalidDataTypeException
392
-     * @throws EE_Error
393
-     * @throws InvalidArgumentException
394
-     */
395
-    public function get_total_line_items_with_no_transaction()
396
-    {
397
-        return $this->get_total_line_items_for_carts();
398
-    }
399
-
400
-
401
-    /**
402
-     * @return EE_Base_Class[]|EE_Line_Item[]
403
-     * @throws InvalidInterfaceException
404
-     * @throws InvalidDataTypeException
405
-     * @throws EE_Error
406
-     * @throws InvalidArgumentException
407
-     */
408
-    public function get_total_line_items_for_active_carts()
409
-    {
410
-        return $this->get_total_line_items_for_carts(false);
411
-    }
412
-
413
-
414
-    /**
415
-     * @return EE_Base_Class[]|EE_Line_Item[]
416
-     * @throws InvalidInterfaceException
417
-     * @throws InvalidDataTypeException
418
-     * @throws EE_Error
419
-     * @throws InvalidArgumentException
420
-     */
421
-    public function get_total_line_items_for_expired_carts()
422
-    {
423
-        return $this->get_total_line_items_for_carts(true);
424
-    }
425
-
426
-
427
-    /**
428
-     * Returns an array of grand total line items where the TXN_ID is 0.
429
-     * If $expired is set to true, then only line items for expired sessions will be returned.
430
-     * If $expired is set to false, then only line items for active sessions will be returned.
431
-     *
432
-     * @param null $expired
433
-     * @return EE_Base_Class[]|EE_Line_Item[]
434
-     * @throws EE_Error
435
-     * @throws InvalidArgumentException
436
-     * @throws InvalidDataTypeException
437
-     * @throws InvalidInterfaceException
438
-     */
439
-    private function get_total_line_items_for_carts($expired = null)
440
-    {
441
-        $where_params = array(
442
-            'TXN_ID' => 0,
443
-            'LIN_type' => 'total',
444
-        );
445
-        if ($expired !== null) {
446
-            /** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
447
-            $session_lifespan = LoaderFactory::getLoader()->getShared(
448
-                'EventEspresso\core\domain\values\session\SessionLifespan'
449
-            );
450
-            $where_params['LIN_timestamp'] = array(
451
-                $expired ? '<=' : '>',
452
-                $session_lifespan->expiration(),
453
-            );
454
-        }
455
-        return $this->get_all(array($where_params));
456
-    }
457
-
458
-
459
-    /**
460
-     * Returns an array of ticket total line items where the TXN_ID is 0
461
-     * AND the timestamp is older than the session lifespan.
462
-     *
463
-     * @param int $timestamp
464
-     * @return EE_Base_Class[]|EE_Line_Item[]
465
-     * @throws EE_Error
466
-     * @throws InvalidArgumentException
467
-     * @throws InvalidDataTypeException
468
-     * @throws InvalidInterfaceException
469
-     */
470
-    public function getTicketLineItemsForExpiredCarts($timestamp = 0)
471
-    {
472
-        if(! absint($timestamp)) {
473
-            /** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
474
-            $session_lifespan = LoaderFactory::getLoader()->getShared(
475
-                'EventEspresso\core\domain\values\session\SessionLifespan'
476
-            );
477
-            $timestamp = $session_lifespan->expiration();
478
-        }
479
-        return $this->get_all(
480
-            array(
481
-                array(
482
-                    'TXN_ID'        => 0,
483
-                    'OBJ_type'      => 'Ticket',
484
-                    'LIN_timestamp' => array('<=', $timestamp),
485
-                )
486
-            )
487
-        );
488
-    }
230
+			// use GMT time because that's what TXN_timestamps are in
231
+			date('Y-m-d H:i:s', time() - $time_to_leave_alone)
232
+		);
233
+		return $wpdb->query($query);
234
+	}
235
+
236
+
237
+	/**
238
+	 * get_line_item_for_transaction_object
239
+	 * Gets a transaction's line item record for a specific object such as a EE_Event or EE_Ticket
240
+	 *
241
+	 * @param int $TXN_ID
242
+	 * @param \EE_Base_Class $object
243
+	 * @return EE_Line_Item[]
244
+	 */
245
+	public function get_line_item_for_transaction_object($TXN_ID, EE_Base_Class $object)
246
+	{
247
+		return $this->get_all(array(array(
248
+			'TXN_ID' => $TXN_ID,
249
+			'OBJ_type' => str_replace('EE_', '', get_class($object)),
250
+			'OBJ_ID' => $object->ID()
251
+		)));
252
+	}
253
+
254
+
255
+	/**
256
+	 * get_object_line_items_for_transaction
257
+	 * Gets all of the the object line items for a transaction, based on an object type plus an array of object IDs
258
+	 *
259
+	 * @param int $TXN_ID
260
+	 * @param string $OBJ_type
261
+	 * @param array $OBJ_IDs
262
+	 * @return EE_Line_Item[]
263
+	 */
264
+	public function get_object_line_items_for_transaction($TXN_ID, $OBJ_type = 'Event', $OBJ_IDs = array())
265
+	{
266
+		$query_params = array(
267
+			'OBJ_type' => $OBJ_type,
268
+			// if incoming $OBJ_IDs is an array, then make sure it is formatted correctly for the query
269
+			'OBJ_ID' => is_array($OBJ_IDs) && !isset($OBJ_IDs['IN']) ? array('IN', $OBJ_IDs) : $OBJ_IDs
270
+		);
271
+		if ($TXN_ID) {
272
+			$query_params['TXN_ID'] = $TXN_ID;
273
+		}
274
+		return $this->get_all(array($query_params));
275
+	}
276
+
277
+
278
+	/**
279
+	 * get_all_ticket_line_items_for_transaction
280
+	 *
281
+	 * @param EE_Transaction $transaction
282
+	 * @return EE_Line_Item[]
283
+	 */
284
+	public function get_all_ticket_line_items_for_transaction(EE_Transaction $transaction)
285
+	{
286
+		return $this->get_all(array(
287
+			array(
288
+				'TXN_ID' => $transaction->ID(),
289
+				'OBJ_type' => 'Ticket',
290
+			)
291
+		));
292
+	}
293
+
294
+
295
+	/**
296
+	 * get_ticket_line_item_for_transaction
297
+	 *
298
+	 * @param int $TXN_ID
299
+	 * @param int $TKT_ID
300
+	 * @return \EE_Line_Item
301
+	 */
302
+	public function get_ticket_line_item_for_transaction($TXN_ID, $TKT_ID)
303
+	{
304
+		return $this->get_one(array(
305
+			array(
306
+				'TXN_ID' => EEM_Transaction::instance()->ensure_is_ID($TXN_ID),
307
+				'OBJ_ID' => $TKT_ID,
308
+				'OBJ_type' => 'Ticket',
309
+			)
310
+		));
311
+	}
312
+
313
+
314
+	/**
315
+	 * get_existing_promotion_line_item
316
+	 * searches the cart for existing line items for the specified promotion
317
+	 *
318
+	 * @since   1.0.0
319
+	 *
320
+	 * @param EE_Line_Item $parent_line_item
321
+	 * @param EE_Promotion $promotion
322
+	 * @return EE_Line_Item
323
+	 */
324
+	public function get_existing_promotion_line_item(EE_Line_Item $parent_line_item, EE_Promotion $promotion)
325
+	{
326
+		return $this->get_one(array(
327
+			array(
328
+				'TXN_ID' => $parent_line_item->TXN_ID(),
329
+				'LIN_parent' => $parent_line_item->ID(),
330
+				'OBJ_type' => 'Promotion',
331
+				'OBJ_ID' => $promotion->ID()
332
+			)
333
+		));
334
+	}
335
+
336
+
337
+	/**
338
+	 * get_all_promotion_line_items
339
+	 * searches the cart for any and all existing promotion line items
340
+	 *
341
+	 * @since   1.0.0
342
+	 *
343
+	 * @param EE_Line_Item $parent_line_item
344
+	 * @return EE_Line_Item[]
345
+	 */
346
+	public function get_all_promotion_line_items(EE_Line_Item $parent_line_item)
347
+	{
348
+		return $this->get_all(array(
349
+			array(
350
+				'TXN_ID' => $parent_line_item->TXN_ID(),
351
+				'LIN_parent' => $parent_line_item->ID(),
352
+				'OBJ_type' => 'Promotion'
353
+			)
354
+		));
355
+	}
356
+
357
+	/**
358
+	 * Gets the registration's corresponding line item.
359
+	 * Note: basically does NOT support having multiple line items for a single ticket,
360
+	 * which would happen if some of the registrations had a price modifier while others didn't.
361
+	 * In order to support that, we'd probably need a LIN_ID on registrations or something.
362
+	 * @param EE_Registration $registration
363
+	 * @return EE_Line_ITem
364
+	 */
365
+	public function get_line_item_for_registration(EE_Registration $registration)
366
+	{
367
+		return $this->get_one($this->line_item_for_registration_query_params($registration));
368
+	}
369
+
370
+	/**
371
+	 * Gets the query params used to retrieve a specific line item for the given registration
372
+	 * @param EE_Registration $registration
373
+	 * @param array $original_query_params any extra query params you'd like to be merged with
374
+	 * @return array like EEM_Base::get_all()'s $query_params
375
+	 */
376
+	public function line_item_for_registration_query_params(EE_Registration $registration, $original_query_params = array())
377
+	{
378
+		return array_replace_recursive($original_query_params, array(
379
+			array(
380
+				'OBJ_ID' => $registration->ticket_ID(),
381
+				'OBJ_type' => 'Ticket',
382
+				'TXN_ID' => $registration->transaction_ID()
383
+			)
384
+		));
385
+	}
386
+
387
+
388
+	/**
389
+	 * @return EE_Base_Class[]|EE_Line_Item[]
390
+	 * @throws InvalidInterfaceException
391
+	 * @throws InvalidDataTypeException
392
+	 * @throws EE_Error
393
+	 * @throws InvalidArgumentException
394
+	 */
395
+	public function get_total_line_items_with_no_transaction()
396
+	{
397
+		return $this->get_total_line_items_for_carts();
398
+	}
399
+
400
+
401
+	/**
402
+	 * @return EE_Base_Class[]|EE_Line_Item[]
403
+	 * @throws InvalidInterfaceException
404
+	 * @throws InvalidDataTypeException
405
+	 * @throws EE_Error
406
+	 * @throws InvalidArgumentException
407
+	 */
408
+	public function get_total_line_items_for_active_carts()
409
+	{
410
+		return $this->get_total_line_items_for_carts(false);
411
+	}
412
+
413
+
414
+	/**
415
+	 * @return EE_Base_Class[]|EE_Line_Item[]
416
+	 * @throws InvalidInterfaceException
417
+	 * @throws InvalidDataTypeException
418
+	 * @throws EE_Error
419
+	 * @throws InvalidArgumentException
420
+	 */
421
+	public function get_total_line_items_for_expired_carts()
422
+	{
423
+		return $this->get_total_line_items_for_carts(true);
424
+	}
425
+
426
+
427
+	/**
428
+	 * Returns an array of grand total line items where the TXN_ID is 0.
429
+	 * If $expired is set to true, then only line items for expired sessions will be returned.
430
+	 * If $expired is set to false, then only line items for active sessions will be returned.
431
+	 *
432
+	 * @param null $expired
433
+	 * @return EE_Base_Class[]|EE_Line_Item[]
434
+	 * @throws EE_Error
435
+	 * @throws InvalidArgumentException
436
+	 * @throws InvalidDataTypeException
437
+	 * @throws InvalidInterfaceException
438
+	 */
439
+	private function get_total_line_items_for_carts($expired = null)
440
+	{
441
+		$where_params = array(
442
+			'TXN_ID' => 0,
443
+			'LIN_type' => 'total',
444
+		);
445
+		if ($expired !== null) {
446
+			/** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
447
+			$session_lifespan = LoaderFactory::getLoader()->getShared(
448
+				'EventEspresso\core\domain\values\session\SessionLifespan'
449
+			);
450
+			$where_params['LIN_timestamp'] = array(
451
+				$expired ? '<=' : '>',
452
+				$session_lifespan->expiration(),
453
+			);
454
+		}
455
+		return $this->get_all(array($where_params));
456
+	}
457
+
458
+
459
+	/**
460
+	 * Returns an array of ticket total line items where the TXN_ID is 0
461
+	 * AND the timestamp is older than the session lifespan.
462
+	 *
463
+	 * @param int $timestamp
464
+	 * @return EE_Base_Class[]|EE_Line_Item[]
465
+	 * @throws EE_Error
466
+	 * @throws InvalidArgumentException
467
+	 * @throws InvalidDataTypeException
468
+	 * @throws InvalidInterfaceException
469
+	 */
470
+	public function getTicketLineItemsForExpiredCarts($timestamp = 0)
471
+	{
472
+		if(! absint($timestamp)) {
473
+			/** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
474
+			$session_lifespan = LoaderFactory::getLoader()->getShared(
475
+				'EventEspresso\core\domain\values\session\SessionLifespan'
476
+			);
477
+			$timestamp = $session_lifespan->expiration();
478
+		}
479
+		return $this->get_all(
480
+			array(
481
+				array(
482
+					'TXN_ID'        => 0,
483
+					'OBJ_type'      => 'Ticket',
484
+					'LIN_timestamp' => array('<=', $timestamp),
485
+				)
486
+			)
487
+		);
488
+	}
489 489
 
490 490
 }
Please login to merge, or discard this patch.
modules/ticket_sales_monitor/EED_Ticket_Sales_Monitor.module.php 2 patches
Indentation   +1066 added lines, -1066 removed lines patch added patch discarded remove patch
@@ -24,1073 +24,1073 @@
 block discarded – undo
24 24
 class EED_Ticket_Sales_Monitor extends EED_Module
25 25
 {
26 26
 
27
-    const debug = false;    //	true false
28
-
29
-    private static $nl = '';
30
-
31
-    /**
32
-     * an array of raw ticket data from EED_Ticket_Selector
33
-     *
34
-     * @var array $ticket_selections
35
-     */
36
-    protected $ticket_selections = array();
37
-
38
-    /**
39
-     * the raw ticket data from EED_Ticket_Selector is organized in rows
40
-     * according to how they are displayed in the actual Ticket_Selector
41
-     * this tracks the current row being processed
42
-     *
43
-     * @var int $current_row
44
-     */
45
-    protected $current_row = 0;
46
-
47
-    /**
48
-     * an array for tracking names of tickets that have sold out
49
-     *
50
-     * @var array $sold_out_tickets
51
-     */
52
-    protected $sold_out_tickets = array();
53
-
54
-    /**
55
-     * an array for tracking names of tickets that have had their quantities reduced
56
-     *
57
-     * @var array $decremented_tickets
58
-     */
59
-    protected $decremented_tickets = array();
60
-
61
-
62
-
63
-    /**
64
-     * set_hooks - for hooking into EE Core, other modules, etc
65
-     *
66
-     * @return    void
67
-     */
68
-    public static function set_hooks()
69
-    {
70
-        self::$nl = defined('EE_TESTS_DIR')? "\n" : '<br />';
71
-        // release tickets for expired carts
72
-        add_action(
73
-            'EED_Ticket_Selector__process_ticket_selections__before',
74
-            array('EED_Ticket_Sales_Monitor', 'release_tickets_for_expired_carts'),
75
-            1
76
-        );
77
-        // check ticket reserves AFTER MER does it's check (hence priority 20)
78
-        add_filter(
79
-            'FHEE__EE_Ticket_Selector___add_ticket_to_cart__ticket_qty',
80
-            array('EED_Ticket_Sales_Monitor', 'validate_ticket_sale'),
81
-            20,
82
-            3
83
-        );
84
-        // add notices for sold out tickets
85
-        add_action(
86
-            'AHEE__EE_Ticket_Selector__process_ticket_selections__after_tickets_added_to_cart',
87
-            array('EED_Ticket_Sales_Monitor', 'post_notices'),
88
-            10
89
-        );
90
-        // handle ticket quantities adjusted in cart
91
-        //add_action(
92
-        //	'FHEE__EED_Multi_Event_Registration__adjust_line_item_quantity__line_item_quantity_updated',
93
-        //	array( 'EED_Ticket_Sales_Monitor', 'ticket_quantity_updated' ),
94
-        //	10, 2
95
-        //);
96
-        // handle tickets deleted from cart
97
-        add_action(
98
-            'FHEE__EED_Multi_Event_Registration__delete_ticket__ticket_removed_from_cart',
99
-            array('EED_Ticket_Sales_Monitor', 'ticket_removed_from_cart'),
100
-            10,
101
-            2
102
-        );
103
-        // handle emptied carts
104
-        add_action(
105
-            'AHEE__EE_Session__reset_cart__before_reset',
106
-            array('EED_Ticket_Sales_Monitor', 'session_cart_reset'),
107
-            10,
108
-            1
109
-        );
110
-        add_action(
111
-            'AHEE__EED_Multi_Event_Registration__empty_event_cart__before_delete_cart',
112
-            array('EED_Ticket_Sales_Monitor', 'session_cart_reset'),
113
-            10,
114
-            1
115
-        );
116
-        // handle cancelled registrations
117
-        add_action(
118
-            'AHEE__EE_Session__reset_checkout__before_reset',
119
-            array('EED_Ticket_Sales_Monitor', 'session_checkout_reset'),
120
-            10,
121
-            1
122
-        );
123
-        // cron tasks
124
-        add_action(
125
-            'AHEE__EE_Cron_Tasks__process_expired_transactions__abandoned_transaction',
126
-            array('EED_Ticket_Sales_Monitor', 'process_abandoned_transactions'),
127
-            10,
128
-            1
129
-        );
130
-        add_action(
131
-            'AHEE__EE_Cron_Tasks__process_expired_transactions__incomplete_transaction',
132
-            array('EED_Ticket_Sales_Monitor', 'process_abandoned_transactions'),
133
-            10,
134
-            1
135
-        );
136
-        add_action(
137
-            'AHEE__EE_Cron_Tasks__process_expired_transactions__failed_transaction',
138
-            array('EED_Ticket_Sales_Monitor', 'process_failed_transactions'),
139
-            10,
140
-            1
141
-        );
142
-    }
143
-
144
-
145
-
146
-    /**
147
-     * set_hooks_admin - for hooking into EE Admin Core, other modules, etc
148
-     *
149
-     * @return void
150
-     */
151
-    public static function set_hooks_admin()
152
-    {
153
-        EED_Ticket_Sales_Monitor::set_hooks();
154
-    }
155
-
156
-
157
-
158
-    /**
159
-     * @return EED_Ticket_Sales_Monitor|EED_Module
160
-     */
161
-    public static function instance()
162
-    {
163
-        return parent::get_instance(__CLASS__);
164
-    }
165
-
166
-
167
-
168
-    /**
169
-     * @param WP_Query $WP_Query
170
-     * @return    void
171
-     */
172
-    public function run($WP_Query)
173
-    {
174
-    }
175
-
176
-
177
-
178
-    /********************************** PRE_TICKET_SALES  **********************************/
179
-
180
-
181
-
182
-    /**
183
-     * Retrieves grand totals from the line items that have no TXN ID
184
-     * and timestamps less than the current time minus the session lifespan.
185
-     * These are carts that have been abandoned before the "registrant" even attempted to checkout.
186
-     * We're going to release the tickets for these line items before attempting to add more to the cart.
187
-     *
188
-     * @return void
189
-     * @throws DomainException
190
-     * @throws EE_Error
191
-     * @throws InvalidArgumentException
192
-     * @throws InvalidDataTypeException
193
-     * @throws InvalidInterfaceException
194
-     * @throws UnexpectedEntityException
195
-     */
196
-    public static function release_tickets_for_expired_carts()
197
-    {
198
-        if (self::debug) {
199
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '()';
200
-        }
201
-        do_action('AHEE__EED_Ticket_Sales_Monitor__release_tickets_for_expired_carts__begin');
202
-        $expired_ticket_IDs = array();
203
-        /** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
204
-        $session_lifespan = LoaderFactory::getLoader()->getShared(
205
-            'EventEspresso\core\domain\values\session\SessionLifespan'
206
-        );
207
-        $timestamp = $session_lifespan->expiration();
208
-        $expired_ticket_line_items = EEM_Line_Item::instance()->getTicketLineItemsForExpiredCarts($timestamp);
209
-        if (self::debug) {
210
-            echo self::$nl . ' . time(): ' . time();
211
-            echo self::$nl . ' . time() as date: ' . date('Y-m-d H:i a');
212
-            echo self::$nl . ' . session expiration: ' . $session_lifespan->expiration();
213
-            echo self::$nl . ' . session expiration as date: ' . date('Y-m-d H:i a', $session_lifespan->expiration());
214
-            echo self::$nl . ' . timestamp: ' . $timestamp;
215
-            echo self::$nl . ' . $expired_ticket_line_items: ' . count($expired_ticket_line_items);
216
-        }
217
-        if (! empty($expired_ticket_line_items)) {
218
-            foreach ($expired_ticket_line_items as $expired_ticket_line_item) {
219
-                if (! $expired_ticket_line_item instanceof EE_Line_Item) {
220
-                    continue;
221
-                }
222
-                $expired_ticket_IDs[ $expired_ticket_line_item->OBJ_ID() ] = $expired_ticket_line_item->OBJ_ID();
223
-                if (self::debug) {
224
-                    echo self::$nl . ' . $expired_ticket_line_item->OBJ_ID(): ' . $expired_ticket_line_item->OBJ_ID();
225
-                    echo self::$nl . ' . $expired_ticket_line_item->timestamp(): ' . date('Y-m-d h:i a',
226
-                            $expired_ticket_line_item->timestamp(true));
227
-                }
228
-            }
229
-            if (! empty($expired_ticket_IDs)) {
230
-                EED_Ticket_Sales_Monitor::release_reservations_for_tickets(
231
-                    \EEM_Ticket::instance()->get_tickets_with_IDs($expired_ticket_IDs),
232
-                    array(),
233
-                    __FUNCTION__
234
-                );
235
-                // now  let's get rid of expired line items so that they can't interfere with tracking
236
-                EED_Ticket_Sales_Monitor::clear_expired_line_items_with_no_transaction($timestamp);
237
-            }
238
-        }
239
-        do_action(
240
-            'AHEE__EED_Ticket_Sales_Monitor__release_tickets_for_expired_carts__end',
241
-            $expired_ticket_IDs,
242
-            $expired_ticket_line_items
243
-        );
244
-    }
245
-
246
-
247
-
248
-    /********************************** VALIDATE_TICKET_SALE  **********************************/
249
-
250
-
251
-
252
-    /**
253
-     * callback for 'FHEE__EED_Ticket_Selector__process_ticket_selections__valid_post_data'
254
-     *
255
-     * @param int       $qty
256
-     * @param EE_Ticket $ticket
257
-     * @return bool
258
-     * @throws UnexpectedEntityException
259
-     * @throws EE_Error
260
-     */
261
-    public static function validate_ticket_sale($qty = 1, EE_Ticket $ticket)
262
-    {
263
-        $qty = absint($qty);
264
-        if ($qty > 0) {
265
-            $qty = EED_Ticket_Sales_Monitor::instance()->_validate_ticket_sale($ticket, $qty);
266
-        }
267
-        if (self::debug) {
268
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '()';
269
-            echo self::$nl . self::$nl . '<b> RETURNED QTY: ' . $qty . '</b>';
270
-        }
271
-        return $qty;
272
-    }
273
-
274
-
275
-
276
-    /**
277
-     * checks whether an individual ticket is available for purchase based on datetime, and ticket details
278
-     *
279
-     * @param   EE_Ticket $ticket
280
-     * @param int         $qty
281
-     * @return int
282
-     * @throws UnexpectedEntityException
283
-     * @throws EE_Error
284
-     */
285
-    protected function _validate_ticket_sale(EE_Ticket $ticket, $qty = 1)
286
-    {
287
-        if (self::debug) {
288
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
289
-        }
290
-        if (! $ticket instanceof EE_Ticket) {
291
-            return 0;
292
-        }
293
-        if (self::debug) {
294
-            echo self::$nl . '<b> . ticket->ID: ' . $ticket->ID() . '</b>';
295
-            echo self::$nl . ' . original ticket->reserved: ' . $ticket->reserved();
296
-        }
297
-        $ticket->refresh_from_db();
298
-        // first let's determine the ticket availability based on sales
299
-        $available = $ticket->qty('saleable');
300
-        if (self::debug) {
301
-            echo self::$nl . ' . . . ticket->qty: ' . $ticket->qty();
302
-            echo self::$nl . ' . . . ticket->sold: ' . $ticket->sold();
303
-            echo self::$nl . ' . . . ticket->reserved: ' . $ticket->reserved();
304
-            echo self::$nl . ' . . . ticket->qty(saleable): ' . $ticket->qty('saleable');
305
-            echo self::$nl . ' . . . available: ' . $available;
306
-        }
307
-        if ($available < 1) {
308
-            $this->_ticket_sold_out($ticket);
309
-            return 0;
310
-        }
311
-        if (self::debug) {
312
-            echo self::$nl . ' . . . qty: ' . $qty;
313
-        }
314
-        if ($available < $qty) {
315
-            $qty = $available;
316
-            if (self::debug) {
317
-                echo self::$nl . ' . . . QTY ADJUSTED: ' . $qty;
318
-            }
319
-            $this->_ticket_quantity_decremented($ticket);
320
-        }
321
-        $this->_reserve_ticket($ticket, $qty);
322
-        return $qty;
323
-    }
324
-
325
-
326
-
327
-    /**
328
-     * increments ticket reserved based on quantity passed
329
-     *
330
-     * @param    EE_Ticket $ticket
331
-     * @param int          $quantity
332
-     * @return bool
333
-     * @throws EE_Error
334
-     */
335
-    protected function _reserve_ticket(EE_Ticket $ticket, $quantity = 1)
336
-    {
337
-        if (self::debug) {
338
-            echo self::$nl . self::$nl . ' . . . INCREASE RESERVED: ' . $quantity;
339
-        }
340
-        $ticket->increase_reserved($quantity, 'TicketSalesMonitor:'. __LINE__);
341
-        return $ticket->save();
342
-    }
343
-
344
-
345
-
346
-    /**
347
-     * @param  EE_Ticket $ticket
348
-     * @param  int       $quantity
349
-     * @return bool
350
-     * @throws EE_Error
351
-     */
352
-    protected function _release_reserved_ticket(EE_Ticket $ticket, $quantity = 1)
353
-    {
354
-        if (self::debug) {
355
-            echo self::$nl . ' . . . ticket->ID: ' . $ticket->ID();
356
-            echo self::$nl . ' . . . ticket->reserved: ' . $ticket->reserved();
357
-        }
358
-        $ticket->decrease_reserved($quantity, true, 'TicketSalesMonitor:'. __LINE__);
359
-        if (self::debug) {
360
-            echo self::$nl . ' . . . ticket->reserved: ' . $ticket->reserved();
361
-        }
362
-        return $ticket->save() ? 1 : 0;
363
-    }
364
-
365
-
366
-
367
-    /**
368
-     * removes quantities within the ticket selector based on zero ticket availability
369
-     *
370
-     * @param    EE_Ticket $ticket
371
-     * @return    void
372
-     * @throws UnexpectedEntityException
373
-     * @throws EE_Error
374
-     */
375
-    protected function _ticket_sold_out(EE_Ticket $ticket)
376
-    {
377
-        if (self::debug) {
378
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
379
-            echo self::$nl . ' . . ticket->name: ' . $this->_get_ticket_and_event_name($ticket);
380
-        }
381
-        $this->sold_out_tickets[] = $this->_get_ticket_and_event_name($ticket);
382
-    }
383
-
384
-
385
-
386
-    /**
387
-     * adjusts quantities within the ticket selector based on decreased ticket availability
388
-     *
389
-     * @param    EE_Ticket $ticket
390
-     * @return void
391
-     * @throws UnexpectedEntityException
392
-     * @throws EE_Error
393
-     */
394
-    protected function _ticket_quantity_decremented(EE_Ticket $ticket)
395
-    {
396
-        if (self::debug) {
397
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
398
-            echo self::$nl . ' . . ticket->name: ' . $this->_get_ticket_and_event_name($ticket);
399
-        }
400
-        $this->decremented_tickets[] = $this->_get_ticket_and_event_name($ticket);
401
-    }
402
-
403
-
404
-
405
-    /**
406
-     * builds string out of ticket and event name
407
-     *
408
-     * @param    EE_Ticket $ticket
409
-     * @return string
410
-     * @throws UnexpectedEntityException
411
-     * @throws EE_Error
412
-     */
413
-    protected function _get_ticket_and_event_name(EE_Ticket $ticket)
414
-    {
415
-        $event = $ticket->get_related_event();
416
-        if ($event instanceof EE_Event) {
417
-            $ticket_name = sprintf(
418
-                _x('%1$s for %2$s', 'ticket name for event name', 'event_espresso'),
419
-                $ticket->name(),
420
-                $event->name()
421
-            );
422
-        } else {
423
-            $ticket_name = $ticket->name();
424
-        }
425
-        return $ticket_name;
426
-    }
427
-
428
-
429
-
430
-    /********************************** EVENT CART  **********************************/
431
-
432
-
433
-
434
-    /**
435
-     * releases or reserves ticket(s) based on quantity passed
436
-     *
437
-     * @param  EE_Line_Item $line_item
438
-     * @param  int          $quantity
439
-     * @return void
440
-     * @throws EE_Error
441
-     * @throws InvalidArgumentException
442
-     * @throws InvalidDataTypeException
443
-     * @throws InvalidInterfaceException
444
-     */
445
-    public static function ticket_quantity_updated(EE_Line_Item $line_item, $quantity = 1)
446
-    {
447
-        $ticket = EEM_Ticket::instance()->get_one_by_ID(absint($line_item->OBJ_ID()));
448
-        if ($ticket instanceof EE_Ticket) {
449
-            $ticket->add_extra_meta(
450
-                EE_Ticket::META_KEY_TICKET_RESERVATIONS,
451
-                __LINE__ . ') ' . __METHOD__ . '()'
452
-            );
453
-            if ($quantity > 0) {
454
-                EED_Ticket_Sales_Monitor::instance()->_reserve_ticket($ticket, $quantity);
455
-            } else {
456
-                EED_Ticket_Sales_Monitor::instance()->_release_reserved_ticket($ticket, $quantity);
457
-            }
458
-        }
459
-    }
460
-
461
-
462
-
463
-    /**
464
-     * releases reserved ticket(s) based on quantity passed
465
-     *
466
-     * @param  EE_Ticket $ticket
467
-     * @param  int       $quantity
468
-     * @return void
469
-     * @throws EE_Error
470
-     */
471
-    public static function ticket_removed_from_cart(EE_Ticket $ticket, $quantity = 1)
472
-    {
473
-        $ticket->add_extra_meta(
474
-            EE_Ticket::META_KEY_TICKET_RESERVATIONS,
475
-            __LINE__ . ') ' . __METHOD__ . '()'
476
-        );
477
-        EED_Ticket_Sales_Monitor::instance()->_release_reserved_ticket($ticket, $quantity);
478
-    }
479
-
480
-
481
-
482
-    /********************************** POST_NOTICES  **********************************/
483
-
484
-
485
-
486
-    /**
487
-     * @return void
488
-     * @throws EE_Error
489
-     * @throws InvalidArgumentException
490
-     * @throws ReflectionException
491
-     * @throws InvalidDataTypeException
492
-     * @throws InvalidInterfaceException
493
-     */
494
-    public static function post_notices()
495
-    {
496
-        EED_Ticket_Sales_Monitor::instance()->_post_notices();
497
-    }
498
-
499
-
500
-
501
-    /**
502
-     * @return void
503
-     * @throws EE_Error
504
-     * @throws InvalidArgumentException
505
-     * @throws ReflectionException
506
-     * @throws InvalidDataTypeException
507
-     * @throws InvalidInterfaceException
508
-     */
509
-    protected function _post_notices()
510
-    {
511
-        if (self::debug) {
512
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
513
-        }
514
-        $refresh_msg    = '';
515
-        $none_added_msg = '';
516
-        if (defined('DOING_AJAX') && DOING_AJAX) {
517
-            $refresh_msg    = __(
518
-                'Please refresh the page to view updated ticket quantities.',
519
-                'event_espresso'
520
-            );
521
-            $none_added_msg = __('No tickets were added for the event.', 'event_espresso');
522
-        }
523
-        if (! empty($this->sold_out_tickets)) {
524
-            EE_Error::add_attention(
525
-                sprintf(
526
-                    apply_filters(
527
-                        'FHEE__EED_Ticket_Sales_Monitor___post_notices__sold_out_tickets_notice',
528
-                        __(
529
-                            'We\'re sorry...%1$sThe following items have sold out since you first viewed this page, and can no longer be registered for:%1$s%1$s%2$s%1$s%1$sPlease note that availability can change at any time due to cancellations, so please check back again later if registration for this event(s) is important to you.%1$s%1$s%3$s%1$s%4$s%1$s',
530
-                            'event_espresso'
531
-                        )
532
-                    ),
533
-                    '<br />',
534
-                    implode('<br />', $this->sold_out_tickets),
535
-                    $none_added_msg,
536
-                    $refresh_msg
537
-                )
538
-            );
539
-            // alter code flow in the Ticket Selector for better UX
540
-            add_filter('FHEE__EED_Ticket_Selector__process_ticket_selections__tckts_slctd', '__return_true');
541
-            add_filter('FHEE__EED_Ticket_Selector__process_ticket_selections__success', '__return_false');
542
-            $this->sold_out_tickets = array();
543
-            // and reset the cart
544
-            EED_Ticket_Sales_Monitor::session_cart_reset(EE_Registry::instance()->SSN);
545
-        }
546
-        if (! empty($this->decremented_tickets)) {
547
-            EE_Error::add_attention(
548
-                sprintf(
549
-                    apply_filters(
550
-                        'FHEE__EED_Ticket_Sales_Monitor___ticket_quantity_decremented__notice',
551
-                        __(
552
-                            'We\'re sorry...%1$sDue to sales that have occurred since you first viewed the last page, the following items have had their quantities adjusted to match the current available amount:%1$s%1$s%2$s%1$s%1$sPlease note that availability can change at any time due to cancellations, so please check back again later if registration for this event(s) is important to you.%1$s%1$s%3$s%1$s%4$s%1$s',
553
-                            'event_espresso'
554
-                        )
555
-                    ),
556
-                    '<br />',
557
-                    implode('<br />', $this->decremented_tickets),
558
-                    $none_added_msg,
559
-                    $refresh_msg
560
-                )
561
-            );
562
-            $this->decremented_tickets = array();
563
-        }
564
-    }
565
-
566
-
567
-
568
-    /********************************** RELEASE_ALL_RESERVED_TICKETS_FOR_TRANSACTION  **********************************/
569
-
570
-
571
-
572
-    /**
573
-     * releases reserved tickets for all registrations of an EE_Transaction
574
-     * by default, will NOT release tickets for finalized transactions
575
-     *
576
-     * @param    EE_Transaction $transaction
577
-     * @return int
578
-     * @throws EE_Error
579
-     * @throws InvalidSessionDataException
580
-     */
581
-    protected function _release_all_reserved_tickets_for_transaction(EE_Transaction $transaction)
582
-    {
583
-        if (self::debug) {
584
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
585
-            echo self::$nl . ' . transaction->ID: ' . $transaction->ID();
586
-            echo self::$nl . ' . TXN status_ID: ' . $transaction->status_ID();
587
-        }
588
-        // check if 'finalize_registration' step has been completed...
589
-        $finalized = $transaction->reg_step_completed('finalize_registration');
590
-        if (self::debug) {
591
-            // DEBUG LOG
592
-            EEH_Debug_Tools::log(
593
-                __CLASS__,
594
-                __FUNCTION__,
595
-                __LINE__,
596
-                array('finalized' => $finalized),
597
-                false,
598
-                'EE_Transaction: ' . $transaction->ID()
599
-            );
600
-        }
601
-        // how many tickets were released
602
-        $count = 0;
603
-        if (self::debug) {
604
-            echo self::$nl . ' . . . TXN finalized: ' . $finalized;
605
-        }
606
-        $release_tickets_with_TXN_status = array(
607
-            EEM_Transaction::failed_status_code,
608
-            EEM_Transaction::abandoned_status_code,
609
-            EEM_Transaction::incomplete_status_code,
610
-        );
611
-        $events = array();
612
-        // if the session is getting cleared BEFORE the TXN has been finalized or the transaction is not completed
613
-        if (! $finalized || in_array($transaction->status_ID(), $release_tickets_with_TXN_status, true)) {
614
-            // cancel any reserved tickets for registrations that were not approved
615
-            $registrations = $transaction->registrations();
616
-            if (self::debug) {
617
-                echo self::$nl . ' . . . # registrations: ' . count($registrations);
618
-                $reg    = reset($registrations);
619
-                $ticket = $reg->ticket();
620
-                if ($ticket instanceof EE_Ticket) {
621
-                    $ticket->add_extra_meta(
622
-                        EE_Ticket::META_KEY_TICKET_RESERVATIONS,
623
-                        __LINE__ . ') Release All Tickets TXN:' . $transaction->ID()
624
-                    );
625
-                }
626
-            }
627
-            if (! empty($registrations)) {
628
-                foreach ($registrations as $registration) {
629
-                    if (
630
-                        $registration instanceof EE_Registration
631
-                        && $this->_release_reserved_ticket_for_registration($registration, $transaction)
632
-                    ) {
633
-                        $count++;
634
-                        $events[ $registration->event_ID() ] = $registration->event();
635
-                    }
636
-                }
637
-            }
638
-        }
639
-        if ($events !== array()) {
640
-            foreach ($events as $event) {
641
-                /** @var EE_Event $event */
642
-                $event->perform_sold_out_status_check();
643
-            }
644
-        }
645
-        return $count;
646
-    }
647
-
648
-
649
-
650
-    /**
651
-     * releases reserved tickets for an EE_Registration
652
-     * by default, will NOT release tickets for APPROVED registrations
653
-     *
654
-     * @param EE_Registration $registration
655
-     * @param EE_Transaction  $transaction
656
-     * @return int
657
-     * @throws EE_Error
658
-     */
659
-    protected function _release_reserved_ticket_for_registration(
660
-        EE_Registration $registration,
661
-        EE_Transaction $transaction
662
-    ) {
663
-        $STS_ID = $transaction->status_ID();
664
-        if (self::debug) {
665
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
666
-            echo self::$nl . ' . . registration->ID: ' . $registration->ID();
667
-            echo self::$nl . ' . . registration->status_ID: ' . $registration->status_ID();
668
-            echo self::$nl . ' . . transaction->status_ID(): ' . $STS_ID;
669
-        }
670
-        if (
671
-            // release Tickets for Failed Transactions and Abandoned Transactions
672
-            $STS_ID === EEM_Transaction::failed_status_code
673
-            || $STS_ID === EEM_Transaction::abandoned_status_code
674
-            || (
675
-                // also release Tickets for Incomplete Transactions, but ONLY if the Registrations are NOT Approved
676
-                $STS_ID === EEM_Transaction::incomplete_status_code
677
-                && $registration->status_ID() !== EEM_Registration::status_id_approved
678
-            )
679
-        ) {
680
-            if (self::debug) {
681
-                echo self::$nl . self::$nl . ' . . RELEASE RESERVED TICKET';
682
-                $rsrvd = $registration->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true);
683
-                echo self::$nl . ' . . . registration HAS_RESERVED_TICKET_KEY: ';
684
-                var_dump($rsrvd);
685
-            }
686
-            $registration->release_reserved_ticket(true, 'TicketSalesMonitor:'. __LINE__);
687
-            return 1;
688
-        }
689
-        return 0;
690
-    }
691
-
692
-
693
-
694
-    /********************************** SESSION_CART_RESET  **********************************/
695
-
696
-
697
-
698
-    /**
699
-     * callback hooked into 'AHEE__EE_Session__reset_cart__before_reset'
700
-     *
701
-     * @param EE_Session $session
702
-     * @return void
703
-     * @throws EE_Error
704
-     * @throws InvalidArgumentException
705
-     * @throws ReflectionException
706
-     * @throws InvalidDataTypeException
707
-     * @throws InvalidInterfaceException
708
-     */
709
-    public static function session_cart_reset(EE_Session $session)
710
-    {
711
-        if (self::debug) {
712
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
713
-        }
714
-        // first check of the session has a valid Checkout object
715
-        $checkout = $session->checkout();
716
-        if ($checkout instanceof EE_Checkout) {
717
-            // and use that to clear ticket reservations because it will update the associated registration meta data
718
-            EED_Ticket_Sales_Monitor::instance()->_session_checkout_reset($checkout);
719
-            return;
720
-        }
721
-        $cart = $session->cart();
722
-        if ($cart instanceof EE_Cart) {
723
-            if (self::debug) {
724
-                echo self::$nl . self::$nl . ' cart instance of EE_Cart: ';
725
-            }
726
-            EED_Ticket_Sales_Monitor::instance()->_session_cart_reset($cart, $session);
727
-        } else {
728
-            if (self::debug) {
729
-                echo self::$nl . self::$nl . ' invalid EE_Cart: ';
730
-                var_export($cart, true);
731
-            }
732
-        }
733
-    }
734
-
735
-
736
-
737
-    /**
738
-     * releases reserved tickets in the EE_Cart
739
-     *
740
-     * @param EE_Cart $cart
741
-     * @return void
742
-     * @throws EE_Error
743
-     * @throws InvalidArgumentException
744
-     * @throws ReflectionException
745
-     * @throws InvalidDataTypeException
746
-     * @throws InvalidInterfaceException
747
-     */
748
-    protected function _session_cart_reset(EE_Cart $cart, EE_Session $session)
749
-    {
750
-        if (self::debug) {
751
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
752
-        }
753
-        EE_Registry::instance()->load_helper('Line_Item');
754
-        $ticket_line_items = $cart->get_tickets();
755
-        if (empty($ticket_line_items)) {
756
-            return;
757
-        }
758
-        foreach ($ticket_line_items as $ticket_line_item) {
759
-            if (self::debug) {
760
-                echo self::$nl . ' . ticket_line_item->ID(): ' . $ticket_line_item->ID();
761
-            }
762
-            if ($ticket_line_item instanceof EE_Line_Item && $ticket_line_item->OBJ_type() === 'Ticket') {
763
-                if (self::debug) {
764
-                    echo self::$nl . ' . . ticket_line_item->OBJ_ID(): ' . $ticket_line_item->OBJ_ID();
765
-                }
766
-                $ticket = EEM_Ticket::instance()->get_one_by_ID($ticket_line_item->OBJ_ID());
767
-                if ($ticket instanceof EE_Ticket) {
768
-                    if (self::debug) {
769
-                        echo self::$nl . ' . . ticket->ID(): ' . $ticket->ID();
770
-                        echo self::$nl . ' . . ticket_line_item->quantity(): ' . $ticket_line_item->quantity();
771
-                    }
772
-                    $ticket->add_extra_meta(
773
-                        EE_Ticket::META_KEY_TICKET_RESERVATIONS,
774
-                        __LINE__ . ') ' . __METHOD__ . '() SID = ' . $session->id()
775
-                    );
776
-                    $this->_release_reserved_ticket($ticket, $ticket_line_item->quantity());
777
-                }
778
-            }
779
-        }
780
-        if (self::debug) {
781
-            echo self::$nl . self::$nl . ' RESET COMPLETED ';
782
-        }
783
-    }
784
-
785
-
786
-
787
-    /********************************** SESSION_CHECKOUT_RESET  **********************************/
788
-
789
-
790
-
791
-    /**
792
-     * callback hooked into 'AHEE__EE_Session__reset_checkout__before_reset'
793
-     *
794
-     * @param EE_Session $session
795
-     * @return void
796
-     * @throws EE_Error
797
-     * @throws InvalidSessionDataException
798
-     */
799
-    public static function session_checkout_reset(EE_Session $session)
800
-    {
801
-        $checkout = $session->checkout();
802
-        if ($checkout instanceof EE_Checkout) {
803
-            EED_Ticket_Sales_Monitor::instance()->_session_checkout_reset($checkout);
804
-        }
805
-    }
806
-
807
-
808
-
809
-    /**
810
-     * releases reserved tickets for the EE_Checkout->transaction
811
-     *
812
-     * @param EE_Checkout $checkout
813
-     * @return void
814
-     * @throws EE_Error
815
-     * @throws InvalidSessionDataException
816
-     */
817
-    protected function _session_checkout_reset(EE_Checkout $checkout)
818
-    {
819
-        if (self::debug) {
820
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
821
-        }
822
-        // we want to release the each registration's reserved tickets if the session was cleared, but not if this is a revisit
823
-        if ($checkout->revisit || ! $checkout->transaction instanceof EE_Transaction) {
824
-            return;
825
-        }
826
-        $this->_release_all_reserved_tickets_for_transaction($checkout->transaction);
827
-    }
828
-
829
-
830
-
831
-    /********************************** SESSION_EXPIRED_RESET  **********************************/
832
-
833
-
834
-
835
-    /**
836
-     * @param    EE_Session $session
837
-     * @return    void
838
-     */
839
-    public static function session_expired_reset(EE_Session $session)
840
-    {
841
-    }
842
-
843
-
844
-
845
-    /********************************** PROCESS_ABANDONED_TRANSACTIONS  **********************************/
846
-
847
-
848
-
849
-    /**
850
-     * releases reserved tickets for all registrations of an ABANDONED EE_Transaction
851
-     * by default, will NOT release tickets for free transactions, or any that have received a payment
852
-     *
853
-     * @param EE_Transaction $transaction
854
-     * @return void
855
-     * @throws EE_Error
856
-     * @throws InvalidSessionDataException
857
-     */
858
-    public static function process_abandoned_transactions(EE_Transaction $transaction)
859
-    {
860
-        // is this TXN free or has any money been paid towards this TXN? If so, then leave it alone
861
-        if ($transaction->is_free() || $transaction->paid() > 0) {
862
-            if (self::debug) {
863
-                // DEBUG LOG
864
-                EEH_Debug_Tools::log(
865
-                    __CLASS__,
866
-                    __FUNCTION__,
867
-                    __LINE__,
868
-                    array($transaction),
869
-                    false,
870
-                    'EE_Transaction: ' . $transaction->ID()
871
-                );
872
-            }
873
-            return;
874
-        }
875
-        // have their been any successful payments made ?
876
-        $payments = $transaction->payments();
877
-        foreach ($payments as $payment) {
878
-            if ($payment instanceof EE_Payment && $payment->status() === EEM_Payment::status_id_approved) {
879
-                if (self::debug) {
880
-                    // DEBUG LOG
881
-                    EEH_Debug_Tools::log(
882
-                        __CLASS__,
883
-                        __FUNCTION__,
884
-                        __LINE__,
885
-                        array($payment),
886
-                        false,
887
-                        'EE_Transaction: ' . $transaction->ID()
888
-                    );
889
-                }
890
-                return;
891
-            }
892
-        }
893
-        // since you haven't even attempted to pay for your ticket...
894
-        EED_Ticket_Sales_Monitor::instance()->_release_all_reserved_tickets_for_transaction($transaction);
895
-    }
896
-
897
-
898
-
899
-    /********************************** PROCESS_FAILED_TRANSACTIONS  **********************************/
900
-
901
-
902
-
903
-    /**
904
-     * releases reserved tickets for absolutely ALL registrations of a FAILED EE_Transaction
905
-     *
906
-     * @param EE_Transaction $transaction
907
-     * @return void
908
-     * @throws EE_Error
909
-     * @throws InvalidSessionDataException
910
-     */
911
-    public static function process_failed_transactions(EE_Transaction $transaction)
912
-    {
913
-        // since you haven't even attempted to pay for your ticket...
914
-        EED_Ticket_Sales_Monitor::instance()->_release_all_reserved_tickets_for_transaction($transaction);
915
-    }
916
-
917
-
918
-
919
-    /********************************** RESET RESERVATION COUNTS  *********************************/
920
-
921
-
922
-
923
-    /**
924
-     * Resets all ticket and datetime reserved counts to zero
925
-     * Tickets that are currently associated with a Transaction that is in progress
926
-     *
927
-     * @throws EE_Error
928
-     * @throws DomainException
929
-     * @throws InvalidDataTypeException
930
-     * @throws InvalidInterfaceException
931
-     * @throws InvalidArgumentException
932
-     * @throws UnexpectedEntityException
933
-     */
934
-    public static function reset_reservation_counts()
935
-    {
936
-        /** @var EE_Line_Item[] $valid_reserved_tickets */
937
-        $valid_reserved_tickets = array();
938
-        /** @var EE_Transaction[] $transactions_not_in_progress */
939
-        $transactions_not_in_progress = EEM_Transaction::instance()->get_transactions_not_in_progress();
940
-        foreach ($transactions_not_in_progress as $transaction) {
941
-            // if this TXN has been fully completed, then skip it
942
-            if ($transaction->reg_step_completed('finalize_registration')) {
943
-                continue;
944
-            }
945
-            $total_line_item = $transaction->total_line_item();
946
-            // $transaction_in_progress->line
947
-            if (! $total_line_item instanceof EE_Line_Item) {
948
-                throw new DomainException(
949
-                    esc_html__(
950
-                        'Transaction does not have a valid Total Line Item associated with it.',
951
-                        'event_espresso'
952
-                    )
953
-                );
954
-            }
955
-            $valid_reserved_tickets += EED_Ticket_Sales_Monitor::get_ticket_line_items_for_grand_total(
956
-                $total_line_item
957
-            );
958
-        }
959
-        $total_line_items = EEM_Line_Item::instance()->get_total_line_items_for_active_carts();
960
-        foreach ($total_line_items as $total_line_item) {
961
-            $valid_reserved_tickets += EED_Ticket_Sales_Monitor::get_ticket_line_items_for_grand_total(
962
-                $total_line_item
963
-            );
964
-        }
965
-        $tickets_with_reservations = EEM_Ticket::instance()->get_tickets_with_reservations();
966
-        return EED_Ticket_Sales_Monitor::release_reservations_for_tickets(
967
-            $tickets_with_reservations,
968
-            $valid_reserved_tickets,
969
-            __FUNCTION__
970
-        );
971
-    }
972
-
973
-
974
-
975
-    /**
976
-     * @param EE_Line_Item $total_line_item
977
-     * @return EE_Line_Item[]
978
-     */
979
-    private static function get_ticket_line_items_for_grand_total(EE_Line_Item $total_line_item)
980
-    {
981
-        /** @var EE_Line_Item[] $valid_reserved_tickets */
982
-        $valid_reserved_tickets = array();
983
-        $ticket_line_items      = EEH_Line_Item::get_ticket_line_items($total_line_item);
984
-        foreach ($ticket_line_items as $ticket_line_item) {
985
-            if ($ticket_line_item instanceof EE_Line_Item) {
986
-                $valid_reserved_tickets[] = $ticket_line_item;
987
-            }
988
-        }
989
-        return $valid_reserved_tickets;
990
-    }
991
-
992
-
993
-
994
-    /**
995
-     * @param EE_Ticket[]    $tickets_with_reservations
996
-     * @param EE_Line_Item[] $valid_reserved_ticket_line_items
997
-     * @return int
998
-     * @throws UnexpectedEntityException
999
-     * @throws DomainException
1000
-     * @throws EE_Error
1001
-     */
1002
-    private static function release_reservations_for_tickets(
1003
-        array $tickets_with_reservations,
1004
-        array $valid_reserved_ticket_line_items = array(),
1005
-        $source
1006
-    ) {
1007
-        if (self::debug) {
1008
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '()';
1009
-        }
1010
-        $total_tickets_released = 0;
1011
-        $sold_out_events = array();
1012
-        foreach ($tickets_with_reservations as $ticket_with_reservations) {
1013
-            if (! $ticket_with_reservations instanceof EE_Ticket) {
1014
-                continue;
1015
-            }
1016
-            $reserved_qty = $ticket_with_reservations->reserved();
1017
-            if (self::debug) {
1018
-                echo self::$nl . ' . $ticket_with_reservations->ID(): ' . $ticket_with_reservations->ID();
1019
-                echo self::$nl . ' . $reserved_qty: ' . $reserved_qty;
1020
-            }
1021
-            foreach ($valid_reserved_ticket_line_items as $valid_reserved_ticket_line_item) {
1022
-                if (
1023
-                    $valid_reserved_ticket_line_item instanceof EE_Line_Item
1024
-                    && $valid_reserved_ticket_line_item->OBJ_ID() === $ticket_with_reservations->ID()
1025
-                ) {
1026
-                    if (self::debug) {
1027
-                        echo self::$nl . ' . $valid_reserved_ticket_line_item->quantity(): ' . $valid_reserved_ticket_line_item->quantity();
1028
-                    }
1029
-                    $reserved_qty -= $valid_reserved_ticket_line_item->quantity();
1030
-                }
1031
-            }
1032
-            if ($reserved_qty > 0) {
1033
-                $ticket_with_reservations->add_extra_meta(
1034
-                    EE_Ticket::META_KEY_TICKET_RESERVATIONS,
1035
-                    __LINE__ . ') ' . $source . '()'
1036
-                );
1037
-                $ticket_with_reservations->decrease_reserved($reserved_qty, true, 'TicketSalesMonitor:'. __LINE__);
1038
-                $ticket_with_reservations->save();
1039
-                $total_tickets_released += $reserved_qty;
1040
-                $event = $ticket_with_reservations->get_related_event();
1041
-                // track sold out events
1042
-                if ($event instanceof EE_Event && $event->is_sold_out()) {
1043
-                    $sold_out_events[] = $event;
1044
-                }
1045
-            }
1046
-        }
1047
-        if (self::debug) {
1048
-            echo self::$nl . ' . $total_tickets_released: ' . $total_tickets_released;
1049
-        }
1050
-        // double check whether sold out events should remain sold out after releasing tickets
1051
-        if($sold_out_events !== array()){
1052
-            foreach ($sold_out_events as $sold_out_event) {
1053
-                /** @var EE_Event $sold_out_event */
1054
-                $sold_out_event->perform_sold_out_status_check();
1055
-            }
1056
-        }
1057
-        return $total_tickets_released;
1058
-    }
1059
-
1060
-
1061
-
1062
-    /********************************** SHUTDOWN  **********************************/
1063
-
1064
-
1065
-
1066
-    /**
1067
-     * @param int $timestamp
1068
-     * @return false|int
1069
-     * @throws EE_Error
1070
-     * @throws InvalidArgumentException
1071
-     * @throws InvalidDataTypeException
1072
-     * @throws InvalidInterfaceException
1073
-     */
1074
-    public static function clear_expired_line_items_with_no_transaction($timestamp = 0)
1075
-    {
1076
-       /** @type WPDB $wpdb */
1077
-        global $wpdb;
1078
-        if (! absint($timestamp)) {
1079
-            /** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
1080
-            $session_lifespan = LoaderFactory::getLoader()->getShared(
1081
-                'EventEspresso\core\domain\values\session\SessionLifespan'
1082
-            );
1083
-            $timestamp = $session_lifespan->expiration();
1084
-        }
1085
-         return $wpdb->query(
1086
-            $wpdb->prepare(
1087
-                'DELETE FROM ' . EEM_Line_Item::instance()->table() . '
27
+	const debug = false;    //	true false
28
+
29
+	private static $nl = '';
30
+
31
+	/**
32
+	 * an array of raw ticket data from EED_Ticket_Selector
33
+	 *
34
+	 * @var array $ticket_selections
35
+	 */
36
+	protected $ticket_selections = array();
37
+
38
+	/**
39
+	 * the raw ticket data from EED_Ticket_Selector is organized in rows
40
+	 * according to how they are displayed in the actual Ticket_Selector
41
+	 * this tracks the current row being processed
42
+	 *
43
+	 * @var int $current_row
44
+	 */
45
+	protected $current_row = 0;
46
+
47
+	/**
48
+	 * an array for tracking names of tickets that have sold out
49
+	 *
50
+	 * @var array $sold_out_tickets
51
+	 */
52
+	protected $sold_out_tickets = array();
53
+
54
+	/**
55
+	 * an array for tracking names of tickets that have had their quantities reduced
56
+	 *
57
+	 * @var array $decremented_tickets
58
+	 */
59
+	protected $decremented_tickets = array();
60
+
61
+
62
+
63
+	/**
64
+	 * set_hooks - for hooking into EE Core, other modules, etc
65
+	 *
66
+	 * @return    void
67
+	 */
68
+	public static function set_hooks()
69
+	{
70
+		self::$nl = defined('EE_TESTS_DIR')? "\n" : '<br />';
71
+		// release tickets for expired carts
72
+		add_action(
73
+			'EED_Ticket_Selector__process_ticket_selections__before',
74
+			array('EED_Ticket_Sales_Monitor', 'release_tickets_for_expired_carts'),
75
+			1
76
+		);
77
+		// check ticket reserves AFTER MER does it's check (hence priority 20)
78
+		add_filter(
79
+			'FHEE__EE_Ticket_Selector___add_ticket_to_cart__ticket_qty',
80
+			array('EED_Ticket_Sales_Monitor', 'validate_ticket_sale'),
81
+			20,
82
+			3
83
+		);
84
+		// add notices for sold out tickets
85
+		add_action(
86
+			'AHEE__EE_Ticket_Selector__process_ticket_selections__after_tickets_added_to_cart',
87
+			array('EED_Ticket_Sales_Monitor', 'post_notices'),
88
+			10
89
+		);
90
+		// handle ticket quantities adjusted in cart
91
+		//add_action(
92
+		//	'FHEE__EED_Multi_Event_Registration__adjust_line_item_quantity__line_item_quantity_updated',
93
+		//	array( 'EED_Ticket_Sales_Monitor', 'ticket_quantity_updated' ),
94
+		//	10, 2
95
+		//);
96
+		// handle tickets deleted from cart
97
+		add_action(
98
+			'FHEE__EED_Multi_Event_Registration__delete_ticket__ticket_removed_from_cart',
99
+			array('EED_Ticket_Sales_Monitor', 'ticket_removed_from_cart'),
100
+			10,
101
+			2
102
+		);
103
+		// handle emptied carts
104
+		add_action(
105
+			'AHEE__EE_Session__reset_cart__before_reset',
106
+			array('EED_Ticket_Sales_Monitor', 'session_cart_reset'),
107
+			10,
108
+			1
109
+		);
110
+		add_action(
111
+			'AHEE__EED_Multi_Event_Registration__empty_event_cart__before_delete_cart',
112
+			array('EED_Ticket_Sales_Monitor', 'session_cart_reset'),
113
+			10,
114
+			1
115
+		);
116
+		// handle cancelled registrations
117
+		add_action(
118
+			'AHEE__EE_Session__reset_checkout__before_reset',
119
+			array('EED_Ticket_Sales_Monitor', 'session_checkout_reset'),
120
+			10,
121
+			1
122
+		);
123
+		// cron tasks
124
+		add_action(
125
+			'AHEE__EE_Cron_Tasks__process_expired_transactions__abandoned_transaction',
126
+			array('EED_Ticket_Sales_Monitor', 'process_abandoned_transactions'),
127
+			10,
128
+			1
129
+		);
130
+		add_action(
131
+			'AHEE__EE_Cron_Tasks__process_expired_transactions__incomplete_transaction',
132
+			array('EED_Ticket_Sales_Monitor', 'process_abandoned_transactions'),
133
+			10,
134
+			1
135
+		);
136
+		add_action(
137
+			'AHEE__EE_Cron_Tasks__process_expired_transactions__failed_transaction',
138
+			array('EED_Ticket_Sales_Monitor', 'process_failed_transactions'),
139
+			10,
140
+			1
141
+		);
142
+	}
143
+
144
+
145
+
146
+	/**
147
+	 * set_hooks_admin - for hooking into EE Admin Core, other modules, etc
148
+	 *
149
+	 * @return void
150
+	 */
151
+	public static function set_hooks_admin()
152
+	{
153
+		EED_Ticket_Sales_Monitor::set_hooks();
154
+	}
155
+
156
+
157
+
158
+	/**
159
+	 * @return EED_Ticket_Sales_Monitor|EED_Module
160
+	 */
161
+	public static function instance()
162
+	{
163
+		return parent::get_instance(__CLASS__);
164
+	}
165
+
166
+
167
+
168
+	/**
169
+	 * @param WP_Query $WP_Query
170
+	 * @return    void
171
+	 */
172
+	public function run($WP_Query)
173
+	{
174
+	}
175
+
176
+
177
+
178
+	/********************************** PRE_TICKET_SALES  **********************************/
179
+
180
+
181
+
182
+	/**
183
+	 * Retrieves grand totals from the line items that have no TXN ID
184
+	 * and timestamps less than the current time minus the session lifespan.
185
+	 * These are carts that have been abandoned before the "registrant" even attempted to checkout.
186
+	 * We're going to release the tickets for these line items before attempting to add more to the cart.
187
+	 *
188
+	 * @return void
189
+	 * @throws DomainException
190
+	 * @throws EE_Error
191
+	 * @throws InvalidArgumentException
192
+	 * @throws InvalidDataTypeException
193
+	 * @throws InvalidInterfaceException
194
+	 * @throws UnexpectedEntityException
195
+	 */
196
+	public static function release_tickets_for_expired_carts()
197
+	{
198
+		if (self::debug) {
199
+			echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '()';
200
+		}
201
+		do_action('AHEE__EED_Ticket_Sales_Monitor__release_tickets_for_expired_carts__begin');
202
+		$expired_ticket_IDs = array();
203
+		/** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
204
+		$session_lifespan = LoaderFactory::getLoader()->getShared(
205
+			'EventEspresso\core\domain\values\session\SessionLifespan'
206
+		);
207
+		$timestamp = $session_lifespan->expiration();
208
+		$expired_ticket_line_items = EEM_Line_Item::instance()->getTicketLineItemsForExpiredCarts($timestamp);
209
+		if (self::debug) {
210
+			echo self::$nl . ' . time(): ' . time();
211
+			echo self::$nl . ' . time() as date: ' . date('Y-m-d H:i a');
212
+			echo self::$nl . ' . session expiration: ' . $session_lifespan->expiration();
213
+			echo self::$nl . ' . session expiration as date: ' . date('Y-m-d H:i a', $session_lifespan->expiration());
214
+			echo self::$nl . ' . timestamp: ' . $timestamp;
215
+			echo self::$nl . ' . $expired_ticket_line_items: ' . count($expired_ticket_line_items);
216
+		}
217
+		if (! empty($expired_ticket_line_items)) {
218
+			foreach ($expired_ticket_line_items as $expired_ticket_line_item) {
219
+				if (! $expired_ticket_line_item instanceof EE_Line_Item) {
220
+					continue;
221
+				}
222
+				$expired_ticket_IDs[ $expired_ticket_line_item->OBJ_ID() ] = $expired_ticket_line_item->OBJ_ID();
223
+				if (self::debug) {
224
+					echo self::$nl . ' . $expired_ticket_line_item->OBJ_ID(): ' . $expired_ticket_line_item->OBJ_ID();
225
+					echo self::$nl . ' . $expired_ticket_line_item->timestamp(): ' . date('Y-m-d h:i a',
226
+							$expired_ticket_line_item->timestamp(true));
227
+				}
228
+			}
229
+			if (! empty($expired_ticket_IDs)) {
230
+				EED_Ticket_Sales_Monitor::release_reservations_for_tickets(
231
+					\EEM_Ticket::instance()->get_tickets_with_IDs($expired_ticket_IDs),
232
+					array(),
233
+					__FUNCTION__
234
+				);
235
+				// now  let's get rid of expired line items so that they can't interfere with tracking
236
+				EED_Ticket_Sales_Monitor::clear_expired_line_items_with_no_transaction($timestamp);
237
+			}
238
+		}
239
+		do_action(
240
+			'AHEE__EED_Ticket_Sales_Monitor__release_tickets_for_expired_carts__end',
241
+			$expired_ticket_IDs,
242
+			$expired_ticket_line_items
243
+		);
244
+	}
245
+
246
+
247
+
248
+	/********************************** VALIDATE_TICKET_SALE  **********************************/
249
+
250
+
251
+
252
+	/**
253
+	 * callback for 'FHEE__EED_Ticket_Selector__process_ticket_selections__valid_post_data'
254
+	 *
255
+	 * @param int       $qty
256
+	 * @param EE_Ticket $ticket
257
+	 * @return bool
258
+	 * @throws UnexpectedEntityException
259
+	 * @throws EE_Error
260
+	 */
261
+	public static function validate_ticket_sale($qty = 1, EE_Ticket $ticket)
262
+	{
263
+		$qty = absint($qty);
264
+		if ($qty > 0) {
265
+			$qty = EED_Ticket_Sales_Monitor::instance()->_validate_ticket_sale($ticket, $qty);
266
+		}
267
+		if (self::debug) {
268
+			echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '()';
269
+			echo self::$nl . self::$nl . '<b> RETURNED QTY: ' . $qty . '</b>';
270
+		}
271
+		return $qty;
272
+	}
273
+
274
+
275
+
276
+	/**
277
+	 * checks whether an individual ticket is available for purchase based on datetime, and ticket details
278
+	 *
279
+	 * @param   EE_Ticket $ticket
280
+	 * @param int         $qty
281
+	 * @return int
282
+	 * @throws UnexpectedEntityException
283
+	 * @throws EE_Error
284
+	 */
285
+	protected function _validate_ticket_sale(EE_Ticket $ticket, $qty = 1)
286
+	{
287
+		if (self::debug) {
288
+			echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
289
+		}
290
+		if (! $ticket instanceof EE_Ticket) {
291
+			return 0;
292
+		}
293
+		if (self::debug) {
294
+			echo self::$nl . '<b> . ticket->ID: ' . $ticket->ID() . '</b>';
295
+			echo self::$nl . ' . original ticket->reserved: ' . $ticket->reserved();
296
+		}
297
+		$ticket->refresh_from_db();
298
+		// first let's determine the ticket availability based on sales
299
+		$available = $ticket->qty('saleable');
300
+		if (self::debug) {
301
+			echo self::$nl . ' . . . ticket->qty: ' . $ticket->qty();
302
+			echo self::$nl . ' . . . ticket->sold: ' . $ticket->sold();
303
+			echo self::$nl . ' . . . ticket->reserved: ' . $ticket->reserved();
304
+			echo self::$nl . ' . . . ticket->qty(saleable): ' . $ticket->qty('saleable');
305
+			echo self::$nl . ' . . . available: ' . $available;
306
+		}
307
+		if ($available < 1) {
308
+			$this->_ticket_sold_out($ticket);
309
+			return 0;
310
+		}
311
+		if (self::debug) {
312
+			echo self::$nl . ' . . . qty: ' . $qty;
313
+		}
314
+		if ($available < $qty) {
315
+			$qty = $available;
316
+			if (self::debug) {
317
+				echo self::$nl . ' . . . QTY ADJUSTED: ' . $qty;
318
+			}
319
+			$this->_ticket_quantity_decremented($ticket);
320
+		}
321
+		$this->_reserve_ticket($ticket, $qty);
322
+		return $qty;
323
+	}
324
+
325
+
326
+
327
+	/**
328
+	 * increments ticket reserved based on quantity passed
329
+	 *
330
+	 * @param    EE_Ticket $ticket
331
+	 * @param int          $quantity
332
+	 * @return bool
333
+	 * @throws EE_Error
334
+	 */
335
+	protected function _reserve_ticket(EE_Ticket $ticket, $quantity = 1)
336
+	{
337
+		if (self::debug) {
338
+			echo self::$nl . self::$nl . ' . . . INCREASE RESERVED: ' . $quantity;
339
+		}
340
+		$ticket->increase_reserved($quantity, 'TicketSalesMonitor:'. __LINE__);
341
+		return $ticket->save();
342
+	}
343
+
344
+
345
+
346
+	/**
347
+	 * @param  EE_Ticket $ticket
348
+	 * @param  int       $quantity
349
+	 * @return bool
350
+	 * @throws EE_Error
351
+	 */
352
+	protected function _release_reserved_ticket(EE_Ticket $ticket, $quantity = 1)
353
+	{
354
+		if (self::debug) {
355
+			echo self::$nl . ' . . . ticket->ID: ' . $ticket->ID();
356
+			echo self::$nl . ' . . . ticket->reserved: ' . $ticket->reserved();
357
+		}
358
+		$ticket->decrease_reserved($quantity, true, 'TicketSalesMonitor:'. __LINE__);
359
+		if (self::debug) {
360
+			echo self::$nl . ' . . . ticket->reserved: ' . $ticket->reserved();
361
+		}
362
+		return $ticket->save() ? 1 : 0;
363
+	}
364
+
365
+
366
+
367
+	/**
368
+	 * removes quantities within the ticket selector based on zero ticket availability
369
+	 *
370
+	 * @param    EE_Ticket $ticket
371
+	 * @return    void
372
+	 * @throws UnexpectedEntityException
373
+	 * @throws EE_Error
374
+	 */
375
+	protected function _ticket_sold_out(EE_Ticket $ticket)
376
+	{
377
+		if (self::debug) {
378
+			echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
379
+			echo self::$nl . ' . . ticket->name: ' . $this->_get_ticket_and_event_name($ticket);
380
+		}
381
+		$this->sold_out_tickets[] = $this->_get_ticket_and_event_name($ticket);
382
+	}
383
+
384
+
385
+
386
+	/**
387
+	 * adjusts quantities within the ticket selector based on decreased ticket availability
388
+	 *
389
+	 * @param    EE_Ticket $ticket
390
+	 * @return void
391
+	 * @throws UnexpectedEntityException
392
+	 * @throws EE_Error
393
+	 */
394
+	protected function _ticket_quantity_decremented(EE_Ticket $ticket)
395
+	{
396
+		if (self::debug) {
397
+			echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
398
+			echo self::$nl . ' . . ticket->name: ' . $this->_get_ticket_and_event_name($ticket);
399
+		}
400
+		$this->decremented_tickets[] = $this->_get_ticket_and_event_name($ticket);
401
+	}
402
+
403
+
404
+
405
+	/**
406
+	 * builds string out of ticket and event name
407
+	 *
408
+	 * @param    EE_Ticket $ticket
409
+	 * @return string
410
+	 * @throws UnexpectedEntityException
411
+	 * @throws EE_Error
412
+	 */
413
+	protected function _get_ticket_and_event_name(EE_Ticket $ticket)
414
+	{
415
+		$event = $ticket->get_related_event();
416
+		if ($event instanceof EE_Event) {
417
+			$ticket_name = sprintf(
418
+				_x('%1$s for %2$s', 'ticket name for event name', 'event_espresso'),
419
+				$ticket->name(),
420
+				$event->name()
421
+			);
422
+		} else {
423
+			$ticket_name = $ticket->name();
424
+		}
425
+		return $ticket_name;
426
+	}
427
+
428
+
429
+
430
+	/********************************** EVENT CART  **********************************/
431
+
432
+
433
+
434
+	/**
435
+	 * releases or reserves ticket(s) based on quantity passed
436
+	 *
437
+	 * @param  EE_Line_Item $line_item
438
+	 * @param  int          $quantity
439
+	 * @return void
440
+	 * @throws EE_Error
441
+	 * @throws InvalidArgumentException
442
+	 * @throws InvalidDataTypeException
443
+	 * @throws InvalidInterfaceException
444
+	 */
445
+	public static function ticket_quantity_updated(EE_Line_Item $line_item, $quantity = 1)
446
+	{
447
+		$ticket = EEM_Ticket::instance()->get_one_by_ID(absint($line_item->OBJ_ID()));
448
+		if ($ticket instanceof EE_Ticket) {
449
+			$ticket->add_extra_meta(
450
+				EE_Ticket::META_KEY_TICKET_RESERVATIONS,
451
+				__LINE__ . ') ' . __METHOD__ . '()'
452
+			);
453
+			if ($quantity > 0) {
454
+				EED_Ticket_Sales_Monitor::instance()->_reserve_ticket($ticket, $quantity);
455
+			} else {
456
+				EED_Ticket_Sales_Monitor::instance()->_release_reserved_ticket($ticket, $quantity);
457
+			}
458
+		}
459
+	}
460
+
461
+
462
+
463
+	/**
464
+	 * releases reserved ticket(s) based on quantity passed
465
+	 *
466
+	 * @param  EE_Ticket $ticket
467
+	 * @param  int       $quantity
468
+	 * @return void
469
+	 * @throws EE_Error
470
+	 */
471
+	public static function ticket_removed_from_cart(EE_Ticket $ticket, $quantity = 1)
472
+	{
473
+		$ticket->add_extra_meta(
474
+			EE_Ticket::META_KEY_TICKET_RESERVATIONS,
475
+			__LINE__ . ') ' . __METHOD__ . '()'
476
+		);
477
+		EED_Ticket_Sales_Monitor::instance()->_release_reserved_ticket($ticket, $quantity);
478
+	}
479
+
480
+
481
+
482
+	/********************************** POST_NOTICES  **********************************/
483
+
484
+
485
+
486
+	/**
487
+	 * @return void
488
+	 * @throws EE_Error
489
+	 * @throws InvalidArgumentException
490
+	 * @throws ReflectionException
491
+	 * @throws InvalidDataTypeException
492
+	 * @throws InvalidInterfaceException
493
+	 */
494
+	public static function post_notices()
495
+	{
496
+		EED_Ticket_Sales_Monitor::instance()->_post_notices();
497
+	}
498
+
499
+
500
+
501
+	/**
502
+	 * @return void
503
+	 * @throws EE_Error
504
+	 * @throws InvalidArgumentException
505
+	 * @throws ReflectionException
506
+	 * @throws InvalidDataTypeException
507
+	 * @throws InvalidInterfaceException
508
+	 */
509
+	protected function _post_notices()
510
+	{
511
+		if (self::debug) {
512
+			echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
513
+		}
514
+		$refresh_msg    = '';
515
+		$none_added_msg = '';
516
+		if (defined('DOING_AJAX') && DOING_AJAX) {
517
+			$refresh_msg    = __(
518
+				'Please refresh the page to view updated ticket quantities.',
519
+				'event_espresso'
520
+			);
521
+			$none_added_msg = __('No tickets were added for the event.', 'event_espresso');
522
+		}
523
+		if (! empty($this->sold_out_tickets)) {
524
+			EE_Error::add_attention(
525
+				sprintf(
526
+					apply_filters(
527
+						'FHEE__EED_Ticket_Sales_Monitor___post_notices__sold_out_tickets_notice',
528
+						__(
529
+							'We\'re sorry...%1$sThe following items have sold out since you first viewed this page, and can no longer be registered for:%1$s%1$s%2$s%1$s%1$sPlease note that availability can change at any time due to cancellations, so please check back again later if registration for this event(s) is important to you.%1$s%1$s%3$s%1$s%4$s%1$s',
530
+							'event_espresso'
531
+						)
532
+					),
533
+					'<br />',
534
+					implode('<br />', $this->sold_out_tickets),
535
+					$none_added_msg,
536
+					$refresh_msg
537
+				)
538
+			);
539
+			// alter code flow in the Ticket Selector for better UX
540
+			add_filter('FHEE__EED_Ticket_Selector__process_ticket_selections__tckts_slctd', '__return_true');
541
+			add_filter('FHEE__EED_Ticket_Selector__process_ticket_selections__success', '__return_false');
542
+			$this->sold_out_tickets = array();
543
+			// and reset the cart
544
+			EED_Ticket_Sales_Monitor::session_cart_reset(EE_Registry::instance()->SSN);
545
+		}
546
+		if (! empty($this->decremented_tickets)) {
547
+			EE_Error::add_attention(
548
+				sprintf(
549
+					apply_filters(
550
+						'FHEE__EED_Ticket_Sales_Monitor___ticket_quantity_decremented__notice',
551
+						__(
552
+							'We\'re sorry...%1$sDue to sales that have occurred since you first viewed the last page, the following items have had their quantities adjusted to match the current available amount:%1$s%1$s%2$s%1$s%1$sPlease note that availability can change at any time due to cancellations, so please check back again later if registration for this event(s) is important to you.%1$s%1$s%3$s%1$s%4$s%1$s',
553
+							'event_espresso'
554
+						)
555
+					),
556
+					'<br />',
557
+					implode('<br />', $this->decremented_tickets),
558
+					$none_added_msg,
559
+					$refresh_msg
560
+				)
561
+			);
562
+			$this->decremented_tickets = array();
563
+		}
564
+	}
565
+
566
+
567
+
568
+	/********************************** RELEASE_ALL_RESERVED_TICKETS_FOR_TRANSACTION  **********************************/
569
+
570
+
571
+
572
+	/**
573
+	 * releases reserved tickets for all registrations of an EE_Transaction
574
+	 * by default, will NOT release tickets for finalized transactions
575
+	 *
576
+	 * @param    EE_Transaction $transaction
577
+	 * @return int
578
+	 * @throws EE_Error
579
+	 * @throws InvalidSessionDataException
580
+	 */
581
+	protected function _release_all_reserved_tickets_for_transaction(EE_Transaction $transaction)
582
+	{
583
+		if (self::debug) {
584
+			echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
585
+			echo self::$nl . ' . transaction->ID: ' . $transaction->ID();
586
+			echo self::$nl . ' . TXN status_ID: ' . $transaction->status_ID();
587
+		}
588
+		// check if 'finalize_registration' step has been completed...
589
+		$finalized = $transaction->reg_step_completed('finalize_registration');
590
+		if (self::debug) {
591
+			// DEBUG LOG
592
+			EEH_Debug_Tools::log(
593
+				__CLASS__,
594
+				__FUNCTION__,
595
+				__LINE__,
596
+				array('finalized' => $finalized),
597
+				false,
598
+				'EE_Transaction: ' . $transaction->ID()
599
+			);
600
+		}
601
+		// how many tickets were released
602
+		$count = 0;
603
+		if (self::debug) {
604
+			echo self::$nl . ' . . . TXN finalized: ' . $finalized;
605
+		}
606
+		$release_tickets_with_TXN_status = array(
607
+			EEM_Transaction::failed_status_code,
608
+			EEM_Transaction::abandoned_status_code,
609
+			EEM_Transaction::incomplete_status_code,
610
+		);
611
+		$events = array();
612
+		// if the session is getting cleared BEFORE the TXN has been finalized or the transaction is not completed
613
+		if (! $finalized || in_array($transaction->status_ID(), $release_tickets_with_TXN_status, true)) {
614
+			// cancel any reserved tickets for registrations that were not approved
615
+			$registrations = $transaction->registrations();
616
+			if (self::debug) {
617
+				echo self::$nl . ' . . . # registrations: ' . count($registrations);
618
+				$reg    = reset($registrations);
619
+				$ticket = $reg->ticket();
620
+				if ($ticket instanceof EE_Ticket) {
621
+					$ticket->add_extra_meta(
622
+						EE_Ticket::META_KEY_TICKET_RESERVATIONS,
623
+						__LINE__ . ') Release All Tickets TXN:' . $transaction->ID()
624
+					);
625
+				}
626
+			}
627
+			if (! empty($registrations)) {
628
+				foreach ($registrations as $registration) {
629
+					if (
630
+						$registration instanceof EE_Registration
631
+						&& $this->_release_reserved_ticket_for_registration($registration, $transaction)
632
+					) {
633
+						$count++;
634
+						$events[ $registration->event_ID() ] = $registration->event();
635
+					}
636
+				}
637
+			}
638
+		}
639
+		if ($events !== array()) {
640
+			foreach ($events as $event) {
641
+				/** @var EE_Event $event */
642
+				$event->perform_sold_out_status_check();
643
+			}
644
+		}
645
+		return $count;
646
+	}
647
+
648
+
649
+
650
+	/**
651
+	 * releases reserved tickets for an EE_Registration
652
+	 * by default, will NOT release tickets for APPROVED registrations
653
+	 *
654
+	 * @param EE_Registration $registration
655
+	 * @param EE_Transaction  $transaction
656
+	 * @return int
657
+	 * @throws EE_Error
658
+	 */
659
+	protected function _release_reserved_ticket_for_registration(
660
+		EE_Registration $registration,
661
+		EE_Transaction $transaction
662
+	) {
663
+		$STS_ID = $transaction->status_ID();
664
+		if (self::debug) {
665
+			echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
666
+			echo self::$nl . ' . . registration->ID: ' . $registration->ID();
667
+			echo self::$nl . ' . . registration->status_ID: ' . $registration->status_ID();
668
+			echo self::$nl . ' . . transaction->status_ID(): ' . $STS_ID;
669
+		}
670
+		if (
671
+			// release Tickets for Failed Transactions and Abandoned Transactions
672
+			$STS_ID === EEM_Transaction::failed_status_code
673
+			|| $STS_ID === EEM_Transaction::abandoned_status_code
674
+			|| (
675
+				// also release Tickets for Incomplete Transactions, but ONLY if the Registrations are NOT Approved
676
+				$STS_ID === EEM_Transaction::incomplete_status_code
677
+				&& $registration->status_ID() !== EEM_Registration::status_id_approved
678
+			)
679
+		) {
680
+			if (self::debug) {
681
+				echo self::$nl . self::$nl . ' . . RELEASE RESERVED TICKET';
682
+				$rsrvd = $registration->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true);
683
+				echo self::$nl . ' . . . registration HAS_RESERVED_TICKET_KEY: ';
684
+				var_dump($rsrvd);
685
+			}
686
+			$registration->release_reserved_ticket(true, 'TicketSalesMonitor:'. __LINE__);
687
+			return 1;
688
+		}
689
+		return 0;
690
+	}
691
+
692
+
693
+
694
+	/********************************** SESSION_CART_RESET  **********************************/
695
+
696
+
697
+
698
+	/**
699
+	 * callback hooked into 'AHEE__EE_Session__reset_cart__before_reset'
700
+	 *
701
+	 * @param EE_Session $session
702
+	 * @return void
703
+	 * @throws EE_Error
704
+	 * @throws InvalidArgumentException
705
+	 * @throws ReflectionException
706
+	 * @throws InvalidDataTypeException
707
+	 * @throws InvalidInterfaceException
708
+	 */
709
+	public static function session_cart_reset(EE_Session $session)
710
+	{
711
+		if (self::debug) {
712
+			echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
713
+		}
714
+		// first check of the session has a valid Checkout object
715
+		$checkout = $session->checkout();
716
+		if ($checkout instanceof EE_Checkout) {
717
+			// and use that to clear ticket reservations because it will update the associated registration meta data
718
+			EED_Ticket_Sales_Monitor::instance()->_session_checkout_reset($checkout);
719
+			return;
720
+		}
721
+		$cart = $session->cart();
722
+		if ($cart instanceof EE_Cart) {
723
+			if (self::debug) {
724
+				echo self::$nl . self::$nl . ' cart instance of EE_Cart: ';
725
+			}
726
+			EED_Ticket_Sales_Monitor::instance()->_session_cart_reset($cart, $session);
727
+		} else {
728
+			if (self::debug) {
729
+				echo self::$nl . self::$nl . ' invalid EE_Cart: ';
730
+				var_export($cart, true);
731
+			}
732
+		}
733
+	}
734
+
735
+
736
+
737
+	/**
738
+	 * releases reserved tickets in the EE_Cart
739
+	 *
740
+	 * @param EE_Cart $cart
741
+	 * @return void
742
+	 * @throws EE_Error
743
+	 * @throws InvalidArgumentException
744
+	 * @throws ReflectionException
745
+	 * @throws InvalidDataTypeException
746
+	 * @throws InvalidInterfaceException
747
+	 */
748
+	protected function _session_cart_reset(EE_Cart $cart, EE_Session $session)
749
+	{
750
+		if (self::debug) {
751
+			echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
752
+		}
753
+		EE_Registry::instance()->load_helper('Line_Item');
754
+		$ticket_line_items = $cart->get_tickets();
755
+		if (empty($ticket_line_items)) {
756
+			return;
757
+		}
758
+		foreach ($ticket_line_items as $ticket_line_item) {
759
+			if (self::debug) {
760
+				echo self::$nl . ' . ticket_line_item->ID(): ' . $ticket_line_item->ID();
761
+			}
762
+			if ($ticket_line_item instanceof EE_Line_Item && $ticket_line_item->OBJ_type() === 'Ticket') {
763
+				if (self::debug) {
764
+					echo self::$nl . ' . . ticket_line_item->OBJ_ID(): ' . $ticket_line_item->OBJ_ID();
765
+				}
766
+				$ticket = EEM_Ticket::instance()->get_one_by_ID($ticket_line_item->OBJ_ID());
767
+				if ($ticket instanceof EE_Ticket) {
768
+					if (self::debug) {
769
+						echo self::$nl . ' . . ticket->ID(): ' . $ticket->ID();
770
+						echo self::$nl . ' . . ticket_line_item->quantity(): ' . $ticket_line_item->quantity();
771
+					}
772
+					$ticket->add_extra_meta(
773
+						EE_Ticket::META_KEY_TICKET_RESERVATIONS,
774
+						__LINE__ . ') ' . __METHOD__ . '() SID = ' . $session->id()
775
+					);
776
+					$this->_release_reserved_ticket($ticket, $ticket_line_item->quantity());
777
+				}
778
+			}
779
+		}
780
+		if (self::debug) {
781
+			echo self::$nl . self::$nl . ' RESET COMPLETED ';
782
+		}
783
+	}
784
+
785
+
786
+
787
+	/********************************** SESSION_CHECKOUT_RESET  **********************************/
788
+
789
+
790
+
791
+	/**
792
+	 * callback hooked into 'AHEE__EE_Session__reset_checkout__before_reset'
793
+	 *
794
+	 * @param EE_Session $session
795
+	 * @return void
796
+	 * @throws EE_Error
797
+	 * @throws InvalidSessionDataException
798
+	 */
799
+	public static function session_checkout_reset(EE_Session $session)
800
+	{
801
+		$checkout = $session->checkout();
802
+		if ($checkout instanceof EE_Checkout) {
803
+			EED_Ticket_Sales_Monitor::instance()->_session_checkout_reset($checkout);
804
+		}
805
+	}
806
+
807
+
808
+
809
+	/**
810
+	 * releases reserved tickets for the EE_Checkout->transaction
811
+	 *
812
+	 * @param EE_Checkout $checkout
813
+	 * @return void
814
+	 * @throws EE_Error
815
+	 * @throws InvalidSessionDataException
816
+	 */
817
+	protected function _session_checkout_reset(EE_Checkout $checkout)
818
+	{
819
+		if (self::debug) {
820
+			echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
821
+		}
822
+		// we want to release the each registration's reserved tickets if the session was cleared, but not if this is a revisit
823
+		if ($checkout->revisit || ! $checkout->transaction instanceof EE_Transaction) {
824
+			return;
825
+		}
826
+		$this->_release_all_reserved_tickets_for_transaction($checkout->transaction);
827
+	}
828
+
829
+
830
+
831
+	/********************************** SESSION_EXPIRED_RESET  **********************************/
832
+
833
+
834
+
835
+	/**
836
+	 * @param    EE_Session $session
837
+	 * @return    void
838
+	 */
839
+	public static function session_expired_reset(EE_Session $session)
840
+	{
841
+	}
842
+
843
+
844
+
845
+	/********************************** PROCESS_ABANDONED_TRANSACTIONS  **********************************/
846
+
847
+
848
+
849
+	/**
850
+	 * releases reserved tickets for all registrations of an ABANDONED EE_Transaction
851
+	 * by default, will NOT release tickets for free transactions, or any that have received a payment
852
+	 *
853
+	 * @param EE_Transaction $transaction
854
+	 * @return void
855
+	 * @throws EE_Error
856
+	 * @throws InvalidSessionDataException
857
+	 */
858
+	public static function process_abandoned_transactions(EE_Transaction $transaction)
859
+	{
860
+		// is this TXN free or has any money been paid towards this TXN? If so, then leave it alone
861
+		if ($transaction->is_free() || $transaction->paid() > 0) {
862
+			if (self::debug) {
863
+				// DEBUG LOG
864
+				EEH_Debug_Tools::log(
865
+					__CLASS__,
866
+					__FUNCTION__,
867
+					__LINE__,
868
+					array($transaction),
869
+					false,
870
+					'EE_Transaction: ' . $transaction->ID()
871
+				);
872
+			}
873
+			return;
874
+		}
875
+		// have their been any successful payments made ?
876
+		$payments = $transaction->payments();
877
+		foreach ($payments as $payment) {
878
+			if ($payment instanceof EE_Payment && $payment->status() === EEM_Payment::status_id_approved) {
879
+				if (self::debug) {
880
+					// DEBUG LOG
881
+					EEH_Debug_Tools::log(
882
+						__CLASS__,
883
+						__FUNCTION__,
884
+						__LINE__,
885
+						array($payment),
886
+						false,
887
+						'EE_Transaction: ' . $transaction->ID()
888
+					);
889
+				}
890
+				return;
891
+			}
892
+		}
893
+		// since you haven't even attempted to pay for your ticket...
894
+		EED_Ticket_Sales_Monitor::instance()->_release_all_reserved_tickets_for_transaction($transaction);
895
+	}
896
+
897
+
898
+
899
+	/********************************** PROCESS_FAILED_TRANSACTIONS  **********************************/
900
+
901
+
902
+
903
+	/**
904
+	 * releases reserved tickets for absolutely ALL registrations of a FAILED EE_Transaction
905
+	 *
906
+	 * @param EE_Transaction $transaction
907
+	 * @return void
908
+	 * @throws EE_Error
909
+	 * @throws InvalidSessionDataException
910
+	 */
911
+	public static function process_failed_transactions(EE_Transaction $transaction)
912
+	{
913
+		// since you haven't even attempted to pay for your ticket...
914
+		EED_Ticket_Sales_Monitor::instance()->_release_all_reserved_tickets_for_transaction($transaction);
915
+	}
916
+
917
+
918
+
919
+	/********************************** RESET RESERVATION COUNTS  *********************************/
920
+
921
+
922
+
923
+	/**
924
+	 * Resets all ticket and datetime reserved counts to zero
925
+	 * Tickets that are currently associated with a Transaction that is in progress
926
+	 *
927
+	 * @throws EE_Error
928
+	 * @throws DomainException
929
+	 * @throws InvalidDataTypeException
930
+	 * @throws InvalidInterfaceException
931
+	 * @throws InvalidArgumentException
932
+	 * @throws UnexpectedEntityException
933
+	 */
934
+	public static function reset_reservation_counts()
935
+	{
936
+		/** @var EE_Line_Item[] $valid_reserved_tickets */
937
+		$valid_reserved_tickets = array();
938
+		/** @var EE_Transaction[] $transactions_not_in_progress */
939
+		$transactions_not_in_progress = EEM_Transaction::instance()->get_transactions_not_in_progress();
940
+		foreach ($transactions_not_in_progress as $transaction) {
941
+			// if this TXN has been fully completed, then skip it
942
+			if ($transaction->reg_step_completed('finalize_registration')) {
943
+				continue;
944
+			}
945
+			$total_line_item = $transaction->total_line_item();
946
+			// $transaction_in_progress->line
947
+			if (! $total_line_item instanceof EE_Line_Item) {
948
+				throw new DomainException(
949
+					esc_html__(
950
+						'Transaction does not have a valid Total Line Item associated with it.',
951
+						'event_espresso'
952
+					)
953
+				);
954
+			}
955
+			$valid_reserved_tickets += EED_Ticket_Sales_Monitor::get_ticket_line_items_for_grand_total(
956
+				$total_line_item
957
+			);
958
+		}
959
+		$total_line_items = EEM_Line_Item::instance()->get_total_line_items_for_active_carts();
960
+		foreach ($total_line_items as $total_line_item) {
961
+			$valid_reserved_tickets += EED_Ticket_Sales_Monitor::get_ticket_line_items_for_grand_total(
962
+				$total_line_item
963
+			);
964
+		}
965
+		$tickets_with_reservations = EEM_Ticket::instance()->get_tickets_with_reservations();
966
+		return EED_Ticket_Sales_Monitor::release_reservations_for_tickets(
967
+			$tickets_with_reservations,
968
+			$valid_reserved_tickets,
969
+			__FUNCTION__
970
+		);
971
+	}
972
+
973
+
974
+
975
+	/**
976
+	 * @param EE_Line_Item $total_line_item
977
+	 * @return EE_Line_Item[]
978
+	 */
979
+	private static function get_ticket_line_items_for_grand_total(EE_Line_Item $total_line_item)
980
+	{
981
+		/** @var EE_Line_Item[] $valid_reserved_tickets */
982
+		$valid_reserved_tickets = array();
983
+		$ticket_line_items      = EEH_Line_Item::get_ticket_line_items($total_line_item);
984
+		foreach ($ticket_line_items as $ticket_line_item) {
985
+			if ($ticket_line_item instanceof EE_Line_Item) {
986
+				$valid_reserved_tickets[] = $ticket_line_item;
987
+			}
988
+		}
989
+		return $valid_reserved_tickets;
990
+	}
991
+
992
+
993
+
994
+	/**
995
+	 * @param EE_Ticket[]    $tickets_with_reservations
996
+	 * @param EE_Line_Item[] $valid_reserved_ticket_line_items
997
+	 * @return int
998
+	 * @throws UnexpectedEntityException
999
+	 * @throws DomainException
1000
+	 * @throws EE_Error
1001
+	 */
1002
+	private static function release_reservations_for_tickets(
1003
+		array $tickets_with_reservations,
1004
+		array $valid_reserved_ticket_line_items = array(),
1005
+		$source
1006
+	) {
1007
+		if (self::debug) {
1008
+			echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '()';
1009
+		}
1010
+		$total_tickets_released = 0;
1011
+		$sold_out_events = array();
1012
+		foreach ($tickets_with_reservations as $ticket_with_reservations) {
1013
+			if (! $ticket_with_reservations instanceof EE_Ticket) {
1014
+				continue;
1015
+			}
1016
+			$reserved_qty = $ticket_with_reservations->reserved();
1017
+			if (self::debug) {
1018
+				echo self::$nl . ' . $ticket_with_reservations->ID(): ' . $ticket_with_reservations->ID();
1019
+				echo self::$nl . ' . $reserved_qty: ' . $reserved_qty;
1020
+			}
1021
+			foreach ($valid_reserved_ticket_line_items as $valid_reserved_ticket_line_item) {
1022
+				if (
1023
+					$valid_reserved_ticket_line_item instanceof EE_Line_Item
1024
+					&& $valid_reserved_ticket_line_item->OBJ_ID() === $ticket_with_reservations->ID()
1025
+				) {
1026
+					if (self::debug) {
1027
+						echo self::$nl . ' . $valid_reserved_ticket_line_item->quantity(): ' . $valid_reserved_ticket_line_item->quantity();
1028
+					}
1029
+					$reserved_qty -= $valid_reserved_ticket_line_item->quantity();
1030
+				}
1031
+			}
1032
+			if ($reserved_qty > 0) {
1033
+				$ticket_with_reservations->add_extra_meta(
1034
+					EE_Ticket::META_KEY_TICKET_RESERVATIONS,
1035
+					__LINE__ . ') ' . $source . '()'
1036
+				);
1037
+				$ticket_with_reservations->decrease_reserved($reserved_qty, true, 'TicketSalesMonitor:'. __LINE__);
1038
+				$ticket_with_reservations->save();
1039
+				$total_tickets_released += $reserved_qty;
1040
+				$event = $ticket_with_reservations->get_related_event();
1041
+				// track sold out events
1042
+				if ($event instanceof EE_Event && $event->is_sold_out()) {
1043
+					$sold_out_events[] = $event;
1044
+				}
1045
+			}
1046
+		}
1047
+		if (self::debug) {
1048
+			echo self::$nl . ' . $total_tickets_released: ' . $total_tickets_released;
1049
+		}
1050
+		// double check whether sold out events should remain sold out after releasing tickets
1051
+		if($sold_out_events !== array()){
1052
+			foreach ($sold_out_events as $sold_out_event) {
1053
+				/** @var EE_Event $sold_out_event */
1054
+				$sold_out_event->perform_sold_out_status_check();
1055
+			}
1056
+		}
1057
+		return $total_tickets_released;
1058
+	}
1059
+
1060
+
1061
+
1062
+	/********************************** SHUTDOWN  **********************************/
1063
+
1064
+
1065
+
1066
+	/**
1067
+	 * @param int $timestamp
1068
+	 * @return false|int
1069
+	 * @throws EE_Error
1070
+	 * @throws InvalidArgumentException
1071
+	 * @throws InvalidDataTypeException
1072
+	 * @throws InvalidInterfaceException
1073
+	 */
1074
+	public static function clear_expired_line_items_with_no_transaction($timestamp = 0)
1075
+	{
1076
+	   /** @type WPDB $wpdb */
1077
+		global $wpdb;
1078
+		if (! absint($timestamp)) {
1079
+			/** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
1080
+			$session_lifespan = LoaderFactory::getLoader()->getShared(
1081
+				'EventEspresso\core\domain\values\session\SessionLifespan'
1082
+			);
1083
+			$timestamp = $session_lifespan->expiration();
1084
+		}
1085
+		 return $wpdb->query(
1086
+			$wpdb->prepare(
1087
+				'DELETE FROM ' . EEM_Line_Item::instance()->table() . '
1088 1088
                 WHERE TXN_ID = 0 AND LIN_timestamp <= %s',
1089
-                // use GMT time because that's what LIN_timestamps are in
1090
-                date('Y-m-d H:i:s', $timestamp)
1091
-            )
1092
-        );
1093
-    }
1089
+				// use GMT time because that's what LIN_timestamps are in
1090
+				date('Y-m-d H:i:s', $timestamp)
1091
+			)
1092
+		);
1093
+	}
1094 1094
 
1095 1095
 }
1096 1096
 // End of file EED_Ticket_Sales_Monitor.module.php
Please login to merge, or discard this patch.
Spacing   +86 added lines, -86 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
 class EED_Ticket_Sales_Monitor extends EED_Module
25 25
 {
26 26
 
27
-    const debug = false;    //	true false
27
+    const debug = false; //	true false
28 28
 
29 29
     private static $nl = '';
30 30
 
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
      */
68 68
     public static function set_hooks()
69 69
     {
70
-        self::$nl = defined('EE_TESTS_DIR')? "\n" : '<br />';
70
+        self::$nl = defined('EE_TESTS_DIR') ? "\n" : '<br />';
71 71
         // release tickets for expired carts
72 72
         add_action(
73 73
             'EED_Ticket_Selector__process_ticket_selections__before',
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
     public static function release_tickets_for_expired_carts()
197 197
     {
198 198
         if (self::debug) {
199
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '()';
199
+            echo self::$nl.self::$nl.__LINE__.') '.__METHOD__.'()';
200 200
         }
201 201
         do_action('AHEE__EED_Ticket_Sales_Monitor__release_tickets_for_expired_carts__begin');
202 202
         $expired_ticket_IDs = array();
@@ -207,26 +207,26 @@  discard block
 block discarded – undo
207 207
         $timestamp = $session_lifespan->expiration();
208 208
         $expired_ticket_line_items = EEM_Line_Item::instance()->getTicketLineItemsForExpiredCarts($timestamp);
209 209
         if (self::debug) {
210
-            echo self::$nl . ' . time(): ' . time();
211
-            echo self::$nl . ' . time() as date: ' . date('Y-m-d H:i a');
212
-            echo self::$nl . ' . session expiration: ' . $session_lifespan->expiration();
213
-            echo self::$nl . ' . session expiration as date: ' . date('Y-m-d H:i a', $session_lifespan->expiration());
214
-            echo self::$nl . ' . timestamp: ' . $timestamp;
215
-            echo self::$nl . ' . $expired_ticket_line_items: ' . count($expired_ticket_line_items);
210
+            echo self::$nl.' . time(): '.time();
211
+            echo self::$nl.' . time() as date: '.date('Y-m-d H:i a');
212
+            echo self::$nl.' . session expiration: '.$session_lifespan->expiration();
213
+            echo self::$nl.' . session expiration as date: '.date('Y-m-d H:i a', $session_lifespan->expiration());
214
+            echo self::$nl.' . timestamp: '.$timestamp;
215
+            echo self::$nl.' . $expired_ticket_line_items: '.count($expired_ticket_line_items);
216 216
         }
217
-        if (! empty($expired_ticket_line_items)) {
217
+        if ( ! empty($expired_ticket_line_items)) {
218 218
             foreach ($expired_ticket_line_items as $expired_ticket_line_item) {
219
-                if (! $expired_ticket_line_item instanceof EE_Line_Item) {
219
+                if ( ! $expired_ticket_line_item instanceof EE_Line_Item) {
220 220
                     continue;
221 221
                 }
222
-                $expired_ticket_IDs[ $expired_ticket_line_item->OBJ_ID() ] = $expired_ticket_line_item->OBJ_ID();
222
+                $expired_ticket_IDs[$expired_ticket_line_item->OBJ_ID()] = $expired_ticket_line_item->OBJ_ID();
223 223
                 if (self::debug) {
224
-                    echo self::$nl . ' . $expired_ticket_line_item->OBJ_ID(): ' . $expired_ticket_line_item->OBJ_ID();
225
-                    echo self::$nl . ' . $expired_ticket_line_item->timestamp(): ' . date('Y-m-d h:i a',
224
+                    echo self::$nl.' . $expired_ticket_line_item->OBJ_ID(): '.$expired_ticket_line_item->OBJ_ID();
225
+                    echo self::$nl.' . $expired_ticket_line_item->timestamp(): '.date('Y-m-d h:i a',
226 226
                             $expired_ticket_line_item->timestamp(true));
227 227
                 }
228 228
             }
229
-            if (! empty($expired_ticket_IDs)) {
229
+            if ( ! empty($expired_ticket_IDs)) {
230 230
                 EED_Ticket_Sales_Monitor::release_reservations_for_tickets(
231 231
                     \EEM_Ticket::instance()->get_tickets_with_IDs($expired_ticket_IDs),
232 232
                     array(),
@@ -265,8 +265,8 @@  discard block
 block discarded – undo
265 265
             $qty = EED_Ticket_Sales_Monitor::instance()->_validate_ticket_sale($ticket, $qty);
266 266
         }
267 267
         if (self::debug) {
268
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '()';
269
-            echo self::$nl . self::$nl . '<b> RETURNED QTY: ' . $qty . '</b>';
268
+            echo self::$nl.self::$nl.__LINE__.') '.__METHOD__.'()';
269
+            echo self::$nl.self::$nl.'<b> RETURNED QTY: '.$qty.'</b>';
270 270
         }
271 271
         return $qty;
272 272
     }
@@ -285,36 +285,36 @@  discard block
 block discarded – undo
285 285
     protected function _validate_ticket_sale(EE_Ticket $ticket, $qty = 1)
286 286
     {
287 287
         if (self::debug) {
288
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
288
+            echo self::$nl.self::$nl.__LINE__.') '.__METHOD__.'() ';
289 289
         }
290
-        if (! $ticket instanceof EE_Ticket) {
290
+        if ( ! $ticket instanceof EE_Ticket) {
291 291
             return 0;
292 292
         }
293 293
         if (self::debug) {
294
-            echo self::$nl . '<b> . ticket->ID: ' . $ticket->ID() . '</b>';
295
-            echo self::$nl . ' . original ticket->reserved: ' . $ticket->reserved();
294
+            echo self::$nl.'<b> . ticket->ID: '.$ticket->ID().'</b>';
295
+            echo self::$nl.' . original ticket->reserved: '.$ticket->reserved();
296 296
         }
297 297
         $ticket->refresh_from_db();
298 298
         // first let's determine the ticket availability based on sales
299 299
         $available = $ticket->qty('saleable');
300 300
         if (self::debug) {
301
-            echo self::$nl . ' . . . ticket->qty: ' . $ticket->qty();
302
-            echo self::$nl . ' . . . ticket->sold: ' . $ticket->sold();
303
-            echo self::$nl . ' . . . ticket->reserved: ' . $ticket->reserved();
304
-            echo self::$nl . ' . . . ticket->qty(saleable): ' . $ticket->qty('saleable');
305
-            echo self::$nl . ' . . . available: ' . $available;
301
+            echo self::$nl.' . . . ticket->qty: '.$ticket->qty();
302
+            echo self::$nl.' . . . ticket->sold: '.$ticket->sold();
303
+            echo self::$nl.' . . . ticket->reserved: '.$ticket->reserved();
304
+            echo self::$nl.' . . . ticket->qty(saleable): '.$ticket->qty('saleable');
305
+            echo self::$nl.' . . . available: '.$available;
306 306
         }
307 307
         if ($available < 1) {
308 308
             $this->_ticket_sold_out($ticket);
309 309
             return 0;
310 310
         }
311 311
         if (self::debug) {
312
-            echo self::$nl . ' . . . qty: ' . $qty;
312
+            echo self::$nl.' . . . qty: '.$qty;
313 313
         }
314 314
         if ($available < $qty) {
315 315
             $qty = $available;
316 316
             if (self::debug) {
317
-                echo self::$nl . ' . . . QTY ADJUSTED: ' . $qty;
317
+                echo self::$nl.' . . . QTY ADJUSTED: '.$qty;
318 318
             }
319 319
             $this->_ticket_quantity_decremented($ticket);
320 320
         }
@@ -335,9 +335,9 @@  discard block
 block discarded – undo
335 335
     protected function _reserve_ticket(EE_Ticket $ticket, $quantity = 1)
336 336
     {
337 337
         if (self::debug) {
338
-            echo self::$nl . self::$nl . ' . . . INCREASE RESERVED: ' . $quantity;
338
+            echo self::$nl.self::$nl.' . . . INCREASE RESERVED: '.$quantity;
339 339
         }
340
-        $ticket->increase_reserved($quantity, 'TicketSalesMonitor:'. __LINE__);
340
+        $ticket->increase_reserved($quantity, 'TicketSalesMonitor:'.__LINE__);
341 341
         return $ticket->save();
342 342
     }
343 343
 
@@ -352,12 +352,12 @@  discard block
 block discarded – undo
352 352
     protected function _release_reserved_ticket(EE_Ticket $ticket, $quantity = 1)
353 353
     {
354 354
         if (self::debug) {
355
-            echo self::$nl . ' . . . ticket->ID: ' . $ticket->ID();
356
-            echo self::$nl . ' . . . ticket->reserved: ' . $ticket->reserved();
355
+            echo self::$nl.' . . . ticket->ID: '.$ticket->ID();
356
+            echo self::$nl.' . . . ticket->reserved: '.$ticket->reserved();
357 357
         }
358
-        $ticket->decrease_reserved($quantity, true, 'TicketSalesMonitor:'. __LINE__);
358
+        $ticket->decrease_reserved($quantity, true, 'TicketSalesMonitor:'.__LINE__);
359 359
         if (self::debug) {
360
-            echo self::$nl . ' . . . ticket->reserved: ' . $ticket->reserved();
360
+            echo self::$nl.' . . . ticket->reserved: '.$ticket->reserved();
361 361
         }
362 362
         return $ticket->save() ? 1 : 0;
363 363
     }
@@ -375,8 +375,8 @@  discard block
 block discarded – undo
375 375
     protected function _ticket_sold_out(EE_Ticket $ticket)
376 376
     {
377 377
         if (self::debug) {
378
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
379
-            echo self::$nl . ' . . ticket->name: ' . $this->_get_ticket_and_event_name($ticket);
378
+            echo self::$nl.self::$nl.__LINE__.') '.__METHOD__.'() ';
379
+            echo self::$nl.' . . ticket->name: '.$this->_get_ticket_and_event_name($ticket);
380 380
         }
381 381
         $this->sold_out_tickets[] = $this->_get_ticket_and_event_name($ticket);
382 382
     }
@@ -394,8 +394,8 @@  discard block
 block discarded – undo
394 394
     protected function _ticket_quantity_decremented(EE_Ticket $ticket)
395 395
     {
396 396
         if (self::debug) {
397
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
398
-            echo self::$nl . ' . . ticket->name: ' . $this->_get_ticket_and_event_name($ticket);
397
+            echo self::$nl.self::$nl.__LINE__.') '.__METHOD__.'() ';
398
+            echo self::$nl.' . . ticket->name: '.$this->_get_ticket_and_event_name($ticket);
399 399
         }
400 400
         $this->decremented_tickets[] = $this->_get_ticket_and_event_name($ticket);
401 401
     }
@@ -448,7 +448,7 @@  discard block
 block discarded – undo
448 448
         if ($ticket instanceof EE_Ticket) {
449 449
             $ticket->add_extra_meta(
450 450
                 EE_Ticket::META_KEY_TICKET_RESERVATIONS,
451
-                __LINE__ . ') ' . __METHOD__ . '()'
451
+                __LINE__.') '.__METHOD__.'()'
452 452
             );
453 453
             if ($quantity > 0) {
454 454
                 EED_Ticket_Sales_Monitor::instance()->_reserve_ticket($ticket, $quantity);
@@ -472,7 +472,7 @@  discard block
 block discarded – undo
472 472
     {
473 473
         $ticket->add_extra_meta(
474 474
             EE_Ticket::META_KEY_TICKET_RESERVATIONS,
475
-            __LINE__ . ') ' . __METHOD__ . '()'
475
+            __LINE__.') '.__METHOD__.'()'
476 476
         );
477 477
         EED_Ticket_Sales_Monitor::instance()->_release_reserved_ticket($ticket, $quantity);
478 478
     }
@@ -509,18 +509,18 @@  discard block
 block discarded – undo
509 509
     protected function _post_notices()
510 510
     {
511 511
         if (self::debug) {
512
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
512
+            echo self::$nl.self::$nl.__LINE__.') '.__METHOD__.'() ';
513 513
         }
514 514
         $refresh_msg    = '';
515 515
         $none_added_msg = '';
516 516
         if (defined('DOING_AJAX') && DOING_AJAX) {
517
-            $refresh_msg    = __(
517
+            $refresh_msg = __(
518 518
                 'Please refresh the page to view updated ticket quantities.',
519 519
                 'event_espresso'
520 520
             );
521 521
             $none_added_msg = __('No tickets were added for the event.', 'event_espresso');
522 522
         }
523
-        if (! empty($this->sold_out_tickets)) {
523
+        if ( ! empty($this->sold_out_tickets)) {
524 524
             EE_Error::add_attention(
525 525
                 sprintf(
526 526
                     apply_filters(
@@ -543,7 +543,7 @@  discard block
 block discarded – undo
543 543
             // and reset the cart
544 544
             EED_Ticket_Sales_Monitor::session_cart_reset(EE_Registry::instance()->SSN);
545 545
         }
546
-        if (! empty($this->decremented_tickets)) {
546
+        if ( ! empty($this->decremented_tickets)) {
547 547
             EE_Error::add_attention(
548 548
                 sprintf(
549 549
                     apply_filters(
@@ -581,9 +581,9 @@  discard block
 block discarded – undo
581 581
     protected function _release_all_reserved_tickets_for_transaction(EE_Transaction $transaction)
582 582
     {
583 583
         if (self::debug) {
584
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
585
-            echo self::$nl . ' . transaction->ID: ' . $transaction->ID();
586
-            echo self::$nl . ' . TXN status_ID: ' . $transaction->status_ID();
584
+            echo self::$nl.self::$nl.__LINE__.') '.__METHOD__.'() ';
585
+            echo self::$nl.' . transaction->ID: '.$transaction->ID();
586
+            echo self::$nl.' . TXN status_ID: '.$transaction->status_ID();
587 587
         }
588 588
         // check if 'finalize_registration' step has been completed...
589 589
         $finalized = $transaction->reg_step_completed('finalize_registration');
@@ -595,13 +595,13 @@  discard block
 block discarded – undo
595 595
                 __LINE__,
596 596
                 array('finalized' => $finalized),
597 597
                 false,
598
-                'EE_Transaction: ' . $transaction->ID()
598
+                'EE_Transaction: '.$transaction->ID()
599 599
             );
600 600
         }
601 601
         // how many tickets were released
602 602
         $count = 0;
603 603
         if (self::debug) {
604
-            echo self::$nl . ' . . . TXN finalized: ' . $finalized;
604
+            echo self::$nl.' . . . TXN finalized: '.$finalized;
605 605
         }
606 606
         $release_tickets_with_TXN_status = array(
607 607
             EEM_Transaction::failed_status_code,
@@ -610,28 +610,28 @@  discard block
 block discarded – undo
610 610
         );
611 611
         $events = array();
612 612
         // if the session is getting cleared BEFORE the TXN has been finalized or the transaction is not completed
613
-        if (! $finalized || in_array($transaction->status_ID(), $release_tickets_with_TXN_status, true)) {
613
+        if ( ! $finalized || in_array($transaction->status_ID(), $release_tickets_with_TXN_status, true)) {
614 614
             // cancel any reserved tickets for registrations that were not approved
615 615
             $registrations = $transaction->registrations();
616 616
             if (self::debug) {
617
-                echo self::$nl . ' . . . # registrations: ' . count($registrations);
617
+                echo self::$nl.' . . . # registrations: '.count($registrations);
618 618
                 $reg    = reset($registrations);
619 619
                 $ticket = $reg->ticket();
620 620
                 if ($ticket instanceof EE_Ticket) {
621 621
                     $ticket->add_extra_meta(
622 622
                         EE_Ticket::META_KEY_TICKET_RESERVATIONS,
623
-                        __LINE__ . ') Release All Tickets TXN:' . $transaction->ID()
623
+                        __LINE__.') Release All Tickets TXN:'.$transaction->ID()
624 624
                     );
625 625
                 }
626 626
             }
627
-            if (! empty($registrations)) {
627
+            if ( ! empty($registrations)) {
628 628
                 foreach ($registrations as $registration) {
629 629
                     if (
630 630
                         $registration instanceof EE_Registration
631 631
                         && $this->_release_reserved_ticket_for_registration($registration, $transaction)
632 632
                     ) {
633 633
                         $count++;
634
-                        $events[ $registration->event_ID() ] = $registration->event();
634
+                        $events[$registration->event_ID()] = $registration->event();
635 635
                     }
636 636
                 }
637 637
             }
@@ -662,10 +662,10 @@  discard block
 block discarded – undo
662 662
     ) {
663 663
         $STS_ID = $transaction->status_ID();
664 664
         if (self::debug) {
665
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
666
-            echo self::$nl . ' . . registration->ID: ' . $registration->ID();
667
-            echo self::$nl . ' . . registration->status_ID: ' . $registration->status_ID();
668
-            echo self::$nl . ' . . transaction->status_ID(): ' . $STS_ID;
665
+            echo self::$nl.self::$nl.__LINE__.') '.__METHOD__.'() ';
666
+            echo self::$nl.' . . registration->ID: '.$registration->ID();
667
+            echo self::$nl.' . . registration->status_ID: '.$registration->status_ID();
668
+            echo self::$nl.' . . transaction->status_ID(): '.$STS_ID;
669 669
         }
670 670
         if (
671 671
             // release Tickets for Failed Transactions and Abandoned Transactions
@@ -678,12 +678,12 @@  discard block
 block discarded – undo
678 678
             )
679 679
         ) {
680 680
             if (self::debug) {
681
-                echo self::$nl . self::$nl . ' . . RELEASE RESERVED TICKET';
681
+                echo self::$nl.self::$nl.' . . RELEASE RESERVED TICKET';
682 682
                 $rsrvd = $registration->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true);
683
-                echo self::$nl . ' . . . registration HAS_RESERVED_TICKET_KEY: ';
683
+                echo self::$nl.' . . . registration HAS_RESERVED_TICKET_KEY: ';
684 684
                 var_dump($rsrvd);
685 685
             }
686
-            $registration->release_reserved_ticket(true, 'TicketSalesMonitor:'. __LINE__);
686
+            $registration->release_reserved_ticket(true, 'TicketSalesMonitor:'.__LINE__);
687 687
             return 1;
688 688
         }
689 689
         return 0;
@@ -709,7 +709,7 @@  discard block
 block discarded – undo
709 709
     public static function session_cart_reset(EE_Session $session)
710 710
     {
711 711
         if (self::debug) {
712
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
712
+            echo self::$nl.self::$nl.__LINE__.') '.__METHOD__.'() ';
713 713
         }
714 714
         // first check of the session has a valid Checkout object
715 715
         $checkout = $session->checkout();
@@ -721,12 +721,12 @@  discard block
 block discarded – undo
721 721
         $cart = $session->cart();
722 722
         if ($cart instanceof EE_Cart) {
723 723
             if (self::debug) {
724
-                echo self::$nl . self::$nl . ' cart instance of EE_Cart: ';
724
+                echo self::$nl.self::$nl.' cart instance of EE_Cart: ';
725 725
             }
726 726
             EED_Ticket_Sales_Monitor::instance()->_session_cart_reset($cart, $session);
727 727
         } else {
728 728
             if (self::debug) {
729
-                echo self::$nl . self::$nl . ' invalid EE_Cart: ';
729
+                echo self::$nl.self::$nl.' invalid EE_Cart: ';
730 730
                 var_export($cart, true);
731 731
             }
732 732
         }
@@ -748,7 +748,7 @@  discard block
 block discarded – undo
748 748
     protected function _session_cart_reset(EE_Cart $cart, EE_Session $session)
749 749
     {
750 750
         if (self::debug) {
751
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
751
+            echo self::$nl.self::$nl.__LINE__.') '.__METHOD__.'() ';
752 752
         }
753 753
         EE_Registry::instance()->load_helper('Line_Item');
754 754
         $ticket_line_items = $cart->get_tickets();
@@ -757,28 +757,28 @@  discard block
 block discarded – undo
757 757
         }
758 758
         foreach ($ticket_line_items as $ticket_line_item) {
759 759
             if (self::debug) {
760
-                echo self::$nl . ' . ticket_line_item->ID(): ' . $ticket_line_item->ID();
760
+                echo self::$nl.' . ticket_line_item->ID(): '.$ticket_line_item->ID();
761 761
             }
762 762
             if ($ticket_line_item instanceof EE_Line_Item && $ticket_line_item->OBJ_type() === 'Ticket') {
763 763
                 if (self::debug) {
764
-                    echo self::$nl . ' . . ticket_line_item->OBJ_ID(): ' . $ticket_line_item->OBJ_ID();
764
+                    echo self::$nl.' . . ticket_line_item->OBJ_ID(): '.$ticket_line_item->OBJ_ID();
765 765
                 }
766 766
                 $ticket = EEM_Ticket::instance()->get_one_by_ID($ticket_line_item->OBJ_ID());
767 767
                 if ($ticket instanceof EE_Ticket) {
768 768
                     if (self::debug) {
769
-                        echo self::$nl . ' . . ticket->ID(): ' . $ticket->ID();
770
-                        echo self::$nl . ' . . ticket_line_item->quantity(): ' . $ticket_line_item->quantity();
769
+                        echo self::$nl.' . . ticket->ID(): '.$ticket->ID();
770
+                        echo self::$nl.' . . ticket_line_item->quantity(): '.$ticket_line_item->quantity();
771 771
                     }
772 772
                     $ticket->add_extra_meta(
773 773
                         EE_Ticket::META_KEY_TICKET_RESERVATIONS,
774
-                        __LINE__ . ') ' . __METHOD__ . '() SID = ' . $session->id()
774
+                        __LINE__.') '.__METHOD__.'() SID = '.$session->id()
775 775
                     );
776 776
                     $this->_release_reserved_ticket($ticket, $ticket_line_item->quantity());
777 777
                 }
778 778
             }
779 779
         }
780 780
         if (self::debug) {
781
-            echo self::$nl . self::$nl . ' RESET COMPLETED ';
781
+            echo self::$nl.self::$nl.' RESET COMPLETED ';
782 782
         }
783 783
     }
784 784
 
@@ -817,7 +817,7 @@  discard block
 block discarded – undo
817 817
     protected function _session_checkout_reset(EE_Checkout $checkout)
818 818
     {
819 819
         if (self::debug) {
820
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '() ';
820
+            echo self::$nl.self::$nl.__LINE__.') '.__METHOD__.'() ';
821 821
         }
822 822
         // we want to release the each registration's reserved tickets if the session was cleared, but not if this is a revisit
823 823
         if ($checkout->revisit || ! $checkout->transaction instanceof EE_Transaction) {
@@ -867,7 +867,7 @@  discard block
 block discarded – undo
867 867
                     __LINE__,
868 868
                     array($transaction),
869 869
                     false,
870
-                    'EE_Transaction: ' . $transaction->ID()
870
+                    'EE_Transaction: '.$transaction->ID()
871 871
                 );
872 872
             }
873 873
             return;
@@ -884,7 +884,7 @@  discard block
 block discarded – undo
884 884
                         __LINE__,
885 885
                         array($payment),
886 886
                         false,
887
-                        'EE_Transaction: ' . $transaction->ID()
887
+                        'EE_Transaction: '.$transaction->ID()
888 888
                     );
889 889
                 }
890 890
                 return;
@@ -944,7 +944,7 @@  discard block
 block discarded – undo
944 944
             }
945 945
             $total_line_item = $transaction->total_line_item();
946 946
             // $transaction_in_progress->line
947
-            if (! $total_line_item instanceof EE_Line_Item) {
947
+            if ( ! $total_line_item instanceof EE_Line_Item) {
948 948
                 throw new DomainException(
949 949
                     esc_html__(
950 950
                         'Transaction does not have a valid Total Line Item associated with it.',
@@ -1005,18 +1005,18 @@  discard block
 block discarded – undo
1005 1005
         $source
1006 1006
     ) {
1007 1007
         if (self::debug) {
1008
-            echo self::$nl . self::$nl . __LINE__ . ') ' . __METHOD__ . '()';
1008
+            echo self::$nl.self::$nl.__LINE__.') '.__METHOD__.'()';
1009 1009
         }
1010 1010
         $total_tickets_released = 0;
1011 1011
         $sold_out_events = array();
1012 1012
         foreach ($tickets_with_reservations as $ticket_with_reservations) {
1013
-            if (! $ticket_with_reservations instanceof EE_Ticket) {
1013
+            if ( ! $ticket_with_reservations instanceof EE_Ticket) {
1014 1014
                 continue;
1015 1015
             }
1016 1016
             $reserved_qty = $ticket_with_reservations->reserved();
1017 1017
             if (self::debug) {
1018
-                echo self::$nl . ' . $ticket_with_reservations->ID(): ' . $ticket_with_reservations->ID();
1019
-                echo self::$nl . ' . $reserved_qty: ' . $reserved_qty;
1018
+                echo self::$nl.' . $ticket_with_reservations->ID(): '.$ticket_with_reservations->ID();
1019
+                echo self::$nl.' . $reserved_qty: '.$reserved_qty;
1020 1020
             }
1021 1021
             foreach ($valid_reserved_ticket_line_items as $valid_reserved_ticket_line_item) {
1022 1022
                 if (
@@ -1024,7 +1024,7 @@  discard block
 block discarded – undo
1024 1024
                     && $valid_reserved_ticket_line_item->OBJ_ID() === $ticket_with_reservations->ID()
1025 1025
                 ) {
1026 1026
                     if (self::debug) {
1027
-                        echo self::$nl . ' . $valid_reserved_ticket_line_item->quantity(): ' . $valid_reserved_ticket_line_item->quantity();
1027
+                        echo self::$nl.' . $valid_reserved_ticket_line_item->quantity(): '.$valid_reserved_ticket_line_item->quantity();
1028 1028
                     }
1029 1029
                     $reserved_qty -= $valid_reserved_ticket_line_item->quantity();
1030 1030
                 }
@@ -1032,9 +1032,9 @@  discard block
 block discarded – undo
1032 1032
             if ($reserved_qty > 0) {
1033 1033
                 $ticket_with_reservations->add_extra_meta(
1034 1034
                     EE_Ticket::META_KEY_TICKET_RESERVATIONS,
1035
-                    __LINE__ . ') ' . $source . '()'
1035
+                    __LINE__.') '.$source.'()'
1036 1036
                 );
1037
-                $ticket_with_reservations->decrease_reserved($reserved_qty, true, 'TicketSalesMonitor:'. __LINE__);
1037
+                $ticket_with_reservations->decrease_reserved($reserved_qty, true, 'TicketSalesMonitor:'.__LINE__);
1038 1038
                 $ticket_with_reservations->save();
1039 1039
                 $total_tickets_released += $reserved_qty;
1040 1040
                 $event = $ticket_with_reservations->get_related_event();
@@ -1045,10 +1045,10 @@  discard block
 block discarded – undo
1045 1045
             }
1046 1046
         }
1047 1047
         if (self::debug) {
1048
-            echo self::$nl . ' . $total_tickets_released: ' . $total_tickets_released;
1048
+            echo self::$nl.' . $total_tickets_released: '.$total_tickets_released;
1049 1049
         }
1050 1050
         // double check whether sold out events should remain sold out after releasing tickets
1051
-        if($sold_out_events !== array()){
1051
+        if ($sold_out_events !== array()) {
1052 1052
             foreach ($sold_out_events as $sold_out_event) {
1053 1053
                 /** @var EE_Event $sold_out_event */
1054 1054
                 $sold_out_event->perform_sold_out_status_check();
@@ -1075,7 +1075,7 @@  discard block
 block discarded – undo
1075 1075
     {
1076 1076
        /** @type WPDB $wpdb */
1077 1077
         global $wpdb;
1078
-        if (! absint($timestamp)) {
1078
+        if ( ! absint($timestamp)) {
1079 1079
             /** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
1080 1080
             $session_lifespan = LoaderFactory::getLoader()->getShared(
1081 1081
                 'EventEspresso\core\domain\values\session\SessionLifespan'
@@ -1084,7 +1084,7 @@  discard block
 block discarded – undo
1084 1084
         }
1085 1085
          return $wpdb->query(
1086 1086
             $wpdb->prepare(
1087
-                'DELETE FROM ' . EEM_Line_Item::instance()->table() . '
1087
+                'DELETE FROM '.EEM_Line_Item::instance()->table().'
1088 1088
                 WHERE TXN_ID = 0 AND LIN_timestamp <= %s',
1089 1089
                 // use GMT time because that's what LIN_timestamps are in
1090 1090
                 date('Y-m-d H:i:s', $timestamp)
Please login to merge, or discard this patch.
core/domain/values/session/SessionLifespan.php 1 patch
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -24,99 +24,99 @@
 block discarded – undo
24 24
 class SessionLifespan
25 25
 {
26 26
 
27
-    /**
28
-     * how long an EE session lasts in seconds
29
-     * default session lifespan of 1 hour (for not so instant IPNs)
30
-     *
31
-     * @var int $lifespan
32
-     */
33
-    private $lifespan;
34
-
35
-
36
-    /**
37
-     * SessionLifespan constructor.
38
-     *
39
-     * @param int $lifespan
40
-     * @throws DomainException
41
-     */
42
-    public function __construct($lifespan = 0)
43
-    {
44
-        $lifespan = absint($lifespan);
45
-        $lifespan = $lifespan > 0 ? $lifespan : (int) HOUR_IN_SECONDS;
46
-        $this->setLifespan($lifespan);
47
-    }
48
-
49
-
50
-    /**
51
-     * @param int $lifespan
52
-     * @throws DomainException
53
-     */
54
-    protected function setLifespan($lifespan)
55
-    {
56
-        if($lifespan < 60) {
57
-            throw new DomainException(
58
-                esc_html__(
59
-                    'The session lifespan needs to be at least 60 seconds, and even that is extremely short',
60
-                    'event_espresso'
61
-                )
62
-            );
63
-
64
-        }
65
-        $this->lifespan = apply_filters(
66
-            'FHEE__EventEspresso_core_domain_values_session_SessionLifespan__setLifespan___lifespan',
67
-            // apply legacy filter for now but add doing it wrong notice in future
68
-            apply_filters(
69
-                'FHEE__EE_Session__construct___lifespan',
70
-                $lifespan
71
-            )
72
-        ) + 1;
73
-    }
74
-
75
-
76
-    /**
77
-     * @return int
78
-     */
79
-    public function inSeconds()
80
-    {
81
-        return $this->lifespan;
82
-    }
83
-
84
-
85
-    /**
86
-     * @param string $separator
87
-     * @return string
88
-     */
89
-    public function inHoursMinutesSeconds($separator = ':')
90
-    {
91
-        return sprintf(
92
-            '%02d%s%02d%s%02d',
93
-            floor($this->lifespan / 3600),
94
-            $separator,
95
-            ($this->lifespan / 60) % 60,
96
-            $separator,
97
-            $this->lifespan % 60
98
-        );
99
-    }
100
-
101
-
102
-    /**
103
-     * Returns a timestamp for when the session would expire based on this lifespan
104
-     *
105
-     * @param bool $utc If true, displays expiration in UTC
106
-     *                  If false, displays expiration in local time
107
-     * @return int
108
-     */
109
-    public function expiration($utc = true)
110
-    {
111
-        return (int) current_time('timestamp', $utc) - $this->lifespan;
112
-    }
113
-
114
-
115
-    /**
116
-     * @return string
117
-     */
118
-    public function __toString()
119
-    {
120
-        return (string) $this->inSeconds();
121
-    }
27
+	/**
28
+	 * how long an EE session lasts in seconds
29
+	 * default session lifespan of 1 hour (for not so instant IPNs)
30
+	 *
31
+	 * @var int $lifespan
32
+	 */
33
+	private $lifespan;
34
+
35
+
36
+	/**
37
+	 * SessionLifespan constructor.
38
+	 *
39
+	 * @param int $lifespan
40
+	 * @throws DomainException
41
+	 */
42
+	public function __construct($lifespan = 0)
43
+	{
44
+		$lifespan = absint($lifespan);
45
+		$lifespan = $lifespan > 0 ? $lifespan : (int) HOUR_IN_SECONDS;
46
+		$this->setLifespan($lifespan);
47
+	}
48
+
49
+
50
+	/**
51
+	 * @param int $lifespan
52
+	 * @throws DomainException
53
+	 */
54
+	protected function setLifespan($lifespan)
55
+	{
56
+		if($lifespan < 60) {
57
+			throw new DomainException(
58
+				esc_html__(
59
+					'The session lifespan needs to be at least 60 seconds, and even that is extremely short',
60
+					'event_espresso'
61
+				)
62
+			);
63
+
64
+		}
65
+		$this->lifespan = apply_filters(
66
+			'FHEE__EventEspresso_core_domain_values_session_SessionLifespan__setLifespan___lifespan',
67
+			// apply legacy filter for now but add doing it wrong notice in future
68
+			apply_filters(
69
+				'FHEE__EE_Session__construct___lifespan',
70
+				$lifespan
71
+			)
72
+		) + 1;
73
+	}
74
+
75
+
76
+	/**
77
+	 * @return int
78
+	 */
79
+	public function inSeconds()
80
+	{
81
+		return $this->lifespan;
82
+	}
83
+
84
+
85
+	/**
86
+	 * @param string $separator
87
+	 * @return string
88
+	 */
89
+	public function inHoursMinutesSeconds($separator = ':')
90
+	{
91
+		return sprintf(
92
+			'%02d%s%02d%s%02d',
93
+			floor($this->lifespan / 3600),
94
+			$separator,
95
+			($this->lifespan / 60) % 60,
96
+			$separator,
97
+			$this->lifespan % 60
98
+		);
99
+	}
100
+
101
+
102
+	/**
103
+	 * Returns a timestamp for when the session would expire based on this lifespan
104
+	 *
105
+	 * @param bool $utc If true, displays expiration in UTC
106
+	 *                  If false, displays expiration in local time
107
+	 * @return int
108
+	 */
109
+	public function expiration($utc = true)
110
+	{
111
+		return (int) current_time('timestamp', $utc) - $this->lifespan;
112
+	}
113
+
114
+
115
+	/**
116
+	 * @return string
117
+	 */
118
+	public function __toString()
119
+	{
120
+		return (string) $this->inSeconds();
121
+	}
122 122
 }
Please login to merge, or discard this patch.
core/services/payment_methods/gateways/GatewayDataFormatter.php 1 patch
Indentation   +116 added lines, -116 removed lines patch added patch discarded remove patch
@@ -17,122 +17,122 @@
 block discarded – undo
17 17
 class GatewayDataFormatter implements GatewayDataFormatterInterface
18 18
 {
19 19
 
20
-    /**
21
-     * Gets the text to use for a gateway's line item name when this is a partial payment
22
-     *
23
-     * @param \EEI_Payment $payment
24
-     * @return string
25
-     */
26
-    public function formatPartialPaymentLineItemName(\EEI_Payment $payment)
27
-    {
28
-        return apply_filters(
29
-            'EEG_Paypal_Pro__do_direct_payment__partial_amount_line_item_name',
30
-            $payment->get_first_event_name(),
31
-            $this,
32
-            $payment
33
-        );
34
-    }
35
-
36
-
37
-
38
-    /**
39
-     * Gets the text to use for a gateway's line item description when this is a partial payment
40
-     *
41
-     * @param \EEI_Payment $payment
42
-     * @return string
43
-     */
44
-    public function formatPartialPaymentLineItemDesc(\EEI_Payment $payment)
45
-    {
46
-        return apply_filters(
47
-            'FHEE__EE_Gateway___partial_payment_desc',
48
-            sprintf(
49
-                __("Payment of %s for %s", "event_espresso"),
50
-                $payment->get_pretty('PAY_amount', 'no_currency_code'),
51
-                $payment->get_first_event_name()
52
-            ),
53
-            $this,
54
-            $payment
55
-        );
56
-    }
57
-
58
-
59
-
60
-    /**
61
-     * Gets the name to use for a line item when sending line items to the gateway
62
-     *
63
-     * @param \EEI_Line_Item $line_item
64
-     * @param \EEI_Payment   $payment
65
-     * @return string
66
-     */
67
-    public function formatLineItemName(\EEI_Line_Item $line_item, \EEI_Payment $payment)
68
-    {
69
-        return apply_filters(
70
-            'FHEE__EE_gateway___line_item_name',
71
-            sprintf(
72
-                _x('%1$s for %2$s', 'Ticket for Event', 'event_espresso'),
73
-                $line_item->name(),
74
-                $line_item->ticket_event_name()
75
-            ),
76
-            $this,
77
-            $line_item,
78
-            $payment
79
-        );
80
-    }
81
-
82
-
83
-
84
-    /**
85
-     * Gets the description to use for a line item when sending line items to the gateway
86
-     *
87
-     * @param \EEI_Line_Item $line_item
88
-     * @param \EEI_Payment   $payment
89
-     * @return string
90
-     */
91
-    public function formatLineItemDesc(\EEI_Line_Item $line_item, \EEI_Payment $payment)
92
-    {
93
-        return apply_filters(
94
-            'FHEE__EE_Gateway___line_item_desc',
95
-            $line_item->desc(),
96
-            $this,
97
-            $line_item,
98
-            $payment
99
-        );
100
-    }
101
-
102
-
103
-
104
-    /**
105
-     * Gets the order description that should generally be sent to gateways
106
-     *
107
-     * @param \EEI_Payment $payment
108
-     * @return string
109
-     */
110
-    public function formatOrderDescription(\EEI_Payment $payment)
111
-    {
112
-        return apply_filters(
113
-            'FHEE__EE_Gateway___order_description',
114
-            sprintf(
115
-                __('Event Registrations from %1$s for %2$s', "event_espresso"),
116
-                wp_specialchars_decode(get_bloginfo(), ENT_QUOTES),
117
-                $payment->get_first_event_name()
118
-            ),
119
-            $this,
120
-            $payment
121
-        );
122
-    }
123
-
124
-
125
-
126
-    /**
127
-     * Formats the amount so it can generally be sent to gateways
128
-     *
129
-     * @param float $amount
130
-     * @return string
131
-     */
132
-    public function formatCurrency($amount)
133
-    {
134
-        return number_format($amount, 2, '.', '');
135
-    }
20
+	/**
21
+	 * Gets the text to use for a gateway's line item name when this is a partial payment
22
+	 *
23
+	 * @param \EEI_Payment $payment
24
+	 * @return string
25
+	 */
26
+	public function formatPartialPaymentLineItemName(\EEI_Payment $payment)
27
+	{
28
+		return apply_filters(
29
+			'EEG_Paypal_Pro__do_direct_payment__partial_amount_line_item_name',
30
+			$payment->get_first_event_name(),
31
+			$this,
32
+			$payment
33
+		);
34
+	}
35
+
36
+
37
+
38
+	/**
39
+	 * Gets the text to use for a gateway's line item description when this is a partial payment
40
+	 *
41
+	 * @param \EEI_Payment $payment
42
+	 * @return string
43
+	 */
44
+	public function formatPartialPaymentLineItemDesc(\EEI_Payment $payment)
45
+	{
46
+		return apply_filters(
47
+			'FHEE__EE_Gateway___partial_payment_desc',
48
+			sprintf(
49
+				__("Payment of %s for %s", "event_espresso"),
50
+				$payment->get_pretty('PAY_amount', 'no_currency_code'),
51
+				$payment->get_first_event_name()
52
+			),
53
+			$this,
54
+			$payment
55
+		);
56
+	}
57
+
58
+
59
+
60
+	/**
61
+	 * Gets the name to use for a line item when sending line items to the gateway
62
+	 *
63
+	 * @param \EEI_Line_Item $line_item
64
+	 * @param \EEI_Payment   $payment
65
+	 * @return string
66
+	 */
67
+	public function formatLineItemName(\EEI_Line_Item $line_item, \EEI_Payment $payment)
68
+	{
69
+		return apply_filters(
70
+			'FHEE__EE_gateway___line_item_name',
71
+			sprintf(
72
+				_x('%1$s for %2$s', 'Ticket for Event', 'event_espresso'),
73
+				$line_item->name(),
74
+				$line_item->ticket_event_name()
75
+			),
76
+			$this,
77
+			$line_item,
78
+			$payment
79
+		);
80
+	}
81
+
82
+
83
+
84
+	/**
85
+	 * Gets the description to use for a line item when sending line items to the gateway
86
+	 *
87
+	 * @param \EEI_Line_Item $line_item
88
+	 * @param \EEI_Payment   $payment
89
+	 * @return string
90
+	 */
91
+	public function formatLineItemDesc(\EEI_Line_Item $line_item, \EEI_Payment $payment)
92
+	{
93
+		return apply_filters(
94
+			'FHEE__EE_Gateway___line_item_desc',
95
+			$line_item->desc(),
96
+			$this,
97
+			$line_item,
98
+			$payment
99
+		);
100
+	}
101
+
102
+
103
+
104
+	/**
105
+	 * Gets the order description that should generally be sent to gateways
106
+	 *
107
+	 * @param \EEI_Payment $payment
108
+	 * @return string
109
+	 */
110
+	public function formatOrderDescription(\EEI_Payment $payment)
111
+	{
112
+		return apply_filters(
113
+			'FHEE__EE_Gateway___order_description',
114
+			sprintf(
115
+				__('Event Registrations from %1$s for %2$s', "event_espresso"),
116
+				wp_specialchars_decode(get_bloginfo(), ENT_QUOTES),
117
+				$payment->get_first_event_name()
118
+			),
119
+			$this,
120
+			$payment
121
+		);
122
+	}
123
+
124
+
125
+
126
+	/**
127
+	 * Formats the amount so it can generally be sent to gateways
128
+	 *
129
+	 * @param float $amount
130
+	 * @return string
131
+	 */
132
+	public function formatCurrency($amount)
133
+	{
134
+		return number_format($amount, 2, '.', '');
135
+	}
136 136
 }
137 137
 // End of file GatewayDataFormatter.php
138 138
 // Location: core\services\gateways/GatewayDataFormatter.php
139 139
\ No newline at end of file
Please login to merge, or discard this patch.