Merge pull request #15975 from eileenmcnaughton/setting
[civicrm-core.git] / CRM / Core / Payment / BaseIPN.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
TO
11
12/**
1d86918a 13 * Class CRM_Core_Payment_BaseIPN.
6a488035
TO
14 */
15class CRM_Core_Payment_BaseIPN {
16
518fa0ee 17 public static $_now = NULL;
8196c759 18
c8aa607b 19 /**
20 * Input parameters from payment processor. Store these so that
21 * the code does not need to keep retrieving from the http request
22 * @var array
23 */
be2fb01f 24 protected $_inputParameters = [];
c8aa607b 25
59cdadfc 26 /**
27 * Only used by AuthorizeNetIPN.
518fa0ee 28 * @var bool
59cdadfc 29 *
30 * @deprecated
31 *
59cdadfc 32 */
937cf542
EM
33 protected $_isRecurring = FALSE;
34
59cdadfc 35 /**
36 * Only used by AuthorizeNetIPN.
518fa0ee 37 * @var bool
59cdadfc 38 *
39 * @deprecated
40 *
59cdadfc 41 */
937cf542 42 protected $_isFirstOrLastRecurringPayment = FALSE;
353ffa53 43
8196c759 44 /**
fe482240 45 * Constructor.
8196c759 46 */
00be9182 47 public function __construct() {
6a488035
TO
48 self::$_now = date('YmdHis');
49 }
50
c8aa607b 51 /**
fe482240 52 * Store input array on the class.
77b97be7 53 *
c8aa607b 54 * @param array $parameters
77b97be7
EM
55 *
56 * @throws CRM_Core_Exception
c8aa607b 57 */
00be9182 58 public function setInputParameters($parameters) {
22e263ad 59 if (!is_array($parameters)) {
cc0c30cc 60 throw new CRM_Core_Exception('Invalid input parameters');
c8aa607b 61 }
62 $this->_inputParameters = $parameters;
63 }
353ffa53 64
8196c759 65 /**
1d86918a
EM
66 * Validate incoming data.
67 *
68 * This function is intended to ensure that incoming data matches
8196c759 69 * It provides a form of pseudo-authentication - by checking the calling fn already knows
70 * the correct contact id & contribution id (this can be problematic when that has changed in
71 * the meantime for transactions that are delayed & contacts are merged in-between. e.g
72 * Paypal allows you to resend Instant Payment Notifications if you, for example, moved site
73 * and didn't update your IPN URL.
74 *
6a0b768e
TO
75 * @param array $input
76 * Interpreted values from the values returned through the IPN.
77 * @param array $ids
78 * More interpreted values (ids) from the values returned through the IPN.
79 * @param array $objects
80 * An empty array that will be populated with loaded object.
81 * @param bool $required
82 * Boolean Return FALSE if the relevant objects don't exist.
83 * @param int $paymentProcessorID
84 * Id of the payment processor ID in use.
1d86918a 85 *
5c766a0b 86 * @return bool
8196c759 87 */
00be9182 88 public function validateData(&$input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
6a488035
TO
89
90 // make sure contact exists and is valid
5a9c68ac 91 $contact = new CRM_Contact_BAO_Contact();
6a488035
TO
92 $contact->id = $ids['contact'];
93 if (!$contact->find(TRUE)) {
92fcb95f 94 CRM_Core_Error::debug_log_message("Could not find contact record: {$ids['contact']} in IPN request: " . print_r($input, TRUE));
6a488035
TO
95 echo "Failure: Could not find contact record: {$ids['contact']}<p>";
96 return FALSE;
97 }
98
99 // make sure contribution exists and is valid
5a9c68ac 100 $contribution = new CRM_Contribute_BAO_Contribution();
6a488035
TO
101 $contribution->id = $ids['contribution'];
102 if (!$contribution->find(TRUE)) {
92fcb95f 103 CRM_Core_Error::debug_log_message("Could not find contribution record: {$contribution->id} in IPN request: " . print_r($input, TRUE));
6a488035
TO
104 echo "Failure: Could not find contribution record for {$contribution->id}<p>";
105 return FALSE;
106 }
107 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
d9924163 108 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
6a488035
TO
109
110 $objects['contact'] = &$contact;
111 $objects['contribution'] = &$contribution;
d0488f03 112
113 // CRM-19478: handle oddity when p=null is set in place of contribution page ID,
114 if (!empty($ids['contributionPage']) && !is_numeric($ids['contributionPage'])) {
115 // We don't need to worry if about removing contribution page id as it will be set later in
116 // CRM_Contribute_BAO_Contribution::loadRelatedObjects(..) using $objects['contribution']->contribution_page_id
117 unset($ids['contributionPage']);
118 }
119
6a488035
TO
120 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
121 return FALSE;
122 }
a284891b
EM
123 //the process is that the loadObjects is kind of hacked by loading the objects for the original contribution and then somewhat inconsistently using them for the
124 //current contribution. Here we ensure that the original contribution is available to the complete transaction function
125 //we don't want to fix this in the payment processor classes because we would have to fix all of them - so better to fix somewhere central
126 if (isset($objects['contributionRecur'])) {
127 $objects['first_contribution'] = $objects['contribution'];
128 }
6a488035
TO
129 return TRUE;
130 }
131
8196c759 132 /**
fe482240 133 * Load objects related to contribution.
6a488035
TO
134 *
135 * @input array information from Payment processor
dd244018 136 *
3aaa68fb 137 * @param array $input
8196c759 138 * @param array $ids
139 * @param array $objects
6a0b768e
TO
140 * @param bool $required
141 * @param int $paymentProcessorID
8196c759 142 * @param array $error_handling
dd244018 143 *
3aaa68fb 144 * @return bool|array
6a488035 145 */
00be9182 146 public function loadObjects(&$input, &$ids, &$objects, $required, $paymentProcessorID, $error_handling = NULL) {
6a488035
TO
147 if (empty($error_handling)) {
148 // default options are that we log an error & echo it out
149 // note that we should refactor this error handling into error code @ some point
150 // but for now setting up enough separation so we can do unit tests
be2fb01f 151 $error_handling = [
6a488035
TO
152 'log_error' => 1,
153 'echo_error' => 1,
be2fb01f 154 ];
6a488035
TO
155 }
156 $ids['paymentProcessor'] = $paymentProcessorID;
157 if (is_a($objects['contribution'], 'CRM_Contribute_BAO_Contribution')) {
158 $contribution = &$objects['contribution'];
159 }
160 else {
161 //legacy support - functions are 'used' to be able to pass in a DAO
162 $contribution = new CRM_Contribute_BAO_Contribution();
163 $contribution->id = CRM_Utils_Array::value('contribution', $ids);
164 $contribution->find(TRUE);
165 $objects['contribution'] = &$contribution;
166 }
167 try {
276e3ec6 168 $success = $contribution->loadRelatedObjects($input, $ids);
169 if ($required && empty($contribution->_relatedObjects['paymentProcessor'])) {
170 throw new CRM_Core_Exception("Could not find payment processor for contribution record: " . $contribution->id);
171 }
6a488035 172 }
353ffa53 173 catch (Exception $e) {
cc0c30cc 174 $success = FALSE;
a7488080 175 if (!empty($error_handling['log_error'])) {
6a488035
TO
176 CRM_Core_Error::debug_log_message($e->getMessage());
177 }
a7488080 178 if (!empty($error_handling['echo_error'])) {
6c552737 179 echo $e->getMessage();
6a488035 180 }
a7488080 181 if (!empty($error_handling['return_error'])) {
be2fb01f 182 return [
6a488035
TO
183 'is_error' => 1,
184 'error_message' => ($e->getMessage()),
be2fb01f 185 ];
6a488035
TO
186 }
187 }
188 $objects = array_merge($objects, $contribution->_relatedObjects);
189 return $success;
190 }
191
8196c759 192 /**
fe482240 193 * Set contribution to failed.
28de42d1 194 *
8196c759 195 * @param array $objects
196 * @param object $transaction
197 * @param array $input
28de42d1 198 *
5c766a0b 199 * @return bool
e44c82e1 200 * @throws \CiviCRM_API3_Exception
8196c759 201 */
be2fb01f 202 public function failed(&$objects, &$transaction, $input = []) {
6a488035 203 $contribution = &$objects['contribution'];
be2fb01f 204 $memberships = [];
a7488080 205 if (!empty($objects['membership'])) {
6a488035
TO
206 $memberships = &$objects['membership'];
207 if (is_numeric($memberships)) {
be2fb01f 208 $memberships = [$objects['membership']];
6a488035
TO
209 }
210 }
211
212 $addLineItems = FALSE;
213 if (empty($contribution->id)) {
214 $addLineItems = TRUE;
215 }
216 $participant = &$objects['participant'];
217
3aaa68fb 218 // CRM-15546
be2fb01f 219 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
518fa0ee
SL
220 'labelColumn' => 'name',
221 'flip' => 1,
222 ]);
e44c82e1 223 $contribution->contribution_status_id = $contributionStatuses['Failed'];
5a9c68ac
PJ
224 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
225 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
226 $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
6a488035
TO
227 $contribution->save();
228
28de42d1 229 // Add line items for recurring payments.
a7488080 230 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
e577770c 231 CRM_Contribute_BAO_ContributionRecur::addRecurLineItems($objects['contributionRecur']->id, $contribution);
6a488035
TO
232 }
233
8381af80 234 //add new soft credit against current contribution id and
6357981e 235 //copy initial contribution custom fields for recurring contributions
a7488080 236 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id) {
e577770c
EM
237 CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
238 CRM_Contribute_BAO_ContributionRecur::copyCustomValues($objects['contributionRecur']->id, $contribution->id);
6357981e
PJ
239 }
240
0bad10e7 241 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
6a488035
TO
242 if (!empty($memberships)) {
243 foreach ($memberships as $membership) {
56c7d914
MWMC
244 // @fixme Should we cancel only Pending memberships? per cancelled()
245 $this->cancelMembership($membership, $membership->status_id, FALSE);
6a488035
TO
246 }
247 }
d63f4fc3 248
6a488035 249 if ($participant) {
56c7d914 250 $this->cancelParticipant($participant->id);
6a488035
TO
251 }
252 }
253
254 $transaction->commit();
e44c82e1 255 Civi::log()->debug("Setting contribution status to Failed");
6a488035
TO
256 return TRUE;
257 }
258
8196c759 259 /**
fe482240 260 * Handled pending contribution status.
1d86918a 261 *
8196c759 262 * @param array $objects
263 * @param object $transaction
1d86918a 264 *
5c766a0b 265 * @return bool
8196c759 266 */
00be9182 267 public function pending(&$objects, &$transaction) {
6a488035 268 $transaction->commit();
e44c82e1 269 Civi::log()->debug("Returning since contribution status is Pending");
6a488035
TO
270 echo "Success: Returning since contribution status is pending<p>";
271 return TRUE;
272 }
273
6c786a9b 274 /**
1d86918a
EM
275 * Process cancelled payment outcome.
276 *
3aaa68fb 277 * @param array $objects
278 * @param CRM_Core_Transaction $transaction
6c786a9b
EM
279 * @param array $input
280 *
281 * @return bool
e44c82e1 282 * @throws \CiviCRM_API3_Exception
6c786a9b 283 */
be2fb01f 284 public function cancelled(&$objects, &$transaction, $input = []) {
6a488035 285 $contribution = &$objects['contribution'];
e44c82e1
MWMC
286 $memberships = [];
287 if (!empty($objects['membership'])) {
288 $memberships = &$objects['membership'];
289 if (is_numeric($memberships)) {
290 $memberships = [$objects['membership']];
291 }
6a488035
TO
292 }
293
6a488035
TO
294 $addLineItems = FALSE;
295 if (empty($contribution->id)) {
296 $addLineItems = TRUE;
297 }
e44c82e1
MWMC
298 $participant = &$objects['participant'];
299
300 // CRM-15546
be2fb01f 301 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
518fa0ee
SL
302 'labelColumn' => 'name',
303 'flip' => 1,
304 ]);
71d085fe 305 $contribution->contribution_status_id = $contributionStatuses['Cancelled'];
6a488035
TO
306 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
307 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
308 $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
e44c82e1
MWMC
309 $contribution->cancel_date = self::$_now;
310 $contribution->cancel_reason = CRM_Utils_Array::value('reasonCode', $input);
6a488035
TO
311 $contribution->save();
312
e44c82e1 313 // Add line items for recurring payments.
a7488080 314 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
e577770c 315 CRM_Contribute_BAO_ContributionRecur::addRecurLineItems($objects['contributionRecur']->id, $contribution);
6a488035
TO
316 }
317
8381af80 318 //add new soft credit against current $contribution and
6357981e 319 //copy initial contribution custom fields for recurring contributions
a7488080 320 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id) {
e577770c
EM
321 CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
322 CRM_Contribute_BAO_ContributionRecur::copyCustomValues($objects['contributionRecur']->id, $contribution->id);
6357981e
PJ
323 }
324
0bad10e7 325 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
6a488035
TO
326 if (!empty($memberships)) {
327 foreach ($memberships as $membership) {
56c7d914
MWMC
328 if ($membership) {
329 $this->cancelMembership($membership, $membership->status_id);
6a488035
TO
330 }
331 }
332 }
d63f4fc3 333
6a488035 334 if ($participant) {
56c7d914 335 $this->cancelParticipant($participant->id);
6a488035
TO
336 }
337 }
338 $transaction->commit();
e44c82e1 339 Civi::log()->debug("Setting contribution status to Cancelled");
6a488035
TO
340 return TRUE;
341 }
342
6c786a9b 343 /**
1d86918a
EM
344 * Rollback unhandled outcomes.
345 *
3aaa68fb 346 * @param array $objects
347 * @param CRM_Core_Transaction $transaction
6c786a9b
EM
348 *
349 * @return bool
350 */
00be9182 351 public function unhandled(&$objects, &$transaction) {
6a488035 352 $transaction->rollback();
e44c82e1 353 Civi::log()->debug("Returning since contribution status is not handled");
2d8851f6 354 echo "Failure: contribution status is not handled<p>";
6a488035
TO
355 return FALSE;
356 }
357
56c7d914
MWMC
358 /**
359 * Logic to cancel a participant record when the related contribution changes to failed/cancelled.
360 * @todo This is part of a bigger refactor for dev/core/issues/927 - "duplicate" functionality exists in CRM_Contribute_BAO_Contribution::cancel()
361 *
362 * @param $participantID
363 *
364 * @throws \CiviCRM_API3_Exception
365 */
366 private function cancelParticipant($participantID) {
367 // @fixme https://lab.civicrm.org/dev/core/issues/927 Cancelling membership etc is not desirable for all use-cases and we should be able to disable it
368 $participantParams['id'] = $participantID;
369 $participantParams['status_id'] = 'Cancelled';
370 civicrm_api3('Participant', 'create', $participantParams);
371 }
372
373 /**
374 * Logic to cancel a membership record when the related contribution changes to failed/cancelled.
375 * @todo This is part of a bigger refactor for dev/core/issues/927 - "duplicate" functionality exists in CRM_Contribute_BAO_Contribution::cancel()
376 * @param \CRM_Member_BAO_Membership $membership
377 * @param int $membershipStatusID
378 * @param boolean $onlyCancelPendingMembership
379 * Do we only cancel pending memberships? OR memberships in any status? (see CRM-18688)
380 * @fixme Historically failed() cancelled membership in any status, cancelled() cancelled only pending memberships so we retain that behaviour for now.
381 *
382 */
383 private function cancelMembership($membership, $membershipStatusID, $onlyCancelPendingMembership = TRUE) {
384 // @fixme https://lab.civicrm.org/dev/core/issues/927 Cancelling membership etc is not desirable for all use-cases and we should be able to disable it
385 // Cancel only Pending memberships
386 $pendingMembershipStatusId = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending');
387 if (($membershipStatusID == $pendingMembershipStatusId) || ($onlyCancelPendingMembership == FALSE)) {
388 $cancelledMembershipStatusId = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Cancelled');
389
390 $membership->status_id = $cancelledMembershipStatusId;
391 $membership->save();
392
393 $params = ['status_id' => $cancelledMembershipStatusId];
394 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
395
396 // @todo Convert the above to API
397 // $membershipParams = [
398 // 'id' => $membership->id,
399 // 'status_id' => $cancelledMembershipStatusId,
400 // ];
401 // civicrm_api3('Membership', 'create', $membershipParams);
402 // CRM_Member_BAO_Membership::updateRelatedMemberships($membershipParams['id'], ['status_id' => $cancelledMembershipStatusId]);
403 }
404
405 }
406
6c786a9b 407 /**
4a1ba425 408 * @deprecated
409 *
3ccde016 410 * Jumbled up function.
1d86918a 411 *
3ccde016
EM
412 * The purpose of this function is to transition a pending transaction to Completed including updating any
413 * related entities.
414 *
415 * It has been overloaded to also add recurring transactions to the database, cloning the original transaction and
416 * updating related entities.
417 *
418 * It is recommended to avoid calling this function directly and call the api functions:
419 * - contribution.completetransaction
420 * - contribution.repeattransaction
421 *
422 * These functions are the focus of testing efforts and more accurately reflect the division of roles
423 * (the job of the IPN class is to determine the outcome, transaction id, invoice id & to validate the source
424 * and from there it should be possible to pass off transaction management.)
425 *
426 * This function has been problematic for some time but there are now several tests via the api_v3_Contribution test
427 * and the Paypal & Authorize.net IPN tests so any refactoring should be done in conjunction with those.
428 *
5ca657dd 429 * This function needs to have the 'body' moved to the CRM_Contribute_BAO_Contribute class and to undergo
3ccde016
EM
430 * refactoring to separate the complete transaction and repeat transaction functionality into separate functions with
431 * a shared function that updates related components.
432 *
433 * Note that it is not necessary payment processor extension to implement an IPN class now. In general the code on the
434 * IPN class is better accessed through the api which de-jumbles it a bit.
435 *
436 * e.g the payment class can have a function like (based on Omnipay extension):
437 *
438 * public function handlePaymentNotification() {
439 * $response = $this->getValidatedOutcome();
440 * if ($response->isSuccessful()) {
441 * try {
442 * // @todo check if it is a repeat transaction & call repeattransaction instead.
443 * civicrm_api3('contribution', 'completetransaction', array('id' => $this->transaction_id));
444 * }
445 * catch (CiviCRM_API3_Exception $e) {
446 * if (!stristr($e->getMessage(), 'Contribution already completed')) {
447 * $this->handleError('error', $this->transaction_id . $e->getMessage(), 'ipn_completion', 9000, 'An error may
448 * have occurred. Please check your receipt is correct');
449 * $this->redirectOrExit('success');
450 * }
451 * elseif ($this->transaction_id) {
452 * civicrm_api3('contribution', 'create', array('id' => $this->transaction_id, 'contribution_status_id' =>
453 * 'Failed'));
454 * }
455 *
456 * @param array $input
457 * @param array $ids
458 * @param array $objects
3aaa68fb 459 * @param CRM_Core_Transaction $transaction
e44c82e1
MWMC
460 *
461 * @throws \CRM_Core_Exception
462 * @throws \CiviCRM_API3_Exception
6c786a9b 463 */
27d10f99 464 public function completeTransaction(&$input, &$ids, &$objects, &$transaction) {
6a488035 465 $contribution = &$objects['contribution'];
a284891b 466
27d10f99 467 CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $objects, $transaction, $contribution);
6a488035
TO
468 }
469
6c786a9b 470 /**
1d86918a
EM
471 * Get site billing ID.
472 *
473 * @param array $ids
6c786a9b
EM
474 *
475 * @return bool
476 */
00be9182 477 public function getBillingID(&$ids) {
b576d770 478 $ids['billing'] = CRM_Core_BAO_LocationType::getBilling();
6a488035 479 if (!$ids['billing']) {
be2fb01f 480 CRM_Core_Error::debug_log_message(ts('Please set a location type of %1', [1 => 'Billing']));
6a488035
TO
481 echo "Failure: Could not find billing location type<p>";
482 return FALSE;
483 }
484 return TRUE;
485 }
486
c490a46a 487 /**
db59bb73
EM
488 * @deprecated
489 *
6626a693 490 * @todo confirm this function is not being used by any payment processor outside core & remove.
491 *
1d86918a 492 * Note that the compose message part has been moved to contribution
6a488035
TO
493 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
494 *
6a0b768e
TO
495 * @param array $input
496 * Incoming data from Payment processor.
497 * @param array $ids
498 * Related object IDs.
3aaa68fb 499 * @param array $objects
6a0b768e
TO
500 * @param array $values
501 * Values related to objects that have already been loaded.
502 * @param bool $recur
503 * Is it part of a recurring contribution.
504 * @param bool $returnMessageText
505 * Should text be returned instead of sent. This.
16b10e64 506 * is because the function is also used to generate pdfs
6c786a9b 507 *
c490a46a 508 * @return array
e44c82e1
MWMC
509 * @throws \CRM_Core_Exception
510 * @throws \CiviCRM_API3_Exception
6c786a9b 511 */
00be9182 512 public function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
6626a693 513 return CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $objects['contribution']->id, $values,
3425da09 514 $returnMessageText);
6a488035
TO
515 }
516
b2b0530a 517}