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