Remove error handling from loadObjects
[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 throw new CRM_Core_Exception('Failure: Could not find contribution record for ' . (int) $contribution->id, NULL, ['context' => "Could not find contribution record: {$contribution->id} in IPN request: " . print_r($input, TRUE)]);
96 }
97
98 // make sure contact exists and is valid
99 // use the contact id from the contribution record as the id in the IPN may not be valid anymore.
100 $contact = new CRM_Contact_BAO_Contact();
101 $contact->id = $contribution->contact_id;
102 $contact->find(TRUE);
103 if ($contact->id != $ids['contact']) {
104 // 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
105 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");
106 echo "WARNING: Could not find contact record: {$ids['contact']}<p>";
107 $ids['contact'] = $contribution->contact_id;
108 }
109
110 if (!empty($ids['contributionRecur'])) {
111 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
112 $contributionRecur->id = $ids['contributionRecur'];
113 if (!$contributionRecur->find(TRUE)) {
114 CRM_Core_Error::debug_log_message("Could not find contribution recur record: {$ids['ContributionRecur']} in IPN request: " . print_r($input, TRUE));
115 echo "Failure: Could not find contribution recur record: {$ids['ContributionRecur']}<p>";
116 return FALSE;
117 }
118 }
119
120 $objects['contact'] = &$contact;
121 $objects['contribution'] = &$contribution;
122
123 // CRM-19478: handle oddity when p=null is set in place of contribution page ID,
124 if (!empty($ids['contributionPage']) && !is_numeric($ids['contributionPage'])) {
125 // We don't need to worry if about removing contribution page id as it will be set later in
126 // CRM_Contribute_BAO_Contribution::loadRelatedObjects(..) using $objects['contribution']->contribution_page_id
127 unset($ids['contributionPage']);
128 }
129
130 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
131 return FALSE;
132 }
133 return TRUE;
134 }
135
136 /**
137 * Load objects related to contribution.
138 *
139 * @input array information from Payment processor
140 *
141 * @param array $input
142 * @param array $ids
143 * @param array $objects
144 * @param bool $required
145 * @param int $paymentProcessorID
146 *
147 * @return bool|array
148 * @throws \CRM_Core_Exception
149 */
150 public function loadObjects($input, &$ids, &$objects, $required, $paymentProcessorID) {
151 $contribution = &$objects['contribution'];
152 $ids['paymentProcessor'] = $paymentProcessorID;
153 $success = $contribution->loadRelatedObjects($input, $ids);
154 if ($required && empty($contribution->_relatedObjects['paymentProcessor'])) {
155 throw new CRM_Core_Exception("Could not find payment processor for contribution record: " . $contribution->id);
156 }
157 $objects = array_merge($objects, $contribution->_relatedObjects);
158 return $success;
159 }
160
161 /**
162 * Set contribution to failed.
163 *
164 * @param array $objects
165 * @param object $transaction
166 * @param array $input
167 *
168 * @return bool
169 * @throws \CiviCRM_API3_Exception
170 */
171 public function failed(&$objects, $transaction = NULL, $input = []) {
172 $contribution = &$objects['contribution'];
173 $memberships = [];
174 if (!empty($objects['membership'])) {
175 $memberships = &$objects['membership'];
176 if (is_numeric($memberships)) {
177 $memberships = [$objects['membership']];
178 }
179 }
180
181 $addLineItems = empty($contribution->id);
182 $participant = &$objects['participant'];
183 $contribution->contribution_status_id = CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Failed');
184 $contribution->save();
185
186 // Add line items for recurring payments.
187 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
188 CRM_Contribute_BAO_ContributionRecur::addRecurLineItems($objects['contributionRecur']->id, $contribution);
189 }
190
191 //add new soft credit against current contribution id and
192 //copy initial contribution custom fields for recurring contributions
193 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id) {
194 CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
195 CRM_Contribute_BAO_ContributionRecur::copyCustomValues($objects['contributionRecur']->id, $contribution->id);
196 }
197
198 if (!empty($memberships)) {
199 foreach ($memberships as $membership) {
200 // @fixme Should we cancel only Pending memberships? per cancelled()
201 $this->cancelMembership($membership, $membership->status_id, FALSE);
202 }
203 }
204
205 if ($participant) {
206 $this->cancelParticipant($participant->id);
207 }
208
209 if ($transaction) {
210 $transaction->commit();
211 }
212 Civi::log()->debug("Setting contribution status to Failed");
213 return TRUE;
214 }
215
216 /**
217 * Handled pending contribution status.
218 *
219 * @deprecated
220 *
221 * @param array $objects
222 * @param object $transaction
223 *
224 * @return bool
225 */
226 public function pending(&$objects, &$transaction) {
227 CRM_Core_Error::deprecatedFunctionWarning('This function will be removed at some point');
228 $transaction->commit();
229 Civi::log()->debug('Returning since contribution status is Pending');
230 echo 'Success: Returning since contribution status is pending<p>';
231 return TRUE;
232 }
233
234 /**
235 * Process cancelled payment outcome.
236 *
237 * @param array $objects
238 * @param CRM_Core_Transaction $transaction
239 * @param array $input
240 *
241 * @return bool
242 * @throws \CiviCRM_API3_Exception
243 */
244 public function cancelled(&$objects, $transaction = NULL, $input = []) {
245 $contribution = &$objects['contribution'];
246 $memberships = [];
247 if (!empty($objects['membership'])) {
248 $memberships = &$objects['membership'];
249 if (is_numeric($memberships)) {
250 $memberships = [$objects['membership']];
251 }
252 }
253
254 $addLineItems = FALSE;
255 if (empty($contribution->id)) {
256 $addLineItems = TRUE;
257 }
258 $participant = &$objects['participant'];
259
260 // CRM-15546
261 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
262 'labelColumn' => 'name',
263 'flip' => 1,
264 ]);
265 $contribution->contribution_status_id = $contributionStatuses['Cancelled'];
266 $contribution->cancel_date = self::$_now;
267 $contribution->cancel_reason = $input['reasonCode'] ?? NULL;
268 $contribution->save();
269
270 // Add line items for recurring payments.
271 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
272 CRM_Contribute_BAO_ContributionRecur::addRecurLineItems($objects['contributionRecur']->id, $contribution);
273 }
274
275 //add new soft credit against current $contribution and
276 //copy initial contribution custom fields for recurring contributions
277 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id) {
278 CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
279 CRM_Contribute_BAO_ContributionRecur::copyCustomValues($objects['contributionRecur']->id, $contribution->id);
280 }
281
282 if (!empty($memberships)) {
283 foreach ($memberships as $membership) {
284 if ($membership) {
285 $this->cancelMembership($membership, $membership->status_id);
286 }
287 }
288 }
289
290 if ($participant) {
291 $this->cancelParticipant($participant->id);
292 }
293
294 if ($transaction) {
295 $transaction->commit();
296 }
297 Civi::log()->debug("Setting contribution status to Cancelled");
298 return TRUE;
299 }
300
301 /**
302 * Rollback unhandled outcomes.
303 *
304 * @deprecated
305 *
306 * @param array $objects
307 * @param CRM_Core_Transaction $transaction
308 *
309 * @return bool
310 */
311 public function unhandled(&$objects, &$transaction) {
312 CRM_Core_Error::deprecatedFunctionWarning('This function will be removed at some point');
313 $transaction->rollback();
314 Civi::log()->debug('Returning since contribution status is not handled');
315 echo 'Failure: contribution status is not handled<p>';
316 return FALSE;
317 }
318
319 /**
320 * Logic to cancel a participant record when the related contribution changes to failed/cancelled.
321 * @todo This is part of a bigger refactor for dev/core/issues/927 - "duplicate" functionality exists in CRM_Contribute_BAO_Contribution::cancel()
322 *
323 * @param $participantID
324 *
325 * @throws \CiviCRM_API3_Exception
326 */
327 private function cancelParticipant($participantID) {
328 // @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
329 $participantParams['id'] = $participantID;
330 $participantParams['status_id'] = 'Cancelled';
331 civicrm_api3('Participant', 'create', $participantParams);
332 }
333
334 /**
335 * Logic to cancel a membership record when the related contribution changes to failed/cancelled.
336 * @todo This is part of a bigger refactor for dev/core/issues/927 - "duplicate" functionality exists in CRM_Contribute_BAO_Contribution::cancel()
337 * @param \CRM_Member_BAO_Membership $membership
338 * @param int $membershipStatusID
339 * @param boolean $onlyCancelPendingMembership
340 * Do we only cancel pending memberships? OR memberships in any status? (see CRM-18688)
341 * @fixme Historically failed() cancelled membership in any status, cancelled() cancelled only pending memberships so we retain that behaviour for now.
342 *
343 */
344 private function cancelMembership($membership, $membershipStatusID, $onlyCancelPendingMembership = TRUE) {
345 // @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
346 // Cancel only Pending memberships
347 $pendingMembershipStatusId = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending');
348 if (($membershipStatusID == $pendingMembershipStatusId) || ($onlyCancelPendingMembership == FALSE)) {
349 $cancelledMembershipStatusId = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Cancelled');
350
351 $membership->status_id = $cancelledMembershipStatusId;
352 $membership->save();
353
354 $params = ['status_id' => $cancelledMembershipStatusId];
355 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
356
357 // @todo Convert the above to API
358 // $membershipParams = [
359 // 'id' => $membership->id,
360 // 'status_id' => $cancelledMembershipStatusId,
361 // ];
362 // civicrm_api3('Membership', 'create', $membershipParams);
363 // CRM_Member_BAO_Membership::updateRelatedMemberships($membershipParams['id'], ['status_id' => $cancelledMembershipStatusId]);
364 }
365
366 }
367
368 /**
369 * @deprecated
370 *
371 * Jumbled up function.
372 *
373 * The purpose of this function is to transition a pending transaction to Completed including updating any
374 * related entities.
375 *
376 * It has been overloaded to also add recurring transactions to the database, cloning the original transaction and
377 * updating related entities.
378 *
379 * It is recommended to avoid calling this function directly and call the api functions:
380 * - contribution.completetransaction
381 * - contribution.repeattransaction
382 *
383 * These functions are the focus of testing efforts and more accurately reflect the division of roles
384 * (the job of the IPN class is to determine the outcome, transaction id, invoice id & to validate the source
385 * and from there it should be possible to pass off transaction management.)
386 *
387 * This function has been problematic for some time but there are now several tests via the api_v3_Contribution test
388 * and the Paypal & Authorize.net IPN tests so any refactoring should be done in conjunction with those.
389 *
390 * This function needs to have the 'body' moved to the CRM_Contribute_BAO_Contribute class and to undergo
391 * refactoring to separate the complete transaction and repeat transaction functionality into separate functions with
392 * a shared function that updates related components.
393 *
394 * Note that it is not necessary payment processor extension to implement an IPN class now. In general the code on the
395 * IPN class is better accessed through the api which de-jumbles it a bit.
396 *
397 * e.g the payment class can have a function like (based on Omnipay extension):
398 *
399 * public function handlePaymentNotification() {
400 * $response = $this->getValidatedOutcome();
401 * if ($response->isSuccessful()) {
402 * try {
403 * // @todo check if it is a repeat transaction & call repeattransaction instead.
404 * civicrm_api3('contribution', 'completetransaction', array('id' => $this->transaction_id));
405 * }
406 * catch (CiviCRM_API3_Exception $e) {
407 * if (!stristr($e->getMessage(), 'Contribution already completed')) {
408 * $this->handleError('error', $this->transaction_id . $e->getMessage(), 'ipn_completion', 9000, 'An error may
409 * have occurred. Please check your receipt is correct');
410 * $this->redirectOrExit('success');
411 * }
412 * elseif ($this->transaction_id) {
413 * civicrm_api3('contribution', 'create', array('id' => $this->transaction_id, 'contribution_status_id' =>
414 * 'Failed'));
415 * }
416 *
417 * @param array $input
418 * @param array $ids
419 * @param array $objects
420 *
421 * @throws \CRM_Core_Exception
422 * @throws \CiviCRM_API3_Exception
423 */
424 public function completeTransaction($input, $ids, $objects) {
425 CRM_Core_Error::deprecatedFunctionWarning('Use Payment.create api');
426 CRM_Contribute_BAO_Contribution::completeOrder($input, [
427 'related_contact' => $ids['related_contact'] ?? NULL,
428 'participant' => !empty($objects['participant']) ? $objects['participant']->id : NULL,
429 'contributionRecur' => !empty($objects['contributionRecur']) ? $objects['contributionRecur']->id : NULL,
430 ], $objects);
431 }
432
433 /**
434 * @deprecated
435 * Get site billing ID.
436 *
437 * @param array $ids
438 *
439 * @return bool
440 */
441 public function getBillingID(&$ids) {
442 CRM_Core_Error::deprecatedFunctionWarning('CRM_Core_BAO_LocationType::getBilling()');
443 $ids['billing'] = CRM_Core_BAO_LocationType::getBilling();
444 if (!$ids['billing']) {
445 CRM_Core_Error::debug_log_message(ts('Please set a location type of %1', [1 => 'Billing']));
446 echo "Failure: Could not find billing location type<p>";
447 return FALSE;
448 }
449 return TRUE;
450 }
451
452 /**
453 * @deprecated
454 *
455 * @todo confirm this function is not being used by any payment processor outside core & remove.
456 *
457 * Note that the compose message part has been moved to contribution
458 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
459 *
460 * @param array $input
461 * Incoming data from Payment processor.
462 * @param array $ids
463 * Related object IDs.
464 * @param array $objects
465 *
466 * @throws \CiviCRM_API3_Exception
467 */
468 public function sendMail($input, $ids, $objects) {
469 CRM_Core_Error::deprecatedFunctionWarning('this should be done via completetransaction api');
470 civicrm_api3('Contribution', 'sendconfirmation', [
471 'id' => $objects['contribution']->id,
472 ]);
473 }
474
475 }