Merge pull request #20196 from eileenmcnaughton/import
[civicrm-core.git] / CRM / Core / Payment / PayPalProIPN.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 use Civi\Api4\Contribution;
13
14 /**
15 *
16 * @package CRM
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 */
19 class CRM_Core_Payment_PayPalProIPN extends CRM_Core_Payment_BaseIPN {
20
21 /**
22 * Input parameters from payment processor. Store these so that
23 * the code does not need to keep retrieving from the http request
24 * @var array
25 */
26 protected $_inputParameters = [];
27
28 /**
29 * Store for the variables from the invoice string.
30 * @var array
31 */
32 protected $_invoiceData = [];
33
34 /**
35 * Is this a payment express transaction.
36 * @var bool
37 */
38 protected $_isPaymentExpress = FALSE;
39
40 /**
41 * Recurring contribution ID.
42 *
43 * @var int|null
44 */
45 protected $contributionRecurID;
46
47 /**
48 * Recurring contribution object.
49 *
50 * @var \CRM_Contribute_BAO_ContributionRecur
51 */
52 protected $contributionRecurObject;
53
54 /**
55 * Contribution object.
56 *
57 * @var \CRM_Contribute_BAO_Contribution
58 */
59 protected $contributionObject;
60 /**
61 * Contribution ID.
62 *
63 * @var int
64 */
65 protected $contributionID;
66
67 /**
68 * Get the recurring contribution ID, if any.
69 *
70 * @return int|null
71 *
72 * @throws \CRM_Core_Exception
73 */
74 public function getContributionRecurID(): ?int {
75 if (!$this->contributionRecurID && $this->getValue('r', FALSE)) {
76 $this->contributionRecurID = (int) $this->getValue('r', FALSE);
77 }
78 return $this->contributionRecurID;
79 }
80
81 /**
82 * Get the relevant contribution ID.
83 *
84 * This is the contribution being paid or the original in the
85 * recurring series.
86 *
87 * @return int
88 *
89 * @throws \CRM_Core_Exception
90 */
91 protected function getContributionID(): int {
92 if (!$this->contributionID && $this->getValue('b', TRUE)) {
93 $this->contributionID = (int) $this->getValue('b', TRUE);
94 }
95 return $this->contributionID;
96 }
97
98 /**
99 * @param int|null $contributionRecurID
100 */
101 public function setContributionRecurID(?int $contributionRecurID): void {
102 $this->contributionRecurID = $contributionRecurID;
103 }
104
105 /**
106 * Set contribution ID.
107 *
108 * @param int $contributionID
109 */
110 public function setContributionID(int $contributionID): void {
111 $this->contributionID = $contributionID;
112 }
113
114 /**
115 * Component.
116 *
117 * Are we dealing with an event an 'anything else' (contribute).
118 *
119 * @var string
120 */
121 protected $_component = 'contribute';
122
123 /**
124 * Constructor function.
125 *
126 * @param array $inputData
127 * Contents of HTTP REQUEST.
128 *
129 * @throws CRM_Core_Exception
130 */
131 public function __construct($inputData) {
132 $this->setInputParameters($inputData);
133 $this->setInvoiceData();
134 parent::__construct();
135 }
136
137 /**
138 * get the values from the rp_invoice_id string.
139 *
140 * @param string $name
141 * E.g. i, values are stored in the string with letter codes.
142 * @param bool $abort
143 * Throw exception if not found
144 *
145 * @throws CRM_Core_Exception
146 * @return mixed
147 */
148 public function getValue($name, $abort = TRUE) {
149 if ($abort && empty($this->_invoiceData[$name])) {
150 throw new CRM_Core_Exception("Failure: Missing Parameter $name");
151 }
152 else {
153 return $this->_invoiceData[$name] ?? NULL;
154 }
155 }
156
157 /**
158 * Set $this->_invoiceData from the input array
159 */
160 public function setInvoiceData() {
161 if (empty($this->_inputParameters['rp_invoice_id'])) {
162 $this->_isPaymentExpress = TRUE;
163 return;
164 }
165 $rpInvoiceArray = explode('&', $this->_inputParameters['rp_invoice_id']);
166 // for clarify let's also store without the single letter unreadable
167 //@todo after more refactoring we might ditch storing the one letter stuff
168 $mapping = [
169 'i' => 'invoice_id',
170 'm' => 'component',
171 'c' => 'contact_id',
172 'b' => 'contribution_id',
173 'r' => 'contribution_recur_id',
174 'p' => 'participant_id',
175 'e' => 'event_id',
176 ];
177 foreach ($rpInvoiceArray as $rpInvoiceValue) {
178 $rpValueArray = explode('=', $rpInvoiceValue);
179 $this->_invoiceData[$rpValueArray[0]] = $rpValueArray[1];
180 $this->_inputParameters[$mapping[$rpValueArray[0]]] = $rpValueArray[1];
181 // p has been overloaded & could mean contribution page or participant id. Clearly we need an
182 // alphabet with more letters.
183 // the mode will always be resolved before the mystery p is reached
184 if ($rpValueArray[1] === 'contribute') {
185 $mapping['p'] = 'contribution_page_id';
186 }
187 }
188 if (empty($this->_inputParameters['component'])) {
189 $this->_isPaymentExpress = TRUE;
190 }
191 }
192
193 /**
194 * @param string $name
195 * Of variable to return.
196 * @param string $type
197 * Data type.
198 * - String
199 * - Integer
200 * @param string $location
201 * Deprecated.
202 * @param bool $abort
203 * Abort if empty.
204 *
205 * @throws CRM_Core_Exception
206 * @return mixed
207 */
208 public function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
209 $value = CRM_Utils_Type::validate(
210 CRM_Utils_Array::value($name, $this->_inputParameters),
211 $type,
212 FALSE
213 );
214 if ($abort && $value === NULL) {
215 throw new CRM_Core_Exception("Could not find an entry for $name in $location");
216 }
217 return $value;
218 }
219
220 /**
221 * Process recurring contributions.
222 *
223 * @param array $input
224 * @param \CRM_Contribute_BAO_ContributionRecur $recur
225 * @param \CRM_Contribute_BAO_Contribution $contribution
226 * @param bool $first
227 *
228 * @throws \API_Exception
229 * @throws \CRM_Core_Exception
230 * @throws \CiviCRM_API3_Exception
231 * @throws \Civi\API\Exception\UnauthorizedException
232 */
233 public function recur($input, $recur, $contribution, $first) {
234 if (!isset($input['txnType'])) {
235 Civi::log()->debug('PayPalProIPN: Could not find txn_type in input request.');
236 echo 'Failure: Invalid parameters<p>';
237 return;
238 }
239
240 // make sure the invoice ids match
241 // make sure the invoice is valid and matches what we have in
242 // the contribution record
243 if ($recur->invoice_id != $input['invoice']) {
244 Civi::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id . ' input is ' . $input['invoice']);
245 echo 'Failure: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id . " input is " . $input['invoice'];
246 return;
247 }
248
249 $now = date('YmdHis');
250
251 $sendNotification = FALSE;
252 $subscriptionPaymentStatus = NULL;
253 //List of Transaction Type
254 /*
255 recurring_payment_profile_created RP Profile Created
256 recurring_payment RP Successful Payment
257 recurring_payment_failed RP Failed Payment
258 recurring_payment_profile_cancel RP Profile Cancelled
259 recurring_payment_expired RP Profile Expired
260 recurring_payment_skipped RP Profile Skipped
261 recurring_payment_outstanding_payment RP Successful Outstanding Payment
262 recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
263 recurring_payment_suspended RP Profile Suspended
264 recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
265 */
266
267 //set transaction type
268 $txnType = $this->retrieve('txn_type', 'String');
269 //Changes for paypal pro recurring payment
270 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate'));
271 switch ($txnType) {
272 case 'recurring_payment_profile_created':
273 if (in_array($recur->contribution_status_id, [
274 $contributionStatuses['Pending'],
275 $contributionStatuses['In Progress'],
276 ])
277 && !empty($recur->processor_id)
278 ) {
279 echo "already handled";
280 return;
281 }
282 $recur->create_date = $now;
283 $recur->contribution_status_id = $contributionStatuses['Pending'];
284 $recur->processor_id = $this->retrieve('recurring_payment_id', 'String');
285 $recur->trxn_id = $recur->processor_id;
286 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
287 $sendNotification = TRUE;
288 break;
289
290 case 'recurring_payment':
291 if ($first) {
292 $recur->start_date = $now;
293 }
294 else {
295 if ($input['paymentStatus'] !== 'Completed') {
296 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
297 }
298
299 // In future moving to create pending & then complete, but this OK for now.
300 // Also consider accepting 'Failed' like other processors.
301 $input['contribution_status_id'] = $contributionStatuses['Completed'];
302 $input['invoice_id'] = md5(uniqid(rand(), TRUE));
303 $input['original_contribution_id'] = $this->getContributionID();
304 $input['contribution_recur_id'] = $this->getContributionRecurID();
305
306 civicrm_api3('Contribution', 'repeattransaction', $input);
307 return;
308 }
309
310 //contribution installment is completed
311 if ($this->retrieve('profile_status', 'String') == 'Expired') {
312 if (!empty($recur->end_date)) {
313 echo "already handled";
314 return;
315 }
316 $recur->contribution_status_id = $contributionStatuses['Completed'];
317 $recur->end_date = $now;
318 $sendNotification = TRUE;
319 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
320 }
321
322 // make sure the contribution status is not done
323 // since order of ipn's is unknown
324 if ($recur->contribution_status_id != $contributionStatuses['Completed']) {
325 $recur->contribution_status_id = $contributionStatuses['In Progress'];
326 }
327 break;
328 }
329
330 $recur->save();
331
332 if ($sendNotification) {
333 //send recurring Notification email for user
334 CRM_Contribute_BAO_ContributionPage::recurringNotify(
335 $this->getContributionID(),
336 $subscriptionPaymentStatus,
337 $recur
338 );
339 }
340
341 if ($txnType !== 'recurring_payment') {
342 return;
343 }
344
345 // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
346 $contribution->receive_date = !empty($input['payment_date']) ? date('YmdHis', strtotime($input['payment_date'])) : $now;
347
348 $this->single($input, $contribution, TRUE, $first);
349 }
350
351 /**
352 * @param array $input
353 * @param \CRM_Contribute_BAO_Contribution $contribution
354 * @param bool $recur
355 * @param bool $first
356 *
357 * @return void
358 * @throws \API_Exception
359 * @throws \CRM_Core_Exception
360 * @throws \CiviCRM_API3_Exception
361 * @throws \Civi\API\Exception\UnauthorizedException
362 */
363 public function single($input, $contribution, $recur = FALSE, $first = FALSE) {
364
365 // make sure the invoice is valid and matches what we have in the contribution record
366 if ((!$recur) || ($recur && $first)) {
367 if ($contribution->invoice_id != $input['invoice']) {
368 Civi::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request.');
369 echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id . " and input is " . $input['invoice'];
370 return;
371 }
372 }
373 else {
374 $contribution->invoice_id = md5(uniqid(rand(), TRUE));
375 }
376
377 if (!$recur) {
378 if ($contribution->total_amount != $input['amount']) {
379 Civi::log()->debug('PayPalProIPN: Amount values dont match between database and IPN request.');
380 echo "Failure: Amount values dont match between database and IPN request<p>";
381 return;
382 }
383 }
384 else {
385 $contribution->total_amount = $input['amount'];
386 }
387
388 $status = $input['paymentStatus'];
389 if ($status === 'Denied' || $status === 'Failed' || $status === 'Voided') {
390 Contribution::update(FALSE)->setValues([
391 'cancel_date' => 'now',
392 'contribution_status_id:name' => 'Failed',
393 ])->addWhere('id', '=', $contribution->id)->execute();
394 Civi::log()->debug("Setting contribution status to Failed");
395 return;
396 }
397 if ($status === 'Pending') {
398 Civi::log()->debug('Returning since contribution status is Pending');
399 return;
400 }
401 if ($status === 'Refunded' || $status === 'Reversed') {
402 Contribution::update(FALSE)->setValues([
403 'cancel_date' => 'now',
404 'contribution_status_id:name' => 'Cancelled',
405 ])->addWhere('id', '=', $contribution->id)->execute();
406 Civi::log()->debug("Setting contribution status to Cancelled");
407 return;
408 }
409 elseif ($status !== 'Completed') {
410 Civi::log()->debug('Returning since contribution status is not handled');
411 return;
412 }
413
414 // check if contribution is already completed, if so we ignore this ipn
415 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
416 if ($contribution->contribution_status_id == $completedStatusId) {
417 Civi::log()->debug('PayPalProIPN: Returning since contribution has already been handled.');
418 echo 'Success: Contribution has already been handled<p>';
419 return;
420 }
421
422 CRM_Contribute_BAO_Contribution::completeOrder($input, $this->getContributionRecurID(), $contribution->id ?? NULL);
423 }
424
425 /**
426 * Gets PaymentProcessorID for PayPal
427 *
428 * @return int
429 */
430 public function getPayPalPaymentProcessorID() {
431 // This is an unreliable method as there could be more than one instance.
432 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
433 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
434 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
435 // & call completetransaction or call fail? (which may not exist yet).
436
437 Civi::log()->warning('Unreliable method used to get payment_processor_id for PayPal Pro IPN - this will cause problems if you have more than one instance');
438
439 $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
440 'PayPal', 'id', 'name'
441 );
442 return (int) civicrm_api3('PaymentProcessor', 'getvalue', [
443 'is_test' => 0,
444 'options' => ['limit' => 1],
445 'payment_processor_type_id' => $paymentProcessorTypeID,
446 'return' => 'id',
447 ]);
448
449 }
450
451 /**
452 * This is the main function to call. It should be sufficient to instantiate the class
453 * (with the input parameters) & call this & all will be done
454 *
455 * @todo the references to POST throughout this class need to be removed
456 * @return void
457 */
458 public function main() {
459 CRM_Core_Error::debug_var('GET', $_GET, TRUE, TRUE);
460 CRM_Core_Error::debug_var('POST', $_POST, TRUE, TRUE);
461 $ids = $input = [];
462 try {
463 if ($this->_isPaymentExpress) {
464 $this->handlePaymentExpress();
465 return;
466 }
467 $this->_component = $input['component'] = self::getValue('m');
468 $input['invoice'] = self::getValue('i', TRUE);
469 // get the contribution and contact ids from the GET params
470 $ids['contact'] = $this->getContactID();
471 $ids['contribution'] = $this->getContributionID();
472
473 $this->getInput($input);
474
475 if ($this->_component == 'event') {
476 $ids['event'] = self::getValue('e', TRUE);
477 $ids['participant'] = self::getValue('p', TRUE);
478 $ids['contributionRecur'] = $this->getContributionRecurID();
479 }
480 else {
481 // get the optional ids
482 //@ how can this not be broken retrieving from GET as we are dealing with a POST request?
483 // copy & paste? Note the retrieve function now uses data from _REQUEST so this will be included
484 $ids['membership'] = self::retrieve('membershipID', 'Integer', 'GET', FALSE);
485 $ids['contributionRecur'] = $this->getContributionRecurID();
486 $ids['contributionPage'] = self::getValue('p', FALSE);
487 $ids['related_contact'] = self::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
488 $ids['onbehalf_dupe_alert'] = self::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
489 }
490
491 if (!$ids['membership'] && $this->getContributionRecurID()) {
492 $sql = "
493 SELECT m.id
494 FROM civicrm_membership m
495 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
496 WHERE m.contribution_recur_id = %2
497 LIMIT 1";
498 $sqlParams = [
499 1 => [$ids['contribution'], 'Integer'],
500 2 => [$this->getContributionRecurID(), 'Integer'],
501 ];
502 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql, $sqlParams)) {
503 $ids['membership'] = $membershipId;
504 }
505 }
506
507 $paymentProcessorID = CRM_Utils_Array::value('processor_id', $this->_inputParameters);
508 if (!$paymentProcessorID) {
509 $paymentProcessorID = self::getPayPalPaymentProcessorID();
510 }
511 $contribution = $this->getContributionObject();
512
513 // make sure contact exists and is valid
514 // use the contact id from the contribution record as the id in the IPN may not be valid anymore.
515 $contact = new CRM_Contact_BAO_Contact();
516 $contact->id = $contribution->contact_id;
517 $contact->find(TRUE);
518 if ($contact->id != $ids['contact']) {
519 // If the ids do not match then it is possible the contact id in the IPN has been merged into another contact which is why we use the contact_id from the contribution
520 CRM_Core_Error::debug_log_message("Contact ID in IPN {$ids['contact']} not found but contact_id found in contribution {$contribution->contact_id} used instead");
521 echo "WARNING: Could not find contact record: {$ids['contact']}<p>";
522 $ids['contact'] = $contribution->contact_id;
523 }
524
525 // CRM-19478: handle oddity when p=null is set in place of contribution page ID,
526 if (!empty($ids['contributionPage']) && !is_numeric($ids['contributionPage'])) {
527 // We don't need to worry if about removing contribution page id as it will be set later in
528 // CRM_Contribute_BAO_Contribution::loadRelatedObjects(..) using $objects['contribution']->contribution_page_id
529 unset($ids['contributionPage']);
530 }
531
532 $ids['paymentProcessor'] = $paymentProcessorID;
533 $contribution->loadRelatedObjects($input, $ids);
534
535 $input['payment_processor_id'] = $paymentProcessorID;
536
537 if ($this->getContributionRecurID()) {
538 $contributionRecur = $this->getContributionRecurObject();
539 // check if first contribution is completed, else complete first contribution
540 $first = TRUE;
541 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
542 if ($contribution->contribution_status_id == $completedStatusId) {
543 $first = FALSE;
544 }
545 $this->recur($input, $contributionRecur, $contribution, $first);
546 return;
547 }
548
549 $this->single($input, $contribution, FALSE, FALSE);
550 }
551 catch (CRM_Core_Exception $e) {
552 Civi::log()->debug($e->getMessage() . ' input {input}', ['input' => $input]);
553 echo 'Invalid or missing data';
554 }
555 }
556
557 /**
558 * @param array $input
559 *
560 * @return void
561 * @throws CRM_Core_Exception
562 */
563 public function getInput(&$input) {
564 $billingID = CRM_Core_BAO_LocationType::getBilling();
565
566 $input['txnType'] = self::retrieve('txn_type', 'String', 'POST', FALSE);
567 $input['paymentStatus'] = self::retrieve('payment_status', 'String', 'POST', FALSE);
568
569 $input['amount'] = self::retrieve('mc_gross', 'Money', 'POST', FALSE);
570 $input['reasonCode'] = self::retrieve('ReasonCode', 'String', 'POST', FALSE);
571
572 $lookup = [
573 "first_name" => 'first_name',
574 "last_name" => 'last_name',
575 "street_address-{$billingID}" => 'address_street',
576 "city-{$billingID}" => 'address_city',
577 "state-{$billingID}" => 'address_state',
578 "postal_code-{$billingID}" => 'address_zip',
579 "country-{$billingID}" => 'address_country_code',
580 ];
581 foreach ($lookup as $name => $paypalName) {
582 $value = self::retrieve($paypalName, 'String', 'POST', FALSE);
583 $input[$name] = $value ? $value : NULL;
584 }
585
586 $input['is_test'] = self::retrieve('test_ipn', 'Integer', 'POST', FALSE);
587 $input['fee_amount'] = self::retrieve('mc_fee', 'Money', 'POST', FALSE);
588 $input['net_amount'] = self::retrieve('settle_amount', 'Money', 'POST', FALSE);
589 $input['trxn_id'] = self::retrieve('txn_id', 'String', 'POST', FALSE);
590 $input['payment_date'] = $input['receive_date'] = self::retrieve('payment_date', 'String', 'POST', FALSE);
591 $input['total_amount'] = $input['amount'];
592 }
593
594 /**
595 * Handle payment express IPNs.
596 *
597 * For one off IPNS no actual response is required
598 * Recurring is more difficult as we have limited confirmation material
599 * lets look up invoice id in recur_contribution & rely on the unique transaction id to ensure no
600 * duplicated
601 * this may not be acceptable to all sites - e.g. if they are shipping or delivering something in return
602 * then the quasi security of the ids array might be required - although better to
603 * http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
604 * but let's assume knowledge on invoice id & schedule is enough for now esp
605 * for donations only contribute is handled
606 *
607 * @throws \CRM_Core_Exception
608 */
609 public function handlePaymentExpress() {
610 //@todo - loads of copy & paste / code duplication but as this not going into core need to try to
611 // keep discreet
612 // also note that a lot of the complexity above could be removed if we used
613 // http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
614 // as membership id etc can be derived by the load objects fn
615 $objects = $ids = $input = [];
616 $isFirst = FALSE;
617 $input['invoice'] = self::getValue('i', FALSE);
618 //Avoid return in case of unit test.
619 if (empty($input['invoice']) && empty($this->_inputParameters['is_unit_test'])) {
620 return;
621 }
622 $input['txnType'] = $this->retrieve('txn_type', 'String');
623 $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', [
624 'return' => 'contact_id, id, payment_processor_id',
625 'invoice_id' => $input['invoice'],
626 ]);
627 $this->setContributionRecurID((int) $contributionRecur['id']);
628
629 if ($input['txnType'] !== 'recurring_payment' && $input['txnType'] !== 'recurring_payment_profile_created') {
630 throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
631 }
632
633 $this->getInput($input, $ids);
634 if ($input['txnType'] === 'recurring_payment' && $this->transactionExists($input['trxn_id'])) {
635 throw new CRM_Core_Exception('This transaction has already been processed');
636 }
637
638 $ids['contact'] = $contributionRecur['contact_id'];
639 $ids['contributionRecur'] = $this->getContributionRecurID();
640 $result = civicrm_api3('contribution', 'getsingle', ['invoice_id' => $input['invoice'], 'contribution_test' => '']);
641
642 $this->setContributionID((int) $result['id']);
643 $ids['contribution'] = $this->getContributionID();
644 //@todo hardcoding 'pending' for now
645 $pendingStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
646 if ($result['contribution_status_id'] == $pendingStatusId) {
647 $isFirst = TRUE;
648 }
649 // arg api won't get this - fix it
650 $ids['contributionPage'] = CRM_Core_DAO::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", [
651 1 => [
652 $ids['contribution'],
653 'Integer',
654 ],
655 ]);
656 // only handle component at this stage - not terribly sure how a recurring event payment would arise
657 // & suspec main function may be a victom of copy & paste
658 // membership would be an easy add - but not relevant to my customer...
659 $this->_component = $input['component'] = 'contribute';
660 $input['trxn_date'] = date('Y-m-d H:i:s', strtotime(self::retrieve('time_created', 'String')));
661 $paymentProcessorID = $contributionRecur['payment_processor_id'];
662
663 // Check if the contribution exists
664 // make sure contribution exists and is valid
665 $contribution = $this->getContributionObject();
666 $objects['contribution'] = &$contribution;
667
668 // CRM-19478: handle oddity when p=null is set in place of contribution page ID,
669 if (!empty($ids['contributionPage']) && !is_numeric($ids['contributionPage'])) {
670 // We don't need to worry if about removing contribution page id as it will be set later in
671 // CRM_Contribute_BAO_Contribution::loadRelatedObjects(..) using $objects['contribution']->contribution_page_id
672 unset($ids['contributionPage']);
673 }
674
675 $contribution = &$objects['contribution'];
676 $ids['paymentProcessor'] = $paymentProcessorID;
677 $contribution->loadRelatedObjects($input, $ids);
678 $objects = array_merge($objects, $contribution->_relatedObjects);
679
680 $this->recur($input, $this->getContributionRecurObject(), $objects['contribution'], $isFirst);
681 }
682
683 /**
684 * Function check if transaction already exists.
685 * @param string $trxn_id
686 * @return bool|void
687 */
688 public function transactionExists($trxn_id) {
689 if (CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
690 [
691 1 => [$trxn_id, 'String'],
692 ])
693 ) {
694 return TRUE;
695 }
696 }
697
698 /**
699 * Get the recurring contribution object.
700 *
701 * @return \CRM_Contribute_BAO_ContributionRecur
702 * @throws \CRM_Core_Exception
703 */
704 protected function getContributionRecurObject(): CRM_Contribute_BAO_ContributionRecur {
705 if (!$this->contributionRecurObject) {
706 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
707 $contributionRecur->id = $this->getContributionRecurID();
708 if (!$contributionRecur->find(TRUE)) {
709 throw new CRM_Core_Exception('Failure: Could not find contribution recur record');
710 }
711 return $this->contributionRecurObject = $contributionRecur;
712 }
713 return $this->contributionRecurObject;
714 }
715
716 /**
717 * @return \CRM_Contribute_BAO_Contribution
718 * @throws \CRM_Core_Exception
719 */
720 protected function getContributionObject(): CRM_Contribute_BAO_Contribution {
721 if (!$this->contributionObject) {
722 // Check if the contribution exists
723 // make sure contribution exists and is valid
724 $contribution = new CRM_Contribute_BAO_Contribution();
725 $contribution->id = $this->getContributionID();
726 if (!$contribution->find(TRUE)) {
727 throw new CRM_Core_Exception('Failure: Could not find contribution record');
728 }
729 $this->contributionObject = $contribution;
730 }
731 return $this->contributionObject;
732 }
733
734 /**
735 * Get the relevant contact ID.
736 *
737 * @return int
738 * @throws \CRM_Core_Exception
739 */
740 protected function getContactID(): int {
741 return $this->getValue('c', TRUE);
742 }
743
744 }