Merge pull request #24115 from kcristiano/5.52-token
[civicrm-core.git] / CRM / Core / Payment / PayPalProIPN.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035 11
a201e208 12use Civi\Api4\Contribution;
13
6a488035
TO
14/**
15 *
16 * @package CRM
ca5cec67 17 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
18 */
19class CRM_Core_Payment_PayPalProIPN extends CRM_Core_Payment_BaseIPN {
20
c8aa607b 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 */
be2fb01f 26 protected $_inputParameters = [];
c8aa607b 27
28 /**
fe482240 29 * Store for the variables from the invoice string.
c8aa607b 30 * @var array
31 */
be2fb01f 32 protected $_invoiceData = [];
c8aa607b 33
34 /**
fe482240 35 * Is this a payment express transaction.
518fa0ee 36 * @var bool
c8aa607b 37 */
38 protected $_isPaymentExpress = FALSE;
39
55f6a006
EM
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
6c196048
EM
54 /**
55 * Contribution object.
56 *
57 * @var \CRM_Contribute_BAO_Contribution
58 */
59 protected $contributionObject;
65f88018
EM
60 /**
61 * Contribution ID.
62 *
63 * @var int
64 */
65 protected $contributionID;
66
55f6a006
EM
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
65f88018
EM
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
55f6a006
EM
98 /**
99 * @param int|null $contributionRecurID
100 */
101 public function setContributionRecurID(?int $contributionRecurID): void {
102 $this->contributionRecurID = $contributionRecurID;
103 }
104
65f88018
EM
105 /**
106 * Set contribution ID.
107 *
108 * @param int $contributionID
109 */
110 public function setContributionID(int $contributionID): void {
111 $this->contributionID = $contributionID;
112 }
113
c8aa607b 114 /**
e97c66ff 115 * Component.
116 *
117 * Are we dealing with an event an 'anything else' (contribute).
118 *
119 * @var string
c8aa607b 120 */
121 protected $_component = 'contribute';
0dbefed3 122
c8aa607b 123 /**
fe482240 124 * Constructor function.
0dbefed3 125 *
6a0b768e
TO
126 * @param array $inputData
127 * Contents of HTTP REQUEST.
0dbefed3
EM
128 *
129 * @throws CRM_Core_Exception
c8aa607b 130 */
00be9182 131 public function __construct($inputData) {
c8aa607b 132 $this->setInputParameters($inputData);
133 $this->setInvoiceData();
6a488035
TO
134 parent::__construct();
135 }
136
c8aa607b 137 /**
fe482240 138 * get the values from the rp_invoice_id string.
77b97be7 139 *
6a0b768e
TO
140 * @param string $name
141 * E.g. i, values are stored in the string with letter codes.
142 * @param bool $abort
16b10e64 143 * Throw exception if not found
77b97be7
EM
144 *
145 * @throws CRM_Core_Exception
16b10e64 146 * @return mixed
c8aa607b 147 */
00be9182 148 public function getValue($name, $abort = TRUE) {
c8aa607b 149 if ($abort && empty($this->_invoiceData[$name])) {
150 throw new CRM_Core_Exception("Failure: Missing Parameter $name");
6a488035
TO
151 }
152 else {
914d3734 153 return $this->_invoiceData[$name] ?? NULL;
c8aa607b 154 }
155 }
156
157 /**
158 * Set $this->_invoiceData from the input array
159 */
00be9182 160 public function setInvoiceData() {
22e263ad 161 if (empty($this->_inputParameters['rp_invoice_id'])) {
c8aa607b 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
be2fb01f 168 $mapping = [
c8aa607b 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',
be2fb01f 176 ];
c8aa607b 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
6c1df5dc 184 if ($rpValueArray[1] === 'contribute') {
c8aa607b 185 $mapping['p'] = 'contribution_page_id';
186 }
6a488035 187 }
22e263ad 188 if (empty($this->_inputParameters['component'])) {
949babe8
JM
189 $this->_isPaymentExpress = TRUE;
190 }
6a488035
TO
191 }
192
c8aa607b 193 /**
6a0b768e
TO
194 * @param string $name
195 * Of variable to return.
196 * @param string $type
197 * Data type.
c8aa607b 198 * - String
199 * - Integer
6a0b768e
TO
200 * @param string $location
201 * Deprecated.
202 * @param bool $abort
203 * Abort if empty.
77b97be7
EM
204 *
205 * @throws CRM_Core_Exception
72b3a70c 206 * @return mixed
c8aa607b 207 */
00be9182 208 public function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
c8aa607b 209 $value = CRM_Utils_Type::validate(
210 CRM_Utils_Array::value($name, $this->_inputParameters),
211 $type,
212 FALSE
6a488035
TO
213 );
214 if ($abort && $value === NULL) {
c8aa607b 215 throw new CRM_Core_Exception("Could not find an entry for $name in $location");
6a488035
TO
216 }
217 return $value;
218 }
219
c8aa607b 220 /**
fe482240 221 * Process recurring contributions.
95179d8a 222 *
c8aa607b 223 * @param array $input
95179d8a 224 *
62dda083 225 * @throws \API_Exception
95179d8a 226 * @throws \CRM_Core_Exception
227 * @throws \CiviCRM_API3_Exception
62dda083 228 * @throws \Civi\API\Exception\UnauthorizedException
c8aa607b 229 */
93b7ac88 230 public function recur(array $input): void {
f4190115
EM
231 // check if first contribution is completed, else complete first contribution
232 $first = !$this->isContributionCompleted();
93b7ac88 233 $recur = $this->getContributionRecurObject();
6a488035 234 if (!isset($input['txnType'])) {
d2803851 235 Civi::log()->debug('PayPalProIPN: Could not find txn_type in input request.');
95179d8a 236 echo 'Failure: Invalid parameters<p>';
d2803851 237 return;
6a488035
TO
238 }
239
6a488035
TO
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']) {
d2803851 244 Civi::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id . ' input is ' . $input['invoice']);
95179d8a 245 echo 'Failure: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id . " input is " . $input['invoice'];
d2803851 246 return;
6a488035
TO
247 }
248
249 $now = date('YmdHis');
250
6a488035
TO
251 $sendNotification = FALSE;
252 $subscriptionPaymentStatus = NULL;
253 //List of Transaction Type
254 /*
e70a7fc0 255 recurring_payment_profile_created RP Profile Created
b44e3f84 256 recurring_payment RP Successful Payment
e70a7fc0
TO
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
b44e3f84 261 recurring_payment_outstanding_payment RP Successful Outstanding Payment
e70a7fc0
TO
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 */
6a488035 266
6a488035 267 //set transaction type
c8aa607b 268 $txnType = $this->retrieve('txn_type', 'String');
6a488035 269 //Changes for paypal pro recurring payment
d2803851 270 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate'));
6a488035
TO
271 switch ($txnType) {
272 case 'recurring_payment_profile_created':
be2fb01f 273 if (in_array($recur->contribution_status_id, [
518fa0ee
SL
274 $contributionStatuses['Pending'],
275 $contributionStatuses['In Progress'],
276 ])
353ffa53
TO
277 && !empty($recur->processor_id)
278 ) {
e25b58d1 279 echo "already handled";
d2803851 280 return;
e25b58d1 281 }
6a488035 282 $recur->create_date = $now;
d2803851 283 $recur->contribution_status_id = $contributionStatuses['Pending'];
d57577d4 284 $recur->processor_id = $this->retrieve('recurring_payment_id', 'String');
6a488035
TO
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':
c4055cec 291 if (!$first) {
55f6a006 292 if ($input['paymentStatus'] !== 'Completed') {
5b51381e 293 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
294 }
b3924856 295
5b51381e 296 // In future moving to create pending & then complete, but this OK for now.
297 // Also consider accepting 'Failed' like other processors.
b3924856
MWMC
298 $input['contribution_status_id'] = $contributionStatuses['Completed'];
299 $input['invoice_id'] = md5(uniqid(rand(), TRUE));
65f88018 300 $input['original_contribution_id'] = $this->getContributionID();
2d222eb9 301 $input['contribution_recur_id'] = $this->getContributionRecurID();
5b51381e 302
303 civicrm_api3('Contribution', 'repeattransaction', $input);
304 return;
6a488035
TO
305 }
306
307 //contribution installment is completed
c8aa607b 308 if ($this->retrieve('profile_status', 'String') == 'Expired') {
22e263ad 309 if (!empty($recur->end_date)) {
e25b58d1 310 echo "already handled";
d2803851 311 return;
e25b58d1 312 }
d2803851 313 $recur->contribution_status_id = $contributionStatuses['Completed'];
6a488035
TO
314 $recur->end_date = $now;
315 $sendNotification = TRUE;
316 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
317 }
318
6a488035
TO
319 break;
320 }
321
322 $recur->save();
323
324 if ($sendNotification) {
6a488035 325 //send recurring Notification email for user
ce9ceea4 326 CRM_Contribute_BAO_ContributionPage::recurringNotify(
65f88018 327 $this->getContributionID(),
ce9ceea4 328 $subscriptionPaymentStatus,
4206fa5c 329 $recur
6a488035
TO
330 );
331 }
332
cfb2f038 333 if ($txnType !== 'recurring_payment') {
d2803851 334 return;
6a488035
TO
335 }
336
7ca87aa3 337 $this->single($input);
6a488035
TO
338 }
339
6c786a9b 340 /**
d2803851 341 * @param array $input
7a9ab499 342 *
d2803851 343 * @return void
61470a1a 344 * @throws \API_Exception
a29b1ef2 345 * @throws \CRM_Core_Exception
346 * @throws \CiviCRM_API3_Exception
6c786a9b 347 */
83da51fa 348 protected function single(array $input): void {
6a488035
TO
349
350 // make sure the invoice is valid and matches what we have in the contribution record
65e97828 351 if (!$this->isContributionCompleted()) {
3d11a1e8
EM
352 if ($this->getContributionObject()->invoice_id !== $input['invoice']) {
353 throw new CRM_Core_Exception('PayPalProIPN: Invoice values dont match between database and IPN request.');
6a488035 354 }
65e97828 355 if (!$this->getContributionRecurID() && $this->getContributionObject()->total_amount != $input['amount']) {
3d11a1e8 356 throw new CRM_Core_Exception('PayPalProIPN: Amount values dont match between database and IPN request.');
6a488035
TO
357 }
358 }
6a488035 359
6a488035 360 $status = $input['paymentStatus'];
95179d8a 361 if ($status === 'Denied' || $status === 'Failed' || $status === 'Voided') {
61470a1a 362 Contribution::update(FALSE)->setValues([
363 'cancel_date' => 'now',
364 'contribution_status_id:name' => 'Failed',
65e97828
EM
365 ])->addWhere('id', '=', $this->getContributionID())->execute();
366 Civi::log()->debug('Setting contribution status to Failed');
d2803851 367 return;
6a488035 368 }
0e89200f 369 if ($status === 'Pending') {
370 Civi::log()->debug('Returning since contribution status is Pending');
d2803851 371 return;
6a488035 372 }
a201e208 373 if ($status === 'Refunded' || $status === 'Reversed') {
374 Contribution::update(FALSE)->setValues([
375 'cancel_date' => 'now',
376 'contribution_status_id:name' => 'Cancelled',
3d11a1e8 377 ])->addWhere('id', '=', $this->getContributionID())->execute();
83da51fa 378 Civi::log()->debug('Setting contribution status to Cancelled');
d2803851 379 return;
6a488035 380 }
65e97828 381 if ($status !== 'Completed') {
85ce114d 382 Civi::log()->debug('Returning since contribution status is not handled');
d2803851 383 return;
6a488035
TO
384 }
385
65e97828 386 if ($this->isContributionCompleted()) {
d2803851 387 Civi::log()->debug('PayPalProIPN: Returning since contribution has already been handled.');
85ce114d 388 echo 'Success: Contribution has already been handled<p>';
d2803851 389 return;
6a488035
TO
390 }
391
3d11a1e8 392 CRM_Contribute_BAO_Contribution::completeOrder($input, $this->getContributionRecurID(), $this->getContributionID());
6a488035
TO
393 }
394
eaf9432c
LB
395 /**
396 * Gets PaymentProcessorID for PayPal
397 *
398 * @return int
399 */
400 public function getPayPalPaymentProcessorID() {
401 // This is an unreliable method as there could be more than one instance.
402 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
403 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
404 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
405 // & call completetransaction or call fail? (which may not exist yet).
d2803851
MW
406
407 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');
408
eaf9432c
LB
409 $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
410 'PayPal', 'id', 'name'
411 );
be2fb01f 412 return (int) civicrm_api3('PaymentProcessor', 'getvalue', [
eaf9432c 413 'is_test' => 0,
be2fb01f 414 'options' => ['limit' => 1],
eaf9432c
LB
415 'payment_processor_type_id' => $paymentProcessorTypeID,
416 'return' => 'id',
be2fb01f 417 ]);
eaf9432c
LB
418
419 }
420
c8aa607b 421 /**
422 * This is the main function to call. It should be sufficient to instantiate the class
423 * (with the input parameters) & call this & all will be done
424 *
425 * @todo the references to POST throughout this class need to be removed
d2803851 426 * @return void
c8aa607b 427 */
83da51fa 428 public function main(): void {
6a488035
TO
429 CRM_Core_Error::debug_var('GET', $_GET, TRUE, TRUE);
430 CRM_Core_Error::debug_var('POST', $_POST, TRUE, TRUE);
83da51fa 431 $input = [];
cd0f2a34 432 try {
433 if ($this->_isPaymentExpress) {
434 $this->handlePaymentExpress();
435 return;
436 }
83da51fa
EM
437 if ($this->getValue('m') === 'event') {
438 // Validate required params.
439 $this->getValue('e');
440 $this->getValue('p');
441 }
442 $input['invoice'] = $this->getValue('i');
4ea61b8d
EM
443 if ($this->getContributionObject()->contact_id !== $this->getContactID()) {
444 // 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
445 CRM_Core_Error::debug_log_message('Contact ID in IPN ' . $this->getContactID() . ' not found but contact_id found in contribution ' . $this->getContributionID() . ' used instead');
446 echo 'WARNING: Could not find contact record: ' . $this->getContactID() . '<p>';
4ea61b8d 447 }
cd0f2a34 448
449 $this->getInput($input);
83da51fa 450 $input['payment_processor_id'] = $this->_inputParameters['processor_id'] ?? $this->getPayPalPaymentProcessorID();
dc65872a 451
55f6a006 452 if ($this->getContributionRecurID()) {
93b7ac88 453 $this->recur($input);
2ae7909b 454 return;
6a488035 455 }
2ae7909b 456
7ca87aa3 457 $this->single($input);
cd0f2a34 458 }
83da51fa 459 catch (Exception $e) {
55f6a006 460 Civi::log()->debug($e->getMessage() . ' input {input}', ['input' => $input]);
cd0f2a34 461 echo 'Invalid or missing data';
6a488035
TO
462 }
463 }
464
6c786a9b 465 /**
d2803851 466 * @param array $input
6c786a9b 467 *
d2803851 468 * @return void
6c786a9b
EM
469 * @throws CRM_Core_Exception
470 */
41ce57e7 471 public function getInput(&$input) {
472 $billingID = CRM_Core_BAO_LocationType::getBilling();
6a488035
TO
473
474 $input['txnType'] = self::retrieve('txn_type', 'String', 'POST', FALSE);
475 $input['paymentStatus'] = self::retrieve('payment_status', 'String', 'POST', FALSE);
6a488035
TO
476
477 $input['amount'] = self::retrieve('mc_gross', 'Money', 'POST', FALSE);
478 $input['reasonCode'] = self::retrieve('ReasonCode', 'String', 'POST', FALSE);
479
be2fb01f 480 $lookup = [
6a488035
TO
481 "first_name" => 'first_name',
482 "last_name" => 'last_name',
483 "street_address-{$billingID}" => 'address_street',
484 "city-{$billingID}" => 'address_city',
485 "state-{$billingID}" => 'address_state',
486 "postal_code-{$billingID}" => 'address_zip',
487 "country-{$billingID}" => 'address_country_code',
be2fb01f 488 ];
6a488035
TO
489 foreach ($lookup as $name => $paypalName) {
490 $value = self::retrieve($paypalName, 'String', 'POST', FALSE);
491 $input[$name] = $value ? $value : NULL;
492 }
493
353ffa53 494 $input['is_test'] = self::retrieve('test_ipn', 'Integer', 'POST', FALSE);
6a488035
TO
495 $input['fee_amount'] = self::retrieve('mc_fee', 'Money', 'POST', FALSE);
496 $input['net_amount'] = self::retrieve('settle_amount', 'Money', 'POST', FALSE);
353ffa53 497 $input['trxn_id'] = self::retrieve('txn_id', 'String', 'POST', FALSE);
12829b5d 498 $input['payment_date'] = $input['receive_date'] = self::retrieve('payment_date', 'String', 'POST', FALSE);
94155403 499 $input['total_amount'] = $input['amount'];
6a488035 500 }
c8aa607b 501
502 /**
fe482240 503 * Handle payment express IPNs.
6439290e 504 *
c8aa607b 505 * For one off IPNS no actual response is required
506 * Recurring is more difficult as we have limited confirmation material
83da51fa
EM
507 * lets look up invoice id in recur_contribution & rely on the unique
508 * transaction id to ensure no duplicated this may not be acceptable to all
509 * sites - e.g. if they are shipping or delivering something in return then
510 * the quasi security of the ids array might be required - although better to
949babe8 511 * http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
65f88018
EM
512 * but let's assume knowledge on invoice id & schedule is enough for now esp
513 * for donations only contribute is handled
514 *
5541557b 515 * @throws \API_Exception
65f88018 516 * @throws \CRM_Core_Exception
5541557b 517 * @throws \CiviCRM_API3_Exception
c8aa607b 518 */
5541557b
EM
519 public function handlePaymentExpress(): void {
520 $input = ['invoice' => $this->getValue('i', FALSE)];
6d8785b9
JP
521 //Avoid return in case of unit test.
522 if (empty($input['invoice']) && empty($this->_inputParameters['is_unit_test'])) {
b9bb2511
JP
523 return;
524 }
353ffa53 525 $input['txnType'] = $this->retrieve('txn_type', 'String');
be2fb01f 526 $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', [
6439290e 527 'return' => 'contact_id, id, payment_processor_id',
528 'invoice_id' => $input['invoice'],
be2fb01f 529 ]);
55f6a006 530 $this->setContributionRecurID((int) $contributionRecur['id']);
6439290e 531
532 if ($input['txnType'] !== 'recurring_payment' && $input['txnType'] !== 'recurring_payment_profile_created') {
949babe8
JM
533 throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
534 }
6439290e 535
5541557b 536 $this->getInput($input);
6439290e 537 if ($input['txnType'] === 'recurring_payment' && $this->transactionExists($input['trxn_id'])) {
949babe8
JM
538 throw new CRM_Core_Exception('This transaction has already been processed');
539 }
6439290e 540 $result = civicrm_api3('contribution', 'getsingle', ['invoice_id' => $input['invoice'], 'contribution_test' => '']);
65f88018 541 $this->setContributionID((int) $result['id']);
5541557b 542 $input['trxn_date'] = date('Y-m-d H:i:s', strtotime($this->retrieve('time_created', 'String')));
93b7ac88 543 $this->recur($input);
949babe8
JM
544 }
545
546 /**
fe482240 547 * Function check if transaction already exists.
949babe8 548 * @param string $trxn_id
72b3a70c 549 * @return bool|void
949babe8 550 */
00be9182 551 public function transactionExists($trxn_id) {
22e263ad 552 if (CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
be2fb01f
CW
553 [
554 1 => [$trxn_id, 'String'],
555 ])
353ffa53 556 ) {
949babe8
JM
557 return TRUE;
558 }
c8aa607b 559 }
96025800 560
55f6a006
EM
561 /**
562 * Get the recurring contribution object.
563 *
564 * @return \CRM_Contribute_BAO_ContributionRecur
565 * @throws \CRM_Core_Exception
566 */
567 protected function getContributionRecurObject(): CRM_Contribute_BAO_ContributionRecur {
568 if (!$this->contributionRecurObject) {
569 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
570 $contributionRecur->id = $this->getContributionRecurID();
571 if (!$contributionRecur->find(TRUE)) {
572 throw new CRM_Core_Exception('Failure: Could not find contribution recur record');
573 }
574 return $this->contributionRecurObject = $contributionRecur;
575 }
576 return $this->contributionRecurObject;
577 }
578
6c196048
EM
579 /**
580 * @return \CRM_Contribute_BAO_Contribution
581 * @throws \CRM_Core_Exception
582 */
583 protected function getContributionObject(): CRM_Contribute_BAO_Contribution {
584 if (!$this->contributionObject) {
585 // Check if the contribution exists
586 // make sure contribution exists and is valid
587 $contribution = new CRM_Contribute_BAO_Contribution();
588 $contribution->id = $this->getContributionID();
589 if (!$contribution->find(TRUE)) {
590 throw new CRM_Core_Exception('Failure: Could not find contribution record');
591 }
83da51fa
EM
592 // The DAO types it as int but doesn't return it as int.
593 $contribution->contact_id = (int) $contribution->contact_id;
6c196048
EM
594 $this->contributionObject = $contribution;
595 }
596 return $this->contributionObject;
597 }
598
599 /**
600 * Get the relevant contact ID.
601 *
602 * @return int
603 * @throws \CRM_Core_Exception
604 */
605 protected function getContactID(): int {
606 return $this->getValue('c', TRUE);
607 }
608
65e97828
EM
609 /**
610 * Is the original contribution completed.
611 *
612 * @return bool
613 * @throws \CRM_Core_Exception
614 */
615 private function isContributionCompleted(): bool {
616 $status = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $this->getContributionObject()->contribution_status_id);
617 return $status === 'Completed';
618 }
619
6a488035 620}