Completed
Branch BUG-10355-improve-paypal-tls-f... (079e77)
by
unknown
23:37 queued 12:45
created
core/EE_Payment_Processor.core.php 2 patches
Indentation   +749 added lines, -749 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,752 +16,752 @@  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
-     * @link https://core.trac.wordpress.org/ticket/36320
740
-     * @link https://core.trac.wordpress.org/ticket/34924#comment:15
741
-     * @link https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US
742
-     * @link https://github.com/woocommerce/woocommerce-gateway-stripe/pull/67/commits/877dcabf5c60ef6e41f770ecf654274fa1fc0ce5
743
-     * This will affect paypal standard, pro, express, and payflow.
744
-     */
745
-    public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
746
-    {
747
-        if (! $handle ) {
748
-            return;
749
-        }
750
-        if (strstr($url, 'https://') && strstr($url, '.paypal.com')) {
751
-            if (OPENSSL_VERSION_NUMBER >= 0x1000100f) {
752
-                if (! defined('CURL_SSLVERSION_TLSv1_2')) {
753
-                    // Note the value 6 comes from its position in the enum that
754
-                    // defines it in cURL's source code.
755
-                    define('CURL_SSLVERSION_TLSv1_2', 6); // constant not defined in PHP < 5.5
756
-                }
757
-
758
-                curl_setopt($handle, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
759
-            } else {
760
-                if (! defined('CURL_SSLVERSION_TLSv1')) {
761
-                    define('CURL_SSLVERSION_TLSv1', 1); // constant not defined in PHP < 5.5
762
-                }
763
-                curl_setopt($handle, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
764
-            }
765
-        }
766
-    }
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
+	 * @link https://core.trac.wordpress.org/ticket/36320
740
+	 * @link https://core.trac.wordpress.org/ticket/34924#comment:15
741
+	 * @link https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US
742
+	 * @link https://github.com/woocommerce/woocommerce-gateway-stripe/pull/67/commits/877dcabf5c60ef6e41f770ecf654274fa1fc0ce5
743
+	 * This will affect paypal standard, pro, express, and payflow.
744
+	 */
745
+	public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
746
+	{
747
+		if (! $handle ) {
748
+			return;
749
+		}
750
+		if (strstr($url, 'https://') && strstr($url, '.paypal.com')) {
751
+			if (OPENSSL_VERSION_NUMBER >= 0x1000100f) {
752
+				if (! defined('CURL_SSLVERSION_TLSv1_2')) {
753
+					// Note the value 6 comes from its position in the enum that
754
+					// defines it in cURL's source code.
755
+					define('CURL_SSLVERSION_TLSv1_2', 6); // constant not defined in PHP < 5.5
756
+				}
757
+
758
+				curl_setopt($handle, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
759
+			} else {
760
+				if (! defined('CURL_SSLVERSION_TLSv1')) {
761
+					define('CURL_SSLVERSION_TLSv1', 1); // constant not defined in PHP < 5.5
762
+				}
763
+				curl_setopt($handle, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
764
+			}
765
+		}
766
+	}
767 767
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
         $update_txn = true,
88 88
         $cancel_url = ''
89 89
     ) {
90
-        if ((float)$amount < 0) {
90
+        if ((float) $amount < 0) {
91 91
             throw new EE_Error(
92 92
                 sprintf(
93 93
                     __(
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
         if ($payment_method->type_obj() instanceof EE_PMT_Base) {
109 109
             $payment = $payment_method->type_obj()->process_payment(
110 110
                 $transaction,
111
-                min($amount, $transaction->remaining()),//make sure we don't overcharge
111
+                min($amount, $transaction->remaining()), //make sure we don't overcharge
112 112
                 $billing_form,
113 113
                 $return_url,
114 114
                 add_query_arg(array('ee_cancel_payment' => true), $cancel_url),
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
         $separate_IPN_request = true
196 196
     ) {
197 197
         EE_Registry::instance()->load_model('Change_Log');
198
-        $_req_data = $this->_remove_unusable_characters_from_array((array)$_req_data);
198
+        $_req_data = $this->_remove_unusable_characters_from_array((array) $_req_data);
199 199
         EE_Processor_Base::set_IPN($separate_IPN_request);
200 200
         $obj_for_log = null;
201 201
         if ($transaction instanceof EE_Transaction) {
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
                         EEM_Change_Log::instance()->log(
235 235
                             EEM_Change_Log::type_gateway,
236 236
                             array(
237
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
237
+                                'message'     => 'IPN Exception: '.$e->getMessage(),
238 238
                                 'current_url' => EEH_URL::current_url(),
239 239
                                 'payment'     => $e->getPaymentProperties(),
240 240
                                 'IPN_data'    => $e->getIpnData(),
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
                         EEM_Change_Log::instance()->log(
272 272
                             EEM_Change_Log::type_gateway,
273 273
                             array(
274
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
274
+                                'message'     => 'IPN Exception: '.$e->getMessage(),
275 275
                                 'current_url' => EEH_URL::current_url(),
276 276
                                 'payment'     => $e->getPaymentProperties(),
277 277
                                 'IPN_data'    => $e->getIpnData(),
@@ -642,15 +642,15 @@  discard block
 block discarded – undo
642 642
         //EEH_Debug_Tools::printr( $payment->amount(), '$payment->amount()', __FILE__, __LINE__ );
643 643
         if ($registration->paid() > 0) {
644 644
             // ensure $available_refund_amount is NOT negative
645
-            $available_refund_amount = (float)abs($available_refund_amount);
645
+            $available_refund_amount = (float) abs($available_refund_amount);
646 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());
647
+            $refund_amount = min($available_refund_amount, (float) $registration->paid());
648 648
             // update $available_payment_amount
649 649
             $available_refund_amount -= $refund_amount;
650 650
             //calculate and set new REG_paid
651 651
             $registration->set_paid($registration->paid() - $refund_amount);
652 652
             // convert payment amount back to a negative value for storage in the db
653
-            $refund_amount = (float)abs($refund_amount) * -1;
653
+            $refund_amount = (float) abs($refund_amount) * -1;
654 654
             // now save it
655 655
             $this->_apply_registration_payment($registration, $payment, $refund_amount);
656 656
         }
@@ -744,12 +744,12 @@  discard block
 block discarded – undo
744 744
      */
745 745
     public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
746 746
     {
747
-        if (! $handle ) {
747
+        if ( ! $handle) {
748 748
             return;
749 749
         }
750 750
         if (strstr($url, 'https://') && strstr($url, '.paypal.com')) {
751 751
             if (OPENSSL_VERSION_NUMBER >= 0x1000100f) {
752
-                if (! defined('CURL_SSLVERSION_TLSv1_2')) {
752
+                if ( ! defined('CURL_SSLVERSION_TLSv1_2')) {
753 753
                     // Note the value 6 comes from its position in the enum that
754 754
                     // defines it in cURL's source code.
755 755
                     define('CURL_SSLVERSION_TLSv1_2', 6); // constant not defined in PHP < 5.5
@@ -757,7 +757,7 @@  discard block
 block discarded – undo
757 757
 
758 758
                 curl_setopt($handle, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
759 759
             } else {
760
-                if (! defined('CURL_SSLVERSION_TLSv1')) {
760
+                if ( ! defined('CURL_SSLVERSION_TLSv1')) {
761 761
                     define('CURL_SSLVERSION_TLSv1', 1); // constant not defined in PHP < 5.5
762 762
                 }
763 763
                 curl_setopt($handle, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
Please login to merge, or discard this patch.