3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
29 * Class CRM_Core_Payment_BaseIPN.
31 class CRM_Core_Payment_BaseIPN
{
36 * Input parameters from payment processor. Store these so that
37 * the code does not need to keep retrieving from the http request
40 protected $_inputParameters = array();
42 protected $_isRecurring = FALSE;
44 protected $_isFirstOrLastRecurringPayment = FALSE;
49 public function __construct() {
50 self
::$_now = date('YmdHis');
54 * Store input array on the class.
56 * @param array $parameters
58 * @throws CRM_Core_Exception
60 public function setInputParameters($parameters) {
61 if (!is_array($parameters)) {
62 throw new CRM_Core_Exception('Invalid input parameters');
64 $this->_inputParameters
= $parameters;
68 * Validate incoming data.
70 * This function is intended to ensure that incoming data matches
71 * It provides a form of pseudo-authentication - by checking the calling fn already knows
72 * the correct contact id & contribution id (this can be problematic when that has changed in
73 * the meantime for transactions that are delayed & contacts are merged in-between. e.g
74 * Paypal allows you to resend Instant Payment Notifications if you, for example, moved site
75 * and didn't update your IPN URL.
78 * Interpreted values from the values returned through the IPN.
80 * More interpreted values (ids) from the values returned through the IPN.
81 * @param array $objects
82 * An empty array that will be populated with loaded object.
83 * @param bool $required
84 * Boolean Return FALSE if the relevant objects don't exist.
85 * @param int $paymentProcessorID
86 * Id of the payment processor ID in use.
90 public function validateData(&$input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
92 // make sure contact exists and is valid
93 $contact = new CRM_Contact_BAO_Contact();
94 $contact->id
= $ids['contact'];
95 if (!$contact->find(TRUE)) {
96 CRM_Core_Error
::debug_log_message("Could not find contact record: {$ids['contact']} in IPN request: " . print_r($input, TRUE));
97 echo "Failure: Could not find contact record: {$ids['contact']}<p>";
101 // make sure contribution exists and is valid
102 $contribution = new CRM_Contribute_BAO_Contribution();
103 $contribution->id
= $ids['contribution'];
104 if (!$contribution->find(TRUE)) {
105 CRM_Core_Error
::debug_log_message("Could not find contribution record: {$contribution->id} in IPN request: " . print_r($input, TRUE));
106 echo "Failure: Could not find contribution record for {$contribution->id}<p>";
109 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
111 $objects['contact'] = &$contact;
112 $objects['contribution'] = &$contribution;
113 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
116 //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
117 //current contribution. Here we ensure that the original contribution is available to the complete transaction function
118 //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
119 if (isset($objects['contributionRecur'])) {
120 $objects['first_contribution'] = $objects['contribution'];
126 * Load objects related to contribution.
128 * @input array information from Payment processor
132 * @param array $objects
133 * @param bool $required
134 * @param int $paymentProcessorID
135 * @param array $error_handling
139 public function loadObjects(&$input, &$ids, &$objects, $required, $paymentProcessorID, $error_handling = NULL) {
140 if (empty($error_handling)) {
141 // default options are that we log an error & echo it out
142 // note that we should refactor this error handling into error code @ some point
143 // but for now setting up enough separation so we can do unit tests
144 $error_handling = array(
149 $ids['paymentProcessor'] = $paymentProcessorID;
150 if (is_a($objects['contribution'], 'CRM_Contribute_BAO_Contribution')) {
151 $contribution = &$objects['contribution'];
154 //legacy support - functions are 'used' to be able to pass in a DAO
155 $contribution = new CRM_Contribute_BAO_Contribution();
156 $contribution->id
= CRM_Utils_Array
::value('contribution', $ids);
157 $contribution->find(TRUE);
158 $objects['contribution'] = &$contribution;
161 $success = $contribution->loadRelatedObjects($input, $ids, $required);
163 catch (Exception
$e) {
165 if (!empty($error_handling['log_error'])) {
166 CRM_Core_Error
::debug_log_message($e->getMessage());
168 if (!empty($error_handling['echo_error'])) {
169 echo $e->getMessage();
171 if (!empty($error_handling['return_error'])) {
174 'error_message' => ($e->getMessage()),
178 $objects = array_merge($objects, $contribution->_relatedObjects
);
183 * Set contribution to failed.
185 * @param array $objects
186 * @param object $transaction
187 * @param array $input
191 public function failed(&$objects, &$transaction, $input = array()) {
192 $contribution = &$objects['contribution'];
193 $memberships = array();
194 if (!empty($objects['membership'])) {
195 $memberships = &$objects['membership'];
196 if (is_numeric($memberships)) {
197 $memberships = array($objects['membership']);
201 $addLineItems = FALSE;
202 if (empty($contribution->id
)) {
203 $addLineItems = TRUE;
205 $participant = &$objects['participant'];
208 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
209 'labelColumn' => 'name',
212 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
213 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
214 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
215 $contribution->contribution_status_id
= $contributionStatuses['Failed'];
216 $contribution->save();
218 // Add line items for recurring payments.
219 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
220 $this->addRecurLineItems($objects['contributionRecur']->id
, $contribution);
223 //add new soft credit against current contribution id and
224 //copy initial contribution custom fields for recurring contributions
225 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
226 $this->addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
227 $this->copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
230 if (empty($input['skipComponentSync'])) {
231 if (!empty($memberships)) {
232 // if transaction is failed then set "Cancelled" as membership status
233 $membershipStatuses = CRM_Core_PseudoConstant
::get('CRM_Member_DAO_Membership', 'status_id', array(
234 'labelColumn' => 'name',
237 foreach ($memberships as $membership) {
239 $membership->status_id
= $membershipStatuses['Cancelled'];
242 //update related Memberships.
243 $params = array('status_id' => $membershipStatuses['Cancelled']);
244 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
250 $participantStatuses = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'status_id', array(
251 'labelColumn' => 'name',
254 $participant->status_id
= $participantStatuses['Cancelled'];
255 $participant->save();
259 $transaction->commit();
260 CRM_Core_Error
::debug_log_message("Setting contribution status to failed");
261 //echo "Success: Setting contribution status to failed<p>";
266 * Handled pending contribution status.
268 * @param array $objects
269 * @param object $transaction
273 public function pending(&$objects, &$transaction) {
274 $transaction->commit();
275 CRM_Core_Error
::debug_log_message("returning since contribution status is pending");
276 echo "Success: Returning since contribution status is pending<p>";
281 * Process cancelled payment outcome.
284 * @param $transaction
285 * @param array $input
289 public function cancelled(&$objects, &$transaction, $input = array()) {
290 $contribution = &$objects['contribution'];
291 $memberships = &$objects['membership'];
292 if (is_numeric($memberships)) {
293 $memberships = array($objects['membership']);
296 $participant = &$objects['participant'];
297 $addLineItems = FALSE;
298 if (empty($contribution->id
)) {
299 $addLineItems = TRUE;
301 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
302 'labelColumn' => 'name',
305 $contribution->contribution_status_id
= $contributionStatuses['Cancelled'];
306 $contribution->cancel_date
= self
::$_now;
307 $contribution->cancel_reason
= CRM_Utils_Array
::value('reasonCode', $input);
308 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
309 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
310 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
311 $contribution->save();
313 //add lineitems for recurring payments
314 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
315 $this->addRecurLineItems($objects['contributionRecur']->id
, $contribution);
318 //add new soft credit against current $contribution and
319 //copy initial contribution custom fields for recurring contributions
320 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
321 $this->addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
322 $this->copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
325 if (empty($input['skipComponentSync'])) {
326 if (!empty($memberships)) {
327 $membershipStatuses = CRM_Core_PseudoConstant
::get('CRM_Member_DAO_Membership', 'status_id', array(
328 'labelColumn' => 'name',
331 foreach ($memberships as $membership) {
333 $membership->status_id
= $membershipStatuses['Cancelled'];
336 //update related Memberships.
337 $params = array('status_id' => $membershipStatuses['Cancelled']);
338 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
344 $participantStatuses = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'status_id', array(
345 'labelColumn' => 'name',
348 $participant->status_id
= $participantStatuses['Cancelled'];
349 $participant->save();
352 $transaction->commit();
353 CRM_Core_Error
::debug_log_message("Setting contribution status to cancelled");
354 //echo "Success: Setting contribution status to cancelled<p>";
359 * Rollback unhandled outcomes.
362 * @param $transaction
366 public function unhandled(&$objects, &$transaction) {
367 $transaction->rollback();
368 CRM_Core_Error
::debug_log_message("returning since contribution status: is not handled");
369 echo "Failure: contribution status is not handled<p>";
374 * Jumbled up function.
376 * The purpose of this function is to transition a pending transaction to Completed including updating any
379 * It has been overloaded to also add recurring transactions to the database, cloning the original transaction and
380 * updating related entities.
382 * It is recommended to avoid calling this function directly and call the api functions:
383 * - contribution.completetransaction
384 * - contribution.repeattransaction
386 * These functions are the focus of testing efforts and more accurately reflect the division of roles
387 * (the job of the IPN class is to determine the outcome, transaction id, invoice id & to validate the source
388 * and from there it should be possible to pass off transaction management.)
390 * This function has been problematic for some time but there are now several tests via the api_v3_Contribution test
391 * and the Paypal & Authorize.net IPN tests so any refactoring should be done in conjunction with those.
393 * This function needs to have the 'body' moved to the CRM_Contribution_BAO_Contribute class and to undergo
394 * refactoring to separate the complete transaction and repeat transaction functionality into separate functions with
395 * a shared function that updates related components.
397 * Note that it is not necessary payment processor extension to implement an IPN class now. In general the code on the
398 * IPN class is better accessed through the api which de-jumbles it a bit.
400 * e.g the payment class can have a function like (based on Omnipay extension):
402 * public function handlePaymentNotification() {
403 * $response = $this->getValidatedOutcome();
404 * if ($response->isSuccessful()) {
406 * // @todo check if it is a repeat transaction & call repeattransaction instead.
407 * civicrm_api3('contribution', 'completetransaction', array('id' => $this->transaction_id));
409 * catch (CiviCRM_API3_Exception $e) {
410 * if (!stristr($e->getMessage(), 'Contribution already completed')) {
411 * $this->handleError('error', $this->transaction_id . $e->getMessage(), 'ipn_completion', 9000, 'An error may
412 * have occurred. Please check your receipt is correct');
413 * $this->redirectOrExit('success');
415 * elseif ($this->transaction_id) {
416 * civicrm_api3('contribution', 'create', array('id' => $this->transaction_id, 'contribution_status_id' =>
420 * @param array $input
422 * @param array $objects
423 * @param $transaction
426 public function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) {
427 $contribution = &$objects['contribution'];
429 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
431 $memberships = &$objects['membership'];
432 if (is_numeric($memberships)) {
433 $memberships = array($objects['membership']);
435 $participant = &$objects['participant'];
437 $changeToday = CRM_Utils_Array
::value('trxn_date', $input, self
::$_now);
438 $recurContrib = &$objects['contributionRecur'];
441 if (isset($input['is_email_receipt'])) {
442 $values['is_email_receipt'] = $input['is_email_receipt'];
445 if ($input['component'] == 'contribute') {
446 if ($contribution->contribution_page_id
) {
447 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
448 $source = ts('Online Contribution') . ': ' . $values['title'];
450 elseif ($recurContrib && $recurContrib->id
) {
451 $contribution->contribution_page_id
= NULL;
452 $values['amount'] = $recurContrib->amount
;
453 $values['financial_type_id'] = $objects['contributionType']->id
;
454 $values['title'] = $source = ts('Offline Recurring Contribution');
455 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
456 $values['receipt_from_name'] = $domainValues[0];
457 $values['receipt_from_email'] = $domainValues[1];
460 if ($recurContrib && $recurContrib->id
&& !isset($input['is_email_receipt'])) {
461 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
462 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
463 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
466 $contribution->source
= $source;
467 if (!empty($values['is_email_receipt'])) {
468 $contribution->receipt_date
= self
::$_now;
471 if (!empty($memberships)) {
472 $membershipsUpdate = array();
473 foreach ($memberships as $membershipTypeIdKey => $membership) {
477 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
478 $membership->membership_type_id
,
479 $membership->is_test
, $membership->id
482 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
483 // this picks up membership type changes during renewals
485 SELECT membership_type_id
486 FROM civicrm_membership_log
487 WHERE membership_id=$membership->id
490 $dao = new CRM_Core_DAO();
493 if (!empty($dao->membership_type_id
)) {
494 $membership->membership_type_id
= $dao->membership_type_id
;
497 // else fall back to using current membership type
499 // else fall back to using current membership type
502 $num_terms = $contribution->getNumTermsByContributionAndMembershipType($membership->membership_type_id
, $primaryContributionID);
503 if ($currentMembership) {
506 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
507 * when Contribution mode is notify and membership is for renewal )
509 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
511 // @todo - we should pass membership_type_id instead of null here but not
512 // adding as not sure of testing
513 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
514 $changeToday, NULL, $num_terms
517 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
520 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $num_terms);
523 //get the status for membership.
524 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
529 $membership->membership_type_id
,
533 $formatedParams = array(
534 'status_id' => CRM_Utils_Array
::value('id', $calcStatus, 2),
535 'join_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('join_date', $dates), $format),
536 'start_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('start_date', $dates), $format),
537 'end_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('end_date', $dates), $format),
539 //we might be renewing membership,
540 //so make status override false.
541 $formatedParams['is_override'] = FALSE;
542 $membership->copyValues($formatedParams);
545 //updating the membership log
546 $membershipLog = array();
547 $membershipLog = $formatedParams;
549 $logStartDate = $formatedParams['start_date'];
550 if (!empty($dates['log_start_date'])) {
551 $logStartDate = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
552 $logStartDate = CRM_Utils_Date
::isoToMysql($logStartDate);
555 $membershipLog['start_date'] = $logStartDate;
556 $membershipLog['membership_id'] = $membership->id
;
557 $membershipLog['modified_id'] = $membership->contact_id
;
558 $membershipLog['modified_date'] = date('Ymd');
559 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
561 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
563 //update related Memberships.
564 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formatedParams);
566 //update the membership type key of membership relatedObjects array
567 //if it has changed after membership update
568 if ($membershipTypeIdKey != $membership->membership_type_id
) {
569 $membershipsUpdate[$membership->membership_type_id
] = $membership;
570 $contribution->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
571 unset($contribution->_relatedObjects
['membership'][$membershipTypeIdKey]);
572 unset($memberships[$membershipTypeIdKey]);
576 //update the memberships object with updated membershipTypeId data
577 //if membershipTypeId has changed after membership update
578 if (!empty($membershipsUpdate)) {
579 $memberships = $memberships +
$membershipsUpdate;
585 $eventParams = array('id' => $objects['event']->id
);
586 $values['event'] = array();
588 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
590 //get location details
591 $locationParams = array('entity_id' => $objects['event']->id
, 'entity_table' => 'civicrm_event');
592 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
594 $ufJoinParams = array(
595 'entity_table' => 'civicrm_event',
596 'entity_id' => $ids['event'],
597 'module' => 'CiviEvent',
602 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
604 $values['custom_pre_id'] = $custom_pre_id;
605 $values['custom_post_id'] = $custom_post_ids;
606 //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
607 //and cases involving status updation through ipn
608 $values['totalAmount'] = $input['amount'];
610 $contribution->source
= ts('Online Event Registration') . ': ' . $values['event']['title'];
612 if ($values['event']['is_email_confirm']) {
613 $contribution->receipt_date
= self
::$_now;
614 $values['is_email_receipt'] = 1;
616 if (empty($input['skipComponentSync'])) {
617 $participantStatuses = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'status_id', array(
618 'labelColumn' => 'name',
621 $participant->status_id
= $participantStatuses['Registered'];
623 $participant->save();
626 if (CRM_Utils_Array
::value('net_amount', $input, 0) == 0 &&
627 CRM_Utils_Array
::value('fee_amount', $input, 0) != 0
629 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
631 // This complete transaction function is being overloaded to create new contributions too.
632 // here we record if it is a new contribution.
633 // @todo separate the 2 more appropriately.
634 $isNewContribution = FALSE;
635 if (empty($contribution->id
)) {
636 $isNewContribution = TRUE;
637 if (!empty($input['amount']) && $input['amount'] != $contribution->total_amount
) {
638 $contribution->total_amount
= $input['amount'];
639 // The BAO does this stuff but we are actually kinda bypassing it here (bad code! go sit in the corner)
640 // so we have to handle net_amount in this (naughty) code.
641 if (isset($input['fee_amount']) && is_numeric($input['fee_amount'])) {
642 $contribution->fee_amount
= $input['fee_amount'];
644 $contribution->net_amount
= $contribution->total_amount
- $contribution->fee_amount
;
646 if (!empty($input['campaign_id'])) {
647 $contribution->campaign_id
= $input['campaign_id'];
651 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
652 'labelColumn' => 'name',
656 // @todo this section should call the api in order to have hooks called &
657 // because all this 'messiness' setting variables could be avoided
658 // by letting the api resolve pseudoconstants & copy set values and format dates.
659 $contribution->contribution_status_id
= $contributionStatuses['Completed'];
660 $contribution->is_test
= $input['is_test'];
662 // CRM-15960 If we don't have a value we 'want' for the amounts, leave it to the BAO to sort out.
663 if (isset($input['net_amount'])) {
664 $contribution->fee_amount
= CRM_Utils_Array
::value('fee_amount', $input, 0);
666 if (isset($input['net_amount'])) {
667 $contribution->net_amount
= $input['net_amount'];
670 $contribution->trxn_id
= $input['trxn_id'];
671 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
672 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
673 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
674 $contribution->cancel_date
= 'null';
676 if (!empty($input['check_number'])) {
677 $contribution->check_number
= $input['check_number'];
680 if (!empty($input['payment_instrument_id'])) {
681 $contribution->payment_instrument_id
= $input['payment_instrument_id'];
684 if (!empty($contribution->id
)) {
685 $contributionId['id'] = $contribution->id
;
686 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues($contributionId, CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
689 $contribution->save();
691 // Add new soft credit against current $contribution.
692 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
693 $this->addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
696 //add line items for recurring payments
697 if (!empty($contribution->contribution_recur_id
)) {
698 if ($isNewContribution) {
699 $input['line_item'] = $this->addRecurLineItems($contribution->contribution_recur_id
, $contribution);
702 // this is just to prevent e-notices when we call recordFinancialAccounts - per comments on that line - intention is somewhat unclear
703 $input['line_item'] = array();
707 //copy initial contribution custom fields for recurring contributions
708 if ($recurContrib && $recurContrib->id
) {
709 $this->copyCustomValues($recurContrib->id
, $contribution->id
);
712 $paymentProcessorId = '';
713 if (isset($objects['paymentProcessor'])) {
714 if (is_array($objects['paymentProcessor'])) {
715 $paymentProcessorId = $objects['paymentProcessor']['id'];
718 $paymentProcessorId = $objects['paymentProcessor']->id
;
721 //it's hard to see how it could reach this point without a contributon id as it is saved in line 511 above
722 // which raised the question as to whether this check preceded line 511 & if so whether something could be broken
723 // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code
724 // it would be good if someone added some comments or refactored this
725 if ($contribution->id
) {
726 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
727 'labelColumn' => 'name',
730 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
731 $input['payment_processor'] = $paymentProcessorId;
733 $input['contribution_status_id'] = $contributionStatuses['Completed'];
734 $input['total_amount'] = $input['amount'];
735 $input['contribution'] = $contribution;
736 $input['financial_type_id'] = $contribution->financial_type_id
;
738 if (!empty($contribution->_relatedObjects
['participant'])) {
739 $input['contribution_mode'] = 'participant';
740 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
741 $input['skipLineItem'] = 1;
743 elseif (!empty($contribution->_relatedObjects
['membership'])) {
744 $input['skipLineItem'] = TRUE;
745 $input['contribution_mode'] = 'membership';
747 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
748 // and subsequent payments. In this case the line items are created at $this->addRecurLineItems
749 // and since the contribution is saved prior to this line there is always a contribution-id,
750 // however there is never a prevContribution (which appears to mean original contribution not previous
751 // contribution - or preUpdateContributionObject most accurately)
752 // so, this is always called & only appears to succeed when prevContribution exists - which appears
753 // to mean "are we updating an exisitng pending contribution"
754 //I was able to make the unit test complete as fataling here doesn't prevent
755 // the contribution being created - but activities would not be created or emails sent
757 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
760 self
::updateRecurLinkedPledge($contribution);
762 // create an activity record
763 if ($input['component'] == 'contribute') {
765 $targetContactID = NULL;
766 if (!empty($ids['related_contact'])) {
767 $targetContactID = $contribution->contact_id
;
768 $contribution->contact_id
= $ids['related_contact'];
770 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
774 CRM_Activity_BAO_Activity
::addActivity($participant);
777 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
778 $transaction->commit();
780 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
781 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
782 if (!array_key_exists('is_email_receipt', $values) ||
783 $values['is_email_receipt'] == 1
785 self
::sendMail($input, $ids, $objects, $values, $recur, FALSE);
786 CRM_Core_Error
::debug_log_message("Receipt sent");
789 CRM_Core_Error
::debug_log_message("Success: Database updated");
790 if ($this->_isRecurring
) {
791 $this->sendRecurringStartOrEndNotification($ids, $recur);
796 * Get site billing ID.
802 public function getBillingID(&$ids) {
803 // get the billing location type
804 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
805 // CRM-8108 remove the ts around the Billing location type
806 //$ids['billing'] = array_search( ts('Billing'), $locationTypes );
807 $ids['billing'] = array_search('Billing', $locationTypes);
808 if (!$ids['billing']) {
809 CRM_Core_Error
::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
810 echo "Failure: Could not find billing location type<p>";
817 * Send receipt from contribution.
819 * Note that the compose message part has been moved to contribution
820 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
822 * @param array $input
823 * Incoming data from Payment processor.
825 * Related object IDs.
827 * @param array $values
828 * Values related to objects that have already been loaded.
830 * Is it part of a recurring contribution.
831 * @param bool $returnMessageText
832 * Should text be returned instead of sent. This.
833 * is because the function is also used to generate pdfs
837 public function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
838 $contribution = &$objects['contribution'];
839 $input['is_recur'] = $recur;
840 // set receipt from e-mail and name in value
841 if (!$returnMessageText) {
842 $session = CRM_Core_Session
::singleton();
843 $userID = $session->get('userID');
844 if (!empty($userID)) {
845 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
846 $values['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $input, $userEmail);
847 $values['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $input, $userName);
850 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
854 * Send start or end notification for recurring payments.
859 public function sendRecurringStartOrEndNotification($ids, $recur) {
860 if ($this->_isFirstOrLastRecurringPayment
) {
861 $autoRenewMembership = FALSE;
863 isset($ids['membership']) && $ids['membership']
865 $autoRenewMembership = TRUE;
868 //send recurring Notification email for user
869 CRM_Contribute_BAO_ContributionPage
::recurringNotify($this->_isFirstOrLastRecurringPayment
,
871 $ids['contributionPage'],
879 * Update contribution status.
882 * This is only called from one place in the code &
883 * it is unclear whether it is a function on the way in or on the way out
885 * @param array $params
887 * @return void|NULL|int
889 public function updateContributionStatus(&$params) {
890 // get minimum required values.
891 $statusId = CRM_Utils_Array
::value('contribution_status_id', $params);
892 $componentId = CRM_Utils_Array
::value('component_id', $params);
893 $componentName = CRM_Utils_Array
::value('componentName', $params);
894 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
896 if (!$contributionId ||
!$componentId ||
!$componentName ||
!$statusId) {
900 $input = $ids = $objects = array();
902 //get the required ids.
903 $ids['contribution'] = $contributionId;
905 if (!$ids['contact'] = CRM_Utils_Array
::value('contact_id', $params)) {
906 $ids['contact'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
912 if ($componentName == 'Event') {
914 $ids['participant'] = $componentId;
916 if (!$ids['event'] = CRM_Utils_Array
::value('event_id', $params)) {
917 $ids['event'] = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
924 if ($componentName == 'Membership') {
925 $name = 'contribute';
926 $ids['membership'] = $componentId;
928 $ids['contributionPage'] = NULL;
929 $ids['contributionRecur'] = NULL;
930 $input['component'] = $name;
932 $baseIPN = new CRM_Core_Payment_BaseIPN();
933 $transaction = new CRM_Core_Transaction();
935 // reset template values.
936 $template = CRM_Core_Smarty
::singleton();
937 $template->clearTemplateVars();
939 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
940 CRM_Core_Error
::fatal();
943 $contribution = &$objects['contribution'];
945 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
946 'labelColumn' => 'name',
949 $input['skipComponentSync'] = CRM_Utils_Array
::value('skipComponentSync', $params);
950 if ($statusId == $contributionStatuses['Cancelled']) {
951 $baseIPN->cancelled($objects, $transaction, $input);
952 $transaction->commit();
955 elseif ($statusId == $contributionStatuses['Failed']) {
956 $baseIPN->failed($objects, $transaction, $input);
957 $transaction->commit();
961 // status is not pending
962 if ($contribution->contribution_status_id
!= $contributionStatuses['Pending']) {
963 $transaction->commit();
967 //set values for ipn code.
971 'payment_instrument_id',
973 if (!$input[$field] = CRM_Utils_Array
::value($field, $params)) {
974 $input[$field] = $contribution->$field;
977 if (!$input['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $params)) {
978 $input['trxn_id'] = $contribution->invoice_id
;
980 if (!$input['amount'] = CRM_Utils_Array
::value('total_amount', $params)) {
981 $input['amount'] = $contribution->total_amount
;
983 $input['is_test'] = $contribution->is_test
;
984 $input['net_amount'] = $contribution->net_amount
;
985 if (!empty($input['fee_amount']) && !empty($input['amount'])) {
986 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
989 //complete the contribution.
990 $baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
992 // reset template values before processing next transactions
993 $template->clearTemplateVars();
999 * Update pledge associated with a recurring contribution.
1001 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
1003 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
1004 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
1005 * it should be assumed they
1006 * do so with the intention that all payments will be linked
1008 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
1009 * If not the contribution will also need to be linked to the pledge
1011 * @param CRM_Contribute_BAO_Contribution $contribution
1013 public function updateRecurLinkedPledge(&$contribution) {
1014 $returnProperties = array('id', 'pledge_id');
1015 $paymentDetails = $paymentIDs = array();
1017 if (CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id
,
1018 $paymentDetails, $returnProperties
1021 foreach ($paymentDetails as $key => $value) {
1022 $paymentIDs[] = $value['id'];
1023 $pledgeId = $value['pledge_id'];
1027 //payment is not already linked - if it is linked with a pledge we need to create a link.
1028 // return if it is not recurring contribution
1029 if (!$contribution->contribution_recur_id
) {
1033 $relatedContributions = new CRM_Contribute_DAO_Contribution();
1034 $relatedContributions->contribution_recur_id
= $contribution->contribution_recur_id
;
1035 $relatedContributions->find();
1037 while ($relatedContributions->fetch()) {
1038 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id
,
1039 $paymentDetails, $returnProperties
1043 if (empty($paymentDetails)) {
1044 // payment is not linked with a pledge and neither are any other contributions on this
1048 foreach ($paymentDetails as $key => $value) {
1049 $pledgeId = $value['pledge_id'];
1052 // we have a pledge now we need to get the oldest unpaid payment
1053 $paymentDetails = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeId);
1054 if (empty($paymentDetails['id'])) {
1055 // we can assume this pledge is now completed
1056 // return now so we don't create a core error & roll back
1059 $paymentDetails['contribution_id'] = $contribution->id
;
1060 $paymentDetails['status_id'] = $contribution->contribution_status_id
;
1061 $paymentDetails['actual_amount'] = $contribution->total_amount
;
1063 // put contribution against it
1064 $payment = CRM_Pledge_BAO_PledgePayment
::add($paymentDetails);
1065 $paymentIDs[] = $payment->id
;
1068 // update pledge and corresponding payment statuses
1069 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id
,
1070 NULL, $contribution->total_amount
1075 * Add line items for recurring contribution.
1077 * @param int $recurId
1078 * @param $contribution
1082 public function addRecurLineItems($recurId, $contribution) {
1083 $lineSets = array();
1085 $originalContributionID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
1086 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($originalContributionID);
1087 if (count($lineItems) == 1) {
1088 foreach ($lineItems as $index => $lineItem) {
1089 if ($lineItem['line_total'] != $contribution->total_amount
) {
1090 // We are dealing with a changed amount! Per CRM-16397 we can work out what to do with these
1091 // if there is only one line item, and the UI should prevent this situation for those with more than one.
1092 $lineItems[$index]['line_total'] = $contribution->total_amount
;
1093 $lineItems[$index]['unit_price'] = round($contribution->total_amount
/ $lineItems[$index]['qty'], 2);
1097 if (!empty($lineItems)) {
1098 foreach ($lineItems as $key => $value) {
1099 $priceField = new CRM_Price_DAO_PriceField();
1100 $priceField->id
= $value['price_field_id'];
1101 $priceField->find(TRUE);
1102 $lineSets[$priceField->price_set_id
][] = $value;
1104 if ($value['entity_table'] == 'civicrm_membership') {
1106 civicrm_api3('membership_payment', 'create', array(
1107 'membership_id' => $value['entity_id'],
1108 'contribution_id' => $contribution->id
,
1111 catch (CiviCRM_API3_Exception
$e) {
1112 // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
1113 // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
1119 CRM_Price_BAO_LineItem
::processPriceSet($contribution->id
, $lineSets, $contribution);
1125 * Copy custom data of the initial contribution into its recurring contributions.
1127 * @param int $recurId
1128 * @param int $targetContributionId
1130 public function copyCustomValues($recurId, $targetContributionId) {
1131 if ($recurId && $targetContributionId) {
1132 // get the initial contribution id of recur id
1133 $sourceContributionId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
1135 // if the same contribution is being proccessed then return
1136 if ($sourceContributionId == $targetContributionId) {
1139 // check if proper recurring contribution record is being processed
1140 $targetConRecurId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
1141 if ($targetConRecurId != $recurId) {
1146 $extends = array('Contribution');
1147 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
1149 foreach ($groupTree as $groupID => $group) {
1150 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
1151 foreach ($group['fields'] as $fieldID => $field) {
1152 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
1156 foreach ($table as $tableName => $tableColumns) {
1157 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
1158 $tableColumns[0] = $targetContributionId;
1159 $select = 'SELECT ' . implode(', ', $tableColumns);
1160 $from = ' FROM ' . $tableName;
1161 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
1162 $query = $insert . $select . $from . $where;
1163 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1170 * Add soft credit to for recurring payment.
1172 * copy soft credit record of first recurring contribution.
1173 * and add new soft credit against $targetContributionId
1175 * @param int $recurId
1176 * @param int $targetContributionId
1178 public function addrecurSoftCredit($recurId, $targetContributionId) {
1179 $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
1180 $soft_contribution->contribution_id
= CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
1182 // Check if first recurring contribution has any associated soft credit.
1183 if ($soft_contribution->find(TRUE)) {
1184 $soft_contribution->contribution_id
= $targetContributionId;
1185 unset($soft_contribution->id
);
1186 $soft_contribution->save();