Completed
Branch FET-8385-datetime-ticket-selec... (dcae27)
by
unknown
34:01 queued 22:12
created
reg_steps/payment_options/EE_SPCO_Reg_Step_Payment_Options.class.php 2 patches
Indentation   +84 added lines, -84 removed lines patch added patch discarded remove patch
@@ -286,41 +286,41 @@  discard block
 block discarded – undo
286 286
 			$this->checkout->revisit
287 287
 		);
288 288
 		foreach ( $registrations as $REG_ID => $registration ) {
289
-            /** @var $registration EE_Registration */
290
-            // has this registration lost it's space ?
289
+			/** @var $registration EE_Registration */
290
+			// has this registration lost it's space ?
291 291
 			if ( isset( $ejected_registrations[ $REG_ID ] ) ) {
292 292
 				$insufficient_spaces_available[ $registration->event()->ID() ] = $registration->event();
293 293
 				continue;
294 294
 			}
295
-            // event requires admin approval
296
-            if ($registration->status_ID() === EEM_Registration::status_id_not_approved) {
297
-                // add event to list of events with pre-approval reg status
298
-                $registrations_requiring_pre_approval[$REG_ID] = $registration;
299
-                do_action(
300
-                    'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_pre_approval',
301
-                    $registration->event(),
302
-                    $this
303
-                );
304
-                continue;
305
-            }
306
-            if (
295
+			// event requires admin approval
296
+			if ($registration->status_ID() === EEM_Registration::status_id_not_approved) {
297
+				// add event to list of events with pre-approval reg status
298
+				$registrations_requiring_pre_approval[$REG_ID] = $registration;
299
+				do_action(
300
+					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_pre_approval',
301
+					$registration->event(),
302
+					$this
303
+				);
304
+				continue;
305
+			}
306
+			if (
307 307
 				// returning registrant
308 308
 				$this->checkout->revisit
309 309
 				// anything other than Approved
310 310
 				&& $registration->status_ID() !== EEM_Registration::status_id_approved
311
-                && (
312
-                    $registration->event()->is_sold_out()
313
-                    || $registration->event()->is_sold_out( true )
314
-                )
315
-            ) {
316
-                // add event to list of events that are sold out
317
-                $sold_out_events[ $registration->event()->ID() ] = $registration->event();
318
-                do_action(
319
-                    'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__sold_out_event',
320
-                    $registration->event(),
321
-                    $this
322
-                );
323
-                continue;
311
+				&& (
312
+					$registration->event()->is_sold_out()
313
+					|| $registration->event()->is_sold_out( true )
314
+				)
315
+			) {
316
+				// add event to list of events that are sold out
317
+				$sold_out_events[ $registration->event()->ID() ] = $registration->event();
318
+				do_action(
319
+					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__sold_out_event',
320
+					$registration->event(),
321
+					$this
322
+				);
323
+				continue;
324 324
 			}
325 325
 			// are they allowed to pay now and is there monies owing?
326 326
 			if ( $registration->owes_monies_and_can_pay() ) {
@@ -428,11 +428,11 @@  discard block
 block discarded – undo
428 428
 			new EE_Billable_Line_Item_Filter(
429 429
 				EE_SPCO_Reg_Step_Payment_Options::remove_ejected_registrations(
430 430
 					EE_Registry::instance()->SSN->checkout()->transaction->registrations(
431
-                        EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
432
-                    )
431
+						EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
432
+					)
433 433
 				)
434 434
 			)
435
-        );
435
+		);
436 436
 		$line_item_filter_collection->add( new EE_Non_Zero_Line_Item_Filter() );
437 437
 		return $line_item_filter_collection;
438 438
 	}
@@ -481,38 +481,38 @@  discard block
 block discarded – undo
481 481
 	 * @throws \EE_Error
482 482
 	 */
483 483
 	public static function find_registrations_that_lost_their_space( array $registrations, $revisit = false ) {
484
-        // registrations per event
484
+		// registrations per event
485 485
 		$event_reg_count = array();
486 486
 		// spaces left per event
487 487
 		$event_spaces_remaining = array();
488
-        // tickets left sorted by ID
489
-        $tickets_remaining = array();
490
-        // registrations that have lost their space
488
+		// tickets left sorted by ID
489
+		$tickets_remaining = array();
490
+		// registrations that have lost their space
491 491
 		$ejected_registrations = array();
492 492
 		foreach ( $registrations as $REG_ID => $registration ) {
493 493
 			if ( $registration->status_ID() === EEM_Registration::status_id_approved ) {
494 494
 				continue;
495 495
 			}
496 496
 			$EVT_ID = $registration->event_ID();
497
-            $ticket = $registration->ticket();
498
-            if ( ! isset($tickets_remaining[$ticket->ID()])) {
499
-                $tickets_remaining[$ticket->ID()] = $ticket->remaining();
500
-            }
501
-            if ($tickets_remaining[$ticket->ID()] > 0) {
502
-                if ( ! isset($event_reg_count[$EVT_ID])) {
503
-                    $event_reg_count[$EVT_ID] = 0;
504
-                }
505
-                $event_reg_count[$EVT_ID]++;
506
-                if ( ! isset($event_spaces_remaining[$EVT_ID])) {
507
-                    $event_spaces_remaining[$EVT_ID] = $registration->event()->spaces_remaining_for_sale();
508
-                }
509
-            }
497
+			$ticket = $registration->ticket();
498
+			if ( ! isset($tickets_remaining[$ticket->ID()])) {
499
+				$tickets_remaining[$ticket->ID()] = $ticket->remaining();
500
+			}
501
+			if ($tickets_remaining[$ticket->ID()] > 0) {
502
+				if ( ! isset($event_reg_count[$EVT_ID])) {
503
+					$event_reg_count[$EVT_ID] = 0;
504
+				}
505
+				$event_reg_count[$EVT_ID]++;
506
+				if ( ! isset($event_spaces_remaining[$EVT_ID])) {
507
+					$event_spaces_remaining[$EVT_ID] = $registration->event()->spaces_remaining_for_sale();
508
+				}
509
+			}
510 510
 			if (
511 511
 				$revisit
512 512
 				&& (
513
-                    $tickets_remaining[$ticket->ID()] === 0
514
-				    || $event_reg_count[ $EVT_ID ] > $event_spaces_remaining[ $EVT_ID ]
515
-                )
513
+					$tickets_remaining[$ticket->ID()] === 0
514
+					|| $event_reg_count[ $EVT_ID ] > $event_spaces_remaining[ $EVT_ID ]
515
+				)
516 516
 			) {
517 517
 				$ejected_registrations[ $REG_ID ] = $registration->event();
518 518
 				if ( $registration->status_ID() !== EEM_Registration::status_id_wait_list ) {
@@ -581,9 +581,9 @@  discard block
 block discarded – undo
581 581
 				'layout_strategy'		=> new EE_Template_Layout(
582 582
 					array(
583 583
 						'layout_template_file' => SPCO_REG_STEPS_PATH
584
-						                          . $this->_slug
585
-						                          . DS
586
-						                          . 'sold_out_events.template.php',
584
+												  . $this->_slug
585
+												  . DS
586
+												  . 'sold_out_events.template.php',
587 587
 						'template_args'        => apply_filters(
588 588
 							'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
589 589
 							array(
@@ -636,9 +636,9 @@  discard block
 block discarded – undo
636 636
 				'layout_strategy' => new EE_Template_Layout(
637 637
 					array(
638 638
 						'layout_template_file' => SPCO_REG_STEPS_PATH
639
-						                          . $this->_slug
640
-						                          . DS
641
-						                          . 'sold_out_events.template.php',
639
+												  . $this->_slug
640
+												  . DS
641
+												  . 'sold_out_events.template.php',
642 642
 						'template_args'        => apply_filters(
643 643
 							'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__template_args',
644 644
 							array(
@@ -686,9 +686,9 @@  discard block
 block discarded – undo
686 686
 				'layout_strategy'		=> new EE_Template_Layout(
687 687
 					array(
688 688
 						'layout_template_file' => SPCO_REG_STEPS_PATH
689
-						                          . $this->_slug
690
-						                          . DS
691
-						                          . 'events_requiring_pre_approval.template.php', // layout_template
689
+												  . $this->_slug
690
+												  . DS
691
+												  . 'events_requiring_pre_approval.template.php', // layout_template
692 692
 						'template_args'        => apply_filters(
693 693
 							'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
694 694
 							array(
@@ -726,9 +726,9 @@  discard block
 block discarded – undo
726 726
 				'layout_strategy' 	=> new EE_Template_Layout(
727 727
 					array(
728 728
 						'layout_template_file' => SPCO_REG_STEPS_PATH
729
-						                          . $this->_slug
730
-						                          . DS
731
-						                          . 'no_payment_required.template.php', // layout_template
729
+												  . $this->_slug
730
+												  . DS
731
+												  . 'no_payment_required.template.php', // layout_template
732 732
 						'template_args'        => apply_filters(
733 733
 							'FHEE__EE_SPCO_Reg_Step_Payment_Options___no_payment_required__template_args',
734 734
 							array(
@@ -956,7 +956,7 @@  discard block
 block discarded – undo
956 956
 					$available_payment_method_options[ $payment_method->slug() ] = $payment_method_button;
957 957
 				}
958 958
 				$payment_methods_billing_info[ $payment_method->slug()
959
-				                               . '-info' ] = $this->_payment_method_billing_info(
959
+											   . '-info' ] = $this->_payment_method_billing_info(
960 960
 					$payment_method
961 961
 				);
962 962
 			}
@@ -1144,7 +1144,7 @@  discard block
 block discarded – undo
1144 1144
 		// fill form with attendee info if applicable
1145 1145
 		if (
1146 1146
 			$payment_method_billing_form instanceof EE_Billing_Attendee_Info_Form
1147
-		    && $this->checkout->transaction_has_primary_registrant()
1147
+			&& $this->checkout->transaction_has_primary_registrant()
1148 1148
 		) {
1149 1149
 			$payment_method_billing_form->populate_from_attendee(
1150 1150
 				$this->checkout->transaction->primary_registration()->attendee()
@@ -1153,7 +1153,7 @@  discard block
 block discarded – undo
1153 1153
 		// and debug content
1154 1154
 		if (
1155 1155
 			$payment_method_billing_form instanceof EE_Billing_Info_Form
1156
-		    && $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1156
+			&& $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1157 1157
 		) {
1158 1158
 			$payment_method_billing_form = $this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1159 1159
 				$payment_method_billing_form
@@ -1328,7 +1328,7 @@  discard block
 block discarded – undo
1328 1328
 		}
1329 1329
 		// and debug content
1330 1330
 		if ( $this->checkout->billing_form instanceof EE_Billing_Info_Form
1331
-		     && $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1331
+			 && $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1332 1332
 		) {
1333 1333
 			$this->checkout->billing_form = $this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1334 1334
 				$this->checkout->billing_form
@@ -1498,8 +1498,8 @@  discard block
 block discarded – undo
1498 1498
 		}
1499 1499
 		// does this attendee already exist in the db ? we're searching using a combination of first name, last name, AND email address
1500 1500
 		if ( ! empty( $attendee_data['ATT_fname'] )
1501
-		     && ! empty( $attendee_data['ATT_lname'] )
1502
-		     && ! empty( $attendee_data['ATT_email'] )
1501
+			 && ! empty( $attendee_data['ATT_lname'] )
1502
+			 && ! empty( $attendee_data['ATT_email'] )
1503 1503
 		) {
1504 1504
 			$existing_attendee = EE_Registry::instance()->LIB->EEM_Attendee->find_existing_attendee(
1505 1505
 				array(
@@ -1746,7 +1746,7 @@  discard block
 block discarded – undo
1746 1746
 			$payment_status = $payment->status();
1747 1747
 			if (
1748 1748
 				$payment_status === EEM_Payment::status_id_approved
1749
-			    || $payment_status === EEM_Payment::status_id_pending
1749
+				|| $payment_status === EEM_Payment::status_id_pending
1750 1750
 			) {
1751 1751
 				return true;
1752 1752
 			} else {
@@ -1972,8 +1972,8 @@  discard block
 block discarded – undo
1972 1972
 			return false;
1973 1973
 		}
1974 1974
 		if ( ! $primary_registration->_add_relation_to( $this->checkout->primary_attendee_obj, 'Attendee' )
1975
-		       instanceof
1976
-		       EE_Attendee
1975
+			   instanceof
1976
+			   EE_Attendee
1977 1977
 		) {
1978 1978
 			EE_Error::add_error(
1979 1979
 				sprintf(
@@ -2691,19 +2691,19 @@  discard block
 block discarded – undo
2691 2691
 
2692 2692
 
2693 2693
 
2694
-    /**
2695
-     *    __sleep
2696
-     * to conserve db space, let's remove the reg_form and the EE_Checkout object from EE_SPCO_Reg_Step objects upon serialization
2697
-     * EE_Checkout will handle the reimplementation of itself upon waking,
2698
-     * but we won't bother with the reg form, because if needed, it will be regenerated anyways
2699
-     *
2700
-     * @return array
2701
-     */
2702
-    public function __sleep()
2703
-    {
2704
-        // remove the reg form and the checkout
2705
-        return array_diff( array_keys( get_object_vars( $this ) ), array( 'reg_form', 'checkout', 'line_item_display' ) );
2706
-    }
2694
+	/**
2695
+	 *    __sleep
2696
+	 * to conserve db space, let's remove the reg_form and the EE_Checkout object from EE_SPCO_Reg_Step objects upon serialization
2697
+	 * EE_Checkout will handle the reimplementation of itself upon waking,
2698
+	 * but we won't bother with the reg form, because if needed, it will be regenerated anyways
2699
+	 *
2700
+	 * @return array
2701
+	 */
2702
+	public function __sleep()
2703
+	{
2704
+		// remove the reg form and the checkout
2705
+		return array_diff( array_keys( get_object_vars( $this ) ), array( 'reg_form', 'checkout', 'line_item_display' ) );
2706
+	}
2707 2707
 
2708 2708
 
2709 2709
 
Please login to merge, or discard this patch.
Spacing   +363 added lines, -363 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1
-<?php if ( ! defined( 'EVENT_ESPRESSO_VERSION' ) ) {
2
-	exit( 'No direct script access allowed' );
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -38,32 +38,32 @@  discard block
 block discarded – undo
38 38
 	public static function set_hooks() {
39 39
 		add_filter(
40 40
 			'FHEE__SPCO__EE_Line_Item_Filter_Collection',
41
-			array( 'EE_SPCO_Reg_Step_Payment_Options', 'add_spco_line_item_filters' )
41
+			array('EE_SPCO_Reg_Step_Payment_Options', 'add_spco_line_item_filters')
42 42
 		);
43 43
 		add_action(
44 44
 			'wp_ajax_switch_spco_billing_form',
45
-			array( 'EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form' )
45
+			array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
46 46
 		);
47 47
 		add_action(
48 48
 			'wp_ajax_nopriv_switch_spco_billing_form',
49
-			array( 'EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form' )
49
+			array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
50 50
 		);
51
-		add_action( 'wp_ajax_save_payer_details', array( 'EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details' ) );
51
+		add_action('wp_ajax_save_payer_details', array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details'));
52 52
 		add_action(
53 53
 			'wp_ajax_nopriv_save_payer_details',
54
-			array( 'EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details' )
54
+			array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details')
55 55
 		);
56 56
 		add_action(
57 57
 			'wp_ajax_get_transaction_details_for_gateways',
58
-			array( 'EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details' )
58
+			array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
59 59
 		);
60 60
 		add_action(
61 61
 			'wp_ajax_nopriv_get_transaction_details_for_gateways',
62
-			array( 'EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details' )
62
+			array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
63 63
 		);
64 64
 		add_filter(
65 65
 			'FHEE__EED_Recaptcha___bypass_recaptcha__bypass_request_params_array',
66
-			array( 'EE_SPCO_Reg_Step_Payment_Options', 'bypass_recaptcha_for_load_payment_method' ),
66
+			array('EE_SPCO_Reg_Step_Payment_Options', 'bypass_recaptcha_for_load_payment_method'),
67 67
 			10,
68 68
 			1
69 69
 		);
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
 	 * @throws \EE_Error
78 78
 	 */
79 79
 	public static function switch_spco_billing_form() {
80
-		EED_Single_Page_Checkout::process_ajax_request( 'switch_payment_method' );
80
+		EED_Single_Page_Checkout::process_ajax_request('switch_payment_method');
81 81
 	}
82 82
 
83 83
 
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
 	 * @throws \EE_Error
89 89
 	 */
90 90
 	public static function save_payer_details() {
91
-		EED_Single_Page_Checkout::process_ajax_request( 'save_payer_details_via_ajax' );
91
+		EED_Single_Page_Checkout::process_ajax_request('save_payer_details_via_ajax');
92 92
 	}
93 93
 
94 94
 
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
 	 * @throws \EE_Error
100 100
 	 */
101 101
 	public static function get_transaction_details() {
102
-		EED_Single_Page_Checkout::process_ajax_request( 'get_transaction_details_for_gateways' );
102
+		EED_Single_Page_Checkout::process_ajax_request('get_transaction_details_for_gateways');
103 103
 	}
104 104
 
105 105
 
@@ -126,10 +126,10 @@  discard block
 block discarded – undo
126 126
 	 * @access    public
127 127
 	 * @param    EE_Checkout $checkout
128 128
 	 */
129
-	public function __construct( EE_Checkout $checkout ) {
129
+	public function __construct(EE_Checkout $checkout) {
130 130
 		$this->_slug = 'payment_options';
131
-		$this->_name = __( 'Payment Options', 'event_espresso' );
132
-		$this->_template = SPCO_REG_STEPS_PATH . $this->_slug . DS . 'payment_options_main.template.php';
131
+		$this->_name = __('Payment Options', 'event_espresso');
132
+		$this->_template = SPCO_REG_STEPS_PATH.$this->_slug.DS.'payment_options_main.template.php';
133 133
 		$this->checkout = $checkout;
134 134
 		$this->_reset_success_message();
135 135
 		$this->set_instructions(
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
 	/**
155 155
 	 * @param null $line_item_display
156 156
 	 */
157
-	public function set_line_item_display( $line_item_display ) {
157
+	public function set_line_item_display($line_item_display) {
158 158
 		$this->line_item_display = $line_item_display;
159 159
 	}
160 160
 
@@ -172,8 +172,8 @@  discard block
 block discarded – undo
172 172
 	/**
173 173
 	 * @param boolean $handle_IPN_in_this_request
174 174
 	 */
175
-	public function set_handle_IPN_in_this_request( $handle_IPN_in_this_request ) {
176
-		$this->handle_IPN_in_this_request = filter_var( $handle_IPN_in_this_request, FILTER_VALIDATE_BOOLEAN );
175
+	public function set_handle_IPN_in_this_request($handle_IPN_in_this_request) {
176
+		$this->handle_IPN_in_this_request = filter_var($handle_IPN_in_this_request, FILTER_VALIDATE_BOOLEAN);
177 177
 	}
178 178
 
179 179
 
@@ -208,14 +208,14 @@  discard block
 block discarded – undo
208 208
 	public function enqueue_styles_and_scripts() {
209 209
 		$transaction = $this->checkout->transaction;
210 210
 		//if the transaction isn't set or nothing is owed on it, don't enqueue any JS
211
-		if( ! $transaction instanceof EE_Transaction || EEH_Money::compare_floats( $transaction->remaining(), 0 ) ) {
211
+		if ( ! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
212 212
 			return;
213 213
 		}
214
-		foreach( EEM_Payment_Method::instance()->get_all_for_transaction( $transaction, EEM_Payment_Method::scope_cart ) as $payment_method ) {
214
+		foreach (EEM_Payment_Method::instance()->get_all_for_transaction($transaction, EEM_Payment_Method::scope_cart) as $payment_method) {
215 215
 			$type_obj = $payment_method->type_obj();
216
-			if( $type_obj instanceof EE_PMT_Base ) {
217
-				$billing_form = $type_obj->generate_new_billing_form( $transaction );
218
-				if( $billing_form instanceof EE_Form_Section_Proper ) {
216
+			if ($type_obj instanceof EE_PMT_Base) {
217
+				$billing_form = $type_obj->generate_new_billing_form($transaction);
218
+				if ($billing_form instanceof EE_Form_Section_Proper) {
219 219
 					$billing_form->enqueue_js();
220 220
 				}
221 221
 			}
@@ -240,20 +240,20 @@  discard block
 block discarded – undo
240 240
 			// 	$ 0.00 transactions (no payment required)
241 241
 			! $this->checkout->payment_required()
242 242
 			// but do NOT remove if current action being called belongs to this reg step
243
-			&& ! is_callable( array( $this, $this->checkout->action ) )
243
+			&& ! is_callable(array($this, $this->checkout->action))
244 244
 			&& ! $this->completed()
245 245
 		) {
246 246
 			// and if so, then we no longer need the Payment Options step
247
-			if ( $this->is_current_step() ) {
247
+			if ($this->is_current_step()) {
248 248
 				$this->checkout->generate_reg_form = false;
249 249
 			}
250
-			$this->checkout->remove_reg_step( $this->_slug );
250
+			$this->checkout->remove_reg_step($this->_slug);
251 251
 			// DEBUG LOG
252 252
 			//$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__ );
253 253
 			return false;
254 254
 		}
255 255
 		// load EEM_Payment_Method
256
-		EE_Registry::instance()->load_model( 'Payment_Method' );
256
+		EE_Registry::instance()->load_model('Payment_Method');
257 257
 		// get all active payment methods
258 258
 		$this->checkout->available_payment_methods = EEM_Payment_Method::instance()->get_all_for_transaction(
259 259
 			$this->checkout->transaction,
@@ -280,16 +280,16 @@  discard block
 block discarded – undo
280 280
 		$insufficient_spaces_available = array();
281 281
 		$no_payment_required = true;
282 282
 		// loop thru registrations to gather info
283
-		$registrations = $this->checkout->transaction->registrations( $this->checkout->reg_cache_where_params );
283
+		$registrations = $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params);
284 284
 		$ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
285 285
 			$registrations,
286 286
 			$this->checkout->revisit
287 287
 		);
288
-		foreach ( $registrations as $REG_ID => $registration ) {
288
+		foreach ($registrations as $REG_ID => $registration) {
289 289
             /** @var $registration EE_Registration */
290 290
             // has this registration lost it's space ?
291
-			if ( isset( $ejected_registrations[ $REG_ID ] ) ) {
292
-				$insufficient_spaces_available[ $registration->event()->ID() ] = $registration->event();
291
+			if (isset($ejected_registrations[$REG_ID])) {
292
+				$insufficient_spaces_available[$registration->event()->ID()] = $registration->event();
293 293
 				continue;
294 294
 			}
295 295
             // event requires admin approval
@@ -310,11 +310,11 @@  discard block
 block discarded – undo
310 310
 				&& $registration->status_ID() !== EEM_Registration::status_id_approved
311 311
                 && (
312 312
                     $registration->event()->is_sold_out()
313
-                    || $registration->event()->is_sold_out( true )
313
+                    || $registration->event()->is_sold_out(true)
314 314
                 )
315 315
             ) {
316 316
                 // add event to list of events that are sold out
317
-                $sold_out_events[ $registration->event()->ID() ] = $registration->event();
317
+                $sold_out_events[$registration->event()->ID()] = $registration->event();
318 318
                 do_action(
319 319
                     'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__sold_out_event',
320 320
                     $registration->event(),
@@ -323,8 +323,8 @@  discard block
 block discarded – undo
323 323
                 continue;
324 324
 			}
325 325
 			// are they allowed to pay now and is there monies owing?
326
-			if ( $registration->owes_monies_and_can_pay() ) {
327
-				$registrations_requiring_payment[ $REG_ID ] = $registration;
326
+			if ($registration->owes_monies_and_can_pay()) {
327
+				$registrations_requiring_payment[$REG_ID] = $registration;
328 328
 				do_action(
329 329
 					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_payment',
330 330
 					$registration->event(),
@@ -335,29 +335,29 @@  discard block
 block discarded – undo
335 335
 				&& $registration->status_ID() !== EEM_Registration::status_id_not_approved
336 336
 				&& $registration->ticket()->is_free()
337 337
 			) {
338
-				$registrations_for_free_events[ $registration->event()->ID() ] = $registration;
338
+				$registrations_for_free_events[$registration->event()->ID()] = $registration;
339 339
 			}
340 340
 		}
341 341
 		$subsections = array();
342 342
 		// now decide which template to load
343
-		if ( ! empty( $sold_out_events ) ) {
344
-			$subsections['sold_out_events'] = $this->_sold_out_events( $sold_out_events );
343
+		if ( ! empty($sold_out_events)) {
344
+			$subsections['sold_out_events'] = $this->_sold_out_events($sold_out_events);
345 345
 		}
346
-		if ( ! empty( $insufficient_spaces_available ) ) {
346
+		if ( ! empty($insufficient_spaces_available)) {
347 347
 			$subsections['insufficient_space'] = $this->_insufficient_spaces_available(
348 348
 				$insufficient_spaces_available
349 349
 			);
350 350
 		}
351
-		if ( ! empty( $registrations_requiring_pre_approval ) ) {
351
+		if ( ! empty($registrations_requiring_pre_approval)) {
352 352
 			$subsections['registrations_requiring_pre_approval'] = $this->_registrations_requiring_pre_approval(
353 353
 				$registrations_requiring_pre_approval
354 354
 			);
355 355
 		}
356
-		if ( ! empty( $registrations_for_free_events ) ) {
357
-			$subsections['no_payment_required'] = $this->_no_payment_required( $registrations_for_free_events );
356
+		if ( ! empty($registrations_for_free_events)) {
357
+			$subsections['no_payment_required'] = $this->_no_payment_required($registrations_for_free_events);
358 358
 		}
359
-		if ( ! empty( $registrations_requiring_payment ) ) {
360
-			if ( $this->checkout->amount_owing > 0 ) {
359
+		if ( ! empty($registrations_requiring_payment)) {
360
+			if ($this->checkout->amount_owing > 0) {
361 361
 				// autoload Line_Item_Display classes
362 362
 				EEH_Autoloader::register_line_item_filter_autoloaders();
363 363
 				$line_item_filter_processor = new EE_Line_Item_Filter_Processor(
@@ -370,15 +370,15 @@  discard block
 block discarded – undo
370 370
 				/** @var EE_Line_Item $filtered_line_item_tree */
371 371
 				$filtered_line_item_tree = $line_item_filter_processor->process();
372 372
 				EEH_Autoloader::register_line_item_display_autoloaders();
373
-				$this->set_line_item_display( new EE_Line_Item_Display( 'spco' ) );
373
+				$this->set_line_item_display(new EE_Line_Item_Display('spco'));
374 374
 				$subsections['payment_options'] = $this->_display_payment_options(
375 375
 					$this->line_item_display->display_line_item(
376 376
 						$filtered_line_item_tree,
377
-						array( 'registrations' => $registrations )
377
+						array('registrations' => $registrations)
378 378
 					)
379 379
 				);
380 380
 				$this->checkout->amount_owing = $filtered_line_item_tree->total();
381
-				$this->_apply_registration_payments_to_amount_owing( $registrations );
381
+				$this->_apply_registration_payments_to_amount_owing($registrations);
382 382
 			}
383 383
 			$no_payment_required = false;
384 384
 		} else {
@@ -387,7 +387,7 @@  discard block
 block discarded – undo
387 387
 		$this->_save_selected_method_of_payment();
388 388
 
389 389
 		$subsections['default_hidden_inputs'] = $this->reg_step_hidden_inputs();
390
-		$subsections['extra_hidden_inputs' ] = $this->_extra_hidden_inputs( $no_payment_required );
390
+		$subsections['extra_hidden_inputs'] = $this->_extra_hidden_inputs($no_payment_required);
391 391
 
392 392
 		return new EE_Form_Section_Proper(
393 393
 			array(
@@ -414,14 +414,14 @@  discard block
 block discarded – undo
414 414
 	 * @return \EE_Line_Item_Filter_Collection
415 415
 	 * @throws \EE_Error
416 416
 	 */
417
-	public static function add_spco_line_item_filters( EE_Line_Item_Filter_Collection $line_item_filter_collection ) {
418
-		if ( ! EE_Registry::instance()->SSN instanceof EE_Session ) {
417
+	public static function add_spco_line_item_filters(EE_Line_Item_Filter_Collection $line_item_filter_collection) {
418
+		if ( ! EE_Registry::instance()->SSN instanceof EE_Session) {
419 419
 			return $line_item_filter_collection;
420 420
 		}
421
-		if ( ! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout ) {
421
+		if ( ! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
422 422
 			return $line_item_filter_collection;
423 423
 		}
424
-		if ( ! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction ) {
424
+		if ( ! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
425 425
 			return $line_item_filter_collection;
426 426
 		}
427 427
 		$line_item_filter_collection->add(
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
 				)
434 434
 			)
435 435
         );
436
-		$line_item_filter_collection->add( new EE_Non_Zero_Line_Item_Filter() );
436
+		$line_item_filter_collection->add(new EE_Non_Zero_Line_Item_Filter());
437 437
 		return $line_item_filter_collection;
438 438
 	}
439 439
 
@@ -449,15 +449,15 @@  discard block
 block discarded – undo
449 449
 	 * @return \EE_Registration[]
450 450
 	 * @throws \EE_Error
451 451
 	 */
452
-	public static function remove_ejected_registrations( array $registrations ) {
452
+	public static function remove_ejected_registrations(array $registrations) {
453 453
 		$ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
454 454
 			$registrations,
455 455
 			EE_Registry::instance()->SSN->checkout()->revisit
456 456
 		);
457
-		foreach ( $registrations as $REG_ID => $registration ) {
457
+		foreach ($registrations as $REG_ID => $registration) {
458 458
 			// has this registration lost it's space ?
459
-			if ( isset( $ejected_registrations[ $REG_ID ] ) ) {
460
-				unset( $registrations[ $REG_ID ] );
459
+			if (isset($ejected_registrations[$REG_ID])) {
460
+				unset($registrations[$REG_ID]);
461 461
 				continue;
462 462
 			}
463 463
 		}
@@ -480,7 +480,7 @@  discard block
 block discarded – undo
480 480
 	 * @return array
481 481
 	 * @throws \EE_Error
482 482
 	 */
483
-	public static function find_registrations_that_lost_their_space( array $registrations, $revisit = false ) {
483
+	public static function find_registrations_that_lost_their_space(array $registrations, $revisit = false) {
484 484
         // registrations per event
485 485
 		$event_reg_count = array();
486 486
 		// spaces left per event
@@ -489,8 +489,8 @@  discard block
 block discarded – undo
489 489
         $tickets_remaining = array();
490 490
         // registrations that have lost their space
491 491
 		$ejected_registrations = array();
492
-		foreach ( $registrations as $REG_ID => $registration ) {
493
-			if ( $registration->status_ID() === EEM_Registration::status_id_approved ) {
492
+		foreach ($registrations as $REG_ID => $registration) {
493
+			if ($registration->status_ID() === EEM_Registration::status_id_approved) {
494 494
 				continue;
495 495
 			}
496 496
 			$EVT_ID = $registration->event_ID();
@@ -511,13 +511,13 @@  discard block
 block discarded – undo
511 511
 				$revisit
512 512
 				&& (
513 513
                     $tickets_remaining[$ticket->ID()] === 0
514
-				    || $event_reg_count[ $EVT_ID ] > $event_spaces_remaining[ $EVT_ID ]
514
+				    || $event_reg_count[$EVT_ID] > $event_spaces_remaining[$EVT_ID]
515 515
                 )
516 516
 			) {
517
-				$ejected_registrations[ $REG_ID ] = $registration->event();
518
-				if ( $registration->status_ID() !== EEM_Registration::status_id_wait_list ) {
517
+				$ejected_registrations[$REG_ID] = $registration->event();
518
+				if ($registration->status_ID() !== EEM_Registration::status_id_wait_list) {
519 519
 					/** @type EE_Registration_Processor $registration_processor */
520
-					$registration_processor = EE_Registry::instance()->load_class( 'Registration_Processor' );
520
+					$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
521 521
 					// at this point, we should have enough details about the registrant to consider the registration NOT incomplete
522 522
 					$registration_processor->manually_update_registration_status(
523 523
 						$registration,
@@ -552,8 +552,8 @@  discard block
 block discarded – undo
552 552
 	 * @return void
553 553
 	 */
554 554
 	protected function _hide_reg_step_submit_button_if_revisit() {
555
-		if ( $this->checkout->revisit ) {
556
-			add_filter( 'FHEE__EE_SPCO_Reg_Step__reg_step_submit_button__sbmt_btn_html', '__return_empty_string' );
555
+		if ($this->checkout->revisit) {
556
+			add_filter('FHEE__EE_SPCO_Reg_Step__reg_step_submit_button__sbmt_btn_html', '__return_empty_string');
557 557
 		}
558 558
 	}
559 559
 
@@ -567,13 +567,13 @@  discard block
 block discarded – undo
567 567
 	 * @return \EE_Form_Section_Proper
568 568
 	 * @throws \EE_Error
569 569
 	 */
570
-	private function _sold_out_events( $sold_out_events_array = array() ) {
570
+	private function _sold_out_events($sold_out_events_array = array()) {
571 571
 		// set some defaults
572 572
 		$this->checkout->selected_method_of_payment = 'events_sold_out';
573 573
 		$sold_out_events = '';
574
-		foreach ( $sold_out_events_array as $sold_out_event ) {
574
+		foreach ($sold_out_events_array as $sold_out_event) {
575 575
 			$sold_out_events .= EEH_HTML::li(
576
-				EEH_HTML::span( '  ' .$sold_out_event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text' )
576
+				EEH_HTML::span('  '.$sold_out_event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
577 577
 			);
578 578
 		}
579 579
 		return new EE_Form_Section_Proper(
@@ -591,7 +591,7 @@  discard block
 block discarded – undo
591 591
 								'sold_out_events_msg' => apply_filters(
592 592
 									'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__sold_out_events_msg',
593 593
 									sprintf(
594
-										__( 'It appears that the event you were about to make a payment for has sold out since you first registered. If you have already made a partial payment towards this event, please contact the event administrator for a refund.%3$s%3$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.%2$s', 'event_espresso' ),
594
+										__('It appears that the event you were about to make a payment for has sold out since you first registered. If you have already made a partial payment towards this event, please contact the event administrator for a refund.%3$s%3$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.%2$s', 'event_espresso'),
595 595
 										'<strong>',
596 596
 										'</strong>',
597 597
 										'<br />'
@@ -616,14 +616,14 @@  discard block
 block discarded – undo
616 616
 	 * @return \EE_Form_Section_Proper
617 617
 	 * @throws \EE_Error
618 618
 	 */
619
-	private function _insufficient_spaces_available( $insufficient_spaces_events_array = array() ) {
619
+	private function _insufficient_spaces_available($insufficient_spaces_events_array = array()) {
620 620
 		// set some defaults
621 621
 		$this->checkout->selected_method_of_payment = 'invoice';
622 622
 		$insufficient_space_events = '';
623
-		foreach ( $insufficient_spaces_events_array as $event ) {
624
-			if ( $event instanceof EE_Event ) {
623
+		foreach ($insufficient_spaces_events_array as $event) {
624
+			if ($event instanceof EE_Event) {
625 625
 				$insufficient_space_events .= EEH_HTML::li(
626
-					EEH_HTML::span( ' ' . $event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text' )
626
+					EEH_HTML::span(' '.$event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
627 627
 				);
628 628
 			}
629 629
 		}
@@ -667,17 +667,17 @@  discard block
 block discarded – undo
667 667
 	 * @return \EE_Form_Section_Proper
668 668
 	 * @throws \EE_Error
669 669
 	 */
670
-	private function _registrations_requiring_pre_approval( $registrations_requiring_pre_approval = array() ) {
670
+	private function _registrations_requiring_pre_approval($registrations_requiring_pre_approval = array()) {
671 671
 		$events_requiring_pre_approval = '';
672
-		foreach ( $registrations_requiring_pre_approval as $registration ) {
673
-			if ( $registration instanceof EE_Registration && $registration->event() instanceof EE_Event ) {
674
-				$events_requiring_pre_approval[ $registration->event()->ID() ] = EEH_HTML::li(
672
+		foreach ($registrations_requiring_pre_approval as $registration) {
673
+			if ($registration instanceof EE_Registration && $registration->event() instanceof EE_Event) {
674
+				$events_requiring_pre_approval[$registration->event()->ID()] = EEH_HTML::li(
675 675
 					EEH_HTML::span(
676 676
 						'',
677 677
 						'',
678 678
 						'dashicons dashicons-marker ee-icon-size-16 orange-text'
679 679
 					)
680
-					. EEH_HTML::span( $registration->event()->name(), '', 'orange-text' )
680
+					. EEH_HTML::span($registration->event()->name(), '', 'orange-text')
681 681
 				);
682 682
 			}
683 683
 		}
@@ -692,7 +692,7 @@  discard block
 block discarded – undo
692 692
 						'template_args'        => apply_filters(
693 693
 							'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
694 694
 							array(
695
-								'events_requiring_pre_approval'     => implode( '', $events_requiring_pre_approval ),
695
+								'events_requiring_pre_approval'     => implode('', $events_requiring_pre_approval),
696 696
 								'events_requiring_pre_approval_msg' => apply_filters(
697 697
 									'FHEE__EE_SPCO_Reg_Step_Payment_Options___events_requiring_pre_approval__events_requiring_pre_approval_msg',
698 698
 									__(
@@ -717,7 +717,7 @@  discard block
 block discarded – undo
717 717
 	 * @return \EE_Form_Section_Proper
718 718
 	 * @throws \EE_Error
719 719
 	 */
720
-	private function _no_payment_required( $registrations_for_free_events = array() ) {
720
+	private function _no_payment_required($registrations_for_free_events = array()) {
721 721
 		// set some defaults
722 722
 		$this->checkout->selected_method_of_payment = 'no_payment_required';
723 723
 		// generate no_payment_required form
@@ -737,7 +737,7 @@  discard block
 block discarded – undo
737 737
 								'ticket_count'                  => array(),
738 738
 								'registrations_for_free_events' => $registrations_for_free_events,
739 739
 								'no_payment_required_msg'       => EEH_HTML::p(
740
-									__( 'This is a free event, so no billing will occur.', 'event_espresso' )
740
+									__('This is a free event, so no billing will occur.', 'event_espresso')
741 741
 								)
742 742
 							)
743 743
 						),
@@ -756,7 +756,7 @@  discard block
 block discarded – undo
756 756
 	 * @return \EE_Form_Section_Proper
757 757
 	 * @throws \EE_Error
758 758
 	 */
759
-	private function _display_payment_options( $transaction_details = '' ) {
759
+	private function _display_payment_options($transaction_details = '') {
760 760
 		// has method_of_payment been set by no-js user?
761 761
 		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment();
762 762
 		// build payment options form
@@ -768,14 +768,14 @@  discard block
 block discarded – undo
768 768
 						'before_payment_options' => apply_filters(
769 769
 							'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__before_payment_options',
770 770
 							new EE_Form_Section_Proper(
771
-								array( 'layout_strategy' => new EE_Div_Per_Section_Layout() )
771
+								array('layout_strategy' => new EE_Div_Per_Section_Layout())
772 772
 							)
773 773
 						),
774 774
 						'payment_options'        => $this->_setup_payment_options(),
775 775
 						'after_payment_options'  => apply_filters(
776 776
 							'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__after_payment_options',
777 777
 							new EE_Form_Section_Proper(
778
-								array( 'layout_strategy' => new EE_Div_Per_Section_Layout() )
778
+								array('layout_strategy' => new EE_Div_Per_Section_Layout())
779 779
 							)
780 780
 						),
781 781
 					),
@@ -806,10 +806,10 @@  discard block
 block discarded – undo
806 806
 	 * @return \EE_Form_Section_Proper
807 807
 	 * @throws \EE_Error
808 808
 	 */
809
-	private function _extra_hidden_inputs( $no_payment_required = true ) {
809
+	private function _extra_hidden_inputs($no_payment_required = true) {
810 810
 		return new EE_Form_Section_Proper(
811 811
 			array(
812
-				'html_id'         => 'ee-' . $this->slug() . '-extra-hidden-inputs',
812
+				'html_id'         => 'ee-'.$this->slug().'-extra-hidden-inputs',
813 813
 				'layout_strategy' => new EE_Div_Per_Section_Layout(),
814 814
 				'subsections'     => array(
815 815
 					'spco_no_payment_required' => new EE_Hidden_Input(
@@ -841,16 +841,16 @@  discard block
 block discarded – undo
841 841
 	 * @access protected
842 842
 	 * @param array $registrations
843 843
 	 */
844
-	protected function _apply_registration_payments_to_amount_owing( array $registrations ) {
844
+	protected function _apply_registration_payments_to_amount_owing(array $registrations) {
845 845
 		$payments = array();
846
-		foreach ( $registrations as $registration ) {
847
-			if ( $registration instanceof EE_Registration && $registration->owes_monies_and_can_pay() ) {
846
+		foreach ($registrations as $registration) {
847
+			if ($registration instanceof EE_Registration && $registration->owes_monies_and_can_pay()) {
848 848
 				$payments += $registration->registration_payments();
849 849
 			}
850 850
 		}
851
-		if ( ! empty( $payments ) ) {
852
-			foreach ( $payments as $payment ) {
853
-				if ( $payment instanceof EE_Registration_Payment ) {
851
+		if ( ! empty($payments)) {
852
+			foreach ($payments as $payment) {
853
+				if ($payment instanceof EE_Registration_Payment) {
854 854
 					$this->checkout->amount_owing -= $payment->amount();
855 855
 				}
856 856
 			}
@@ -866,11 +866,11 @@  discard block
 block discarded – undo
866 866
 	 * @param    bool $force_reset
867 867
 	 * @return    void
868 868
 	 */
869
-	private function _reset_selected_method_of_payment( $force_reset = false ) {
869
+	private function _reset_selected_method_of_payment($force_reset = false) {
870 870
 		$reset_payment_method = $force_reset
871 871
 			? true
872
-			: sanitize_text_field( EE_Registry::instance()->REQ->get( 'reset_payment_method', false ) );
873
-		if ( $reset_payment_method ) {
872
+			: sanitize_text_field(EE_Registry::instance()->REQ->get('reset_payment_method', false));
873
+		if ($reset_payment_method) {
874 874
 			$this->checkout->selected_method_of_payment = null;
875 875
 			$this->checkout->payment_method = null;
876 876
 			$this->checkout->billing_form = null;
@@ -889,12 +889,12 @@  discard block
 block discarded – undo
889 889
 	 * @param string $selected_method_of_payment
890 890
 	 * @return  void
891 891
 	 */
892
-	private function _save_selected_method_of_payment( $selected_method_of_payment = '' ) {
893
-		$selected_method_of_payment = ! empty( $selected_method_of_payment )
892
+	private function _save_selected_method_of_payment($selected_method_of_payment = '') {
893
+		$selected_method_of_payment = ! empty($selected_method_of_payment)
894 894
 			? $selected_method_of_payment
895 895
 			: $this->checkout->selected_method_of_payment;
896 896
 		EE_Registry::instance()->SSN->set_session_data(
897
-			array( 'selected_method_of_payment' => $selected_method_of_payment )
897
+			array('selected_method_of_payment' => $selected_method_of_payment)
898 898
 		);
899 899
 	}
900 900
 
@@ -910,19 +910,19 @@  discard block
 block discarded – undo
910 910
 		// load payment method classes
911 911
 		$this->checkout->available_payment_methods = $this->_get_available_payment_methods();
912 912
 		// switch up header depending on number of available payment methods
913
-		$payment_method_header = count( $this->checkout->available_payment_methods ) > 1
913
+		$payment_method_header = count($this->checkout->available_payment_methods) > 1
914 914
 			? apply_filters(
915 915
 				'FHEE__registration_page_payment_options__method_of_payment_hdr',
916
-				__( 'Please Select Your Method of Payment', 'event_espresso' )
916
+				__('Please Select Your Method of Payment', 'event_espresso')
917 917
 			)
918 918
 			: apply_filters(
919 919
 				'FHEE__registration_page_payment_options__method_of_payment_hdr',
920
-				__( 'Method of Payment', 'event_espresso' )
920
+				__('Method of Payment', 'event_espresso')
921 921
 			);
922 922
 		$available_payment_methods = array(
923 923
 			// display the "Payment Method" header
924 924
 			'payment_method_header' => new EE_Form_Section_HTML(
925
-				EEH_HTML::h4( $payment_method_header, 'method-of-payment-hdr' )
925
+				EEH_HTML::h4($payment_method_header, 'method-of-payment-hdr')
926 926
 			)
927 927
 		);
928 928
 		// the list of actual payment methods ( invoice, paypal, etc ) in a  ( slug => HTML )  format
@@ -931,32 +931,32 @@  discard block
 block discarded – undo
931 931
 		// additional instructions to be displayed and hidden below payment methods (adding a clearing div to start)
932 932
 		$payment_methods_billing_info = array(
933 933
 			new EE_Form_Section_HTML(
934
-				EEH_HTML::div( '<br />', '', '', 'clear:both;' )
934
+				EEH_HTML::div('<br />', '', '', 'clear:both;')
935 935
 			)
936 936
 		);
937 937
 		// loop through payment methods
938
-		foreach ( $this->checkout->available_payment_methods as $payment_method ) {
939
-			if ( $payment_method instanceof EE_Payment_Method ) {
938
+		foreach ($this->checkout->available_payment_methods as $payment_method) {
939
+			if ($payment_method instanceof EE_Payment_Method) {
940 940
 				$payment_method_button = EEH_HTML::img(
941 941
 					$payment_method->button_url(),
942 942
 					$payment_method->name(),
943
-					'spco-payment-method-' . $payment_method->slug() . '-btn-img',
943
+					'spco-payment-method-'.$payment_method->slug().'-btn-img',
944 944
 					'spco-payment-method-btn-img'
945 945
 				);
946 946
 				// check if any payment methods are set as default
947 947
 				// if payment method is already selected OR nothing is selected and this payment method should be open_by_default
948 948
 				if (
949
-					( $this->checkout->selected_method_of_payment === $payment_method->slug() )
950
-					|| ( ! $this->checkout->selected_method_of_payment && $payment_method->open_by_default() )
949
+					($this->checkout->selected_method_of_payment === $payment_method->slug())
950
+					|| ( ! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
951 951
 				) {
952 952
 					$this->checkout->selected_method_of_payment = $payment_method->slug();
953 953
 					$this->_save_selected_method_of_payment();
954
-					$default_payment_method_option[ $payment_method->slug() ] = $payment_method_button;
954
+					$default_payment_method_option[$payment_method->slug()] = $payment_method_button;
955 955
 				} else {
956
-					$available_payment_method_options[ $payment_method->slug() ] = $payment_method_button;
956
+					$available_payment_method_options[$payment_method->slug()] = $payment_method_button;
957 957
 				}
958
-				$payment_methods_billing_info[ $payment_method->slug()
959
-				                               . '-info' ] = $this->_payment_method_billing_info(
958
+				$payment_methods_billing_info[$payment_method->slug()
959
+				                               . '-info'] = $this->_payment_method_billing_info(
960 960
 					$payment_method
961 961
 				);
962 962
 			}
@@ -986,12 +986,12 @@  discard block
 block discarded – undo
986 986
 	 * @return EE_Payment_Method[]
987 987
 	 */
988 988
 	protected function _get_available_payment_methods() {
989
-		if ( ! empty( $this->checkout->available_payment_methods ) ) {
989
+		if ( ! empty($this->checkout->available_payment_methods)) {
990 990
 			return $this->checkout->available_payment_methods;
991 991
 		}
992 992
 		$available_payment_methods = array();
993 993
 		// load EEM_Payment_Method
994
-		EE_Registry::instance()->load_model( 'Payment_Method' );
994
+		EE_Registry::instance()->load_model('Payment_Method');
995 995
 		/** @type EEM_Payment_Method $EEM_Payment_Method */
996 996
 		$EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
997 997
 		// get all active payment methods
@@ -999,9 +999,9 @@  discard block
 block discarded – undo
999 999
 			$this->checkout->transaction,
1000 1000
 			EEM_Payment_Method::scope_cart
1001 1001
 		);
1002
-		foreach ( $payment_methods as $payment_method ) {
1003
-			if ( $payment_method instanceof EE_Payment_Method ) {
1004
-				$available_payment_methods[ $payment_method->slug() ] = $payment_method;
1002
+		foreach ($payment_methods as $payment_method) {
1003
+			if ($payment_method instanceof EE_Payment_Method) {
1004
+				$available_payment_methods[$payment_method->slug()] = $payment_method;
1005 1005
 			}
1006 1006
 		}
1007 1007
 		return $available_payment_methods;
@@ -1016,14 +1016,14 @@  discard block
 block discarded – undo
1016 1016
 	 * @param    array $available_payment_method_options
1017 1017
 	 * @return    \EE_Form_Section_Proper
1018 1018
 	 */
1019
-	private function _available_payment_method_inputs( $available_payment_method_options = array() ) {
1019
+	private function _available_payment_method_inputs($available_payment_method_options = array()) {
1020 1020
 		// generate inputs
1021 1021
 		return new EE_Form_Section_Proper(
1022 1022
 			array(
1023 1023
 				'html_id'         => 'ee-available-payment-method-inputs',
1024 1024
 				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1025 1025
 				'subsections'     => array(
1026
-					'' => new EE_Radio_Button_Input (
1026
+					'' => new EE_Radio_Button_Input(
1027 1027
 						$available_payment_method_options,
1028 1028
 						array(
1029 1029
 							'html_name'          => 'selected_method_of_payment',
@@ -1048,28 +1048,28 @@  discard block
 block discarded – undo
1048 1048
 	 * @return    \EE_Form_Section_Proper
1049 1049
 	 * @throws \EE_Error
1050 1050
 	 */
1051
-	private function _payment_method_billing_info( EE_Payment_Method $payment_method ) {
1051
+	private function _payment_method_billing_info(EE_Payment_Method $payment_method) {
1052 1052
 		$currently_selected = $this->checkout->selected_method_of_payment === $payment_method->slug()
1053 1053
 			? true
1054 1054
 			: false;
1055 1055
 		// generate the billing form for payment method
1056 1056
 		$billing_form = $currently_selected
1057
-			? $this->_get_billing_form_for_payment_method( $payment_method )
1057
+			? $this->_get_billing_form_for_payment_method($payment_method)
1058 1058
 			: new EE_Form_Section_HTML();
1059 1059
 		$this->checkout->billing_form = $currently_selected
1060 1060
 			? $billing_form
1061 1061
 			: $this->checkout->billing_form;
1062 1062
 		// it's all in the details
1063 1063
 		$info_html = EEH_HTML::h3(
1064
-			__( 'Important information regarding your payment', 'event_espresso' ),
1064
+			__('Important information regarding your payment', 'event_espresso'),
1065 1065
 			'',
1066 1066
 			'spco-payment-method-hdr'
1067 1067
 		);
1068 1068
 		// add some info regarding the step, either from what's saved in the admin,
1069 1069
 		// or a default string depending on whether the PM has a billing form or not
1070
-		if ( $payment_method->description() ) {
1070
+		if ($payment_method->description()) {
1071 1071
 			$payment_method_info = $payment_method->description();
1072
-		} elseif ( $billing_form instanceof EE_Billing_Info_Form ) {
1072
+		} elseif ($billing_form instanceof EE_Billing_Info_Form) {
1073 1073
 			$payment_method_info = sprintf(
1074 1074
 				__(
1075 1075
 					'Please provide the following billing information, then click the "%1$s" button below in order to proceed.',
@@ -1079,7 +1079,7 @@  discard block
 block discarded – undo
1079 1079
 			);
1080 1080
 		} else {
1081 1081
 			$payment_method_info = sprintf(
1082
-				__( 'Please click the "%1$s" button below in order to proceed.', 'event_espresso' ),
1082
+				__('Please click the "%1$s" button below in order to proceed.', 'event_espresso'),
1083 1083
 				$this->submit_button_text()
1084 1084
 			);
1085 1085
 		}
@@ -1093,13 +1093,13 @@  discard block
 block discarded – undo
1093 1093
 		);
1094 1094
 		return new EE_Form_Section_Proper(
1095 1095
 			array(
1096
-				'html_id'         => 'spco-payment-method-info-' . $payment_method->slug(),
1096
+				'html_id'         => 'spco-payment-method-info-'.$payment_method->slug(),
1097 1097
 				'html_class'      => 'spco-payment-method-info-dv',
1098 1098
 				// only display the selected or default PM
1099 1099
 				'html_style'      => $currently_selected ? '' : 'display:none;',
1100 1100
 				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1101 1101
 				'subsections'     => array(
1102
-					'info'         => new EE_Form_Section_HTML( $info_html ),
1102
+					'info'         => new EE_Form_Section_HTML($info_html),
1103 1103
 					'billing_form' => $currently_selected ? $billing_form : new EE_Form_Section_HTML()
1104 1104
 				)
1105 1105
 			)
@@ -1117,15 +1117,15 @@  discard block
 block discarded – undo
1117 1117
 	 */
1118 1118
 	public function get_billing_form_html_for_payment_method() {
1119 1119
 		// how have they chosen to pay?
1120
-		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment( true );
1120
+		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1121 1121
 		$this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1122
-		if ( ! $this->checkout->payment_method instanceof EE_Payment_Method ) {
1122
+		if ( ! $this->checkout->payment_method instanceof EE_Payment_Method) {
1123 1123
 			return false;
1124 1124
 		}
1125
-		if ( apply_filters(
1125
+		if (apply_filters(
1126 1126
 			'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1127 1127
 			false
1128
-		) ) {
1128
+		)) {
1129 1129
 			EE_Error::add_success(
1130 1130
 				apply_filters(
1131 1131
 					'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
@@ -1140,7 +1140,7 @@  discard block
 block discarded – undo
1140 1140
 			);
1141 1141
 		}
1142 1142
 		// now generate billing form for selected method of payment
1143
-		$payment_method_billing_form = $this->_get_billing_form_for_payment_method( $this->checkout->payment_method );
1143
+		$payment_method_billing_form = $this->_get_billing_form_for_payment_method($this->checkout->payment_method);
1144 1144
 		// fill form with attendee info if applicable
1145 1145
 		if (
1146 1146
 			$payment_method_billing_form instanceof EE_Billing_Attendee_Info_Form
@@ -1162,10 +1162,10 @@  discard block
 block discarded – undo
1162 1162
 		$billing_info = $payment_method_billing_form instanceof EE_Form_Section_Proper
1163 1163
 			? $payment_method_billing_form->get_html()
1164 1164
 			: '';
1165
-		$this->checkout->json_response->set_return_data( array( 'payment_method_info' => $billing_info ) );
1165
+		$this->checkout->json_response->set_return_data(array('payment_method_info' => $billing_info));
1166 1166
 		// localize validation rules for main form
1167 1167
 		$this->checkout->current_step->reg_form->localize_validation_rules();
1168
-		$this->checkout->json_response->add_validation_rules( EE_Form_Section_Proper::js_localization() );
1168
+		$this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1169 1169
 		return true;
1170 1170
 	}
1171 1171
 
@@ -1179,18 +1179,18 @@  discard block
 block discarded – undo
1179 1179
 	 * @return \EE_Billing_Info_Form|\EE_Form_Section_HTML
1180 1180
 	 * @throws \EE_Error
1181 1181
 	 */
1182
-	private function _get_billing_form_for_payment_method( EE_Payment_Method $payment_method ) {
1182
+	private function _get_billing_form_for_payment_method(EE_Payment_Method $payment_method) {
1183 1183
 		$billing_form = $payment_method->type_obj()->billing_form(
1184 1184
 			$this->checkout->transaction,
1185
-			array( 'amount_owing' => $this->checkout->amount_owing )
1185
+			array('amount_owing' => $this->checkout->amount_owing)
1186 1186
 		);
1187
-		if ( $billing_form instanceof EE_Billing_Info_Form ) {
1187
+		if ($billing_form instanceof EE_Billing_Info_Form) {
1188 1188
 			if (
1189 1189
 				apply_filters(
1190 1190
 					'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1191 1191
 					false
1192 1192
 				)
1193
-				&& EE_Registry::instance()->REQ->is_set( 'payment_method' )
1193
+				&& EE_Registry::instance()->REQ->is_set('payment_method')
1194 1194
 			) {
1195 1195
 				EE_Error::add_success(
1196 1196
 					apply_filters(
@@ -1232,15 +1232,15 @@  discard block
 block discarded – undo
1232 1232
 		$request_param = 'selected_method_of_payment'
1233 1233
 	) {
1234 1234
 		// is selected_method_of_payment set in the request ?
1235
-		$selected_method_of_payment = EE_Registry::instance()->REQ->get( $request_param, false );
1236
-		if ( $selected_method_of_payment ) {
1235
+		$selected_method_of_payment = EE_Registry::instance()->REQ->get($request_param, false);
1236
+		if ($selected_method_of_payment) {
1237 1237
 			// sanitize it
1238
-			$selected_method_of_payment = is_array( $selected_method_of_payment )
1239
-				? array_shift( $selected_method_of_payment )
1238
+			$selected_method_of_payment = is_array($selected_method_of_payment)
1239
+				? array_shift($selected_method_of_payment)
1240 1240
 				: $selected_method_of_payment;
1241
-			$selected_method_of_payment = sanitize_text_field( $selected_method_of_payment );
1241
+			$selected_method_of_payment = sanitize_text_field($selected_method_of_payment);
1242 1242
 			// store it in the session so that it's available for all subsequent requests including AJAX
1243
-			$this->_save_selected_method_of_payment( $selected_method_of_payment );
1243
+			$this->_save_selected_method_of_payment($selected_method_of_payment);
1244 1244
 		} else {
1245 1245
 			// or is is set in the session ?
1246 1246
 			$selected_method_of_payment = EE_Registry::instance()->SSN->get_session_data(
@@ -1248,7 +1248,7 @@  discard block
 block discarded – undo
1248 1248
 			);
1249 1249
 		}
1250 1250
 		// do ya really really gotta have it?
1251
-		if ( empty( $selected_method_of_payment ) && $required ) {
1251
+		if (empty($selected_method_of_payment) && $required) {
1252 1252
 			EE_Error::add_error(
1253 1253
 				sprintf(
1254 1254
 					__(
@@ -1257,7 +1257,7 @@  discard block
 block discarded – undo
1257 1257
 					),
1258 1258
 					'<br/>',
1259 1259
 					'<br/>',
1260
-					EE_Registry::instance()->CFG->organization->get_pretty( 'email' )
1260
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
1261 1261
 				),
1262 1262
 				__FILE__,
1263 1263
 				__FUNCTION__,
@@ -1284,13 +1284,13 @@  discard block
 block discarded – undo
1284 1284
 	 * @throws \EE_Error
1285 1285
 	 */
1286 1286
 	public function switch_payment_method() {
1287
-		if ( ! $this->_verify_payment_method_is_set() ) {
1287
+		if ( ! $this->_verify_payment_method_is_set()) {
1288 1288
 			return false;
1289 1289
 		}
1290
-		if ( apply_filters(
1290
+		if (apply_filters(
1291 1291
 			'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1292 1292
 			false
1293
-		) ) {
1293
+		)) {
1294 1294
 			EE_Error::add_success(
1295 1295
 				apply_filters(
1296 1296
 					'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
@@ -1305,7 +1305,7 @@  discard block
 block discarded – undo
1305 1305
 			);
1306 1306
 		}
1307 1307
 		// generate billing form for selected method of payment if it hasn't been done already
1308
-		if ( $this->checkout->payment_method->type_obj()->has_billing_form() ) {
1308
+		if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1309 1309
 			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1310 1310
 				$this->checkout->payment_method
1311 1311
 			);
@@ -1327,7 +1327,7 @@  discard block
 block discarded – undo
1327 1327
 			);
1328 1328
 		}
1329 1329
 		// and debug content
1330
-		if ( $this->checkout->billing_form instanceof EE_Billing_Info_Form
1330
+		if ($this->checkout->billing_form instanceof EE_Billing_Info_Form
1331 1331
 		     && $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1332 1332
 		) {
1333 1333
 			$this->checkout->billing_form = $this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
@@ -1335,15 +1335,15 @@  discard block
 block discarded – undo
1335 1335
 			);
1336 1336
 		}
1337 1337
 		// get html and validation rules for form
1338
-		if ( $this->checkout->billing_form instanceof EE_Form_Section_Proper ) {
1338
+		if ($this->checkout->billing_form instanceof EE_Form_Section_Proper) {
1339 1339
 			$this->checkout->json_response->set_return_data(
1340
-				array( 'payment_method_info' => $this->checkout->billing_form->get_html() )
1340
+				array('payment_method_info' => $this->checkout->billing_form->get_html())
1341 1341
 			);
1342 1342
 			// localize validation rules for main form
1343
-			$this->checkout->billing_form->localize_validation_rules( true );
1344
-			$this->checkout->json_response->add_validation_rules( EE_Form_Section_Proper::js_localization() );
1343
+			$this->checkout->billing_form->localize_validation_rules(true);
1344
+			$this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1345 1345
 		} else {
1346
-			$this->checkout->json_response->set_return_data( array( 'payment_method_info' => '' ) );
1346
+			$this->checkout->json_response->set_return_data(array('payment_method_info' => ''));
1347 1347
 		}
1348 1348
 		//prevents advancement to next step
1349 1349
 		$this->checkout->continue_reg = false;
@@ -1360,18 +1360,18 @@  discard block
 block discarded – undo
1360 1360
 	 */
1361 1361
 	protected function _verify_payment_method_is_set() {
1362 1362
 		// generate billing form for selected method of payment if it hasn't been done already
1363
-		if ( empty( $this->checkout->selected_method_of_payment ) ) {
1363
+		if (empty($this->checkout->selected_method_of_payment)) {
1364 1364
 			// how have they chosen to pay?
1365
-			$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment( true );
1365
+			$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1366 1366
 		} else {
1367 1367
 			// choose your own adventure based on method_of_payment
1368
-			switch ( $this->checkout->selected_method_of_payment ) {
1368
+			switch ($this->checkout->selected_method_of_payment) {
1369 1369
 				case 'events_sold_out' :
1370 1370
 					EE_Error::add_attention(
1371 1371
 						apply_filters(
1372 1372
 							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__sold_out_events_msg',
1373
-							__( 'It appears that the event you were about to make a payment for has sold out since this form first loaded. Please contact the event administrator if you believe this is an error.',
1374
-								'event_espresso' )
1373
+							__('It appears that the event you were about to make a payment for has sold out since this form first loaded. Please contact the event administrator if you believe this is an error.',
1374
+								'event_espresso')
1375 1375
 						),
1376 1376
 						__FILE__, __FUNCTION__, __LINE__
1377 1377
 					);
@@ -1381,7 +1381,7 @@  discard block
 block discarded – undo
1381 1381
 					EE_Error::add_attention(
1382 1382
 						apply_filters(
1383 1383
 							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__payments_closed_msg',
1384
-							__( 'It appears that the event you were about to make a payment for is not accepting payments at this time. Please contact the event administrator if you believe this is an error.', 'event_espresso' )
1384
+							__('It appears that the event you were about to make a payment for is not accepting payments at this time. Please contact the event administrator if you believe this is an error.', 'event_espresso')
1385 1385
 						),
1386 1386
 						__FILE__, __FUNCTION__, __LINE__
1387 1387
 					);
@@ -1391,7 +1391,7 @@  discard block
 block discarded – undo
1391 1391
 					EE_Error::add_attention(
1392 1392
 						apply_filters(
1393 1393
 							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__no_payment_required_msg',
1394
-							__( 'It appears that the event you were about to make a payment for does not require payment. Please contact the event administrator if you believe this is an error.', 'event_espresso' )
1394
+							__('It appears that the event you were about to make a payment for does not require payment. Please contact the event administrator if you believe this is an error.', 'event_espresso')
1395 1395
 						),
1396 1396
 						__FILE__, __FUNCTION__, __LINE__
1397 1397
 					);
@@ -1401,7 +1401,7 @@  discard block
 block discarded – undo
1401 1401
 			}
1402 1402
 		}
1403 1403
 		// verify payment method
1404
-		if ( ! $this->checkout->payment_method instanceof EE_Payment_Method ) {
1404
+		if ( ! $this->checkout->payment_method instanceof EE_Payment_Method) {
1405 1405
 			// get payment method for selected method of payment
1406 1406
 			$this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1407 1407
 		}
@@ -1420,25 +1420,25 @@  discard block
 block discarded – undo
1420 1420
 	 * @throws \EE_Error
1421 1421
 	 */
1422 1422
 	public function save_payer_details_via_ajax() {
1423
-		if ( ! $this->_verify_payment_method_is_set() ) {
1423
+		if ( ! $this->_verify_payment_method_is_set()) {
1424 1424
 			return;
1425 1425
 		}
1426 1426
 		// generate billing form for selected method of payment if it hasn't been done already
1427
-		if ( $this->checkout->payment_method->type_obj()->has_billing_form() ) {
1427
+		if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1428 1428
 			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1429 1429
 				$this->checkout->payment_method
1430 1430
 			);
1431 1431
 		}
1432 1432
 		// generate primary attendee from payer info if applicable
1433
-		if ( ! $this->checkout->transaction_has_primary_registrant() ) {
1433
+		if ( ! $this->checkout->transaction_has_primary_registrant()) {
1434 1434
 			$attendee = $this->_create_attendee_from_request_data();
1435
-			if ( $attendee instanceof EE_Attendee ) {
1436
-				foreach ( $this->checkout->transaction->registrations() as $registration ) {
1437
-					if ( $registration->is_primary_registrant() ) {
1435
+			if ($attendee instanceof EE_Attendee) {
1436
+				foreach ($this->checkout->transaction->registrations() as $registration) {
1437
+					if ($registration->is_primary_registrant()) {
1438 1438
 						$this->checkout->primary_attendee_obj = $attendee;
1439
-						$registration->_add_relation_to( $attendee, 'Attendee' );
1440
-						$registration->set_attendee_id( $attendee->ID() );
1441
-						$registration->update_cache_after_object_save( 'Attendee', $attendee );
1439
+						$registration->_add_relation_to($attendee, 'Attendee');
1440
+						$registration->set_attendee_id($attendee->ID());
1441
+						$registration->update_cache_after_object_save('Attendee', $attendee);
1442 1442
 					}
1443 1443
 				}
1444 1444
 			}
@@ -1456,50 +1456,50 @@  discard block
 block discarded – undo
1456 1456
 	 */
1457 1457
 	protected function _create_attendee_from_request_data() {
1458 1458
 		// get State ID
1459
-		$STA_ID = ! empty( $_REQUEST['state'] ) ? sanitize_text_field( $_REQUEST['state'] ) : '';
1460
-		if ( ! empty( $STA_ID ) ) {
1459
+		$STA_ID = ! empty($_REQUEST['state']) ? sanitize_text_field($_REQUEST['state']) : '';
1460
+		if ( ! empty($STA_ID)) {
1461 1461
 			// can we get state object from name ?
1462
-			EE_Registry::instance()->load_model( 'State' );
1463
-			$state = EEM_State::instance()->get_col( array( array( 'STA_name' => $STA_ID ), 'limit' => 1 ), 'STA_ID' );
1464
-			$STA_ID = is_array( $state ) && ! empty( $state ) ? reset( $state ) : $STA_ID;
1462
+			EE_Registry::instance()->load_model('State');
1463
+			$state = EEM_State::instance()->get_col(array(array('STA_name' => $STA_ID), 'limit' => 1), 'STA_ID');
1464
+			$STA_ID = is_array($state) && ! empty($state) ? reset($state) : $STA_ID;
1465 1465
 		}
1466 1466
 		// get Country ISO
1467
-		$CNT_ISO = ! empty( $_REQUEST['country'] ) ? sanitize_text_field( $_REQUEST['country'] ) : '';
1468
-		if ( ! empty( $CNT_ISO ) ) {
1467
+		$CNT_ISO = ! empty($_REQUEST['country']) ? sanitize_text_field($_REQUEST['country']) : '';
1468
+		if ( ! empty($CNT_ISO)) {
1469 1469
 			// can we get country object from name ?
1470
-			EE_Registry::instance()->load_model( 'Country' );
1470
+			EE_Registry::instance()->load_model('Country');
1471 1471
 			$country = EEM_Country::instance()->get_col(
1472
-				array( array( 'CNT_name' => $CNT_ISO ), 'limit' => 1 ),
1472
+				array(array('CNT_name' => $CNT_ISO), 'limit' => 1),
1473 1473
 				'CNT_ISO'
1474 1474
 			);
1475
-			$CNT_ISO = is_array( $country ) && ! empty( $country ) ? reset( $country ) : $CNT_ISO;
1475
+			$CNT_ISO = is_array($country) && ! empty($country) ? reset($country) : $CNT_ISO;
1476 1476
 		}
1477 1477
 		// grab attendee data
1478 1478
 		$attendee_data = array(
1479
-			'ATT_fname'    => ! empty( $_REQUEST['first_name'] ) ? sanitize_text_field( $_REQUEST['first_name'] ) : '',
1480
-			'ATT_lname'    => ! empty( $_REQUEST['last_name'] ) ? sanitize_text_field( $_REQUEST['last_name'] ) : '',
1481
-			'ATT_email'    => ! empty( $_REQUEST['email'] ) ? sanitize_email( $_REQUEST['email'] ) : '',
1482
-			'ATT_address'  => ! empty( $_REQUEST['address'] ) ? sanitize_text_field( $_REQUEST['address'] ) : '',
1483
-			'ATT_address2' => ! empty( $_REQUEST['address2'] ) ? sanitize_text_field( $_REQUEST['address2'] ) : '',
1484
-			'ATT_city'     => ! empty( $_REQUEST['city'] ) ? sanitize_text_field( $_REQUEST['city'] ) : '',
1479
+			'ATT_fname'    => ! empty($_REQUEST['first_name']) ? sanitize_text_field($_REQUEST['first_name']) : '',
1480
+			'ATT_lname'    => ! empty($_REQUEST['last_name']) ? sanitize_text_field($_REQUEST['last_name']) : '',
1481
+			'ATT_email'    => ! empty($_REQUEST['email']) ? sanitize_email($_REQUEST['email']) : '',
1482
+			'ATT_address'  => ! empty($_REQUEST['address']) ? sanitize_text_field($_REQUEST['address']) : '',
1483
+			'ATT_address2' => ! empty($_REQUEST['address2']) ? sanitize_text_field($_REQUEST['address2']) : '',
1484
+			'ATT_city'     => ! empty($_REQUEST['city']) ? sanitize_text_field($_REQUEST['city']) : '',
1485 1485
 			'STA_ID'       => $STA_ID,
1486 1486
 			'CNT_ISO'      => $CNT_ISO,
1487
-			'ATT_zip'      => ! empty( $_REQUEST['zip'] ) ? sanitize_text_field( $_REQUEST['zip'] ) : '',
1488
-			'ATT_phone'    => ! empty( $_REQUEST['phone'] ) ? sanitize_text_field( $_REQUEST['phone'] ) : '',
1487
+			'ATT_zip'      => ! empty($_REQUEST['zip']) ? sanitize_text_field($_REQUEST['zip']) : '',
1488
+			'ATT_phone'    => ! empty($_REQUEST['phone']) ? sanitize_text_field($_REQUEST['phone']) : '',
1489 1489
 		);
1490 1490
 		// validate the email address since it is the most important piece of info
1491
-		if ( empty( $attendee_data['ATT_email'] ) || $attendee_data['ATT_email'] !== $_REQUEST['email'] ) {
1491
+		if (empty($attendee_data['ATT_email']) || $attendee_data['ATT_email'] !== $_REQUEST['email']) {
1492 1492
 			EE_Error::add_error(
1493
-				__( 'An invalid email address was submitted.', 'event_espresso' ),
1493
+				__('An invalid email address was submitted.', 'event_espresso'),
1494 1494
 				__FILE__,
1495 1495
 				__FUNCTION__,
1496 1496
 				__LINE__
1497 1497
 			);
1498 1498
 		}
1499 1499
 		// does this attendee already exist in the db ? we're searching using a combination of first name, last name, AND email address
1500
-		if ( ! empty( $attendee_data['ATT_fname'] )
1501
-		     && ! empty( $attendee_data['ATT_lname'] )
1502
-		     && ! empty( $attendee_data['ATT_email'] )
1500
+		if ( ! empty($attendee_data['ATT_fname'])
1501
+		     && ! empty($attendee_data['ATT_lname'])
1502
+		     && ! empty($attendee_data['ATT_email'])
1503 1503
 		) {
1504 1504
 			$existing_attendee = EE_Registry::instance()->LIB->EEM_Attendee->find_existing_attendee(
1505 1505
 				array(
@@ -1508,19 +1508,19 @@  discard block
 block discarded – undo
1508 1508
 					'ATT_email' => $attendee_data['ATT_email']
1509 1509
 				)
1510 1510
 			);
1511
-			if ( $existing_attendee instanceof EE_Attendee ) {
1511
+			if ($existing_attendee instanceof EE_Attendee) {
1512 1512
 				return $existing_attendee;
1513 1513
 			}
1514 1514
 		}
1515 1515
 		// no existing attendee? kk let's create a new one
1516 1516
 		// kinda lame, but we need a first and last name to create an attendee, so use the email address if those don't exist
1517
-		$attendee_data['ATT_fname'] = ! empty( $attendee_data['ATT_fname'] )
1517
+		$attendee_data['ATT_fname'] = ! empty($attendee_data['ATT_fname'])
1518 1518
 			? $attendee_data['ATT_fname']
1519 1519
 			: $attendee_data['ATT_email'];
1520
-		$attendee_data['ATT_lname'] = ! empty( $attendee_data['ATT_lname'] )
1520
+		$attendee_data['ATT_lname'] = ! empty($attendee_data['ATT_lname'])
1521 1521
 			? $attendee_data['ATT_lname']
1522 1522
 			: $attendee_data['ATT_email'];
1523
-		return EE_Attendee::new_instance( $attendee_data );
1523
+		return EE_Attendee::new_instance($attendee_data);
1524 1524
 	}
1525 1525
 
1526 1526
 
@@ -1538,26 +1538,26 @@  discard block
 block discarded – undo
1538 1538
 		// how have they chosen to pay?
1539 1539
 		$this->checkout->selected_method_of_payment = $this->checkout->transaction->is_free()
1540 1540
 			? 'no_payment_required'
1541
-			: $this->_get_selected_method_of_payment( true );
1541
+			: $this->_get_selected_method_of_payment(true);
1542 1542
 		// choose your own adventure based on method_of_payment
1543
-		switch ( $this->checkout->selected_method_of_payment ) {
1543
+		switch ($this->checkout->selected_method_of_payment) {
1544 1544
 
1545 1545
 			case 'events_sold_out' :
1546 1546
 				$this->checkout->redirect = true;
1547 1547
 				$this->checkout->redirect_url = $this->checkout->cancel_page_url;
1548
-				$this->checkout->json_response->set_redirect_url( $this->checkout->redirect_url );
1548
+				$this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1549 1549
 				// mark this reg step as completed
1550 1550
 				$this->set_completed();
1551 1551
 				return false;
1552 1552
 				break;
1553 1553
 
1554 1554
 			case 'payments_closed' :
1555
-				if ( apply_filters(
1555
+				if (apply_filters(
1556 1556
 					'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__payments_closed__display_success',
1557 1557
 					false
1558
-				) ) {
1558
+				)) {
1559 1559
 					EE_Error::add_success(
1560
-						__( 'no payment required at this time.', 'event_espresso' ),
1560
+						__('no payment required at this time.', 'event_espresso'),
1561 1561
 						__FILE__,
1562 1562
 						__FUNCTION__,
1563 1563
 						__LINE__
@@ -1569,12 +1569,12 @@  discard block
 block discarded – undo
1569 1569
 				break;
1570 1570
 
1571 1571
 			case 'no_payment_required' :
1572
-				if ( apply_filters(
1572
+				if (apply_filters(
1573 1573
 					'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__no_payment_required__display_success',
1574 1574
 					false
1575
-				) ) {
1575
+				)) {
1576 1576
 					EE_Error::add_success(
1577
-						__( 'no payment required.', 'event_espresso' ),
1577
+						__('no payment required.', 'event_espresso'),
1578 1578
 						__FILE__,
1579 1579
 						__FUNCTION__,
1580 1580
 						__LINE__
@@ -1594,15 +1594,15 @@  discard block
 block discarded – undo
1594 1594
 					EE_Registry::instance()->SSN->checkout()->revisit
1595 1595
 				);
1596 1596
 				// calculate difference between the two arrays
1597
-				$registrations = array_diff( $registrations, $ejected_registrations );
1598
-				if ( empty( $registrations ) ) {
1597
+				$registrations = array_diff($registrations, $ejected_registrations);
1598
+				if (empty($registrations)) {
1599 1599
 					$this->_redirect_because_event_sold_out();
1600 1600
 					return false;
1601 1601
 				}
1602 1602
 				$payment_successful = $this->_process_payment();
1603
-				if ( $payment_successful ) {
1603
+				if ($payment_successful) {
1604 1604
 					$this->checkout->continue_reg = true;
1605
-					$this->_maybe_set_completed( $this->checkout->payment_method );
1605
+					$this->_maybe_set_completed($this->checkout->payment_method);
1606 1606
 				} else {
1607 1607
 					$this->checkout->continue_reg = false;
1608 1608
 				}
@@ -1623,10 +1623,10 @@  discard block
 block discarded – undo
1623 1623
 		$this->checkout->continue_reg = false;
1624 1624
 		// set redirect URL
1625 1625
 		$this->checkout->redirect_url = add_query_arg(
1626
-			array( 'e_reg_url_link' => $this->checkout->reg_url_link ),
1626
+			array('e_reg_url_link' => $this->checkout->reg_url_link),
1627 1627
 			$this->checkout->current_step->reg_step_url()
1628 1628
 		);
1629
-		$this->checkout->json_response->set_redirect_url( $this->checkout->redirect_url );
1629
+		$this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1630 1630
 	}
1631 1631
 
1632 1632
 
@@ -1639,8 +1639,8 @@  discard block
 block discarded – undo
1639 1639
 	 * @return void
1640 1640
 	 * @throws \EE_Error
1641 1641
 	 */
1642
-	protected function _maybe_set_completed( EE_Payment_Method $payment_method ) {
1643
-		switch ( $payment_method->type_obj()->payment_occurs() ) {
1642
+	protected function _maybe_set_completed(EE_Payment_Method $payment_method) {
1643
+		switch ($payment_method->type_obj()->payment_occurs()) {
1644 1644
 			case EE_PMT_Base::offsite :
1645 1645
 				break;
1646 1646
 			case EE_PMT_Base::onsite :
@@ -1663,7 +1663,7 @@  discard block
 block discarded – undo
1663 1663
 	public function update_reg_step() {
1664 1664
 		$success = true;
1665 1665
 		// if payment required
1666
-		if ( $this->checkout->transaction->total() > 0 ) {
1666
+		if ($this->checkout->transaction->total() > 0) {
1667 1667
 			do_action(
1668 1668
 				'AHEE__EE_Single_Page_Checkout__process_finalize_registration__before_gateway',
1669 1669
 				$this->checkout->transaction
@@ -1671,13 +1671,13 @@  discard block
 block discarded – undo
1671 1671
 			// attempt payment via payment method
1672 1672
 			$success = $this->process_reg_step();
1673 1673
 		}
1674
-		if ( $success && ! $this->checkout->redirect ) {
1674
+		if ($success && ! $this->checkout->redirect) {
1675 1675
 			$this->checkout->cart->get_grand_total()->save_this_and_descendants_to_txn(
1676 1676
 				$this->checkout->transaction->ID()
1677 1677
 			);
1678 1678
 			// set return URL
1679 1679
 			$this->checkout->redirect_url = add_query_arg(
1680
-				array( 'e_reg_url_link' => $this->checkout->reg_url_link ),
1680
+				array('e_reg_url_link' => $this->checkout->reg_url_link),
1681 1681
 				$this->checkout->thank_you_page_url
1682 1682
 			);
1683 1683
 		}
@@ -1695,36 +1695,36 @@  discard block
 block discarded – undo
1695 1695
 	 */
1696 1696
 	private function _process_payment() {
1697 1697
 		// basically confirm that the event hasn't sold out since they hit the page
1698
-		if ( ! $this->_last_second_ticket_verifications() ) {
1698
+		if ( ! $this->_last_second_ticket_verifications()) {
1699 1699
 			return false;
1700 1700
 		}
1701 1701
 		// ya gotta make a choice man
1702
-		if ( empty( $this->checkout->selected_method_of_payment ) ) {
1702
+		if (empty($this->checkout->selected_method_of_payment)) {
1703 1703
 			$this->checkout->json_response->set_plz_select_method_of_payment(
1704
-				__( 'Please select a method of payment before proceeding.', 'event_espresso' )
1704
+				__('Please select a method of payment before proceeding.', 'event_espresso')
1705 1705
 			);
1706 1706
 			return false;
1707 1707
 		}
1708 1708
 		// get EE_Payment_Method object
1709
-		if ( ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment() ) {
1709
+		if ( ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1710 1710
 			return false;
1711 1711
 		}
1712 1712
 		// setup billing form
1713
-		if ( $this->checkout->payment_method->is_on_site() ) {
1713
+		if ($this->checkout->payment_method->is_on_site()) {
1714 1714
 			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1715 1715
 				$this->checkout->payment_method
1716 1716
 			);
1717 1717
 			// bad billing form ?
1718
-			if ( ! $this->_billing_form_is_valid() ) {
1718
+			if ( ! $this->_billing_form_is_valid()) {
1719 1719
 				return false;
1720 1720
 			}
1721 1721
 		}
1722 1722
 		// ensure primary registrant has been fully processed
1723
-		if ( ! $this->_setup_primary_registrant_prior_to_payment() ) {
1723
+		if ( ! $this->_setup_primary_registrant_prior_to_payment()) {
1724 1724
 			return false;
1725 1725
 		}
1726 1726
 		// if session is close to expiring (under 10 minutes by default)
1727
-		if ( ( time() - EE_Registry::instance()->SSN->expiration() ) < EE_Registry::instance()->SSN->extension() ) {
1727
+		if ((time() - EE_Registry::instance()->SSN->expiration()) < EE_Registry::instance()->SSN->extension()) {
1728 1728
 			// add some time to session expiration so that payment can be completed
1729 1729
 			EE_Registry::instance()->SSN->extend_expiration();
1730 1730
 		}
@@ -1733,12 +1733,12 @@  discard block
 block discarded – undo
1733 1733
 		// in case a registrant leaves to an Off-Site Gateway and never returns, we want to approve any registrations for events with a default reg status of Approved
1734 1734
 		//$transaction_processor->toggle_registration_statuses_for_default_approved_events( $this->checkout->transaction, $this->checkout->reg_cache_where_params );
1735 1735
 		// attempt payment
1736
-		$payment = $this->_attempt_payment( $this->checkout->payment_method );
1736
+		$payment = $this->_attempt_payment($this->checkout->payment_method);
1737 1737
 		// process results
1738
-		$payment = $this->_validate_payment( $payment );
1739
-		$payment = $this->_post_payment_processing( $payment );
1738
+		$payment = $this->_validate_payment($payment);
1739
+		$payment = $this->_post_payment_processing($payment);
1740 1740
 		// verify payment
1741
-		if ( $payment instanceof EE_Payment ) {
1741
+		if ($payment instanceof EE_Payment) {
1742 1742
 			// store that for later
1743 1743
 			$this->checkout->payment = $payment;
1744 1744
 			// we can also consider the TXN to not have been failed, so temporarily upgrade it's status to abandoned
@@ -1752,7 +1752,7 @@  discard block
 block discarded – undo
1752 1752
 			} else {
1753 1753
 				return false;
1754 1754
 			}
1755
-		} else if ( $payment === true ) {
1755
+		} else if ($payment === true) {
1756 1756
 			// please note that offline payment methods will NOT make a payment,
1757 1757
 			// but instead just mark themselves as the PMD_ID on the transaction, and return true
1758 1758
 			$this->checkout->payment = $payment;
@@ -1772,22 +1772,22 @@  discard block
 block discarded – undo
1772 1772
 	 */
1773 1773
 	protected function _last_second_ticket_verifications() {
1774 1774
 		// don't bother re-validating if not a return visit
1775
-		if ( ! $this->checkout->revisit ) {
1775
+		if ( ! $this->checkout->revisit) {
1776 1776
 			return true;
1777 1777
 		}
1778 1778
 		$registrations = $this->checkout->transaction->registrations();
1779
-		if ( empty( $registrations ) ) {
1779
+		if (empty($registrations)) {
1780 1780
 			return false;
1781 1781
 		}
1782
-		foreach ( $registrations as $registration ) {
1783
-			if ( $registration instanceof EE_Registration ) {
1782
+		foreach ($registrations as $registration) {
1783
+			if ($registration instanceof EE_Registration) {
1784 1784
 				$event = $registration->event_obj();
1785
-				if ( $event instanceof EE_Event && $event->is_sold_out( true ) ) {
1785
+				if ($event instanceof EE_Event && $event->is_sold_out(true)) {
1786 1786
 					EE_Error::add_error(
1787 1787
 						apply_filters(
1788 1788
 							'FHEE__EE_SPCO_Reg_Step_Payment_Options___last_second_ticket_verifications__sold_out_events_msg',
1789 1789
 							sprintf(
1790
-								__( 'It appears that the %1$s event that you were about to make a payment for has sold out since you first registered and/or arrived at this page. Please refresh the page and try again. If you have already made a partial payment towards this event, please contact the event administrator for a refund.', 'event_espresso' ),
1790
+								__('It appears that the %1$s event that you were about to make a payment for has sold out since you first registered and/or arrived at this page. Please refresh the page and try again. If you have already made a partial payment towards this event, please contact the event administrator for a refund.', 'event_espresso'),
1791 1791
 								$event->name()
1792 1792
 							)
1793 1793
 						),
@@ -1817,7 +1817,7 @@  discard block
 block discarded – undo
1817 1817
 		);
1818 1818
 		$html = $payment_method_billing_info->get_html();
1819 1819
 		$html .= $this->checkout->redirect_form;
1820
-		EE_Registry::instance()->REQ->add_output( $html );
1820
+		EE_Registry::instance()->REQ->add_output($html);
1821 1821
 		return true;
1822 1822
 	}
1823 1823
 
@@ -1831,28 +1831,28 @@  discard block
 block discarded – undo
1831 1831
 	 * @throws \EE_Error
1832 1832
 	 */
1833 1833
 	private function _billing_form_is_valid() {
1834
-		if ( ! $this->checkout->payment_method->type_obj()->has_billing_form() ) {
1834
+		if ( ! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1835 1835
 			return true;
1836 1836
 		}
1837
-		if ( $this->checkout->billing_form instanceof EE_Billing_Info_Form ) {
1838
-			if ( $this->checkout->billing_form->was_submitted() ) {
1837
+		if ($this->checkout->billing_form instanceof EE_Billing_Info_Form) {
1838
+			if ($this->checkout->billing_form->was_submitted()) {
1839 1839
 				$this->checkout->billing_form->receive_form_submission();
1840
-				if ( $this->checkout->billing_form->is_valid() ) {
1840
+				if ($this->checkout->billing_form->is_valid()) {
1841 1841
 					return true;
1842 1842
 				}
1843 1843
 				$validation_errors = $this->checkout->billing_form->get_validation_errors_accumulated();
1844 1844
 				$error_strings = array();
1845
-				foreach ( $validation_errors as $validation_error ) {
1846
-					if ( $validation_error instanceof EE_Validation_Error ) {
1845
+				foreach ($validation_errors as $validation_error) {
1846
+					if ($validation_error instanceof EE_Validation_Error) {
1847 1847
 						$form_section = $validation_error->get_form_section();
1848
-						if ( $form_section instanceof EE_Form_Input_Base ) {
1848
+						if ($form_section instanceof EE_Form_Input_Base) {
1849 1849
 							$label = $form_section->html_label_text();
1850
-						} elseif ( $form_section instanceof EE_Form_Section_Base ) {
1850
+						} elseif ($form_section instanceof EE_Form_Section_Base) {
1851 1851
 							$label = $form_section->name();
1852 1852
 						} else {
1853
-							$label = __( 'Validation Error', 'event_espresso' );
1853
+							$label = __('Validation Error', 'event_espresso');
1854 1854
 						}
1855
-						$error_strings[] = sprintf( '%1$s: %2$s', $label, $validation_error->getMessage() );
1855
+						$error_strings[] = sprintf('%1$s: %2$s', $label, $validation_error->getMessage());
1856 1856
 					}
1857 1857
 				}
1858 1858
 				EE_Error::add_error(
@@ -1862,7 +1862,7 @@  discard block
 block discarded – undo
1862 1862
 							'event_espresso'
1863 1863
 						),
1864 1864
 						'<br/>',
1865
-						implode( '<br/>', $error_strings )
1865
+						implode('<br/>', $error_strings)
1866 1866
 					),
1867 1867
 					__FILE__,
1868 1868
 					__FUNCTION__,
@@ -1881,7 +1881,7 @@  discard block
 block discarded – undo
1881 1881
 			}
1882 1882
 		} else {
1883 1883
 			EE_Error::add_error(
1884
-				__( 'The submitted billing form is invalid possibly due to a technical reason.', 'event_espresso' ),
1884
+				__('The submitted billing form is invalid possibly due to a technical reason.', 'event_espresso'),
1885 1885
 				__FILE__,
1886 1886
 				__FUNCTION__,
1887 1887
 				__LINE__
@@ -1920,7 +1920,7 @@  discard block
 block discarded – undo
1920 1920
 		// save the TXN ( which clears cached copy of primary_registration)
1921 1921
 		$this->checkout->transaction->save();
1922 1922
 		// grab TXN ID and save it to the primary_registration
1923
-		$primary_registration->set_transaction_id( $this->checkout->transaction->ID() );
1923
+		$primary_registration->set_transaction_id($this->checkout->transaction->ID());
1924 1924
 		// save what we have so far
1925 1925
 		$primary_registration->save();
1926 1926
 		return true;
@@ -1938,7 +1938,7 @@  discard block
 block discarded – undo
1938 1938
 	private function _capture_primary_registration_data_from_billing_form() {
1939 1939
 		// convert billing form data into an attendee
1940 1940
 		$this->checkout->primary_attendee_obj = $this->checkout->billing_form->create_attendee_from_billing_form_data();
1941
-		if ( ! $this->checkout->primary_attendee_obj instanceof EE_Attendee ) {
1941
+		if ( ! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
1942 1942
 			EE_Error::add_error(
1943 1943
 				sprintf(
1944 1944
 					__(
@@ -1946,7 +1946,7 @@  discard block
 block discarded – undo
1946 1946
 						'event_espresso'
1947 1947
 					),
1948 1948
 					'<br/>',
1949
-					EE_Registry::instance()->CFG->organization->get_pretty( 'email' )
1949
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
1950 1950
 				),
1951 1951
 				__FILE__,
1952 1952
 				__FUNCTION__,
@@ -1955,7 +1955,7 @@  discard block
 block discarded – undo
1955 1955
 			return false;
1956 1956
 		}
1957 1957
 		$primary_registration = $this->checkout->transaction->primary_registration();
1958
-		if ( ! $primary_registration instanceof EE_Registration ) {
1958
+		if ( ! $primary_registration instanceof EE_Registration) {
1959 1959
 			EE_Error::add_error(
1960 1960
 				sprintf(
1961 1961
 					__(
@@ -1963,7 +1963,7 @@  discard block
 block discarded – undo
1963 1963
 						'event_espresso'
1964 1964
 					),
1965 1965
 					'<br/>',
1966
-					EE_Registry::instance()->CFG->organization->get_pretty( 'email' )
1966
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
1967 1967
 				),
1968 1968
 				__FILE__,
1969 1969
 				__FUNCTION__,
@@ -1971,7 +1971,7 @@  discard block
 block discarded – undo
1971 1971
 			);
1972 1972
 			return false;
1973 1973
 		}
1974
-		if ( ! $primary_registration->_add_relation_to( $this->checkout->primary_attendee_obj, 'Attendee' )
1974
+		if ( ! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
1975 1975
 		       instanceof
1976 1976
 		       EE_Attendee
1977 1977
 		) {
@@ -1982,7 +1982,7 @@  discard block
 block discarded – undo
1982 1982
 						'event_espresso'
1983 1983
 					),
1984 1984
 					'<br/>',
1985
-					EE_Registry::instance()->CFG->organization->get_pretty( 'email' )
1985
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
1986 1986
 				),
1987 1987
 				__FILE__,
1988 1988
 				__FUNCTION__,
@@ -1991,9 +1991,9 @@  discard block
 block discarded – undo
1991 1991
 			return false;
1992 1992
 		}
1993 1993
 		/** @type EE_Registration_Processor $registration_processor */
1994
-		$registration_processor = EE_Registry::instance()->load_class( 'Registration_Processor' );
1994
+		$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
1995 1995
 		// at this point, we should have enough details about the registrant to consider the registration NOT incomplete
1996
-		$registration_processor->toggle_incomplete_registration_status_to_default( $primary_registration );
1996
+		$registration_processor->toggle_incomplete_registration_status_to_default($primary_registration);
1997 1997
 		return true;
1998 1998
 	}
1999 1999
 
@@ -2008,22 +2008,22 @@  discard block
 block discarded – undo
2008 2008
 	 * @throws \EE_Error
2009 2009
 	 */
2010 2010
 	private function _get_payment_method_for_selected_method_of_payment() {
2011
-		if ( $this->checkout->selected_method_of_payment === 'events_sold_out' ) {
2011
+		if ($this->checkout->selected_method_of_payment === 'events_sold_out') {
2012 2012
 			$this->_redirect_because_event_sold_out();
2013 2013
 			return null;
2014 2014
 		}
2015 2015
 		// get EE_Payment_Method object
2016
-		if ( isset( $this->checkout->available_payment_methods[ $this->checkout->selected_method_of_payment ] ) ) {
2017
-			$payment_method = $this->checkout->available_payment_methods[ $this->checkout->selected_method_of_payment ];
2016
+		if (isset($this->checkout->available_payment_methods[$this->checkout->selected_method_of_payment])) {
2017
+			$payment_method = $this->checkout->available_payment_methods[$this->checkout->selected_method_of_payment];
2018 2018
 		} else {
2019 2019
 			// load EEM_Payment_Method
2020
-			EE_Registry::instance()->load_model( 'Payment_Method' );
2020
+			EE_Registry::instance()->load_model('Payment_Method');
2021 2021
 			/** @type EEM_Payment_Method $EEM_Payment_Method */
2022 2022
 			$EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
2023
-			$payment_method = $EEM_Payment_Method->get_one_by_slug( $this->checkout->selected_method_of_payment );
2023
+			$payment_method = $EEM_Payment_Method->get_one_by_slug($this->checkout->selected_method_of_payment);
2024 2024
 		}
2025 2025
 		// verify $payment_method
2026
-		if ( ! $payment_method instanceof EE_Payment_Method ) {
2026
+		if ( ! $payment_method instanceof EE_Payment_Method) {
2027 2027
 			// not a payment
2028 2028
 			EE_Error::add_error(
2029 2029
 				sprintf(
@@ -2032,7 +2032,7 @@  discard block
 block discarded – undo
2032 2032
 						'event_espresso'
2033 2033
 					),
2034 2034
 					'<br/>',
2035
-					EE_Registry::instance()->CFG->organization->get_pretty( 'email' )
2035
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2036 2036
 				),
2037 2037
 				__FILE__,
2038 2038
 				__FUNCTION__,
@@ -2041,7 +2041,7 @@  discard block
 block discarded – undo
2041 2041
 			return null;
2042 2042
 		}
2043 2043
 		// and verify it has a valid Payment_Method Type object
2044
-		if ( ! $payment_method->type_obj() instanceof EE_PMT_Base ) {
2044
+		if ( ! $payment_method->type_obj() instanceof EE_PMT_Base) {
2045 2045
 			// not a payment
2046 2046
 			EE_Error::add_error(
2047 2047
 				sprintf(
@@ -2050,7 +2050,7 @@  discard block
 block discarded – undo
2050 2050
 						'event_espresso'
2051 2051
 					),
2052 2052
 					'<br/>',
2053
-					EE_Registry::instance()->CFG->organization->get_pretty( 'email' )
2053
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2054 2054
 				),
2055 2055
 				__FILE__,
2056 2056
 				__FUNCTION__,
@@ -2071,29 +2071,29 @@  discard block
 block discarded – undo
2071 2071
 	 * @return    mixed    EE_Payment | boolean
2072 2072
 	 * @throws \EE_Error
2073 2073
 	 */
2074
-	private function _attempt_payment( EE_Payment_Method $payment_method ) {
2074
+	private function _attempt_payment(EE_Payment_Method $payment_method) {
2075 2075
 		$payment = null;
2076 2076
 		$this->checkout->transaction->save();
2077
-		$payment_processor = EE_Registry::instance()->load_core( 'Payment_Processor' );
2078
-		if ( ! $payment_processor instanceof EE_Payment_Processor ) {
2077
+		$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2078
+		if ( ! $payment_processor instanceof EE_Payment_Processor) {
2079 2079
 			return false;
2080 2080
 		}
2081 2081
 		try {
2082
-			$payment_processor->set_revisit( $this->checkout->revisit );
2082
+			$payment_processor->set_revisit($this->checkout->revisit);
2083 2083
 			// generate payment object
2084 2084
 			$payment = $payment_processor->process_payment(
2085 2085
 				$payment_method,
2086 2086
 				$this->checkout->transaction,
2087 2087
 				$this->checkout->amount_owing,
2088 2088
 				$this->checkout->billing_form,
2089
-				$this->_get_return_url( $payment_method ),
2089
+				$this->_get_return_url($payment_method),
2090 2090
 				'CART',
2091 2091
 				$this->checkout->admin_request,
2092 2092
 				true,
2093 2093
 				$this->reg_step_url()
2094 2094
 			);
2095
-		} catch ( Exception $e ) {
2096
-			$this->_handle_payment_processor_exception( $e );
2095
+		} catch (Exception $e) {
2096
+			$this->_handle_payment_processor_exception($e);
2097 2097
 		}
2098 2098
 		return $payment;
2099 2099
 	}
@@ -2108,7 +2108,7 @@  discard block
 block discarded – undo
2108 2108
 	 * @return void
2109 2109
 	 * @throws \EE_Error
2110 2110
 	 */
2111
-	protected function _handle_payment_processor_exception( Exception $e ) {
2111
+	protected function _handle_payment_processor_exception(Exception $e) {
2112 2112
 		EE_Error::add_error(
2113 2113
 			sprintf(
2114 2114
 				__(
@@ -2116,7 +2116,7 @@  discard block
 block discarded – undo
2116 2116
 					'event_espresso'
2117 2117
 				),
2118 2118
 				'<br/>',
2119
-				EE_Registry::instance()->CFG->organization->get_pretty( 'email' ),
2119
+				EE_Registry::instance()->CFG->organization->get_pretty('email'),
2120 2120
 				$e->getMessage(),
2121 2121
 				$e->getFile(),
2122 2122
 				$e->getLine()
@@ -2137,9 +2137,9 @@  discard block
 block discarded – undo
2137 2137
 	 * @return string
2138 2138
 	 * @throws \EE_Error
2139 2139
 	 */
2140
-	protected function _get_return_url( EE_Payment_Method $payment_method ) {
2140
+	protected function _get_return_url(EE_Payment_Method $payment_method) {
2141 2141
 		$return_url = '';
2142
-		switch ( $payment_method->type_obj()->payment_occurs() ) {
2142
+		switch ($payment_method->type_obj()->payment_occurs()) {
2143 2143
 			case EE_PMT_Base::offsite :
2144 2144
 				$return_url = add_query_arg(
2145 2145
 					array(
@@ -2168,12 +2168,12 @@  discard block
 block discarded – undo
2168 2168
 	 * @return EE_Payment | FALSE
2169 2169
 	 * @throws \EE_Error
2170 2170
 	 */
2171
-	private function _validate_payment( $payment = null ) {
2172
-		if ( $this->checkout->payment_method->is_off_line() ) {
2171
+	private function _validate_payment($payment = null) {
2172
+		if ($this->checkout->payment_method->is_off_line()) {
2173 2173
 			return true;
2174 2174
 		}
2175 2175
 		// verify payment object
2176
-		if ( ! $payment instanceof EE_Payment ) {
2176
+		if ( ! $payment instanceof EE_Payment) {
2177 2177
 			// not a payment
2178 2178
 			EE_Error::add_error(
2179 2179
 				sprintf(
@@ -2182,7 +2182,7 @@  discard block
 block discarded – undo
2182 2182
 						'event_espresso'
2183 2183
 					),
2184 2184
 					'<br/>',
2185
-					EE_Registry::instance()->CFG->organization->get_pretty( 'email' )
2185
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2186 2186
 				),
2187 2187
 				__FILE__,
2188 2188
 				__FUNCTION__,
@@ -2203,27 +2203,27 @@  discard block
 block discarded – undo
2203 2203
 	 * @return bool
2204 2204
 	 * @throws \EE_Error
2205 2205
 	 */
2206
-	private function _post_payment_processing( $payment = null ) {
2206
+	private function _post_payment_processing($payment = null) {
2207 2207
 		// Off-Line payment?
2208
-		if ( $payment === true ) {
2208
+		if ($payment === true) {
2209 2209
 			//$this->_setup_redirect_for_next_step();
2210 2210
 			return true;
2211 2211
 		// On-Site payment?
2212
-		} else if ( $this->checkout->payment_method->is_on_site() ) {
2213
-			if ( ! $this->_process_payment_status( $payment, EE_PMT_Base::onsite ) ) {
2212
+		} else if ($this->checkout->payment_method->is_on_site()) {
2213
+			if ( ! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2214 2214
 				//$this->_setup_redirect_for_next_step();
2215 2215
 				$this->checkout->continue_reg = false;
2216 2216
 			}
2217 2217
 		// Off-Site payment?
2218
-		} else if ( $this->checkout->payment_method->is_off_site() ) {
2218
+		} else if ($this->checkout->payment_method->is_off_site()) {
2219 2219
 			// if a payment object was made and it specifies a redirect url, then we'll setup that redirect info
2220
-			if ( $payment instanceof EE_Payment && $payment->redirect_url() ) {
2221
-				do_action( 'AHEE_log', __CLASS__, __FUNCTION__, $payment->redirect_url(), '$payment->redirect_url()' );
2220
+			if ($payment instanceof EE_Payment && $payment->redirect_url()) {
2221
+				do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->redirect_url(), '$payment->redirect_url()');
2222 2222
 				$this->checkout->redirect = true;
2223 2223
 				$this->checkout->redirect_form = $payment->redirect_form();
2224
-				$this->checkout->redirect_url = $this->reg_step_url( 'redirect_form' );
2224
+				$this->checkout->redirect_url = $this->reg_step_url('redirect_form');
2225 2225
 				// set JSON response
2226
-				$this->checkout->json_response->set_redirect_form( $this->checkout->redirect_form );
2226
+				$this->checkout->json_response->set_redirect_form($this->checkout->redirect_form);
2227 2227
 				// set cron job for finalizing the TXN
2228 2228
 				// in case the user does not return from the off-site gateway
2229 2229
 				EE_Cron_Tasks::schedule_finalize_abandoned_transactions_check(
@@ -2231,7 +2231,7 @@  discard block
 block discarded – undo
2231 2231
 					$this->checkout->transaction->ID()
2232 2232
 				);
2233 2233
 				// and lastly, let's bump the payment status to pending
2234
-				$payment->set_status( EEM_Payment::status_id_pending );
2234
+				$payment->set_status(EEM_Payment::status_id_pending);
2235 2235
 				$payment->save();
2236 2236
 			} else {
2237 2237
 				// not a payment
@@ -2243,7 +2243,7 @@  discard block
 block discarded – undo
2243 2243
 							'event_espresso'
2244 2244
 						),
2245 2245
 						'<br/>',
2246
-						EE_Registry::instance()->CFG->organization->get_pretty( 'email' )
2246
+						EE_Registry::instance()->CFG->organization->get_pretty('email')
2247 2247
 					),
2248 2248
 					__FILE__,
2249 2249
 					__FUNCTION__,
@@ -2281,21 +2281,21 @@  discard block
 block discarded – undo
2281 2281
 	 * @return bool
2282 2282
 	 * @throws \EE_Error
2283 2283
 	 */
2284
-	private function _process_payment_status( $payment, $payment_occurs = EE_PMT_Base::offline ) {
2284
+	private function _process_payment_status($payment, $payment_occurs = EE_PMT_Base::offline) {
2285 2285
 		// off-line payment? carry on
2286
-		if ( $payment_occurs === EE_PMT_Base::offline ) {
2286
+		if ($payment_occurs === EE_PMT_Base::offline) {
2287 2287
 			return true;
2288 2288
 		}
2289 2289
 		// verify payment validity
2290
-		if ( $payment instanceof EE_Payment ) {
2291
-			do_action( 'AHEE_log', __CLASS__, __FUNCTION__, $payment->status(), '$payment->status()' );
2290
+		if ($payment instanceof EE_Payment) {
2291
+			do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->status(), '$payment->status()');
2292 2292
 			$msg = $payment->gateway_response();
2293 2293
 			// check results
2294
-			switch ( $payment->status() ) {
2294
+			switch ($payment->status()) {
2295 2295
 				// good payment
2296 2296
 				case EEM_Payment::status_id_approved :
2297 2297
 					EE_Error::add_success(
2298
-						__( 'Your payment was processed successfully.', 'event_espresso' ),
2298
+						__('Your payment was processed successfully.', 'event_espresso'),
2299 2299
 						__FILE__,
2300 2300
 						__FUNCTION__,
2301 2301
 						__LINE__
@@ -2304,45 +2304,45 @@  discard block
 block discarded – undo
2304 2304
 					break;
2305 2305
 				// slow payment
2306 2306
 				case EEM_Payment::status_id_pending :
2307
-					if ( empty( $msg ) ) {
2307
+					if (empty($msg)) {
2308 2308
 						$msg = __(
2309 2309
 							'Your payment appears to have been processed successfully, but the Instant Payment Notification has not yet been received. It should arrive shortly.',
2310 2310
 							'event_espresso'
2311 2311
 						);
2312 2312
 					}
2313
-					EE_Error::add_success( $msg, __FILE__, __FUNCTION__, __LINE__ );
2313
+					EE_Error::add_success($msg, __FILE__, __FUNCTION__, __LINE__);
2314 2314
 					return true;
2315 2315
 					break;
2316 2316
 				// don't wanna payment
2317 2317
 				case EEM_Payment::status_id_cancelled :
2318
-					if ( empty( $msg ) ) {
2318
+					if (empty($msg)) {
2319 2319
 						$msg = _n(
2320 2320
 							'Payment cancelled. Please try again.',
2321 2321
 							'Payment cancelled. Please try again or select another method of payment.',
2322
-							count( $this->checkout->available_payment_methods ),
2322
+							count($this->checkout->available_payment_methods),
2323 2323
 							'event_espresso'
2324 2324
 						);
2325 2325
 					}
2326
-					EE_Error::add_attention( $msg, __FILE__, __FUNCTION__, __LINE__ );
2326
+					EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2327 2327
 					return false;
2328 2328
 					break;
2329 2329
 				// not enough payment
2330 2330
 				case EEM_Payment::status_id_declined :
2331
-					if ( empty( $msg ) ) {
2331
+					if (empty($msg)) {
2332 2332
 						$msg = _n(
2333 2333
 							'We\'re sorry but your payment was declined. Please try again.',
2334 2334
 							'We\'re sorry but your payment was declined. Please try again or select another method of payment.',
2335
-							count( $this->checkout->available_payment_methods ),
2335
+							count($this->checkout->available_payment_methods),
2336 2336
 							'event_espresso'
2337 2337
 						);
2338 2338
 					}
2339
-					EE_Error::add_attention( $msg, __FILE__, __FUNCTION__, __LINE__ );
2339
+					EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2340 2340
 					return false;
2341 2341
 					break;
2342 2342
 				// bad payment
2343 2343
 				case EEM_Payment::status_id_failed :
2344
-					if ( ! empty( $msg ) ) {
2345
-						EE_Error::add_error( $msg, __FILE__, __FUNCTION__, __LINE__ );
2344
+					if ( ! empty($msg)) {
2345
+						EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2346 2346
 						return false;
2347 2347
 					}
2348 2348
 					// default to error below
@@ -2351,7 +2351,7 @@  discard block
 block discarded – undo
2351 2351
 		}
2352 2352
 		// off-site payment gateway responses are too unreliable, so let's just assume that
2353 2353
 		// the payment processing is just running slower than the registrant's request
2354
-		if ( $payment_occurs === EE_PMT_Base::offsite ) {
2354
+		if ($payment_occurs === EE_PMT_Base::offsite) {
2355 2355
 			return true;
2356 2356
 		}
2357 2357
 		EE_Error::add_error(
@@ -2361,7 +2361,7 @@  discard block
 block discarded – undo
2361 2361
 					'event_espresso'
2362 2362
 				),
2363 2363
 				'<br/>',
2364
-				EE_Registry::instance()->CFG->organization->get_pretty( 'email' )
2364
+				EE_Registry::instance()->CFG->organization->get_pretty('email')
2365 2365
 			),
2366 2366
 			__FILE__,
2367 2367
 			__FUNCTION__,
@@ -2394,13 +2394,13 @@  discard block
 block discarded – undo
2394 2394
 	public function process_gateway_response() {
2395 2395
 		$payment = null;
2396 2396
 		// how have they chosen to pay?
2397
-		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment( true );
2397
+		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
2398 2398
 		// get EE_Payment_Method object
2399
-		if ( ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment() ) {
2399
+		if ( ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2400 2400
 			$this->checkout->continue_reg = false;
2401 2401
 			return false;
2402 2402
 		}
2403
-		if ( ! $this->checkout->payment_method->is_off_site() ) {
2403
+		if ( ! $this->checkout->payment_method->is_off_site()) {
2404 2404
 			return false;
2405 2405
 		}
2406 2406
 		$this->_validate_offsite_return();
@@ -2414,23 +2414,23 @@  discard block
 block discarded – undo
2414 2414
 		//	true
2415 2415
 		//);
2416 2416
 		// verify TXN
2417
-		if ( $this->checkout->transaction instanceof EE_Transaction ) {
2417
+		if ($this->checkout->transaction instanceof EE_Transaction) {
2418 2418
 			$gateway = $this->checkout->payment_method->type_obj()->get_gateway();
2419
-			if ( ! $gateway instanceof EE_Offsite_Gateway ) {
2419
+			if ( ! $gateway instanceof EE_Offsite_Gateway) {
2420 2420
 				$this->checkout->continue_reg = false;
2421 2421
 				return false;
2422 2422
 			}
2423
-			$payment = $this->_process_off_site_payment( $gateway );
2424
-			$payment = $this->_process_cancelled_payments( $payment );
2425
-			$payment = $this->_validate_payment( $payment );
2423
+			$payment = $this->_process_off_site_payment($gateway);
2424
+			$payment = $this->_process_cancelled_payments($payment);
2425
+			$payment = $this->_validate_payment($payment);
2426 2426
 			// if payment was not declined by the payment gateway or cancelled by the registrant
2427
-			if ( $this->_process_payment_status( $payment, EE_PMT_Base::offsite ) ) {
2427
+			if ($this->_process_payment_status($payment, EE_PMT_Base::offsite)) {
2428 2428
 				//$this->_setup_redirect_for_next_step();
2429 2429
 				// store that for later
2430 2430
 				$this->checkout->payment = $payment;
2431 2431
 				// mark this reg step as completed, as long as gateway doesn't use a separate IPN request,
2432 2432
 				// because we will complete this step during the IPN processing then
2433
-				if ( $gateway instanceof EE_Offsite_Gateway && ! $this->handle_IPN_in_this_request() ) {
2433
+				if ($gateway instanceof EE_Offsite_Gateway && ! $this->handle_IPN_in_this_request()) {
2434 2434
 					$this->set_completed();
2435 2435
 				}
2436 2436
 				return true;
@@ -2454,21 +2454,21 @@  discard block
 block discarded – undo
2454 2454
 	 * @throws \EE_Error
2455 2455
 	 */
2456 2456
 	private function _validate_offsite_return() {
2457
-		$TXN_ID = (int)EE_Registry::instance()->REQ->get( 'spco_txn', 0 );
2458
-		if ( $TXN_ID !== $this->checkout->transaction->ID() ) {
2457
+		$TXN_ID = (int) EE_Registry::instance()->REQ->get('spco_txn', 0);
2458
+		if ($TXN_ID !== $this->checkout->transaction->ID()) {
2459 2459
 			// Houston... we might have a problem
2460 2460
 			$invalid_TXN = false;
2461 2461
 			// first gather some info
2462
-			$valid_TXN = EEM_Transaction::instance()->get_one_by_ID( $TXN_ID );
2462
+			$valid_TXN = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2463 2463
 			$primary_registrant = $valid_TXN instanceof EE_Transaction
2464 2464
 				? $valid_TXN->primary_registration()
2465 2465
 				: null;
2466 2466
 			// let's start by retrieving the cart for this TXN
2467
-			$cart = $this->checkout->get_cart_for_transaction( $this->checkout->transaction );
2468
-			if ( $cart instanceof EE_Cart ) {
2467
+			$cart = $this->checkout->get_cart_for_transaction($this->checkout->transaction);
2468
+			if ($cart instanceof EE_Cart) {
2469 2469
 				// verify that the current cart has tickets
2470 2470
 				$tickets = $cart->get_tickets();
2471
-				if ( empty( $tickets ) ) {
2471
+				if (empty($tickets)) {
2472 2472
 					$invalid_TXN = true;
2473 2473
 				}
2474 2474
 			} else {
@@ -2478,35 +2478,35 @@  discard block
 block discarded – undo
2478 2478
 				? $primary_registrant->session_ID()
2479 2479
 				: null;
2480 2480
 			// validate current Session ID and compare against valid TXN session ID
2481
-			if ( EE_Session::instance()->id() === null ) {
2481
+			if (EE_Session::instance()->id() === null) {
2482 2482
 				$invalid_TXN = true;
2483
-			} else if ( EE_Session::instance()->id() === $valid_TXN_SID ) {
2483
+			} else if (EE_Session::instance()->id() === $valid_TXN_SID) {
2484 2484
 				// WARNING !!!
2485 2485
 				// this could be PayPal sending back duplicate requests (ya they do that)
2486 2486
 				// or it **could** mean someone is simply registering AGAIN after having just done so
2487 2487
 				// so now we need to determine if this current TXN looks valid or not
2488 2488
 				// has this step even been started ?
2489
-				if ( $this->checkout->transaction->reg_step_completed( $this->slug() === false )
2489
+				if ($this->checkout->transaction->reg_step_completed($this->slug() === false)
2490 2490
 				) {
2491 2491
 					// really? you're half way through this reg step, but you never started it ?
2492 2492
 					$invalid_TXN = true;
2493 2493
 				}
2494 2494
 			}
2495
-			if ( $invalid_TXN ) {
2495
+			if ($invalid_TXN) {
2496 2496
 				// is the valid TXN completed ?
2497
-				if ( $valid_TXN instanceof EE_Transaction ) {
2497
+				if ($valid_TXN instanceof EE_Transaction) {
2498 2498
 					// has this step even been started ?
2499
-					$reg_step_completed = $valid_TXN->reg_step_completed( $this->slug() );
2500
-					if ( $reg_step_completed !== false && $reg_step_completed !== true ) {
2499
+					$reg_step_completed = $valid_TXN->reg_step_completed($this->slug());
2500
+					if ($reg_step_completed !== false && $reg_step_completed !== true) {
2501 2501
 						// so it **looks** like this is a double request from PayPal
2502 2502
 						// so let's try to pick up where we left off
2503 2503
 						$this->checkout->transaction = $valid_TXN;
2504
-						$this->checkout->refresh_all_entities( true );
2504
+						$this->checkout->refresh_all_entities(true);
2505 2505
 						return;
2506 2506
 					}
2507 2507
 				}
2508 2508
 				// you appear to be lost?
2509
-				$this->_redirect_wayward_request( $primary_registrant );
2509
+				$this->_redirect_wayward_request($primary_registrant);
2510 2510
 			}
2511 2511
 		}
2512 2512
 	}
@@ -2521,14 +2521,14 @@  discard block
 block discarded – undo
2521 2521
 	 * @return bool
2522 2522
 	 * @throws \EE_Error
2523 2523
 	 */
2524
-	private function _redirect_wayward_request( EE_Registration $primary_registrant ) {
2525
-		if ( ! $primary_registrant instanceof EE_Registration ) {
2524
+	private function _redirect_wayward_request(EE_Registration $primary_registrant) {
2525
+		if ( ! $primary_registrant instanceof EE_Registration) {
2526 2526
 			// try redirecting based on the current TXN
2527 2527
 			$primary_registrant = $this->checkout->transaction instanceof EE_Transaction
2528 2528
 				? $this->checkout->transaction->primary_registration()
2529 2529
 				: null;
2530 2530
 		}
2531
-		if ( ! $primary_registrant instanceof EE_Registration ) {
2531
+		if ( ! $primary_registrant instanceof EE_Registration) {
2532 2532
 			EE_Error::add_error(
2533 2533
 				sprintf(
2534 2534
 					__(
@@ -2536,7 +2536,7 @@  discard block
 block discarded – undo
2536 2536
 						'event_espresso'
2537 2537
 					),
2538 2538
 					'<br/>',
2539
-					EE_Registry::instance()->CFG->organization->get_pretty( 'email' )
2539
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2540 2540
 				),
2541 2541
 				__FILE__,
2542 2542
 				__FUNCTION__,
@@ -2567,17 +2567,17 @@  discard block
 block discarded – undo
2567 2567
 	 * @return \EE_Payment
2568 2568
 	 * @throws \EE_Error
2569 2569
 	 */
2570
-	private function _process_off_site_payment( EE_Offsite_Gateway $gateway ) {
2570
+	private function _process_off_site_payment(EE_Offsite_Gateway $gateway) {
2571 2571
 		try {
2572 2572
 			$request_data = \EE_Registry::instance()->REQ->params();
2573 2573
 			// if gateway uses_separate_IPN_request, then we don't have to process the IPN manually
2574 2574
 			$this->set_handle_IPN_in_this_request(
2575
-				$gateway->handle_IPN_in_this_request( $request_data, false )
2575
+				$gateway->handle_IPN_in_this_request($request_data, false)
2576 2576
 			);
2577
-			if ( $this->handle_IPN_in_this_request() ) {
2577
+			if ($this->handle_IPN_in_this_request()) {
2578 2578
 				// get payment details and process results
2579 2579
 				/** @type EE_Payment_Processor $payment_processor */
2580
-				$payment_processor = EE_Registry::instance()->load_core( 'Payment_Processor' );
2580
+				$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2581 2581
 				$payment = $payment_processor->process_ipn(
2582 2582
 					$request_data,
2583 2583
 					$this->checkout->transaction,
@@ -2590,14 +2590,14 @@  discard block
 block discarded – undo
2590 2590
 				$payment = $this->checkout->transaction->last_payment();
2591 2591
 				//$payment_source = 'last_payment';
2592 2592
 			}
2593
-		} catch ( Exception $e ) {
2593
+		} catch (Exception $e) {
2594 2594
 			// let's just eat the exception and try to move on using any previously set payment info
2595 2595
 			$payment = $this->checkout->transaction->last_payment();
2596 2596
 			//$payment_source = 'last_payment after Exception';
2597 2597
 			// but if we STILL don't have a payment object
2598
-			if ( ! $payment instanceof EE_Payment ) {
2598
+			if ( ! $payment instanceof EE_Payment) {
2599 2599
 				// then we'll object ! ( not object like a thing... but object like what a lawyer says ! )
2600
-				$this->_handle_payment_processor_exception( $e );
2600
+				$this->_handle_payment_processor_exception($e);
2601 2601
 			}
2602 2602
 		}
2603 2603
 		// DEBUG LOG
@@ -2622,13 +2622,13 @@  discard block
 block discarded – undo
2622 2622
 	 * @return EE_Payment | FALSE
2623 2623
 	 * @throws \EE_Error
2624 2624
 	 */
2625
-	private function _process_cancelled_payments( $payment = null ) {
2625
+	private function _process_cancelled_payments($payment = null) {
2626 2626
 		if (
2627 2627
 			$payment instanceof EE_Payment
2628
-			&& isset( $_REQUEST['ee_cancel_payment'] )
2628
+			&& isset($_REQUEST['ee_cancel_payment'])
2629 2629
 			&& $payment->status() === EEM_Payment::status_id_failed
2630 2630
 		) {
2631
-			$payment->set_status( EEM_Payment::status_id_cancelled );
2631
+			$payment->set_status(EEM_Payment::status_id_cancelled);
2632 2632
 		}
2633 2633
 		return $payment;
2634 2634
 	}
@@ -2645,14 +2645,14 @@  discard block
 block discarded – undo
2645 2645
 	public function get_transaction_details_for_gateways() {
2646 2646
 		$txn_details = array();
2647 2647
 		// ya gotta make a choice man
2648
-		if ( empty( $this->checkout->selected_method_of_payment ) ) {
2648
+		if (empty($this->checkout->selected_method_of_payment)) {
2649 2649
 			$txn_details = array(
2650
-				'error' => __( 'Please select a method of payment before proceeding.', 'event_espresso' )
2650
+				'error' => __('Please select a method of payment before proceeding.', 'event_espresso')
2651 2651
 			);
2652 2652
 		}
2653 2653
 		// get EE_Payment_Method object
2654 2654
 		if (
2655
-			empty( $txn_details )
2655
+			empty($txn_details)
2656 2656
 			&&
2657 2657
 			! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()
2658 2658
 		) {
@@ -2664,8 +2664,8 @@  discard block
 block discarded – undo
2664 2664
 				)
2665 2665
 			);
2666 2666
 		}
2667
-		if ( empty( $txn_details ) && $this->checkout->transaction instanceof EE_Transaction ) {
2668
-			$return_url = $this->_get_return_url( $this->checkout->payment_method );
2667
+		if (empty($txn_details) && $this->checkout->transaction instanceof EE_Transaction) {
2668
+			$return_url = $this->_get_return_url($this->checkout->payment_method);
2669 2669
 			$txn_details = array(
2670 2670
 				'TXN_ID'         => $this->checkout->transaction->ID(),
2671 2671
 				'TXN_timestamp'  => $this->checkout->transaction->datetime(),
@@ -2676,7 +2676,7 @@  discard block
 block discarded – undo
2676 2676
 				'PMD_ID'         => $this->checkout->transaction->payment_method_ID(),
2677 2677
 				'payment_amount' => $this->checkout->amount_owing,
2678 2678
 				'return_url'     => $return_url,
2679
-				'cancel_url'     => add_query_arg( array( 'ee_cancel_payment' => true ), $return_url ),
2679
+				'cancel_url'     => add_query_arg(array('ee_cancel_payment' => true), $return_url),
2680 2680
 				'notify_url'     => EE_Config::instance()->core->txn_page_url(
2681 2681
 					array(
2682 2682
 						'e_reg_url_link'    => $this->checkout->transaction->primary_registration()->reg_url_link(),
@@ -2685,7 +2685,7 @@  discard block
 block discarded – undo
2685 2685
 				)
2686 2686
 			);
2687 2687
 		}
2688
-		echo wp_json_encode( $txn_details );
2688
+		echo wp_json_encode($txn_details);
2689 2689
 		exit();
2690 2690
 	}
2691 2691
 
@@ -2702,7 +2702,7 @@  discard block
 block discarded – undo
2702 2702
     public function __sleep()
2703 2703
     {
2704 2704
         // remove the reg form and the checkout
2705
-        return array_diff( array_keys( get_object_vars( $this ) ), array( 'reg_form', 'checkout', 'line_item_display' ) );
2705
+        return array_diff(array_keys(get_object_vars($this)), array('reg_form', 'checkout', 'line_item_display'));
2706 2706
     }
2707 2707
 
2708 2708
 
Please login to merge, or discard this patch.
core/EE_Cart.core.php 2 patches
Indentation   +413 added lines, -413 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 do_action('AHEE_log', __FILE__, __FUNCTION__, '');
5 5
 
@@ -20,418 +20,418 @@  discard block
 block discarded – undo
20 20
 class EE_Cart
21 21
 {
22 22
 
23
-    /**
24
-     * instance of the EE_Cart object
25
-     *
26
-     * @access    private
27
-     * @var EE_Cart $_instance
28
-     */
29
-    private static $_instance;
30
-
31
-    /**
32
-     * instance of the EE_Session object
33
-     *
34
-     * @access    protected
35
-     * @var EE_Session $_session
36
-     */
37
-    protected $_session;
38
-
39
-    /**
40
-     * The total Line item which comprises all the children line-item subtotals,
41
-     * which in turn each have their line items.
42
-     * Typically, the line item structure will look like:
43
-     * grand total
44
-     * -tickets-sub-total
45
-     * --ticket1
46
-     * --ticket2
47
-     * --...
48
-     * -taxes-sub-total
49
-     * --tax1
50
-     * --tax2
51
-     *
52
-     * @var EE_Line_Item
53
-     */
54
-    private $_grand_total;
55
-
56
-
57
-
58
-    /**
59
-     * @singleton method used to instantiate class object
60
-     * @access    public
61
-     * @param EE_Line_Item $grand_total
62
-     * @param EE_Session   $session
63
-     * @return \EE_Cart
64
-     * @throws \EE_Error
65
-     */
66
-    public static function instance(EE_Line_Item $grand_total = null, EE_Session $session = null)
67
-    {
68
-        if ( ! empty($grand_total)) {
69
-            self::$_instance = new self($grand_total, $session);
70
-        }
71
-        // or maybe retrieve an existing one ?
72
-        if ( ! self::$_instance instanceof EE_Cart) {
73
-            // try getting the cart out of the session
74
-            $saved_cart = $session instanceof EE_Session ? $session->cart() : null;
75
-            self::$_instance = $saved_cart instanceof EE_Cart ? $saved_cart : new self($grand_total, $session);
76
-            unset($saved_cart);
77
-        }
78
-        // verify that cart is ok and grand total line item exists
79
-        if ( ! self::$_instance instanceof EE_Cart || ! self::$_instance->_grand_total instanceof EE_Line_Item) {
80
-            self::$_instance = new self($grand_total, $session);
81
-        }
82
-        self::$_instance->get_grand_total();
83
-        // once everything is all said and done, save the cart to the EE_Session
84
-        add_action('shutdown', array(self::$_instance, 'save_cart'), 90);
85
-        return self::$_instance;
86
-    }
87
-
88
-
89
-
90
-    /**
91
-     * private constructor to prevent direct creation
92
-     *
93
-     * @Constructor
94
-     * @access private
95
-     * @param EE_Line_Item $grand_total
96
-     * @param EE_Session   $session
97
-     */
98
-    private function __construct(EE_Line_Item $grand_total = null, EE_Session $session = null)
99
-    {
100
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
101
-        $this->set_session($session);
102
-        if ($grand_total instanceof EE_Line_Item) {
103
-            $this->set_grand_total_line_item($grand_total);
104
-        }
105
-    }
106
-
107
-
108
-
109
-    /**
110
-     * Resets the cart completely (whereas empty_cart
111
-     *
112
-     * @param EE_Line_Item $grand_total
113
-     * @param EE_Session   $session
114
-     * @return EE_Cart
115
-     * @throws \EE_Error
116
-     */
117
-    public static function reset(EE_Line_Item $grand_total = null, EE_Session $session = null)
118
-    {
119
-        remove_action('shutdown', array(self::$_instance, 'save_cart'), 90);
120
-        if ($session instanceof EE_Session) {
121
-            $session->reset_cart();
122
-        }
123
-        self::$_instance = null;
124
-        return self::instance($grand_total, $session);
125
-    }
126
-
127
-
128
-
129
-    /**
130
-     * @return \EE_Session
131
-     */
132
-    public function session()
133
-    {
134
-        if ( ! $this->_session instanceof EE_Session) {
135
-            $this->set_session();
136
-        }
137
-        return $this->_session;
138
-    }
139
-
140
-
141
-
142
-    /**
143
-     * @param EE_Session $session
144
-     */
145
-    public function set_session(EE_Session $session = null)
146
-    {
147
-        $this->_session = $session instanceof EE_Session ? $session : EE_Registry::instance()->load_core('Session');
148
-    }
149
-
150
-
151
-
152
-    /**
153
-     * Sets the cart to match the line item. Especially handy for loading an old cart where you
154
-     *  know the grand total line item on it
155
-     *
156
-     * @param EE_Line_Item $line_item
157
-     */
158
-    public function set_grand_total_line_item(EE_Line_Item $line_item)
159
-    {
160
-        $this->_grand_total = $line_item;
161
-    }
162
-
163
-
164
-
165
-    /**
166
-     * get_cart_from_reg_url_link
167
-     *
168
-     * @access public
169
-     * @param EE_Transaction $transaction
170
-     * @param EE_Session     $session
171
-     * @return \EE_Cart
172
-     * @throws \EE_Error
173
-     */
174
-    public static function get_cart_from_txn(EE_Transaction $transaction, EE_Session $session = null)
175
-    {
176
-        $grand_total = $transaction->total_line_item();
177
-        $grand_total->get_items();
178
-        $grand_total->tax_descendants();
179
-        return EE_Cart::instance($grand_total, $session);
180
-    }
181
-
182
-
183
-
184
-    /**
185
-     * Creates the total line item, and ensures it has its 'tickets' and 'taxes' sub-items
186
-     *
187
-     * @return EE_Line_Item
188
-     * @throws \EE_Error
189
-     */
190
-    private function _create_grand_total()
191
-    {
192
-        $this->_grand_total = EEH_Line_Item::create_total_line_item();
193
-        return $this->_grand_total;
194
-    }
195
-
196
-
197
-
198
-    /**
199
-     * Gets all the line items of object type Ticket
200
-     *
201
-     * @access public
202
-     * @return \EE_Line_Item[]
203
-     */
204
-    public function get_tickets()
205
-    {
206
-        if ($this->_grand_total === null ) {
207
-            return array();
208
-        }
209
-        return EEH_Line_Item::get_ticket_line_items($this->_grand_total);
210
-    }
211
-
212
-
213
-
214
-    /**
215
-     * returns the total quantity of tickets in the cart
216
-     *
217
-     * @access public
218
-     * @return int
219
-     * @throws \EE_Error
220
-     */
221
-    public function all_ticket_quantity_count()
222
-    {
223
-        $tickets = $this->get_tickets();
224
-        if (empty($tickets)) {
225
-            return 0;
226
-        }
227
-        $count = 0;
228
-        foreach ($tickets as $ticket) {
229
-            $count += $ticket->get('LIN_quantity');
230
-        }
231
-        return $count;
232
-    }
233
-
234
-
235
-
236
-    /**
237
-     * Gets all the tax line items
238
-     *
239
-     * @return \EE_Line_Item[]
240
-     * @throws \EE_Error
241
-     */
242
-    public function get_taxes()
243
-    {
244
-        return EEH_Line_Item::get_taxes_subtotal($this->_grand_total)->children();
245
-    }
246
-
247
-
248
-
249
-    /**
250
-     * Gets the total line item (which is a parent of all other line items) on this cart
251
-     *
252
-     * @return EE_Line_Item
253
-     * @throws \EE_Error
254
-     */
255
-    public function get_grand_total()
256
-    {
257
-        return $this->_grand_total instanceof EE_Line_Item ? $this->_grand_total : $this->_create_grand_total();
258
-    }
259
-
260
-
261
-
262
-    /**
263
-     * @process items for adding to cart
264
-     * @access  public
265
-     * @param EE_Ticket $ticket
266
-     * @param int       $qty
267
-     * @return TRUE on success, FALSE on fail
268
-     * @throws \EE_Error
269
-     */
270
-    public function add_ticket_to_cart(EE_Ticket $ticket, $qty = 1)
271
-    {
272
-        EEH_Line_Item::add_ticket_purchase($this->get_grand_total(), $ticket, $qty);
273
-        return $this->save_cart() ? true : false;
274
-    }
275
-
276
-
277
-
278
-    /**
279
-     * get_cart_total_before_tax
280
-     *
281
-     * @access public
282
-     * @return float
283
-     * @throws \EE_Error
284
-     */
285
-    public function get_cart_total_before_tax()
286
-    {
287
-        return $this->get_grand_total()->recalculate_pre_tax_total();
288
-    }
289
-
290
-
291
-
292
-    /**
293
-     * gets the total amount of tax paid for items in this cart
294
-     *
295
-     * @access public
296
-     * @return float
297
-     * @throws \EE_Error
298
-     */
299
-    public function get_applied_taxes()
300
-    {
301
-        return EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
302
-    }
303
-
304
-
305
-
306
-    /**
307
-     * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
308
-     *
309
-     * @access public
310
-     * @return float
311
-     * @throws \EE_Error
312
-     */
313
-    public function get_cart_grand_total()
314
-    {
315
-        EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
316
-        return $this->get_grand_total()->total();
317
-    }
318
-
319
-
320
-
321
-    /**
322
-     * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
323
-     *
324
-     * @access public
325
-     * @return float
326
-     * @throws \EE_Error
327
-     */
328
-    public function recalculate_all_cart_totals()
329
-    {
330
-        $pre_tax_total = $this->get_cart_total_before_tax();
331
-        $taxes_total = EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
332
-        $this->_grand_total->set_total($pre_tax_total + $taxes_total);
333
-        $this->_grand_total->save_this_and_descendants_to_txn();
334
-        return $this->get_grand_total()->total();
335
-    }
336
-
337
-
338
-
339
-    /**
340
-     * deletes an item from the cart
341
-     *
342
-     * @access public
343
-     * @param array|bool|string $line_item_codes
344
-     * @return int on success, FALSE on fail
345
-     * @throws \EE_Error
346
-     */
347
-    public function delete_items($line_item_codes = false)
348
-    {
349
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
350
-        return EEH_Line_Item::delete_items($this->get_grand_total(), $line_item_codes);
351
-    }
352
-
353
-
354
-
355
-    /**
356
-     * @remove ALL items from cart and zero ALL totals
357
-     * @access public
358
-     * @return bool
359
-     * @throws \EE_Error
360
-     */
361
-    public function empty_cart()
362
-    {
363
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
364
-        $this->_grand_total = $this->_create_grand_total();
365
-        return $this->save_cart(true);
366
-    }
367
-
368
-
369
-
370
-    /**
371
-     * @remove ALL items from cart and delete total as well
372
-     * @access public
373
-     * @return bool
374
-     * @throws \EE_Error
375
-     */
376
-    public function delete_cart()
377
-    {
378
-        $deleted = EEH_Line_Item::delete_all_child_items($this->_grand_total);
379
-        if ($deleted) {
380
-            $deleted += $this->_grand_total->delete();
381
-            $this->_grand_total = null;
382
-        }
383
-        return $deleted;
384
-    }
385
-
386
-
387
-
388
-    /**
389
-     * @save   cart to session
390
-     * @access public
391
-     * @param bool $apply_taxes
392
-     * @return TRUE on success, FALSE on fail
393
-     * @throws \EE_Error
394
-     */
395
-    public function save_cart($apply_taxes = true)
396
-    {
397
-        if ($apply_taxes && $this->_grand_total instanceof EE_Line_Item) {
398
-            EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
399
-            //make sure we don't cache the transaction because it can get stale
400
-            if ($this->_grand_total->get_one_from_cache('Transaction') instanceof EE_Transaction
401
-                && $this->_grand_total->get_one_from_cache('Transaction')->ID()
402
-            ) {
403
-                $this->_grand_total->clear_cache('Transaction', null, true);
404
-            }
405
-        }
406
-        if ($this->session() instanceof EE_Session) {
407
-            return $this->session()->set_cart($this);
408
-        } else {
409
-            return false;
410
-        }
411
-    }
412
-
413
-
414
-
415
-    public function __wakeup()
416
-    {
417
-        if ( ! $this->_grand_total instanceof EE_Line_Item && absint($this->_grand_total) !== 0) {
418
-            // $this->_grand_total is actually just an ID, so use it to get the object from the db
419
-            $this->_grand_total = EEM_Line_Item::instance()->get_one_by_ID($this->_grand_total);
420
-        }
421
-    }
422
-
423
-
424
-
425
-    /**
426
-     * @return array
427
-     */
428
-    public function __sleep()
429
-    {
430
-        if ($this->_grand_total instanceof EE_Line_Item && $this->_grand_total->ID()) {
431
-            $this->_grand_total = $this->_grand_total->ID();
432
-        }
433
-        return array('_grand_total');
434
-    }
23
+	/**
24
+	 * instance of the EE_Cart object
25
+	 *
26
+	 * @access    private
27
+	 * @var EE_Cart $_instance
28
+	 */
29
+	private static $_instance;
30
+
31
+	/**
32
+	 * instance of the EE_Session object
33
+	 *
34
+	 * @access    protected
35
+	 * @var EE_Session $_session
36
+	 */
37
+	protected $_session;
38
+
39
+	/**
40
+	 * The total Line item which comprises all the children line-item subtotals,
41
+	 * which in turn each have their line items.
42
+	 * Typically, the line item structure will look like:
43
+	 * grand total
44
+	 * -tickets-sub-total
45
+	 * --ticket1
46
+	 * --ticket2
47
+	 * --...
48
+	 * -taxes-sub-total
49
+	 * --tax1
50
+	 * --tax2
51
+	 *
52
+	 * @var EE_Line_Item
53
+	 */
54
+	private $_grand_total;
55
+
56
+
57
+
58
+	/**
59
+	 * @singleton method used to instantiate class object
60
+	 * @access    public
61
+	 * @param EE_Line_Item $grand_total
62
+	 * @param EE_Session   $session
63
+	 * @return \EE_Cart
64
+	 * @throws \EE_Error
65
+	 */
66
+	public static function instance(EE_Line_Item $grand_total = null, EE_Session $session = null)
67
+	{
68
+		if ( ! empty($grand_total)) {
69
+			self::$_instance = new self($grand_total, $session);
70
+		}
71
+		// or maybe retrieve an existing one ?
72
+		if ( ! self::$_instance instanceof EE_Cart) {
73
+			// try getting the cart out of the session
74
+			$saved_cart = $session instanceof EE_Session ? $session->cart() : null;
75
+			self::$_instance = $saved_cart instanceof EE_Cart ? $saved_cart : new self($grand_total, $session);
76
+			unset($saved_cart);
77
+		}
78
+		// verify that cart is ok and grand total line item exists
79
+		if ( ! self::$_instance instanceof EE_Cart || ! self::$_instance->_grand_total instanceof EE_Line_Item) {
80
+			self::$_instance = new self($grand_total, $session);
81
+		}
82
+		self::$_instance->get_grand_total();
83
+		// once everything is all said and done, save the cart to the EE_Session
84
+		add_action('shutdown', array(self::$_instance, 'save_cart'), 90);
85
+		return self::$_instance;
86
+	}
87
+
88
+
89
+
90
+	/**
91
+	 * private constructor to prevent direct creation
92
+	 *
93
+	 * @Constructor
94
+	 * @access private
95
+	 * @param EE_Line_Item $grand_total
96
+	 * @param EE_Session   $session
97
+	 */
98
+	private function __construct(EE_Line_Item $grand_total = null, EE_Session $session = null)
99
+	{
100
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
101
+		$this->set_session($session);
102
+		if ($grand_total instanceof EE_Line_Item) {
103
+			$this->set_grand_total_line_item($grand_total);
104
+		}
105
+	}
106
+
107
+
108
+
109
+	/**
110
+	 * Resets the cart completely (whereas empty_cart
111
+	 *
112
+	 * @param EE_Line_Item $grand_total
113
+	 * @param EE_Session   $session
114
+	 * @return EE_Cart
115
+	 * @throws \EE_Error
116
+	 */
117
+	public static function reset(EE_Line_Item $grand_total = null, EE_Session $session = null)
118
+	{
119
+		remove_action('shutdown', array(self::$_instance, 'save_cart'), 90);
120
+		if ($session instanceof EE_Session) {
121
+			$session->reset_cart();
122
+		}
123
+		self::$_instance = null;
124
+		return self::instance($grand_total, $session);
125
+	}
126
+
127
+
128
+
129
+	/**
130
+	 * @return \EE_Session
131
+	 */
132
+	public function session()
133
+	{
134
+		if ( ! $this->_session instanceof EE_Session) {
135
+			$this->set_session();
136
+		}
137
+		return $this->_session;
138
+	}
139
+
140
+
141
+
142
+	/**
143
+	 * @param EE_Session $session
144
+	 */
145
+	public function set_session(EE_Session $session = null)
146
+	{
147
+		$this->_session = $session instanceof EE_Session ? $session : EE_Registry::instance()->load_core('Session');
148
+	}
149
+
150
+
151
+
152
+	/**
153
+	 * Sets the cart to match the line item. Especially handy for loading an old cart where you
154
+	 *  know the grand total line item on it
155
+	 *
156
+	 * @param EE_Line_Item $line_item
157
+	 */
158
+	public function set_grand_total_line_item(EE_Line_Item $line_item)
159
+	{
160
+		$this->_grand_total = $line_item;
161
+	}
162
+
163
+
164
+
165
+	/**
166
+	 * get_cart_from_reg_url_link
167
+	 *
168
+	 * @access public
169
+	 * @param EE_Transaction $transaction
170
+	 * @param EE_Session     $session
171
+	 * @return \EE_Cart
172
+	 * @throws \EE_Error
173
+	 */
174
+	public static function get_cart_from_txn(EE_Transaction $transaction, EE_Session $session = null)
175
+	{
176
+		$grand_total = $transaction->total_line_item();
177
+		$grand_total->get_items();
178
+		$grand_total->tax_descendants();
179
+		return EE_Cart::instance($grand_total, $session);
180
+	}
181
+
182
+
183
+
184
+	/**
185
+	 * Creates the total line item, and ensures it has its 'tickets' and 'taxes' sub-items
186
+	 *
187
+	 * @return EE_Line_Item
188
+	 * @throws \EE_Error
189
+	 */
190
+	private function _create_grand_total()
191
+	{
192
+		$this->_grand_total = EEH_Line_Item::create_total_line_item();
193
+		return $this->_grand_total;
194
+	}
195
+
196
+
197
+
198
+	/**
199
+	 * Gets all the line items of object type Ticket
200
+	 *
201
+	 * @access public
202
+	 * @return \EE_Line_Item[]
203
+	 */
204
+	public function get_tickets()
205
+	{
206
+		if ($this->_grand_total === null ) {
207
+			return array();
208
+		}
209
+		return EEH_Line_Item::get_ticket_line_items($this->_grand_total);
210
+	}
211
+
212
+
213
+
214
+	/**
215
+	 * returns the total quantity of tickets in the cart
216
+	 *
217
+	 * @access public
218
+	 * @return int
219
+	 * @throws \EE_Error
220
+	 */
221
+	public function all_ticket_quantity_count()
222
+	{
223
+		$tickets = $this->get_tickets();
224
+		if (empty($tickets)) {
225
+			return 0;
226
+		}
227
+		$count = 0;
228
+		foreach ($tickets as $ticket) {
229
+			$count += $ticket->get('LIN_quantity');
230
+		}
231
+		return $count;
232
+	}
233
+
234
+
235
+
236
+	/**
237
+	 * Gets all the tax line items
238
+	 *
239
+	 * @return \EE_Line_Item[]
240
+	 * @throws \EE_Error
241
+	 */
242
+	public function get_taxes()
243
+	{
244
+		return EEH_Line_Item::get_taxes_subtotal($this->_grand_total)->children();
245
+	}
246
+
247
+
248
+
249
+	/**
250
+	 * Gets the total line item (which is a parent of all other line items) on this cart
251
+	 *
252
+	 * @return EE_Line_Item
253
+	 * @throws \EE_Error
254
+	 */
255
+	public function get_grand_total()
256
+	{
257
+		return $this->_grand_total instanceof EE_Line_Item ? $this->_grand_total : $this->_create_grand_total();
258
+	}
259
+
260
+
261
+
262
+	/**
263
+	 * @process items for adding to cart
264
+	 * @access  public
265
+	 * @param EE_Ticket $ticket
266
+	 * @param int       $qty
267
+	 * @return TRUE on success, FALSE on fail
268
+	 * @throws \EE_Error
269
+	 */
270
+	public function add_ticket_to_cart(EE_Ticket $ticket, $qty = 1)
271
+	{
272
+		EEH_Line_Item::add_ticket_purchase($this->get_grand_total(), $ticket, $qty);
273
+		return $this->save_cart() ? true : false;
274
+	}
275
+
276
+
277
+
278
+	/**
279
+	 * get_cart_total_before_tax
280
+	 *
281
+	 * @access public
282
+	 * @return float
283
+	 * @throws \EE_Error
284
+	 */
285
+	public function get_cart_total_before_tax()
286
+	{
287
+		return $this->get_grand_total()->recalculate_pre_tax_total();
288
+	}
289
+
290
+
291
+
292
+	/**
293
+	 * gets the total amount of tax paid for items in this cart
294
+	 *
295
+	 * @access public
296
+	 * @return float
297
+	 * @throws \EE_Error
298
+	 */
299
+	public function get_applied_taxes()
300
+	{
301
+		return EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
302
+	}
303
+
304
+
305
+
306
+	/**
307
+	 * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
308
+	 *
309
+	 * @access public
310
+	 * @return float
311
+	 * @throws \EE_Error
312
+	 */
313
+	public function get_cart_grand_total()
314
+	{
315
+		EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
316
+		return $this->get_grand_total()->total();
317
+	}
318
+
319
+
320
+
321
+	/**
322
+	 * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
323
+	 *
324
+	 * @access public
325
+	 * @return float
326
+	 * @throws \EE_Error
327
+	 */
328
+	public function recalculate_all_cart_totals()
329
+	{
330
+		$pre_tax_total = $this->get_cart_total_before_tax();
331
+		$taxes_total = EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
332
+		$this->_grand_total->set_total($pre_tax_total + $taxes_total);
333
+		$this->_grand_total->save_this_and_descendants_to_txn();
334
+		return $this->get_grand_total()->total();
335
+	}
336
+
337
+
338
+
339
+	/**
340
+	 * deletes an item from the cart
341
+	 *
342
+	 * @access public
343
+	 * @param array|bool|string $line_item_codes
344
+	 * @return int on success, FALSE on fail
345
+	 * @throws \EE_Error
346
+	 */
347
+	public function delete_items($line_item_codes = false)
348
+	{
349
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
350
+		return EEH_Line_Item::delete_items($this->get_grand_total(), $line_item_codes);
351
+	}
352
+
353
+
354
+
355
+	/**
356
+	 * @remove ALL items from cart and zero ALL totals
357
+	 * @access public
358
+	 * @return bool
359
+	 * @throws \EE_Error
360
+	 */
361
+	public function empty_cart()
362
+	{
363
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
364
+		$this->_grand_total = $this->_create_grand_total();
365
+		return $this->save_cart(true);
366
+	}
367
+
368
+
369
+
370
+	/**
371
+	 * @remove ALL items from cart and delete total as well
372
+	 * @access public
373
+	 * @return bool
374
+	 * @throws \EE_Error
375
+	 */
376
+	public function delete_cart()
377
+	{
378
+		$deleted = EEH_Line_Item::delete_all_child_items($this->_grand_total);
379
+		if ($deleted) {
380
+			$deleted += $this->_grand_total->delete();
381
+			$this->_grand_total = null;
382
+		}
383
+		return $deleted;
384
+	}
385
+
386
+
387
+
388
+	/**
389
+	 * @save   cart to session
390
+	 * @access public
391
+	 * @param bool $apply_taxes
392
+	 * @return TRUE on success, FALSE on fail
393
+	 * @throws \EE_Error
394
+	 */
395
+	public function save_cart($apply_taxes = true)
396
+	{
397
+		if ($apply_taxes && $this->_grand_total instanceof EE_Line_Item) {
398
+			EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
399
+			//make sure we don't cache the transaction because it can get stale
400
+			if ($this->_grand_total->get_one_from_cache('Transaction') instanceof EE_Transaction
401
+				&& $this->_grand_total->get_one_from_cache('Transaction')->ID()
402
+			) {
403
+				$this->_grand_total->clear_cache('Transaction', null, true);
404
+			}
405
+		}
406
+		if ($this->session() instanceof EE_Session) {
407
+			return $this->session()->set_cart($this);
408
+		} else {
409
+			return false;
410
+		}
411
+	}
412
+
413
+
414
+
415
+	public function __wakeup()
416
+	{
417
+		if ( ! $this->_grand_total instanceof EE_Line_Item && absint($this->_grand_total) !== 0) {
418
+			// $this->_grand_total is actually just an ID, so use it to get the object from the db
419
+			$this->_grand_total = EEM_Line_Item::instance()->get_one_by_ID($this->_grand_total);
420
+		}
421
+	}
422
+
423
+
424
+
425
+	/**
426
+	 * @return array
427
+	 */
428
+	public function __sleep()
429
+	{
430
+		if ($this->_grand_total instanceof EE_Line_Item && $this->_grand_total->ID()) {
431
+			$this->_grand_total = $this->_grand_total->ID();
432
+		}
433
+		return array('_grand_total');
434
+	}
435 435
 
436 436
 
437 437
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -203,7 +203,7 @@
 block discarded – undo
203 203
      */
204 204
     public function get_tickets()
205 205
     {
206
-        if ($this->_grand_total === null ) {
206
+        if ($this->_grand_total === null) {
207 207
             return array();
208 208
         }
209 209
         return EEH_Line_Item::get_ticket_line_items($this->_grand_total);
Please login to merge, or discard this patch.
core/EE_Session.core.php 2 patches
Indentation   +190 added lines, -190 removed lines patch added patch discarded remove patch
@@ -52,12 +52,12 @@  discard block
 block discarded – undo
52 52
 	  */
53 53
 	 private $_expiration;
54 54
 
55
-    /**
56
-     * whether or not session has expired at some point
57
-     *
58
-     * @var boolean
59
-     */
60
-    private $_expired = false;
55
+	/**
56
+	 * whether or not session has expired at some point
57
+	 *
58
+	 * @var boolean
59
+	 */
60
+	private $_expired = false;
61 61
 
62 62
 	 /**
63 63
 	  * current time as Unix timestamp in GMT
@@ -100,14 +100,14 @@  discard block
 block discarded – undo
100 100
 	  * @var array
101 101
 	  */
102 102
 	 private $_default_session_vars = array (
103
-        'id'            => null,
104
-        'user_id'       => null,
105
-        'ip_address'    => null,
106
-        'user_agent'    => null,
107
-        'init_access'   => null,
108
-        'last_access'   => null,
109
-        'expiration'    => null,
110
-        'pages_visited' => array(),
103
+		'id'            => null,
104
+		'user_id'       => null,
105
+		'ip_address'    => null,
106
+		'user_agent'    => null,
107
+		'init_access'   => null,
108
+		'last_access'   => null,
109
+		'expiration'    => null,
110
+		'pages_visited' => array(),
111 111
 	);
112 112
 
113 113
 
@@ -171,18 +171,18 @@  discard block
 block discarded – undo
171 171
 				$this->{$var_name} = $session_setting;
172 172
 			}
173 173
 		}
174
-         // are we using encryption?
175
-         $this->_use_encryption = $encryption instanceof EE_Encryption && EE_Registry::instance()->CFG->admin->encode_session_data();
176
-         // \EEH_Debug_Tools::printr($this->_use_encryption, '$this->_use_encryption', __FILE__, __LINE__);
177
-        // encrypt data via: $this->encryption->encrypt();
178
-        $this->encryption = $encryption;
174
+		 // are we using encryption?
175
+		 $this->_use_encryption = $encryption instanceof EE_Encryption && EE_Registry::instance()->CFG->admin->encode_session_data();
176
+		 // \EEH_Debug_Tools::printr($this->_use_encryption, '$this->_use_encryption', __FILE__, __LINE__);
177
+		// encrypt data via: $this->encryption->encrypt();
178
+		$this->encryption = $encryption;
179 179
 		// filter hook allows outside functions/classes/plugins to change default empty cart
180 180
 		$extra_default_session_vars = apply_filters( 'FHEE__EE_Session__construct__extra_default_session_vars', array() );
181 181
 		array_merge( $this->_default_session_vars, $extra_default_session_vars );
182 182
 		// apply default session vars
183 183
 		$this->_set_defaults();
184
-         add_action('AHEE__EE_System__initialize', array($this, 'open_session'));
185
-         // check request for 'clear_session' param
184
+		 add_action('AHEE__EE_System__initialize', array($this, 'open_session'));
185
+		 // check request for 'clear_session' param
186 186
 		add_action( 'AHEE__EE_Request_Handler__construct__complete', array( $this, 'wp_loaded' ));
187 187
 		// once everything is all said and done,
188 188
 		add_action( 'shutdown', array( $this, 'update' ), 100 );
@@ -191,38 +191,38 @@  discard block
 block discarded – undo
191 191
 
192 192
 
193 193
 
194
-     /**
195
-      * @return void
196
-      * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
197
-      * @throws \EE_Error
198
-      */
194
+	 /**
195
+	  * @return void
196
+	  * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
197
+	  * @throws \EE_Error
198
+	  */
199 199
 	 public function open_session() {
200
-         // check for existing session and retrieve it from db
201
-         if ( ! $this->_espresso_session()) {
202
-             // or just start a new one
203
-             $this->_create_espresso_session();
204
-         }
205
-     }
200
+		 // check for existing session and retrieve it from db
201
+		 if ( ! $this->_espresso_session()) {
202
+			 // or just start a new one
203
+			 $this->_create_espresso_session();
204
+		 }
205
+	 }
206 206
 
207 207
 
208 208
 
209
-    /**
210
-     * @return bool
211
-     */
212
-    public function expired()
213
-    {
214
-        return $this->_expired;
215
-    }
209
+	/**
210
+	 * @return bool
211
+	 */
212
+	public function expired()
213
+	{
214
+		return $this->_expired;
215
+	}
216 216
 
217 217
 
218 218
 
219
-    /**
220
-     * @return void
221
-     */
222
-    public function reset_expired()
223
-    {
224
-        $this->_expired = false;
225
-    }
219
+	/**
220
+	 * @return void
221
+	 */
222
+	public function reset_expired()
223
+	{
224
+		$this->_expired = false;
225
+	}
226 226
 
227 227
 
228 228
 	 /**
@@ -234,25 +234,25 @@  discard block
 block discarded – undo
234 234
 
235 235
 
236 236
 
237
-    /**
238
-     * @return int
239
-     */
240
-    public function extension()
241
-    {
242
-        return apply_filters('FHEE__EE_Session__extend_expiration__seconds_added', (10 * MINUTE_IN_SECONDS));
243
-    }
237
+	/**
238
+	 * @return int
239
+	 */
240
+	public function extension()
241
+	{
242
+		return apply_filters('FHEE__EE_Session__extend_expiration__seconds_added', (10 * MINUTE_IN_SECONDS));
243
+	}
244 244
 
245 245
 
246 246
 
247
-    /**
248
-     * @param int $time number of seconds to add to session expiration
249
-     * @return int
250
-     */
251
-    public function extend_expiration($time = 0)
252
-    {
253
-        $time = $time ? $time : $this->extension();
254
-        $this->_expiration += absint($time);
255
-    }
247
+	/**
248
+	 * @param int $time number of seconds to add to session expiration
249
+	 * @return int
250
+	 */
251
+	public function extend_expiration($time = 0)
252
+	{
253
+		$time = $time ? $time : $this->extension();
254
+		$this->_expiration += absint($time);
255
+	}
256 256
 
257 257
 
258 258
 
@@ -296,15 +296,15 @@  discard block
 block discarded – undo
296 296
 
297 297
 
298 298
 
299
-    /**
300
-     * @param \EE_Cart $cart
301
-     * @return bool
302
-     */
303
-    public function set_cart(EE_Cart $cart)
304
-    {
305
-        $this->_session_data['cart'] = $cart;
306
-        return true;
307
-    }
299
+	/**
300
+	 * @param \EE_Cart $cart
301
+	 * @return bool
302
+	 */
303
+	public function set_cart(EE_Cart $cart)
304
+	{
305
+		$this->_session_data['cart'] = $cart;
306
+		return true;
307
+	}
308 308
 
309 309
 
310 310
 
@@ -312,7 +312,7 @@  discard block
 block discarded – undo
312 312
 	  * reset_cart
313 313
 	  */
314 314
 	 public function reset_cart() {
315
-        do_action('AHEE__EE_Session__reset_cart__before_reset', $this);
315
+		do_action('AHEE__EE_Session__reset_cart__before_reset', $this);
316 316
 		 $this->_session_data['cart'] = NULL;
317 317
 	 }
318 318
 
@@ -322,9 +322,9 @@  discard block
 block discarded – undo
322 322
 	  * @return \EE_Cart
323 323
 	  */
324 324
 	 public function cart() {
325
-        return isset($this->_session_data['cart']) && $this->_session_data['cart'] instanceof EE_Cart
326
-            ? $this->_session_data['cart']
327
-            : null;
325
+		return isset($this->_session_data['cart']) && $this->_session_data['cart'] instanceof EE_Cart
326
+			? $this->_session_data['cart']
327
+			: null;
328 328
 	 }
329 329
 
330 330
 
@@ -344,7 +344,7 @@  discard block
 block discarded – undo
344 344
 	  * reset_checkout
345 345
 	  */
346 346
 	 public function reset_checkout() {
347
-        do_action('AHEE__EE_Session__reset_checkout__before_reset', $this);
347
+		do_action('AHEE__EE_Session__reset_checkout__before_reset', $this);
348 348
 		 $this->_session_data['checkout'] = NULL;
349 349
 	 }
350 350
 
@@ -354,9 +354,9 @@  discard block
 block discarded – undo
354 354
 	  * @return \EE_Checkout
355 355
 	  */
356 356
 	 public function checkout() {
357
-        return isset($this->_session_data['checkout']) && $this->_session_data['checkout'] instanceof EE_Checkout
358
-            ? $this->_session_data['checkout']
359
-            : null;
357
+		return isset($this->_session_data['checkout']) && $this->_session_data['checkout'] instanceof EE_Checkout
358
+			? $this->_session_data['checkout']
359
+			: null;
360 360
 	 }
361 361
 
362 362
 
@@ -379,7 +379,7 @@  discard block
 block discarded – undo
379 379
 	  * reset_transaction
380 380
 	  */
381 381
 	 public function reset_transaction() {
382
-        do_action('AHEE__EE_Session__reset_transaction__before_reset', $this);
382
+		do_action('AHEE__EE_Session__reset_transaction__before_reset', $this);
383 383
 		 $this->_session_data['transaction'] = NULL;
384 384
 	 }
385 385
 
@@ -389,10 +389,10 @@  discard block
 block discarded – undo
389 389
 	  * @return \EE_Transaction
390 390
 	  */
391 391
 	 public function transaction() {
392
-        return isset($this->_session_data['transaction'])
393
-               && $this->_session_data['transaction'] instanceof EE_Transaction
394
-           ? $this->_session_data['transaction']
395
-           : null;
392
+		return isset($this->_session_data['transaction'])
393
+			   && $this->_session_data['transaction'] instanceof EE_Transaction
394
+		   ? $this->_session_data['transaction']
395
+		   : null;
396 396
 	 }
397 397
 
398 398
 
@@ -469,16 +469,16 @@  discard block
 block discarded – undo
469 469
 		// set the "user agent"
470 470
 		$this->_user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? esc_attr( $_SERVER['HTTP_USER_AGENT'] ) : FALSE;
471 471
 		// now let's retrieve what's in the db
472
-        $session_data = $this->_retrieve_session_data();
473
-        if (! empty($session_data)) {
474
-            // get the current time in UTC
472
+		$session_data = $this->_retrieve_session_data();
473
+		if (! empty($session_data)) {
474
+			// get the current time in UTC
475 475
 			$this->_time = isset( $this->_time ) ? $this->_time : time();
476 476
 			// and reset the session expiration
477 477
 			$this->_expiration = isset( $session_data['expiration'] )
478 478
 				? $session_data['expiration']
479 479
 				: $this->_time + $this->_lifespan;
480 480
 		} else {
481
-            // set initial site access time and the session expiration
481
+			// set initial site access time and the session expiration
482 482
 			$this->_set_init_access_and_expiration();
483 483
 			// set referer
484 484
 			$this->_session_data[ 'pages_visited' ][ $this->_session_data['init_access'] ] = isset( $_SERVER['HTTP_REFERER'] )
@@ -487,14 +487,14 @@  discard block
 block discarded – undo
487 487
 			// no previous session = go back and create one (on top of the data above)
488 488
 			return FALSE;
489 489
 		}
490
-        // now the user agent
490
+		// now the user agent
491 491
 		if ( $session_data['user_agent'] !== $this->_user_agent ) {
492 492
 			return FALSE;
493 493
 		}
494 494
 		// wait a minute... how old are you?
495 495
 		if ( $this->_time > $this->_expiration ) {
496 496
 			// yer too old fer me!
497
-            $this->_expired = true;
497
+			$this->_expired = true;
498 498
 			// wipe out everything that isn't a default session datum
499 499
 			$this->clear_session( __CLASS__, __FUNCTION__ );
500 500
 		}
@@ -506,95 +506,95 @@  discard block
 block discarded – undo
506 506
 
507 507
 
508 508
 
509
-     /**
510
-      * _get_session_data
511
-      * Retrieves the session data, and attempts to correct any encoding issues that can occur due to improperly setup databases
512
-      *
513
-      * @return array
514
-      * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
515
-      */
516
-     protected function _retrieve_session_data()
517
-     {
518
-         $ssn_key = EE_Session::session_id_prefix . $this->_sid;
519
-         try {
520
-             // we're using WP's Transient API to store session data using the PHP session ID as the option name
521
-             $session_data = get_transient($ssn_key);
522
-	         if ($session_data === false) {
523
-		         return array();
524
-             }
525
-             if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
526
-                 $hash_check = get_transient(EE_Session::hash_check_prefix . $this->_sid);
527
-                 if ($hash_check && $hash_check !== md5($session_data)) {
528
-	                 EE_Error::add_error(
529
-                         sprintf(
530
-                             __('The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.', 'event_espresso'),
531
-                             EE_Session::session_id_prefix . $this->_sid
532
-                         ),
533
-                         __FILE__, __FUNCTION__, __LINE__
534
-                     );
535
-                 }
536
-             }
537
-         } catch (Exception $e) {
538
-             // let's just eat that error for now and attempt to correct any corrupted data
539
-             global $wpdb;
540
-             $row = $wpdb->get_row(
541
-                 $wpdb->prepare(
542
-                     "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
543
-                     '_transient_' . $ssn_key
544
-                 )
545
-             );
546
-             $session_data = is_object($row) ? $row->option_value : null;
547
-             if ($session_data) {
548
-                 $session_data = preg_replace_callback(
549
-                     '!s:(d+):"(.*?)";!',
550
-                     function ($match) {
551
-                         return $match[1] === strlen($match[2])
552
-                             ? $match[0]
553
-                             : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
554
-                     },
555
-                     $session_data
556
-                 );
557
-             }
558
-	         $session_data = maybe_unserialize($session_data);
559
-         }
560
-	     // in case the data is encoded... try to decode it
561
-         $session_data = $this->encryption instanceof EE_Encryption
562
-             ? $this->encryption->base64_string_decode($session_data)
563
-             : $session_data;
564
-
565
-         if ( ! is_array($session_data)) {
566
-             try {
567
-	             $session_data = maybe_unserialize($session_data);
568
-             } catch (Exception $e) {
569
-                 $msg = esc_html__(
570
-                     'An error occurred while attempting to unserialize the session data.',
571
-                     'event_espresso'
572
-                 );
573
-                 $msg .= WP_DEBUG
574
-                     ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
575
-                     : '';
576
-                 throw new InvalidSessionDataException($msg, 0, $e);
577
-             }
578
-         }
579
-         // just a check to make sure the session array is indeed an array
580
-         if ( ! is_array($session_data)) {
581
-             // no?!?! then something is wrong
582
-             $msg = esc_html__(
583
-                 'The session data is missing, invalid, or corrupted.',
584
-                 'event_espresso'
585
-             );
586
-             $msg .= WP_DEBUG
587
-                 ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
588
-                 : '';
589
-	         throw new InvalidSessionDataException($msg);
590
-         }
591
-	     if ( isset( $this->_session_data['transaction'] ) && absint( $this->_session_data['transaction'] ) !== 0 ) {
592
-		     $this->_session_data['transaction'] = EEM_Transaction::instance()->get_one_by_ID(
593
-			     $this->_session_data['transaction']
594
-	         );
595
-	     }
596
-	     return $session_data;
597
-     }
509
+	 /**
510
+	  * _get_session_data
511
+	  * Retrieves the session data, and attempts to correct any encoding issues that can occur due to improperly setup databases
512
+	  *
513
+	  * @return array
514
+	  * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
515
+	  */
516
+	 protected function _retrieve_session_data()
517
+	 {
518
+		 $ssn_key = EE_Session::session_id_prefix . $this->_sid;
519
+		 try {
520
+			 // we're using WP's Transient API to store session data using the PHP session ID as the option name
521
+			 $session_data = get_transient($ssn_key);
522
+			 if ($session_data === false) {
523
+				 return array();
524
+			 }
525
+			 if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
526
+				 $hash_check = get_transient(EE_Session::hash_check_prefix . $this->_sid);
527
+				 if ($hash_check && $hash_check !== md5($session_data)) {
528
+					 EE_Error::add_error(
529
+						 sprintf(
530
+							 __('The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.', 'event_espresso'),
531
+							 EE_Session::session_id_prefix . $this->_sid
532
+						 ),
533
+						 __FILE__, __FUNCTION__, __LINE__
534
+					 );
535
+				 }
536
+			 }
537
+		 } catch (Exception $e) {
538
+			 // let's just eat that error for now and attempt to correct any corrupted data
539
+			 global $wpdb;
540
+			 $row = $wpdb->get_row(
541
+				 $wpdb->prepare(
542
+					 "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
543
+					 '_transient_' . $ssn_key
544
+				 )
545
+			 );
546
+			 $session_data = is_object($row) ? $row->option_value : null;
547
+			 if ($session_data) {
548
+				 $session_data = preg_replace_callback(
549
+					 '!s:(d+):"(.*?)";!',
550
+					 function ($match) {
551
+						 return $match[1] === strlen($match[2])
552
+							 ? $match[0]
553
+							 : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
554
+					 },
555
+					 $session_data
556
+				 );
557
+			 }
558
+			 $session_data = maybe_unserialize($session_data);
559
+		 }
560
+		 // in case the data is encoded... try to decode it
561
+		 $session_data = $this->encryption instanceof EE_Encryption
562
+			 ? $this->encryption->base64_string_decode($session_data)
563
+			 : $session_data;
564
+
565
+		 if ( ! is_array($session_data)) {
566
+			 try {
567
+				 $session_data = maybe_unserialize($session_data);
568
+			 } catch (Exception $e) {
569
+				 $msg = esc_html__(
570
+					 'An error occurred while attempting to unserialize the session data.',
571
+					 'event_espresso'
572
+				 );
573
+				 $msg .= WP_DEBUG
574
+					 ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
575
+					 : '';
576
+				 throw new InvalidSessionDataException($msg, 0, $e);
577
+			 }
578
+		 }
579
+		 // just a check to make sure the session array is indeed an array
580
+		 if ( ! is_array($session_data)) {
581
+			 // no?!?! then something is wrong
582
+			 $msg = esc_html__(
583
+				 'The session data is missing, invalid, or corrupted.',
584
+				 'event_espresso'
585
+			 );
586
+			 $msg .= WP_DEBUG
587
+				 ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
588
+				 : '';
589
+			 throw new InvalidSessionDataException($msg);
590
+		 }
591
+		 if ( isset( $this->_session_data['transaction'] ) && absint( $this->_session_data['transaction'] ) !== 0 ) {
592
+			 $this->_session_data['transaction'] = EEM_Transaction::instance()->get_one_by_ID(
593
+				 $this->_session_data['transaction']
594
+			 );
595
+		 }
596
+		 return $session_data;
597
+	 }
598 598
 
599 599
 
600 600
 
@@ -1040,17 +1040,17 @@  discard block
 block discarded – undo
1040 1040
 					OR option_value > {$too_far_in_the_the_future} )
1041 1041
 					LIMIT {$expired_session_transient_delete_query_limit}
1042 1042
 				";
1043
-                    $expired_sessions = $wpdb->get_col($SQL);
1044
-                    // valid results?
1045
-                    if ( ! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1046
-                        // format array of results into something usable within the actual DELETE query's IN clause
1047
-                        $expired = array();
1048
-                        foreach ($expired_sessions as $expired_session) {
1049
-                            $expired[] = "'" . $expired_session . "'";
1050
-                            $expired[] = "'" . str_replace('timeout_', '', $expired_session) . "'";
1051
-                        }
1052
-                        $expired = implode(', ', $expired);
1053
-                        $SQL = "
1043
+					$expired_sessions = $wpdb->get_col($SQL);
1044
+					// valid results?
1045
+					if ( ! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1046
+						// format array of results into something usable within the actual DELETE query's IN clause
1047
+						$expired = array();
1048
+						foreach ($expired_sessions as $expired_session) {
1049
+							$expired[] = "'" . $expired_session . "'";
1050
+							$expired[] = "'" . str_replace('timeout_', '', $expired_session) . "'";
1051
+						}
1052
+						$expired = implode(', ', $expired);
1053
+						$SQL = "
1054 1054
 						DELETE FROM {$wpdb->options}
1055 1055
 						WHERE option_name
1056 1056
 						IN ( $expired );
Please login to merge, or discard this patch.
Spacing   +161 added lines, -161 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php use EventEspresso\core\exceptions\InvalidSessionDataException;
2 2
 
3
-if (!defined( 'EVENT_ESPRESSO_VERSION')) {exit('No direct script access allowed');}
3
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {exit('No direct script access allowed'); }
4 4
 /**
5 5
  *
6 6
  * EE_Session class
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
 	  * array for defining default session vars
100 100
 	  * @var array
101 101
 	  */
102
-	 private $_default_session_vars = array (
102
+	 private $_default_session_vars = array(
103 103
         'id'            => null,
104 104
         'user_id'       => null,
105 105
         'ip_address'    => null,
@@ -119,12 +119,12 @@  discard block
 block discarded – undo
119 119
 	  * @throws InvalidSessionDataException
120 120
 	  * @throws \EE_Error
121 121
 	  */
122
-	public static function instance( EE_Encryption $encryption = null ) {
122
+	public static function instance(EE_Encryption $encryption = null) {
123 123
 		// check if class object is instantiated
124 124
 		// session loading is turned ON by default, but prior to the init hook, can be turned back OFF via:
125 125
 		// add_filter( 'FHEE_load_EE_Session', '__return_false' );
126
-		if ( ! self::$_instance instanceof EE_Session && apply_filters( 'FHEE_load_EE_Session', true ) ) {
127
-			self::$_instance = new self( $encryption );
126
+		if ( ! self::$_instance instanceof EE_Session && apply_filters('FHEE_load_EE_Session', true)) {
127
+			self::$_instance = new self($encryption);
128 128
 		}
129 129
 		return self::$_instance;
130 130
 	}
@@ -140,15 +140,15 @@  discard block
 block discarded – undo
140 140
 	  * @throws \EE_Error
141 141
 	  * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
142 142
 	  */
143
-	 protected function __construct( EE_Encryption $encryption = null ) {
143
+	 protected function __construct(EE_Encryption $encryption = null) {
144 144
 
145 145
 		// session loading is turned ON by default, but prior to the init hook, can be turned back OFF via: add_filter( 'FHEE_load_EE_Session', '__return_false' );
146
-		if ( ! apply_filters( 'FHEE_load_EE_Session', true ) ) {
146
+		if ( ! apply_filters('FHEE_load_EE_Session', true)) {
147 147
 			return;
148 148
 		}
149
-		do_action( 'AHEE_log', __FILE__, __FUNCTION__, '' );
150
-		if ( ! defined( 'ESPRESSO_SESSION' ) ) {
151
-			define( 'ESPRESSO_SESSION', true );
149
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
150
+		if ( ! defined('ESPRESSO_SESSION')) {
151
+			define('ESPRESSO_SESSION', true);
152 152
 		}
153 153
 		// default session lifespan in seconds
154 154
 		$this->_lifespan = apply_filters(
@@ -162,12 +162,12 @@  discard block
 block discarded – undo
162 162
 		 * 		}
163 163
 		 */
164 164
 		// retrieve session options from db
165
-		$session_settings = (array) get_option( 'ee_session_settings', array() );
166
-		if ( ! empty( $session_settings )) {
165
+		$session_settings = (array) get_option('ee_session_settings', array());
166
+		if ( ! empty($session_settings)) {
167 167
 			// cycle though existing session options
168
-			foreach ( $session_settings as $var_name => $session_setting ) {
168
+			foreach ($session_settings as $var_name => $session_setting) {
169 169
 				// set values for class properties
170
-				$var_name = '_' . $var_name;
170
+				$var_name = '_'.$var_name;
171 171
 				$this->{$var_name} = $session_setting;
172 172
 			}
173 173
 		}
@@ -177,16 +177,16 @@  discard block
 block discarded – undo
177 177
         // encrypt data via: $this->encryption->encrypt();
178 178
         $this->encryption = $encryption;
179 179
 		// filter hook allows outside functions/classes/plugins to change default empty cart
180
-		$extra_default_session_vars = apply_filters( 'FHEE__EE_Session__construct__extra_default_session_vars', array() );
181
-		array_merge( $this->_default_session_vars, $extra_default_session_vars );
180
+		$extra_default_session_vars = apply_filters('FHEE__EE_Session__construct__extra_default_session_vars', array());
181
+		array_merge($this->_default_session_vars, $extra_default_session_vars);
182 182
 		// apply default session vars
183 183
 		$this->_set_defaults();
184 184
          add_action('AHEE__EE_System__initialize', array($this, 'open_session'));
185 185
          // check request for 'clear_session' param
186
-		add_action( 'AHEE__EE_Request_Handler__construct__complete', array( $this, 'wp_loaded' ));
186
+		add_action('AHEE__EE_Request_Handler__construct__complete', array($this, 'wp_loaded'));
187 187
 		// once everything is all said and done,
188
-		add_action( 'shutdown', array( $this, 'update' ), 100 );
189
-		add_action( 'shutdown', array( $this, 'garbage_collection' ), 999 );
188
+		add_action('shutdown', array($this, 'update'), 100);
189
+		add_action('shutdown', array($this, 'garbage_collection'), 999);
190 190
 	}
191 191
 
192 192
 
@@ -274,11 +274,11 @@  discard block
 block discarded – undo
274 274
 	 */
275 275
 	private function _set_defaults() {
276 276
 		// set some defaults
277
-		foreach ( $this->_default_session_vars as $key => $default_var ) {
278
-			if ( is_array( $default_var )) {
279
-				$this->_session_data[ $key ] = array();
277
+		foreach ($this->_default_session_vars as $key => $default_var) {
278
+			if (is_array($default_var)) {
279
+				$this->_session_data[$key] = array();
280 280
 			} else {
281
-				$this->_session_data[ $key ] = '';
281
+				$this->_session_data[$key] = '';
282 282
 			}
283 283
 		}
284 284
 	}
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
 	  * @param \EE_Checkout $checkout
334 334
 	  * @return bool
335 335
 	  */
336
-	 public function set_checkout( EE_Checkout $checkout ) {
336
+	 public function set_checkout(EE_Checkout $checkout) {
337 337
 		 $this->_session_data['checkout'] = $checkout;
338 338
 		 return TRUE;
339 339
 	 }
@@ -366,9 +366,9 @@  discard block
 block discarded – undo
366 366
 	  * @return bool
367 367
 	  * @throws \EE_Error
368 368
 	  */
369
-	 public function set_transaction( EE_Transaction $transaction ) {
369
+	 public function set_transaction(EE_Transaction $transaction) {
370 370
 		 // first remove the session from the transaction before we save the transaction in the session
371
-		 $transaction->set_txn_session_data( NULL );
371
+		 $transaction->set_txn_session_data(NULL);
372 372
 		 $this->_session_data['transaction'] = $transaction;
373 373
 		 return TRUE;
374 374
 	 }
@@ -404,15 +404,15 @@  discard block
 block discarded – undo
404 404
 	  * @param bool $reset_cache
405 405
 	  * @return    array
406 406
 	  */
407
-	public function get_session_data( $key = NULL, $reset_cache = FALSE ) {
408
-		if ( $reset_cache ) {
407
+	public function get_session_data($key = NULL, $reset_cache = FALSE) {
408
+		if ($reset_cache) {
409 409
 			$this->reset_cart();
410 410
 			$this->reset_checkout();
411 411
 			$this->reset_transaction();
412 412
 		}
413
-		 if ( ! empty( $key ))  {
414
-			return  isset( $this->_session_data[ $key ] ) ? $this->_session_data[ $key ] : NULL;
415
-		}  else  {
413
+		 if ( ! empty($key)) {
414
+			return  isset($this->_session_data[$key]) ? $this->_session_data[$key] : NULL;
415
+		} else {
416 416
 			return $this->_session_data;
417 417
 		}
418 418
 	}
@@ -425,20 +425,20 @@  discard block
 block discarded – undo
425 425
 	  * @param 	array $data
426 426
 	  * @return 	TRUE on success, FALSE on fail
427 427
 	  */
428
-	public function set_session_data( $data ) {
428
+	public function set_session_data($data) {
429 429
 
430 430
 		// nothing ??? bad data ??? go home!
431
-		if ( empty( $data ) || ! is_array( $data )) {
432
-			EE_Error::add_error( __( 'No session data or invalid session data was provided.', 'event_espresso' ), __FILE__, __FUNCTION__, __LINE__ );
431
+		if (empty($data) || ! is_array($data)) {
432
+			EE_Error::add_error(__('No session data or invalid session data was provided.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
433 433
 			return FALSE;
434 434
 		}
435 435
 
436
-		foreach ( $data as $key =>$value ) {
437
-			if ( isset( $this->_default_session_vars[ $key ] )) {
438
-				EE_Error::add_error( sprintf( __( 'Sorry! %s is a default session datum and can not be reset.', 'event_espresso' ), $key ), __FILE__, __FUNCTION__, __LINE__ );
436
+		foreach ($data as $key =>$value) {
437
+			if (isset($this->_default_session_vars[$key])) {
438
+				EE_Error::add_error(sprintf(__('Sorry! %s is a default session datum and can not be reset.', 'event_espresso'), $key), __FILE__, __FUNCTION__, __LINE__);
439 439
 				return FALSE;
440 440
 			} else {
441
-				$this->_session_data[ $key ] = $value;
441
+				$this->_session_data[$key] = $value;
442 442
 			}
443 443
 		}
444 444
 
@@ -456,9 +456,9 @@  discard block
 block discarded – undo
456 456
 	  * @throws \EE_Error
457 457
 	  */
458 458
 	private function _espresso_session() {
459
-		do_action( 'AHEE_log', __FILE__, __FUNCTION__, '' );
459
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
460 460
 		// check that session has started
461
-		if ( session_id() === '' ) {
461
+		if (session_id() === '') {
462 462
 			//starts a new session if one doesn't already exist, or re-initiates an existing one
463 463
 			session_start();
464 464
 		}
@@ -467,39 +467,39 @@  discard block
 block discarded – undo
467 467
 		// and the visitors IP
468 468
 		$this->_ip_address = $this->_visitor_ip();
469 469
 		// set the "user agent"
470
-		$this->_user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? esc_attr( $_SERVER['HTTP_USER_AGENT'] ) : FALSE;
470
+		$this->_user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? esc_attr($_SERVER['HTTP_USER_AGENT']) : FALSE;
471 471
 		// now let's retrieve what's in the db
472 472
         $session_data = $this->_retrieve_session_data();
473
-        if (! empty($session_data)) {
473
+        if ( ! empty($session_data)) {
474 474
             // get the current time in UTC
475
-			$this->_time = isset( $this->_time ) ? $this->_time : time();
475
+			$this->_time = isset($this->_time) ? $this->_time : time();
476 476
 			// and reset the session expiration
477
-			$this->_expiration = isset( $session_data['expiration'] )
477
+			$this->_expiration = isset($session_data['expiration'])
478 478
 				? $session_data['expiration']
479 479
 				: $this->_time + $this->_lifespan;
480 480
 		} else {
481 481
             // set initial site access time and the session expiration
482 482
 			$this->_set_init_access_and_expiration();
483 483
 			// set referer
484
-			$this->_session_data[ 'pages_visited' ][ $this->_session_data['init_access'] ] = isset( $_SERVER['HTTP_REFERER'] )
485
-				? esc_attr( $_SERVER['HTTP_REFERER'] )
484
+			$this->_session_data['pages_visited'][$this->_session_data['init_access']] = isset($_SERVER['HTTP_REFERER'])
485
+				? esc_attr($_SERVER['HTTP_REFERER'])
486 486
 				: '';
487 487
 			// no previous session = go back and create one (on top of the data above)
488 488
 			return FALSE;
489 489
 		}
490 490
         // now the user agent
491
-		if ( $session_data['user_agent'] !== $this->_user_agent ) {
491
+		if ($session_data['user_agent'] !== $this->_user_agent) {
492 492
 			return FALSE;
493 493
 		}
494 494
 		// wait a minute... how old are you?
495
-		if ( $this->_time > $this->_expiration ) {
495
+		if ($this->_time > $this->_expiration) {
496 496
 			// yer too old fer me!
497 497
             $this->_expired = true;
498 498
 			// wipe out everything that isn't a default session datum
499
-			$this->clear_session( __CLASS__, __FUNCTION__ );
499
+			$this->clear_session(__CLASS__, __FUNCTION__);
500 500
 		}
501 501
 		// make event espresso session data available to plugin
502
-		$this->_session_data = array_merge( $this->_session_data, $session_data );
502
+		$this->_session_data = array_merge($this->_session_data, $session_data);
503 503
 		return TRUE;
504 504
 
505 505
 	}
@@ -515,7 +515,7 @@  discard block
 block discarded – undo
515 515
       */
516 516
      protected function _retrieve_session_data()
517 517
      {
518
-         $ssn_key = EE_Session::session_id_prefix . $this->_sid;
518
+         $ssn_key = EE_Session::session_id_prefix.$this->_sid;
519 519
          try {
520 520
              // we're using WP's Transient API to store session data using the PHP session ID as the option name
521 521
              $session_data = get_transient($ssn_key);
@@ -523,12 +523,12 @@  discard block
 block discarded – undo
523 523
 		         return array();
524 524
              }
525 525
              if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
526
-                 $hash_check = get_transient(EE_Session::hash_check_prefix . $this->_sid);
526
+                 $hash_check = get_transient(EE_Session::hash_check_prefix.$this->_sid);
527 527
                  if ($hash_check && $hash_check !== md5($session_data)) {
528 528
 	                 EE_Error::add_error(
529 529
                          sprintf(
530 530
                              __('The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.', 'event_espresso'),
531
-                             EE_Session::session_id_prefix . $this->_sid
531
+                             EE_Session::session_id_prefix.$this->_sid
532 532
                          ),
533 533
                          __FILE__, __FUNCTION__, __LINE__
534 534
                      );
@@ -540,17 +540,17 @@  discard block
 block discarded – undo
540 540
              $row = $wpdb->get_row(
541 541
                  $wpdb->prepare(
542 542
                      "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
543
-                     '_transient_' . $ssn_key
543
+                     '_transient_'.$ssn_key
544 544
                  )
545 545
              );
546 546
              $session_data = is_object($row) ? $row->option_value : null;
547 547
              if ($session_data) {
548 548
                  $session_data = preg_replace_callback(
549 549
                      '!s:(d+):"(.*?)";!',
550
-                     function ($match) {
550
+                     function($match) {
551 551
                          return $match[1] === strlen($match[2])
552 552
                              ? $match[0]
553
-                             : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
553
+                             : 's:'.strlen($match[2]).':"'.$match[2].'";';
554 554
                      },
555 555
                      $session_data
556 556
                  );
@@ -571,7 +571,7 @@  discard block
 block discarded – undo
571 571
                      'event_espresso'
572 572
                  );
573 573
                  $msg .= WP_DEBUG
574
-                     ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
574
+                     ? '<br><pre>'.print_r($session_data, true).'</pre><br>'.$this->find_serialize_error($session_data)
575 575
                      : '';
576 576
                  throw new InvalidSessionDataException($msg, 0, $e);
577 577
              }
@@ -584,11 +584,11 @@  discard block
 block discarded – undo
584 584
                  'event_espresso'
585 585
              );
586 586
              $msg .= WP_DEBUG
587
-                 ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
587
+                 ? '<br><pre>'.print_r($session_data, true).'</pre><br>'.$this->find_serialize_error($session_data)
588 588
                  : '';
589 589
 	         throw new InvalidSessionDataException($msg);
590 590
          }
591
-	     if ( isset( $this->_session_data['transaction'] ) && absint( $this->_session_data['transaction'] ) !== 0 ) {
591
+	     if (isset($this->_session_data['transaction']) && absint($this->_session_data['transaction']) !== 0) {
592 592
 		     $this->_session_data['transaction'] = EEM_Transaction::instance()->get_one_by_ID(
593 593
 			     $this->_session_data['transaction']
594 594
 	         );
@@ -609,12 +609,12 @@  discard block
 block discarded – undo
609 609
 	  */
610 610
 	protected function _generate_session_id() {
611 611
 		// check if the SID was passed explicitly, otherwise get from session, then add salt and hash it to reduce length
612
-		if ( isset( $_REQUEST[ 'EESID' ] ) ) {
613
-			$session_id = sanitize_text_field( $_REQUEST[ 'EESID' ] );
612
+		if (isset($_REQUEST['EESID'])) {
613
+			$session_id = sanitize_text_field($_REQUEST['EESID']);
614 614
 		} else {
615
-			$session_id = md5( session_id() . get_current_blog_id() . $this->_get_sid_salt() );
615
+			$session_id = md5(session_id().get_current_blog_id().$this->_get_sid_salt());
616 616
 		}
617
-		return apply_filters( 'FHEE__EE_Session___generate_session_id__session_id', $session_id );
617
+		return apply_filters('FHEE__EE_Session___generate_session_id__session_id', $session_id);
618 618
 	}
619 619
 
620 620
 
@@ -626,20 +626,20 @@  discard block
 block discarded – undo
626 626
 	  */
627 627
 	protected function _get_sid_salt() {
628 628
 		// was session id salt already saved to db ?
629
-		if ( empty( $this->_sid_salt ) ) {
629
+		if (empty($this->_sid_salt)) {
630 630
 			// no?  then maybe use WP defined constant
631
-			if ( defined( 'AUTH_SALT' ) ) {
631
+			if (defined('AUTH_SALT')) {
632 632
 				$this->_sid_salt = AUTH_SALT;
633 633
 			}
634 634
 			// if salt doesn't exist or is too short
635
-			if ( empty( $this->_sid_salt ) || strlen( $this->_sid_salt ) < 32 ) {
635
+			if (empty($this->_sid_salt) || strlen($this->_sid_salt) < 32) {
636 636
 				// create a new one
637
-				$this->_sid_salt = wp_generate_password( 64 );
637
+				$this->_sid_salt = wp_generate_password(64);
638 638
 			}
639 639
 			// and save it as a permanent session setting
640
-			$session_settings = get_option( 'ee_session_settings' );
641
-			$session_settings[ 'sid_salt' ] = $this->_sid_salt;
642
-			update_option( 'ee_session_settings', $session_settings );
640
+			$session_settings = get_option('ee_session_settings');
641
+			$session_settings['sid_salt'] = $this->_sid_salt;
642
+			update_option('ee_session_settings', $session_settings);
643 643
 		}
644 644
 		return $this->_sid_salt;
645 645
 	}
@@ -667,19 +667,19 @@  discard block
 block discarded – undo
667 667
 	  * @param bool $new_session
668 668
 	  * @return TRUE on success, FALSE on fail
669 669
 	  */
670
-	public function update( $new_session = FALSE ) {
671
-		$this->_session_data = isset( $this->_session_data )
672
-			&& is_array( $this->_session_data )
673
-			&& isset( $this->_session_data['id'])
670
+	public function update($new_session = FALSE) {
671
+		$this->_session_data = isset($this->_session_data)
672
+			&& is_array($this->_session_data)
673
+			&& isset($this->_session_data['id'])
674 674
 			? $this->_session_data
675 675
 			: array();
676
-		if ( empty( $this->_session_data )) {
676
+		if (empty($this->_session_data)) {
677 677
 			$this->_set_defaults();
678 678
 		}
679 679
 		$session_data = array();
680
-		foreach ( $this->_session_data as $key => $value ) {
680
+		foreach ($this->_session_data as $key => $value) {
681 681
 
682
-			switch( $key ) {
682
+			switch ($key) {
683 683
 
684 684
 				case 'id' :
685 685
 					// session ID
@@ -697,7 +697,7 @@  discard block
 block discarded – undo
697 697
 				break;
698 698
 
699 699
 				case 'init_access' :
700
-					$session_data['init_access'] = absint( $value );
700
+					$session_data['init_access'] = absint($value);
701 701
 				break;
702 702
 
703 703
 				case 'last_access' :
@@ -707,7 +707,7 @@  discard block
 block discarded – undo
707 707
 
708 708
 				case 'expiration' :
709 709
 					// when the session expires
710
-					$session_data['expiration'] = ! empty( $this->_expiration )
710
+					$session_data['expiration'] = ! empty($this->_expiration)
711 711
 						? $this->_expiration
712 712
 						: $session_data['init_access'] + $this->_lifespan;
713 713
 				break;
@@ -719,11 +719,11 @@  discard block
 block discarded – undo
719 719
 
720 720
 				case 'pages_visited' :
721 721
 					$page_visit = $this->_get_page_visit();
722
-					if ( $page_visit ) {
722
+					if ($page_visit) {
723 723
 						// set pages visited where the first will be the http referrer
724
-						$this->_session_data[ 'pages_visited' ][ $this->_time ] = $page_visit;
724
+						$this->_session_data['pages_visited'][$this->_time] = $page_visit;
725 725
 						// we'll only save the last 10 page visits.
726
-						$session_data[ 'pages_visited' ] = array_slice( $this->_session_data['pages_visited'], -10 );
726
+						$session_data['pages_visited'] = array_slice($this->_session_data['pages_visited'], -10);
727 727
 					}
728 728
 				break;
729 729
 
@@ -737,9 +737,9 @@  discard block
 block discarded – undo
737 737
 
738 738
 		$this->_session_data = $session_data;
739 739
 		// creating a new session does not require saving to the db just yet
740
-		if ( ! $new_session ) {
740
+		if ( ! $new_session) {
741 741
 			// ready? let's save
742
-			if ( $this->_save_session_to_db() ) {
742
+			if ($this->_save_session_to_db()) {
743 743
 				return TRUE;
744 744
 			} else {
745 745
 				return FALSE;
@@ -758,9 +758,9 @@  discard block
 block discarded – undo
758 758
 	 * 	@return bool
759 759
 	 */
760 760
 	private function _create_espresso_session( ) {
761
-		do_action( 'AHEE_log', __CLASS__, __FUNCTION__, '' );
761
+		do_action('AHEE_log', __CLASS__, __FUNCTION__, '');
762 762
 		// use the update function for now with $new_session arg set to TRUE
763
-		return  $this->update( TRUE ) ? TRUE : FALSE;
763
+		return  $this->update(TRUE) ? TRUE : FALSE;
764 764
 	}
765 765
 
766 766
 
@@ -786,15 +786,15 @@  discard block
 block discarded – undo
786 786
 				// OR an admin request that is NOT AJAX
787 787
 				|| (
788 788
 					is_admin()
789
-					&& ! ( defined( 'DOING_AJAX' ) && DOING_AJAX )
789
+					&& ! (defined('DOING_AJAX') && DOING_AJAX)
790 790
 				)
791 791
 			)
792 792
 		) {
793 793
 			return false;
794 794
 		}
795 795
 		$transaction = $this->transaction();
796
-		if ( $transaction instanceof EE_Transaction ) {
797
-			if ( ! $transaction->ID() ) {
796
+		if ($transaction instanceof EE_Transaction) {
797
+			if ( ! $transaction->ID()) {
798 798
 				$transaction->save();
799 799
 			}
800 800
 			$this->_session_data['transaction'] = $transaction->ID();
@@ -802,13 +802,13 @@  discard block
 block discarded – undo
802 802
 		// then serialize all of our session data
803 803
 		$session_data = serialize($this->_session_data);
804 804
 		// do we need to also encode it to avoid corrupted data when saved to the db?
805
-		$session_data = $this->_use_encryption ? $this->encryption->base64_string_encode( $session_data ) : $session_data;
805
+		$session_data = $this->_use_encryption ? $this->encryption->base64_string_encode($session_data) : $session_data;
806 806
 		// maybe save hash check
807
-		if ( apply_filters( 'FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG ) ) {
808
-			set_transient( EE_Session::hash_check_prefix . $this->_sid, md5( $session_data ), $this->_lifespan );
807
+		if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
808
+			set_transient(EE_Session::hash_check_prefix.$this->_sid, md5($session_data), $this->_lifespan);
809 809
 		}
810 810
 		// we're using the Transient API for storing session data, cuz it's so damn simple -> set_transient(  transient ID, data, expiry )
811
-		return set_transient( EE_Session::session_id_prefix . $this->_sid, $session_data, $this->_lifespan );
811
+		return set_transient(EE_Session::session_id_prefix.$this->_sid, $session_data, $this->_lifespan);
812 812
 	}
813 813
 
814 814
 
@@ -834,10 +834,10 @@  discard block
 block discarded – undo
834 834
 			'HTTP_FORWARDED',
835 835
 			'REMOTE_ADDR'
836 836
 		);
837
-		foreach ( $server_keys as $key ){
838
-			if ( isset( $_SERVER[ $key ] )) {
839
-				foreach ( array_map( 'trim', explode( ',', $_SERVER[ $key ] )) as $ip ) {
840
-					if ( $ip === '127.0.0.1' || filter_var( $ip, FILTER_VALIDATE_IP ) !== FALSE ) {
837
+		foreach ($server_keys as $key) {
838
+			if (isset($_SERVER[$key])) {
839
+				foreach (array_map('trim', explode(',', $_SERVER[$key])) as $ip) {
840
+					if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== FALSE) {
841 841
 						$visitor_ip = $ip;
842 842
 					}
843 843
 				}
@@ -856,32 +856,32 @@  discard block
 block discarded – undo
856 856
 	 *			@return string
857 857
 	 */
858 858
 	public function _get_page_visit() {
859
-		$page_visit = home_url('/') . 'wp-admin/admin-ajax.php';
859
+		$page_visit = home_url('/').'wp-admin/admin-ajax.php';
860 860
 		// check for request url
861
-		if ( isset( $_SERVER['REQUEST_URI'] )) {
861
+		if (isset($_SERVER['REQUEST_URI'])) {
862 862
 			$http_host = '';
863 863
 			$page_id = '?';
864 864
 			$e_reg = '';
865
-			$request_uri = esc_url( $_SERVER['REQUEST_URI'] );
866
-			$ru_bits = explode( '?', $request_uri );
865
+			$request_uri = esc_url($_SERVER['REQUEST_URI']);
866
+			$ru_bits = explode('?', $request_uri);
867 867
 			$request_uri = $ru_bits[0];
868 868
 			// check for and grab host as well
869
-			if ( isset( $_SERVER['HTTP_HOST'] )) {
870
-				$http_host = esc_url( $_SERVER['HTTP_HOST'] );
869
+			if (isset($_SERVER['HTTP_HOST'])) {
870
+				$http_host = esc_url($_SERVER['HTTP_HOST']);
871 871
 			}
872 872
 			// check for page_id in SERVER REQUEST
873
-			if ( isset( $_REQUEST['page_id'] )) {
873
+			if (isset($_REQUEST['page_id'])) {
874 874
 				// rebuild $e_reg without any of the extra parameters
875
-				$page_id = '?page_id=' . esc_attr( $_REQUEST['page_id'] ) . '&amp;';
875
+				$page_id = '?page_id='.esc_attr($_REQUEST['page_id']).'&amp;';
876 876
 			}
877 877
 			// check for $e_reg in SERVER REQUEST
878
-			if ( isset( $_REQUEST['ee'] )) {
878
+			if (isset($_REQUEST['ee'])) {
879 879
 				// rebuild $e_reg without any of the extra parameters
880
-				$e_reg = 'ee=' . esc_attr( $_REQUEST['ee'] );
880
+				$e_reg = 'ee='.esc_attr($_REQUEST['ee']);
881 881
 			}
882
-			$page_visit = rtrim( $http_host . $request_uri . $page_id . $e_reg, '?' );
882
+			$page_visit = rtrim($http_host.$request_uri.$page_id.$e_reg, '?');
883 883
 		}
884
-		return $page_visit !== home_url( '/wp-admin/admin-ajax.php' ) ? $page_visit : '';
884
+		return $page_visit !== home_url('/wp-admin/admin-ajax.php') ? $page_visit : '';
885 885
 
886 886
 	}
887 887
 
@@ -910,14 +910,14 @@  discard block
 block discarded – undo
910 910
 	  * @param string $function
911 911
 	  * @return void
912 912
 	  */
913
-	public function clear_session( $class = '', $function = '' ) {
913
+	public function clear_session($class = '', $function = '') {
914 914
 		//echo '<h3 style="color:#999;line-height:.9em;"><span style="color:#2EA2CC">' . __CLASS__ . '</span>::<span style="color:#E76700">' . __FUNCTION__ . '( ' . $class . '::' . $function . '() )</span><br/><span style="font-size:9px;font-weight:normal;">' . __FILE__ . '</span>    <b style="font-size:10px;">  ' . __LINE__ . ' </b></h3>';
915
-		do_action( 'AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : ' . $class . '::' .  $function . '()' );
915
+		do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : '.$class.'::'.$function.'()');
916 916
 		$this->reset_cart();
917 917
 		$this->reset_checkout();
918 918
 		$this->reset_transaction();
919 919
 		// wipe out everything that isn't a default session datum
920
-		$this->reset_data( array_keys( $this->_session_data ));
920
+		$this->reset_data(array_keys($this->_session_data));
921 921
 		// reset initial site access time and the session expiration
922 922
 		$this->_set_init_access_and_expiration();
923 923
 		$this->_save_session_to_db();
@@ -932,42 +932,42 @@  discard block
 block discarded – undo
932 932
 	  * @param bool  $show_all_notices
933 933
 	  * @return TRUE on success, FALSE on fail
934 934
 	  */
935
-	public function reset_data( $data_to_reset = array(), $show_all_notices = FALSE ) {
935
+	public function reset_data($data_to_reset = array(), $show_all_notices = FALSE) {
936 936
 		// if $data_to_reset is not in an array, then put it in one
937
-		if ( ! is_array( $data_to_reset ) ) {
938
-			$data_to_reset = array ( $data_to_reset );
937
+		if ( ! is_array($data_to_reset)) {
938
+			$data_to_reset = array($data_to_reset);
939 939
 		}
940 940
 		// nothing ??? go home!
941
-		if ( empty( $data_to_reset )) {
942
-			EE_Error::add_error( __( 'No session data could be reset, because no session var name was provided.', 'event_espresso' ), __FILE__, __FUNCTION__, __LINE__ );
941
+		if (empty($data_to_reset)) {
942
+			EE_Error::add_error(__('No session data could be reset, because no session var name was provided.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
943 943
 			return FALSE;
944 944
 		}
945 945
 		$return_value = TRUE;
946 946
 		// since $data_to_reset is an array, cycle through the values
947
-		foreach ( $data_to_reset as $reset ) {
947
+		foreach ($data_to_reset as $reset) {
948 948
 
949 949
 			// first check to make sure it is a valid session var
950
-			if ( isset( $this->_session_data[ $reset ] )) {
950
+			if (isset($this->_session_data[$reset])) {
951 951
 				// then check to make sure it is not a default var
952
-				if ( ! array_key_exists( $reset, $this->_default_session_vars )) {
952
+				if ( ! array_key_exists($reset, $this->_default_session_vars)) {
953 953
 					// remove session var
954
-					unset( $this->_session_data[ $reset ] );
955
-					if ( $show_all_notices ) {
956
-						EE_Error::add_success( sprintf( __( 'The session variable %s was removed.', 'event_espresso' ), $reset ), __FILE__, __FUNCTION__, __LINE__ );
954
+					unset($this->_session_data[$reset]);
955
+					if ($show_all_notices) {
956
+						EE_Error::add_success(sprintf(__('The session variable %s was removed.', 'event_espresso'), $reset), __FILE__, __FUNCTION__, __LINE__);
957 957
 					}
958
-					$return_value = !isset($return_value) ? TRUE : $return_value;
958
+					$return_value = ! isset($return_value) ? TRUE : $return_value;
959 959
 
960 960
 				} else {
961 961
 					// yeeeeeeeeerrrrrrrrrrr OUT !!!!
962
-					if ( $show_all_notices ) {
963
-						EE_Error::add_error( sprintf( __( 'Sorry! %s is a default session datum and can not be reset.', 'event_espresso' ), $reset ), __FILE__, __FUNCTION__, __LINE__ );
962
+					if ($show_all_notices) {
963
+						EE_Error::add_error(sprintf(__('Sorry! %s is a default session datum and can not be reset.', 'event_espresso'), $reset), __FILE__, __FUNCTION__, __LINE__);
964 964
 					}
965 965
 					$return_value = FALSE;
966 966
 				}
967 967
 
968
-			} else if ( $show_all_notices ) {
968
+			} else if ($show_all_notices) {
969 969
 				// oops! that session var does not exist!
970
-				EE_Error::add_error( sprintf( __( 'The session item provided, %s, is invalid or does not exist.', 'event_espresso' ), $reset ), __FILE__, __FUNCTION__, __LINE__ );
970
+				EE_Error::add_error(sprintf(__('The session item provided, %s, is invalid or does not exist.', 'event_espresso'), $reset), __FILE__, __FUNCTION__, __LINE__);
971 971
 				$return_value = FALSE;
972 972
 			}
973 973
 
@@ -987,8 +987,8 @@  discard block
 block discarded – undo
987 987
 	 *   @access public
988 988
 	 */
989 989
 	public function wp_loaded() {
990
-		if ( isset(  EE_Registry::instance()->REQ ) && EE_Registry::instance()->REQ->is_set( 'clear_session' )) {
991
-			$this->clear_session( __CLASS__, __FUNCTION__ );
990
+		if (isset(EE_Registry::instance()->REQ) && EE_Registry::instance()->REQ->is_set('clear_session')) {
991
+			$this->clear_session(__CLASS__, __FUNCTION__);
992 992
 		}
993 993
 	}
994 994
 
@@ -1013,24 +1013,24 @@  discard block
 block discarded – undo
1013 1013
 	  */
1014 1014
 	 public function garbage_collection() {
1015 1015
 		 // only perform during regular requests
1016
-		 if ( ! defined( 'DOING_AJAX') || ! DOING_AJAX ) {
1016
+		 if ( ! defined('DOING_AJAX') || ! DOING_AJAX) {
1017 1017
 			 /** @type WPDB $wpdb */
1018 1018
 			 global $wpdb;
1019 1019
 			 // since transient expiration timestamps are set in the future, we can compare against NOW
1020 1020
 			 $expiration = time();
1021
-			 $too_far_in_the_the_future = $expiration + ( $this->_lifespan * 2 );
1021
+			 $too_far_in_the_the_future = $expiration + ($this->_lifespan * 2);
1022 1022
 			 // filter the query limit. Set to 0 to turn off garbage collection
1023
-			 $expired_session_transient_delete_query_limit = absint( apply_filters( 'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit', 50 ));
1023
+			 $expired_session_transient_delete_query_limit = absint(apply_filters('FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit', 50));
1024 1024
 			 // non-zero LIMIT means take out the trash
1025
-			 if ( $expired_session_transient_delete_query_limit ) {
1025
+			 if ($expired_session_transient_delete_query_limit) {
1026 1026
 				 //array of transient keys that require garbage collection
1027 1027
 				 $session_keys = array(
1028 1028
 					 EE_Session::session_id_prefix,
1029 1029
 					 EE_Session::hash_check_prefix,
1030 1030
 				 );
1031
-				 foreach ( $session_keys as $session_key ) {
1032
-					 $session_key = str_replace( '_', '\_', $session_key );
1033
-					 $session_key = '\_transient\_timeout\_' . $session_key . '%';
1031
+				 foreach ($session_keys as $session_key) {
1032
+					 $session_key = str_replace('_', '\_', $session_key);
1033
+					 $session_key = '\_transient\_timeout\_'.$session_key.'%';
1034 1034
 					 $SQL = "
1035 1035
 					SELECT option_name
1036 1036
 					FROM {$wpdb->options}
@@ -1046,8 +1046,8 @@  discard block
 block discarded – undo
1046 1046
                         // format array of results into something usable within the actual DELETE query's IN clause
1047 1047
                         $expired = array();
1048 1048
                         foreach ($expired_sessions as $expired_session) {
1049
-                            $expired[] = "'" . $expired_session . "'";
1050
-                            $expired[] = "'" . str_replace('timeout_', '', $expired_session) . "'";
1049
+                            $expired[] = "'".$expired_session."'";
1050
+                            $expired[] = "'".str_replace('timeout_', '', $expired_session)."'";
1051 1051
                         }
1052 1052
                         $expired = implode(', ', $expired);
1053 1053
                         $SQL = "
@@ -1055,10 +1055,10 @@  discard block
 block discarded – undo
1055 1055
 						WHERE option_name
1056 1056
 						IN ( $expired );
1057 1057
 					 ";
1058
-						 $results = $wpdb->query( $SQL );
1058
+						 $results = $wpdb->query($SQL);
1059 1059
 						 // if something went wrong, then notify the admin
1060
-						 if ( $results instanceof WP_Error && is_admin() ) {
1061
-							 EE_Error::add_error( $results->get_error_message(), __FILE__, __FUNCTION__, __LINE__ );
1060
+						 if ($results instanceof WP_Error && is_admin()) {
1061
+							 EE_Error::add_error($results->get_error_message(), __FILE__, __FUNCTION__, __LINE__);
1062 1062
 						 }
1063 1063
 					 }
1064 1064
 				 }
@@ -1079,34 +1079,34 @@  discard block
 block discarded – undo
1079 1079
 	  * @param $data1
1080 1080
 	  * @return string
1081 1081
 	  */
1082
-	 private function find_serialize_error( $data1 ) {
1082
+	 private function find_serialize_error($data1) {
1083 1083
 		$error = "<pre>";
1084 1084
 		 $data2 = preg_replace_callback(
1085 1085
 			 '!s:(\d+):"(.*?)";!',
1086
-			 function ( $match ) {
1087
-				 return ( $match[1] === strlen( $match[2] ) )
1086
+			 function($match) {
1087
+				 return ($match[1] === strlen($match[2]))
1088 1088
 					 ? $match[0]
1089 1089
 					 : 's:'
1090
-					   . strlen( $match[2] )
1090
+					   . strlen($match[2])
1091 1091
 					   . ':"'
1092 1092
 					   . $match[2]
1093 1093
 					   . '";';
1094 1094
 			 },
1095 1095
 			 $data1
1096 1096
 		 );
1097
-		$max = ( strlen( $data1 ) > strlen( $data2 ) ) ? strlen( $data1 ) : strlen( $data2 );
1098
-		$error .= $data1 . PHP_EOL;
1099
-		$error .= $data2 . PHP_EOL;
1100
-		for ( $i = 0; $i < $max; $i++ ) {
1101
-			if ( @$data1[ $i ] !== @$data2[ $i ] ) {
1102
-				$error .= "Difference " . @$data1[ $i ] . " != " . @$data2[ $i ] . PHP_EOL;
1103
-				$error .= "\t-> ORD number " . ord( @$data1[ $i ] ) . " != " . ord( @$data2[ $i ] ) . PHP_EOL;
1104
-				$error .= "\t-> Line Number = $i" . PHP_EOL;
1105
-				$start = ( $i - 20 );
1106
-				$start = ( $start < 0 ) ? 0 : $start;
1097
+		$max = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1098
+		$error .= $data1.PHP_EOL;
1099
+		$error .= $data2.PHP_EOL;
1100
+		for ($i = 0; $i < $max; $i++) {
1101
+			if (@$data1[$i] !== @$data2[$i]) {
1102
+				$error .= "Difference ".@$data1[$i]." != ".@$data2[$i].PHP_EOL;
1103
+				$error .= "\t-> ORD number ".ord(@$data1[$i])." != ".ord(@$data2[$i]).PHP_EOL;
1104
+				$error .= "\t-> Line Number = $i".PHP_EOL;
1105
+				$start = ($i - 20);
1106
+				$start = ($start < 0) ? 0 : $start;
1107 1107
 				$length = 40;
1108 1108
 				$point = $max - $i;
1109
-				if ( $point < 20 ) {
1109
+				if ($point < 20) {
1110 1110
 					$rlength = 1;
1111 1111
 					$rpoint = -$point;
1112 1112
 				} else {
@@ -1115,16 +1115,16 @@  discard block
 block discarded – undo
1115 1115
 				}
1116 1116
 				$error .= "\t-> Section Data1  = ";
1117 1117
 				$error .= substr_replace(
1118
-					substr( $data1, $start, $length ),
1119
-					"<b style=\"color:green\">{$data1[ $i ]}</b>",
1118
+					substr($data1, $start, $length),
1119
+					"<b style=\"color:green\">{$data1[$i]}</b>",
1120 1120
 					$rpoint,
1121 1121
 					$rlength
1122 1122
 				);
1123 1123
 				$error .= PHP_EOL;
1124 1124
 				$error .= "\t-> Section Data2  = ";
1125 1125
 				$error .= substr_replace(
1126
-					substr( $data2, $start, $length ),
1127
-					"<b style=\"color:red\">{$data2[ $i ]}</b>",
1126
+					substr($data2, $start, $length),
1127
+					"<b style=\"color:red\">{$data2[$i]}</b>",
1128 1128
 					$rpoint,
1129 1129
 					$rlength
1130 1130
 				);
Please login to merge, or discard this patch.
core/EE_Payment_Processor.core.php 1 patch
Indentation   +734 added lines, -734 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 EE_Registry::instance()->load_class('Processor_Base');
5 5
 
@@ -16,737 +16,737 @@  discard block
 block discarded – undo
16 16
 class EE_Payment_Processor extends EE_Processor_Base
17 17
 {
18 18
 
19
-    /**
20
-     * @var EE_Payment_Processor $_instance
21
-     * @access    private
22
-     */
23
-    private static $_instance;
24
-
25
-
26
-
27
-    /**
28
-     * @singleton method used to instantiate class object
29
-     * @access    public
30
-     * @return EE_Payment_Processor instance
31
-     */
32
-    public static function instance()
33
-    {
34
-        // check if class object is instantiated
35
-        if ( ! self::$_instance instanceof EE_Payment_Processor) {
36
-            self::$_instance = new self();
37
-        }
38
-        return self::$_instance;
39
-    }
40
-
41
-
42
-
43
-    /**
44
-     *private constructor to prevent direct creation
45
-     *
46
-     * @Constructor
47
-     * @access private
48
-     */
49
-    private function __construct()
50
-    {
51
-        do_action('AHEE__EE_Payment_Processor__construct');
52
-        add_action('http_api_curl', array($this, '_curl_requests_to_paypal_use_tls'), 10, 3);
53
-    }
54
-
55
-
56
-
57
-    /**
58
-     * Using the selected gateway, processes the payment for that transaction, and updates the transaction
59
-     * appropriately. Saves the payment that is generated
60
-     *
61
-     * @param EE_Payment_Method    $payment_method
62
-     * @param EE_Transaction       $transaction
63
-     * @param float                $amount       if only part of the transaction is to be paid for, how much.
64
-     *                                           Leave null if payment is for the full amount owing
65
-     * @param EE_Billing_Info_Form $billing_form (or probably null, if it's an offline or offsite payment method).
66
-     *                                           Receive_form_submission() should have
67
-     *                                           already been called on the billing form
68
-     *                                           (ie, its inputs should have their normalized values set).
69
-     * @param string               $return_url   string used mostly by offsite gateways to specify
70
-     *                                           where to go AFTER the offsite gateway
71
-     * @param string               $method       like 'CART', indicates who the client who called this was
72
-     * @param bool                 $by_admin     TRUE if payment is being attempted from the admin
73
-     * @param boolean              $update_txn   whether or not to call
74
-     *                                           EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
75
-     * @param string               $cancel_url   URL to return to if off-site payments are cancelled
76
-     * @return \EE_Payment
77
-     * @throws \EE_Error
78
-     */
79
-    public function process_payment(
80
-        EE_Payment_Method $payment_method,
81
-        EE_Transaction $transaction,
82
-        $amount = null,
83
-        $billing_form = null,
84
-        $return_url = null,
85
-        $method = 'CART',
86
-        $by_admin = false,
87
-        $update_txn = true,
88
-        $cancel_url = ''
89
-    ) {
90
-        if ((float)$amount < 0) {
91
-            throw new EE_Error(
92
-                sprintf(
93
-                    __(
94
-                        'Attempting to make a payment for a negative amount of %1$d for transaction %2$d. That should be a refund',
95
-                        'event_espresso'
96
-                    ),
97
-                    $amount,
98
-                    $transaction->ID()
99
-                )
100
-            );
101
-        }
102
-        // verify payment method
103
-        $payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
104
-        // verify transaction
105
-        EEM_Transaction::instance()->ensure_is_obj($transaction);
106
-        $transaction->set_payment_method_ID($payment_method->ID());
107
-        // verify payment method type
108
-        if ($payment_method->type_obj() instanceof EE_PMT_Base) {
109
-            $payment = $payment_method->type_obj()->process_payment(
110
-                $transaction,
111
-                min($amount, $transaction->remaining()),//make sure we don't overcharge
112
-                $billing_form,
113
-                $return_url,
114
-                add_query_arg(array('ee_cancel_payment' => true), $cancel_url),
115
-                $method,
116
-                $by_admin
117
-            );
118
-            // check if payment method uses an off-site gateway
119
-            if ($payment_method->type_obj()->payment_occurs() !== EE_PMT_Base::offsite) {
120
-                // don't process payments for off-site gateways yet because no payment has occurred yet
121
-                $this->update_txn_based_on_payment($transaction, $payment, $update_txn);
122
-            }
123
-            return $payment;
124
-        } else {
125
-            EE_Error::add_error(
126
-                sprintf(
127
-                    __('A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.', 'event_espresso'),
128
-                    '<br/>',
129
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
130
-                ), __FILE__, __FUNCTION__, __LINE__
131
-            );
132
-            return null;
133
-        }
134
-    }
135
-
136
-
137
-
138
-    /**
139
-     * @param EE_Transaction|int $transaction
140
-     * @param EE_Payment_Method  $payment_method
141
-     * @throws EE_Error
142
-     * @return string
143
-     */
144
-    public function get_ipn_url_for_payment_method($transaction, $payment_method)
145
-    {
146
-        /** @type \EE_Transaction $transaction */
147
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
148
-        $primary_reg = $transaction->primary_registration();
149
-        if ( ! $primary_reg instanceof EE_Registration) {
150
-            throw new EE_Error(
151
-                sprintf(
152
-                    __(
153
-                        "Cannot get IPN URL for transaction with ID %d because it has no primary registration",
154
-                        "event_espresso"
155
-                    ),
156
-                    $transaction->ID()
157
-                )
158
-            );
159
-        }
160
-        $payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
161
-        $url = add_query_arg(
162
-            array(
163
-                'e_reg_url_link'    => $primary_reg->reg_url_link(),
164
-                'ee_payment_method' => $payment_method->slug(),
165
-            ),
166
-            EE_Registry::instance()->CFG->core->txn_page_url()
167
-        );
168
-        return $url;
169
-    }
170
-
171
-
172
-
173
-    /**
174
-     * Process the IPN. Firstly, we'll hope we put the standard args into the IPN URL so
175
-     * we can easily find what registration the IPN is for and what payment method.
176
-     * However, if not, we'll give all payment methods a chance to claim it and process it.
177
-     * If a payment is found for the IPN info, it is saved.
178
-     *
179
-     * @param array              $_req_data            eg $_REQUEST
180
-     * @param EE_Transaction|int $transaction          optional (or a transactions id)
181
-     * @param EE_Payment_Method  $payment_method       (or a slug or id of one)
182
-     * @param boolean            $update_txn           whether or not to call
183
-     *                                                 EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
184
-     * @param bool               $separate_IPN_request whether the IPN uses a separate request ( true like PayPal )
185
-     *                                                 or is processed manually ( false like Mijireh )
186
-     * @throws EE_Error
187
-     * @throws Exception
188
-     * @return EE_Payment
189
-     */
190
-    public function process_ipn(
191
-        $_req_data,
192
-        $transaction = null,
193
-        $payment_method = null,
194
-        $update_txn = true,
195
-        $separate_IPN_request = true
196
-    ) {
197
-        EE_Registry::instance()->load_model('Change_Log');
198
-        $_req_data = $this->_remove_unusable_characters_from_array((array)$_req_data);
199
-        EE_Processor_Base::set_IPN($separate_IPN_request);
200
-        $obj_for_log = null;
201
-        if ($transaction instanceof EE_Transaction) {
202
-            $obj_for_log = $transaction;
203
-            if ($payment_method instanceof EE_Payment_Method) {
204
-                $obj_for_log = EEM_Payment::instance()->get_one(
205
-                    array(
206
-                        array('TXN_ID' => $transaction->ID(), 'PMD_ID' => $payment_method->ID()),
207
-                        'order_by' => array('PAY_timestamp' => 'desc'),
208
-                    )
209
-                );
210
-            }
211
-        } else if ($payment_method instanceof EE_Payment) {
212
-            $obj_for_log = $payment_method;
213
-        }
214
-        $log = EEM_Change_Log::instance()->log(
215
-            EEM_Change_Log::type_gateway,
216
-            array('IPN data received' => $_req_data),
217
-            $obj_for_log
218
-        );
219
-        try {
220
-            /**
221
-             * @var EE_Payment $payment
222
-             */
223
-            $payment = null;
224
-            if ($transaction && $payment_method) {
225
-                /** @type EE_Transaction $transaction */
226
-                $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
227
-                /** @type EE_Payment_Method $payment_method */
228
-                $payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method);
229
-                if ($payment_method->type_obj() instanceof EE_PMT_Base) {
230
-                    try {
231
-                        $payment = $payment_method->type_obj()->handle_ipn($_req_data, $transaction);
232
-                        $log->set_object($payment);
233
-                    } catch (EventEspresso\core\exceptions\IpnException $e) {
234
-                        EEM_Change_Log::instance()->log(
235
-                            EEM_Change_Log::type_gateway,
236
-                            array(
237
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
238
-                                'current_url' => EEH_URL::current_url(),
239
-                                'payment'     => $e->getPaymentProperties(),
240
-                                'IPN_data'    => $e->getIpnData(),
241
-                            ),
242
-                            $obj_for_log
243
-                        );
244
-                        return $e->getPayment();
245
-                    }
246
-                } else {
247
-                    // not a payment
248
-                    EE_Error::add_error(
249
-                        sprintf(
250
-                            __('A valid payment method could not be determined due to a technical issue.%sPlease refresh your browser and try again or contact %s for assistance.', 'event_espresso'),
251
-                            '<br/>',
252
-                            EE_Registry::instance()->CFG->organization->get_pretty('email')
253
-                        ),
254
-                        __FILE__, __FUNCTION__, __LINE__
255
-                    );
256
-                }
257
-            } else {
258
-                //that's actually pretty ok. The IPN just wasn't able
259
-                //to identify which transaction or payment method this was for
260
-                // give all active payment methods a chance to claim it
261
-                $active_payment_methods = EEM_Payment_Method::instance()->get_all_active();
262
-                foreach ($active_payment_methods as $active_payment_method) {
263
-                    try {
264
-                        $payment = $active_payment_method->type_obj()->handle_unclaimed_ipn($_req_data);
265
-                        $payment_method = $active_payment_method;
266
-                        EEM_Change_Log::instance()->log(
267
-                            EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment
268
-                        );
269
-                        break;
270
-                    } catch (EventEspresso\core\exceptions\IpnException $e) {
271
-                        EEM_Change_Log::instance()->log(
272
-                            EEM_Change_Log::type_gateway,
273
-                            array(
274
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
275
-                                'current_url' => EEH_URL::current_url(),
276
-                                'payment'     => $e->getPaymentProperties(),
277
-                                'IPN_data'    => $e->getIpnData(),
278
-                            ),
279
-                            $obj_for_log
280
-                        );
281
-                        return $e->getPayment();
282
-                    } catch (EE_Error $e) {
283
-                        //that's fine- it apparently couldn't handle the IPN
284
-                    }
285
-                }
286
-            }
287
-            // 			EEM_Payment_Log::instance()->log("got to 7",$transaction,$payment_method);
288
-            if ($payment instanceof EE_Payment) {
289
-                $payment->save();
290
-                //  update the TXN
291
-                $this->update_txn_based_on_payment($transaction, $payment, $update_txn, $separate_IPN_request);
292
-            } else {
293
-                //we couldn't find the payment for this IPN... let's try and log at least SOMETHING
294
-                if ($payment_method) {
295
-                    EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment_method);
296
-                } elseif ($transaction) {
297
-                    EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $transaction);
298
-                }
299
-            }
300
-            return $payment;
301
-        } catch (EE_Error $e) {
302
-            do_action(
303
-                'AHEE__log', __FILE__, __FUNCTION__, sprintf(
304
-                    __('Error occurred while receiving IPN. Transaction: %1$s, req data: %2$s. The error was "%3$s"', 'event_espresso'),
305
-                    print_r($transaction, true),
306
-                    print_r($_req_data, true),
307
-                    $e->getMessage()
308
-                )
309
-            );
310
-            throw $e;
311
-        }
312
-    }
313
-
314
-
315
-
316
-    /**
317
-     * Removes any non-printable illegal characters from the input,
318
-     * which might cause a raucous when trying to insert into the database
319
-     *
320
-     * @param  array $request_data
321
-     * @return array
322
-     */
323
-    protected function _remove_unusable_characters_from_array(array $request_data)
324
-    {
325
-        $return_data = array();
326
-        foreach ($request_data as $key => $value) {
327
-            $return_data[$this->_remove_unusable_characters($key)] = $this->_remove_unusable_characters($value);
328
-        }
329
-        return $return_data;
330
-    }
331
-
332
-
333
-
334
-    /**
335
-     * Removes any non-printable illegal characters from the input,
336
-     * which might cause a raucous when trying to insert into the database
337
-     *
338
-     * @param string $request_data
339
-     * @return string
340
-     */
341
-    protected function _remove_unusable_characters($request_data)
342
-    {
343
-        return preg_replace('/[^[:print:]]/', '', $request_data);
344
-    }
345
-
346
-
347
-
348
-    /**
349
-     * Should be called just before displaying the payment attempt results to the user,
350
-     * when the payment attempt has finished. Some payment methods may have special
351
-     * logic to perform here. For example, if process_payment() happens on a special request
352
-     * and then the user is redirected to a page that displays the payment's status, this
353
-     * should be called while loading the page that displays the payment's status. If the user is
354
-     * sent to an offsite payment provider, this should be called upon returning from that offsite payment
355
-     * provider.
356
-     *
357
-     * @param EE_Transaction|int $transaction
358
-     * @param bool               $update_txn whether or not to call
359
-     *                                       EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
360
-     * @throws \EE_Error
361
-     * @return EE_Payment
362
-     * @deprecated 4.6.24 method is no longer used. Instead it is up to client code, like SPCO,
363
-     *                                       to call handle_ipn() for offsite gateways that don't receive separate IPNs
364
-     */
365
-    public function finalize_payment_for($transaction, $update_txn = true)
366
-    {
367
-        /** @var $transaction EE_Transaction */
368
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
369
-        $last_payment_method = $transaction->payment_method();
370
-        if ($last_payment_method instanceof EE_Payment_Method) {
371
-            $payment = $last_payment_method->type_obj()->finalize_payment_for($transaction);
372
-            $this->update_txn_based_on_payment($transaction, $payment, $update_txn);
373
-            return $payment;
374
-        } else {
375
-            return null;
376
-        }
377
-    }
378
-
379
-
380
-
381
-    /**
382
-     * Processes a direct refund request, saves the payment, and updates the transaction appropriately.
383
-     *
384
-     * @param EE_Payment_Method $payment_method
385
-     * @param EE_Payment        $payment_to_refund
386
-     * @param array             $refund_info
387
-     * @return EE_Payment
388
-     * @throws \EE_Error
389
-     */
390
-    public function process_refund(
391
-        EE_Payment_Method $payment_method,
392
-        EE_Payment $payment_to_refund,
393
-        $refund_info = array()
394
-    ) {
395
-        if ($payment_method instanceof EE_Payment_Method && $payment_method->type_obj()->supports_sending_refunds()) {
396
-            $payment_method->type_obj()->process_refund($payment_to_refund, $refund_info);
397
-            $this->update_txn_based_on_payment($payment_to_refund->transaction(), $payment_to_refund);
398
-        }
399
-        return $payment_to_refund;
400
-    }
401
-
402
-
403
-
404
-    /**
405
-     * This should be called each time there may have been an update to a
406
-     * payment on a transaction (ie, we asked for a payment to process a
407
-     * payment for a transaction, or we told a payment method about an IPN, or
408
-     * we told a payment method to
409
-     * "finalize_payment_for" (a transaction), or we told a payment method to
410
-     * process a refund. This should handle firing the correct hooks to
411
-     * indicate
412
-     * what exactly happened and updating the transaction appropriately). This
413
-     * could be integrated directly into EE_Transaction upon save, but we want
414
-     * this logic to be separate from 'normal' plain-jane saving and updating
415
-     * of transactions and payments, and to be tied to payment processing.
416
-     * Note: this method DOES NOT save the payment passed into it. It is the responsibility
417
-     * of previous code to decide whether or not to save (because the payment passed into
418
-     * this method might be a temporary, never-to-be-saved payment from an offline gateway,
419
-     * in which case we only want that payment object for some temporary usage during this request,
420
-     * but we don't want it to be saved).
421
-     *
422
-     * @param EE_Transaction|int $transaction
423
-     * @param EE_Payment         $payment
424
-     * @param boolean            $update_txn
425
-     *                        whether or not to call
426
-     *                        EE_Transaction_Processor::
427
-     *                        update_transaction_and_registrations_after_checkout_or_payment()
428
-     *                        (you can save 1 DB query if you know you're going
429
-     *                        to save it later instead)
430
-     * @param bool               $IPN
431
-     *                        if processing IPNs or other similar payment
432
-     *                        related activities that occur in alternate
433
-     *                        requests than the main one that is processing the
434
-     *                        TXN, then set this to true to check whether the
435
-     *                        TXN is locked before updating
436
-     * @throws \EE_Error
437
-     */
438
-    public function update_txn_based_on_payment($transaction, $payment, $update_txn = true, $IPN = false)
439
-    {
440
-        $do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__not_successful';
441
-        /** @type EE_Transaction $transaction */
442
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
443
-        // can we freely update the TXN at this moment?
444
-        if ($IPN && $transaction->is_locked()) {
445
-            // don't update the transaction at this exact moment
446
-            // because the TXN is active in another request
447
-            EE_Cron_Tasks::schedule_update_transaction_with_payment(
448
-                time(),
449
-                $transaction->ID(),
450
-                $payment->ID()
451
-            );
452
-        } else {
453
-            // verify payment and that it has been saved
454
-            if ($payment instanceof EE_Payment && $payment->ID()) {
455
-                if (
456
-                    $payment->payment_method() instanceof EE_Payment_Method
457
-                    && $payment->payment_method()->type_obj() instanceof EE_PMT_Base
458
-                ) {
459
-                    $payment->payment_method()->type_obj()->update_txn_based_on_payment($payment);
460
-                    // update TXN registrations with payment info
461
-                    $this->process_registration_payments($transaction, $payment);
462
-                }
463
-                $do_action = $payment->just_approved()
464
-                    ? 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful'
465
-                    : $do_action;
466
-            } else {
467
-                // send out notifications
468
-                add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
469
-                $do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__no_payment_made';
470
-            }
471
-            if ($payment->status() !== EEM_Payment::status_id_failed) {
472
-                /** @type EE_Transaction_Payments $transaction_payments */
473
-                $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
474
-                // set new value for total paid
475
-                $transaction_payments->calculate_total_payments_and_update_status($transaction);
476
-                // call EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment() ???
477
-                if ($update_txn) {
478
-                    $this->_post_payment_processing($transaction, $payment, $IPN);
479
-                }
480
-            }
481
-            // granular hook for others to use.
482
-            do_action($do_action, $transaction, $payment);
483
-            do_action('AHEE_log', __CLASS__, __FUNCTION__, $do_action, '$do_action');
484
-            //global hook for others to use.
485
-            do_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', $transaction, $payment);
486
-        }
487
-    }
488
-
489
-
490
-
491
-    /**
492
-     * update registrations REG_paid field after successful payment and link registrations with payment
493
-     *
494
-     * @param EE_Transaction    $transaction
495
-     * @param EE_Payment        $payment
496
-     * @param EE_Registration[] $registrations
497
-     * @throws \EE_Error
498
-     */
499
-    public function process_registration_payments(
500
-        EE_Transaction $transaction,
501
-        EE_Payment $payment,
502
-        $registrations = array()
503
-    ) {
504
-        // only process if payment was successful
505
-        if ($payment->status() !== EEM_Payment::status_id_approved) {
506
-            return;
507
-        }
508
-        //EEM_Registration::instance()->show_next_x_db_queries();
509
-        if (empty($registrations)) {
510
-            // find registrations with monies owing that can receive a payment
511
-            $registrations = $transaction->registrations(
512
-                array(
513
-                    array(
514
-                        // only these reg statuses can receive payments
515
-                        'STS_ID'           => array('IN', EEM_Registration::reg_statuses_that_allow_payment()),
516
-                        'REG_final_price'  => array('!=', 0),
517
-                        'REG_final_price*' => array('!=', 'REG_paid', true),
518
-                    ),
519
-                )
520
-            );
521
-        }
522
-        // still nothing ??!??
523
-        if (empty($registrations)) {
524
-            return;
525
-        }
526
-        // todo: break out the following logic into a separate strategy class
527
-        // todo: named something like "Sequential_Reg_Payment_Strategy"
528
-        // todo: which would apply payments using the capitalist "first come first paid" approach
529
-        // todo: then have another strategy class like "Distributed_Reg_Payment_Strategy"
530
-        // todo: which would be the socialist "everybody gets a piece of pie" approach,
531
-        // todo: which would be better for deposits, where you want a bit of the payment applied to each registration
532
-        $refund = $payment->is_a_refund();
533
-        // how much is available to apply to registrations?
534
-        $available_payment_amount = abs($payment->amount());
535
-        foreach ($registrations as $registration) {
536
-            if ($registration instanceof EE_Registration) {
537
-                // nothing left?
538
-                if ($available_payment_amount <= 0) {
539
-                    break;
540
-                }
541
-                if ($refund) {
542
-                    $available_payment_amount = $this->process_registration_refund($registration, $payment, $available_payment_amount);
543
-                } else {
544
-                    $available_payment_amount = $this->process_registration_payment($registration, $payment, $available_payment_amount);
545
-                }
546
-            }
547
-        }
548
-        if ($available_payment_amount > 0 && apply_filters('FHEE__EE_Payment_Processor__process_registration_payments__display_notifications', false)) {
549
-            EE_Error::add_attention(
550
-                sprintf(
551
-                    __('A remainder of %1$s exists after applying this payment to Registration(s) %2$s.%3$sPlease verify that the original payment amount of %4$s is correct. If so, you should edit this payment and select at least one additional registration in the "Registrations to Apply Payment to" section, so that the remainder of this payment can be applied to the additional registration(s).',
552
-                        'event_espresso'),
553
-                    EEH_Template::format_currency($available_payment_amount),
554
-                    implode(', ', array_keys($registrations)),
555
-                    '<br/>',
556
-                    EEH_Template::format_currency($payment->amount())
557
-                ),
558
-                __FILE__, __FUNCTION__, __LINE__
559
-            );
560
-        }
561
-    }
562
-
563
-
564
-
565
-    /**
566
-     * update registration REG_paid field after successful payment and link registration with payment
567
-     *
568
-     * @param EE_Registration $registration
569
-     * @param EE_Payment      $payment
570
-     * @param float           $available_payment_amount
571
-     * @return float
572
-     * @throws \EE_Error
573
-     */
574
-    public function process_registration_payment(
575
-        EE_Registration $registration,
576
-        EE_Payment $payment,
577
-        $available_payment_amount = 0.00
578
-    ) {
579
-        $owing = $registration->final_price() - $registration->paid();
580
-        if ($owing > 0) {
581
-            // don't allow payment amount to exceed the available payment amount, OR the amount owing
582
-            $payment_amount = min($available_payment_amount, $owing);
583
-            // update $available_payment_amount
584
-            $available_payment_amount -= $payment_amount;
585
-            //calculate and set new REG_paid
586
-            $registration->set_paid($registration->paid() + $payment_amount);
587
-            // now save it
588
-            $this->_apply_registration_payment($registration, $payment, $payment_amount);
589
-        }
590
-        return $available_payment_amount;
591
-    }
592
-
593
-
594
-
595
-    /**
596
-     * update registration REG_paid field after successful payment and link registration with payment
597
-     *
598
-     * @param EE_Registration $registration
599
-     * @param EE_Payment      $payment
600
-     * @param float           $payment_amount
601
-     * @return void
602
-     * @throws \EE_Error
603
-     */
604
-    protected function _apply_registration_payment(
605
-        EE_Registration $registration,
606
-        EE_Payment $payment,
607
-        $payment_amount = 0.00
608
-    ) {
609
-        // find any existing reg payment records for this registration and payment
610
-        $existing_reg_payment = EEM_Registration_Payment::instance()->get_one(
611
-            array(array('REG_ID' => $registration->ID(), 'PAY_ID' => $payment->ID()))
612
-        );
613
-        // if existing registration payment exists
614
-        if ($existing_reg_payment instanceof EE_Registration_Payment) {
615
-            // then update that record
616
-            $existing_reg_payment->set_amount($payment_amount);
617
-            $existing_reg_payment->save();
618
-        } else {
619
-            // or add new relation between registration and payment and set amount
620
-            $registration->_add_relation_to($payment, 'Payment', array('RPY_amount' => $payment_amount));
621
-            // make it stick
622
-            $registration->save();
623
-        }
624
-    }
625
-
626
-
627
-
628
-    /**
629
-     * update registration REG_paid field after refund and link registration with payment
630
-     *
631
-     * @param EE_Registration $registration
632
-     * @param EE_Payment      $payment
633
-     * @param float           $available_refund_amount - IMPORTANT !!! SEND AVAILABLE REFUND AMOUNT AS A POSITIVE NUMBER
634
-     * @return float
635
-     * @throws \EE_Error
636
-     */
637
-    public function process_registration_refund(
638
-        EE_Registration $registration,
639
-        EE_Payment $payment,
640
-        $available_refund_amount = 0.00
641
-    ) {
642
-        //EEH_Debug_Tools::printr( $payment->amount(), '$payment->amount()', __FILE__, __LINE__ );
643
-        if ($registration->paid() > 0) {
644
-            // ensure $available_refund_amount is NOT negative
645
-            $available_refund_amount = (float)abs($available_refund_amount);
646
-            // don't allow refund amount to exceed the available payment amount, OR the amount paid
647
-            $refund_amount = min($available_refund_amount, (float)$registration->paid());
648
-            // update $available_payment_amount
649
-            $available_refund_amount -= $refund_amount;
650
-            //calculate and set new REG_paid
651
-            $registration->set_paid($registration->paid() - $refund_amount);
652
-            // convert payment amount back to a negative value for storage in the db
653
-            $refund_amount = (float)abs($refund_amount) * -1;
654
-            // now save it
655
-            $this->_apply_registration_payment($registration, $payment, $refund_amount);
656
-        }
657
-        return $available_refund_amount;
658
-    }
659
-
660
-
661
-
662
-    /**
663
-     * Process payments and transaction after payment process completed.
664
-     * ultimately this will send the TXN and payment details off so that notifications can be sent out.
665
-     * if this request happens to be processing an IPN,
666
-     * then we will also set the Payment Options Reg Step to completed,
667
-     * and attempt to completely finalize the TXN if all of the other Reg Steps are completed as well.
668
-     *
669
-     * @param EE_Transaction $transaction
670
-     * @param EE_Payment     $payment
671
-     * @param bool           $IPN
672
-     * @throws \EE_Error
673
-     */
674
-    protected function _post_payment_processing(EE_Transaction $transaction, EE_Payment $payment, $IPN = false)
675
-    {
676
-        /** @type EE_Transaction_Processor $transaction_processor */
677
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
678
-        // is the Payment Options Reg Step completed ?
679
-        $payment_options_step_completed = $transaction->reg_step_completed('payment_options');
680
-        // if the Payment Options Reg Step is completed...
681
-        $revisit = $payment_options_step_completed === true ? true : false;
682
-        // then this is kinda sorta a revisit with regards to payments at least
683
-        $transaction_processor->set_revisit($revisit);
684
-        // if this is an IPN, let's consider the Payment Options Reg Step completed if not already
685
-        if (
686
-            $IPN
687
-            && $payment_options_step_completed !== true
688
-            && ($payment->is_approved() || $payment->is_pending())
689
-        ) {
690
-            $payment_options_step_completed = $transaction->set_reg_step_completed(
691
-                'payment_options'
692
-            );
693
-        }
694
-        // maybe update status, but don't save transaction just yet
695
-        $transaction->update_status_based_on_total_paid(false);
696
-        // check if 'finalize_registration' step has been completed...
697
-        $finalized = $transaction->reg_step_completed('finalize_registration');
698
-        //  if this is an IPN and the final step has not been initiated
699
-        if ($IPN && $payment_options_step_completed && $finalized === false) {
700
-            // and if it hasn't already been set as being started...
701
-            $finalized = $transaction->set_reg_step_initiated('finalize_registration');
702
-        }
703
-        $transaction->save();
704
-        // because the above will return false if the final step was not fully completed, we need to check again...
705
-        if ($IPN && $finalized !== false) {
706
-            // and if we are all good to go, then send out notifications
707
-            add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
708
-            //ok, now process the transaction according to the payment
709
-            $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment($transaction, $payment);
710
-        }
711
-        // DEBUG LOG
712
-        $payment_method = $payment->payment_method();
713
-        if ($payment_method instanceof EE_Payment_Method) {
714
-            $payment_method_type_obj = $payment_method->type_obj();
715
-            if ($payment_method_type_obj instanceof EE_PMT_Base) {
716
-                $gateway = $payment_method_type_obj->get_gateway();
717
-                if ($gateway instanceof EE_Gateway) {
718
-                    $gateway->log(
719
-                        array(
720
-                            'message'               => __('Post Payment Transaction Details', 'event_espresso'),
721
-                            'transaction'           => $transaction->model_field_array(),
722
-                            'finalized'             => $finalized,
723
-                            'IPN'                   => $IPN,
724
-                            'deliver_notifications' => has_filter(
725
-                                'FHEE__EED_Messages___maybe_registration__deliver_notifications'
726
-                            ),
727
-                        ),
728
-                        $payment
729
-                    );
730
-                }
731
-            }
732
-        }
733
-    }
734
-
735
-
736
-
737
-    /**
738
-     * Force posts to PayPal to use TLS v1.2. See:
739
-     * https://core.trac.wordpress.org/ticket/36320
740
-     * https://core.trac.wordpress.org/ticket/34924#comment:15
741
-     * https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US
742
-     * This will affect paypal standard, pro, express, and payflow.
743
-     */
744
-    public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
745
-    {
746
-        if (strstr($url, 'https://') && strstr($url, '.paypal.com')) {
747
-            //Use the value of the constant CURL_SSLVERSION_TLSv1 = 1
748
-            //instead of the constant because it might not be defined
749
-            curl_setopt($handle, CURLOPT_SSLVERSION, 1);
750
-        }
751
-    }
19
+	/**
20
+	 * @var EE_Payment_Processor $_instance
21
+	 * @access    private
22
+	 */
23
+	private static $_instance;
24
+
25
+
26
+
27
+	/**
28
+	 * @singleton method used to instantiate class object
29
+	 * @access    public
30
+	 * @return EE_Payment_Processor instance
31
+	 */
32
+	public static function instance()
33
+	{
34
+		// check if class object is instantiated
35
+		if ( ! self::$_instance instanceof EE_Payment_Processor) {
36
+			self::$_instance = new self();
37
+		}
38
+		return self::$_instance;
39
+	}
40
+
41
+
42
+
43
+	/**
44
+	 *private constructor to prevent direct creation
45
+	 *
46
+	 * @Constructor
47
+	 * @access private
48
+	 */
49
+	private function __construct()
50
+	{
51
+		do_action('AHEE__EE_Payment_Processor__construct');
52
+		add_action('http_api_curl', array($this, '_curl_requests_to_paypal_use_tls'), 10, 3);
53
+	}
54
+
55
+
56
+
57
+	/**
58
+	 * Using the selected gateway, processes the payment for that transaction, and updates the transaction
59
+	 * appropriately. Saves the payment that is generated
60
+	 *
61
+	 * @param EE_Payment_Method    $payment_method
62
+	 * @param EE_Transaction       $transaction
63
+	 * @param float                $amount       if only part of the transaction is to be paid for, how much.
64
+	 *                                           Leave null if payment is for the full amount owing
65
+	 * @param EE_Billing_Info_Form $billing_form (or probably null, if it's an offline or offsite payment method).
66
+	 *                                           Receive_form_submission() should have
67
+	 *                                           already been called on the billing form
68
+	 *                                           (ie, its inputs should have their normalized values set).
69
+	 * @param string               $return_url   string used mostly by offsite gateways to specify
70
+	 *                                           where to go AFTER the offsite gateway
71
+	 * @param string               $method       like 'CART', indicates who the client who called this was
72
+	 * @param bool                 $by_admin     TRUE if payment is being attempted from the admin
73
+	 * @param boolean              $update_txn   whether or not to call
74
+	 *                                           EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
75
+	 * @param string               $cancel_url   URL to return to if off-site payments are cancelled
76
+	 * @return \EE_Payment
77
+	 * @throws \EE_Error
78
+	 */
79
+	public function process_payment(
80
+		EE_Payment_Method $payment_method,
81
+		EE_Transaction $transaction,
82
+		$amount = null,
83
+		$billing_form = null,
84
+		$return_url = null,
85
+		$method = 'CART',
86
+		$by_admin = false,
87
+		$update_txn = true,
88
+		$cancel_url = ''
89
+	) {
90
+		if ((float)$amount < 0) {
91
+			throw new EE_Error(
92
+				sprintf(
93
+					__(
94
+						'Attempting to make a payment for a negative amount of %1$d for transaction %2$d. That should be a refund',
95
+						'event_espresso'
96
+					),
97
+					$amount,
98
+					$transaction->ID()
99
+				)
100
+			);
101
+		}
102
+		// verify payment method
103
+		$payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
104
+		// verify transaction
105
+		EEM_Transaction::instance()->ensure_is_obj($transaction);
106
+		$transaction->set_payment_method_ID($payment_method->ID());
107
+		// verify payment method type
108
+		if ($payment_method->type_obj() instanceof EE_PMT_Base) {
109
+			$payment = $payment_method->type_obj()->process_payment(
110
+				$transaction,
111
+				min($amount, $transaction->remaining()),//make sure we don't overcharge
112
+				$billing_form,
113
+				$return_url,
114
+				add_query_arg(array('ee_cancel_payment' => true), $cancel_url),
115
+				$method,
116
+				$by_admin
117
+			);
118
+			// check if payment method uses an off-site gateway
119
+			if ($payment_method->type_obj()->payment_occurs() !== EE_PMT_Base::offsite) {
120
+				// don't process payments for off-site gateways yet because no payment has occurred yet
121
+				$this->update_txn_based_on_payment($transaction, $payment, $update_txn);
122
+			}
123
+			return $payment;
124
+		} else {
125
+			EE_Error::add_error(
126
+				sprintf(
127
+					__('A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.', 'event_espresso'),
128
+					'<br/>',
129
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
130
+				), __FILE__, __FUNCTION__, __LINE__
131
+			);
132
+			return null;
133
+		}
134
+	}
135
+
136
+
137
+
138
+	/**
139
+	 * @param EE_Transaction|int $transaction
140
+	 * @param EE_Payment_Method  $payment_method
141
+	 * @throws EE_Error
142
+	 * @return string
143
+	 */
144
+	public function get_ipn_url_for_payment_method($transaction, $payment_method)
145
+	{
146
+		/** @type \EE_Transaction $transaction */
147
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
148
+		$primary_reg = $transaction->primary_registration();
149
+		if ( ! $primary_reg instanceof EE_Registration) {
150
+			throw new EE_Error(
151
+				sprintf(
152
+					__(
153
+						"Cannot get IPN URL for transaction with ID %d because it has no primary registration",
154
+						"event_espresso"
155
+					),
156
+					$transaction->ID()
157
+				)
158
+			);
159
+		}
160
+		$payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
161
+		$url = add_query_arg(
162
+			array(
163
+				'e_reg_url_link'    => $primary_reg->reg_url_link(),
164
+				'ee_payment_method' => $payment_method->slug(),
165
+			),
166
+			EE_Registry::instance()->CFG->core->txn_page_url()
167
+		);
168
+		return $url;
169
+	}
170
+
171
+
172
+
173
+	/**
174
+	 * Process the IPN. Firstly, we'll hope we put the standard args into the IPN URL so
175
+	 * we can easily find what registration the IPN is for and what payment method.
176
+	 * However, if not, we'll give all payment methods a chance to claim it and process it.
177
+	 * If a payment is found for the IPN info, it is saved.
178
+	 *
179
+	 * @param array              $_req_data            eg $_REQUEST
180
+	 * @param EE_Transaction|int $transaction          optional (or a transactions id)
181
+	 * @param EE_Payment_Method  $payment_method       (or a slug or id of one)
182
+	 * @param boolean            $update_txn           whether or not to call
183
+	 *                                                 EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
184
+	 * @param bool               $separate_IPN_request whether the IPN uses a separate request ( true like PayPal )
185
+	 *                                                 or is processed manually ( false like Mijireh )
186
+	 * @throws EE_Error
187
+	 * @throws Exception
188
+	 * @return EE_Payment
189
+	 */
190
+	public function process_ipn(
191
+		$_req_data,
192
+		$transaction = null,
193
+		$payment_method = null,
194
+		$update_txn = true,
195
+		$separate_IPN_request = true
196
+	) {
197
+		EE_Registry::instance()->load_model('Change_Log');
198
+		$_req_data = $this->_remove_unusable_characters_from_array((array)$_req_data);
199
+		EE_Processor_Base::set_IPN($separate_IPN_request);
200
+		$obj_for_log = null;
201
+		if ($transaction instanceof EE_Transaction) {
202
+			$obj_for_log = $transaction;
203
+			if ($payment_method instanceof EE_Payment_Method) {
204
+				$obj_for_log = EEM_Payment::instance()->get_one(
205
+					array(
206
+						array('TXN_ID' => $transaction->ID(), 'PMD_ID' => $payment_method->ID()),
207
+						'order_by' => array('PAY_timestamp' => 'desc'),
208
+					)
209
+				);
210
+			}
211
+		} else if ($payment_method instanceof EE_Payment) {
212
+			$obj_for_log = $payment_method;
213
+		}
214
+		$log = EEM_Change_Log::instance()->log(
215
+			EEM_Change_Log::type_gateway,
216
+			array('IPN data received' => $_req_data),
217
+			$obj_for_log
218
+		);
219
+		try {
220
+			/**
221
+			 * @var EE_Payment $payment
222
+			 */
223
+			$payment = null;
224
+			if ($transaction && $payment_method) {
225
+				/** @type EE_Transaction $transaction */
226
+				$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
227
+				/** @type EE_Payment_Method $payment_method */
228
+				$payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method);
229
+				if ($payment_method->type_obj() instanceof EE_PMT_Base) {
230
+					try {
231
+						$payment = $payment_method->type_obj()->handle_ipn($_req_data, $transaction);
232
+						$log->set_object($payment);
233
+					} catch (EventEspresso\core\exceptions\IpnException $e) {
234
+						EEM_Change_Log::instance()->log(
235
+							EEM_Change_Log::type_gateway,
236
+							array(
237
+								'message'     => 'IPN Exception: ' . $e->getMessage(),
238
+								'current_url' => EEH_URL::current_url(),
239
+								'payment'     => $e->getPaymentProperties(),
240
+								'IPN_data'    => $e->getIpnData(),
241
+							),
242
+							$obj_for_log
243
+						);
244
+						return $e->getPayment();
245
+					}
246
+				} else {
247
+					// not a payment
248
+					EE_Error::add_error(
249
+						sprintf(
250
+							__('A valid payment method could not be determined due to a technical issue.%sPlease refresh your browser and try again or contact %s for assistance.', 'event_espresso'),
251
+							'<br/>',
252
+							EE_Registry::instance()->CFG->organization->get_pretty('email')
253
+						),
254
+						__FILE__, __FUNCTION__, __LINE__
255
+					);
256
+				}
257
+			} else {
258
+				//that's actually pretty ok. The IPN just wasn't able
259
+				//to identify which transaction or payment method this was for
260
+				// give all active payment methods a chance to claim it
261
+				$active_payment_methods = EEM_Payment_Method::instance()->get_all_active();
262
+				foreach ($active_payment_methods as $active_payment_method) {
263
+					try {
264
+						$payment = $active_payment_method->type_obj()->handle_unclaimed_ipn($_req_data);
265
+						$payment_method = $active_payment_method;
266
+						EEM_Change_Log::instance()->log(
267
+							EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment
268
+						);
269
+						break;
270
+					} catch (EventEspresso\core\exceptions\IpnException $e) {
271
+						EEM_Change_Log::instance()->log(
272
+							EEM_Change_Log::type_gateway,
273
+							array(
274
+								'message'     => 'IPN Exception: ' . $e->getMessage(),
275
+								'current_url' => EEH_URL::current_url(),
276
+								'payment'     => $e->getPaymentProperties(),
277
+								'IPN_data'    => $e->getIpnData(),
278
+							),
279
+							$obj_for_log
280
+						);
281
+						return $e->getPayment();
282
+					} catch (EE_Error $e) {
283
+						//that's fine- it apparently couldn't handle the IPN
284
+					}
285
+				}
286
+			}
287
+			// 			EEM_Payment_Log::instance()->log("got to 7",$transaction,$payment_method);
288
+			if ($payment instanceof EE_Payment) {
289
+				$payment->save();
290
+				//  update the TXN
291
+				$this->update_txn_based_on_payment($transaction, $payment, $update_txn, $separate_IPN_request);
292
+			} else {
293
+				//we couldn't find the payment for this IPN... let's try and log at least SOMETHING
294
+				if ($payment_method) {
295
+					EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment_method);
296
+				} elseif ($transaction) {
297
+					EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $transaction);
298
+				}
299
+			}
300
+			return $payment;
301
+		} catch (EE_Error $e) {
302
+			do_action(
303
+				'AHEE__log', __FILE__, __FUNCTION__, sprintf(
304
+					__('Error occurred while receiving IPN. Transaction: %1$s, req data: %2$s. The error was "%3$s"', 'event_espresso'),
305
+					print_r($transaction, true),
306
+					print_r($_req_data, true),
307
+					$e->getMessage()
308
+				)
309
+			);
310
+			throw $e;
311
+		}
312
+	}
313
+
314
+
315
+
316
+	/**
317
+	 * Removes any non-printable illegal characters from the input,
318
+	 * which might cause a raucous when trying to insert into the database
319
+	 *
320
+	 * @param  array $request_data
321
+	 * @return array
322
+	 */
323
+	protected function _remove_unusable_characters_from_array(array $request_data)
324
+	{
325
+		$return_data = array();
326
+		foreach ($request_data as $key => $value) {
327
+			$return_data[$this->_remove_unusable_characters($key)] = $this->_remove_unusable_characters($value);
328
+		}
329
+		return $return_data;
330
+	}
331
+
332
+
333
+
334
+	/**
335
+	 * Removes any non-printable illegal characters from the input,
336
+	 * which might cause a raucous when trying to insert into the database
337
+	 *
338
+	 * @param string $request_data
339
+	 * @return string
340
+	 */
341
+	protected function _remove_unusable_characters($request_data)
342
+	{
343
+		return preg_replace('/[^[:print:]]/', '', $request_data);
344
+	}
345
+
346
+
347
+
348
+	/**
349
+	 * Should be called just before displaying the payment attempt results to the user,
350
+	 * when the payment attempt has finished. Some payment methods may have special
351
+	 * logic to perform here. For example, if process_payment() happens on a special request
352
+	 * and then the user is redirected to a page that displays the payment's status, this
353
+	 * should be called while loading the page that displays the payment's status. If the user is
354
+	 * sent to an offsite payment provider, this should be called upon returning from that offsite payment
355
+	 * provider.
356
+	 *
357
+	 * @param EE_Transaction|int $transaction
358
+	 * @param bool               $update_txn whether or not to call
359
+	 *                                       EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
360
+	 * @throws \EE_Error
361
+	 * @return EE_Payment
362
+	 * @deprecated 4.6.24 method is no longer used. Instead it is up to client code, like SPCO,
363
+	 *                                       to call handle_ipn() for offsite gateways that don't receive separate IPNs
364
+	 */
365
+	public function finalize_payment_for($transaction, $update_txn = true)
366
+	{
367
+		/** @var $transaction EE_Transaction */
368
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
369
+		$last_payment_method = $transaction->payment_method();
370
+		if ($last_payment_method instanceof EE_Payment_Method) {
371
+			$payment = $last_payment_method->type_obj()->finalize_payment_for($transaction);
372
+			$this->update_txn_based_on_payment($transaction, $payment, $update_txn);
373
+			return $payment;
374
+		} else {
375
+			return null;
376
+		}
377
+	}
378
+
379
+
380
+
381
+	/**
382
+	 * Processes a direct refund request, saves the payment, and updates the transaction appropriately.
383
+	 *
384
+	 * @param EE_Payment_Method $payment_method
385
+	 * @param EE_Payment        $payment_to_refund
386
+	 * @param array             $refund_info
387
+	 * @return EE_Payment
388
+	 * @throws \EE_Error
389
+	 */
390
+	public function process_refund(
391
+		EE_Payment_Method $payment_method,
392
+		EE_Payment $payment_to_refund,
393
+		$refund_info = array()
394
+	) {
395
+		if ($payment_method instanceof EE_Payment_Method && $payment_method->type_obj()->supports_sending_refunds()) {
396
+			$payment_method->type_obj()->process_refund($payment_to_refund, $refund_info);
397
+			$this->update_txn_based_on_payment($payment_to_refund->transaction(), $payment_to_refund);
398
+		}
399
+		return $payment_to_refund;
400
+	}
401
+
402
+
403
+
404
+	/**
405
+	 * This should be called each time there may have been an update to a
406
+	 * payment on a transaction (ie, we asked for a payment to process a
407
+	 * payment for a transaction, or we told a payment method about an IPN, or
408
+	 * we told a payment method to
409
+	 * "finalize_payment_for" (a transaction), or we told a payment method to
410
+	 * process a refund. This should handle firing the correct hooks to
411
+	 * indicate
412
+	 * what exactly happened and updating the transaction appropriately). This
413
+	 * could be integrated directly into EE_Transaction upon save, but we want
414
+	 * this logic to be separate from 'normal' plain-jane saving and updating
415
+	 * of transactions and payments, and to be tied to payment processing.
416
+	 * Note: this method DOES NOT save the payment passed into it. It is the responsibility
417
+	 * of previous code to decide whether or not to save (because the payment passed into
418
+	 * this method might be a temporary, never-to-be-saved payment from an offline gateway,
419
+	 * in which case we only want that payment object for some temporary usage during this request,
420
+	 * but we don't want it to be saved).
421
+	 *
422
+	 * @param EE_Transaction|int $transaction
423
+	 * @param EE_Payment         $payment
424
+	 * @param boolean            $update_txn
425
+	 *                        whether or not to call
426
+	 *                        EE_Transaction_Processor::
427
+	 *                        update_transaction_and_registrations_after_checkout_or_payment()
428
+	 *                        (you can save 1 DB query if you know you're going
429
+	 *                        to save it later instead)
430
+	 * @param bool               $IPN
431
+	 *                        if processing IPNs or other similar payment
432
+	 *                        related activities that occur in alternate
433
+	 *                        requests than the main one that is processing the
434
+	 *                        TXN, then set this to true to check whether the
435
+	 *                        TXN is locked before updating
436
+	 * @throws \EE_Error
437
+	 */
438
+	public function update_txn_based_on_payment($transaction, $payment, $update_txn = true, $IPN = false)
439
+	{
440
+		$do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__not_successful';
441
+		/** @type EE_Transaction $transaction */
442
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
443
+		// can we freely update the TXN at this moment?
444
+		if ($IPN && $transaction->is_locked()) {
445
+			// don't update the transaction at this exact moment
446
+			// because the TXN is active in another request
447
+			EE_Cron_Tasks::schedule_update_transaction_with_payment(
448
+				time(),
449
+				$transaction->ID(),
450
+				$payment->ID()
451
+			);
452
+		} else {
453
+			// verify payment and that it has been saved
454
+			if ($payment instanceof EE_Payment && $payment->ID()) {
455
+				if (
456
+					$payment->payment_method() instanceof EE_Payment_Method
457
+					&& $payment->payment_method()->type_obj() instanceof EE_PMT_Base
458
+				) {
459
+					$payment->payment_method()->type_obj()->update_txn_based_on_payment($payment);
460
+					// update TXN registrations with payment info
461
+					$this->process_registration_payments($transaction, $payment);
462
+				}
463
+				$do_action = $payment->just_approved()
464
+					? 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful'
465
+					: $do_action;
466
+			} else {
467
+				// send out notifications
468
+				add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
469
+				$do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__no_payment_made';
470
+			}
471
+			if ($payment->status() !== EEM_Payment::status_id_failed) {
472
+				/** @type EE_Transaction_Payments $transaction_payments */
473
+				$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
474
+				// set new value for total paid
475
+				$transaction_payments->calculate_total_payments_and_update_status($transaction);
476
+				// call EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment() ???
477
+				if ($update_txn) {
478
+					$this->_post_payment_processing($transaction, $payment, $IPN);
479
+				}
480
+			}
481
+			// granular hook for others to use.
482
+			do_action($do_action, $transaction, $payment);
483
+			do_action('AHEE_log', __CLASS__, __FUNCTION__, $do_action, '$do_action');
484
+			//global hook for others to use.
485
+			do_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', $transaction, $payment);
486
+		}
487
+	}
488
+
489
+
490
+
491
+	/**
492
+	 * update registrations REG_paid field after successful payment and link registrations with payment
493
+	 *
494
+	 * @param EE_Transaction    $transaction
495
+	 * @param EE_Payment        $payment
496
+	 * @param EE_Registration[] $registrations
497
+	 * @throws \EE_Error
498
+	 */
499
+	public function process_registration_payments(
500
+		EE_Transaction $transaction,
501
+		EE_Payment $payment,
502
+		$registrations = array()
503
+	) {
504
+		// only process if payment was successful
505
+		if ($payment->status() !== EEM_Payment::status_id_approved) {
506
+			return;
507
+		}
508
+		//EEM_Registration::instance()->show_next_x_db_queries();
509
+		if (empty($registrations)) {
510
+			// find registrations with monies owing that can receive a payment
511
+			$registrations = $transaction->registrations(
512
+				array(
513
+					array(
514
+						// only these reg statuses can receive payments
515
+						'STS_ID'           => array('IN', EEM_Registration::reg_statuses_that_allow_payment()),
516
+						'REG_final_price'  => array('!=', 0),
517
+						'REG_final_price*' => array('!=', 'REG_paid', true),
518
+					),
519
+				)
520
+			);
521
+		}
522
+		// still nothing ??!??
523
+		if (empty($registrations)) {
524
+			return;
525
+		}
526
+		// todo: break out the following logic into a separate strategy class
527
+		// todo: named something like "Sequential_Reg_Payment_Strategy"
528
+		// todo: which would apply payments using the capitalist "first come first paid" approach
529
+		// todo: then have another strategy class like "Distributed_Reg_Payment_Strategy"
530
+		// todo: which would be the socialist "everybody gets a piece of pie" approach,
531
+		// todo: which would be better for deposits, where you want a bit of the payment applied to each registration
532
+		$refund = $payment->is_a_refund();
533
+		// how much is available to apply to registrations?
534
+		$available_payment_amount = abs($payment->amount());
535
+		foreach ($registrations as $registration) {
536
+			if ($registration instanceof EE_Registration) {
537
+				// nothing left?
538
+				if ($available_payment_amount <= 0) {
539
+					break;
540
+				}
541
+				if ($refund) {
542
+					$available_payment_amount = $this->process_registration_refund($registration, $payment, $available_payment_amount);
543
+				} else {
544
+					$available_payment_amount = $this->process_registration_payment($registration, $payment, $available_payment_amount);
545
+				}
546
+			}
547
+		}
548
+		if ($available_payment_amount > 0 && apply_filters('FHEE__EE_Payment_Processor__process_registration_payments__display_notifications', false)) {
549
+			EE_Error::add_attention(
550
+				sprintf(
551
+					__('A remainder of %1$s exists after applying this payment to Registration(s) %2$s.%3$sPlease verify that the original payment amount of %4$s is correct. If so, you should edit this payment and select at least one additional registration in the "Registrations to Apply Payment to" section, so that the remainder of this payment can be applied to the additional registration(s).',
552
+						'event_espresso'),
553
+					EEH_Template::format_currency($available_payment_amount),
554
+					implode(', ', array_keys($registrations)),
555
+					'<br/>',
556
+					EEH_Template::format_currency($payment->amount())
557
+				),
558
+				__FILE__, __FUNCTION__, __LINE__
559
+			);
560
+		}
561
+	}
562
+
563
+
564
+
565
+	/**
566
+	 * update registration REG_paid field after successful payment and link registration with payment
567
+	 *
568
+	 * @param EE_Registration $registration
569
+	 * @param EE_Payment      $payment
570
+	 * @param float           $available_payment_amount
571
+	 * @return float
572
+	 * @throws \EE_Error
573
+	 */
574
+	public function process_registration_payment(
575
+		EE_Registration $registration,
576
+		EE_Payment $payment,
577
+		$available_payment_amount = 0.00
578
+	) {
579
+		$owing = $registration->final_price() - $registration->paid();
580
+		if ($owing > 0) {
581
+			// don't allow payment amount to exceed the available payment amount, OR the amount owing
582
+			$payment_amount = min($available_payment_amount, $owing);
583
+			// update $available_payment_amount
584
+			$available_payment_amount -= $payment_amount;
585
+			//calculate and set new REG_paid
586
+			$registration->set_paid($registration->paid() + $payment_amount);
587
+			// now save it
588
+			$this->_apply_registration_payment($registration, $payment, $payment_amount);
589
+		}
590
+		return $available_payment_amount;
591
+	}
592
+
593
+
594
+
595
+	/**
596
+	 * update registration REG_paid field after successful payment and link registration with payment
597
+	 *
598
+	 * @param EE_Registration $registration
599
+	 * @param EE_Payment      $payment
600
+	 * @param float           $payment_amount
601
+	 * @return void
602
+	 * @throws \EE_Error
603
+	 */
604
+	protected function _apply_registration_payment(
605
+		EE_Registration $registration,
606
+		EE_Payment $payment,
607
+		$payment_amount = 0.00
608
+	) {
609
+		// find any existing reg payment records for this registration and payment
610
+		$existing_reg_payment = EEM_Registration_Payment::instance()->get_one(
611
+			array(array('REG_ID' => $registration->ID(), 'PAY_ID' => $payment->ID()))
612
+		);
613
+		// if existing registration payment exists
614
+		if ($existing_reg_payment instanceof EE_Registration_Payment) {
615
+			// then update that record
616
+			$existing_reg_payment->set_amount($payment_amount);
617
+			$existing_reg_payment->save();
618
+		} else {
619
+			// or add new relation between registration and payment and set amount
620
+			$registration->_add_relation_to($payment, 'Payment', array('RPY_amount' => $payment_amount));
621
+			// make it stick
622
+			$registration->save();
623
+		}
624
+	}
625
+
626
+
627
+
628
+	/**
629
+	 * update registration REG_paid field after refund and link registration with payment
630
+	 *
631
+	 * @param EE_Registration $registration
632
+	 * @param EE_Payment      $payment
633
+	 * @param float           $available_refund_amount - IMPORTANT !!! SEND AVAILABLE REFUND AMOUNT AS A POSITIVE NUMBER
634
+	 * @return float
635
+	 * @throws \EE_Error
636
+	 */
637
+	public function process_registration_refund(
638
+		EE_Registration $registration,
639
+		EE_Payment $payment,
640
+		$available_refund_amount = 0.00
641
+	) {
642
+		//EEH_Debug_Tools::printr( $payment->amount(), '$payment->amount()', __FILE__, __LINE__ );
643
+		if ($registration->paid() > 0) {
644
+			// ensure $available_refund_amount is NOT negative
645
+			$available_refund_amount = (float)abs($available_refund_amount);
646
+			// don't allow refund amount to exceed the available payment amount, OR the amount paid
647
+			$refund_amount = min($available_refund_amount, (float)$registration->paid());
648
+			// update $available_payment_amount
649
+			$available_refund_amount -= $refund_amount;
650
+			//calculate and set new REG_paid
651
+			$registration->set_paid($registration->paid() - $refund_amount);
652
+			// convert payment amount back to a negative value for storage in the db
653
+			$refund_amount = (float)abs($refund_amount) * -1;
654
+			// now save it
655
+			$this->_apply_registration_payment($registration, $payment, $refund_amount);
656
+		}
657
+		return $available_refund_amount;
658
+	}
659
+
660
+
661
+
662
+	/**
663
+	 * Process payments and transaction after payment process completed.
664
+	 * ultimately this will send the TXN and payment details off so that notifications can be sent out.
665
+	 * if this request happens to be processing an IPN,
666
+	 * then we will also set the Payment Options Reg Step to completed,
667
+	 * and attempt to completely finalize the TXN if all of the other Reg Steps are completed as well.
668
+	 *
669
+	 * @param EE_Transaction $transaction
670
+	 * @param EE_Payment     $payment
671
+	 * @param bool           $IPN
672
+	 * @throws \EE_Error
673
+	 */
674
+	protected function _post_payment_processing(EE_Transaction $transaction, EE_Payment $payment, $IPN = false)
675
+	{
676
+		/** @type EE_Transaction_Processor $transaction_processor */
677
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
678
+		// is the Payment Options Reg Step completed ?
679
+		$payment_options_step_completed = $transaction->reg_step_completed('payment_options');
680
+		// if the Payment Options Reg Step is completed...
681
+		$revisit = $payment_options_step_completed === true ? true : false;
682
+		// then this is kinda sorta a revisit with regards to payments at least
683
+		$transaction_processor->set_revisit($revisit);
684
+		// if this is an IPN, let's consider the Payment Options Reg Step completed if not already
685
+		if (
686
+			$IPN
687
+			&& $payment_options_step_completed !== true
688
+			&& ($payment->is_approved() || $payment->is_pending())
689
+		) {
690
+			$payment_options_step_completed = $transaction->set_reg_step_completed(
691
+				'payment_options'
692
+			);
693
+		}
694
+		// maybe update status, but don't save transaction just yet
695
+		$transaction->update_status_based_on_total_paid(false);
696
+		// check if 'finalize_registration' step has been completed...
697
+		$finalized = $transaction->reg_step_completed('finalize_registration');
698
+		//  if this is an IPN and the final step has not been initiated
699
+		if ($IPN && $payment_options_step_completed && $finalized === false) {
700
+			// and if it hasn't already been set as being started...
701
+			$finalized = $transaction->set_reg_step_initiated('finalize_registration');
702
+		}
703
+		$transaction->save();
704
+		// because the above will return false if the final step was not fully completed, we need to check again...
705
+		if ($IPN && $finalized !== false) {
706
+			// and if we are all good to go, then send out notifications
707
+			add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
708
+			//ok, now process the transaction according to the payment
709
+			$transaction_processor->update_transaction_and_registrations_after_checkout_or_payment($transaction, $payment);
710
+		}
711
+		// DEBUG LOG
712
+		$payment_method = $payment->payment_method();
713
+		if ($payment_method instanceof EE_Payment_Method) {
714
+			$payment_method_type_obj = $payment_method->type_obj();
715
+			if ($payment_method_type_obj instanceof EE_PMT_Base) {
716
+				$gateway = $payment_method_type_obj->get_gateway();
717
+				if ($gateway instanceof EE_Gateway) {
718
+					$gateway->log(
719
+						array(
720
+							'message'               => __('Post Payment Transaction Details', 'event_espresso'),
721
+							'transaction'           => $transaction->model_field_array(),
722
+							'finalized'             => $finalized,
723
+							'IPN'                   => $IPN,
724
+							'deliver_notifications' => has_filter(
725
+								'FHEE__EED_Messages___maybe_registration__deliver_notifications'
726
+							),
727
+						),
728
+						$payment
729
+					);
730
+				}
731
+			}
732
+		}
733
+	}
734
+
735
+
736
+
737
+	/**
738
+	 * Force posts to PayPal to use TLS v1.2. See:
739
+	 * https://core.trac.wordpress.org/ticket/36320
740
+	 * https://core.trac.wordpress.org/ticket/34924#comment:15
741
+	 * https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US
742
+	 * This will affect paypal standard, pro, express, and payflow.
743
+	 */
744
+	public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
745
+	{
746
+		if (strstr($url, 'https://') && strstr($url, '.paypal.com')) {
747
+			//Use the value of the constant CURL_SSLVERSION_TLSv1 = 1
748
+			//instead of the constant because it might not be defined
749
+			curl_setopt($handle, CURLOPT_SSLVERSION, 1);
750
+		}
751
+	}
752 752
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Registration.model.php 2 patches
Indentation   +749 added lines, -749 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 use EventEspresso\core\services\database\TableAnalysis;
3 3
 
4 4
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
5
-    exit('No direct script access allowed');
5
+	exit('No direct script access allowed');
6 6
 }
7 7
 
8 8
 
@@ -17,737 +17,737 @@  discard block
 block discarded – undo
17 17
 class EEM_Registration extends EEM_Soft_Delete_Base
18 18
 {
19 19
 
20
-    // private instance of the Registration object
21
-    protected static $_instance = null;
22
-
23
-    /**
24
-     * Keys are the status IDs for registrations (eg, RAP, RCN, etc), and the values
25
-     * are status codes (eg, approved, cancelled, etc)
26
-     *
27
-     * @var array
28
-     */
29
-    private static $_reg_status;
30
-
31
-    /**
32
-     * The value of REG_count for a primary registrant
33
-     */
34
-    const PRIMARY_REGISTRANT_COUNT = 1;
35
-
36
-    /**
37
-     * Status ID (STS_ID on esp_status table) to indicate an INCOMPLETE registration.
38
-     * Initial status for registrations when they are first created
39
-     * Payments are NOT allowed.
40
-     * Automatically toggled to whatever the default Event registration status is upon completion of the attendee
41
-     * information reg step NO space reserved. Registration is NOT active
42
-     */
43
-    const status_id_incomplete = 'RIC';
44
-
45
-    /**
46
-     * Status ID (STS_ID on esp_status table) to indicate an UNAPPROVED registration.
47
-     * Payments are NOT allowed.
48
-     * Event Admin must manually toggle STS_ID for it to change
49
-     * No space reserved.
50
-     * Registration is active
51
-     */
52
-    const status_id_not_approved = 'RNA';
53
-
54
-    /**
55
-     * Status ID (STS_ID on esp_status table) to indicate registration is PENDING_PAYMENT .
56
-     * Payments are allowed.
57
-     * STS_ID will automatically be toggled to RAP if payment is made in full by the attendee
58
-     * No space reserved.
59
-     * Registration is active
60
-     */
61
-    const status_id_pending_payment = 'RPP';
62
-
63
-    /**
64
-     * Status ID (STS_ID on esp_status table) to indicate registration is on the WAIT_LIST .
65
-     * Payments are allowed.
66
-     * STS_ID will automatically be toggled to RAP if payment is made in full by the attendee
67
-     * No space reserved.
68
-     * Registration is active
69
-     */
70
-    const status_id_wait_list = 'RWL';
71
-
72
-    /**
73
-     * Status ID (STS_ID on esp_status table) to indicate an APPROVED registration.
74
-     * the TXN may or may not be completed ( paid in full )
75
-     * Payments are allowed.
76
-     * A space IS reserved.
77
-     * Registration is active
78
-     */
79
-    const status_id_approved = 'RAP';
80
-
81
-    /**
82
-     * Status ID (STS_ID on esp_status table) to indicate a registration was CANCELLED by the attendee.
83
-     * Payments are NOT allowed.
84
-     * NO space reserved.
85
-     * Registration is NOT active
86
-     */
87
-    const status_id_cancelled = 'RCN';
88
-
89
-    /**
90
-     * Status ID (STS_ID on esp_status table) to indicate a registration was DECLINED by the Event Admin
91
-     * Payments are NOT allowed.
92
-     * No space reserved.
93
-     * Registration is NOT active
94
-     */
95
-    const status_id_declined = 'RDC';
96
-
97
-    /**
98
-     * @var TableAnalysis $table_analysis
99
-     */
100
-    protected $_table_analysis;
101
-
102
-
103
-
104
-    /**
105
-     *    private constructor to prevent direct creation
106
-     *
107
-     * @Constructor
108
-     * @access protected
109
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
110
-     *                         incoming timezone data that gets saved). Note this just sends the timezone info to the
111
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
112
-     *                         timezone in the 'timezone_string' wp option)
113
-     */
114
-    protected function __construct($timezone = null)
115
-    {
116
-        $this->_table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
117
-        $this->singular_item = __('Registration', 'event_espresso');
118
-        $this->plural_item = __('Registrations', 'event_espresso');
119
-        $this->_tables = array(
120
-            'Registration' => new EE_Primary_Table('esp_registration', 'REG_ID'),
121
-        );
122
-        $this->_fields = array(
123
-            'Registration' => array(
124
-                'REG_ID'           => new EE_Primary_Key_Int_Field('REG_ID', __('Registration ID', 'event_espresso')),
125
-                'EVT_ID'           => new EE_Foreign_Key_Int_Field(
126
-                    'EVT_ID', __('Event ID', 'event_espresso'), false, 0, 'Event'
127
-                ),
128
-                'ATT_ID'           => new EE_Foreign_Key_Int_Field(
129
-                    'ATT_ID', __('Attendee ID', 'event_espresso'), false, 0, 'Attendee'
130
-                ),
131
-                'TXN_ID'           => new EE_Foreign_Key_Int_Field('TXN_ID', __('Transaction ID', 'event_espresso'),
132
-                    false, 0, 'Transaction'
133
-                ),
134
-                'TKT_ID'           => new EE_Foreign_Key_Int_Field('TKT_ID', __('Ticket ID', 'event_espresso'), false,
135
-                    0, 'Ticket'
136
-                ),
137
-                'STS_ID'           => new EE_Foreign_Key_String_Field('STS_ID', __('Status ID', 'event_espresso'),
138
-                    false, EEM_Registration::status_id_incomplete, 'Status'
139
-                ),
140
-                'REG_date'         => new EE_Datetime_Field('REG_date',
141
-                    __('Time registration occurred', 'event_espresso'), false, EE_Datetime_Field::now, $timezone
142
-                ),
143
-                'REG_final_price'  => new EE_Money_Field('REG_final_price',
144
-                    __('Registration\'s share of the transaction total', 'event_espresso'), false, 0
145
-                ),
146
-                'REG_paid'         => new EE_Money_Field('REG_paid',
147
-                    __('Amount paid to date towards registration', 'event_espresso'), false, 0
148
-                ),
149
-                'REG_session'      => new EE_Plain_Text_Field('REG_session',
150
-                    __('Session ID of registration', 'event_espresso'), false, ''
151
-                ),
152
-                'REG_code'         => new EE_Plain_Text_Field('REG_code',
153
-                    __('Unique Code for this registration', 'event_espresso'), false, ''
154
-                ),
155
-                'REG_url_link'     => new EE_Plain_Text_Field('REG_url_link',
156
-                    __('String to be used in URL for identifying registration', 'event_espresso'), false, ''
157
-                ),
158
-                'REG_count'        => new EE_Integer_Field('REG_count',
159
-                    __('Count of this registration in the group registration ', 'event_espresso'), true, 1
160
-                ),
161
-                'REG_group_size'   => new EE_Integer_Field('REG_group_size',
162
-                    __('Number of registrations on this group', 'event_espresso'), false, 1
163
-                ),
164
-                'REG_att_is_going' => new EE_Boolean_Field('REG_att_is_going',
165
-                    __('Flag indicating the registrant plans on attending', 'event_espresso'), false, false
166
-                ),
167
-                'REG_deleted'      => new EE_Trashed_Flag_Field(
168
-                    'REG_deleted', __('Flag indicating if registration has been archived or not.', 'event_espresso'),
169
-                    false, false
170
-                ),
171
-            ),
172
-        );
173
-        $this->_model_relations = array(
174
-            'Event'                => new EE_Belongs_To_Relation(),
175
-            'Attendee'             => new EE_Belongs_To_Relation(),
176
-            'Transaction'          => new EE_Belongs_To_Relation(),
177
-            'Ticket'               => new EE_Belongs_To_Relation(),
178
-            'Status'               => new EE_Belongs_To_Relation(),
179
-            'Answer'               => new EE_Has_Many_Relation(),
180
-            'Checkin'              => new EE_Has_Many_Relation(),
181
-            'Registration_Payment' => new EE_Has_Many_Relation(),
182
-            'Payment'              => new EE_HABTM_Relation('Registration_Payment'),
183
-            'Message'              => new EE_Has_Many_Any_Relation(false)
184
-            //allow deletes even if there are messages in the queue related
185
-        );
186
-        $this->_model_chain_to_wp_user = 'Event';
187
-        parent::__construct($timezone);
188
-    }
189
-
190
-
191
-
192
-    /**
193
-     * reg_statuses_that_allow_payment
194
-     * a filterable list of registration statuses that allow a registrant to make a payment
195
-     *
196
-     * @access public
197
-     * @return array
198
-     */
199
-    public static function reg_statuses_that_allow_payment()
200
-    {
201
-        return apply_filters(
202
-            'FHEE__EEM_Registration__reg_statuses_that_allow_payment',
203
-            array(
204
-                EEM_Registration::status_id_approved,
205
-                EEM_Registration::status_id_pending_payment,
206
-                EEM_Registration::status_id_wait_list,
207
-            )
208
-        );
209
-    }
210
-
211
-
212
-
213
-    /**
214
-     * inactive_reg_statuses
215
-     * a filterable list of registration statuses that are considered active
216
-     *
217
-     * @access public
218
-     * @return array
219
-     */
220
-    public static function active_reg_statuses()
221
-    {
222
-        return apply_filters(
223
-            'FHEE__EEM_Registration__reg_statuses_that_allow_payment',
224
-            array(
225
-                EEM_Registration::status_id_approved,
226
-                EEM_Registration::status_id_pending_payment,
227
-                EEM_Registration::status_id_wait_list,
228
-                EEM_Registration::status_id_not_approved,
229
-            )
230
-        );
231
-    }
232
-
233
-
234
-
235
-    /**
236
-     * inactive_reg_statuses
237
-     * a filterable list of registration statuses that are not considered active
238
-     *
239
-     * @access public
240
-     * @return array
241
-     */
242
-    public static function inactive_reg_statuses()
243
-    {
244
-        return apply_filters(
245
-            'FHEE__EEM_Registration__reg_statuses_that_allow_payment',
246
-            array(
247
-                EEM_Registration::status_id_incomplete,
248
-                EEM_Registration::status_id_cancelled,
249
-                EEM_Registration::status_id_declined,
250
-            )
251
-        );
252
-    }
253
-
254
-
255
-
256
-    /**
257
-     *    closed_reg_statuses
258
-     *    a filterable list of registration statuses that are considered "closed"
259
-     * meaning they should not be considered in any calculations involving monies owing
260
-     *
261
-     * @access public
262
-     * @return array
263
-     */
264
-    public static function closed_reg_statuses()
265
-    {
266
-        return apply_filters(
267
-            'FHEE__EEM_Registration__closed_reg_statuses',
268
-            array(
269
-                EEM_Registration::status_id_cancelled,
270
-                EEM_Registration::status_id_declined,
271
-            )
272
-        );
273
-    }
274
-
275
-
276
-
277
-    /**
278
-     *        get list of registration statuses
279
-     *
280
-     * @access public
281
-     * @param array $exclude    The status ids to exclude from the returned results
282
-     * @param bool  $translated If true will return the values as singular localized strings
283
-     * @return array
284
-     */
285
-    public static function reg_status_array($exclude = array(), $translated = false)
286
-    {
287
-        EEM_Registration::instance()->_get_registration_status_array($exclude);
288
-        return $translated ? EEM_Status::instance()->localized_status(self::$_reg_status, false, 'sentence')
289
-            : self::$_reg_status;
290
-    }
291
-
292
-
293
-
294
-    /**
295
-     *    get list of registration statuses
296
-     *
297
-     * @access private
298
-     * @param array $exclude
299
-     * @return array
300
-     */
301
-    private function _get_registration_status_array($exclude = array())
302
-    {
303
-        //in the very rare circumstance that we are deleting a model's table's data
304
-        //and the table hasn't actually been created, this could have an error
305
-        /** @type WPDB $wpdb */
306
-        global $wpdb;
307
-        if ($this->_get_table_analysis()->tableExists($wpdb->prefix . 'esp_status')) {
308
-            $results = $wpdb->get_results(
309
-                "SELECT STS_ID, STS_code FROM {$wpdb->prefix}esp_status WHERE STS_type = 'registration'"
310
-            );
311
-            self::$_reg_status = array();
312
-            foreach ($results as $status) {
313
-                if ( ! in_array($status->STS_ID, $exclude)) {
314
-                    self::$_reg_status[$status->STS_ID] = $status->STS_code;
315
-                }
316
-            }
317
-        }
318
-    }
319
-
320
-
321
-
322
-    /**
323
-     * Gets the injected table analyzer, or throws an exception
324
-     *
325
-     * @return TableAnalysis
326
-     * @throws \EE_Error
327
-     */
328
-    protected function _get_table_analysis()
329
-    {
330
-        if ($this->_table_analysis instanceof TableAnalysis) {
331
-            return $this->_table_analysis;
332
-        } else {
333
-            throw new \EE_Error(
334
-                sprintf(
335
-                    __('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
336
-                    get_class($this)
337
-                )
338
-            );
339
-        }
340
-    }
341
-
342
-
343
-
344
-    /**
345
-     * This returns a wpdb->results array of all registration date month and years matching the incoming query params
346
-     * and grouped by month and year.
347
-     *
348
-     * @param  array $where_params Array of query_params as described in the comments for EEM_Base::get_all()
349
-     * @return array
350
-     * @throws \EE_Error
351
-     */
352
-    public function get_reg_months_and_years($where_params)
353
-    {
354
-        $query_params[0] = $where_params;
355
-        $query_params['group_by'] = array('reg_year', 'reg_month');
356
-        $query_params['order_by'] = array('REG_date' => 'DESC');
357
-        $columns_to_select = array(
358
-            'reg_year'  => array('YEAR(REG_date)', '%s'),
359
-            'reg_month' => array('MONTHNAME(REG_date)', '%s'),
360
-        );
361
-        return $this->_get_all_wpdb_results($query_params, OBJECT, $columns_to_select);
362
-    }
363
-
364
-
365
-
366
-    /**
367
-     *        retrieve ALL registrations for a particular Attendee from db
368
-     *
369
-     * @access        public
370
-     * @param        int $ATT_ID
371
-     * @return    EE_Registration[]
372
-     */
373
-    public function get_all_registrations_for_attendee($ATT_ID = 0)
374
-    {
375
-        if ( ! $ATT_ID) {
376
-            return false;
377
-        }
378
-        return $this->get_all(array(array('ATT_ID' => $ATT_ID)));
379
-    }
380
-
381
-
382
-
383
-    /**
384
-     * Gets a registration given their REG_url_link. Yes, this should usually
385
-     * be passed via a GET parameter.
386
-     *
387
-     * @param string $REG_url_link
388
-     * @return EE_Registration
389
-     */
390
-    public function get_registration_for_reg_url_link($REG_url_link)
391
-    {
392
-        if ( ! $REG_url_link) {
393
-            return false;
394
-        }
395
-        return $this->get_one(array(array('REG_url_link' => $REG_url_link)));
396
-    }
397
-
398
-
399
-
400
-    /**
401
-     *        retrieve registration for a specific transaction attendee from db
402
-     *
403
-     * @access        public
404
-     * @param    int $TXN_ID
405
-     * @param    int $ATT_ID
406
-     * @param    int $att_nmbr in case the ATT_ID is the same for multiple registrations (same details used) then the
407
-     *                         attendee number is required
408
-     * @return        mixed        array on success, FALSE on fail
409
-     */
410
-    public function get_registration_for_transaction_attendee($TXN_ID = 0, $ATT_ID = 0, $att_nmbr = 0)
411
-    {
412
-        return $this->get_one(array(
413
-            array(
414
-                'TXN_ID' => $TXN_ID,
415
-                'ATT_ID' => $ATT_ID,
416
-            ),
417
-            'limit' => array(min(($att_nmbr - 1), 0), 1),
418
-        ));
419
-    }
420
-
421
-
422
-
423
-    /**
424
-     *        get the number of registrations per day  for the Registration Admin page Reports Tab.
425
-     *        (doesn't utilize models because it's a fairly specialized query)
426
-     *
427
-     * @access        public
428
-     * @param $period string which can be passed to php's strtotime function (eg "-1 month")
429
-     * @return stdClass[] with properties regDate and total
430
-     */
431
-    public function get_registrations_per_day_report($period = '-1 month')
432
-    {
433
-        $sql_date = $this->convert_datetime_for_query('REG_date', date("Y-m-d H:i:s", strtotime($period)),
434
-            'Y-m-d H:i:s', 'UTC');
435
-        $where = array(
436
-            'REG_date' => array('>=', $sql_date),
437
-            'STS_ID'   => array('!=', EEM_Registration::status_id_incomplete),
438
-        );
439
-        if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_day_report')) {
440
-            $where['Event.EVT_wp_user'] = get_current_user_id();
441
-        }
442
-        $query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'REG_date');
443
-        $results = $this->_get_all_wpdb_results(
444
-            array(
445
-                $where,
446
-                'group_by' => 'regDate',
447
-                'order_by' => array('REG_date' => 'ASC'),
448
-            ),
449
-            OBJECT,
450
-            array(
451
-                'regDate' => array('DATE(' . $query_interval . ')', '%s'),
452
-                'total'   => array('count(REG_ID)', '%d'),
453
-            ));
454
-        return $results;
455
-    }
456
-
457
-
458
-
459
-    /**
460
-     * Get the number of registrations per day including the count of registrations for each Registration Status.
461
-     * Note: EEM_Registration::status_id_incomplete registrations are excluded from the results.
462
-     *
463
-     * @param string $period
464
-     * @return stdClass[] with properties Registration_REG_date and a column for each registration status as the STS_ID
465
-     *                    (i.e. RAP)
466
-     */
467
-    public function get_registrations_per_day_and_per_status_report($period = '-1 month')
468
-    {
469
-        global $wpdb;
470
-        $registration_table = $wpdb->prefix . 'esp_registration';
471
-        $event_table = $wpdb->posts;
472
-        $sql_date = date("Y-m-d H:i:s", strtotime($period));
473
-        //prepare the query interval for displaying offset
474
-        $query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'dates.REG_date');
475
-        //inner date query
476
-        $inner_date_query = "SELECT DISTINCT REG_date from $registration_table ";
477
-        $inner_where = " WHERE";
478
-        //exclude events not authored by user if permissions in effect
479
-        if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
480
-            $inner_date_query .= "LEFT JOIN $event_table ON ID = EVT_ID";
481
-            $inner_where .= " post_author = " . get_current_user_id() . " AND";
482
-        }
483
-        $inner_where .= " REG_date >= '$sql_date'";
484
-        $inner_date_query .= $inner_where;
485
-        //start main query
486
-        $select = "SELECT DATE($query_interval) as Registration_REG_date, ";
487
-        $join = '';
488
-        $join_parts = array();
489
-        $select_parts = array();
490
-        //loop through registration stati to do parts for each status.
491
-        foreach (EEM_Registration::reg_status_array() as $STS_ID => $STS_code) {
492
-            if ($STS_ID === EEM_Registration::status_id_incomplete) {
493
-                continue;
494
-            }
495
-            $select_parts[] = "COUNT($STS_code.REG_ID) as $STS_ID";
496
-            $join_parts[] = "$registration_table AS $STS_code ON $STS_code.REG_date = dates.REG_date AND $STS_code.STS_ID = '$STS_ID'";
497
-        }
498
-        //setup the selects
499
-        $select .= implode(', ', $select_parts);
500
-        $select .= " FROM ($inner_date_query) AS dates LEFT JOIN ";
501
-        //setup the joins
502
-        $join .= implode(" LEFT JOIN ", $join_parts);
503
-        //now let's put it all together
504
-        $query = $select . $join . ' GROUP BY Registration_REG_date';
505
-        //and execute it
506
-        $results = $wpdb->get_results($query, ARRAY_A);
507
-        return $results;
508
-    }
509
-
510
-
511
-
512
-    /**
513
-     *        get the number of registrations per event  for the Registration Admin page Reports Tab
514
-     *
515
-     * @access        public
516
-     * @param $period string which can be passed to php's strtotime function (eg "-1 month")
517
-     * @return stdClass[] each with properties event_name, reg_limit, and total
518
-     */
519
-    public function get_registrations_per_event_report($period = '-1 month')
520
-    {
521
-        $date_sql = $this->convert_datetime_for_query('REG_date', date("Y-m-d H:i:s", strtotime($period)),
522
-            'Y-m-d H:i:s', 'UTC');
523
-        $where = array(
524
-            'REG_date' => array('>=', $date_sql),
525
-            'STS_ID'   => array('!=', EEM_Registration::status_id_incomplete),
526
-        );
527
-        if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
528
-            $where['Event.EVT_wp_user'] = get_current_user_id();
529
-        }
530
-        $results = $this->_get_all_wpdb_results(array(
531
-            $where,
532
-            'group_by' => 'Event.EVT_name',
533
-            'order_by' => 'Event.EVT_name',
534
-            'limit'    => array(0, 24),
535
-        ),
536
-            OBJECT,
537
-            array(
538
-                'event_name' => array('Event_CPT.post_title', '%s'),
539
-                'total'      => array('COUNT(REG_ID)', '%s'),
540
-            )
541
-        );
542
-        return $results;
543
-    }
544
-
545
-
546
-
547
-    /**
548
-     * Get the number of registrations per event grouped by registration status.
549
-     * Note: EEM_Registration::status_id_incomplete registrations are excluded from the results.
550
-     *
551
-     * @param string $period
552
-     * @return stdClass[] with properties `Registration_Event` and a column for each registration status as the STS_ID
553
-     *                    (i.e. RAP)
554
-     */
555
-    public function get_registrations_per_event_and_per_status_report($period = '-1 month')
556
-    {
557
-        global $wpdb;
558
-        $registration_table = $wpdb->prefix . 'esp_registration';
559
-        $event_table = $wpdb->posts;
560
-        $sql_date = date("Y-m-d H:i:s", strtotime($period));
561
-        //inner date query
562
-        $inner_date_query = "SELECT DISTINCT EVT_ID, REG_date from $registration_table ";
563
-        $inner_where = " WHERE";
564
-        //exclude events not authored by user if permissions in effect
565
-        if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
566
-            $inner_date_query .= "LEFT JOIN $event_table ON ID = EVT_ID";
567
-            $inner_where .= " post_author = " . get_current_user_id() . " AND";
568
-        }
569
-        $inner_where .= " REG_date >= '$sql_date'";
570
-        $inner_date_query .= $inner_where;
571
-        //build main query
572
-        $select = "SELECT Event.post_title as Registration_Event, ";
573
-        $join = '';
574
-        $join_parts = array();
575
-        $select_parts = array();
576
-        //loop through registration stati to do parts for each status.
577
-        foreach (EEM_Registration::reg_status_array() as $STS_ID => $STS_code) {
578
-            if ($STS_ID === EEM_Registration::status_id_incomplete) {
579
-                continue;
580
-            }
581
-            $select_parts[] = "COUNT($STS_code.REG_ID) as $STS_ID";
582
-            $join_parts[] = "$registration_table AS $STS_code ON $STS_code.EVT_ID = dates.EVT_ID AND $STS_code.STS_ID = '$STS_ID' AND $STS_code.REG_date = dates.REG_date";
583
-        }
584
-        //setup the selects
585
-        $select .= implode(', ', $select_parts);
586
-        $select .= " FROM ($inner_date_query) AS dates LEFT JOIN $event_table as Event ON Event.ID = dates.EVT_ID LEFT JOIN ";
587
-        //setup remaining joins
588
-        $join .= implode(" LEFT JOIN ", $join_parts);
589
-        //now put it all together
590
-        $query = $select . $join . ' GROUP BY Registration_Event';
591
-        //and execute
592
-        $results = $wpdb->get_results($query, ARRAY_A);
593
-        return $results;
594
-    }
595
-
596
-
597
-
598
-    /**
599
-     * Returns the EE_Registration of the primary attendee on the transaction id provided
600
-     *
601
-     * @param int $TXN_ID
602
-     * @return EE_Registration
603
-     */
604
-    public function get_primary_registration_for_transaction_ID($TXN_ID = 0)
605
-    {
606
-        if ( ! $TXN_ID) {
607
-            return false;
608
-        }
609
-        return $this->get_one(array(
610
-            array(
611
-                'TXN_ID'    => $TXN_ID,
612
-                'REG_count' => EEM_Registration::PRIMARY_REGISTRANT_COUNT,
613
-            ),
614
-        ));
615
-    }
616
-
617
-
618
-
619
-    /**
620
-     *        get_event_registration_count
621
-     *
622
-     * @access public
623
-     * @param int     $EVT_ID
624
-     * @param boolean $for_incomplete_payments
625
-     * @return int
626
-     */
627
-    public function get_event_registration_count($EVT_ID, $for_incomplete_payments = false)
628
-    {
629
-        // we only count approved registrations towards registration limits
630
-        $query_params = array(array('EVT_ID' => $EVT_ID, 'STS_ID' => self::status_id_approved));
631
-        if ($for_incomplete_payments) {
632
-            $query_params[0]['Transaction.STS_ID'] = array('!=', EEM_Transaction::complete_status_code);
633
-        }
634
-        return $this->count($query_params);
635
-    }
636
-
637
-
638
-
639
-    /**
640
-     * Deletes all registrations with no transactions. Note that this needs to be very efficient
641
-     * and so it uses wpdb directly
642
-     *
643
-     * @global WPDB $wpdb
644
-     * @return int number deleted
645
-     */
646
-    public function delete_registrations_with_no_transaction()
647
-    {
648
-        /** @type WPDB $wpdb */
649
-        global $wpdb;
650
-        return $wpdb->query(
651
-            'DELETE r FROM '
652
-            . $this->table()
653
-            . ' r LEFT JOIN '
654
-            . EEM_Transaction::instance()->table()
655
-            . ' t ON r.TXN_ID = t.TXN_ID WHERE t.TXN_ID IS NULL');
656
-    }
657
-
658
-
659
-
660
-    /**
661
-     *  Count registrations checked into (or out of) a datetime
662
-     *
663
-     * @param int     $DTT_ID     datetime ID
664
-     * @param boolean $checked_in whether to count registrations checked IN or OUT
665
-     * @return int
666
-     */
667
-    public function count_registrations_checked_into_datetime($DTT_ID, $checked_in = true)
668
-    {
669
-        global $wpdb;
670
-        //subquery to get latest checkin
671
-        $query = $wpdb->prepare(
672
-            'SELECT '
673
-            . 'COUNT( DISTINCT checkins.REG_ID ) '
674
-            . 'FROM ' . EEM_Checkin::instance()->table() . ' AS checkins INNER JOIN'
675
-            . '( SELECT '
676
-            . 'max( CHK_timestamp ) AS latest_checkin, '
677
-            . 'REG_ID AS REG_ID '
678
-            . 'FROM ' . EEM_Checkin::instance()->table() . ' '
679
-            . 'WHERE DTT_ID=%d '
680
-            . 'GROUP BY REG_ID'
681
-            . ') AS most_recent_checkin_per_reg '
682
-            . 'ON checkins.REG_ID=most_recent_checkin_per_reg.REG_ID '
683
-            . 'AND checkins.CHK_timestamp = most_recent_checkin_per_reg.latest_checkin '
684
-            . 'WHERE '
685
-            . 'checkins.CHK_in=%d',
686
-            $DTT_ID,
687
-            $checked_in
688
-        );
689
-        return (int)$wpdb->get_var($query);
690
-    }
691
-
692
-
693
-
694
-    /**
695
-     *  Count registrations checked into (or out of) an event.
696
-     *
697
-     * @param int     $EVT_ID     event ID
698
-     * @param boolean $checked_in whether to count registrations checked IN or OUT
699
-     * @return int
700
-     */
701
-    public function count_registrations_checked_into_event($EVT_ID, $checked_in = true)
702
-    {
703
-        global $wpdb;
704
-        //subquery to get latest checkin
705
-        $query = $wpdb->prepare(
706
-            'SELECT '
707
-            . 'COUNT( DISTINCT checkins.REG_ID ) '
708
-            . 'FROM ' . EEM_Checkin::instance()->table() . ' AS checkins INNER JOIN'
709
-            . '( SELECT '
710
-            . 'max( CHK_timestamp ) AS latest_checkin, '
711
-            . 'REG_ID AS REG_ID '
712
-            . 'FROM ' . EEM_Checkin::instance()->table() . ' AS c '
713
-            . 'INNER JOIN ' . EEM_Datetime::instance()->table() . ' AS d '
714
-            . 'ON c.DTT_ID=d.DTT_ID '
715
-            . 'WHERE d.EVT_ID=%d '
716
-            . 'GROUP BY REG_ID'
717
-            . ') AS most_recent_checkin_per_reg '
718
-            . 'ON checkins.REG_ID=most_recent_checkin_per_reg.REG_ID '
719
-            . 'AND checkins.CHK_timestamp = most_recent_checkin_per_reg.latest_checkin '
720
-            . 'WHERE '
721
-            . 'checkins.CHK_in=%d',
722
-            $EVT_ID,
723
-            $checked_in
724
-        );
725
-        return (int)$wpdb->get_var($query);
726
-    }
727
-
728
-
729
-
730
-    /**
731
-     * The purpose of this method is to retrieve an array of
732
-     * EE_Registration objects that represent the latest registration
733
-     * for each ATT_ID given in the function argument.
734
-     *
735
-     * @param array $attendee_ids
736
-     * @return EE_Registration[]
737
-     */
738
-    public function get_latest_registration_for_each_of_given_contacts($attendee_ids = array())
739
-    {
740
-        //first do a native wp_query to get the latest REG_ID's matching these attendees.
741
-        global $wpdb;
742
-        $registration_table = $wpdb->prefix . 'esp_registration';
743
-        $attendee_table = $wpdb->posts;
744
-        $attendee_ids = is_array($attendee_ids)
745
-            ? array_map('absint', $attendee_ids)
746
-            : array((int)$attendee_ids);
747
-        $attendee_ids = implode(',', $attendee_ids);
748
-        //first we do a query to get the registration ids
749
-        // (because a group by before order by causes the order by to be ignored.)
750
-        $registration_id_query = "
20
+	// private instance of the Registration object
21
+	protected static $_instance = null;
22
+
23
+	/**
24
+	 * Keys are the status IDs for registrations (eg, RAP, RCN, etc), and the values
25
+	 * are status codes (eg, approved, cancelled, etc)
26
+	 *
27
+	 * @var array
28
+	 */
29
+	private static $_reg_status;
30
+
31
+	/**
32
+	 * The value of REG_count for a primary registrant
33
+	 */
34
+	const PRIMARY_REGISTRANT_COUNT = 1;
35
+
36
+	/**
37
+	 * Status ID (STS_ID on esp_status table) to indicate an INCOMPLETE registration.
38
+	 * Initial status for registrations when they are first created
39
+	 * Payments are NOT allowed.
40
+	 * Automatically toggled to whatever the default Event registration status is upon completion of the attendee
41
+	 * information reg step NO space reserved. Registration is NOT active
42
+	 */
43
+	const status_id_incomplete = 'RIC';
44
+
45
+	/**
46
+	 * Status ID (STS_ID on esp_status table) to indicate an UNAPPROVED registration.
47
+	 * Payments are NOT allowed.
48
+	 * Event Admin must manually toggle STS_ID for it to change
49
+	 * No space reserved.
50
+	 * Registration is active
51
+	 */
52
+	const status_id_not_approved = 'RNA';
53
+
54
+	/**
55
+	 * Status ID (STS_ID on esp_status table) to indicate registration is PENDING_PAYMENT .
56
+	 * Payments are allowed.
57
+	 * STS_ID will automatically be toggled to RAP if payment is made in full by the attendee
58
+	 * No space reserved.
59
+	 * Registration is active
60
+	 */
61
+	const status_id_pending_payment = 'RPP';
62
+
63
+	/**
64
+	 * Status ID (STS_ID on esp_status table) to indicate registration is on the WAIT_LIST .
65
+	 * Payments are allowed.
66
+	 * STS_ID will automatically be toggled to RAP if payment is made in full by the attendee
67
+	 * No space reserved.
68
+	 * Registration is active
69
+	 */
70
+	const status_id_wait_list = 'RWL';
71
+
72
+	/**
73
+	 * Status ID (STS_ID on esp_status table) to indicate an APPROVED registration.
74
+	 * the TXN may or may not be completed ( paid in full )
75
+	 * Payments are allowed.
76
+	 * A space IS reserved.
77
+	 * Registration is active
78
+	 */
79
+	const status_id_approved = 'RAP';
80
+
81
+	/**
82
+	 * Status ID (STS_ID on esp_status table) to indicate a registration was CANCELLED by the attendee.
83
+	 * Payments are NOT allowed.
84
+	 * NO space reserved.
85
+	 * Registration is NOT active
86
+	 */
87
+	const status_id_cancelled = 'RCN';
88
+
89
+	/**
90
+	 * Status ID (STS_ID on esp_status table) to indicate a registration was DECLINED by the Event Admin
91
+	 * Payments are NOT allowed.
92
+	 * No space reserved.
93
+	 * Registration is NOT active
94
+	 */
95
+	const status_id_declined = 'RDC';
96
+
97
+	/**
98
+	 * @var TableAnalysis $table_analysis
99
+	 */
100
+	protected $_table_analysis;
101
+
102
+
103
+
104
+	/**
105
+	 *    private constructor to prevent direct creation
106
+	 *
107
+	 * @Constructor
108
+	 * @access protected
109
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
110
+	 *                         incoming timezone data that gets saved). Note this just sends the timezone info to the
111
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
112
+	 *                         timezone in the 'timezone_string' wp option)
113
+	 */
114
+	protected function __construct($timezone = null)
115
+	{
116
+		$this->_table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
117
+		$this->singular_item = __('Registration', 'event_espresso');
118
+		$this->plural_item = __('Registrations', 'event_espresso');
119
+		$this->_tables = array(
120
+			'Registration' => new EE_Primary_Table('esp_registration', 'REG_ID'),
121
+		);
122
+		$this->_fields = array(
123
+			'Registration' => array(
124
+				'REG_ID'           => new EE_Primary_Key_Int_Field('REG_ID', __('Registration ID', 'event_espresso')),
125
+				'EVT_ID'           => new EE_Foreign_Key_Int_Field(
126
+					'EVT_ID', __('Event ID', 'event_espresso'), false, 0, 'Event'
127
+				),
128
+				'ATT_ID'           => new EE_Foreign_Key_Int_Field(
129
+					'ATT_ID', __('Attendee ID', 'event_espresso'), false, 0, 'Attendee'
130
+				),
131
+				'TXN_ID'           => new EE_Foreign_Key_Int_Field('TXN_ID', __('Transaction ID', 'event_espresso'),
132
+					false, 0, 'Transaction'
133
+				),
134
+				'TKT_ID'           => new EE_Foreign_Key_Int_Field('TKT_ID', __('Ticket ID', 'event_espresso'), false,
135
+					0, 'Ticket'
136
+				),
137
+				'STS_ID'           => new EE_Foreign_Key_String_Field('STS_ID', __('Status ID', 'event_espresso'),
138
+					false, EEM_Registration::status_id_incomplete, 'Status'
139
+				),
140
+				'REG_date'         => new EE_Datetime_Field('REG_date',
141
+					__('Time registration occurred', 'event_espresso'), false, EE_Datetime_Field::now, $timezone
142
+				),
143
+				'REG_final_price'  => new EE_Money_Field('REG_final_price',
144
+					__('Registration\'s share of the transaction total', 'event_espresso'), false, 0
145
+				),
146
+				'REG_paid'         => new EE_Money_Field('REG_paid',
147
+					__('Amount paid to date towards registration', 'event_espresso'), false, 0
148
+				),
149
+				'REG_session'      => new EE_Plain_Text_Field('REG_session',
150
+					__('Session ID of registration', 'event_espresso'), false, ''
151
+				),
152
+				'REG_code'         => new EE_Plain_Text_Field('REG_code',
153
+					__('Unique Code for this registration', 'event_espresso'), false, ''
154
+				),
155
+				'REG_url_link'     => new EE_Plain_Text_Field('REG_url_link',
156
+					__('String to be used in URL for identifying registration', 'event_espresso'), false, ''
157
+				),
158
+				'REG_count'        => new EE_Integer_Field('REG_count',
159
+					__('Count of this registration in the group registration ', 'event_espresso'), true, 1
160
+				),
161
+				'REG_group_size'   => new EE_Integer_Field('REG_group_size',
162
+					__('Number of registrations on this group', 'event_espresso'), false, 1
163
+				),
164
+				'REG_att_is_going' => new EE_Boolean_Field('REG_att_is_going',
165
+					__('Flag indicating the registrant plans on attending', 'event_espresso'), false, false
166
+				),
167
+				'REG_deleted'      => new EE_Trashed_Flag_Field(
168
+					'REG_deleted', __('Flag indicating if registration has been archived or not.', 'event_espresso'),
169
+					false, false
170
+				),
171
+			),
172
+		);
173
+		$this->_model_relations = array(
174
+			'Event'                => new EE_Belongs_To_Relation(),
175
+			'Attendee'             => new EE_Belongs_To_Relation(),
176
+			'Transaction'          => new EE_Belongs_To_Relation(),
177
+			'Ticket'               => new EE_Belongs_To_Relation(),
178
+			'Status'               => new EE_Belongs_To_Relation(),
179
+			'Answer'               => new EE_Has_Many_Relation(),
180
+			'Checkin'              => new EE_Has_Many_Relation(),
181
+			'Registration_Payment' => new EE_Has_Many_Relation(),
182
+			'Payment'              => new EE_HABTM_Relation('Registration_Payment'),
183
+			'Message'              => new EE_Has_Many_Any_Relation(false)
184
+			//allow deletes even if there are messages in the queue related
185
+		);
186
+		$this->_model_chain_to_wp_user = 'Event';
187
+		parent::__construct($timezone);
188
+	}
189
+
190
+
191
+
192
+	/**
193
+	 * reg_statuses_that_allow_payment
194
+	 * a filterable list of registration statuses that allow a registrant to make a payment
195
+	 *
196
+	 * @access public
197
+	 * @return array
198
+	 */
199
+	public static function reg_statuses_that_allow_payment()
200
+	{
201
+		return apply_filters(
202
+			'FHEE__EEM_Registration__reg_statuses_that_allow_payment',
203
+			array(
204
+				EEM_Registration::status_id_approved,
205
+				EEM_Registration::status_id_pending_payment,
206
+				EEM_Registration::status_id_wait_list,
207
+			)
208
+		);
209
+	}
210
+
211
+
212
+
213
+	/**
214
+	 * inactive_reg_statuses
215
+	 * a filterable list of registration statuses that are considered active
216
+	 *
217
+	 * @access public
218
+	 * @return array
219
+	 */
220
+	public static function active_reg_statuses()
221
+	{
222
+		return apply_filters(
223
+			'FHEE__EEM_Registration__reg_statuses_that_allow_payment',
224
+			array(
225
+				EEM_Registration::status_id_approved,
226
+				EEM_Registration::status_id_pending_payment,
227
+				EEM_Registration::status_id_wait_list,
228
+				EEM_Registration::status_id_not_approved,
229
+			)
230
+		);
231
+	}
232
+
233
+
234
+
235
+	/**
236
+	 * inactive_reg_statuses
237
+	 * a filterable list of registration statuses that are not considered active
238
+	 *
239
+	 * @access public
240
+	 * @return array
241
+	 */
242
+	public static function inactive_reg_statuses()
243
+	{
244
+		return apply_filters(
245
+			'FHEE__EEM_Registration__reg_statuses_that_allow_payment',
246
+			array(
247
+				EEM_Registration::status_id_incomplete,
248
+				EEM_Registration::status_id_cancelled,
249
+				EEM_Registration::status_id_declined,
250
+			)
251
+		);
252
+	}
253
+
254
+
255
+
256
+	/**
257
+	 *    closed_reg_statuses
258
+	 *    a filterable list of registration statuses that are considered "closed"
259
+	 * meaning they should not be considered in any calculations involving monies owing
260
+	 *
261
+	 * @access public
262
+	 * @return array
263
+	 */
264
+	public static function closed_reg_statuses()
265
+	{
266
+		return apply_filters(
267
+			'FHEE__EEM_Registration__closed_reg_statuses',
268
+			array(
269
+				EEM_Registration::status_id_cancelled,
270
+				EEM_Registration::status_id_declined,
271
+			)
272
+		);
273
+	}
274
+
275
+
276
+
277
+	/**
278
+	 *        get list of registration statuses
279
+	 *
280
+	 * @access public
281
+	 * @param array $exclude    The status ids to exclude from the returned results
282
+	 * @param bool  $translated If true will return the values as singular localized strings
283
+	 * @return array
284
+	 */
285
+	public static function reg_status_array($exclude = array(), $translated = false)
286
+	{
287
+		EEM_Registration::instance()->_get_registration_status_array($exclude);
288
+		return $translated ? EEM_Status::instance()->localized_status(self::$_reg_status, false, 'sentence')
289
+			: self::$_reg_status;
290
+	}
291
+
292
+
293
+
294
+	/**
295
+	 *    get list of registration statuses
296
+	 *
297
+	 * @access private
298
+	 * @param array $exclude
299
+	 * @return array
300
+	 */
301
+	private function _get_registration_status_array($exclude = array())
302
+	{
303
+		//in the very rare circumstance that we are deleting a model's table's data
304
+		//and the table hasn't actually been created, this could have an error
305
+		/** @type WPDB $wpdb */
306
+		global $wpdb;
307
+		if ($this->_get_table_analysis()->tableExists($wpdb->prefix . 'esp_status')) {
308
+			$results = $wpdb->get_results(
309
+				"SELECT STS_ID, STS_code FROM {$wpdb->prefix}esp_status WHERE STS_type = 'registration'"
310
+			);
311
+			self::$_reg_status = array();
312
+			foreach ($results as $status) {
313
+				if ( ! in_array($status->STS_ID, $exclude)) {
314
+					self::$_reg_status[$status->STS_ID] = $status->STS_code;
315
+				}
316
+			}
317
+		}
318
+	}
319
+
320
+
321
+
322
+	/**
323
+	 * Gets the injected table analyzer, or throws an exception
324
+	 *
325
+	 * @return TableAnalysis
326
+	 * @throws \EE_Error
327
+	 */
328
+	protected function _get_table_analysis()
329
+	{
330
+		if ($this->_table_analysis instanceof TableAnalysis) {
331
+			return $this->_table_analysis;
332
+		} else {
333
+			throw new \EE_Error(
334
+				sprintf(
335
+					__('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
336
+					get_class($this)
337
+				)
338
+			);
339
+		}
340
+	}
341
+
342
+
343
+
344
+	/**
345
+	 * This returns a wpdb->results array of all registration date month and years matching the incoming query params
346
+	 * and grouped by month and year.
347
+	 *
348
+	 * @param  array $where_params Array of query_params as described in the comments for EEM_Base::get_all()
349
+	 * @return array
350
+	 * @throws \EE_Error
351
+	 */
352
+	public function get_reg_months_and_years($where_params)
353
+	{
354
+		$query_params[0] = $where_params;
355
+		$query_params['group_by'] = array('reg_year', 'reg_month');
356
+		$query_params['order_by'] = array('REG_date' => 'DESC');
357
+		$columns_to_select = array(
358
+			'reg_year'  => array('YEAR(REG_date)', '%s'),
359
+			'reg_month' => array('MONTHNAME(REG_date)', '%s'),
360
+		);
361
+		return $this->_get_all_wpdb_results($query_params, OBJECT, $columns_to_select);
362
+	}
363
+
364
+
365
+
366
+	/**
367
+	 *        retrieve ALL registrations for a particular Attendee from db
368
+	 *
369
+	 * @access        public
370
+	 * @param        int $ATT_ID
371
+	 * @return    EE_Registration[]
372
+	 */
373
+	public function get_all_registrations_for_attendee($ATT_ID = 0)
374
+	{
375
+		if ( ! $ATT_ID) {
376
+			return false;
377
+		}
378
+		return $this->get_all(array(array('ATT_ID' => $ATT_ID)));
379
+	}
380
+
381
+
382
+
383
+	/**
384
+	 * Gets a registration given their REG_url_link. Yes, this should usually
385
+	 * be passed via a GET parameter.
386
+	 *
387
+	 * @param string $REG_url_link
388
+	 * @return EE_Registration
389
+	 */
390
+	public function get_registration_for_reg_url_link($REG_url_link)
391
+	{
392
+		if ( ! $REG_url_link) {
393
+			return false;
394
+		}
395
+		return $this->get_one(array(array('REG_url_link' => $REG_url_link)));
396
+	}
397
+
398
+
399
+
400
+	/**
401
+	 *        retrieve registration for a specific transaction attendee from db
402
+	 *
403
+	 * @access        public
404
+	 * @param    int $TXN_ID
405
+	 * @param    int $ATT_ID
406
+	 * @param    int $att_nmbr in case the ATT_ID is the same for multiple registrations (same details used) then the
407
+	 *                         attendee number is required
408
+	 * @return        mixed        array on success, FALSE on fail
409
+	 */
410
+	public function get_registration_for_transaction_attendee($TXN_ID = 0, $ATT_ID = 0, $att_nmbr = 0)
411
+	{
412
+		return $this->get_one(array(
413
+			array(
414
+				'TXN_ID' => $TXN_ID,
415
+				'ATT_ID' => $ATT_ID,
416
+			),
417
+			'limit' => array(min(($att_nmbr - 1), 0), 1),
418
+		));
419
+	}
420
+
421
+
422
+
423
+	/**
424
+	 *        get the number of registrations per day  for the Registration Admin page Reports Tab.
425
+	 *        (doesn't utilize models because it's a fairly specialized query)
426
+	 *
427
+	 * @access        public
428
+	 * @param $period string which can be passed to php's strtotime function (eg "-1 month")
429
+	 * @return stdClass[] with properties regDate and total
430
+	 */
431
+	public function get_registrations_per_day_report($period = '-1 month')
432
+	{
433
+		$sql_date = $this->convert_datetime_for_query('REG_date', date("Y-m-d H:i:s", strtotime($period)),
434
+			'Y-m-d H:i:s', 'UTC');
435
+		$where = array(
436
+			'REG_date' => array('>=', $sql_date),
437
+			'STS_ID'   => array('!=', EEM_Registration::status_id_incomplete),
438
+		);
439
+		if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_day_report')) {
440
+			$where['Event.EVT_wp_user'] = get_current_user_id();
441
+		}
442
+		$query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'REG_date');
443
+		$results = $this->_get_all_wpdb_results(
444
+			array(
445
+				$where,
446
+				'group_by' => 'regDate',
447
+				'order_by' => array('REG_date' => 'ASC'),
448
+			),
449
+			OBJECT,
450
+			array(
451
+				'regDate' => array('DATE(' . $query_interval . ')', '%s'),
452
+				'total'   => array('count(REG_ID)', '%d'),
453
+			));
454
+		return $results;
455
+	}
456
+
457
+
458
+
459
+	/**
460
+	 * Get the number of registrations per day including the count of registrations for each Registration Status.
461
+	 * Note: EEM_Registration::status_id_incomplete registrations are excluded from the results.
462
+	 *
463
+	 * @param string $period
464
+	 * @return stdClass[] with properties Registration_REG_date and a column for each registration status as the STS_ID
465
+	 *                    (i.e. RAP)
466
+	 */
467
+	public function get_registrations_per_day_and_per_status_report($period = '-1 month')
468
+	{
469
+		global $wpdb;
470
+		$registration_table = $wpdb->prefix . 'esp_registration';
471
+		$event_table = $wpdb->posts;
472
+		$sql_date = date("Y-m-d H:i:s", strtotime($period));
473
+		//prepare the query interval for displaying offset
474
+		$query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'dates.REG_date');
475
+		//inner date query
476
+		$inner_date_query = "SELECT DISTINCT REG_date from $registration_table ";
477
+		$inner_where = " WHERE";
478
+		//exclude events not authored by user if permissions in effect
479
+		if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
480
+			$inner_date_query .= "LEFT JOIN $event_table ON ID = EVT_ID";
481
+			$inner_where .= " post_author = " . get_current_user_id() . " AND";
482
+		}
483
+		$inner_where .= " REG_date >= '$sql_date'";
484
+		$inner_date_query .= $inner_where;
485
+		//start main query
486
+		$select = "SELECT DATE($query_interval) as Registration_REG_date, ";
487
+		$join = '';
488
+		$join_parts = array();
489
+		$select_parts = array();
490
+		//loop through registration stati to do parts for each status.
491
+		foreach (EEM_Registration::reg_status_array() as $STS_ID => $STS_code) {
492
+			if ($STS_ID === EEM_Registration::status_id_incomplete) {
493
+				continue;
494
+			}
495
+			$select_parts[] = "COUNT($STS_code.REG_ID) as $STS_ID";
496
+			$join_parts[] = "$registration_table AS $STS_code ON $STS_code.REG_date = dates.REG_date AND $STS_code.STS_ID = '$STS_ID'";
497
+		}
498
+		//setup the selects
499
+		$select .= implode(', ', $select_parts);
500
+		$select .= " FROM ($inner_date_query) AS dates LEFT JOIN ";
501
+		//setup the joins
502
+		$join .= implode(" LEFT JOIN ", $join_parts);
503
+		//now let's put it all together
504
+		$query = $select . $join . ' GROUP BY Registration_REG_date';
505
+		//and execute it
506
+		$results = $wpdb->get_results($query, ARRAY_A);
507
+		return $results;
508
+	}
509
+
510
+
511
+
512
+	/**
513
+	 *        get the number of registrations per event  for the Registration Admin page Reports Tab
514
+	 *
515
+	 * @access        public
516
+	 * @param $period string which can be passed to php's strtotime function (eg "-1 month")
517
+	 * @return stdClass[] each with properties event_name, reg_limit, and total
518
+	 */
519
+	public function get_registrations_per_event_report($period = '-1 month')
520
+	{
521
+		$date_sql = $this->convert_datetime_for_query('REG_date', date("Y-m-d H:i:s", strtotime($period)),
522
+			'Y-m-d H:i:s', 'UTC');
523
+		$where = array(
524
+			'REG_date' => array('>=', $date_sql),
525
+			'STS_ID'   => array('!=', EEM_Registration::status_id_incomplete),
526
+		);
527
+		if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
528
+			$where['Event.EVT_wp_user'] = get_current_user_id();
529
+		}
530
+		$results = $this->_get_all_wpdb_results(array(
531
+			$where,
532
+			'group_by' => 'Event.EVT_name',
533
+			'order_by' => 'Event.EVT_name',
534
+			'limit'    => array(0, 24),
535
+		),
536
+			OBJECT,
537
+			array(
538
+				'event_name' => array('Event_CPT.post_title', '%s'),
539
+				'total'      => array('COUNT(REG_ID)', '%s'),
540
+			)
541
+		);
542
+		return $results;
543
+	}
544
+
545
+
546
+
547
+	/**
548
+	 * Get the number of registrations per event grouped by registration status.
549
+	 * Note: EEM_Registration::status_id_incomplete registrations are excluded from the results.
550
+	 *
551
+	 * @param string $period
552
+	 * @return stdClass[] with properties `Registration_Event` and a column for each registration status as the STS_ID
553
+	 *                    (i.e. RAP)
554
+	 */
555
+	public function get_registrations_per_event_and_per_status_report($period = '-1 month')
556
+	{
557
+		global $wpdb;
558
+		$registration_table = $wpdb->prefix . 'esp_registration';
559
+		$event_table = $wpdb->posts;
560
+		$sql_date = date("Y-m-d H:i:s", strtotime($period));
561
+		//inner date query
562
+		$inner_date_query = "SELECT DISTINCT EVT_ID, REG_date from $registration_table ";
563
+		$inner_where = " WHERE";
564
+		//exclude events not authored by user if permissions in effect
565
+		if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
566
+			$inner_date_query .= "LEFT JOIN $event_table ON ID = EVT_ID";
567
+			$inner_where .= " post_author = " . get_current_user_id() . " AND";
568
+		}
569
+		$inner_where .= " REG_date >= '$sql_date'";
570
+		$inner_date_query .= $inner_where;
571
+		//build main query
572
+		$select = "SELECT Event.post_title as Registration_Event, ";
573
+		$join = '';
574
+		$join_parts = array();
575
+		$select_parts = array();
576
+		//loop through registration stati to do parts for each status.
577
+		foreach (EEM_Registration::reg_status_array() as $STS_ID => $STS_code) {
578
+			if ($STS_ID === EEM_Registration::status_id_incomplete) {
579
+				continue;
580
+			}
581
+			$select_parts[] = "COUNT($STS_code.REG_ID) as $STS_ID";
582
+			$join_parts[] = "$registration_table AS $STS_code ON $STS_code.EVT_ID = dates.EVT_ID AND $STS_code.STS_ID = '$STS_ID' AND $STS_code.REG_date = dates.REG_date";
583
+		}
584
+		//setup the selects
585
+		$select .= implode(', ', $select_parts);
586
+		$select .= " FROM ($inner_date_query) AS dates LEFT JOIN $event_table as Event ON Event.ID = dates.EVT_ID LEFT JOIN ";
587
+		//setup remaining joins
588
+		$join .= implode(" LEFT JOIN ", $join_parts);
589
+		//now put it all together
590
+		$query = $select . $join . ' GROUP BY Registration_Event';
591
+		//and execute
592
+		$results = $wpdb->get_results($query, ARRAY_A);
593
+		return $results;
594
+	}
595
+
596
+
597
+
598
+	/**
599
+	 * Returns the EE_Registration of the primary attendee on the transaction id provided
600
+	 *
601
+	 * @param int $TXN_ID
602
+	 * @return EE_Registration
603
+	 */
604
+	public function get_primary_registration_for_transaction_ID($TXN_ID = 0)
605
+	{
606
+		if ( ! $TXN_ID) {
607
+			return false;
608
+		}
609
+		return $this->get_one(array(
610
+			array(
611
+				'TXN_ID'    => $TXN_ID,
612
+				'REG_count' => EEM_Registration::PRIMARY_REGISTRANT_COUNT,
613
+			),
614
+		));
615
+	}
616
+
617
+
618
+
619
+	/**
620
+	 *        get_event_registration_count
621
+	 *
622
+	 * @access public
623
+	 * @param int     $EVT_ID
624
+	 * @param boolean $for_incomplete_payments
625
+	 * @return int
626
+	 */
627
+	public function get_event_registration_count($EVT_ID, $for_incomplete_payments = false)
628
+	{
629
+		// we only count approved registrations towards registration limits
630
+		$query_params = array(array('EVT_ID' => $EVT_ID, 'STS_ID' => self::status_id_approved));
631
+		if ($for_incomplete_payments) {
632
+			$query_params[0]['Transaction.STS_ID'] = array('!=', EEM_Transaction::complete_status_code);
633
+		}
634
+		return $this->count($query_params);
635
+	}
636
+
637
+
638
+
639
+	/**
640
+	 * Deletes all registrations with no transactions. Note that this needs to be very efficient
641
+	 * and so it uses wpdb directly
642
+	 *
643
+	 * @global WPDB $wpdb
644
+	 * @return int number deleted
645
+	 */
646
+	public function delete_registrations_with_no_transaction()
647
+	{
648
+		/** @type WPDB $wpdb */
649
+		global $wpdb;
650
+		return $wpdb->query(
651
+			'DELETE r FROM '
652
+			. $this->table()
653
+			. ' r LEFT JOIN '
654
+			. EEM_Transaction::instance()->table()
655
+			. ' t ON r.TXN_ID = t.TXN_ID WHERE t.TXN_ID IS NULL');
656
+	}
657
+
658
+
659
+
660
+	/**
661
+	 *  Count registrations checked into (or out of) a datetime
662
+	 *
663
+	 * @param int     $DTT_ID     datetime ID
664
+	 * @param boolean $checked_in whether to count registrations checked IN or OUT
665
+	 * @return int
666
+	 */
667
+	public function count_registrations_checked_into_datetime($DTT_ID, $checked_in = true)
668
+	{
669
+		global $wpdb;
670
+		//subquery to get latest checkin
671
+		$query = $wpdb->prepare(
672
+			'SELECT '
673
+			. 'COUNT( DISTINCT checkins.REG_ID ) '
674
+			. 'FROM ' . EEM_Checkin::instance()->table() . ' AS checkins INNER JOIN'
675
+			. '( SELECT '
676
+			. 'max( CHK_timestamp ) AS latest_checkin, '
677
+			. 'REG_ID AS REG_ID '
678
+			. 'FROM ' . EEM_Checkin::instance()->table() . ' '
679
+			. 'WHERE DTT_ID=%d '
680
+			. 'GROUP BY REG_ID'
681
+			. ') AS most_recent_checkin_per_reg '
682
+			. 'ON checkins.REG_ID=most_recent_checkin_per_reg.REG_ID '
683
+			. 'AND checkins.CHK_timestamp = most_recent_checkin_per_reg.latest_checkin '
684
+			. 'WHERE '
685
+			. 'checkins.CHK_in=%d',
686
+			$DTT_ID,
687
+			$checked_in
688
+		);
689
+		return (int)$wpdb->get_var($query);
690
+	}
691
+
692
+
693
+
694
+	/**
695
+	 *  Count registrations checked into (or out of) an event.
696
+	 *
697
+	 * @param int     $EVT_ID     event ID
698
+	 * @param boolean $checked_in whether to count registrations checked IN or OUT
699
+	 * @return int
700
+	 */
701
+	public function count_registrations_checked_into_event($EVT_ID, $checked_in = true)
702
+	{
703
+		global $wpdb;
704
+		//subquery to get latest checkin
705
+		$query = $wpdb->prepare(
706
+			'SELECT '
707
+			. 'COUNT( DISTINCT checkins.REG_ID ) '
708
+			. 'FROM ' . EEM_Checkin::instance()->table() . ' AS checkins INNER JOIN'
709
+			. '( SELECT '
710
+			. 'max( CHK_timestamp ) AS latest_checkin, '
711
+			. 'REG_ID AS REG_ID '
712
+			. 'FROM ' . EEM_Checkin::instance()->table() . ' AS c '
713
+			. 'INNER JOIN ' . EEM_Datetime::instance()->table() . ' AS d '
714
+			. 'ON c.DTT_ID=d.DTT_ID '
715
+			. 'WHERE d.EVT_ID=%d '
716
+			. 'GROUP BY REG_ID'
717
+			. ') AS most_recent_checkin_per_reg '
718
+			. 'ON checkins.REG_ID=most_recent_checkin_per_reg.REG_ID '
719
+			. 'AND checkins.CHK_timestamp = most_recent_checkin_per_reg.latest_checkin '
720
+			. 'WHERE '
721
+			. 'checkins.CHK_in=%d',
722
+			$EVT_ID,
723
+			$checked_in
724
+		);
725
+		return (int)$wpdb->get_var($query);
726
+	}
727
+
728
+
729
+
730
+	/**
731
+	 * The purpose of this method is to retrieve an array of
732
+	 * EE_Registration objects that represent the latest registration
733
+	 * for each ATT_ID given in the function argument.
734
+	 *
735
+	 * @param array $attendee_ids
736
+	 * @return EE_Registration[]
737
+	 */
738
+	public function get_latest_registration_for_each_of_given_contacts($attendee_ids = array())
739
+	{
740
+		//first do a native wp_query to get the latest REG_ID's matching these attendees.
741
+		global $wpdb;
742
+		$registration_table = $wpdb->prefix . 'esp_registration';
743
+		$attendee_table = $wpdb->posts;
744
+		$attendee_ids = is_array($attendee_ids)
745
+			? array_map('absint', $attendee_ids)
746
+			: array((int)$attendee_ids);
747
+		$attendee_ids = implode(',', $attendee_ids);
748
+		//first we do a query to get the registration ids
749
+		// (because a group by before order by causes the order by to be ignored.)
750
+		$registration_id_query = "
751 751
 			SELECT registrations.registration_ids as registration_id
752 752
 			FROM (
753 753
 				SELECT
@@ -761,23 +761,23 @@  discard block
 block discarded – undo
761 761
 			  ) AS registrations
762 762
 			  GROUP BY registrations.attendee_ids
763 763
 		";
764
-        $registration_ids = $wpdb->get_results($registration_id_query, ARRAY_A);
765
-        if (empty($registration_ids)) {
766
-            return array();
767
-        }
768
-        $ids_for_model_query = array();
769
-        //let's flatten the ids so they can be used in the model query.
770
-        foreach ($registration_ids as $registration_id) {
771
-            if (isset($registration_id['registration_id'])) {
772
-                $ids_for_model_query[] = $registration_id['registration_id'];
773
-            }
774
-        }
775
-        //construct query
776
-        $_where = array(
777
-            'REG_ID' => array('IN', $ids_for_model_query),
778
-        );
779
-        return $this->get_all(array($_where));
780
-    }
764
+		$registration_ids = $wpdb->get_results($registration_id_query, ARRAY_A);
765
+		if (empty($registration_ids)) {
766
+			return array();
767
+		}
768
+		$ids_for_model_query = array();
769
+		//let's flatten the ids so they can be used in the model query.
770
+		foreach ($registration_ids as $registration_id) {
771
+			if (isset($registration_id['registration_id'])) {
772
+				$ids_for_model_query[] = $registration_id['registration_id'];
773
+			}
774
+		}
775
+		//construct query
776
+		$_where = array(
777
+			'REG_ID' => array('IN', $ids_for_model_query),
778
+		);
779
+		return $this->get_all(array($_where));
780
+	}
781 781
 
782 782
 
783 783
 
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
         //and the table hasn't actually been created, this could have an error
305 305
         /** @type WPDB $wpdb */
306 306
         global $wpdb;
307
-        if ($this->_get_table_analysis()->tableExists($wpdb->prefix . 'esp_status')) {
307
+        if ($this->_get_table_analysis()->tableExists($wpdb->prefix.'esp_status')) {
308 308
             $results = $wpdb->get_results(
309 309
                 "SELECT STS_ID, STS_code FROM {$wpdb->prefix}esp_status WHERE STS_type = 'registration'"
310 310
             );
@@ -448,7 +448,7 @@  discard block
 block discarded – undo
448 448
             ),
449 449
             OBJECT,
450 450
             array(
451
-                'regDate' => array('DATE(' . $query_interval . ')', '%s'),
451
+                'regDate' => array('DATE('.$query_interval.')', '%s'),
452 452
                 'total'   => array('count(REG_ID)', '%d'),
453 453
             ));
454 454
         return $results;
@@ -467,7 +467,7 @@  discard block
 block discarded – undo
467 467
     public function get_registrations_per_day_and_per_status_report($period = '-1 month')
468 468
     {
469 469
         global $wpdb;
470
-        $registration_table = $wpdb->prefix . 'esp_registration';
470
+        $registration_table = $wpdb->prefix.'esp_registration';
471 471
         $event_table = $wpdb->posts;
472 472
         $sql_date = date("Y-m-d H:i:s", strtotime($period));
473 473
         //prepare the query interval for displaying offset
@@ -478,7 +478,7 @@  discard block
 block discarded – undo
478 478
         //exclude events not authored by user if permissions in effect
479 479
         if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
480 480
             $inner_date_query .= "LEFT JOIN $event_table ON ID = EVT_ID";
481
-            $inner_where .= " post_author = " . get_current_user_id() . " AND";
481
+            $inner_where .= " post_author = ".get_current_user_id()." AND";
482 482
         }
483 483
         $inner_where .= " REG_date >= '$sql_date'";
484 484
         $inner_date_query .= $inner_where;
@@ -501,7 +501,7 @@  discard block
 block discarded – undo
501 501
         //setup the joins
502 502
         $join .= implode(" LEFT JOIN ", $join_parts);
503 503
         //now let's put it all together
504
-        $query = $select . $join . ' GROUP BY Registration_REG_date';
504
+        $query = $select.$join.' GROUP BY Registration_REG_date';
505 505
         //and execute it
506 506
         $results = $wpdb->get_results($query, ARRAY_A);
507 507
         return $results;
@@ -555,7 +555,7 @@  discard block
 block discarded – undo
555 555
     public function get_registrations_per_event_and_per_status_report($period = '-1 month')
556 556
     {
557 557
         global $wpdb;
558
-        $registration_table = $wpdb->prefix . 'esp_registration';
558
+        $registration_table = $wpdb->prefix.'esp_registration';
559 559
         $event_table = $wpdb->posts;
560 560
         $sql_date = date("Y-m-d H:i:s", strtotime($period));
561 561
         //inner date query
@@ -564,7 +564,7 @@  discard block
 block discarded – undo
564 564
         //exclude events not authored by user if permissions in effect
565 565
         if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
566 566
             $inner_date_query .= "LEFT JOIN $event_table ON ID = EVT_ID";
567
-            $inner_where .= " post_author = " . get_current_user_id() . " AND";
567
+            $inner_where .= " post_author = ".get_current_user_id()." AND";
568 568
         }
569 569
         $inner_where .= " REG_date >= '$sql_date'";
570 570
         $inner_date_query .= $inner_where;
@@ -587,7 +587,7 @@  discard block
 block discarded – undo
587 587
         //setup remaining joins
588 588
         $join .= implode(" LEFT JOIN ", $join_parts);
589 589
         //now put it all together
590
-        $query = $select . $join . ' GROUP BY Registration_Event';
590
+        $query = $select.$join.' GROUP BY Registration_Event';
591 591
         //and execute
592 592
         $results = $wpdb->get_results($query, ARRAY_A);
593 593
         return $results;
@@ -671,11 +671,11 @@  discard block
 block discarded – undo
671 671
         $query = $wpdb->prepare(
672 672
             'SELECT '
673 673
             . 'COUNT( DISTINCT checkins.REG_ID ) '
674
-            . 'FROM ' . EEM_Checkin::instance()->table() . ' AS checkins INNER JOIN'
674
+            . 'FROM '.EEM_Checkin::instance()->table().' AS checkins INNER JOIN'
675 675
             . '( SELECT '
676 676
             . 'max( CHK_timestamp ) AS latest_checkin, '
677 677
             . 'REG_ID AS REG_ID '
678
-            . 'FROM ' . EEM_Checkin::instance()->table() . ' '
678
+            . 'FROM '.EEM_Checkin::instance()->table().' '
679 679
             . 'WHERE DTT_ID=%d '
680 680
             . 'GROUP BY REG_ID'
681 681
             . ') AS most_recent_checkin_per_reg '
@@ -686,7 +686,7 @@  discard block
 block discarded – undo
686 686
             $DTT_ID,
687 687
             $checked_in
688 688
         );
689
-        return (int)$wpdb->get_var($query);
689
+        return (int) $wpdb->get_var($query);
690 690
     }
691 691
 
692 692
 
@@ -705,12 +705,12 @@  discard block
 block discarded – undo
705 705
         $query = $wpdb->prepare(
706 706
             'SELECT '
707 707
             . 'COUNT( DISTINCT checkins.REG_ID ) '
708
-            . 'FROM ' . EEM_Checkin::instance()->table() . ' AS checkins INNER JOIN'
708
+            . 'FROM '.EEM_Checkin::instance()->table().' AS checkins INNER JOIN'
709 709
             . '( SELECT '
710 710
             . 'max( CHK_timestamp ) AS latest_checkin, '
711 711
             . 'REG_ID AS REG_ID '
712
-            . 'FROM ' . EEM_Checkin::instance()->table() . ' AS c '
713
-            . 'INNER JOIN ' . EEM_Datetime::instance()->table() . ' AS d '
712
+            . 'FROM '.EEM_Checkin::instance()->table().' AS c '
713
+            . 'INNER JOIN '.EEM_Datetime::instance()->table().' AS d '
714 714
             . 'ON c.DTT_ID=d.DTT_ID '
715 715
             . 'WHERE d.EVT_ID=%d '
716 716
             . 'GROUP BY REG_ID'
@@ -722,7 +722,7 @@  discard block
 block discarded – undo
722 722
             $EVT_ID,
723 723
             $checked_in
724 724
         );
725
-        return (int)$wpdb->get_var($query);
725
+        return (int) $wpdb->get_var($query);
726 726
     }
727 727
 
728 728
 
@@ -739,11 +739,11 @@  discard block
 block discarded – undo
739 739
     {
740 740
         //first do a native wp_query to get the latest REG_ID's matching these attendees.
741 741
         global $wpdb;
742
-        $registration_table = $wpdb->prefix . 'esp_registration';
742
+        $registration_table = $wpdb->prefix.'esp_registration';
743 743
         $attendee_table = $wpdb->posts;
744 744
         $attendee_ids = is_array($attendee_ids)
745 745
             ? array_map('absint', $attendee_ids)
746
-            : array((int)$attendee_ids);
746
+            : array((int) $attendee_ids);
747 747
         $attendee_ids = implode(',', $attendee_ids);
748 748
         //first we do a query to get the registration ids
749 749
         // (because a group by before order by causes the order by to be ignored.)
Please login to merge, or discard this patch.
core/EE_Cron_Tasks.core.php 2 patches
Indentation   +444 added lines, -444 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 /**
@@ -12,160 +12,160 @@  discard block
 block discarded – undo
12 12
 class EE_Cron_Tasks extends EE_Base
13 13
 {
14 14
 
15
-    /**
16
-     * WordPress doesn't allow duplicate crons within 10 minutes of the original,
17
-     * so we'll set our retry time for just over 10 minutes to avoid that
18
-     */
19
-    const reschedule_timeout = 605;
20
-
21
-
22
-    /**
23
-     * @var EE_Cron_Tasks
24
-     */
25
-    private static $_instance;
26
-
27
-
28
-    /**
29
-     * @return EE_Cron_Tasks
30
-     */
31
-    public static function instance()
32
-    {
33
-        if ( ! self::$_instance instanceof EE_Cron_Tasks) {
34
-            self::$_instance = new self();
35
-        }
36
-        return self::$_instance;
37
-    }
38
-
39
-
40
-    /**
41
-     * @access private
42
-     */
43
-    private function __construct()
44
-    {
45
-        do_action('AHEE_log', __CLASS__, __FUNCTION__);
46
-        // verify that WP Cron is enabled
47
-        if (
48
-            defined('DISABLE_WP_CRON')
49
-            && DISABLE_WP_CRON
50
-            && is_admin()
51
-            && ! get_option('ee_disabled_wp_cron_check')
52
-        ) {
53
-            /**
54
-             * This needs to be delayed until after the config is loaded because EE_Cron_Tasks is constructed before
55
-             * config is loaded.
56
-             * This is intentionally using a anonymous function so that its not easily de-registered.  Client code
57
-             * wanting to not have this functionality can just register its own action at a priority after this one to
58
-             * reverse any changes.
59
-             */
60
-            add_action('AHEE__EE_System__load_core_configuration__complete', function () {
61
-                EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request = true;
62
-                EE_Registry::instance()->NET_CFG->update_config(true, false);
63
-                add_option('ee_disabled_wp_cron_check', 1, '', false);
64
-            });
65
-        }
66
-        // UPDATE TRANSACTION WITH PAYMENT
67
-        add_action(
68
-            'AHEE__EE_Cron_Tasks__update_transaction_with_payment_2',
69
-            array('EE_Cron_Tasks', 'setup_update_for_transaction_with_payment'),
70
-            10, 2
71
-        );
72
-        // FINALIZE ABANDONED TRANSACTIONS
73
-        add_action(
74
-            'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions',
75
-            array('EE_Cron_Tasks', 'check_for_abandoned_transactions'),
76
-            10, 1
77
-        );
15
+	/**
16
+	 * WordPress doesn't allow duplicate crons within 10 minutes of the original,
17
+	 * so we'll set our retry time for just over 10 minutes to avoid that
18
+	 */
19
+	const reschedule_timeout = 605;
20
+
21
+
22
+	/**
23
+	 * @var EE_Cron_Tasks
24
+	 */
25
+	private static $_instance;
26
+
27
+
28
+	/**
29
+	 * @return EE_Cron_Tasks
30
+	 */
31
+	public static function instance()
32
+	{
33
+		if ( ! self::$_instance instanceof EE_Cron_Tasks) {
34
+			self::$_instance = new self();
35
+		}
36
+		return self::$_instance;
37
+	}
38
+
39
+
40
+	/**
41
+	 * @access private
42
+	 */
43
+	private function __construct()
44
+	{
45
+		do_action('AHEE_log', __CLASS__, __FUNCTION__);
46
+		// verify that WP Cron is enabled
47
+		if (
48
+			defined('DISABLE_WP_CRON')
49
+			&& DISABLE_WP_CRON
50
+			&& is_admin()
51
+			&& ! get_option('ee_disabled_wp_cron_check')
52
+		) {
53
+			/**
54
+			 * This needs to be delayed until after the config is loaded because EE_Cron_Tasks is constructed before
55
+			 * config is loaded.
56
+			 * This is intentionally using a anonymous function so that its not easily de-registered.  Client code
57
+			 * wanting to not have this functionality can just register its own action at a priority after this one to
58
+			 * reverse any changes.
59
+			 */
60
+			add_action('AHEE__EE_System__load_core_configuration__complete', function () {
61
+				EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request = true;
62
+				EE_Registry::instance()->NET_CFG->update_config(true, false);
63
+				add_option('ee_disabled_wp_cron_check', 1, '', false);
64
+			});
65
+		}
66
+		// UPDATE TRANSACTION WITH PAYMENT
67
+		add_action(
68
+			'AHEE__EE_Cron_Tasks__update_transaction_with_payment_2',
69
+			array('EE_Cron_Tasks', 'setup_update_for_transaction_with_payment'),
70
+			10, 2
71
+		);
72
+		// FINALIZE ABANDONED TRANSACTIONS
73
+		add_action(
74
+			'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions',
75
+			array('EE_Cron_Tasks', 'check_for_abandoned_transactions'),
76
+			10, 1
77
+		);
78 78
 		// EXPIRED TRANSACTION CHECK
79 79
 		add_action(
80 80
 			'AHEE__EE_Cron_Tasks__expired_transaction_check',
81 81
 			array( 'EE_Cron_Tasks', 'expired_transaction_check' ),
82 82
 			10, 1
83 83
 		);
84
-        // CLEAN OUT JUNK TRANSACTIONS AND RELATED DATA
85
-        add_action(
86
-            'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
87
-            array('EE_Cron_Tasks', 'clean_out_junk_transactions')
88
-        );
89
-        // logging
90
-        add_action(
91
-            'AHEE__EE_System__load_core_configuration__complete',
92
-            array('EE_Cron_Tasks', 'log_scheduled_ee_crons')
93
-        );
94
-        EE_Registry::instance()->load_lib('Messages_Scheduler');
95
-    }
96
-
97
-
98
-    /**
99
-     * @access protected
100
-     * @return void
101
-     */
102
-    public static function log_scheduled_ee_crons()
103
-    {
104
-        $ee_crons = array(
105
-            'AHEE__EE_Cron_Tasks__update_transaction_with_payment',
106
-            'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions',
107
-            'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
108
-        );
109
-        $crons = (array) get_option('cron');
110
-        if ( ! is_array($crons)) {
111
-            return;
112
-        }
113
-        foreach ($crons as $timestamp => $cron) {
114
-            foreach ($ee_crons as $ee_cron) {
115
-                if (isset($cron[$ee_cron]) && is_array($cron[$ee_cron])) {
116
-                    do_action('AHEE_log', __CLASS__, __FUNCTION__, $ee_cron, 'scheduled EE cron');
117
-                    foreach ($cron[$ee_cron] as $ee_cron_details) {
118
-                        if ( ! empty($ee_cron_details['args'])) {
119
-                            do_action(
120
-                                'AHEE_log',
121
-                                __CLASS__,
122
-                                __FUNCTION__,
123
-                                print_r($ee_cron_details['args'], true),
124
-                                "{$ee_cron} args"
125
-                            );
126
-                        }
127
-                    }
128
-                }
129
-            }
130
-        }
131
-    }
132
-
133
-
134
-
135
-    /**
136
-     * reschedule_cron_for_transactions_if_maintenance_mode
137
-     * if Maintenance Mode is active, this will reschedule a cron to run again in 10 minutes
138
-     *
139
-     * @param string $cron_task
140
-     * @param array  $TXN_IDs
141
-     * @return bool
142
-     * @throws \DomainException
143
-     */
84
+		// CLEAN OUT JUNK TRANSACTIONS AND RELATED DATA
85
+		add_action(
86
+			'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
87
+			array('EE_Cron_Tasks', 'clean_out_junk_transactions')
88
+		);
89
+		// logging
90
+		add_action(
91
+			'AHEE__EE_System__load_core_configuration__complete',
92
+			array('EE_Cron_Tasks', 'log_scheduled_ee_crons')
93
+		);
94
+		EE_Registry::instance()->load_lib('Messages_Scheduler');
95
+	}
96
+
97
+
98
+	/**
99
+	 * @access protected
100
+	 * @return void
101
+	 */
102
+	public static function log_scheduled_ee_crons()
103
+	{
104
+		$ee_crons = array(
105
+			'AHEE__EE_Cron_Tasks__update_transaction_with_payment',
106
+			'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions',
107
+			'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
108
+		);
109
+		$crons = (array) get_option('cron');
110
+		if ( ! is_array($crons)) {
111
+			return;
112
+		}
113
+		foreach ($crons as $timestamp => $cron) {
114
+			foreach ($ee_crons as $ee_cron) {
115
+				if (isset($cron[$ee_cron]) && is_array($cron[$ee_cron])) {
116
+					do_action('AHEE_log', __CLASS__, __FUNCTION__, $ee_cron, 'scheduled EE cron');
117
+					foreach ($cron[$ee_cron] as $ee_cron_details) {
118
+						if ( ! empty($ee_cron_details['args'])) {
119
+							do_action(
120
+								'AHEE_log',
121
+								__CLASS__,
122
+								__FUNCTION__,
123
+								print_r($ee_cron_details['args'], true),
124
+								"{$ee_cron} args"
125
+							);
126
+						}
127
+					}
128
+				}
129
+			}
130
+		}
131
+	}
132
+
133
+
134
+
135
+	/**
136
+	 * reschedule_cron_for_transactions_if_maintenance_mode
137
+	 * if Maintenance Mode is active, this will reschedule a cron to run again in 10 minutes
138
+	 *
139
+	 * @param string $cron_task
140
+	 * @param array  $TXN_IDs
141
+	 * @return bool
142
+	 * @throws \DomainException
143
+	 */
144 144
 	public static function reschedule_cron_for_transactions_if_maintenance_mode( $cron_task, array $TXN_IDs ) {
145
-        if( ! method_exists('EE_Cron_Tasks', $cron_task)) {
146
-            throw new \DomainException(
147
-                sprintf(
148
-                    __('"%1$s" is not valid method on EE_Cron_Tasks.', 'event_espresso'),
149
-                    $cron_task
150
-                )
151
-            );
152
-        }
145
+		if( ! method_exists('EE_Cron_Tasks', $cron_task)) {
146
+			throw new \DomainException(
147
+				sprintf(
148
+					__('"%1$s" is not valid method on EE_Cron_Tasks.', 'event_espresso'),
149
+					$cron_task
150
+				)
151
+			);
152
+		}
153 153
 		// reschedule the cron if we can't hit the db right now
154 154
 		if ( ! EE_Maintenance_Mode::instance()->models_can_query() ) {
155 155
 			foreach( $TXN_IDs as $TXN_ID => $additional_vars ) {
156
-                // ensure $additional_vars is an array
157
-                $additional_vars = is_array($additional_vars) ? $additional_vars : array($additional_vars);
156
+				// ensure $additional_vars is an array
157
+				$additional_vars = is_array($additional_vars) ? $additional_vars : array($additional_vars);
158 158
 				// reset cron job for the TXN
159
-                call_user_func_array(
160
-                    array('EE_Cron_Tasks', $cron_task),
161
-                    array_merge(
162
-                        array(
163
-                            time() + (10 * MINUTE_IN_SECONDS),
164
-                            $TXN_ID
165
-                        ),
166
-                        $additional_vars
167
-                    )
168
-                );
159
+				call_user_func_array(
160
+					array('EE_Cron_Tasks', $cron_task),
161
+					array_merge(
162
+						array(
163
+							time() + (10 * MINUTE_IN_SECONDS),
164
+							$TXN_ID
165
+						),
166
+						$additional_vars
167
+					)
168
+				);
169 169
 			}
170 170
 			return true;
171 171
 		}
@@ -175,85 +175,85 @@  discard block
 block discarded – undo
175 175
 
176 176
 
177 177
 
178
-    /****************  UPDATE TRANSACTION WITH PAYMENT ****************/
179
-
180
-
181
-    /**
182
-     * array of TXN IDs and the payment
183
-     *
184
-     * @var array
185
-     */
186
-    protected static $_update_transactions_with_payment = array();
187
-
188
-
189
-    /**
190
-     * schedule_update_transaction_with_payment
191
-     * sets a wp_schedule_single_event() for updating any TXNs that may
192
-     * require updating due to recently received payments
193
-     *
194
-     * @param int $timestamp
195
-     * @param int $TXN_ID
196
-     * @param int $PAY_ID
197
-     */
198
-    public static function schedule_update_transaction_with_payment(
199
-        $timestamp,
200
-        $TXN_ID,
201
-        $PAY_ID
202
-    ) {
203
-        do_action('AHEE_log', __CLASS__, __FUNCTION__);
204
-        // validate $TXN_ID and $timestamp
205
-        $TXN_ID    = absint($TXN_ID);
206
-        $timestamp = absint($timestamp);
207
-        if ($TXN_ID && $timestamp) {
208
-            wp_schedule_single_event(
209
-                $timestamp,
210
-                'AHEE__EE_Cron_Tasks__update_transaction_with_payment_2',
211
-                array($TXN_ID, $PAY_ID)
212
-            );
213
-        }
214
-    }
215
-
216
-
217
-    /**
218
-     * setup_update_for_transaction_with_payment
219
-     * this is the callback for the action hook:
220
-     * 'AHEE__EE_Cron_Tasks__update_transaction_with_payment'
221
-     * which is setup by EE_Cron_Tasks::schedule_update_transaction_with_payment().
222
-     * The passed TXN_ID and associated payment gets added to an array, and then
223
-     * the EE_Cron_Tasks::update_transaction_with_payment() function is hooked into
224
-     * 'shutdown' which will actually handle the processing of any
225
-     * transactions requiring updating, because doing so now would be too early
226
-     * and the required resources may not be available
227
-     *
228
-     * @param int $TXN_ID
229
-     * @param int $PAY_ID
230
-     */
231
-    public static function setup_update_for_transaction_with_payment($TXN_ID = 0, $PAY_ID = 0)
232
-    {
233
-        do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
234
-        if (absint($TXN_ID)) {
235
-            self::$_update_transactions_with_payment[$TXN_ID] = $PAY_ID;
236
-            add_action(
237
-                'shutdown',
238
-                array('EE_Cron_Tasks', 'update_transaction_with_payment'),
239
-                5
240
-            );
241
-        }
242
-    }
243
-
244
-
245
-    /**
246
-     * update_transaction_with_payment
247
-     * loops through the self::$_abandoned_transactions array
248
-     * and attempts to finalize any TXNs that have not been completed
249
-     * but have had their sessions expired, most likely due to a user not
250
-     * returning from an off-site payment gateway
251
-     *
252
-     * @throws \EE_Error
253
-     */
254
-    public static function update_transaction_with_payment()
255
-    {
256
-        do_action('AHEE_log', __CLASS__, __FUNCTION__);
178
+	/****************  UPDATE TRANSACTION WITH PAYMENT ****************/
179
+
180
+
181
+	/**
182
+	 * array of TXN IDs and the payment
183
+	 *
184
+	 * @var array
185
+	 */
186
+	protected static $_update_transactions_with_payment = array();
187
+
188
+
189
+	/**
190
+	 * schedule_update_transaction_with_payment
191
+	 * sets a wp_schedule_single_event() for updating any TXNs that may
192
+	 * require updating due to recently received payments
193
+	 *
194
+	 * @param int $timestamp
195
+	 * @param int $TXN_ID
196
+	 * @param int $PAY_ID
197
+	 */
198
+	public static function schedule_update_transaction_with_payment(
199
+		$timestamp,
200
+		$TXN_ID,
201
+		$PAY_ID
202
+	) {
203
+		do_action('AHEE_log', __CLASS__, __FUNCTION__);
204
+		// validate $TXN_ID and $timestamp
205
+		$TXN_ID    = absint($TXN_ID);
206
+		$timestamp = absint($timestamp);
207
+		if ($TXN_ID && $timestamp) {
208
+			wp_schedule_single_event(
209
+				$timestamp,
210
+				'AHEE__EE_Cron_Tasks__update_transaction_with_payment_2',
211
+				array($TXN_ID, $PAY_ID)
212
+			);
213
+		}
214
+	}
215
+
216
+
217
+	/**
218
+	 * setup_update_for_transaction_with_payment
219
+	 * this is the callback for the action hook:
220
+	 * 'AHEE__EE_Cron_Tasks__update_transaction_with_payment'
221
+	 * which is setup by EE_Cron_Tasks::schedule_update_transaction_with_payment().
222
+	 * The passed TXN_ID and associated payment gets added to an array, and then
223
+	 * the EE_Cron_Tasks::update_transaction_with_payment() function is hooked into
224
+	 * 'shutdown' which will actually handle the processing of any
225
+	 * transactions requiring updating, because doing so now would be too early
226
+	 * and the required resources may not be available
227
+	 *
228
+	 * @param int $TXN_ID
229
+	 * @param int $PAY_ID
230
+	 */
231
+	public static function setup_update_for_transaction_with_payment($TXN_ID = 0, $PAY_ID = 0)
232
+	{
233
+		do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
234
+		if (absint($TXN_ID)) {
235
+			self::$_update_transactions_with_payment[$TXN_ID] = $PAY_ID;
236
+			add_action(
237
+				'shutdown',
238
+				array('EE_Cron_Tasks', 'update_transaction_with_payment'),
239
+				5
240
+			);
241
+		}
242
+	}
243
+
244
+
245
+	/**
246
+	 * update_transaction_with_payment
247
+	 * loops through the self::$_abandoned_transactions array
248
+	 * and attempts to finalize any TXNs that have not been completed
249
+	 * but have had their sessions expired, most likely due to a user not
250
+	 * returning from an off-site payment gateway
251
+	 *
252
+	 * @throws \EE_Error
253
+	 */
254
+	public static function update_transaction_with_payment()
255
+	{
256
+		do_action('AHEE_log', __CLASS__, __FUNCTION__);
257 257
 		if (
258 258
 			// are there any TXNs that need cleaning up ?
259 259
 			empty( self::$_update_transactions_with_payment )
@@ -263,119 +263,119 @@  discard block
 block discarded – undo
263 263
 				self::$_update_transactions_with_payment
264 264
 			)
265 265
 		) {
266
-            return;
267
-        }
268
-        /** @type EE_Payment_Processor $payment_processor */
269
-        $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
270
-        // set revisit flag for payment processor
271
-        $payment_processor->set_revisit(false);
272
-        // load EEM_Transaction
273
-        EE_Registry::instance()->load_model('Transaction');
274
-        foreach (self::$_update_transactions_with_payment as $TXN_ID => $PAY_ID) {
275
-            // reschedule the cron if we can't hit the db right now
276
-            if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
277
-                // reset cron job for updating the TXN
278
-                EE_Cron_Tasks::schedule_update_transaction_with_payment(
279
-                    time() + EE_Cron_Tasks::reschedule_timeout,
280
-                    $TXN_ID,
281
-                    $PAY_ID
282
-                );
283
-                continue;
284
-            }
285
-            $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
286
-            $payment     = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
287
-            // verify transaction
288
-            if ($transaction instanceof EE_Transaction && $payment instanceof EE_Payment) {
289
-                // now try to update the TXN with any payments
290
-                $payment_processor->update_txn_based_on_payment($transaction, $payment, true, true);
291
-            }
292
-            unset(self::$_update_transactions_with_payment[$TXN_ID]);
293
-        }
294
-    }
295
-
296
-
297
-
298
-    /************  END OF UPDATE TRANSACTION WITH PAYMENT  ************/
299
-
300
-
301
-    /*****************  FINALIZE ABANDONED TRANSACTIONS *****************/
302
-
303
-
304
-    /**
305
-     * array of TXN IDs
306
-     *
307
-     * @var array
308
-     */
309
-    protected static $_abandoned_transactions = array();
310
-
311
-
312
-    /**
313
-     * schedule_finalize_abandoned_transactions_check
314
-     * sets a wp_schedule_single_event() for finalizing any TXNs that may
315
-     * have been abandoned during the registration process
316
-     *
317
-     * @param int $timestamp
318
-     * @param int $TXN_ID
319
-     */
320
-    public static function schedule_finalize_abandoned_transactions_check(
321
-        $timestamp,
322
-        $TXN_ID
323
-    ) {
324
-        // validate $TXN_ID and $timestamp
325
-        $TXN_ID    = absint($TXN_ID);
326
-        $timestamp = absint($timestamp);
327
-        do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
328
-        if ($TXN_ID && $timestamp) {
329
-            wp_schedule_single_event(
330
-                $timestamp,
331
-                'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions',
332
-                array($TXN_ID)
333
-            );
334
-        }
335
-    }
336
-
337
-
338
-    /**
339
-     * check_for_abandoned_transactions
340
-     * this is the callback for the action hook:
341
-     * 'AHEE__EE_Cron_Tasks__espresso_finalize_abandoned_transactions'
342
-     * which is utilized by wp_schedule_single_event()
343
-     * in EE_SPCO_Reg_Step_Payment_Options::_post_payment_processing().
344
-     * The passed TXN_ID gets added to an array, and then the
345
-     * espresso_finalize_abandoned_transactions() function is hooked into
346
-     * 'AHEE__EE_System__core_loaded_and_ready' which will actually handle the
347
-     * processing of any abandoned transactions, because doing so now would be
348
-     * too early and the required resources may not be available
349
-     *
350
-     * @param int $TXN_ID
351
-     */
352
-    public static function check_for_abandoned_transactions($TXN_ID = 0)
353
-    {
354
-        do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
355
-        if (absint($TXN_ID)) {
356
-            self::$_abandoned_transactions[] = $TXN_ID;
357
-            add_action(
358
-                'shutdown',
359
-                array('EE_Cron_Tasks', 'finalize_abandoned_transactions'),
360
-                5
361
-            );
362
-        }
363
-    }
364
-
365
-
366
-    /**
367
-     * finalize_abandoned_transactions
368
-     * loops through the self::$_abandoned_transactions array
369
-     * and attempts to finalize any TXNs that have not been completed
370
-     * but have had their sessions expired, most likely due to a user not
371
-     * returning from an off-site payment gateway
372
-     *
373
-     * @throws \EE_Error
374
-     */
375
-    public static function finalize_abandoned_transactions()
376
-    {
377
-        do_action('AHEE_log', __CLASS__, __FUNCTION__);
378
-        if (
266
+			return;
267
+		}
268
+		/** @type EE_Payment_Processor $payment_processor */
269
+		$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
270
+		// set revisit flag for payment processor
271
+		$payment_processor->set_revisit(false);
272
+		// load EEM_Transaction
273
+		EE_Registry::instance()->load_model('Transaction');
274
+		foreach (self::$_update_transactions_with_payment as $TXN_ID => $PAY_ID) {
275
+			// reschedule the cron if we can't hit the db right now
276
+			if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
277
+				// reset cron job for updating the TXN
278
+				EE_Cron_Tasks::schedule_update_transaction_with_payment(
279
+					time() + EE_Cron_Tasks::reschedule_timeout,
280
+					$TXN_ID,
281
+					$PAY_ID
282
+				);
283
+				continue;
284
+			}
285
+			$transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
286
+			$payment     = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
287
+			// verify transaction
288
+			if ($transaction instanceof EE_Transaction && $payment instanceof EE_Payment) {
289
+				// now try to update the TXN with any payments
290
+				$payment_processor->update_txn_based_on_payment($transaction, $payment, true, true);
291
+			}
292
+			unset(self::$_update_transactions_with_payment[$TXN_ID]);
293
+		}
294
+	}
295
+
296
+
297
+
298
+	/************  END OF UPDATE TRANSACTION WITH PAYMENT  ************/
299
+
300
+
301
+	/*****************  FINALIZE ABANDONED TRANSACTIONS *****************/
302
+
303
+
304
+	/**
305
+	 * array of TXN IDs
306
+	 *
307
+	 * @var array
308
+	 */
309
+	protected static $_abandoned_transactions = array();
310
+
311
+
312
+	/**
313
+	 * schedule_finalize_abandoned_transactions_check
314
+	 * sets a wp_schedule_single_event() for finalizing any TXNs that may
315
+	 * have been abandoned during the registration process
316
+	 *
317
+	 * @param int $timestamp
318
+	 * @param int $TXN_ID
319
+	 */
320
+	public static function schedule_finalize_abandoned_transactions_check(
321
+		$timestamp,
322
+		$TXN_ID
323
+	) {
324
+		// validate $TXN_ID and $timestamp
325
+		$TXN_ID    = absint($TXN_ID);
326
+		$timestamp = absint($timestamp);
327
+		do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
328
+		if ($TXN_ID && $timestamp) {
329
+			wp_schedule_single_event(
330
+				$timestamp,
331
+				'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions',
332
+				array($TXN_ID)
333
+			);
334
+		}
335
+	}
336
+
337
+
338
+	/**
339
+	 * check_for_abandoned_transactions
340
+	 * this is the callback for the action hook:
341
+	 * 'AHEE__EE_Cron_Tasks__espresso_finalize_abandoned_transactions'
342
+	 * which is utilized by wp_schedule_single_event()
343
+	 * in EE_SPCO_Reg_Step_Payment_Options::_post_payment_processing().
344
+	 * The passed TXN_ID gets added to an array, and then the
345
+	 * espresso_finalize_abandoned_transactions() function is hooked into
346
+	 * 'AHEE__EE_System__core_loaded_and_ready' which will actually handle the
347
+	 * processing of any abandoned transactions, because doing so now would be
348
+	 * too early and the required resources may not be available
349
+	 *
350
+	 * @param int $TXN_ID
351
+	 */
352
+	public static function check_for_abandoned_transactions($TXN_ID = 0)
353
+	{
354
+		do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
355
+		if (absint($TXN_ID)) {
356
+			self::$_abandoned_transactions[] = $TXN_ID;
357
+			add_action(
358
+				'shutdown',
359
+				array('EE_Cron_Tasks', 'finalize_abandoned_transactions'),
360
+				5
361
+			);
362
+		}
363
+	}
364
+
365
+
366
+	/**
367
+	 * finalize_abandoned_transactions
368
+	 * loops through the self::$_abandoned_transactions array
369
+	 * and attempts to finalize any TXNs that have not been completed
370
+	 * but have had their sessions expired, most likely due to a user not
371
+	 * returning from an off-site payment gateway
372
+	 *
373
+	 * @throws \EE_Error
374
+	 */
375
+	public static function finalize_abandoned_transactions()
376
+	{
377
+		do_action('AHEE_log', __CLASS__, __FUNCTION__);
378
+		if (
379 379
 			// are there any TXNs that need cleaning up ?
380 380
 			empty( self::$_abandoned_transactions )
381 381
 			// reschedule the cron if we can't hit the db right now
@@ -384,45 +384,45 @@  discard block
 block discarded – undo
384 384
 				self::$_abandoned_transactions
385 385
 			)
386 386
 		) {
387
-            return;
388
-        }
389
-        /** @type EE_Transaction_Processor $transaction_processor */
390
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
391
-        // set revisit flag for txn processor
392
-        $transaction_processor->set_revisit(false);
393
-        /** @type EE_Payment_Processor $payment_processor */
394
-        $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
395
-        // load EEM_Transaction
396
-        EE_Registry::instance()->load_model('Transaction');
397
-        foreach (self::$_abandoned_transactions as $TXN_ID) {
398
-            do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
399
-            // reschedule the cron if we can't hit the db right now
400
-            if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
401
-                // reset cron job for finalizing the TXN
402
-                EE_Cron_Tasks::schedule_finalize_abandoned_transactions_check(
403
-                    time() + EE_Cron_Tasks::reschedule_timeout,
404
-                    $TXN_ID
405
-                );
406
-                continue;
407
-            }
408
-            $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
409
-            // verify transaction
410
-            if ($transaction instanceof EE_Transaction) {
411
-                // don't finalize the TXN if it has already been completed
412
-                if ($transaction->all_reg_steps_completed() === true) {
413
-                    continue;
414
-                }
415
-                // let's simulate an IPN here which will trigger any notifications that need to go out
416
-                $payment_processor->update_txn_based_on_payment($transaction, $transaction->last_payment(), true,
417
-                    true);
418
-            }
419
-            unset(self::$_abandoned_transactions[$TXN_ID]);
420
-        }
421
-    }
422
-
423
-
424
-
425
-    /*************  END OF FINALIZE ABANDONED TRANSACTIONS  *************/
387
+			return;
388
+		}
389
+		/** @type EE_Transaction_Processor $transaction_processor */
390
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
391
+		// set revisit flag for txn processor
392
+		$transaction_processor->set_revisit(false);
393
+		/** @type EE_Payment_Processor $payment_processor */
394
+		$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
395
+		// load EEM_Transaction
396
+		EE_Registry::instance()->load_model('Transaction');
397
+		foreach (self::$_abandoned_transactions as $TXN_ID) {
398
+			do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
399
+			// reschedule the cron if we can't hit the db right now
400
+			if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
401
+				// reset cron job for finalizing the TXN
402
+				EE_Cron_Tasks::schedule_finalize_abandoned_transactions_check(
403
+					time() + EE_Cron_Tasks::reschedule_timeout,
404
+					$TXN_ID
405
+				);
406
+				continue;
407
+			}
408
+			$transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
409
+			// verify transaction
410
+			if ($transaction instanceof EE_Transaction) {
411
+				// don't finalize the TXN if it has already been completed
412
+				if ($transaction->all_reg_steps_completed() === true) {
413
+					continue;
414
+				}
415
+				// let's simulate an IPN here which will trigger any notifications that need to go out
416
+				$payment_processor->update_txn_based_on_payment($transaction, $transaction->last_payment(), true,
417
+					true);
418
+			}
419
+			unset(self::$_abandoned_transactions[$TXN_ID]);
420
+		}
421
+	}
422
+
423
+
424
+
425
+	/*************  END OF FINALIZE ABANDONED TRANSACTIONS  *************/
426 426
 
427 427
 
428 428
 	/*****************  EXPIRED TRANSACTION CHECK *****************/
@@ -491,12 +491,12 @@  discard block
 block discarded – undo
491 491
 
492 492
 
493 493
 
494
-    /**
495
-     * process_expired_transactions
496
-     * loops through the self::$_expired_transactions array and processes any failed TXNs
497
-     *
498
-     * @throws \EE_Error
499
-     */
494
+	/**
495
+	 * process_expired_transactions
496
+	 * loops through the self::$_expired_transactions array and processes any failed TXNs
497
+	 *
498
+	 * @throws \EE_Error
499
+	 */
500 500
 	public static function process_expired_transactions() {
501 501
 		if (
502 502
 			// are there any TXNs that need cleaning up ?
@@ -507,58 +507,58 @@  discard block
 block discarded – undo
507 507
 				self::$_expired_transactions
508 508
 			)
509 509
 		) {
510
-            return;
511
-        }
512
-        /** @type EE_Transaction_Processor $transaction_processor */
513
-        $transaction_processor = EE_Registry::instance()->load_class( 'Transaction_Processor' );
514
-        // set revisit flag for txn processor
515
-        $transaction_processor->set_revisit( false );
516
-         // load EEM_Transaction
517
-        EE_Registry::instance()->load_model( 'Transaction' );
518
-        foreach ( self::$_expired_transactions as $TXN_ID ) {
519
-            $transaction = EEM_Transaction::instance()->get_one_by_ID( $TXN_ID );
520
-            // verify transaction and whether it is failed or not
521
-            if ( $transaction instanceof EE_Transaction) {
522
-                switch( $transaction->status_ID() ) {
523
-                    // Completed TXNs
524
-                    case EEM_Transaction::complete_status_code :
525
-                        do_action( 'AHEE__EE_Cron_Tasks__process_expired_transactions__completed_transaction', $transaction );
526
-                        break;
527
-                    // Overpaid TXNs
528
-                    case EEM_Transaction::overpaid_status_code :
529
-                        do_action( 'AHEE__EE_Cron_Tasks__process_expired_transactions__overpaid_transaction', $transaction );
530
-                        break;
531
-                    // Incomplete TXNs
532
-                    case EEM_Transaction::incomplete_status_code :
533
-                        do_action( 'AHEE__EE_Cron_Tasks__process_expired_transactions__incomplete_transaction', $transaction );
534
-                        // todo : merge the finalize_abandoned_transactions cron into this one...
535
-                        // todo : move business logic into EE_Transaction_Processor for finalizing abandoned transactions
536
-                        break;
537
-                    // Failed TXNs
538
-                    case EEM_Transaction::failed_status_code :
539
-                        do_action( 'AHEE__EE_Cron_Tasks__process_expired_transactions__failed_transaction', $transaction );
540
-                        // todo : perform garbage collection here and remove clean_out_junk_transactions()
541
-                        //$registrations = $transaction->registrations();
542
-                        //if ( ! empty( $registrations ) ) {
543
-                        //	foreach ( $registrations as $registration ) {
544
-                        //		if ( $registration instanceof EE_Registration ) {
545
-                        //$delete_registration = true;
546
-                        //if ( $registration->attendee() instanceof EE_Attendee ) {
547
-                        //	$delete_registration = false;
548
-                        //}
549
-                        //if ( $delete_registration ) {
550
-                        //	$registration->delete_permanently();
551
-                        //	$registration->delete_related_permanently();
552
-                        //}
553
-                        //		}
554
-                        //	}
555
-                        //}
556
-                        break;
557
-                }
558
-
559
-            }
560
-            unset( self::$_expired_transactions[ $TXN_ID ] );
561
-        }
510
+			return;
511
+		}
512
+		/** @type EE_Transaction_Processor $transaction_processor */
513
+		$transaction_processor = EE_Registry::instance()->load_class( 'Transaction_Processor' );
514
+		// set revisit flag for txn processor
515
+		$transaction_processor->set_revisit( false );
516
+		 // load EEM_Transaction
517
+		EE_Registry::instance()->load_model( 'Transaction' );
518
+		foreach ( self::$_expired_transactions as $TXN_ID ) {
519
+			$transaction = EEM_Transaction::instance()->get_one_by_ID( $TXN_ID );
520
+			// verify transaction and whether it is failed or not
521
+			if ( $transaction instanceof EE_Transaction) {
522
+				switch( $transaction->status_ID() ) {
523
+					// Completed TXNs
524
+					case EEM_Transaction::complete_status_code :
525
+						do_action( 'AHEE__EE_Cron_Tasks__process_expired_transactions__completed_transaction', $transaction );
526
+						break;
527
+					// Overpaid TXNs
528
+					case EEM_Transaction::overpaid_status_code :
529
+						do_action( 'AHEE__EE_Cron_Tasks__process_expired_transactions__overpaid_transaction', $transaction );
530
+						break;
531
+					// Incomplete TXNs
532
+					case EEM_Transaction::incomplete_status_code :
533
+						do_action( 'AHEE__EE_Cron_Tasks__process_expired_transactions__incomplete_transaction', $transaction );
534
+						// todo : merge the finalize_abandoned_transactions cron into this one...
535
+						// todo : move business logic into EE_Transaction_Processor for finalizing abandoned transactions
536
+						break;
537
+					// Failed TXNs
538
+					case EEM_Transaction::failed_status_code :
539
+						do_action( 'AHEE__EE_Cron_Tasks__process_expired_transactions__failed_transaction', $transaction );
540
+						// todo : perform garbage collection here and remove clean_out_junk_transactions()
541
+						//$registrations = $transaction->registrations();
542
+						//if ( ! empty( $registrations ) ) {
543
+						//	foreach ( $registrations as $registration ) {
544
+						//		if ( $registration instanceof EE_Registration ) {
545
+						//$delete_registration = true;
546
+						//if ( $registration->attendee() instanceof EE_Attendee ) {
547
+						//	$delete_registration = false;
548
+						//}
549
+						//if ( $delete_registration ) {
550
+						//	$registration->delete_permanently();
551
+						//	$registration->delete_related_permanently();
552
+						//}
553
+						//		}
554
+						//	}
555
+						//}
556
+						break;
557
+				}
558
+
559
+			}
560
+			unset( self::$_expired_transactions[ $TXN_ID ] );
561
+		}
562 562
 	}
563 563
 
564 564
 
@@ -566,18 +566,18 @@  discard block
 block discarded – undo
566 566
 	/*************  END OF EXPIRED TRANSACTION CHECK  *************/
567 567
 
568 568
 
569
-    /************* START CLEAN UP BOT TRANSACTIONS **********************/
569
+	/************* START CLEAN UP BOT TRANSACTIONS **********************/
570 570
 
571
-    //when a transaction is initially made, schedule this check.
572
-    //if it has NO REG data by the time it has expired, forget about it
573
-    public static function clean_out_junk_transactions()
574
-    {
575
-        if (EE_Maintenance_Mode::instance()->models_can_query()) {
576
-            EEM_Transaction::instance('')->delete_junk_transactions();
577
-            EEM_Registration::instance('')->delete_registrations_with_no_transaction();
578
-            EEM_Line_Item::instance('')->delete_line_items_with_no_transaction();
579
-        }
580
-    }
571
+	//when a transaction is initially made, schedule this check.
572
+	//if it has NO REG data by the time it has expired, forget about it
573
+	public static function clean_out_junk_transactions()
574
+	{
575
+		if (EE_Maintenance_Mode::instance()->models_can_query()) {
576
+			EEM_Transaction::instance('')->delete_junk_transactions();
577
+			EEM_Registration::instance('')->delete_registrations_with_no_transaction();
578
+			EEM_Line_Item::instance('')->delete_line_items_with_no_transaction();
579
+		}
580
+	}
581 581
 
582 582
 
583 583
 }
Please login to merge, or discard this patch.
Spacing   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
              * wanting to not have this functionality can just register its own action at a priority after this one to
58 58
              * reverse any changes.
59 59
              */
60
-            add_action('AHEE__EE_System__load_core_configuration__complete', function () {
60
+            add_action('AHEE__EE_System__load_core_configuration__complete', function() {
61 61
                 EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request = true;
62 62
                 EE_Registry::instance()->NET_CFG->update_config(true, false);
63 63
                 add_option('ee_disabled_wp_cron_check', 1, '', false);
@@ -78,7 +78,7 @@  discard block
 block discarded – undo
78 78
 		// EXPIRED TRANSACTION CHECK
79 79
 		add_action(
80 80
 			'AHEE__EE_Cron_Tasks__expired_transaction_check',
81
-			array( 'EE_Cron_Tasks', 'expired_transaction_check' ),
81
+			array('EE_Cron_Tasks', 'expired_transaction_check'),
82 82
 			10, 1
83 83
 		);
84 84
         // CLEAN OUT JUNK TRANSACTIONS AND RELATED DATA
@@ -141,8 +141,8 @@  discard block
 block discarded – undo
141 141
      * @return bool
142 142
      * @throws \DomainException
143 143
      */
144
-	public static function reschedule_cron_for_transactions_if_maintenance_mode( $cron_task, array $TXN_IDs ) {
145
-        if( ! method_exists('EE_Cron_Tasks', $cron_task)) {
144
+	public static function reschedule_cron_for_transactions_if_maintenance_mode($cron_task, array $TXN_IDs) {
145
+        if ( ! method_exists('EE_Cron_Tasks', $cron_task)) {
146 146
             throw new \DomainException(
147 147
                 sprintf(
148 148
                     __('"%1$s" is not valid method on EE_Cron_Tasks.', 'event_espresso'),
@@ -151,8 +151,8 @@  discard block
 block discarded – undo
151 151
             );
152 152
         }
153 153
 		// reschedule the cron if we can't hit the db right now
154
-		if ( ! EE_Maintenance_Mode::instance()->models_can_query() ) {
155
-			foreach( $TXN_IDs as $TXN_ID => $additional_vars ) {
154
+		if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
155
+			foreach ($TXN_IDs as $TXN_ID => $additional_vars) {
156 156
                 // ensure $additional_vars is an array
157 157
                 $additional_vars = is_array($additional_vars) ? $additional_vars : array($additional_vars);
158 158
 				// reset cron job for the TXN
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
         do_action('AHEE_log', __CLASS__, __FUNCTION__);
257 257
 		if (
258 258
 			// are there any TXNs that need cleaning up ?
259
-			empty( self::$_update_transactions_with_payment )
259
+			empty(self::$_update_transactions_with_payment)
260 260
 			// reschedule the cron if we can't hit the db right now
261 261
 			|| EE_Cron_Tasks::reschedule_cron_for_transactions_if_maintenance_mode(
262 262
 				'schedule_update_transaction_with_payment',
@@ -377,7 +377,7 @@  discard block
 block discarded – undo
377 377
         do_action('AHEE_log', __CLASS__, __FUNCTION__);
378 378
         if (
379 379
 			// are there any TXNs that need cleaning up ?
380
-			empty( self::$_abandoned_transactions )
380
+			empty(self::$_abandoned_transactions)
381 381
 			// reschedule the cron if we can't hit the db right now
382 382
 			|| EE_Cron_Tasks::reschedule_cron_for_transactions_if_maintenance_mode(
383 383
 				'schedule_finalize_abandoned_transactions_check',
@@ -450,13 +450,13 @@  discard block
 block discarded – undo
450 450
 		$TXN_ID
451 451
 	) {
452 452
 		// validate $TXN_ID and $timestamp
453
-		$TXN_ID = absint( $TXN_ID );
454
-		$timestamp = absint( $timestamp );
455
-		if ( $TXN_ID && $timestamp ) {
453
+		$TXN_ID = absint($TXN_ID);
454
+		$timestamp = absint($timestamp);
455
+		if ($TXN_ID && $timestamp) {
456 456
 			wp_schedule_single_event(
457 457
 				$timestamp,
458 458
 				'AHEE__EE_Cron_Tasks__expired_transaction_check',
459
-				array( $TXN_ID )
459
+				array($TXN_ID)
460 460
 			);
461 461
 		}
462 462
 	}
@@ -478,12 +478,12 @@  discard block
 block discarded – undo
478 478
 	 *
479 479
 	 * @param int $TXN_ID
480 480
 	 */
481
-	public static function expired_transaction_check( $TXN_ID = 0 ) {
482
-		if ( absint( $TXN_ID )) {
483
-			self::$_expired_transactions[ $TXN_ID ]  = $TXN_ID;
481
+	public static function expired_transaction_check($TXN_ID = 0) {
482
+		if (absint($TXN_ID)) {
483
+			self::$_expired_transactions[$TXN_ID] = $TXN_ID;
484 484
 			add_action(
485 485
 				'shutdown',
486
-				array( 'EE_Cron_Tasks', 'process_expired_transactions' ),
486
+				array('EE_Cron_Tasks', 'process_expired_transactions'),
487 487
 				5
488 488
 			);
489 489
 		}
@@ -500,7 +500,7 @@  discard block
 block discarded – undo
500 500
 	public static function process_expired_transactions() {
501 501
 		if (
502 502
 			// are there any TXNs that need cleaning up ?
503
-			empty( self::$_expired_transactions )
503
+			empty(self::$_expired_transactions)
504 504
 			// reschedule the cron if we can't hit the db right now
505 505
 			|| EE_Cron_Tasks::reschedule_cron_for_transactions_if_maintenance_mode(
506 506
 				'schedule_expired_transaction_check',
@@ -510,33 +510,33 @@  discard block
 block discarded – undo
510 510
             return;
511 511
         }
512 512
         /** @type EE_Transaction_Processor $transaction_processor */
513
-        $transaction_processor = EE_Registry::instance()->load_class( 'Transaction_Processor' );
513
+        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
514 514
         // set revisit flag for txn processor
515
-        $transaction_processor->set_revisit( false );
515
+        $transaction_processor->set_revisit(false);
516 516
          // load EEM_Transaction
517
-        EE_Registry::instance()->load_model( 'Transaction' );
518
-        foreach ( self::$_expired_transactions as $TXN_ID ) {
519
-            $transaction = EEM_Transaction::instance()->get_one_by_ID( $TXN_ID );
517
+        EE_Registry::instance()->load_model('Transaction');
518
+        foreach (self::$_expired_transactions as $TXN_ID) {
519
+            $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
520 520
             // verify transaction and whether it is failed or not
521
-            if ( $transaction instanceof EE_Transaction) {
522
-                switch( $transaction->status_ID() ) {
521
+            if ($transaction instanceof EE_Transaction) {
522
+                switch ($transaction->status_ID()) {
523 523
                     // Completed TXNs
524 524
                     case EEM_Transaction::complete_status_code :
525
-                        do_action( 'AHEE__EE_Cron_Tasks__process_expired_transactions__completed_transaction', $transaction );
525
+                        do_action('AHEE__EE_Cron_Tasks__process_expired_transactions__completed_transaction', $transaction);
526 526
                         break;
527 527
                     // Overpaid TXNs
528 528
                     case EEM_Transaction::overpaid_status_code :
529
-                        do_action( 'AHEE__EE_Cron_Tasks__process_expired_transactions__overpaid_transaction', $transaction );
529
+                        do_action('AHEE__EE_Cron_Tasks__process_expired_transactions__overpaid_transaction', $transaction);
530 530
                         break;
531 531
                     // Incomplete TXNs
532 532
                     case EEM_Transaction::incomplete_status_code :
533
-                        do_action( 'AHEE__EE_Cron_Tasks__process_expired_transactions__incomplete_transaction', $transaction );
533
+                        do_action('AHEE__EE_Cron_Tasks__process_expired_transactions__incomplete_transaction', $transaction);
534 534
                         // todo : merge the finalize_abandoned_transactions cron into this one...
535 535
                         // todo : move business logic into EE_Transaction_Processor for finalizing abandoned transactions
536 536
                         break;
537 537
                     // Failed TXNs
538 538
                     case EEM_Transaction::failed_status_code :
539
-                        do_action( 'AHEE__EE_Cron_Tasks__process_expired_transactions__failed_transaction', $transaction );
539
+                        do_action('AHEE__EE_Cron_Tasks__process_expired_transactions__failed_transaction', $transaction);
540 540
                         // todo : perform garbage collection here and remove clean_out_junk_transactions()
541 541
                         //$registrations = $transaction->registrations();
542 542
                         //if ( ! empty( $registrations ) ) {
@@ -557,7 +557,7 @@  discard block
 block discarded – undo
557 557
                 }
558 558
 
559 559
             }
560
-            unset( self::$_expired_transactions[ $TXN_ID ] );
560
+            unset(self::$_expired_transactions[$TXN_ID]);
561 561
         }
562 562
 	}
563 563
 
Please login to merge, or discard this patch.
core/db_models/EEM_Attendee.model.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -242,7 +242,7 @@
 block discarded – undo
242 242
      *
243 243
      * @access        public
244 244
      * @param        $ATT_ID
245
-     * @return        mixed        array on success, FALSE on fail
245
+     * @return        EE_Base_Class|null        array on success, FALSE on fail
246 246
      * @deprecated
247 247
      */
248 248
     public function get_attendee_by_ID($ATT_ID = false)
Please login to merge, or discard this patch.
Indentation   +306 added lines, -306 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 require_once(EE_MODELS . 'EEM_Base.model.php');
5 5
 
@@ -15,319 +15,319 @@  discard block
 block discarded – undo
15 15
 class EEM_Attendee extends EEM_CPT_Base
16 16
 {
17 17
 
18
-    // private instance of the Attendee object
19
-    protected static $_instance = null;
18
+	// private instance of the Attendee object
19
+	protected static $_instance = null;
20 20
 
21
-    /**
22
-     * QST_system for questions are strings not ints now,
23
-     * so these constants are deprecated.
24
-     * Please instead use the EEM_Attendee::system_question_* constants
25
-     *
26
-     * @deprecated
27
-     */
28
-    const fname_question_id = 1;
21
+	/**
22
+	 * QST_system for questions are strings not ints now,
23
+	 * so these constants are deprecated.
24
+	 * Please instead use the EEM_Attendee::system_question_* constants
25
+	 *
26
+	 * @deprecated
27
+	 */
28
+	const fname_question_id = 1;
29 29
 
30
-    /**
31
-     * @deprecated
32
-     */
33
-    const lname_question_id = 2;
30
+	/**
31
+	 * @deprecated
32
+	 */
33
+	const lname_question_id = 2;
34 34
 
35 35
 
36
-    /**
37
-     * @deprecated
38
-     */
39
-    const email_question_id = 3;
36
+	/**
37
+	 * @deprecated
38
+	 */
39
+	const email_question_id = 3;
40 40
 
41 41
 
42
-    /**
43
-     * @deprecated
44
-     */
45
-    const address_question_id = 4;
42
+	/**
43
+	 * @deprecated
44
+	 */
45
+	const address_question_id = 4;
46 46
 
47 47
 
48
-    /**
49
-     * @deprecated
50
-     */
51
-    const address2_question_id = 5;
52
-
53
-
54
-    /**
55
-     * @deprecated
56
-     */
57
-    const city_question_id = 6;
58
-
59
-
60
-    /**
61
-     * @deprecated
62
-     */
63
-    const state_question_id = 7;
64
-
65
-
66
-    /**
67
-     * @deprecated
68
-     */
69
-    const country_question_id = 8;
70
-
71
-
72
-    /**
73
-     * @deprecated
74
-     */
75
-    const zip_question_id = 9;
76
-
77
-
78
-    /**
79
-     * @deprecated
80
-     */
81
-    const phone_question_id = 10;
82
-
83
-    /**
84
-     * When looking for questions that correspond to attendee fields,
85
-     * look for the question with this QST_system value.
86
-     * These replace the old constants like EEM_Attendee::*_question_id
87
-     */
88
-    const system_question_fname    = 'fname';
89
-
90
-    const system_question_lname    = 'lname';
91
-
92
-    const system_question_email    = 'email';
93
-
94
-    const system_question_address  = 'address';
95
-
96
-    const system_question_address2 = 'address2';
97
-
98
-    const system_question_city     = 'city';
99
-
100
-    const system_question_state    = 'state';
101
-
102
-    const system_question_country  = 'country';
103
-
104
-    const system_question_zip      = 'zip';
105
-
106
-    const system_question_phone    = 'phone';
107
-
108
-    /**
109
-     * Keys are all the EEM_Attendee::system_question_* constants, which are
110
-     * also all the values of QST_system in the questions table, and values
111
-     * are their corresponding Attendee field names
112
-     *
113
-     * @var array
114
-     */
115
-    protected $_system_question_to_attendee_field_name = array(
116
-        EEM_Attendee::system_question_fname    => 'ATT_fname',
117
-        EEM_Attendee::system_question_lname    => 'ATT_lname',
118
-        EEM_Attendee::system_question_email    => 'ATT_email',
119
-        EEM_Attendee::system_question_address  => 'ATT_address',
120
-        EEM_Attendee::system_question_address2 => 'ATT_address2',
121
-        EEM_Attendee::system_question_city     => 'ATT_city',
122
-        EEM_Attendee::system_question_state    => 'STA_ID',
123
-        EEM_Attendee::system_question_country  => 'CNT_ISO',
124
-        EEM_Attendee::system_question_zip      => 'ATT_zip',
125
-        EEM_Attendee::system_question_phone    => 'ATT_phone',
126
-    );
127
-
128
-
129
-
130
-    /**
131
-     *        private constructor to prevent direct creation
132
-     *
133
-     * @Constructor
134
-     * @access protected
135
-     * @param null $timezone
136
-     */
137
-    protected function __construct($timezone = null)
138
-    {
139
-        $this->singular_item = __('Attendee', 'event_espresso');
140
-        $this->plural_item = __('Attendees', 'event_espresso');
141
-        $this->_tables = array(
142
-            'Attendee_CPT'  => new EE_Primary_Table('posts', 'ID'),
143
-            'Attendee_Meta' => new EE_Secondary_Table('esp_attendee_meta', 'ATTM_ID', 'ATT_ID'),
144
-        );
145
-        $this->_fields = array(
146
-            'Attendee_CPT'  => array(
147
-                'ATT_ID'        => new EE_Primary_Key_Int_Field('ID', __("Attendee ID", "event_espresso")),
148
-                'ATT_full_name' => new EE_Plain_Text_Field('post_title', __("Attendee Full Name", "event_espresso"),
149
-                    false, __("Unknown", "event_espresso")),
150
-                'ATT_bio'       => new EE_Post_Content_Field('post_content', __("Attendee Biography", "event_espresso"),
151
-                    false, __("No Biography Provided", "event_espresso")),
152
-                'ATT_slug'      => new EE_Slug_Field('post_name', __("Attendee URL Slug", "event_espresso"), false),
153
-                'ATT_created'   => new EE_Datetime_Field('post_date', __("Time Attendee Created", "event_espresso"),
154
-                    false, EE_Datetime_Field::now),
155
-                'ATT_short_bio' => new EE_Simple_HTML_Field('post_excerpt',
156
-                    __("Attendee Short Biography", "event_espresso"), true,
157
-                    __("No Biography Provided", "event_espresso")),
158
-                'ATT_modified'  => new EE_Datetime_Field('post_modified',
159
-                    __("Time Attendee Last Modified", "event_espresso"), false, EE_Datetime_Field::now),
160
-                'ATT_author'    => new EE_WP_User_Field('post_author',
161
-                    __("Creator ID of the first Event attended", "event_espresso"), false),
162
-                'ATT_parent'    => new EE_DB_Only_Int_Field('post_parent',
163
-                    __("Parent Attendee (unused)", "event_espresso"), false, 0),
164
-                'post_type'     => new EE_WP_Post_Type_Field('espresso_attendees'),
165
-                // EE_DB_Only_Text_Field('post_type', __("Post Type of Attendee", "event_espresso"), false,'espresso_attendees'),
166
-                'status'        => new EE_WP_Post_Status_Field('post_status', __('Attendee Status', 'event_espresso'),
167
-                    false, 'publish'),
168
-            ),
169
-            'Attendee_Meta' => array(
170
-                'ATTM_ID'      => new EE_DB_Only_Int_Field('ATTM_ID', __('Attendee Meta Row ID', 'event_espresso'),
171
-                    false),
172
-                'ATT_ID_fk'    => new EE_DB_Only_Int_Field('ATT_ID',
173
-                    __("Foreign Key to Attendee in Post Table", "event_espresso"), false),
174
-                'ATT_fname'    => new EE_Plain_Text_Field('ATT_fname', __('First Name', 'event_espresso'), true, ''),
175
-                'ATT_lname'    => new EE_Plain_Text_Field('ATT_lname', __('Last Name', 'event_espresso'), true, ''),
176
-                'ATT_address'  => new EE_Plain_Text_Field('ATT_address', __('Address Part 1', 'event_espresso'), true,
177
-                    ''),
178
-                'ATT_address2' => new EE_Plain_Text_Field('ATT_address2', __('Address Part 2', 'event_espresso'), true,
179
-                    ''),
180
-                'ATT_city'     => new EE_Plain_Text_Field('ATT_city', __('City', 'event_espresso'), true, ''),
181
-                'STA_ID'       => new EE_Foreign_Key_Int_Field('STA_ID', __('State', 'event_espresso'), true, 0,
182
-                    'State'),
183
-                'CNT_ISO'      => new EE_Foreign_Key_String_Field('CNT_ISO', __('Country', 'event_espresso'), true, '',
184
-                    'Country'),
185
-                'ATT_zip'      => new EE_Plain_Text_Field('ATT_zip', __('ZIP/Postal Code', 'event_espresso'), true, ''),
186
-                'ATT_email'    => new EE_Email_Field('ATT_email', __('Email Address', 'event_espresso'), true, ''),
187
-                'ATT_phone'    => new EE_Plain_Text_Field('ATT_phone', __('Phone', 'event_espresso'), true, ''),
188
-            ),
189
-        );
190
-        $this->_model_relations = array(
191
-            'Registration'      => new EE_Has_Many_Relation(),
192
-            'State'             => new EE_Belongs_To_Relation(),
193
-            'Country'           => new EE_Belongs_To_Relation(),
194
-            'Event'             => new EE_HABTM_Relation('Registration', false),
195
-            'WP_User'           => new EE_Belongs_To_Relation(),
196
-            'Message'           => new EE_Has_Many_Any_Relation(false),
197
-            //allow deletion of attendees even if they have messages in the queue for them.
198
-            'Term_Relationship' => new EE_Has_Many_Relation(),
199
-            'Term_Taxonomy'     => new EE_HABTM_Relation('Term_Relationship'),
200
-        );
201
-        $this->_caps_slug = 'contacts';
202
-        parent::__construct($timezone);
203
-    }
204
-
205
-
206
-
207
-    /**
208
-     * Gets the name of the field on the attendee model corresponding to the system question string
209
-     * which should be one of the keys from EEM_Attendee::_system_question_to_attendee_field_name
210
-     *
211
-     * @param string $system_question_string
212
-     * @return string|null if not found
213
-     */
214
-    public function get_attendee_field_for_system_question($system_question_string)
215
-    {
216
-        return isset($this->_system_question_to_attendee_field_name[$system_question_string])
217
-            ? $this->_system_question_to_attendee_field_name[$system_question_string] : null;
218
-    }
219
-
220
-
221
-
222
-    /**
223
-     * Gets all the attendees for a transaction (by using the esp_registration as a join table)
224
-     *
225
-     * @param EE_Transaction /int $transaction_id_or_obj EE_Transaction or its ID
226
-     * @return EE_Attendee[]
227
-     */
228
-    public function get_attendees_for_transaction($transaction_id_or_obj)
229
-    {
230
-        return $this->get_all(array(
231
-            array(
232
-                'Registration.Transaction.TXN_ID' => $transaction_id_or_obj instanceof EE_Transaction
233
-                    ? $transaction_id_or_obj->ID() : $transaction_id_or_obj,
234
-            ),
235
-        ));
236
-    }
237
-
238
-
239
-
240
-    /**
241
-     *        retrieve  a single attendee from db via their ID
242
-     *
243
-     * @access        public
244
-     * @param        $ATT_ID
245
-     * @return        mixed        array on success, FALSE on fail
246
-     * @deprecated
247
-     */
248
-    public function get_attendee_by_ID($ATT_ID = false)
249
-    {
250
-        // retrieve a particular EE_Attendee
251
-        return $this->get_one_by_ID($ATT_ID);
252
-    }
253
-
254
-
255
-
256
-    /**
257
-     *        retrieve  a single attendee from db via their ID
258
-     *
259
-     * @access        public
260
-     * @param        array $where_cols_n_values
261
-     * @return        mixed        array on success, FALSE on fail
262
-     */
263
-    public function get_attendee($where_cols_n_values = array())
264
-    {
265
-        if (empty($where_cols_n_values)) {
266
-            return false;
267
-        }
268
-        $attendee = $this->get_all(array($where_cols_n_values));
269
-        if ( ! empty($attendee)) {
270
-            return array_shift($attendee);
271
-        } else {
272
-            return false;
273
-        }
274
-    }
275
-
276
-
277
-
278
-    /**
279
-     *        Search for an existing Attendee record in the DB
280
-     *
281
-     * @access        public
282
-     * @param array $where_cols_n_values
283
-     * @return bool|mixed
284
-     */
285
-    public function find_existing_attendee($where_cols_n_values = null)
286
-    {
287
-        // search by combo of first and last names plus the email address
288
-        $attendee_data_keys = array(
289
-            'ATT_fname' => $this->_ATT_fname,
290
-            'ATT_lname' => $this->_ATT_lname,
291
-            'ATT_email' => $this->_ATT_email,
292
-        );
293
-        // no search params means attendee object already exists.
294
-        $where_cols_n_values = is_array($where_cols_n_values) && ! empty($where_cols_n_values) ? $where_cols_n_values
295
-            : $attendee_data_keys;
296
-        $valid_data = true;
297
-        // check for required values
298
-        $valid_data = isset($where_cols_n_values['ATT_fname']) && ! empty($where_cols_n_values['ATT_fname'])
299
-            ? $valid_data : false;
300
-        $valid_data = isset($where_cols_n_values['ATT_lname']) && ! empty($where_cols_n_values['ATT_lname'])
301
-            ? $valid_data : false;
302
-        $valid_data = isset($where_cols_n_values['ATT_email']) && ! empty($where_cols_n_values['ATT_email'])
303
-            ? $valid_data : false;
304
-        if ($valid_data) {
305
-            $attendee = $this->get_attendee($where_cols_n_values);
306
-            if ($attendee instanceof EE_Attendee) {
307
-                return $attendee;
308
-            }
309
-        }
310
-        return false;
311
-    }
312
-
313
-
314
-
315
-    /**
316
-     * Takes an incoming array of EE_Registration ids and sends back a list of corresponding non duplicate
317
-     * EE_Attendee objects.
318
-     *
319
-     * @since    4.3.0
320
-     * @param  array $ids array of EE_Registration ids
321
-     * @return  EE_Attendee[]
322
-     */
323
-    public function get_array_of_contacts_from_reg_ids($ids)
324
-    {
325
-        $ids = (array)$ids;
326
-        $_where = array(
327
-            'Registration.REG_ID' => array('in', $ids),
328
-        );
329
-        return $this->get_all(array($_where));
330
-    }
48
+	/**
49
+	 * @deprecated
50
+	 */
51
+	const address2_question_id = 5;
52
+
53
+
54
+	/**
55
+	 * @deprecated
56
+	 */
57
+	const city_question_id = 6;
58
+
59
+
60
+	/**
61
+	 * @deprecated
62
+	 */
63
+	const state_question_id = 7;
64
+
65
+
66
+	/**
67
+	 * @deprecated
68
+	 */
69
+	const country_question_id = 8;
70
+
71
+
72
+	/**
73
+	 * @deprecated
74
+	 */
75
+	const zip_question_id = 9;
76
+
77
+
78
+	/**
79
+	 * @deprecated
80
+	 */
81
+	const phone_question_id = 10;
82
+
83
+	/**
84
+	 * When looking for questions that correspond to attendee fields,
85
+	 * look for the question with this QST_system value.
86
+	 * These replace the old constants like EEM_Attendee::*_question_id
87
+	 */
88
+	const system_question_fname    = 'fname';
89
+
90
+	const system_question_lname    = 'lname';
91
+
92
+	const system_question_email    = 'email';
93
+
94
+	const system_question_address  = 'address';
95
+
96
+	const system_question_address2 = 'address2';
97
+
98
+	const system_question_city     = 'city';
99
+
100
+	const system_question_state    = 'state';
101
+
102
+	const system_question_country  = 'country';
103
+
104
+	const system_question_zip      = 'zip';
105
+
106
+	const system_question_phone    = 'phone';
107
+
108
+	/**
109
+	 * Keys are all the EEM_Attendee::system_question_* constants, which are
110
+	 * also all the values of QST_system in the questions table, and values
111
+	 * are their corresponding Attendee field names
112
+	 *
113
+	 * @var array
114
+	 */
115
+	protected $_system_question_to_attendee_field_name = array(
116
+		EEM_Attendee::system_question_fname    => 'ATT_fname',
117
+		EEM_Attendee::system_question_lname    => 'ATT_lname',
118
+		EEM_Attendee::system_question_email    => 'ATT_email',
119
+		EEM_Attendee::system_question_address  => 'ATT_address',
120
+		EEM_Attendee::system_question_address2 => 'ATT_address2',
121
+		EEM_Attendee::system_question_city     => 'ATT_city',
122
+		EEM_Attendee::system_question_state    => 'STA_ID',
123
+		EEM_Attendee::system_question_country  => 'CNT_ISO',
124
+		EEM_Attendee::system_question_zip      => 'ATT_zip',
125
+		EEM_Attendee::system_question_phone    => 'ATT_phone',
126
+	);
127
+
128
+
129
+
130
+	/**
131
+	 *        private constructor to prevent direct creation
132
+	 *
133
+	 * @Constructor
134
+	 * @access protected
135
+	 * @param null $timezone
136
+	 */
137
+	protected function __construct($timezone = null)
138
+	{
139
+		$this->singular_item = __('Attendee', 'event_espresso');
140
+		$this->plural_item = __('Attendees', 'event_espresso');
141
+		$this->_tables = array(
142
+			'Attendee_CPT'  => new EE_Primary_Table('posts', 'ID'),
143
+			'Attendee_Meta' => new EE_Secondary_Table('esp_attendee_meta', 'ATTM_ID', 'ATT_ID'),
144
+		);
145
+		$this->_fields = array(
146
+			'Attendee_CPT'  => array(
147
+				'ATT_ID'        => new EE_Primary_Key_Int_Field('ID', __("Attendee ID", "event_espresso")),
148
+				'ATT_full_name' => new EE_Plain_Text_Field('post_title', __("Attendee Full Name", "event_espresso"),
149
+					false, __("Unknown", "event_espresso")),
150
+				'ATT_bio'       => new EE_Post_Content_Field('post_content', __("Attendee Biography", "event_espresso"),
151
+					false, __("No Biography Provided", "event_espresso")),
152
+				'ATT_slug'      => new EE_Slug_Field('post_name', __("Attendee URL Slug", "event_espresso"), false),
153
+				'ATT_created'   => new EE_Datetime_Field('post_date', __("Time Attendee Created", "event_espresso"),
154
+					false, EE_Datetime_Field::now),
155
+				'ATT_short_bio' => new EE_Simple_HTML_Field('post_excerpt',
156
+					__("Attendee Short Biography", "event_espresso"), true,
157
+					__("No Biography Provided", "event_espresso")),
158
+				'ATT_modified'  => new EE_Datetime_Field('post_modified',
159
+					__("Time Attendee Last Modified", "event_espresso"), false, EE_Datetime_Field::now),
160
+				'ATT_author'    => new EE_WP_User_Field('post_author',
161
+					__("Creator ID of the first Event attended", "event_espresso"), false),
162
+				'ATT_parent'    => new EE_DB_Only_Int_Field('post_parent',
163
+					__("Parent Attendee (unused)", "event_espresso"), false, 0),
164
+				'post_type'     => new EE_WP_Post_Type_Field('espresso_attendees'),
165
+				// EE_DB_Only_Text_Field('post_type', __("Post Type of Attendee", "event_espresso"), false,'espresso_attendees'),
166
+				'status'        => new EE_WP_Post_Status_Field('post_status', __('Attendee Status', 'event_espresso'),
167
+					false, 'publish'),
168
+			),
169
+			'Attendee_Meta' => array(
170
+				'ATTM_ID'      => new EE_DB_Only_Int_Field('ATTM_ID', __('Attendee Meta Row ID', 'event_espresso'),
171
+					false),
172
+				'ATT_ID_fk'    => new EE_DB_Only_Int_Field('ATT_ID',
173
+					__("Foreign Key to Attendee in Post Table", "event_espresso"), false),
174
+				'ATT_fname'    => new EE_Plain_Text_Field('ATT_fname', __('First Name', 'event_espresso'), true, ''),
175
+				'ATT_lname'    => new EE_Plain_Text_Field('ATT_lname', __('Last Name', 'event_espresso'), true, ''),
176
+				'ATT_address'  => new EE_Plain_Text_Field('ATT_address', __('Address Part 1', 'event_espresso'), true,
177
+					''),
178
+				'ATT_address2' => new EE_Plain_Text_Field('ATT_address2', __('Address Part 2', 'event_espresso'), true,
179
+					''),
180
+				'ATT_city'     => new EE_Plain_Text_Field('ATT_city', __('City', 'event_espresso'), true, ''),
181
+				'STA_ID'       => new EE_Foreign_Key_Int_Field('STA_ID', __('State', 'event_espresso'), true, 0,
182
+					'State'),
183
+				'CNT_ISO'      => new EE_Foreign_Key_String_Field('CNT_ISO', __('Country', 'event_espresso'), true, '',
184
+					'Country'),
185
+				'ATT_zip'      => new EE_Plain_Text_Field('ATT_zip', __('ZIP/Postal Code', 'event_espresso'), true, ''),
186
+				'ATT_email'    => new EE_Email_Field('ATT_email', __('Email Address', 'event_espresso'), true, ''),
187
+				'ATT_phone'    => new EE_Plain_Text_Field('ATT_phone', __('Phone', 'event_espresso'), true, ''),
188
+			),
189
+		);
190
+		$this->_model_relations = array(
191
+			'Registration'      => new EE_Has_Many_Relation(),
192
+			'State'             => new EE_Belongs_To_Relation(),
193
+			'Country'           => new EE_Belongs_To_Relation(),
194
+			'Event'             => new EE_HABTM_Relation('Registration', false),
195
+			'WP_User'           => new EE_Belongs_To_Relation(),
196
+			'Message'           => new EE_Has_Many_Any_Relation(false),
197
+			//allow deletion of attendees even if they have messages in the queue for them.
198
+			'Term_Relationship' => new EE_Has_Many_Relation(),
199
+			'Term_Taxonomy'     => new EE_HABTM_Relation('Term_Relationship'),
200
+		);
201
+		$this->_caps_slug = 'contacts';
202
+		parent::__construct($timezone);
203
+	}
204
+
205
+
206
+
207
+	/**
208
+	 * Gets the name of the field on the attendee model corresponding to the system question string
209
+	 * which should be one of the keys from EEM_Attendee::_system_question_to_attendee_field_name
210
+	 *
211
+	 * @param string $system_question_string
212
+	 * @return string|null if not found
213
+	 */
214
+	public function get_attendee_field_for_system_question($system_question_string)
215
+	{
216
+		return isset($this->_system_question_to_attendee_field_name[$system_question_string])
217
+			? $this->_system_question_to_attendee_field_name[$system_question_string] : null;
218
+	}
219
+
220
+
221
+
222
+	/**
223
+	 * Gets all the attendees for a transaction (by using the esp_registration as a join table)
224
+	 *
225
+	 * @param EE_Transaction /int $transaction_id_or_obj EE_Transaction or its ID
226
+	 * @return EE_Attendee[]
227
+	 */
228
+	public function get_attendees_for_transaction($transaction_id_or_obj)
229
+	{
230
+		return $this->get_all(array(
231
+			array(
232
+				'Registration.Transaction.TXN_ID' => $transaction_id_or_obj instanceof EE_Transaction
233
+					? $transaction_id_or_obj->ID() : $transaction_id_or_obj,
234
+			),
235
+		));
236
+	}
237
+
238
+
239
+
240
+	/**
241
+	 *        retrieve  a single attendee from db via their ID
242
+	 *
243
+	 * @access        public
244
+	 * @param        $ATT_ID
245
+	 * @return        mixed        array on success, FALSE on fail
246
+	 * @deprecated
247
+	 */
248
+	public function get_attendee_by_ID($ATT_ID = false)
249
+	{
250
+		// retrieve a particular EE_Attendee
251
+		return $this->get_one_by_ID($ATT_ID);
252
+	}
253
+
254
+
255
+
256
+	/**
257
+	 *        retrieve  a single attendee from db via their ID
258
+	 *
259
+	 * @access        public
260
+	 * @param        array $where_cols_n_values
261
+	 * @return        mixed        array on success, FALSE on fail
262
+	 */
263
+	public function get_attendee($where_cols_n_values = array())
264
+	{
265
+		if (empty($where_cols_n_values)) {
266
+			return false;
267
+		}
268
+		$attendee = $this->get_all(array($where_cols_n_values));
269
+		if ( ! empty($attendee)) {
270
+			return array_shift($attendee);
271
+		} else {
272
+			return false;
273
+		}
274
+	}
275
+
276
+
277
+
278
+	/**
279
+	 *        Search for an existing Attendee record in the DB
280
+	 *
281
+	 * @access        public
282
+	 * @param array $where_cols_n_values
283
+	 * @return bool|mixed
284
+	 */
285
+	public function find_existing_attendee($where_cols_n_values = null)
286
+	{
287
+		// search by combo of first and last names plus the email address
288
+		$attendee_data_keys = array(
289
+			'ATT_fname' => $this->_ATT_fname,
290
+			'ATT_lname' => $this->_ATT_lname,
291
+			'ATT_email' => $this->_ATT_email,
292
+		);
293
+		// no search params means attendee object already exists.
294
+		$where_cols_n_values = is_array($where_cols_n_values) && ! empty($where_cols_n_values) ? $where_cols_n_values
295
+			: $attendee_data_keys;
296
+		$valid_data = true;
297
+		// check for required values
298
+		$valid_data = isset($where_cols_n_values['ATT_fname']) && ! empty($where_cols_n_values['ATT_fname'])
299
+			? $valid_data : false;
300
+		$valid_data = isset($where_cols_n_values['ATT_lname']) && ! empty($where_cols_n_values['ATT_lname'])
301
+			? $valid_data : false;
302
+		$valid_data = isset($where_cols_n_values['ATT_email']) && ! empty($where_cols_n_values['ATT_email'])
303
+			? $valid_data : false;
304
+		if ($valid_data) {
305
+			$attendee = $this->get_attendee($where_cols_n_values);
306
+			if ($attendee instanceof EE_Attendee) {
307
+				return $attendee;
308
+			}
309
+		}
310
+		return false;
311
+	}
312
+
313
+
314
+
315
+	/**
316
+	 * Takes an incoming array of EE_Registration ids and sends back a list of corresponding non duplicate
317
+	 * EE_Attendee objects.
318
+	 *
319
+	 * @since    4.3.0
320
+	 * @param  array $ids array of EE_Registration ids
321
+	 * @return  EE_Attendee[]
322
+	 */
323
+	public function get_array_of_contacts_from_reg_ids($ids)
324
+	{
325
+		$ids = (array)$ids;
326
+		$_where = array(
327
+			'Registration.REG_ID' => array('in', $ids),
328
+		);
329
+		return $this->get_all(array($_where));
330
+	}
331 331
 
332 332
 
333 333
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2 2
     exit('No direct script access allowed');
3 3
 }
4
-require_once(EE_MODELS . 'EEM_Base.model.php');
4
+require_once(EE_MODELS.'EEM_Base.model.php');
5 5
 
6 6
 
7 7
 
@@ -322,7 +322,7 @@  discard block
 block discarded – undo
322 322
      */
323 323
     public function get_array_of_contacts_from_reg_ids($ids)
324 324
     {
325
-        $ids = (array)$ids;
325
+        $ids = (array) $ids;
326 326
         $_where = array(
327 327
             'Registration.REG_ID' => array('in', $ids),
328 328
         );
Please login to merge, or discard this patch.
core/helpers/EEH_Activation.helper.php 3 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -620,7 +620,7 @@  discard block
 block discarded – undo
620 620
      *
621 621
      * @since  4.6.0
622 622
      * @global WPDB $wpdb
623
-     * @return mixed null|int WP_user ID or NULL
623
+     * @return integer|null null|int WP_user ID or NULL
624 624
      */
625 625
     public static function get_default_creator_id()
626 626
     {
@@ -785,7 +785,7 @@  discard block
 block discarded – undo
785 785
 	 * @static
786 786
 	 * @deprecated instead use TableManager::dropTable()
787 787
 	 * @param string $table_name
788
-	 * @return bool | int
788
+	 * @return integer | int
789 789
 	 */
790 790
 	public static function delete_unused_db_table( $table_name ) {
791 791
 		return \EEH_Activation::getTableManager()->dropTable( $table_name );
@@ -801,7 +801,7 @@  discard block
 block discarded – undo
801 801
 	 * @deprecated instead use TableManager::dropIndex()
802 802
 	 * @param string $table_name
803 803
 	 * @param string $index_name
804
-	 * @return bool | int
804
+	 * @return integer | int
805 805
 	 */
806 806
 	public static function drop_index( $table_name, $index_name ) {
807 807
 		return \EEH_Activation::getTableManager()->dropIndex( $table_name, $index_name );
Please login to merge, or discard this patch.
Indentation   +915 added lines, -915 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -14,36 +14,36 @@  discard block
 block discarded – undo
14 14
 class EEH_Activation
15 15
 {
16 16
 
17
-    /**
18
-     * constant used to indicate a cron task is no longer in use
19
-     */
20
-    const cron_task_no_longer_in_use = 'no_longer_in_use';
21
-
22
-    /**
23
-     * option name that will indicate whether or not we still
24
-     * need to create EE's folders in the uploads directory
25
-     * (because if EE was installed without file system access,
26
-     * we need to request credentials before we can create them)
27
-     */
28
-    const upload_directories_incomplete_option_name = 'ee_upload_directories_incomplete';
29
-
30
-    /**
31
-     * WP_User->ID
32
-     *
33
-     * @var int
34
-     */
35
-    private static $_default_creator_id;
36
-
37
-    /**
38
-     * indicates whether or not we've already verified core's default data during this request,
39
-     * because after migrations are done, any addons activated while in maintenance mode
40
-     * will want to setup their own default data, and they might hook into core's default data
41
-     * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
42
-     * This prevents doing that for EVERY single addon.
43
-     *
44
-     * @var boolean
45
-     */
46
-    protected static $_initialized_db_content_already_in_this_request = false;
17
+	/**
18
+	 * constant used to indicate a cron task is no longer in use
19
+	 */
20
+	const cron_task_no_longer_in_use = 'no_longer_in_use';
21
+
22
+	/**
23
+	 * option name that will indicate whether or not we still
24
+	 * need to create EE's folders in the uploads directory
25
+	 * (because if EE was installed without file system access,
26
+	 * we need to request credentials before we can create them)
27
+	 */
28
+	const upload_directories_incomplete_option_name = 'ee_upload_directories_incomplete';
29
+
30
+	/**
31
+	 * WP_User->ID
32
+	 *
33
+	 * @var int
34
+	 */
35
+	private static $_default_creator_id;
36
+
37
+	/**
38
+	 * indicates whether or not we've already verified core's default data during this request,
39
+	 * because after migrations are done, any addons activated while in maintenance mode
40
+	 * will want to setup their own default data, and they might hook into core's default data
41
+	 * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
42
+	 * This prevents doing that for EVERY single addon.
43
+	 *
44
+	 * @var boolean
45
+	 */
46
+	protected static $_initialized_db_content_already_in_this_request = false;
47 47
 
48 48
 	/**
49 49
 	 * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
 			if ( is_array( $hooks_to_fire_at_time ) ) {
259 259
 				foreach ( $hooks_to_fire_at_time as $hook_name => $hook_actions ) {
260 260
 					if ( isset( $ee_cron_tasks_to_remove[ $hook_name ] )
261
-					     && is_array( $ee_cron_tasks_to_remove[ $hook_name ] )
261
+						 && is_array( $ee_cron_tasks_to_remove[ $hook_name ] )
262 262
 					) {
263 263
 						unset( $crons[ $timestamp ][ $hook_name ] );
264 264
 					}
@@ -290,26 +290,26 @@  discard block
 block discarded – undo
290 290
 
291 291
 
292 292
 
293
-    /**
294
-     *    reset_and_update_config
295
-     * The following code was moved over from EE_Config so that it will no longer run on every request.
296
-     * If there is old calendar config data saved, then it will get converted on activation.
297
-     * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
298
-     *
299
-     * @access public
300
-     * @static
301
-     * @return void
302
-     */
303
-    public static function reset_and_update_config()
304
-    {
305
-        do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
306
-        add_filter('FHEE__EE_Config___load_core_config__config_settings',
307
-            array('EEH_Activation', 'migrate_old_config_data'), 10, 3);
308
-        //EE_Config::reset();
309
-        if ( ! EE_Config::logging_enabled()) {
310
-            delete_option(EE_Config::LOG_NAME);
311
-        }
312
-    }
293
+	/**
294
+	 *    reset_and_update_config
295
+	 * The following code was moved over from EE_Config so that it will no longer run on every request.
296
+	 * If there is old calendar config data saved, then it will get converted on activation.
297
+	 * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
298
+	 *
299
+	 * @access public
300
+	 * @static
301
+	 * @return void
302
+	 */
303
+	public static function reset_and_update_config()
304
+	{
305
+		do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
306
+		add_filter('FHEE__EE_Config___load_core_config__config_settings',
307
+			array('EEH_Activation', 'migrate_old_config_data'), 10, 3);
308
+		//EE_Config::reset();
309
+		if ( ! EE_Config::logging_enabled()) {
310
+			delete_option(EE_Config::LOG_NAME);
311
+		}
312
+	}
313 313
 
314 314
 
315 315
 	/**
@@ -349,34 +349,34 @@  discard block
 block discarded – undo
349 349
 
350 350
 
351 351
 
352
-    /**
353
-     *    _migrate_old_config_data
354
-     *
355
-     * @access    public
356
-     * @param array|stdClass $settings
357
-     * @param string         $config
358
-     * @param \EE_Config     $EE_Config
359
-     * @return \stdClass
360
-     */
361
-    public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
362
-    {
363
-        $convert_from_array = array('addons');
364
-        // in case old settings were saved as an array
365
-        if (is_array($settings) && in_array($config, $convert_from_array)) {
366
-            // convert existing settings to an object
367
-            $config_array = $settings;
368
-            $settings = new stdClass();
369
-            foreach ($config_array as $key => $value) {
370
-                if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
371
-                    $EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
372
-                } else {
373
-                    $settings->{$key} = $value;
374
-                }
375
-            }
376
-            add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
377
-        }
378
-        return $settings;
379
-    }
352
+	/**
353
+	 *    _migrate_old_config_data
354
+	 *
355
+	 * @access    public
356
+	 * @param array|stdClass $settings
357
+	 * @param string         $config
358
+	 * @param \EE_Config     $EE_Config
359
+	 * @return \stdClass
360
+	 */
361
+	public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
362
+	{
363
+		$convert_from_array = array('addons');
364
+		// in case old settings were saved as an array
365
+		if (is_array($settings) && in_array($config, $convert_from_array)) {
366
+			// convert existing settings to an object
367
+			$config_array = $settings;
368
+			$settings = new stdClass();
369
+			foreach ($config_array as $key => $value) {
370
+				if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
371
+					$EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
372
+				} else {
373
+					$settings->{$key} = $value;
374
+				}
375
+			}
376
+			add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
377
+		}
378
+		return $settings;
379
+	}
380 380
 
381 381
 
382 382
 
@@ -398,130 +398,130 @@  discard block
 block discarded – undo
398 398
 
399 399
 
400 400
 
401
-    /**
402
-     * verify_default_pages_exist
403
-     *
404
-     * @access public
405
-     * @static
406
-     * @return void
407
-     */
408
-    public static function verify_default_pages_exist()
409
-    {
410
-        $critical_page_problem = false;
411
-        $critical_pages = array(
412
-            array(
413
-                'id'   => 'reg_page_id',
414
-                'name' => __('Registration Checkout', 'event_espresso'),
415
-                'post' => null,
416
-                'code' => 'ESPRESSO_CHECKOUT',
417
-            ),
418
-            array(
419
-                'id'   => 'txn_page_id',
420
-                'name' => __('Transactions', 'event_espresso'),
421
-                'post' => null,
422
-                'code' => 'ESPRESSO_TXN_PAGE',
423
-            ),
424
-            array(
425
-                'id'   => 'thank_you_page_id',
426
-                'name' => __('Thank You', 'event_espresso'),
427
-                'post' => null,
428
-                'code' => 'ESPRESSO_THANK_YOU',
429
-            ),
430
-            array(
431
-                'id'   => 'cancel_page_id',
432
-                'name' => __('Registration Cancelled', 'event_espresso'),
433
-                'post' => null,
434
-                'code' => 'ESPRESSO_CANCELLED',
435
-            ),
436
-        );
437
-        $EE_Core_Config = EE_Registry::instance()->CFG->core;
438
-        foreach ($critical_pages as $critical_page) {
439
-            // is critical page ID set in config ?
440
-            if ($EE_Core_Config->{$critical_page['id']} !== false) {
441
-                // attempt to find post by ID
442
-                $critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
443
-            }
444
-            // no dice?
445
-            if ($critical_page['post'] === null) {
446
-                // attempt to find post by title
447
-                $critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
448
-                // still nothing?
449
-                if ($critical_page['post'] === null) {
450
-                    $critical_page = EEH_Activation::create_critical_page($critical_page);
451
-                    // REALLY? Still nothing ??!?!?
452
-                    if ($critical_page['post'] === null) {
453
-                        $msg = __('The Event Espresso critical page configuration settings could not be updated.',
454
-                            'event_espresso');
455
-                        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
456
-                        break;
457
-                    }
458
-                }
459
-            }
460
-            // track post_shortcodes
461
-            if ($critical_page['post']) {
462
-                EEH_Activation::_track_critical_page_post_shortcodes($critical_page);
463
-            }
464
-            // check that Post ID matches critical page ID in config
465
-            if (
466
-                isset($critical_page['post']->ID)
467
-                && $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
468
-            ) {
469
-                //update Config with post ID
470
-                $EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
471
-                if ( ! EE_Config::instance()->update_espresso_config(false, false)) {
472
-                    $msg = __('The Event Espresso critical page configuration settings could not be updated.',
473
-                        'event_espresso');
474
-                    EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
475
-                }
476
-            }
477
-            $critical_page_problem =
478
-                ! isset($critical_page['post']->post_status)
479
-                || $critical_page['post']->post_status !== 'publish'
480
-                || strpos($critical_page['post']->post_content, $critical_page['code']) === false
481
-                    ? true
482
-                    : $critical_page_problem;
483
-        }
484
-        if ($critical_page_problem) {
485
-            $msg = sprintf(
486
-                __('A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
487
-                    'event_espresso'),
488
-                '<a href="'
489
-                . admin_url('admin.php?page=espresso_general_settings&action=critical_pages')
490
-                . '">'
491
-                . __('Event Espresso Critical Pages Settings', 'event_espresso')
492
-                . '</a>'
493
-            );
494
-            EE_Error::add_persistent_admin_notice('critical_page_problem', $msg);
495
-        }
496
-        if (EE_Error::has_notices()) {
497
-            EE_Error::get_notices(false, true, true);
498
-        }
499
-    }
500
-
501
-
502
-
503
-    /**
504
-     * Returns the first post which uses the specified shortcode
505
-     *
506
-     * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
507
-     *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
508
-     *                             "[ESPRESSO_THANK_YOU"
509
-     *                             (we don't search for the closing shortcode bracket because they might have added
510
-     *                             parameter to the shortcode
511
-     * @return WP_Post or NULl
512
-     */
513
-    public static function get_page_by_ee_shortcode($ee_shortcode)
514
-    {
515
-        global $wpdb;
516
-        $shortcode_and_opening_bracket = '[' . $ee_shortcode;
517
-        $post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
518
-        if ($post_id) {
519
-            return get_post($post_id);
520
-        } else {
521
-            return null;
522
-        }
401
+	/**
402
+	 * verify_default_pages_exist
403
+	 *
404
+	 * @access public
405
+	 * @static
406
+	 * @return void
407
+	 */
408
+	public static function verify_default_pages_exist()
409
+	{
410
+		$critical_page_problem = false;
411
+		$critical_pages = array(
412
+			array(
413
+				'id'   => 'reg_page_id',
414
+				'name' => __('Registration Checkout', 'event_espresso'),
415
+				'post' => null,
416
+				'code' => 'ESPRESSO_CHECKOUT',
417
+			),
418
+			array(
419
+				'id'   => 'txn_page_id',
420
+				'name' => __('Transactions', 'event_espresso'),
421
+				'post' => null,
422
+				'code' => 'ESPRESSO_TXN_PAGE',
423
+			),
424
+			array(
425
+				'id'   => 'thank_you_page_id',
426
+				'name' => __('Thank You', 'event_espresso'),
427
+				'post' => null,
428
+				'code' => 'ESPRESSO_THANK_YOU',
429
+			),
430
+			array(
431
+				'id'   => 'cancel_page_id',
432
+				'name' => __('Registration Cancelled', 'event_espresso'),
433
+				'post' => null,
434
+				'code' => 'ESPRESSO_CANCELLED',
435
+			),
436
+		);
437
+		$EE_Core_Config = EE_Registry::instance()->CFG->core;
438
+		foreach ($critical_pages as $critical_page) {
439
+			// is critical page ID set in config ?
440
+			if ($EE_Core_Config->{$critical_page['id']} !== false) {
441
+				// attempt to find post by ID
442
+				$critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
443
+			}
444
+			// no dice?
445
+			if ($critical_page['post'] === null) {
446
+				// attempt to find post by title
447
+				$critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
448
+				// still nothing?
449
+				if ($critical_page['post'] === null) {
450
+					$critical_page = EEH_Activation::create_critical_page($critical_page);
451
+					// REALLY? Still nothing ??!?!?
452
+					if ($critical_page['post'] === null) {
453
+						$msg = __('The Event Espresso critical page configuration settings could not be updated.',
454
+							'event_espresso');
455
+						EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
456
+						break;
457
+					}
458
+				}
459
+			}
460
+			// track post_shortcodes
461
+			if ($critical_page['post']) {
462
+				EEH_Activation::_track_critical_page_post_shortcodes($critical_page);
463
+			}
464
+			// check that Post ID matches critical page ID in config
465
+			if (
466
+				isset($critical_page['post']->ID)
467
+				&& $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
468
+			) {
469
+				//update Config with post ID
470
+				$EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
471
+				if ( ! EE_Config::instance()->update_espresso_config(false, false)) {
472
+					$msg = __('The Event Espresso critical page configuration settings could not be updated.',
473
+						'event_espresso');
474
+					EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
475
+				}
476
+			}
477
+			$critical_page_problem =
478
+				! isset($critical_page['post']->post_status)
479
+				|| $critical_page['post']->post_status !== 'publish'
480
+				|| strpos($critical_page['post']->post_content, $critical_page['code']) === false
481
+					? true
482
+					: $critical_page_problem;
483
+		}
484
+		if ($critical_page_problem) {
485
+			$msg = sprintf(
486
+				__('A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
487
+					'event_espresso'),
488
+				'<a href="'
489
+				. admin_url('admin.php?page=espresso_general_settings&action=critical_pages')
490
+				. '">'
491
+				. __('Event Espresso Critical Pages Settings', 'event_espresso')
492
+				. '</a>'
493
+			);
494
+			EE_Error::add_persistent_admin_notice('critical_page_problem', $msg);
495
+		}
496
+		if (EE_Error::has_notices()) {
497
+			EE_Error::get_notices(false, true, true);
498
+		}
499
+	}
500
+
501
+
502
+
503
+	/**
504
+	 * Returns the first post which uses the specified shortcode
505
+	 *
506
+	 * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
507
+	 *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
508
+	 *                             "[ESPRESSO_THANK_YOU"
509
+	 *                             (we don't search for the closing shortcode bracket because they might have added
510
+	 *                             parameter to the shortcode
511
+	 * @return WP_Post or NULl
512
+	 */
513
+	public static function get_page_by_ee_shortcode($ee_shortcode)
514
+	{
515
+		global $wpdb;
516
+		$shortcode_and_opening_bracket = '[' . $ee_shortcode;
517
+		$post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
518
+		if ($post_id) {
519
+			return get_post($post_id);
520
+		} else {
521
+			return null;
522
+		}
523 523
 //		return $post_id;
524
-    }
524
+	}
525 525
 
526 526
 
527 527
 
@@ -569,163 +569,163 @@  discard block
 block discarded – undo
569 569
 
570 570
 
571 571
 
572
-    /**
573
-     *    This function adds a critical page's shortcode to the post_shortcodes array
574
-     *
575
-     * @access private
576
-     * @static
577
-     * @param array $critical_page
578
-     * @return void
579
-     */
580
-    private static function _track_critical_page_post_shortcodes($critical_page = array())
581
-    {
582
-        // check the goods
583
-        if ( ! $critical_page['post'] instanceof WP_Post) {
584
-            $msg = sprintf(
585
-                __('The Event Espresso critical page shortcode for the page %s can not be tracked because it is not a WP_Post object.',
586
-                    'event_espresso'),
587
-                $critical_page['name']
588
-            );
589
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
590
-            return;
591
-        }
592
-        $EE_Core_Config = EE_Registry::instance()->CFG->core;
593
-        // map shortcode to post
594
-        $EE_Core_Config->post_shortcodes[$critical_page['post']->post_name][$critical_page['code']] = $critical_page['post']->ID;
595
-        // and make sure it's NOT added to the WP "Posts Page"
596
-        // name of the WP Posts Page
597
-        $posts_page = EE_Config::get_page_for_posts();
598
-        if (isset($EE_Core_Config->post_shortcodes[$posts_page])) {
599
-            unset($EE_Core_Config->post_shortcodes[$posts_page][$critical_page['code']]);
600
-        }
601
-        if ($posts_page !== 'posts' && isset($EE_Core_Config->post_shortcodes['posts'])) {
602
-            unset($EE_Core_Config->post_shortcodes['posts'][$critical_page['code']]);
603
-        }
604
-        // update post_shortcode CFG
605
-        if ( ! EE_Config::instance()->update_espresso_config(false, false)) {
606
-            $msg = sprintf(
607
-                __('The Event Espresso critical page shortcode for the %s page could not be configured properly.',
608
-                    'event_espresso'),
609
-                $critical_page['name']
610
-            );
611
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
612
-        }
613
-    }
614
-
615
-
616
-
617
-    /**
618
-     * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
619
-     * The role being used to check is filterable.
620
-     *
621
-     * @since  4.6.0
622
-     * @global WPDB $wpdb
623
-     * @return mixed null|int WP_user ID or NULL
624
-     */
625
-    public static function get_default_creator_id()
626
-    {
627
-        global $wpdb;
628
-        if ( ! empty(self::$_default_creator_id)) {
629
-            return self::$_default_creator_id;
630
-        }/**/
631
-        $role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
632
-        //let's allow pre_filtering for early exits by alternative methods for getting id.  We check for truthy result and if so then exit early.
633
-        $pre_filtered_id = apply_filters('FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id', false,
634
-            $role_to_check);
635
-        if ($pre_filtered_id !== false) {
636
-            return (int)$pre_filtered_id;
637
-        }
638
-        $capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
639
-        $query = $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
640
-            '%' . $role_to_check . '%');
641
-        $user_id = $wpdb->get_var($query);
642
-        $user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
643
-        if ($user_id && (int)$user_id) {
644
-            self::$_default_creator_id = (int)$user_id;
645
-            return self::$_default_creator_id;
646
-        } else {
647
-            return null;
648
-        }
649
-    }
650
-
651
-
652
-
653
-    /**
654
-     * used by EE and EE addons during plugin activation to create tables.
655
-     * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
656
-     * but includes extra logic regarding activations.
657
-     *
658
-     * @access public
659
-     * @static
660
-     * @param string  $table_name              without the $wpdb->prefix
661
-     * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
662
-     *                                         table query)
663
-     * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
664
-     * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
665
-     *                                         and new once this function is done (ie, you really do want to CREATE a
666
-     *                                         table, and expect it to be empty once you're done) leave as FALSE when
667
-     *                                         you just want to verify the table exists and matches this definition
668
-     *                                         (and if it HAS data in it you want to leave it be)
669
-     * @return void
670
-     * @throws EE_Error if there are database errors
671
-     */
672
-    public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
673
-    {
674
-        if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
675
-            return;
676
-        }
677
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
678
-        if ( ! function_exists('dbDelta')) {
679
-            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
680
-        }
681
-        $tableAnalysis = \EEH_Activation::getTableAnalysis();
682
-        $wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
683
-        // do we need to first delete an existing version of this table ?
684
-        if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
685
-            // ok, delete the table... but ONLY if it's empty
686
-            $deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
687
-            // table is NOT empty, are you SURE you want to delete this table ???
688
-            if ( ! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
689
-                \EEH_Activation::getTableManager()->dropTable($wp_table_name);
690
-            } else if ( ! $deleted_safely) {
691
-                // so we should be more cautious rather than just dropping tables so easily
692
-                EE_Error::add_persistent_admin_notice(
693
-                    'bad_table_' . $wp_table_name . '_detected',
694
-                    sprintf(__('Database table %1$s exists when it shouldn\'t, and may contain erroneous data. If you have previously restored your database from a backup that didn\'t remove the old tables, then we recommend adding %2$s to your %3$s file then restore to that backup again. This will clear out the invalid data from %1$s. Afterwards you should undo that change from your %3$s file. %4$sIf you cannot edit %3$s, you should remove the data from %1$s manually then restore to the backup again.',
695
-                        'event_espresso'),
696
-                        $wp_table_name,
697
-                        "<pre>define( 'EE_DROP_BAD_TABLES', TRUE );</pre>",
698
-                        '<b>wp-config.php</b>',
699
-                        '<br/>'),
700
-                    true);
701
-            }
702
-        }
703
-        $engine = str_replace('ENGINE=', '', $engine);
704
-        \EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
705
-    }
706
-
707
-
708
-
709
-    /**
710
-     *    add_column_if_it_doesn't_exist
711
-     *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
712
-     *
713
-     * @access     public
714
-     * @static
715
-     * @deprecated instead use TableManager::addColumn()
716
-     * @param string $table_name  (without "wp_", eg "esp_attendee"
717
-     * @param string $column_name
718
-     * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
719
-     *                            'VARCHAR(10)'
720
-     * @return bool|int
721
-     */
722
-    public static function add_column_if_it_doesnt_exist(
723
-        $table_name,
724
-        $column_name,
725
-        $column_info = 'INT UNSIGNED NOT NULL'
726
-    ) {
727
-        return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
728
-    }
572
+	/**
573
+	 *    This function adds a critical page's shortcode to the post_shortcodes array
574
+	 *
575
+	 * @access private
576
+	 * @static
577
+	 * @param array $critical_page
578
+	 * @return void
579
+	 */
580
+	private static function _track_critical_page_post_shortcodes($critical_page = array())
581
+	{
582
+		// check the goods
583
+		if ( ! $critical_page['post'] instanceof WP_Post) {
584
+			$msg = sprintf(
585
+				__('The Event Espresso critical page shortcode for the page %s can not be tracked because it is not a WP_Post object.',
586
+					'event_espresso'),
587
+				$critical_page['name']
588
+			);
589
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
590
+			return;
591
+		}
592
+		$EE_Core_Config = EE_Registry::instance()->CFG->core;
593
+		// map shortcode to post
594
+		$EE_Core_Config->post_shortcodes[$critical_page['post']->post_name][$critical_page['code']] = $critical_page['post']->ID;
595
+		// and make sure it's NOT added to the WP "Posts Page"
596
+		// name of the WP Posts Page
597
+		$posts_page = EE_Config::get_page_for_posts();
598
+		if (isset($EE_Core_Config->post_shortcodes[$posts_page])) {
599
+			unset($EE_Core_Config->post_shortcodes[$posts_page][$critical_page['code']]);
600
+		}
601
+		if ($posts_page !== 'posts' && isset($EE_Core_Config->post_shortcodes['posts'])) {
602
+			unset($EE_Core_Config->post_shortcodes['posts'][$critical_page['code']]);
603
+		}
604
+		// update post_shortcode CFG
605
+		if ( ! EE_Config::instance()->update_espresso_config(false, false)) {
606
+			$msg = sprintf(
607
+				__('The Event Espresso critical page shortcode for the %s page could not be configured properly.',
608
+					'event_espresso'),
609
+				$critical_page['name']
610
+			);
611
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
612
+		}
613
+	}
614
+
615
+
616
+
617
+	/**
618
+	 * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
619
+	 * The role being used to check is filterable.
620
+	 *
621
+	 * @since  4.6.0
622
+	 * @global WPDB $wpdb
623
+	 * @return mixed null|int WP_user ID or NULL
624
+	 */
625
+	public static function get_default_creator_id()
626
+	{
627
+		global $wpdb;
628
+		if ( ! empty(self::$_default_creator_id)) {
629
+			return self::$_default_creator_id;
630
+		}/**/
631
+		$role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
632
+		//let's allow pre_filtering for early exits by alternative methods for getting id.  We check for truthy result and if so then exit early.
633
+		$pre_filtered_id = apply_filters('FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id', false,
634
+			$role_to_check);
635
+		if ($pre_filtered_id !== false) {
636
+			return (int)$pre_filtered_id;
637
+		}
638
+		$capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
639
+		$query = $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
640
+			'%' . $role_to_check . '%');
641
+		$user_id = $wpdb->get_var($query);
642
+		$user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
643
+		if ($user_id && (int)$user_id) {
644
+			self::$_default_creator_id = (int)$user_id;
645
+			return self::$_default_creator_id;
646
+		} else {
647
+			return null;
648
+		}
649
+	}
650
+
651
+
652
+
653
+	/**
654
+	 * used by EE and EE addons during plugin activation to create tables.
655
+	 * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
656
+	 * but includes extra logic regarding activations.
657
+	 *
658
+	 * @access public
659
+	 * @static
660
+	 * @param string  $table_name              without the $wpdb->prefix
661
+	 * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
662
+	 *                                         table query)
663
+	 * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
664
+	 * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
665
+	 *                                         and new once this function is done (ie, you really do want to CREATE a
666
+	 *                                         table, and expect it to be empty once you're done) leave as FALSE when
667
+	 *                                         you just want to verify the table exists and matches this definition
668
+	 *                                         (and if it HAS data in it you want to leave it be)
669
+	 * @return void
670
+	 * @throws EE_Error if there are database errors
671
+	 */
672
+	public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
673
+	{
674
+		if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
675
+			return;
676
+		}
677
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
678
+		if ( ! function_exists('dbDelta')) {
679
+			require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
680
+		}
681
+		$tableAnalysis = \EEH_Activation::getTableAnalysis();
682
+		$wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
683
+		// do we need to first delete an existing version of this table ?
684
+		if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
685
+			// ok, delete the table... but ONLY if it's empty
686
+			$deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
687
+			// table is NOT empty, are you SURE you want to delete this table ???
688
+			if ( ! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
689
+				\EEH_Activation::getTableManager()->dropTable($wp_table_name);
690
+			} else if ( ! $deleted_safely) {
691
+				// so we should be more cautious rather than just dropping tables so easily
692
+				EE_Error::add_persistent_admin_notice(
693
+					'bad_table_' . $wp_table_name . '_detected',
694
+					sprintf(__('Database table %1$s exists when it shouldn\'t, and may contain erroneous data. If you have previously restored your database from a backup that didn\'t remove the old tables, then we recommend adding %2$s to your %3$s file then restore to that backup again. This will clear out the invalid data from %1$s. Afterwards you should undo that change from your %3$s file. %4$sIf you cannot edit %3$s, you should remove the data from %1$s manually then restore to the backup again.',
695
+						'event_espresso'),
696
+						$wp_table_name,
697
+						"<pre>define( 'EE_DROP_BAD_TABLES', TRUE );</pre>",
698
+						'<b>wp-config.php</b>',
699
+						'<br/>'),
700
+					true);
701
+			}
702
+		}
703
+		$engine = str_replace('ENGINE=', '', $engine);
704
+		\EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
705
+	}
706
+
707
+
708
+
709
+	/**
710
+	 *    add_column_if_it_doesn't_exist
711
+	 *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
712
+	 *
713
+	 * @access     public
714
+	 * @static
715
+	 * @deprecated instead use TableManager::addColumn()
716
+	 * @param string $table_name  (without "wp_", eg "esp_attendee"
717
+	 * @param string $column_name
718
+	 * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
719
+	 *                            'VARCHAR(10)'
720
+	 * @return bool|int
721
+	 */
722
+	public static function add_column_if_it_doesnt_exist(
723
+		$table_name,
724
+		$column_name,
725
+		$column_info = 'INT UNSIGNED NOT NULL'
726
+	) {
727
+		return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
728
+	}
729 729
 
730 730
 
731 731
 
@@ -762,13 +762,13 @@  discard block
 block discarded – undo
762 762
 
763 763
 
764 764
 /**
765
-	 * delete_db_table_if_empty
766
-	 *
767
-	 * @access public
768
-	 * @static
769
-	 * @param string $table_name
770
-	 * @return bool | int
771
-	 */
765
+ * delete_db_table_if_empty
766
+ *
767
+ * @access public
768
+ * @static
769
+ * @param string $table_name
770
+ * @return bool | int
771
+ */
772 772
 	public static function delete_db_table_if_empty( $table_name ) {
773 773
 		if ( \EEH_Activation::getTableAnalysis()->tableIsEmpty( $table_name ) ) {
774 774
 			return \EEH_Activation::getTableManager()->dropTable( $table_name );
@@ -809,344 +809,344 @@  discard block
 block discarded – undo
809 809
 
810 810
 
811 811
 
812
-    /**
813
-     * create_database_tables
814
-     *
815
-     * @access public
816
-     * @static
817
-     * @throws EE_Error
818
-     * @return boolean success (whether database is setup properly or not)
819
-     */
820
-    public static function create_database_tables()
821
-    {
822
-        EE_Registry::instance()->load_core('Data_Migration_Manager');
823
-        //find the migration script that sets the database to be compatible with the code
824
-        $dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
825
-        if ($dms_name) {
826
-            $current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
827
-            $current_data_migration_script->set_migrating(false);
828
-            $current_data_migration_script->schema_changes_before_migration();
829
-            $current_data_migration_script->schema_changes_after_migration();
830
-            if ($current_data_migration_script->get_errors()) {
831
-                if (WP_DEBUG) {
832
-                    foreach ($current_data_migration_script->get_errors() as $error) {
833
-                        EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
834
-                    }
835
-                } else {
836
-                    EE_Error::add_error(__('There were errors creating the Event Espresso database tables and Event Espresso has been deactivated. To view the errors, please enable WP_DEBUG in your wp-config.php file.',
837
-                        'event_espresso'));
838
-                }
839
-                return false;
840
-            }
841
-            EE_Data_Migration_Manager::instance()->update_current_database_state_to();
842
-        } else {
843
-            EE_Error::add_error(__('Could not determine most up-to-date data migration script from which to pull database schema structure. So database is probably not setup properly',
844
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
845
-            return false;
846
-        }
847
-        return true;
848
-    }
849
-
850
-
851
-
852
-    /**
853
-     * initialize_system_questions
854
-     *
855
-     * @access public
856
-     * @static
857
-     * @return void
858
-     */
859
-    public static function initialize_system_questions()
860
-    {
861
-        // QUESTION GROUPS
862
-        global $wpdb;
863
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
864
-        $SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
865
-        // what we have
866
-        $question_groups = $wpdb->get_col($SQL);
867
-        // check the response
868
-        $question_groups = is_array($question_groups) ? $question_groups : array();
869
-        // what we should have
870
-        $QSG_systems = array(1, 2);
871
-        // loop thru what we should have and compare to what we have
872
-        foreach ($QSG_systems as $QSG_system) {
873
-            // reset values array
874
-            $QSG_values = array();
875
-            // if we don't have what we should have (but use $QST_system as as string because that's what we got from the db)
876
-            if ( ! in_array("$QSG_system", $question_groups)) {
877
-                // add it
878
-                switch ($QSG_system) {
879
-                    case 1:
880
-                        $QSG_values = array(
881
-                            'QSG_name'            => __('Personal Information', 'event_espresso'),
882
-                            'QSG_identifier'      => 'personal-information-' . time(),
883
-                            'QSG_desc'            => '',
884
-                            'QSG_order'           => 1,
885
-                            'QSG_show_group_name' => 1,
886
-                            'QSG_show_group_desc' => 1,
887
-                            'QSG_system'          => EEM_Question_Group::system_personal,
888
-                            'QSG_deleted'         => 0,
889
-                        );
890
-                        break;
891
-                    case 2:
892
-                        $QSG_values = array(
893
-                            'QSG_name'            => __('Address Information', 'event_espresso'),
894
-                            'QSG_identifier'      => 'address-information-' . time(),
895
-                            'QSG_desc'            => '',
896
-                            'QSG_order'           => 2,
897
-                            'QSG_show_group_name' => 1,
898
-                            'QSG_show_group_desc' => 1,
899
-                            'QSG_system'          => EEM_Question_Group::system_address,
900
-                            'QSG_deleted'         => 0,
901
-                        );
902
-                        break;
903
-                }
904
-                // make sure we have some values before inserting them
905
-                if ( ! empty($QSG_values)) {
906
-                    // insert system question
907
-                    $wpdb->insert(
908
-                        $table_name,
909
-                        $QSG_values,
910
-                        array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
911
-                    );
912
-                    $QSG_IDs[$QSG_system] = $wpdb->insert_id;
913
-                }
914
-            }
915
-        }
916
-        // QUESTIONS
917
-        global $wpdb;
918
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
919
-        $SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
920
-        // what we have
921
-        $questions = $wpdb->get_col($SQL);
922
-        // what we should have
923
-        $QST_systems = array(
924
-            'fname',
925
-            'lname',
926
-            'email',
927
-            'address',
928
-            'address2',
929
-            'city',
930
-            'country',
931
-            'state',
932
-            'zip',
933
-            'phone',
934
-        );
935
-        $order_for_group_1 = 1;
936
-        $order_for_group_2 = 1;
937
-        // loop thru what we should have and compare to what we have
938
-        foreach ($QST_systems as $QST_system) {
939
-            // reset values array
940
-            $QST_values = array();
941
-            // if we don't have what we should have
942
-            if ( ! in_array($QST_system, $questions)) {
943
-                // add it
944
-                switch ($QST_system) {
945
-                    case 'fname':
946
-                        $QST_values = array(
947
-                            'QST_display_text'  => __('First Name', 'event_espresso'),
948
-                            'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
949
-                            'QST_system'        => 'fname',
950
-                            'QST_type'          => 'TEXT',
951
-                            'QST_required'      => 1,
952
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
953
-                            'QST_order'         => 1,
954
-                            'QST_admin_only'    => 0,
955
-                            'QST_max'           => EEM_Question::instance()
956
-                                                               ->absolute_max_for_system_question($QST_system),
957
-                            'QST_wp_user'       => self::get_default_creator_id(),
958
-                            'QST_deleted'       => 0,
959
-                        );
960
-                        break;
961
-                    case 'lname':
962
-                        $QST_values = array(
963
-                            'QST_display_text'  => __('Last Name', 'event_espresso'),
964
-                            'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
965
-                            'QST_system'        => 'lname',
966
-                            'QST_type'          => 'TEXT',
967
-                            'QST_required'      => 1,
968
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
969
-                            'QST_order'         => 2,
970
-                            'QST_admin_only'    => 0,
971
-                            'QST_max'           => EEM_Question::instance()
972
-                                                               ->absolute_max_for_system_question($QST_system),
973
-                            'QST_wp_user'       => self::get_default_creator_id(),
974
-                            'QST_deleted'       => 0,
975
-                        );
976
-                        break;
977
-                    case 'email':
978
-                        $QST_values = array(
979
-                            'QST_display_text'  => __('Email Address', 'event_espresso'),
980
-                            'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
981
-                            'QST_system'        => 'email',
982
-                            'QST_type'          => 'EMAIL',
983
-                            'QST_required'      => 1,
984
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
985
-                            'QST_order'         => 3,
986
-                            'QST_admin_only'    => 0,
987
-                            'QST_max'           => EEM_Question::instance()
988
-                                                               ->absolute_max_for_system_question($QST_system),
989
-                            'QST_wp_user'       => self::get_default_creator_id(),
990
-                            'QST_deleted'       => 0,
991
-                        );
992
-                        break;
993
-                    case 'address':
994
-                        $QST_values = array(
995
-                            'QST_display_text'  => __('Address', 'event_espresso'),
996
-                            'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
997
-                            'QST_system'        => 'address',
998
-                            'QST_type'          => 'TEXT',
999
-                            'QST_required'      => 0,
1000
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1001
-                            'QST_order'         => 4,
1002
-                            'QST_admin_only'    => 0,
1003
-                            'QST_max'           => EEM_Question::instance()
1004
-                                                               ->absolute_max_for_system_question($QST_system),
1005
-                            'QST_wp_user'       => self::get_default_creator_id(),
1006
-                            'QST_deleted'       => 0,
1007
-                        );
1008
-                        break;
1009
-                    case 'address2':
1010
-                        $QST_values = array(
1011
-                            'QST_display_text'  => __('Address2', 'event_espresso'),
1012
-                            'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
1013
-                            'QST_system'        => 'address2',
1014
-                            'QST_type'          => 'TEXT',
1015
-                            'QST_required'      => 0,
1016
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1017
-                            'QST_order'         => 5,
1018
-                            'QST_admin_only'    => 0,
1019
-                            'QST_max'           => EEM_Question::instance()
1020
-                                                               ->absolute_max_for_system_question($QST_system),
1021
-                            'QST_wp_user'       => self::get_default_creator_id(),
1022
-                            'QST_deleted'       => 0,
1023
-                        );
1024
-                        break;
1025
-                    case 'city':
1026
-                        $QST_values = array(
1027
-                            'QST_display_text'  => __('City', 'event_espresso'),
1028
-                            'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1029
-                            'QST_system'        => 'city',
1030
-                            'QST_type'          => 'TEXT',
1031
-                            'QST_required'      => 0,
1032
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1033
-                            'QST_order'         => 6,
1034
-                            'QST_admin_only'    => 0,
1035
-                            'QST_max'           => EEM_Question::instance()
1036
-                                                               ->absolute_max_for_system_question($QST_system),
1037
-                            'QST_wp_user'       => self::get_default_creator_id(),
1038
-                            'QST_deleted'       => 0,
1039
-                        );
1040
-                        break;
1041
-                    case 'country' :
1042
-                        $QST_values = array(
1043
-                            'QST_display_text'  => __('Country', 'event_espresso'),
1044
-                            'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1045
-                            'QST_system'        => 'country',
1046
-                            'QST_type'          => 'COUNTRY',
1047
-                            'QST_required'      => 0,
1048
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1049
-                            'QST_order'         => 7,
1050
-                            'QST_admin_only'    => 0,
1051
-                            'QST_wp_user'       => self::get_default_creator_id(),
1052
-                            'QST_deleted'       => 0,
1053
-                        );
1054
-                        break;
1055
-                    case 'state':
1056
-                        $QST_values = array(
1057
-                            'QST_display_text'  => __('State/Province', 'event_espresso'),
1058
-                            'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1059
-                            'QST_system'        => 'state',
1060
-                            'QST_type'          => 'STATE',
1061
-                            'QST_required'      => 0,
1062
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1063
-                            'QST_order'         => 8,
1064
-                            'QST_admin_only'    => 0,
1065
-                            'QST_wp_user'       => self::get_default_creator_id(),
1066
-                            'QST_deleted'       => 0,
1067
-                        );
1068
-                        break;
1069
-                    case 'zip':
1070
-                        $QST_values = array(
1071
-                            'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1072
-                            'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1073
-                            'QST_system'        => 'zip',
1074
-                            'QST_type'          => 'TEXT',
1075
-                            'QST_required'      => 0,
1076
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1077
-                            'QST_order'         => 9,
1078
-                            'QST_admin_only'    => 0,
1079
-                            'QST_max'           => EEM_Question::instance()
1080
-                                                               ->absolute_max_for_system_question($QST_system),
1081
-                            'QST_wp_user'       => self::get_default_creator_id(),
1082
-                            'QST_deleted'       => 0,
1083
-                        );
1084
-                        break;
1085
-                    case 'phone':
1086
-                        $QST_values = array(
1087
-                            'QST_display_text'  => __('Phone Number', 'event_espresso'),
1088
-                            'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1089
-                            'QST_system'        => 'phone',
1090
-                            'QST_type'          => 'TEXT',
1091
-                            'QST_required'      => 0,
1092
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1093
-                            'QST_order'         => 10,
1094
-                            'QST_admin_only'    => 0,
1095
-                            'QST_max'           => EEM_Question::instance()
1096
-                                                               ->absolute_max_for_system_question($QST_system),
1097
-                            'QST_wp_user'       => self::get_default_creator_id(),
1098
-                            'QST_deleted'       => 0,
1099
-                        );
1100
-                        break;
1101
-                }
1102
-                if ( ! empty($QST_values)) {
1103
-                    // insert system question
1104
-                    $wpdb->insert(
1105
-                        $table_name,
1106
-                        $QST_values,
1107
-                        array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1108
-                    );
1109
-                    $QST_ID = $wpdb->insert_id;
1110
-                    // QUESTION GROUP QUESTIONS
1111
-                    if (in_array($QST_system, array('fname', 'lname', 'email'))) {
1112
-                        $system_question_we_want = EEM_Question_Group::system_personal;
1113
-                    } else {
1114
-                        $system_question_we_want = EEM_Question_Group::system_address;
1115
-                    }
1116
-                    if (isset($QSG_IDs[$system_question_we_want])) {
1117
-                        $QSG_ID = $QSG_IDs[$system_question_we_want];
1118
-                    } else {
1119
-                        $id_col = EEM_Question_Group::instance()
1120
-                                                    ->get_col(array(array('QSG_system' => $system_question_we_want)));
1121
-                        if (is_array($id_col)) {
1122
-                            $QSG_ID = reset($id_col);
1123
-                        } else {
1124
-                            //ok so we didn't find it in the db either?? that's weird because we should have inserted it at the start of this method
1125
-                            EE_Log::instance()->log(
1126
-                                __FILE__,
1127
-                                __FUNCTION__,
1128
-                                sprintf(
1129
-                                    __('Could not associate question %1$s to a question group because no system question group existed',
1130
-                                        'event_espresso'),
1131
-                                    $QST_ID),
1132
-                                'error');
1133
-                            continue;
1134
-                        }
1135
-                    }
1136
-                    // add system questions to groups
1137
-                    $wpdb->insert(
1138
-                        \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1139
-                        array(
1140
-                            'QSG_ID'    => $QSG_ID,
1141
-                            'QST_ID'    => $QST_ID,
1142
-                            'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1143
-                        ),
1144
-                        array('%d', '%d', '%d')
1145
-                    );
1146
-                }
1147
-            }
1148
-        }
1149
-    }
812
+	/**
813
+	 * create_database_tables
814
+	 *
815
+	 * @access public
816
+	 * @static
817
+	 * @throws EE_Error
818
+	 * @return boolean success (whether database is setup properly or not)
819
+	 */
820
+	public static function create_database_tables()
821
+	{
822
+		EE_Registry::instance()->load_core('Data_Migration_Manager');
823
+		//find the migration script that sets the database to be compatible with the code
824
+		$dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
825
+		if ($dms_name) {
826
+			$current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
827
+			$current_data_migration_script->set_migrating(false);
828
+			$current_data_migration_script->schema_changes_before_migration();
829
+			$current_data_migration_script->schema_changes_after_migration();
830
+			if ($current_data_migration_script->get_errors()) {
831
+				if (WP_DEBUG) {
832
+					foreach ($current_data_migration_script->get_errors() as $error) {
833
+						EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
834
+					}
835
+				} else {
836
+					EE_Error::add_error(__('There were errors creating the Event Espresso database tables and Event Espresso has been deactivated. To view the errors, please enable WP_DEBUG in your wp-config.php file.',
837
+						'event_espresso'));
838
+				}
839
+				return false;
840
+			}
841
+			EE_Data_Migration_Manager::instance()->update_current_database_state_to();
842
+		} else {
843
+			EE_Error::add_error(__('Could not determine most up-to-date data migration script from which to pull database schema structure. So database is probably not setup properly',
844
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
845
+			return false;
846
+		}
847
+		return true;
848
+	}
849
+
850
+
851
+
852
+	/**
853
+	 * initialize_system_questions
854
+	 *
855
+	 * @access public
856
+	 * @static
857
+	 * @return void
858
+	 */
859
+	public static function initialize_system_questions()
860
+	{
861
+		// QUESTION GROUPS
862
+		global $wpdb;
863
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
864
+		$SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
865
+		// what we have
866
+		$question_groups = $wpdb->get_col($SQL);
867
+		// check the response
868
+		$question_groups = is_array($question_groups) ? $question_groups : array();
869
+		// what we should have
870
+		$QSG_systems = array(1, 2);
871
+		// loop thru what we should have and compare to what we have
872
+		foreach ($QSG_systems as $QSG_system) {
873
+			// reset values array
874
+			$QSG_values = array();
875
+			// if we don't have what we should have (but use $QST_system as as string because that's what we got from the db)
876
+			if ( ! in_array("$QSG_system", $question_groups)) {
877
+				// add it
878
+				switch ($QSG_system) {
879
+					case 1:
880
+						$QSG_values = array(
881
+							'QSG_name'            => __('Personal Information', 'event_espresso'),
882
+							'QSG_identifier'      => 'personal-information-' . time(),
883
+							'QSG_desc'            => '',
884
+							'QSG_order'           => 1,
885
+							'QSG_show_group_name' => 1,
886
+							'QSG_show_group_desc' => 1,
887
+							'QSG_system'          => EEM_Question_Group::system_personal,
888
+							'QSG_deleted'         => 0,
889
+						);
890
+						break;
891
+					case 2:
892
+						$QSG_values = array(
893
+							'QSG_name'            => __('Address Information', 'event_espresso'),
894
+							'QSG_identifier'      => 'address-information-' . time(),
895
+							'QSG_desc'            => '',
896
+							'QSG_order'           => 2,
897
+							'QSG_show_group_name' => 1,
898
+							'QSG_show_group_desc' => 1,
899
+							'QSG_system'          => EEM_Question_Group::system_address,
900
+							'QSG_deleted'         => 0,
901
+						);
902
+						break;
903
+				}
904
+				// make sure we have some values before inserting them
905
+				if ( ! empty($QSG_values)) {
906
+					// insert system question
907
+					$wpdb->insert(
908
+						$table_name,
909
+						$QSG_values,
910
+						array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
911
+					);
912
+					$QSG_IDs[$QSG_system] = $wpdb->insert_id;
913
+				}
914
+			}
915
+		}
916
+		// QUESTIONS
917
+		global $wpdb;
918
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
919
+		$SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
920
+		// what we have
921
+		$questions = $wpdb->get_col($SQL);
922
+		// what we should have
923
+		$QST_systems = array(
924
+			'fname',
925
+			'lname',
926
+			'email',
927
+			'address',
928
+			'address2',
929
+			'city',
930
+			'country',
931
+			'state',
932
+			'zip',
933
+			'phone',
934
+		);
935
+		$order_for_group_1 = 1;
936
+		$order_for_group_2 = 1;
937
+		// loop thru what we should have and compare to what we have
938
+		foreach ($QST_systems as $QST_system) {
939
+			// reset values array
940
+			$QST_values = array();
941
+			// if we don't have what we should have
942
+			if ( ! in_array($QST_system, $questions)) {
943
+				// add it
944
+				switch ($QST_system) {
945
+					case 'fname':
946
+						$QST_values = array(
947
+							'QST_display_text'  => __('First Name', 'event_espresso'),
948
+							'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
949
+							'QST_system'        => 'fname',
950
+							'QST_type'          => 'TEXT',
951
+							'QST_required'      => 1,
952
+							'QST_required_text' => __('This field is required', 'event_espresso'),
953
+							'QST_order'         => 1,
954
+							'QST_admin_only'    => 0,
955
+							'QST_max'           => EEM_Question::instance()
956
+															   ->absolute_max_for_system_question($QST_system),
957
+							'QST_wp_user'       => self::get_default_creator_id(),
958
+							'QST_deleted'       => 0,
959
+						);
960
+						break;
961
+					case 'lname':
962
+						$QST_values = array(
963
+							'QST_display_text'  => __('Last Name', 'event_espresso'),
964
+							'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
965
+							'QST_system'        => 'lname',
966
+							'QST_type'          => 'TEXT',
967
+							'QST_required'      => 1,
968
+							'QST_required_text' => __('This field is required', 'event_espresso'),
969
+							'QST_order'         => 2,
970
+							'QST_admin_only'    => 0,
971
+							'QST_max'           => EEM_Question::instance()
972
+															   ->absolute_max_for_system_question($QST_system),
973
+							'QST_wp_user'       => self::get_default_creator_id(),
974
+							'QST_deleted'       => 0,
975
+						);
976
+						break;
977
+					case 'email':
978
+						$QST_values = array(
979
+							'QST_display_text'  => __('Email Address', 'event_espresso'),
980
+							'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
981
+							'QST_system'        => 'email',
982
+							'QST_type'          => 'EMAIL',
983
+							'QST_required'      => 1,
984
+							'QST_required_text' => __('This field is required', 'event_espresso'),
985
+							'QST_order'         => 3,
986
+							'QST_admin_only'    => 0,
987
+							'QST_max'           => EEM_Question::instance()
988
+															   ->absolute_max_for_system_question($QST_system),
989
+							'QST_wp_user'       => self::get_default_creator_id(),
990
+							'QST_deleted'       => 0,
991
+						);
992
+						break;
993
+					case 'address':
994
+						$QST_values = array(
995
+							'QST_display_text'  => __('Address', 'event_espresso'),
996
+							'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
997
+							'QST_system'        => 'address',
998
+							'QST_type'          => 'TEXT',
999
+							'QST_required'      => 0,
1000
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1001
+							'QST_order'         => 4,
1002
+							'QST_admin_only'    => 0,
1003
+							'QST_max'           => EEM_Question::instance()
1004
+															   ->absolute_max_for_system_question($QST_system),
1005
+							'QST_wp_user'       => self::get_default_creator_id(),
1006
+							'QST_deleted'       => 0,
1007
+						);
1008
+						break;
1009
+					case 'address2':
1010
+						$QST_values = array(
1011
+							'QST_display_text'  => __('Address2', 'event_espresso'),
1012
+							'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
1013
+							'QST_system'        => 'address2',
1014
+							'QST_type'          => 'TEXT',
1015
+							'QST_required'      => 0,
1016
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1017
+							'QST_order'         => 5,
1018
+							'QST_admin_only'    => 0,
1019
+							'QST_max'           => EEM_Question::instance()
1020
+															   ->absolute_max_for_system_question($QST_system),
1021
+							'QST_wp_user'       => self::get_default_creator_id(),
1022
+							'QST_deleted'       => 0,
1023
+						);
1024
+						break;
1025
+					case 'city':
1026
+						$QST_values = array(
1027
+							'QST_display_text'  => __('City', 'event_espresso'),
1028
+							'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1029
+							'QST_system'        => 'city',
1030
+							'QST_type'          => 'TEXT',
1031
+							'QST_required'      => 0,
1032
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1033
+							'QST_order'         => 6,
1034
+							'QST_admin_only'    => 0,
1035
+							'QST_max'           => EEM_Question::instance()
1036
+															   ->absolute_max_for_system_question($QST_system),
1037
+							'QST_wp_user'       => self::get_default_creator_id(),
1038
+							'QST_deleted'       => 0,
1039
+						);
1040
+						break;
1041
+					case 'country' :
1042
+						$QST_values = array(
1043
+							'QST_display_text'  => __('Country', 'event_espresso'),
1044
+							'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1045
+							'QST_system'        => 'country',
1046
+							'QST_type'          => 'COUNTRY',
1047
+							'QST_required'      => 0,
1048
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1049
+							'QST_order'         => 7,
1050
+							'QST_admin_only'    => 0,
1051
+							'QST_wp_user'       => self::get_default_creator_id(),
1052
+							'QST_deleted'       => 0,
1053
+						);
1054
+						break;
1055
+					case 'state':
1056
+						$QST_values = array(
1057
+							'QST_display_text'  => __('State/Province', 'event_espresso'),
1058
+							'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1059
+							'QST_system'        => 'state',
1060
+							'QST_type'          => 'STATE',
1061
+							'QST_required'      => 0,
1062
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1063
+							'QST_order'         => 8,
1064
+							'QST_admin_only'    => 0,
1065
+							'QST_wp_user'       => self::get_default_creator_id(),
1066
+							'QST_deleted'       => 0,
1067
+						);
1068
+						break;
1069
+					case 'zip':
1070
+						$QST_values = array(
1071
+							'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1072
+							'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1073
+							'QST_system'        => 'zip',
1074
+							'QST_type'          => 'TEXT',
1075
+							'QST_required'      => 0,
1076
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1077
+							'QST_order'         => 9,
1078
+							'QST_admin_only'    => 0,
1079
+							'QST_max'           => EEM_Question::instance()
1080
+															   ->absolute_max_for_system_question($QST_system),
1081
+							'QST_wp_user'       => self::get_default_creator_id(),
1082
+							'QST_deleted'       => 0,
1083
+						);
1084
+						break;
1085
+					case 'phone':
1086
+						$QST_values = array(
1087
+							'QST_display_text'  => __('Phone Number', 'event_espresso'),
1088
+							'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1089
+							'QST_system'        => 'phone',
1090
+							'QST_type'          => 'TEXT',
1091
+							'QST_required'      => 0,
1092
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1093
+							'QST_order'         => 10,
1094
+							'QST_admin_only'    => 0,
1095
+							'QST_max'           => EEM_Question::instance()
1096
+															   ->absolute_max_for_system_question($QST_system),
1097
+							'QST_wp_user'       => self::get_default_creator_id(),
1098
+							'QST_deleted'       => 0,
1099
+						);
1100
+						break;
1101
+				}
1102
+				if ( ! empty($QST_values)) {
1103
+					// insert system question
1104
+					$wpdb->insert(
1105
+						$table_name,
1106
+						$QST_values,
1107
+						array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1108
+					);
1109
+					$QST_ID = $wpdb->insert_id;
1110
+					// QUESTION GROUP QUESTIONS
1111
+					if (in_array($QST_system, array('fname', 'lname', 'email'))) {
1112
+						$system_question_we_want = EEM_Question_Group::system_personal;
1113
+					} else {
1114
+						$system_question_we_want = EEM_Question_Group::system_address;
1115
+					}
1116
+					if (isset($QSG_IDs[$system_question_we_want])) {
1117
+						$QSG_ID = $QSG_IDs[$system_question_we_want];
1118
+					} else {
1119
+						$id_col = EEM_Question_Group::instance()
1120
+													->get_col(array(array('QSG_system' => $system_question_we_want)));
1121
+						if (is_array($id_col)) {
1122
+							$QSG_ID = reset($id_col);
1123
+						} else {
1124
+							//ok so we didn't find it in the db either?? that's weird because we should have inserted it at the start of this method
1125
+							EE_Log::instance()->log(
1126
+								__FILE__,
1127
+								__FUNCTION__,
1128
+								sprintf(
1129
+									__('Could not associate question %1$s to a question group because no system question group existed',
1130
+										'event_espresso'),
1131
+									$QST_ID),
1132
+								'error');
1133
+							continue;
1134
+						}
1135
+					}
1136
+					// add system questions to groups
1137
+					$wpdb->insert(
1138
+						\EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1139
+						array(
1140
+							'QSG_ID'    => $QSG_ID,
1141
+							'QST_ID'    => $QST_ID,
1142
+							'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1143
+						),
1144
+						array('%d', '%d', '%d')
1145
+					);
1146
+				}
1147
+			}
1148
+		}
1149
+	}
1150 1150
 
1151 1151
 
1152 1152
 
@@ -1332,111 +1332,111 @@  discard block
 block discarded – undo
1332 1332
 
1333 1333
 
1334 1334
 
1335
-    /**
1336
-     * @param \EE_Message_Resource_Manager $message_resource_manager
1337
-     * @return array|bool
1338
-     * @throws \EE_Error
1339
-     */
1340
-    protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1341
-        EE_Message_Resource_Manager $message_resource_manager
1342
-    ) {
1343
-        /** @type EE_messenger[] $active_messengers */
1344
-        $active_messengers = $message_resource_manager->active_messengers();
1345
-        $installed_message_types = $message_resource_manager->installed_message_types();
1346
-        $templates_created = false;
1347
-        foreach ($active_messengers as $active_messenger) {
1348
-            $default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1349
-            $default_message_type_names_to_activate = array();
1350
-            // looping through each default message type reported by the messenger
1351
-            // and setup the actual message types to activate.
1352
-            foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1353
-                // if already active or has already been activated before we skip
1354
-                // (otherwise we might reactivate something user's intentionally deactivated.)
1355
-                // we also skip if the message type is not installed.
1356
-                if (
1357
-                    $message_resource_manager->has_message_type_been_activated_for_messenger($default_message_type_name_for_messenger,
1358
-                        $active_messenger->name)
1359
-                    || $message_resource_manager->is_message_type_active_for_messenger(
1360
-                        $active_messenger->name,
1361
-                        $default_message_type_name_for_messenger
1362
-                    )
1363
-                    || ! isset($installed_message_types[$default_message_type_name_for_messenger])
1364
-                ) {
1365
-                    continue;
1366
-                }
1367
-                $default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1368
-            }
1369
-            //let's activate!
1370
-            $message_resource_manager->ensure_message_types_are_active(
1371
-                $default_message_type_names_to_activate,
1372
-                $active_messenger->name,
1373
-                false
1374
-            );
1375
-            //activate the templates for these message types
1376
-            if ( ! empty($default_message_type_names_to_activate)) {
1377
-                $templates_created = EEH_MSG_Template::generate_new_templates(
1378
-                    $active_messenger->name,
1379
-                    $default_message_type_names_for_messenger,
1380
-                    '',
1381
-                    true
1382
-                );
1383
-            }
1384
-        }
1385
-        return $templates_created;
1386
-    }
1387
-
1388
-
1389
-
1390
-    /**
1391
-     * This will activate and generate default messengers and default message types for those messengers.
1392
-     *
1393
-     * @param EE_message_Resource_Manager $message_resource_manager
1394
-     * @return array|bool  True means there were default messengers and message type templates generated.
1395
-     *                     False means that there were no templates generated
1396
-     *                     (which could simply mean there are no default message types for a messenger).
1397
-     * @throws EE_Error
1398
-     */
1399
-    protected static function _activate_and_generate_default_messengers_and_message_templates(
1400
-        EE_Message_Resource_Manager $message_resource_manager
1401
-    ) {
1402
-        /** @type EE_messenger[] $messengers_to_generate */
1403
-        $messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1404
-        $installed_message_types = $message_resource_manager->installed_message_types();
1405
-        $templates_generated = false;
1406
-        foreach ($messengers_to_generate as $messenger_to_generate) {
1407
-            $default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1408
-            //verify the default message types match an installed message type.
1409
-            foreach ($default_message_type_names_for_messenger as $key => $name) {
1410
-                if (
1411
-                    ! isset($installed_message_types[$name])
1412
-                    || $message_resource_manager->has_message_type_been_activated_for_messenger($name,
1413
-                        $messenger_to_generate->name)
1414
-                ) {
1415
-                    unset($default_message_type_names_for_messenger[$key]);
1416
-                }
1417
-            }
1418
-            // in previous iterations, the active_messengers option in the db
1419
-            // needed updated before calling create templates. however with the changes this may not be necessary.
1420
-            // This comment is left here just in case we discover that we _do_ need to update before
1421
-            // passing off to create templates (after the refactor is done).
1422
-            // @todo remove this comment when determined not necessary.
1423
-            $message_resource_manager->activate_messenger(
1424
-                $messenger_to_generate->name,
1425
-                $default_message_type_names_for_messenger,
1426
-                false
1427
-            );
1428
-            //create any templates needing created (or will reactivate templates already generated as necessary).
1429
-            if ( ! empty($default_message_type_names_for_messenger)) {
1430
-                $templates_generated = EEH_MSG_Template::generate_new_templates(
1431
-                    $messenger_to_generate->name,
1432
-                    $default_message_type_names_for_messenger,
1433
-                    '',
1434
-                    true
1435
-                );
1436
-            }
1437
-        }
1438
-        return $templates_generated;
1439
-    }
1335
+	/**
1336
+	 * @param \EE_Message_Resource_Manager $message_resource_manager
1337
+	 * @return array|bool
1338
+	 * @throws \EE_Error
1339
+	 */
1340
+	protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1341
+		EE_Message_Resource_Manager $message_resource_manager
1342
+	) {
1343
+		/** @type EE_messenger[] $active_messengers */
1344
+		$active_messengers = $message_resource_manager->active_messengers();
1345
+		$installed_message_types = $message_resource_manager->installed_message_types();
1346
+		$templates_created = false;
1347
+		foreach ($active_messengers as $active_messenger) {
1348
+			$default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1349
+			$default_message_type_names_to_activate = array();
1350
+			// looping through each default message type reported by the messenger
1351
+			// and setup the actual message types to activate.
1352
+			foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1353
+				// if already active or has already been activated before we skip
1354
+				// (otherwise we might reactivate something user's intentionally deactivated.)
1355
+				// we also skip if the message type is not installed.
1356
+				if (
1357
+					$message_resource_manager->has_message_type_been_activated_for_messenger($default_message_type_name_for_messenger,
1358
+						$active_messenger->name)
1359
+					|| $message_resource_manager->is_message_type_active_for_messenger(
1360
+						$active_messenger->name,
1361
+						$default_message_type_name_for_messenger
1362
+					)
1363
+					|| ! isset($installed_message_types[$default_message_type_name_for_messenger])
1364
+				) {
1365
+					continue;
1366
+				}
1367
+				$default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1368
+			}
1369
+			//let's activate!
1370
+			$message_resource_manager->ensure_message_types_are_active(
1371
+				$default_message_type_names_to_activate,
1372
+				$active_messenger->name,
1373
+				false
1374
+			);
1375
+			//activate the templates for these message types
1376
+			if ( ! empty($default_message_type_names_to_activate)) {
1377
+				$templates_created = EEH_MSG_Template::generate_new_templates(
1378
+					$active_messenger->name,
1379
+					$default_message_type_names_for_messenger,
1380
+					'',
1381
+					true
1382
+				);
1383
+			}
1384
+		}
1385
+		return $templates_created;
1386
+	}
1387
+
1388
+
1389
+
1390
+	/**
1391
+	 * This will activate and generate default messengers and default message types for those messengers.
1392
+	 *
1393
+	 * @param EE_message_Resource_Manager $message_resource_manager
1394
+	 * @return array|bool  True means there were default messengers and message type templates generated.
1395
+	 *                     False means that there were no templates generated
1396
+	 *                     (which could simply mean there are no default message types for a messenger).
1397
+	 * @throws EE_Error
1398
+	 */
1399
+	protected static function _activate_and_generate_default_messengers_and_message_templates(
1400
+		EE_Message_Resource_Manager $message_resource_manager
1401
+	) {
1402
+		/** @type EE_messenger[] $messengers_to_generate */
1403
+		$messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1404
+		$installed_message_types = $message_resource_manager->installed_message_types();
1405
+		$templates_generated = false;
1406
+		foreach ($messengers_to_generate as $messenger_to_generate) {
1407
+			$default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1408
+			//verify the default message types match an installed message type.
1409
+			foreach ($default_message_type_names_for_messenger as $key => $name) {
1410
+				if (
1411
+					! isset($installed_message_types[$name])
1412
+					|| $message_resource_manager->has_message_type_been_activated_for_messenger($name,
1413
+						$messenger_to_generate->name)
1414
+				) {
1415
+					unset($default_message_type_names_for_messenger[$key]);
1416
+				}
1417
+			}
1418
+			// in previous iterations, the active_messengers option in the db
1419
+			// needed updated before calling create templates. however with the changes this may not be necessary.
1420
+			// This comment is left here just in case we discover that we _do_ need to update before
1421
+			// passing off to create templates (after the refactor is done).
1422
+			// @todo remove this comment when determined not necessary.
1423
+			$message_resource_manager->activate_messenger(
1424
+				$messenger_to_generate->name,
1425
+				$default_message_type_names_for_messenger,
1426
+				false
1427
+			);
1428
+			//create any templates needing created (or will reactivate templates already generated as necessary).
1429
+			if ( ! empty($default_message_type_names_for_messenger)) {
1430
+				$templates_generated = EEH_MSG_Template::generate_new_templates(
1431
+					$messenger_to_generate->name,
1432
+					$default_message_type_names_for_messenger,
1433
+					'',
1434
+					true
1435
+				);
1436
+			}
1437
+		}
1438
+		return $templates_generated;
1439
+	}
1440 1440
 
1441 1441
 
1442 1442
 
@@ -1604,111 +1604,111 @@  discard block
 block discarded – undo
1604 1604
 
1605 1605
 
1606 1606
 
1607
-    /**
1608
-     * Drops all the tables mentioned in a single MYSQL query. Double-checks
1609
-     * each table name provided has a wpdb prefix attached, and that it exists.
1610
-     * Returns the list actually deleted
1611
-     *
1612
-     * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1613
-     * @global WPDB $wpdb
1614
-     * @param array $table_names
1615
-     * @return array of table names which we deleted
1616
-     */
1617
-    public static function drop_tables($table_names)
1618
-    {
1619
-        return \EEH_Activation::getTableManager()->dropTables($table_names);
1620
-    }
1621
-
1622
-
1623
-
1624
-    /**
1625
-     * plugin_uninstall
1626
-     *
1627
-     * @access public
1628
-     * @static
1629
-     * @param bool $remove_all
1630
-     * @return void
1631
-     */
1632
-    public static function delete_all_espresso_tables_and_data($remove_all = true)
1633
-    {
1634
-        global $wpdb;
1635
-        self::drop_espresso_tables();
1636
-        $wp_options_to_delete = array(
1637
-            'ee_no_ticket_prices'                => true,
1638
-            'ee_active_messengers'               => true,
1639
-            'ee_has_activated_messenger'         => true,
1640
-            'ee_flush_rewrite_rules'             => true,
1641
-            'ee_config'                          => false,
1642
-            'ee_data_migration_current_db_state' => true,
1643
-            'ee_data_migration_mapping_'         => false,
1644
-            'ee_data_migration_script_'          => false,
1645
-            'ee_data_migrations'                 => true,
1646
-            'ee_dms_map'                         => false,
1647
-            'ee_notices'                         => true,
1648
-            'lang_file_check_'                   => false,
1649
-            'ee_maintenance_mode'                => true,
1650
-            'ee_ueip_optin'                      => true,
1651
-            'ee_ueip_has_notified'               => true,
1652
-            'ee_plugin_activation_errors'        => true,
1653
-            'ee_id_mapping_from'                 => false,
1654
-            'espresso_persistent_admin_notices'  => true,
1655
-            'ee_encryption_key'                  => true,
1656
-            'pue_force_upgrade_'                 => false,
1657
-            'pue_json_error_'                    => false,
1658
-            'pue_install_key_'                   => false,
1659
-            'pue_verification_error_'            => false,
1660
-            'pu_dismissed_upgrade_'              => false,
1661
-            'external_updates-'                  => false,
1662
-            'ee_extra_data'                      => true,
1663
-            'ee_ssn_'                            => false,
1664
-            'ee_rss_'                            => false,
1665
-            'ee_rte_n_tx_'                       => false,
1666
-            'ee_pers_admin_notices'              => true,
1667
-            'ee_job_parameters_'                 => false,
1668
-            'ee_upload_directories_incomplete'   => true,
1669
-            'ee_verified_db_collations'          => true,
1670
-        );
1671
-        if (is_main_site()) {
1672
-            $wp_options_to_delete['ee_network_config'] = true;
1673
-        }
1674
-        $undeleted_options = array();
1675
-        foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1676
-            if ($no_wildcard) {
1677
-                if ( ! delete_option($option_name)) {
1678
-                    $undeleted_options[] = $option_name;
1679
-                }
1680
-            } else {
1681
-                $option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1682
-                foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1683
-                    if ( ! delete_option($option_name_from_wildcard)) {
1684
-                        $undeleted_options[] = $option_name_from_wildcard;
1685
-                    }
1686
-                }
1687
-            }
1688
-        }
1689
-        //also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1690
-        remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1691
-        if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1692
-            $db_update_sans_ee4 = array();
1693
-            foreach ($espresso_db_update as $version => $times_activated) {
1694
-                if ((string)$version[0] === '3') {//if its NON EE4
1695
-                    $db_update_sans_ee4[$version] = $times_activated;
1696
-                }
1697
-            }
1698
-            update_option('espresso_db_update', $db_update_sans_ee4);
1699
-        }
1700
-        $errors = '';
1701
-        if ( ! empty($undeleted_options)) {
1702
-            $errors .= sprintf(
1703
-                __('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1704
-                '<br/>',
1705
-                implode(',<br/>', $undeleted_options)
1706
-            );
1707
-        }
1708
-        if ( ! empty($errors)) {
1709
-            EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1710
-        }
1711
-    }
1607
+	/**
1608
+	 * Drops all the tables mentioned in a single MYSQL query. Double-checks
1609
+	 * each table name provided has a wpdb prefix attached, and that it exists.
1610
+	 * Returns the list actually deleted
1611
+	 *
1612
+	 * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1613
+	 * @global WPDB $wpdb
1614
+	 * @param array $table_names
1615
+	 * @return array of table names which we deleted
1616
+	 */
1617
+	public static function drop_tables($table_names)
1618
+	{
1619
+		return \EEH_Activation::getTableManager()->dropTables($table_names);
1620
+	}
1621
+
1622
+
1623
+
1624
+	/**
1625
+	 * plugin_uninstall
1626
+	 *
1627
+	 * @access public
1628
+	 * @static
1629
+	 * @param bool $remove_all
1630
+	 * @return void
1631
+	 */
1632
+	public static function delete_all_espresso_tables_and_data($remove_all = true)
1633
+	{
1634
+		global $wpdb;
1635
+		self::drop_espresso_tables();
1636
+		$wp_options_to_delete = array(
1637
+			'ee_no_ticket_prices'                => true,
1638
+			'ee_active_messengers'               => true,
1639
+			'ee_has_activated_messenger'         => true,
1640
+			'ee_flush_rewrite_rules'             => true,
1641
+			'ee_config'                          => false,
1642
+			'ee_data_migration_current_db_state' => true,
1643
+			'ee_data_migration_mapping_'         => false,
1644
+			'ee_data_migration_script_'          => false,
1645
+			'ee_data_migrations'                 => true,
1646
+			'ee_dms_map'                         => false,
1647
+			'ee_notices'                         => true,
1648
+			'lang_file_check_'                   => false,
1649
+			'ee_maintenance_mode'                => true,
1650
+			'ee_ueip_optin'                      => true,
1651
+			'ee_ueip_has_notified'               => true,
1652
+			'ee_plugin_activation_errors'        => true,
1653
+			'ee_id_mapping_from'                 => false,
1654
+			'espresso_persistent_admin_notices'  => true,
1655
+			'ee_encryption_key'                  => true,
1656
+			'pue_force_upgrade_'                 => false,
1657
+			'pue_json_error_'                    => false,
1658
+			'pue_install_key_'                   => false,
1659
+			'pue_verification_error_'            => false,
1660
+			'pu_dismissed_upgrade_'              => false,
1661
+			'external_updates-'                  => false,
1662
+			'ee_extra_data'                      => true,
1663
+			'ee_ssn_'                            => false,
1664
+			'ee_rss_'                            => false,
1665
+			'ee_rte_n_tx_'                       => false,
1666
+			'ee_pers_admin_notices'              => true,
1667
+			'ee_job_parameters_'                 => false,
1668
+			'ee_upload_directories_incomplete'   => true,
1669
+			'ee_verified_db_collations'          => true,
1670
+		);
1671
+		if (is_main_site()) {
1672
+			$wp_options_to_delete['ee_network_config'] = true;
1673
+		}
1674
+		$undeleted_options = array();
1675
+		foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1676
+			if ($no_wildcard) {
1677
+				if ( ! delete_option($option_name)) {
1678
+					$undeleted_options[] = $option_name;
1679
+				}
1680
+			} else {
1681
+				$option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1682
+				foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1683
+					if ( ! delete_option($option_name_from_wildcard)) {
1684
+						$undeleted_options[] = $option_name_from_wildcard;
1685
+					}
1686
+				}
1687
+			}
1688
+		}
1689
+		//also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1690
+		remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1691
+		if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1692
+			$db_update_sans_ee4 = array();
1693
+			foreach ($espresso_db_update as $version => $times_activated) {
1694
+				if ((string)$version[0] === '3') {//if its NON EE4
1695
+					$db_update_sans_ee4[$version] = $times_activated;
1696
+				}
1697
+			}
1698
+			update_option('espresso_db_update', $db_update_sans_ee4);
1699
+		}
1700
+		$errors = '';
1701
+		if ( ! empty($undeleted_options)) {
1702
+			$errors .= sprintf(
1703
+				__('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1704
+				'<br/>',
1705
+				implode(',<br/>', $undeleted_options)
1706
+			);
1707
+		}
1708
+		if ( ! empty($errors)) {
1709
+			EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1710
+		}
1711
+	}
1712 1712
 
1713 1713
 	/**
1714 1714
 	 * Gets the mysql error code from the last used query by wpdb
Please login to merge, or discard this patch.
Spacing   +130 added lines, -130 removed lines patch added patch discarded remove patch
@@ -61,8 +61,8 @@  discard block
 block discarded – undo
61 61
 	 * @return \EventEspresso\core\services\database\TableAnalysis
62 62
 	 */
63 63
 	public static function getTableAnalysis() {
64
-		if ( ! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis ) {
65
-			self::$table_analysis = EE_Registry::instance()->create( 'TableAnalysis', array(), true );
64
+		if ( ! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
65
+			self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
66 66
 		}
67 67
 		return self::$table_analysis;
68 68
 	}
@@ -73,8 +73,8 @@  discard block
 block discarded – undo
73 73
 	 * @return \EventEspresso\core\services\database\TableManager
74 74
 	 */
75 75
 	public static function getTableManager() {
76
-		if ( ! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager ) {
77
-			self::$table_manager = EE_Registry::instance()->create( 'TableManager', array(), true );
76
+		if ( ! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
77
+			self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
78 78
 		}
79 79
 		return self::$table_manager;
80 80
 	}
@@ -89,8 +89,8 @@  discard block
 block discarded – undo
89 89
 	 * @param $table_name
90 90
 	 * @return string
91 91
 	 */
92
-	public static function ensure_table_name_has_prefix( $table_name ) {
93
-		return \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix( $table_name );
92
+	public static function ensure_table_name_has_prefix($table_name) {
93
+		return \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
94 94
 	}
95 95
 
96 96
 
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
 	 * @return boolean success, whether the database and folders are setup properly
119 119
 	 * @throws \EE_Error
120 120
 	 */
121
-	public static function initialize_db_and_folders(){
121
+	public static function initialize_db_and_folders() {
122 122
 		$good_filesystem = EEH_Activation::create_upload_directories();
123 123
 		$good_db = EEH_Activation::create_database_tables();
124 124
 		return $good_filesystem && $good_db;
@@ -134,9 +134,9 @@  discard block
 block discarded – undo
134 134
 	 *
135 135
 	 * @throws \EE_Error
136 136
 	 */
137
-	public static function initialize_db_content(){
137
+	public static function initialize_db_content() {
138 138
 		//let's avoid doing all this logic repeatedly, especially when addons are requesting it
139
-		if( EEH_Activation::$_initialized_db_content_already_in_this_request ) {
139
+		if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
140 140
 			return;
141 141
 		}
142 142
 		EEH_Activation::$_initialized_db_content_already_in_this_request = true;
@@ -153,9 +153,9 @@  discard block
 block discarded – undo
153 153
 		EEH_Activation::remove_cron_tasks();
154 154
 		EEH_Activation::create_cron_tasks();
155 155
 		// remove all TXN locks since that is being done via extra meta now
156
-		delete_option( 'ee_locked_transactions' );
156
+		delete_option('ee_locked_transactions');
157 157
 		//also, check for CAF default db content
158
-		do_action( 'AHEE__EEH_Activation__initialize_db_content' );
158
+		do_action('AHEE__EEH_Activation__initialize_db_content');
159 159
 		//also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
160 160
 		//which users really won't care about on initial activation
161 161
 		EE_Error::overwrite_success();
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 	 * @return array
176 176
 	 * @throws \EE_Error
177 177
 	 */
178
-	public static function get_cron_tasks( $which_to_include ) {
178
+	public static function get_cron_tasks($which_to_include) {
179 179
 		$cron_tasks = apply_filters(
180 180
 			'FHEE__EEH_Activation__get_cron_tasks',
181 181
 			array(
@@ -184,16 +184,16 @@  discard block
 block discarded – undo
184 184
 				'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use, //there may have been a bug which prevented from these cron tasks from getting unscheduled, so we might want to remove these for a few updates
185 185
 			)
186 186
 		);
187
-		if ( $which_to_include === 'old' ) {
187
+		if ($which_to_include === 'old') {
188 188
 			$cron_tasks = array_filter(
189 189
 				$cron_tasks,
190
-				function ( $value ) {
190
+				function($value) {
191 191
 					return $value === EEH_Activation::cron_task_no_longer_in_use;
192 192
 				}
193 193
 			);
194
-		} elseif ( $which_to_include === 'current' ) {
195
-			$cron_tasks = array_filter( $cron_tasks );
196
-		} elseif ( WP_DEBUG && $which_to_include !== 'all' ) {
194
+		} elseif ($which_to_include === 'current') {
195
+			$cron_tasks = array_filter($cron_tasks);
196
+		} elseif (WP_DEBUG && $which_to_include !== 'all') {
197 197
 			throw new EE_Error(
198 198
 				sprintf(
199 199
 					__(
@@ -216,9 +216,9 @@  discard block
 block discarded – undo
216 216
 	 */
217 217
 	public static function create_cron_tasks() {
218 218
 
219
-		foreach( EEH_Activation::get_cron_tasks( 'current' ) as $hook_name => $frequency ) {
220
-			if( ! wp_next_scheduled( $hook_name ) ) {
221
-				wp_schedule_event( time(), $frequency, $hook_name );
219
+		foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
220
+			if ( ! wp_next_scheduled($hook_name)) {
221
+				wp_schedule_event(time(), $frequency, $hook_name);
222 222
 			}
223 223
 		}
224 224
 
@@ -232,10 +232,10 @@  discard block
 block discarded – undo
232 232
 	 * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
233 233
 	 * @throws \EE_Error
234 234
 	 */
235
-	public static function remove_cron_tasks( $remove_all = true ) {
235
+	public static function remove_cron_tasks($remove_all = true) {
236 236
 		$cron_tasks_to_remove = $remove_all ? 'all' : 'old';
237 237
 		$crons = _get_cron_array();
238
-		$crons = is_array( $crons ) ? $crons : array();
238
+		$crons = is_array($crons) ? $crons : array();
239 239
 		/* reminder of what $crons look like:
240 240
 		 * Top-level keys are timestamps, and their values are arrays.
241 241
 		 * The 2nd level arrays have keys with each of the cron task hook names to run at that time
@@ -253,23 +253,23 @@  discard block
 block discarded – undo
253 253
 		 *					...
254 254
 		 *      ...
255 255
 		 */
256
-		$ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks( $cron_tasks_to_remove );
257
-		foreach ( $crons as $timestamp => $hooks_to_fire_at_time ) {
258
-			if ( is_array( $hooks_to_fire_at_time ) ) {
259
-				foreach ( $hooks_to_fire_at_time as $hook_name => $hook_actions ) {
260
-					if ( isset( $ee_cron_tasks_to_remove[ $hook_name ] )
261
-					     && is_array( $ee_cron_tasks_to_remove[ $hook_name ] )
256
+		$ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
257
+		foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
258
+			if (is_array($hooks_to_fire_at_time)) {
259
+				foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
260
+					if (isset($ee_cron_tasks_to_remove[$hook_name])
261
+					     && is_array($ee_cron_tasks_to_remove[$hook_name])
262 262
 					) {
263
-						unset( $crons[ $timestamp ][ $hook_name ] );
263
+						unset($crons[$timestamp][$hook_name]);
264 264
 					}
265 265
 				}
266 266
 				//also take care of any empty cron timestamps.
267
-				if ( empty( $hooks_to_fire_at_time ) ) {
268
-					unset( $crons[ $timestamp ] );
267
+				if (empty($hooks_to_fire_at_time)) {
268
+					unset($crons[$timestamp]);
269 269
 				}
270 270
 			}
271 271
 		}
272
-		_set_cron_array( $crons );
272
+		_set_cron_array($crons);
273 273
 	}
274 274
 
275 275
 
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
 	 */
285 285
 	public static function CPT_initialization() {
286 286
 		// register Custom Post Types
287
-		EE_Registry::instance()->load_core( 'Register_CPTs' );
287
+		EE_Registry::instance()->load_core('Register_CPTs');
288 288
 		flush_rewrite_rules();
289 289
 	}
290 290
 
@@ -320,28 +320,28 @@  discard block
 block discarded – undo
320 320
 	 */
321 321
 	public static function load_calendar_config() {
322 322
 		// grab array of all plugin folders and loop thru it
323
-		$plugins = glob( WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR );
324
-		if ( empty( $plugins ) ) {
323
+		$plugins = glob(WP_PLUGIN_DIR.DS.'*', GLOB_ONLYDIR);
324
+		if (empty($plugins)) {
325 325
 			return;
326 326
 		}
327
-		foreach ( $plugins as $plugin_path ) {
327
+		foreach ($plugins as $plugin_path) {
328 328
 			// grab plugin folder name from path
329
-			$plugin = basename( $plugin_path );
329
+			$plugin = basename($plugin_path);
330 330
 			// drill down to Espresso plugins
331 331
 			// then to calendar related plugins
332 332
 			if (
333
-				strpos( $plugin, 'espresso' ) !== FALSE
334
-				|| strpos( $plugin, 'Espresso' ) !== FALSE
335
-				|| strpos( $plugin, 'ee4' ) !== FALSE
336
-				|| strpos( $plugin, 'EE4' ) !== FALSE
337
-				|| strpos( $plugin, 'calendar' ) !== false
333
+				strpos($plugin, 'espresso') !== FALSE
334
+				|| strpos($plugin, 'Espresso') !== FALSE
335
+				|| strpos($plugin, 'ee4') !== FALSE
336
+				|| strpos($plugin, 'EE4') !== FALSE
337
+				|| strpos($plugin, 'calendar') !== false
338 338
 			) {
339 339
 				// this is what we are looking for
340
-				$calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
340
+				$calendar_config = $plugin_path.DS.'EE_Calendar_Config.php';
341 341
 				// does it exist in this folder ?
342
-				if ( is_readable( $calendar_config )) {
342
+				if (is_readable($calendar_config)) {
343 343
 					// YEAH! let's load it
344
-					require_once( $calendar_config );
344
+					require_once($calendar_config);
345 345
 				}
346 346
 			}
347 347
 		}
@@ -389,8 +389,8 @@  discard block
 block discarded – undo
389 389
 	 */
390 390
 	public static function deactivate_event_espresso() {
391 391
 		// check permissions
392
-		if ( current_user_can( 'activate_plugins' )) {
393
-			deactivate_plugins( EE_PLUGIN_BASENAME, TRUE );
392
+		if (current_user_can('activate_plugins')) {
393
+			deactivate_plugins(EE_PLUGIN_BASENAME, TRUE);
394 394
 		}
395 395
 	}
396 396
 
@@ -513,7 +513,7 @@  discard block
 block discarded – undo
513 513
     public static function get_page_by_ee_shortcode($ee_shortcode)
514 514
     {
515 515
         global $wpdb;
516
-        $shortcode_and_opening_bracket = '[' . $ee_shortcode;
516
+        $shortcode_and_opening_bracket = '['.$ee_shortcode;
517 517
         $post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
518 518
         if ($post_id) {
519 519
             return get_post($post_id);
@@ -533,32 +533,32 @@  discard block
 block discarded – undo
533 533
 	 * @param array $critical_page
534 534
 	 * @return array
535 535
 	 */
536
-	public static function create_critical_page( $critical_page ) {
536
+	public static function create_critical_page($critical_page) {
537 537
 
538 538
 		$post_args = array(
539 539
 			'post_title' => $critical_page['name'],
540 540
 			'post_status' => 'publish',
541 541
 			'post_type' => 'page',
542 542
 			'comment_status' => 'closed',
543
-			'post_content' => '[' . $critical_page['code'] . ']'
543
+			'post_content' => '['.$critical_page['code'].']'
544 544
 		);
545 545
 
546
-		$post_id = wp_insert_post( $post_args );
547
-		if ( ! $post_id ) {
546
+		$post_id = wp_insert_post($post_args);
547
+		if ( ! $post_id) {
548 548
 			$msg = sprintf(
549
-				__( 'The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso' ),
549
+				__('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
550 550
 				$critical_page['name']
551 551
 			);
552
-			EE_Error::add_error( $msg, __FILE__, __FUNCTION__, __LINE__ );
552
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
553 553
 			return $critical_page;
554 554
 		}
555 555
 		// get newly created post's details
556
-		if ( ! $critical_page['post'] = get_post( $post_id )) {
556
+		if ( ! $critical_page['post'] = get_post($post_id)) {
557 557
 			$msg = sprintf(
558
-				__( 'The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso' ),
558
+				__('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
559 559
 				$critical_page['name']
560 560
 			);
561
-			EE_Error::add_error( $msg, __FILE__, __FUNCTION__, __LINE__ );
561
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
562 562
 		}
563 563
 
564 564
 		return $critical_page;
@@ -633,15 +633,15 @@  discard block
 block discarded – undo
633 633
         $pre_filtered_id = apply_filters('FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id', false,
634 634
             $role_to_check);
635 635
         if ($pre_filtered_id !== false) {
636
-            return (int)$pre_filtered_id;
636
+            return (int) $pre_filtered_id;
637 637
         }
638 638
         $capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
639 639
         $query = $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
640
-            '%' . $role_to_check . '%');
640
+            '%'.$role_to_check.'%');
641 641
         $user_id = $wpdb->get_var($query);
642 642
         $user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
643
-        if ($user_id && (int)$user_id) {
644
-            self::$_default_creator_id = (int)$user_id;
643
+        if ($user_id && (int) $user_id) {
644
+            self::$_default_creator_id = (int) $user_id;
645 645
             return self::$_default_creator_id;
646 646
         } else {
647 647
             return null;
@@ -676,7 +676,7 @@  discard block
 block discarded – undo
676 676
         }
677 677
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
678 678
         if ( ! function_exists('dbDelta')) {
679
-            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
679
+            require_once(ABSPATH.'wp-admin/includes/upgrade.php');
680 680
         }
681 681
         $tableAnalysis = \EEH_Activation::getTableAnalysis();
682 682
         $wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
@@ -690,7 +690,7 @@  discard block
 block discarded – undo
690 690
             } else if ( ! $deleted_safely) {
691 691
                 // so we should be more cautious rather than just dropping tables so easily
692 692
                 EE_Error::add_persistent_admin_notice(
693
-                    'bad_table_' . $wp_table_name . '_detected',
693
+                    'bad_table_'.$wp_table_name.'_detected',
694 694
                     sprintf(__('Database table %1$s exists when it shouldn\'t, and may contain erroneous data. If you have previously restored your database from a backup that didn\'t remove the old tables, then we recommend adding %2$s to your %3$s file then restore to that backup again. This will clear out the invalid data from %1$s. Afterwards you should undo that change from your %3$s file. %4$sIf you cannot edit %3$s, you should remove the data from %1$s manually then restore to the backup again.',
695 695
                         'event_espresso'),
696 696
                         $wp_table_name,
@@ -740,8 +740,8 @@  discard block
 block discarded – undo
740 740
 	 * @param string $table_name, without prefixed $wpdb->prefix
741 741
 	 * @return array of database column names
742 742
 	 */
743
-	public static function get_fields_on_table( $table_name = NULL ) {
744
-		return \EEH_Activation::getTableManager()->getTableColumns( $table_name );
743
+	public static function get_fields_on_table($table_name = NULL) {
744
+		return \EEH_Activation::getTableManager()->getTableColumns($table_name);
745 745
 	}
746 746
 
747 747
 
@@ -755,8 +755,8 @@  discard block
 block discarded – undo
755 755
 	 * @param string $table_name
756 756
 	 * @return bool
757 757
 	 */
758
-	public static function db_table_is_empty( $table_name ) {
759
-		return \EEH_Activation::getTableAnalysis()->tableIsEmpty( $table_name );
758
+	public static function db_table_is_empty($table_name) {
759
+		return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
760 760
 }
761 761
 
762 762
 
@@ -769,9 +769,9 @@  discard block
 block discarded – undo
769 769
 	 * @param string $table_name
770 770
 	 * @return bool | int
771 771
 	 */
772
-	public static function delete_db_table_if_empty( $table_name ) {
773
-		if ( \EEH_Activation::getTableAnalysis()->tableIsEmpty( $table_name ) ) {
774
-			return \EEH_Activation::getTableManager()->dropTable( $table_name );
772
+	public static function delete_db_table_if_empty($table_name) {
773
+		if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
774
+			return \EEH_Activation::getTableManager()->dropTable($table_name);
775 775
 		}
776 776
 		return false;
777 777
 	}
@@ -787,8 +787,8 @@  discard block
 block discarded – undo
787 787
 	 * @param string $table_name
788 788
 	 * @return bool | int
789 789
 	 */
790
-	public static function delete_unused_db_table( $table_name ) {
791
-		return \EEH_Activation::getTableManager()->dropTable( $table_name );
790
+	public static function delete_unused_db_table($table_name) {
791
+		return \EEH_Activation::getTableManager()->dropTable($table_name);
792 792
 	}
793 793
 
794 794
 
@@ -803,8 +803,8 @@  discard block
 block discarded – undo
803 803
 	 * @param string $index_name
804 804
 	 * @return bool | int
805 805
 	 */
806
-	public static function drop_index( $table_name, $index_name ) {
807
-		return \EEH_Activation::getTableManager()->dropIndex( $table_name, $index_name );
806
+	public static function drop_index($table_name, $index_name) {
807
+		return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
808 808
 	}
809 809
 
810 810
 
@@ -879,7 +879,7 @@  discard block
 block discarded – undo
879 879
                     case 1:
880 880
                         $QSG_values = array(
881 881
                             'QSG_name'            => __('Personal Information', 'event_espresso'),
882
-                            'QSG_identifier'      => 'personal-information-' . time(),
882
+                            'QSG_identifier'      => 'personal-information-'.time(),
883 883
                             'QSG_desc'            => '',
884 884
                             'QSG_order'           => 1,
885 885
                             'QSG_show_group_name' => 1,
@@ -891,7 +891,7 @@  discard block
 block discarded – undo
891 891
                     case 2:
892 892
                         $QSG_values = array(
893 893
                             'QSG_name'            => __('Address Information', 'event_espresso'),
894
-                            'QSG_identifier'      => 'address-information-' . time(),
894
+                            'QSG_identifier'      => 'address-information-'.time(),
895 895
                             'QSG_desc'            => '',
896 896
                             'QSG_order'           => 2,
897 897
                             'QSG_show_group_name' => 1,
@@ -1156,11 +1156,11 @@  discard block
 block discarded – undo
1156 1156
 	 *
1157 1157
 	 * @throws \EE_Error
1158 1158
 	 */
1159
-	public static function insert_default_payment_methods(){
1160
-		if( ! EEM_Payment_Method::instance()->count_active( EEM_Payment_Method::scope_cart ) ){
1161
-			EE_Registry::instance()->load_lib( 'Payment_Method_Manager' );
1162
-			EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type( 'Invoice' );
1163
-		}else{
1159
+	public static function insert_default_payment_methods() {
1160
+		if ( ! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1161
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
1162
+			EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1163
+		} else {
1164 1164
 			EEM_Payment_Method::instance()->verify_button_urls();
1165 1165
 		}
1166 1166
 	}
@@ -1176,7 +1176,7 @@  discard block
 block discarded – undo
1176 1176
 
1177 1177
 		global $wpdb;
1178 1178
 
1179
-		if ( \EEH_Activation::getTableAnalysis()->tableExists( EEM_Status::instance()->table() ) ) {
1179
+		if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1180 1180
 
1181 1181
 			$table_name = EEM_Status::instance()->table();
1182 1182
 
@@ -1252,33 +1252,33 @@  discard block
 block discarded – undo
1252 1252
 		$folders = array(
1253 1253
 				EVENT_ESPRESSO_TEMPLATE_DIR,
1254 1254
 				EVENT_ESPRESSO_GATEWAY_DIR,
1255
-				EVENT_ESPRESSO_UPLOAD_DIR . 'logs/',
1256
-				EVENT_ESPRESSO_UPLOAD_DIR . 'css/',
1257
-				EVENT_ESPRESSO_UPLOAD_DIR . 'tickets/'
1255
+				EVENT_ESPRESSO_UPLOAD_DIR.'logs/',
1256
+				EVENT_ESPRESSO_UPLOAD_DIR.'css/',
1257
+				EVENT_ESPRESSO_UPLOAD_DIR.'tickets/'
1258 1258
 		);
1259
-		foreach ( $folders as $folder ) {
1259
+		foreach ($folders as $folder) {
1260 1260
 			try {
1261
-				EEH_File::ensure_folder_exists_and_is_writable( $folder );
1262
-				@ chmod( $folder, 0755 );
1263
-			} catch( EE_Error $e ){
1261
+				EEH_File::ensure_folder_exists_and_is_writable($folder);
1262
+				@ chmod($folder, 0755);
1263
+			} catch (EE_Error $e) {
1264 1264
 				EE_Error::add_error(
1265 1265
 					sprintf(
1266
-						__(  'Could not create the folder at "%1$s" because: %2$s', 'event_espresso' ),
1266
+						__('Could not create the folder at "%1$s" because: %2$s', 'event_espresso'),
1267 1267
 						$folder,
1268
-						'<br />' . $e->getMessage()
1268
+						'<br />'.$e->getMessage()
1269 1269
 					),
1270 1270
 					__FILE__, __FUNCTION__, __LINE__
1271 1271
 				);
1272 1272
 				//indicate we'll need to fix this later
1273
-				update_option( EEH_Activation::upload_directories_incomplete_option_name, true );
1273
+				update_option(EEH_Activation::upload_directories_incomplete_option_name, true);
1274 1274
 				return FALSE;
1275 1275
 			}
1276 1276
 		}
1277 1277
 		//just add the .htaccess file to the logs directory to begin with. Even if logging
1278 1278
 		//is disabled, there might be activation errors recorded in there
1279
-		EEH_File::add_htaccess_deny_from_all( EVENT_ESPRESSO_UPLOAD_DIR . 'logs/' );
1279
+		EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR.'logs/');
1280 1280
 		//remember EE's folders are all good
1281
-		delete_option( EEH_Activation::upload_directories_incomplete_option_name );
1281
+		delete_option(EEH_Activation::upload_directories_incomplete_option_name);
1282 1282
 		return TRUE;
1283 1283
 	}
1284 1284
 
@@ -1291,7 +1291,7 @@  discard block
 block discarded – undo
1291 1291
 	 * @return boolean
1292 1292
 	 */
1293 1293
 	public static function upload_directories_incomplete() {
1294
-		return get_option( EEH_Activation::upload_directories_incomplete_option_name, false );
1294
+		return get_option(EEH_Activation::upload_directories_incomplete_option_name, false);
1295 1295
 	}
1296 1296
 
1297 1297
 
@@ -1308,7 +1308,7 @@  discard block
 block discarded – undo
1308 1308
 	 */
1309 1309
 	public static function generate_default_message_templates() {
1310 1310
 		/** @type EE_Message_Resource_Manager $message_resource_manager */
1311
-		$message_resource_manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' );
1311
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1312 1312
 		/*
1313 1313
 		 * This first method is taking care of ensuring any default messengers
1314 1314
 		 * that should be made active and have templates generated are done.
@@ -1458,18 +1458,18 @@  discard block
 block discarded – undo
1458 1458
 		$has_activated = $message_resource_manager->get_has_activated_messengers_option();
1459 1459
 
1460 1460
 		$messengers_to_generate = array();
1461
-		foreach ( $installed_messengers as $installed_messenger ) {
1461
+		foreach ($installed_messengers as $installed_messenger) {
1462 1462
 			//if installed messenger is a messenger that should be activated on install
1463 1463
 			//and is not already active
1464 1464
 			//and has never been activated
1465 1465
 			if (
1466 1466
 				! $installed_messenger->activate_on_install
1467
-				|| isset( $active_messengers[ $installed_messenger->name ] )
1468
-				|| isset( $has_activated[ $installed_messenger->name ] )
1467
+				|| isset($active_messengers[$installed_messenger->name])
1468
+				|| isset($has_activated[$installed_messenger->name])
1469 1469
 			) {
1470 1470
 				continue;
1471 1471
 			}
1472
-			$messengers_to_generate[ $installed_messenger->name ] = $installed_messenger;
1472
+			$messengers_to_generate[$installed_messenger->name] = $installed_messenger;
1473 1473
 		}
1474 1474
 		return $messengers_to_generate;
1475 1475
 	}
@@ -1494,9 +1494,9 @@  discard block
 block discarded – undo
1494 1494
 	 */
1495 1495
 	public static function validate_messages_system() {
1496 1496
 		/** @type EE_Message_Resource_Manager $message_resource_manager */
1497
-		$message_resource_manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' );
1497
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1498 1498
 		$message_resource_manager->validate_active_message_types_are_installed();
1499
-		do_action( 'AHEE__EEH_Activation__validate_messages_system' );
1499
+		do_action('AHEE__EEH_Activation__validate_messages_system');
1500 1500
 	}
1501 1501
 
1502 1502
 
@@ -1509,12 +1509,12 @@  discard block
 block discarded – undo
1509 1509
 	 * 	@static
1510 1510
 	 * 	@return void
1511 1511
 	 */
1512
-	public static function create_no_ticket_prices_array(){
1512
+	public static function create_no_ticket_prices_array() {
1513 1513
 		// this creates an array for tracking events that have no active ticket prices created
1514 1514
 		// this allows us to warn admins of the situation so that it can be corrected
1515
-		$espresso_no_ticket_prices = get_option( 'ee_no_ticket_prices', FALSE );
1516
-		if ( ! $espresso_no_ticket_prices ) {
1517
-			add_option( 'ee_no_ticket_prices', array(), '', FALSE );
1515
+		$espresso_no_ticket_prices = get_option('ee_no_ticket_prices', FALSE);
1516
+		if ( ! $espresso_no_ticket_prices) {
1517
+			add_option('ee_no_ticket_prices', array(), '', FALSE);
1518 1518
 		}
1519 1519
 	}
1520 1520
 
@@ -1539,24 +1539,24 @@  discard block
 block discarded – undo
1539 1539
 	 * @global wpdb $wpdb
1540 1540
 	 * @throws \EE_Error
1541 1541
 	 */
1542
-	public static function delete_all_espresso_cpt_data(){
1542
+	public static function delete_all_espresso_cpt_data() {
1543 1543
 		global $wpdb;
1544 1544
 		//get all the CPT post_types
1545 1545
 		$ee_post_types = array();
1546
-		foreach(EE_Registry::instance()->non_abstract_db_models as $model_name){
1547
-			if ( method_exists( $model_name, 'instance' )) {
1548
-				$model_obj = call_user_func( array( $model_name, 'instance' ));
1549
-				if ( $model_obj instanceof EEM_CPT_Base ) {
1550
-					$ee_post_types[] = $wpdb->prepare("%s",$model_obj->post_type());
1546
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1547
+			if (method_exists($model_name, 'instance')) {
1548
+				$model_obj = call_user_func(array($model_name, 'instance'));
1549
+				if ($model_obj instanceof EEM_CPT_Base) {
1550
+					$ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1551 1551
 				}
1552 1552
 			}
1553 1553
 		}
1554 1554
 		//get all our CPTs
1555
-		$query = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (".implode(",",$ee_post_types).")";
1555
+		$query = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (".implode(",", $ee_post_types).")";
1556 1556
 		$cpt_ids = $wpdb->get_col($query);
1557 1557
 		//delete each post meta and term relations too
1558
-		foreach($cpt_ids as $post_id){
1559
-			wp_delete_post($post_id,true);
1558
+		foreach ($cpt_ids as $post_id) {
1559
+			wp_delete_post($post_id, true);
1560 1560
 		}
1561 1561
 	}
1562 1562
 
@@ -1568,12 +1568,12 @@  discard block
 block discarded – undo
1568 1568
 	public static function drop_espresso_tables() {
1569 1569
 		$tables = array();
1570 1570
 		// load registry
1571
-		foreach( EE_Registry::instance()->non_abstract_db_models as $model_name ){
1572
-			if ( method_exists( $model_name, 'instance' )) {
1573
-				$model_obj = call_user_func( array( $model_name, 'instance' ));
1574
-				if ( $model_obj instanceof EEM_Base ) {
1575
-					foreach ( $model_obj->get_tables() as $table ) {
1576
-						if ( strpos( $table->get_table_name(), 'esp_' )
1571
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1572
+			if (method_exists($model_name, 'instance')) {
1573
+				$model_obj = call_user_func(array($model_name, 'instance'));
1574
+				if ($model_obj instanceof EEM_Base) {
1575
+					foreach ($model_obj->get_tables() as $table) {
1576
+						if (strpos($table->get_table_name(), 'esp_')
1577 1577
 							&&
1578 1578
 							(
1579 1579
 								is_main_site()//main site? nuke them all
@@ -1596,10 +1596,10 @@  discard block
 block discarded – undo
1596 1596
 			'esp_promotion_rule',
1597 1597
 			'esp_rule'
1598 1598
 		);
1599
-		foreach( $tables_without_models as $table ){
1599
+		foreach ($tables_without_models as $table) {
1600 1600
 			$tables[] = $table;
1601 1601
 		}
1602
-		return \EEH_Activation::getTableManager()->dropTables( $tables );
1602
+		return \EEH_Activation::getTableManager()->dropTables($tables);
1603 1603
 	}
1604 1604
 
1605 1605
 
@@ -1691,7 +1691,7 @@  discard block
 block discarded – undo
1691 1691
         if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1692 1692
             $db_update_sans_ee4 = array();
1693 1693
             foreach ($espresso_db_update as $version => $times_activated) {
1694
-                if ((string)$version[0] === '3') {//if its NON EE4
1694
+                if ((string) $version[0] === '3') {//if its NON EE4
1695 1695
                     $db_update_sans_ee4[$version] = $times_activated;
1696 1696
                 }
1697 1697
             }
@@ -1716,10 +1716,10 @@  discard block
 block discarded – undo
1716 1716
 	 */
1717 1717
 	public static function last_wpdb_error_code() {
1718 1718
 		global $wpdb;
1719
-		if( $wpdb->use_mysqli ) {
1720
-			return mysqli_errno( $wpdb->dbh );
1719
+		if ($wpdb->use_mysqli) {
1720
+			return mysqli_errno($wpdb->dbh);
1721 1721
 		} else {
1722
-			return mysql_errno( $wpdb->dbh );
1722
+			return mysql_errno($wpdb->dbh);
1723 1723
 		}
1724 1724
 	}
1725 1725
 
@@ -1730,14 +1730,14 @@  discard block
 block discarded – undo
1730 1730
 	 * @param string $table_name with or without $wpdb->prefix
1731 1731
 	 * @return boolean
1732 1732
 	 */
1733
-	public static function table_exists( $table_name ){
1734
-		return \EEH_Activation::getTableAnalysis()->tableExists( $table_name );
1733
+	public static function table_exists($table_name) {
1734
+		return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1735 1735
 	}
1736 1736
 
1737 1737
 	/**
1738 1738
 	 * Resets the cache on EEH_Activation
1739 1739
 	 */
1740
-	public static function reset(){
1740
+	public static function reset() {
1741 1741
 		self::$_default_creator_id = NULL;
1742 1742
 		self::$_initialized_db_content_already_in_this_request = false;
1743 1743
 	}
Please login to merge, or discard this patch.
core/services/database/TableManager.php 2 patches
Indentation   +205 added lines, -207 removed lines patch added patch discarded remove patch
@@ -17,214 +17,212 @@
 block discarded – undo
17 17
 class TableManager extends \EE_Base
18 18
 {
19 19
 
20
-    /**
21
-     * @var TableAnalysis $table_analysis
22
-     */
23
-    private $table_analysis;
24
-
25
-
26
-
27
-    /**
28
-     * TableManager constructor.
29
-     *
30
-     * @param TableAnalysis $TableAnalysis
31
-     */
32
-    public function __construct(TableAnalysis $TableAnalysis)
33
-    {
34
-        $this->table_analysis = $TableAnalysis;
35
-    }
36
-
37
-
38
-
39
-    /**
40
-     * Gets the injected table analyzer, or throws an exception
41
-     *
42
-     * @return TableAnalysis
43
-     * @throws \EE_Error
44
-     */
45
-    protected function getTableAnalysis()
46
-    {
47
-        if ($this->table_analysis instanceof TableAnalysis) {
48
-            return $this->table_analysis;
49
-        } else {
50
-            throw new \EE_Error(
51
-                sprintf(
52
-                    __('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
53
-                    get_class($this)
54
-                )
55
-            );
56
-        }
57
-    }
58
-
59
-
60
-
61
-    /**
62
-     * @param string $table_name which can optionally start with $wpdb->prefix or not
63
-     * @param string $column_name
64
-     * @param string $column_info
65
-     * @return bool|false|int
66
-     */
67
-    public function addColumn($table_name, $column_name, $column_info = 'INT UNSIGNED NOT NULL')
68
-    {
69
-        if (apply_filters('FHEE__EEH_Activation__add_column_if_it_doesnt_exist__short_circuit', false)) {
70
-            return false;
71
-        }
72
-        global $wpdb;
73
-        $full_table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
74
-        $columns = $this->getTableColumns($table_name);
75
-        if ( ! in_array($column_name, $columns)) {
76
-            $alter_query = "ALTER TABLE {$full_table_name} ADD {$column_name} {$column_info}";
77
-            return $wpdb->query($alter_query);
78
-        }
79
-        return true;
80
-    }
81
-
82
-
83
-
84
-    /**
85
-     * Gets the name of all columns on the  table. $table_name can
86
-     * optionally start with $wpdb->prefix or not
87
-     *
88
-     * @global \wpdb $wpdb
89
-     * @param string $table_name
90
-     * @return array
91
-     */
92
-    public function getTableColumns($table_name)
93
-    {
94
-        global $wpdb;
95
-        $table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
96
-        $field_array = array();
97
-        if ( ! empty($table_name)) {
98
-            $columns = $wpdb->get_results("SHOW COLUMNS FROM {$table_name} ");
99
-            if ($columns !== false) {
100
-                foreach ($columns as $column) {
101
-                    $field_array[] = $column->Field;
102
-                }
103
-            }
104
-        }
105
-        return $field_array;
106
-    }
107
-
108
-
109
-
110
-    /**
111
-     * Drops the specified table from the database. $table_name can
112
-     * optionally start with $wpdb->prefix or not
113
-     *
114
-     * @global \wpdb $wpdb
115
-     * @param string $table_name
116
-     * @return int
117
-     */
118
-    public function dropTable($table_name)
119
-    {
120
-        global $wpdb;
121
-        if ($this->getTableAnalysis()->tableExists($table_name)) {
122
-            $table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
123
-            return $wpdb->query("DROP TABLE IF EXISTS {$table_name}");
124
-        }
125
-        return 0;
126
-    }
127
-
128
-
129
-
130
-    /**
131
-     * Drops all the tables mentioned in a single MYSQL query. Double-checks
132
-     * each table name provided has a wpdb prefix attached, and that it exists.
133
-     * Returns the list actually deleted
134
-     *
135
-     * @global WPDB $wpdb
136
-     * @param array $table_names
137
-     * @return array of table names which we deleted
138
-     */
139
-    public function dropTables($table_names)
140
-    {
141
-        $tables_to_delete = array();
142
-        foreach ($table_names as $table_name) {
143
-            $table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
144
-            if ($this->getTableAnalysis()->tableExists($table_name)) {
145
-                $tables_to_delete[] = $table_name;
146
-            }
147
-        }
148
-        global $wpdb;
149
-        $wpdb->query('DROP TABLE ' . implode(', ', $tables_to_delete));
150
-        return $tables_to_delete;
151
-    }
152
-
153
-
154
-
155
-    /**
156
-     * Drops the specified index from the specified table. $table_name can
157
-     * optionally start with $wpdb->prefix or not
158
-
159
-     *
20
+	/**
21
+	 * @var TableAnalysis $table_analysis
22
+	 */
23
+	private $table_analysis;
24
+
25
+
26
+
27
+	/**
28
+	 * TableManager constructor.
29
+	 *
30
+	 * @param TableAnalysis $TableAnalysis
31
+	 */
32
+	public function __construct(TableAnalysis $TableAnalysis)
33
+	{
34
+		$this->table_analysis = $TableAnalysis;
35
+	}
36
+
37
+
38
+
39
+	/**
40
+	 * Gets the injected table analyzer, or throws an exception
41
+	 *
42
+	 * @return TableAnalysis
43
+	 * @throws \EE_Error
44
+	 */
45
+	protected function getTableAnalysis()
46
+	{
47
+		if ($this->table_analysis instanceof TableAnalysis) {
48
+			return $this->table_analysis;
49
+		} else {
50
+			throw new \EE_Error(
51
+				sprintf(
52
+					__('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
53
+					get_class($this)
54
+				)
55
+			);
56
+		}
57
+	}
58
+
59
+
60
+
61
+	/**
62
+	 * @param string $table_name which can optionally start with $wpdb->prefix or not
63
+	 * @param string $column_name
64
+	 * @param string $column_info
65
+	 * @return bool|false|int
66
+	 */
67
+	public function addColumn($table_name, $column_name, $column_info = 'INT UNSIGNED NOT NULL')
68
+	{
69
+		if (apply_filters('FHEE__EEH_Activation__add_column_if_it_doesnt_exist__short_circuit', false)) {
70
+			return false;
71
+		}
72
+		global $wpdb;
73
+		$full_table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
74
+		$columns = $this->getTableColumns($table_name);
75
+		if ( ! in_array($column_name, $columns)) {
76
+			$alter_query = "ALTER TABLE {$full_table_name} ADD {$column_name} {$column_info}";
77
+			return $wpdb->query($alter_query);
78
+		}
79
+		return true;
80
+	}
81
+
82
+
83
+
84
+	/**
85
+	 * Gets the name of all columns on the  table. $table_name can
86
+	 * optionally start with $wpdb->prefix or not
87
+	 *
88
+	 * @global \wpdb $wpdb
89
+	 * @param string $table_name
90
+	 * @return array
91
+	 */
92
+	public function getTableColumns($table_name)
93
+	{
94
+		global $wpdb;
95
+		$table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
96
+		$field_array = array();
97
+		if ( ! empty($table_name)) {
98
+			$columns = $wpdb->get_results("SHOW COLUMNS FROM {$table_name} ");
99
+			if ($columns !== false) {
100
+				foreach ($columns as $column) {
101
+					$field_array[] = $column->Field;
102
+				}
103
+			}
104
+		}
105
+		return $field_array;
106
+	}
107
+
108
+
109
+
110
+	/**
111
+	 * Drops the specified table from the database. $table_name can
112
+	 * optionally start with $wpdb->prefix or not
113
+	 *
114
+	 * @global \wpdb $wpdb
115
+	 * @param string $table_name
116
+	 * @return int
117
+	 */
118
+	public function dropTable($table_name)
119
+	{
120
+		global $wpdb;
121
+		if ($this->getTableAnalysis()->tableExists($table_name)) {
122
+			$table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
123
+			return $wpdb->query("DROP TABLE IF EXISTS {$table_name}");
124
+		}
125
+		return 0;
126
+	}
127
+
128
+
129
+
130
+	/**
131
+	 * Drops all the tables mentioned in a single MYSQL query. Double-checks
132
+	 * each table name provided has a wpdb prefix attached, and that it exists.
133
+	 * Returns the list actually deleted
134
+	 *
135
+	 * @global WPDB $wpdb
136
+	 * @param array $table_names
137
+	 * @return array of table names which we deleted
138
+	 */
139
+	public function dropTables($table_names)
140
+	{
141
+		$tables_to_delete = array();
142
+		foreach ($table_names as $table_name) {
143
+			$table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
144
+			if ($this->getTableAnalysis()->tableExists($table_name)) {
145
+				$tables_to_delete[] = $table_name;
146
+			}
147
+		}
148
+		global $wpdb;
149
+		$wpdb->query('DROP TABLE ' . implode(', ', $tables_to_delete));
150
+		return $tables_to_delete;
151
+	}
152
+
153
+
154
+
155
+	/**
156
+	 * Drops the specified index from the specified table. $table_name can
157
+	 * optionally start with $wpdb->prefix or not
158
+	 *
160 159
 *@global \wpdb       $wpdb
161
-     * @param string $table_name
162
-     * @param string $index_name
163
-     * @return int
164
-     */
165
-    public function dropIndex($table_name, $index_name)
166
-    {
167
-        if (apply_filters('FHEE__EEH_Activation__drop_index__short_circuit', false)) {
168
-            return false;
169
-        }
170
-        global $wpdb;
171
-        $table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
172
-        $index_exists_query = "SHOW INDEX FROM {$table_name} WHERE Key_name = '{$index_name}'";
173
-        if (
174
-            $this->getTableAnalysis()->tableExists($table_name)
175
-            && $wpdb->get_var($index_exists_query)
176
-               === $table_name //using get_var with the $index_exists_query returns the table's name
177
-        ) {
178
-            return $wpdb->query("ALTER TABLE {$table_name} DROP INDEX {$index_name}");
179
-        }
180
-        return 0;
181
-    }
182
-
183
-
184
-
185
-    /**
186
-     * Just creates the requested table. $table_name can
187
-     * optionally start with $wpdb->prefix or not
188
-
189
-     *
160
+	 * @param string $table_name
161
+	 * @param string $index_name
162
+	 * @return int
163
+	 */
164
+	public function dropIndex($table_name, $index_name)
165
+	{
166
+		if (apply_filters('FHEE__EEH_Activation__drop_index__short_circuit', false)) {
167
+			return false;
168
+		}
169
+		global $wpdb;
170
+		$table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
171
+		$index_exists_query = "SHOW INDEX FROM {$table_name} WHERE Key_name = '{$index_name}'";
172
+		if (
173
+			$this->getTableAnalysis()->tableExists($table_name)
174
+			&& $wpdb->get_var($index_exists_query)
175
+			   === $table_name //using get_var with the $index_exists_query returns the table's name
176
+		) {
177
+			return $wpdb->query("ALTER TABLE {$table_name} DROP INDEX {$index_name}");
178
+		}
179
+		return 0;
180
+	}
181
+
182
+
183
+
184
+	/**
185
+	 * Just creates the requested table. $table_name can
186
+	 * optionally start with $wpdb->prefix or not
187
+	 *
190 188
 *@param string       $table_name
191
-     * @param string $create_sql defining the table's columns and indexes
192
-     * @param string $engine     (no need to specify "ENGINE=", that's implied)
193
-     * @return void
194
-     * @throws \EE_Error
195
-     */
196
-    public function createTable($table_name, $create_sql, $engine = 'MyISAM')
197
-    {
198
-        // does $sql contain valid column information? ( LPT: https://regex101.com/ is great for working out regex patterns )
199
-        if (preg_match('((((.*?))(,\s))+)', $create_sql, $valid_column_data)) {
200
-            $table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
201
-            /** @var \wpdb $wpdb */
202
-            global $wpdb;
203
-            $SQL = "CREATE TABLE {$table_name} ( {$create_sql} ) ENGINE={$engine} " . $wpdb->get_charset_collate();
204
-
205
-            //get $wpdb to echo errors, but buffer them. This way at least WE know an error
206
-            //happened. And then we can choose to tell the end user
207
-            $old_show_errors_policy = $wpdb->show_errors(true);
208
-            $old_error_suppression_policy = $wpdb->suppress_errors(false);
209
-            ob_start();
210
-            dbDelta($SQL);
211
-            $output = ob_get_contents();
212
-            ob_end_clean();
213
-            $wpdb->show_errors($old_show_errors_policy);
214
-            $wpdb->suppress_errors($old_error_suppression_policy);
215
-            if ( ! empty($output)) {
216
-                throw new \EE_Error($output);
217
-            }
218
-        } else {
219
-            throw new \EE_Error(
220
-                sprintf(
221
-                    __('The following table creation SQL does not contain valid information about the table columns: %1$s %2$s',
222
-                        'event_espresso'),
223
-                    '<br />',
224
-                    $create_sql
225
-                )
226
-            );
227
-        }
228
-    }
189
+	 * @param string $create_sql defining the table's columns and indexes
190
+	 * @param string $engine     (no need to specify "ENGINE=", that's implied)
191
+	 * @return void
192
+	 * @throws \EE_Error
193
+	 */
194
+	public function createTable($table_name, $create_sql, $engine = 'MyISAM')
195
+	{
196
+		// does $sql contain valid column information? ( LPT: https://regex101.com/ is great for working out regex patterns )
197
+		if (preg_match('((((.*?))(,\s))+)', $create_sql, $valid_column_data)) {
198
+			$table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
199
+			/** @var \wpdb $wpdb */
200
+			global $wpdb;
201
+			$SQL = "CREATE TABLE {$table_name} ( {$create_sql} ) ENGINE={$engine} " . $wpdb->get_charset_collate();
202
+
203
+			//get $wpdb to echo errors, but buffer them. This way at least WE know an error
204
+			//happened. And then we can choose to tell the end user
205
+			$old_show_errors_policy = $wpdb->show_errors(true);
206
+			$old_error_suppression_policy = $wpdb->suppress_errors(false);
207
+			ob_start();
208
+			dbDelta($SQL);
209
+			$output = ob_get_contents();
210
+			ob_end_clean();
211
+			$wpdb->show_errors($old_show_errors_policy);
212
+			$wpdb->suppress_errors($old_error_suppression_policy);
213
+			if ( ! empty($output)) {
214
+				throw new \EE_Error($output);
215
+			}
216
+		} else {
217
+			throw new \EE_Error(
218
+				sprintf(
219
+					__('The following table creation SQL does not contain valid information about the table columns: %1$s %2$s',
220
+						'event_espresso'),
221
+					'<br />',
222
+					$create_sql
223
+				)
224
+			);
225
+		}
226
+	}
229 227
 
230 228
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
             }
147 147
         }
148 148
         global $wpdb;
149
-        $wpdb->query('DROP TABLE ' . implode(', ', $tables_to_delete));
149
+        $wpdb->query('DROP TABLE '.implode(', ', $tables_to_delete));
150 150
         return $tables_to_delete;
151 151
     }
152 152
 
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
             $table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
201 201
             /** @var \wpdb $wpdb */
202 202
             global $wpdb;
203
-            $SQL = "CREATE TABLE {$table_name} ( {$create_sql} ) ENGINE={$engine} " . $wpdb->get_charset_collate();
203
+            $SQL = "CREATE TABLE {$table_name} ( {$create_sql} ) ENGINE={$engine} ".$wpdb->get_charset_collate();
204 204
 
205 205
             //get $wpdb to echo errors, but buffer them. This way at least WE know an error
206 206
             //happened. And then we can choose to tell the end user
Please login to merge, or discard this patch.