Ian province abbreviation patch - issue 724
[civicrm-core.git] / CRM / Core / Payment / BaseIPN.php
... / ...
CommitLineData
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28/**
29 * Class CRM_Core_Payment_BaseIPN.
30 */
31class CRM_Core_Payment_BaseIPN {
32
33 static $_now = NULL;
34
35 /**
36 * Input parameters from payment processor. Store these so that
37 * the code does not need to keep retrieving from the http request
38 * @var array
39 */
40 protected $_inputParameters = array();
41
42 /**
43 * Only used by AuthorizeNetIPN.
44 *
45 * @deprecated
46 *
47 * @var bool
48 */
49 protected $_isRecurring = FALSE;
50
51 /**
52 * Only used by AuthorizeNetIPN.
53 *
54 * @deprecated
55 *
56 * @var bool
57 */
58 protected $_isFirstOrLastRecurringPayment = FALSE;
59
60 /**
61 * Constructor.
62 */
63 public function __construct() {
64 self::$_now = date('YmdHis');
65 }
66
67 /**
68 * Store input array on the class.
69 *
70 * @param array $parameters
71 *
72 * @throws CRM_Core_Exception
73 */
74 public function setInputParameters($parameters) {
75 if (!is_array($parameters)) {
76 throw new CRM_Core_Exception('Invalid input parameters');
77 }
78 $this->_inputParameters = $parameters;
79 }
80
81 /**
82 * Validate incoming data.
83 *
84 * This function is intended to ensure that incoming data matches
85 * It provides a form of pseudo-authentication - by checking the calling fn already knows
86 * the correct contact id & contribution id (this can be problematic when that has changed in
87 * the meantime for transactions that are delayed & contacts are merged in-between. e.g
88 * Paypal allows you to resend Instant Payment Notifications if you, for example, moved site
89 * and didn't update your IPN URL.
90 *
91 * @param array $input
92 * Interpreted values from the values returned through the IPN.
93 * @param array $ids
94 * More interpreted values (ids) from the values returned through the IPN.
95 * @param array $objects
96 * An empty array that will be populated with loaded object.
97 * @param bool $required
98 * Boolean Return FALSE if the relevant objects don't exist.
99 * @param int $paymentProcessorID
100 * Id of the payment processor ID in use.
101 *
102 * @return bool
103 */
104 public function validateData(&$input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
105
106 // make sure contact exists and is valid
107 $contact = new CRM_Contact_BAO_Contact();
108 $contact->id = $ids['contact'];
109 if (!$contact->find(TRUE)) {
110 CRM_Core_Error::debug_log_message("Could not find contact record: {$ids['contact']} in IPN request: " . print_r($input, TRUE));
111 echo "Failure: Could not find contact record: {$ids['contact']}<p>";
112 return FALSE;
113 }
114
115 // make sure contribution exists and is valid
116 $contribution = new CRM_Contribute_BAO_Contribution();
117 $contribution->id = $ids['contribution'];
118 if (!$contribution->find(TRUE)) {
119 CRM_Core_Error::debug_log_message("Could not find contribution record: {$contribution->id} in IPN request: " . print_r($input, TRUE));
120 echo "Failure: Could not find contribution record for {$contribution->id}<p>";
121 return FALSE;
122 }
123 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
124
125 $objects['contact'] = &$contact;
126 $objects['contribution'] = &$contribution;
127 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
128 return FALSE;
129 }
130 //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
131 //current contribution. Here we ensure that the original contribution is available to the complete transaction function
132 //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
133 if (isset($objects['contributionRecur'])) {
134 $objects['first_contribution'] = $objects['contribution'];
135 }
136 return TRUE;
137 }
138
139 /**
140 * Load objects related to contribution.
141 *
142 * @input array information from Payment processor
143 *
144 * @param $input
145 * @param array $ids
146 * @param array $objects
147 * @param bool $required
148 * @param int $paymentProcessorID
149 * @param array $error_handling
150 *
151 * @return bool
152 */
153 public function loadObjects(&$input, &$ids, &$objects, $required, $paymentProcessorID, $error_handling = NULL) {
154 if (empty($error_handling)) {
155 // default options are that we log an error & echo it out
156 // note that we should refactor this error handling into error code @ some point
157 // but for now setting up enough separation so we can do unit tests
158 $error_handling = array(
159 'log_error' => 1,
160 'echo_error' => 1,
161 );
162 }
163 $ids['paymentProcessor'] = $paymentProcessorID;
164 if (is_a($objects['contribution'], 'CRM_Contribute_BAO_Contribution')) {
165 $contribution = &$objects['contribution'];
166 }
167 else {
168 //legacy support - functions are 'used' to be able to pass in a DAO
169 $contribution = new CRM_Contribute_BAO_Contribution();
170 $contribution->id = CRM_Utils_Array::value('contribution', $ids);
171 $contribution->find(TRUE);
172 $objects['contribution'] = &$contribution;
173 }
174 try {
175 $success = $contribution->loadRelatedObjects($input, $ids);
176 if ($required && empty($contribution->_relatedObjects['paymentProcessor'])) {
177 throw new CRM_Core_Exception("Could not find payment processor for contribution record: " . $contribution->id);
178 }
179 }
180 catch (Exception $e) {
181 $success = FALSE;
182 if (!empty($error_handling['log_error'])) {
183 CRM_Core_Error::debug_log_message($e->getMessage());
184 }
185 if (!empty($error_handling['echo_error'])) {
186 echo $e->getMessage();
187 }
188 if (!empty($error_handling['return_error'])) {
189 return array(
190 'is_error' => 1,
191 'error_message' => ($e->getMessage()),
192 );
193 }
194 }
195 $objects = array_merge($objects, $contribution->_relatedObjects);
196 return $success;
197 }
198
199 /**
200 * Set contribution to failed.
201 *
202 * @param array $objects
203 * @param object $transaction
204 * @param array $input
205 *
206 * @return bool
207 */
208 public function failed(&$objects, &$transaction, $input = array()) {
209 $contribution = &$objects['contribution'];
210 $memberships = array();
211 if (!empty($objects['membership'])) {
212 $memberships = &$objects['membership'];
213 if (is_numeric($memberships)) {
214 $memberships = array($objects['membership']);
215 }
216 }
217
218 $addLineItems = FALSE;
219 if (empty($contribution->id)) {
220 $addLineItems = TRUE;
221 }
222 $participant = &$objects['participant'];
223
224 //CRM-15546
225 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
226 'labelColumn' => 'name',
227 'flip' => 1,
228 ));
229 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
230 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
231 $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
232 $contribution->contribution_status_id = $contributionStatuses['Failed'];
233 $contribution->save();
234
235 // Add line items for recurring payments.
236 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
237 CRM_Contribute_BAO_ContributionRecur::addRecurLineItems($objects['contributionRecur']->id, $contribution);
238 }
239
240 //add new soft credit against current contribution id and
241 //copy initial contribution custom fields for recurring contributions
242 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id) {
243 CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
244 CRM_Contribute_BAO_ContributionRecur::copyCustomValues($objects['contributionRecur']->id, $contribution->id);
245 }
246
247 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
248 if (!empty($memberships)) {
249 // if transaction is failed then set "Cancelled" as membership status
250 $membershipStatuses = CRM_Core_PseudoConstant::get('CRM_Member_DAO_Membership', 'status_id', array(
251 'labelColumn' => 'name',
252 'flip' => 1,
253 ));
254 foreach ($memberships as $membership) {
255 if ($membership) {
256 $membership->status_id = $membershipStatuses['Cancelled'];
257 $membership->save();
258
259 //update related Memberships.
260 $params = array('status_id' => $membershipStatuses['Cancelled']);
261 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
262 }
263 }
264 }
265
266 if ($participant) {
267 $participantStatuses = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'status_id', array(
268 'labelColumn' => 'name',
269 'flip' => 1,
270 ));
271 $participant->status_id = $participantStatuses['Cancelled'];
272 $participant->save();
273 }
274 }
275
276 $transaction->commit();
277 CRM_Core_Error::debug_log_message("Setting contribution status to failed");
278 //echo "Success: Setting contribution status to failed<p>";
279 return TRUE;
280 }
281
282 /**
283 * Handled pending contribution status.
284 *
285 * @param array $objects
286 * @param object $transaction
287 *
288 * @return bool
289 */
290 public function pending(&$objects, &$transaction) {
291 $transaction->commit();
292 CRM_Core_Error::debug_log_message("returning since contribution status is pending");
293 echo "Success: Returning since contribution status is pending<p>";
294 return TRUE;
295 }
296
297 /**
298 * Process cancelled payment outcome.
299 *
300 * @param $objects
301 * @param $transaction
302 * @param array $input
303 *
304 * @return bool
305 */
306 public function cancelled(&$objects, &$transaction, $input = array()) {
307 $contribution = &$objects['contribution'];
308 $memberships = &$objects['membership'];
309 if (is_numeric($memberships)) {
310 $memberships = array($objects['membership']);
311 }
312
313 $participant = &$objects['participant'];
314 $addLineItems = FALSE;
315 if (empty($contribution->id)) {
316 $addLineItems = TRUE;
317 }
318 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
319 'labelColumn' => 'name',
320 'flip' => 1,
321 ));
322 $contribution->contribution_status_id = $contributionStatuses['Cancelled'];
323 $contribution->cancel_date = self::$_now;
324 $contribution->cancel_reason = CRM_Utils_Array::value('reasonCode', $input);
325 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
326 $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
327 $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
328 $contribution->save();
329
330 //add lineitems for recurring payments
331 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id && $addLineItems) {
332 CRM_Contribute_BAO_ContributionRecur::addRecurLineItems($objects['contributionRecur']->id, $contribution);
333 }
334
335 //add new soft credit against current $contribution and
336 //copy initial contribution custom fields for recurring contributions
337 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id) {
338 CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
339 CRM_Contribute_BAO_ContributionRecur::copyCustomValues($objects['contributionRecur']->id, $contribution->id);
340 }
341
342 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
343 if (!empty($memberships)) {
344 $membershipStatuses = CRM_Core_PseudoConstant::get('CRM_Member_DAO_Membership', 'status_id', array(
345 'labelColumn' => 'name',
346 'flip' => 1,
347 ));
348 foreach ($memberships as $membership) {
349 if ($membership) {
350 $membership->status_id = $membershipStatuses['Cancelled'];
351 $membership->save();
352
353 //update related Memberships.
354 $params = array('status_id' => $membershipStatuses['Cancelled']);
355 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
356 }
357 }
358 }
359
360 if ($participant) {
361 $participantStatuses = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'status_id', array(
362 'labelColumn' => 'name',
363 'flip' => 1,
364 ));
365 $participant->status_id = $participantStatuses['Cancelled'];
366 $participant->save();
367 }
368 }
369 $transaction->commit();
370 CRM_Core_Error::debug_log_message("Setting contribution status to cancelled");
371 //echo "Success: Setting contribution status to cancelled<p>";
372 return TRUE;
373 }
374
375 /**
376 * Rollback unhandled outcomes.
377 *
378 * @param $objects
379 * @param $transaction
380 *
381 * @return bool
382 */
383 public function unhandled(&$objects, &$transaction) {
384 $transaction->rollback();
385 CRM_Core_Error::debug_log_message("returning since contribution status: is not handled");
386 echo "Failure: contribution status is not handled<p>";
387 return FALSE;
388 }
389
390 /**
391 * Jumbled up function.
392 *
393 * The purpose of this function is to transition a pending transaction to Completed including updating any
394 * related entities.
395 *
396 * It has been overloaded to also add recurring transactions to the database, cloning the original transaction and
397 * updating related entities.
398 *
399 * It is recommended to avoid calling this function directly and call the api functions:
400 * - contribution.completetransaction
401 * - contribution.repeattransaction
402 *
403 * These functions are the focus of testing efforts and more accurately reflect the division of roles
404 * (the job of the IPN class is to determine the outcome, transaction id, invoice id & to validate the source
405 * and from there it should be possible to pass off transaction management.)
406 *
407 * This function has been problematic for some time but there are now several tests via the api_v3_Contribution test
408 * and the Paypal & Authorize.net IPN tests so any refactoring should be done in conjunction with those.
409 *
410 * This function needs to have the 'body' moved to the CRM_Contribution_BAO_Contribute class and to undergo
411 * refactoring to separate the complete transaction and repeat transaction functionality into separate functions with
412 * a shared function that updates related components.
413 *
414 * Note that it is not necessary payment processor extension to implement an IPN class now. In general the code on the
415 * IPN class is better accessed through the api which de-jumbles it a bit.
416 *
417 * e.g the payment class can have a function like (based on Omnipay extension):
418 *
419 * public function handlePaymentNotification() {
420 * $response = $this->getValidatedOutcome();
421 * if ($response->isSuccessful()) {
422 * try {
423 * // @todo check if it is a repeat transaction & call repeattransaction instead.
424 * civicrm_api3('contribution', 'completetransaction', array('id' => $this->transaction_id));
425 * }
426 * catch (CiviCRM_API3_Exception $e) {
427 * if (!stristr($e->getMessage(), 'Contribution already completed')) {
428 * $this->handleError('error', $this->transaction_id . $e->getMessage(), 'ipn_completion', 9000, 'An error may
429 * have occurred. Please check your receipt is correct');
430 * $this->redirectOrExit('success');
431 * }
432 * elseif ($this->transaction_id) {
433 * civicrm_api3('contribution', 'create', array('id' => $this->transaction_id, 'contribution_status_id' =>
434 * 'Failed'));
435 * }
436 *
437 * @param array $input
438 * @param array $ids
439 * @param array $objects
440 * @param $transaction
441 * @param bool $recur
442 */
443 public function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) {
444 $isRecurring = $this->_isRecurring;
445 $isFirstOrLastRecurringPayment = $this->_isFirstOrLastRecurringPayment;
446 $contribution = &$objects['contribution'];
447
448 CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $objects, $transaction, $recur, $contribution,
449 $isRecurring, $isFirstOrLastRecurringPayment);
450 }
451
452 /**
453 * Get site billing ID.
454 *
455 * @param array $ids
456 *
457 * @return bool
458 */
459 public function getBillingID(&$ids) {
460 // get the billing location type
461 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
462 // CRM-8108 remove the ts around the Billing location type
463 //$ids['billing'] = array_search( ts('Billing'), $locationTypes );
464 $ids['billing'] = array_search('Billing', $locationTypes);
465 if (!$ids['billing']) {
466 CRM_Core_Error::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
467 echo "Failure: Could not find billing location type<p>";
468 return FALSE;
469 }
470 return TRUE;
471 }
472
473 /**
474 * Send receipt from contribution.
475 *
476 * @deprecated
477 *
478 * Note that the compose message part has been moved to contribution
479 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
480 *
481 * @param array $input
482 * Incoming data from Payment processor.
483 * @param array $ids
484 * Related object IDs.
485 * @param $objects
486 * @param array $values
487 * Values related to objects that have already been loaded.
488 * @param bool $recur
489 * Is it part of a recurring contribution.
490 * @param bool $returnMessageText
491 * Should text be returned instead of sent. This.
492 * is because the function is also used to generate pdfs
493 *
494 * @return array
495 */
496 public function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
497 return CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $objects['contribution'], $values, $recur,
498 $returnMessageText);
499 }
500
501}