Merge pull request #20411 from eileenmcnaughton/ppp2
[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 *
227 * @throws \API_Exception
228 * @throws \CRM_Core_Exception
229 * @throws \CiviCRM_API3_Exception
230 * @throws \Civi\API\Exception\UnauthorizedException
231 */
232 public function recur($input, $recur, $contribution) {
233 // check if first contribution is completed, else complete first contribution
234 $first = !$this->isContributionCompleted();
235 if (!isset($input['txnType'])) {
236 Civi::log()->debug('PayPalProIPN: Could not find txn_type in input request.');
237 echo 'Failure: Invalid parameters<p>';
238 return;
239 }
240
241 // make sure the invoice ids match
242 // make sure the invoice is valid and matches what we have in
243 // the contribution record
244 if ($recur->invoice_id != $input['invoice']) {
245 Civi::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id . ' input is ' . $input['invoice']);
246 echo 'Failure: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id . " input is " . $input['invoice'];
247 return;
248 }
249
250 $now = date('YmdHis');
251
252 $sendNotification = FALSE;
253 $subscriptionPaymentStatus = NULL;
254 //List of Transaction Type
255 /*
256 recurring_payment_profile_created RP Profile Created
257 recurring_payment RP Successful Payment
258 recurring_payment_failed RP Failed Payment
259 recurring_payment_profile_cancel RP Profile Cancelled
260 recurring_payment_expired RP Profile Expired
261 recurring_payment_skipped RP Profile Skipped
262 recurring_payment_outstanding_payment RP Successful Outstanding Payment
263 recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
264 recurring_payment_suspended RP Profile Suspended
265 recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
266 */
267
268 //set transaction type
269 $txnType = $this->retrieve('txn_type', 'String');
270 //Changes for paypal pro recurring payment
271 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate'));
272 switch ($txnType) {
273 case 'recurring_payment_profile_created':
274 if (in_array($recur->contribution_status_id, [
275 $contributionStatuses['Pending'],
276 $contributionStatuses['In Progress'],
277 ])
278 && !empty($recur->processor_id)
279 ) {
280 echo "already handled";
281 return;
282 }
283 $recur->create_date = $now;
284 $recur->contribution_status_id = $contributionStatuses['Pending'];
285 $recur->processor_id = $this->retrieve('recurring_payment_id', 'String');
286 $recur->trxn_id = $recur->processor_id;
287 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
288 $sendNotification = TRUE;
289 break;
290
291 case 'recurring_payment':
292 if ($first) {
293 $recur->start_date = $now;
294 }
295 else {
296 if ($input['paymentStatus'] !== 'Completed') {
297 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
298 }
299
300 // In future moving to create pending & then complete, but this OK for now.
301 // Also consider accepting 'Failed' like other processors.
302 $input['contribution_status_id'] = $contributionStatuses['Completed'];
303 $input['invoice_id'] = md5(uniqid(rand(), TRUE));
304 $input['original_contribution_id'] = $this->getContributionID();
305 $input['contribution_recur_id'] = $this->getContributionRecurID();
306
307 civicrm_api3('Contribution', 'repeattransaction', $input);
308 return;
309 }
310
311 //contribution installment is completed
312 if ($this->retrieve('profile_status', 'String') == 'Expired') {
313 if (!empty($recur->end_date)) {
314 echo "already handled";
315 return;
316 }
317 $recur->contribution_status_id = $contributionStatuses['Completed'];
318 $recur->end_date = $now;
319 $sendNotification = TRUE;
320 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
321 }
322
323 // make sure the contribution status is not done
324 // since order of ipn's is unknown
325 if ($recur->contribution_status_id != $contributionStatuses['Completed']) {
326 $recur->contribution_status_id = $contributionStatuses['In Progress'];
327 }
328 break;
329 }
330
331 $recur->save();
332
333 if ($sendNotification) {
334 //send recurring Notification email for user
335 CRM_Contribute_BAO_ContributionPage::recurringNotify(
336 $this->getContributionID(),
337 $subscriptionPaymentStatus,
338 $recur
339 );
340 }
341
342 if ($txnType !== 'recurring_payment') {
343 return;
344 }
345
346 // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
347 $contribution->receive_date = !empty($input['payment_date']) ? date('YmdHis', strtotime($input['payment_date'])) : $now;
348
349 $this->single($input);
350 }
351
352 /**
353 * @param array $input
354 *
355 * @return void
356 * @throws \API_Exception
357 * @throws \CRM_Core_Exception
358 * @throws \CiviCRM_API3_Exception
359 * @throws \Civi\API\Exception\UnauthorizedException
360 */
361 public function single($input) {
362
363 // make sure the invoice is valid and matches what we have in the contribution record
364 if (!$this->isContributionCompleted()) {
365 if ($this->getContributionObject()->invoice_id !== $input['invoice']) {
366 throw new CRM_Core_Exception('PayPalProIPN: Invoice values dont match between database and IPN request.');
367 }
368 if (!$this->getContributionRecurID() && $this->getContributionObject()->total_amount != $input['amount']) {
369 throw new CRM_Core_Exception('PayPalProIPN: Amount values dont match between database and IPN request.');
370 }
371 }
372
373 $status = $input['paymentStatus'];
374 if ($status === 'Denied' || $status === 'Failed' || $status === 'Voided') {
375 Contribution::update(FALSE)->setValues([
376 'cancel_date' => 'now',
377 'contribution_status_id:name' => 'Failed',
378 ])->addWhere('id', '=', $this->getContributionID())->execute();
379 Civi::log()->debug('Setting contribution status to Failed');
380 return;
381 }
382 if ($status === 'Pending') {
383 Civi::log()->debug('Returning since contribution status is Pending');
384 return;
385 }
386 if ($status === 'Refunded' || $status === 'Reversed') {
387 Contribution::update(FALSE)->setValues([
388 'cancel_date' => 'now',
389 'contribution_status_id:name' => 'Cancelled',
390 ])->addWhere('id', '=', $this->getContributionID())->execute();
391 Civi::log()->debug("Setting contribution status to Cancelled");
392 return;
393 }
394 if ($status !== 'Completed') {
395 Civi::log()->debug('Returning since contribution status is not handled');
396 return;
397 }
398
399 if ($this->isContributionCompleted()) {
400 Civi::log()->debug('PayPalProIPN: Returning since contribution has already been handled.');
401 echo 'Success: Contribution has already been handled<p>';
402 return;
403 }
404
405 CRM_Contribute_BAO_Contribution::completeOrder($input, $this->getContributionRecurID(), $this->getContributionID());
406 }
407
408 /**
409 * Gets PaymentProcessorID for PayPal
410 *
411 * @return int
412 */
413 public function getPayPalPaymentProcessorID() {
414 // This is an unreliable method as there could be more than one instance.
415 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
416 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
417 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
418 // & call completetransaction or call fail? (which may not exist yet).
419
420 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');
421
422 $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
423 'PayPal', 'id', 'name'
424 );
425 return (int) civicrm_api3('PaymentProcessor', 'getvalue', [
426 'is_test' => 0,
427 'options' => ['limit' => 1],
428 'payment_processor_type_id' => $paymentProcessorTypeID,
429 'return' => 'id',
430 ]);
431
432 }
433
434 /**
435 * This is the main function to call. It should be sufficient to instantiate the class
436 * (with the input parameters) & call this & all will be done
437 *
438 * @todo the references to POST throughout this class need to be removed
439 * @return void
440 */
441 public function main() {
442 CRM_Core_Error::debug_var('GET', $_GET, TRUE, TRUE);
443 CRM_Core_Error::debug_var('POST', $_POST, TRUE, TRUE);
444 $ids = $input = [];
445 try {
446 if ($this->_isPaymentExpress) {
447 $this->handlePaymentExpress();
448 return;
449 }
450 $this->_component = $input['component'] = self::getValue('m');
451 $input['invoice'] = self::getValue('i', TRUE);
452 // get the contribution and contact ids from the GET params
453 $ids['contact'] = $this->getContactID();
454 $ids['contribution'] = $this->getContributionID();
455
456 $this->getInput($input);
457
458 if ($this->_component == 'event') {
459 $ids['event'] = self::getValue('e', TRUE);
460 $ids['participant'] = self::getValue('p', TRUE);
461 $ids['contributionRecur'] = $this->getContributionRecurID();
462 }
463 else {
464 // get the optional ids
465 //@ how can this not be broken retrieving from GET as we are dealing with a POST request?
466 // copy & paste? Note the retrieve function now uses data from _REQUEST so this will be included
467 $ids['membership'] = self::retrieve('membershipID', 'Integer', 'GET', FALSE);
468 $ids['contributionRecur'] = $this->getContributionRecurID();
469 $ids['contributionPage'] = self::getValue('p', FALSE);
470 $ids['related_contact'] = self::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
471 $ids['onbehalf_dupe_alert'] = self::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
472 }
473
474 if (!$ids['membership'] && $this->getContributionRecurID()) {
475 $sql = "
476 SELECT m.id
477 FROM civicrm_membership m
478 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
479 WHERE m.contribution_recur_id = %2
480 LIMIT 1";
481 $sqlParams = [
482 1 => [$ids['contribution'], 'Integer'],
483 2 => [$this->getContributionRecurID(), 'Integer'],
484 ];
485 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql, $sqlParams)) {
486 $ids['membership'] = $membershipId;
487 }
488 }
489
490 $paymentProcessorID = CRM_Utils_Array::value('processor_id', $this->_inputParameters);
491 if (!$paymentProcessorID) {
492 $paymentProcessorID = self::getPayPalPaymentProcessorID();
493 }
494 $contribution = $this->getContributionObject();
495
496 // make sure contact exists and is valid
497 // use the contact id from the contribution record as the id in the IPN may not be valid anymore.
498 $contact = new CRM_Contact_BAO_Contact();
499 $contact->id = $contribution->contact_id;
500 $contact->find(TRUE);
501 if ($contact->id != $ids['contact']) {
502 // 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
503 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");
504 echo "WARNING: Could not find contact record: {$ids['contact']}<p>";
505 $ids['contact'] = $contribution->contact_id;
506 }
507
508 // CRM-19478: handle oddity when p=null is set in place of contribution page ID,
509 if (!empty($ids['contributionPage']) && !is_numeric($ids['contributionPage'])) {
510 // We don't need to worry if about removing contribution page id as it will be set later in
511 // CRM_Contribute_BAO_Contribution::loadRelatedObjects(..) using $objects['contribution']->contribution_page_id
512 unset($ids['contributionPage']);
513 }
514
515 $ids['paymentProcessor'] = $paymentProcessorID;
516 $contribution->loadRelatedObjects($input, $ids);
517
518 $input['payment_processor_id'] = $paymentProcessorID;
519
520 if ($this->getContributionRecurID()) {
521 $contributionRecur = $this->getContributionRecurObject();
522 $this->recur($input, $contributionRecur, $contribution);
523 return;
524 }
525
526 $this->single($input);
527 }
528 catch (CRM_Core_Exception $e) {
529 Civi::log()->debug($e->getMessage() . ' input {input}', ['input' => $input]);
530 echo 'Invalid or missing data';
531 }
532 }
533
534 /**
535 * @param array $input
536 *
537 * @return void
538 * @throws CRM_Core_Exception
539 */
540 public function getInput(&$input) {
541 $billingID = CRM_Core_BAO_LocationType::getBilling();
542
543 $input['txnType'] = self::retrieve('txn_type', 'String', 'POST', FALSE);
544 $input['paymentStatus'] = self::retrieve('payment_status', 'String', 'POST', FALSE);
545
546 $input['amount'] = self::retrieve('mc_gross', 'Money', 'POST', FALSE);
547 $input['reasonCode'] = self::retrieve('ReasonCode', 'String', 'POST', FALSE);
548
549 $lookup = [
550 "first_name" => 'first_name',
551 "last_name" => 'last_name',
552 "street_address-{$billingID}" => 'address_street',
553 "city-{$billingID}" => 'address_city',
554 "state-{$billingID}" => 'address_state',
555 "postal_code-{$billingID}" => 'address_zip',
556 "country-{$billingID}" => 'address_country_code',
557 ];
558 foreach ($lookup as $name => $paypalName) {
559 $value = self::retrieve($paypalName, 'String', 'POST', FALSE);
560 $input[$name] = $value ? $value : NULL;
561 }
562
563 $input['is_test'] = self::retrieve('test_ipn', 'Integer', 'POST', FALSE);
564 $input['fee_amount'] = self::retrieve('mc_fee', 'Money', 'POST', FALSE);
565 $input['net_amount'] = self::retrieve('settle_amount', 'Money', 'POST', FALSE);
566 $input['trxn_id'] = self::retrieve('txn_id', 'String', 'POST', FALSE);
567 $input['payment_date'] = $input['receive_date'] = self::retrieve('payment_date', 'String', 'POST', FALSE);
568 $input['total_amount'] = $input['amount'];
569 }
570
571 /**
572 * Handle payment express IPNs.
573 *
574 * For one off IPNS no actual response is required
575 * Recurring is more difficult as we have limited confirmation material
576 * lets look up invoice id in recur_contribution & rely on the unique transaction id to ensure no
577 * duplicated
578 * this may not be acceptable to all sites - e.g. if they are shipping or delivering something in return
579 * then the quasi security of the ids array might be required - although better to
580 * http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
581 * but let's assume knowledge on invoice id & schedule is enough for now esp
582 * for donations only contribute is handled
583 *
584 * @throws \CRM_Core_Exception
585 */
586 public function handlePaymentExpress() {
587 //@todo - loads of copy & paste / code duplication but as this not going into core need to try to
588 // keep discreet
589 // also note that a lot of the complexity above could be removed if we used
590 // http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
591 // as membership id etc can be derived by the load objects fn
592 $objects = $ids = $input = [];
593 $input['invoice'] = self::getValue('i', FALSE);
594 //Avoid return in case of unit test.
595 if (empty($input['invoice']) && empty($this->_inputParameters['is_unit_test'])) {
596 return;
597 }
598 $input['txnType'] = $this->retrieve('txn_type', 'String');
599 $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', [
600 'return' => 'contact_id, id, payment_processor_id',
601 'invoice_id' => $input['invoice'],
602 ]);
603 $this->setContributionRecurID((int) $contributionRecur['id']);
604
605 if ($input['txnType'] !== 'recurring_payment' && $input['txnType'] !== 'recurring_payment_profile_created') {
606 throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
607 }
608
609 $this->getInput($input, $ids);
610 if ($input['txnType'] === 'recurring_payment' && $this->transactionExists($input['trxn_id'])) {
611 throw new CRM_Core_Exception('This transaction has already been processed');
612 }
613
614 $ids['contact'] = $contributionRecur['contact_id'];
615 $ids['contributionRecur'] = $this->getContributionRecurID();
616 $result = civicrm_api3('contribution', 'getsingle', ['invoice_id' => $input['invoice'], 'contribution_test' => '']);
617
618 $this->setContributionID((int) $result['id']);
619 $ids['contribution'] = $this->getContributionID();
620 // arg api won't get this - fix it
621 $ids['contributionPage'] = CRM_Core_DAO::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", [
622 1 => [
623 $ids['contribution'],
624 'Integer',
625 ],
626 ]);
627 // only handle component at this stage - not terribly sure how a recurring event payment would arise
628 // & suspec main function may be a victom of copy & paste
629 // membership would be an easy add - but not relevant to my customer...
630 $this->_component = $input['component'] = 'contribute';
631 $input['trxn_date'] = date('Y-m-d H:i:s', strtotime(self::retrieve('time_created', 'String')));
632 $paymentProcessorID = $contributionRecur['payment_processor_id'];
633
634 // Check if the contribution exists
635 // make sure contribution exists and is valid
636 $contribution = $this->getContributionObject();
637 $objects['contribution'] = &$contribution;
638
639 // CRM-19478: handle oddity when p=null is set in place of contribution page ID,
640 if (!empty($ids['contributionPage']) && !is_numeric($ids['contributionPage'])) {
641 // We don't need to worry if about removing contribution page id as it will be set later in
642 // CRM_Contribute_BAO_Contribution::loadRelatedObjects(..) using $objects['contribution']->contribution_page_id
643 unset($ids['contributionPage']);
644 }
645
646 $contribution = &$objects['contribution'];
647 $ids['paymentProcessor'] = $paymentProcessorID;
648 $contribution->loadRelatedObjects($input, $ids);
649 $objects = array_merge($objects, $contribution->_relatedObjects);
650
651 $this->recur($input, $this->getContributionRecurObject(), $objects['contribution']);
652 }
653
654 /**
655 * Function check if transaction already exists.
656 * @param string $trxn_id
657 * @return bool|void
658 */
659 public function transactionExists($trxn_id) {
660 if (CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
661 [
662 1 => [$trxn_id, 'String'],
663 ])
664 ) {
665 return TRUE;
666 }
667 }
668
669 /**
670 * Get the recurring contribution object.
671 *
672 * @return \CRM_Contribute_BAO_ContributionRecur
673 * @throws \CRM_Core_Exception
674 */
675 protected function getContributionRecurObject(): CRM_Contribute_BAO_ContributionRecur {
676 if (!$this->contributionRecurObject) {
677 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
678 $contributionRecur->id = $this->getContributionRecurID();
679 if (!$contributionRecur->find(TRUE)) {
680 throw new CRM_Core_Exception('Failure: Could not find contribution recur record');
681 }
682 return $this->contributionRecurObject = $contributionRecur;
683 }
684 return $this->contributionRecurObject;
685 }
686
687 /**
688 * @return \CRM_Contribute_BAO_Contribution
689 * @throws \CRM_Core_Exception
690 */
691 protected function getContributionObject(): CRM_Contribute_BAO_Contribution {
692 if (!$this->contributionObject) {
693 // Check if the contribution exists
694 // make sure contribution exists and is valid
695 $contribution = new CRM_Contribute_BAO_Contribution();
696 $contribution->id = $this->getContributionID();
697 if (!$contribution->find(TRUE)) {
698 throw new CRM_Core_Exception('Failure: Could not find contribution record');
699 }
700 $this->contributionObject = $contribution;
701 }
702 return $this->contributionObject;
703 }
704
705 /**
706 * Get the relevant contact ID.
707 *
708 * @return int
709 * @throws \CRM_Core_Exception
710 */
711 protected function getContactID(): int {
712 return $this->getValue('c', TRUE);
713 }
714
715 /**
716 * Is the original contribution completed.
717 *
718 * @return bool
719 * @throws \CRM_Core_Exception
720 */
721 private function isContributionCompleted(): bool {
722 $status = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $this->getContributionObject()->contribution_status_id);
723 return $status === 'Completed';
724 }
725
726 }