3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Core_Payment_BaseIPN
{
40 * Input parameters from payment processor. Store these so that
41 * the code does not need to keep retrieving from the http request
44 protected $_inputParameters = array();
46 protected $_isRecurring = FALSE;
48 protected $_isFirstOrLastRecurringPayment = FALSE;
53 public function __construct() {
54 self
::$_now = date('YmdHis');
58 * Store input array on the class
60 * @param array $parameters
62 * @throws CRM_Core_Exception
64 public function setInputParameters($parameters) {
65 if (!is_array($parameters)) {
66 throw new CRM_Core_Exception('Invalid input parameters');
68 $this->_inputParameters
= $parameters;
72 * Validate incoming data. This function is intended to ensure that incoming data matches
73 * It provides a form of pseudo-authentication - by checking the calling fn already knows
74 * the correct contact id & contribution id (this can be problematic when that has changed in
75 * the meantime for transactions that are delayed & contacts are merged in-between. e.g
76 * Paypal allows you to resend Instant Payment Notifications if you, for example, moved site
77 * and didn't update your IPN URL.
80 * Interpreted values from the values returned through the IPN.
82 * More interpreted values (ids) from the values returned through the IPN.
83 * @param array $objects
84 * An empty array that will be populated with loaded object.
85 * @param bool $required
86 * Boolean Return FALSE if the relevant objects don't exist.
87 * @param int $paymentProcessorID
88 * Id of the payment processor ID in use.
91 public function validateData(&$input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
93 // make sure contact exists and is valid
94 $contact = new CRM_Contact_BAO_Contact();
95 $contact->id
= $ids['contact'];
96 if (!$contact->find(TRUE)) {
97 CRM_Core_Error
::debug_log_message("Could not find contact record: {$ids['contact']} in IPN request: " . print_r($input, TRUE));
98 echo "Failure: Could not find contact record: {$ids['contact']}<p>";
102 // make sure contribution exists and is valid
103 $contribution = new CRM_Contribute_BAO_Contribution();
104 $contribution->id
= $ids['contribution'];
105 if (!$contribution->find(TRUE)) {
106 CRM_Core_Error
::debug_log_message("Could not find contribution record: {$contribution->id} in IPN request: " . print_r($input, TRUE));
107 echo "Failure: Could not find contribution record for {$contribution->id}<p>";
110 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
112 $objects['contact'] = &$contact;
113 $objects['contribution'] = &$contribution;
114 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
117 //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
118 //current contribution. Here we ensure that the original contribution is available to the complete transaction function
119 //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
120 if (isset($objects['contributionRecur'])) {
121 $objects['first_contribution'] = $objects['contribution'];
127 * Load objects related to contribution
129 * @input array information from Payment processor
133 * @param array $objects
134 * @param bool $required
135 * @param int $paymentProcessorID
136 * @param array $error_handling
140 public function loadObjects(&$input, &$ids, &$objects, $required, $paymentProcessorID, $error_handling = NULL) {
141 if (empty($error_handling)) {
142 // default options are that we log an error & echo it out
143 // note that we should refactor this error handling into error code @ some point
144 // but for now setting up enough separation so we can do unit tests
145 $error_handling = array(
150 $ids['paymentProcessor'] = $paymentProcessorID;
151 if (is_a($objects['contribution'], 'CRM_Contribute_BAO_Contribution')) {
152 $contribution = &$objects['contribution'];
155 //legacy support - functions are 'used' to be able to pass in a DAO
156 $contribution = new CRM_Contribute_BAO_Contribution();
157 $contribution->id
= CRM_Utils_Array
::value('contribution', $ids);
158 $contribution->find(TRUE);
159 $objects['contribution'] = &$contribution;
162 $success = $contribution->loadRelatedObjects($input, $ids, $required);
164 catch (Exception
$e) {
166 if (!empty($error_handling['log_error'])) {
167 CRM_Core_Error
::debug_log_message($e->getMessage());
169 if (!empty($error_handling['echo_error'])) {
170 echo($e->getMessage());
172 if (!empty($error_handling['return_error'])) {
175 'error_message' => ($e->getMessage()),
179 $objects = array_merge($objects, $contribution->_relatedObjects
);
184 * Set contribution to failed
185 * @param array $objects
186 * @param object $transaction
187 * @param array $input
190 public function failed(&$objects, &$transaction, $input = array()) {
191 $contribution = &$objects['contribution'];
192 $memberships = array();
193 if (!empty($objects['membership'])) {
194 $memberships = &$objects['membership'];
195 if (is_numeric($memberships)) {
196 $memberships = array($objects['membership']);
200 $addLineItems = FALSE;
201 if (empty($contribution->id
)) {
202 $addLineItems = TRUE;
204 $participant = &$objects['participant'];
207 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
208 'labelColumn' => 'name',
211 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
212 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
213 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
214 $contribution->contribution_status_id
= $contributionStatuses['Failed'];
215 $contribution->save();
217 //add lineitems for recurring payments
218 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
219 $this->addRecurLineItems($objects['contributionRecur']->id
, $contribution);
222 //add new soft credit against current contribution id and
223 //copy initial contribution custom fields for recurring contributions
224 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
225 $this->addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
226 $this->copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
229 if (empty($input['skipComponentSync'])) {
230 if (!empty($memberships)) {
231 // if transaction is failed then set "Cancelled" as membership status
232 $membershipStatuses = CRM_Core_PseudoConstant
::get('CRM_Member_DAO_Membership', 'status_id', array(
233 'labelColumn' => 'name',
236 foreach ($memberships as $membership) {
238 $membership->status_id
= $membershipStatuses['Cancelled'];
241 //update related Memberships.
242 $params = array('status_id' => $membershipStatuses['Cancelled']);
243 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
249 $participantStatuses = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'status_id', array(
250 'labelColumn' => 'name',
253 $participant->status_id
= $participantStatuses['Cancelled'];
254 $participant->save();
258 $transaction->commit();
259 CRM_Core_Error
::debug_log_message("Setting contribution status to failed");
260 //echo "Success: Setting contribution status to failed<p>";
265 * Handled pending contribution status
266 * @param array $objects
267 * @param object $transaction
270 public function pending(&$objects, &$transaction) {
271 $transaction->commit();
272 CRM_Core_Error
::debug_log_message("returning since contribution status is pending");
273 echo "Success: Returning since contribution status is pending<p>";
279 * @param $transaction
280 * @param array $input
284 public function cancelled(&$objects, &$transaction, $input = array()) {
285 $contribution = &$objects['contribution'];
286 $memberships = &$objects['membership'];
287 if (is_numeric($memberships)) {
288 $memberships = array($objects['membership']);
291 $participant = &$objects['participant'];
292 $addLineItems = FALSE;
293 if (empty($contribution->id
)) {
294 $addLineItems = TRUE;
296 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
297 'labelColumn' => 'name',
300 $contribution->contribution_status_id
= $contributionStatuses['Cancelled'];
301 $contribution->cancel_date
= self
::$_now;
302 $contribution->cancel_reason
= CRM_Utils_Array
::value('reasonCode', $input);
303 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
304 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
305 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
306 $contribution->save();
308 //add lineitems for recurring payments
309 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
310 $this->addRecurLineItems($objects['contributionRecur']->id
, $contribution);
313 //add new soft credit against current $contribution and
314 //copy initial contribution custom fields for recurring contributions
315 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
316 $this->addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
317 $this->copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
320 if (empty($input['skipComponentSync'])) {
321 if (!empty($memberships)) {
322 $membershipStatuses = CRM_Core_PseudoConstant
::get('CRM_Member_DAO_Membership', 'status_id', array(
323 'labelColumn' => 'name',
326 foreach ($memberships as $membership) {
328 $membership->status_id
= $membershipStatuses['Cancelled'];
331 //update related Memberships.
332 $params = array('status_id' => $membershipStatuses['Cancelled']);
333 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
339 $participantStatuses = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'status_id', array(
340 'labelColumn' => 'name',
343 $participant->status_id
= $participantStatuses['Cancelled'];
344 $participant->save();
347 $transaction->commit();
348 CRM_Core_Error
::debug_log_message("Setting contribution status to cancelled");
349 //echo "Success: Setting contribution status to cancelled<p>";
355 * @param $transaction
359 public function unhandled(&$objects, &$transaction) {
360 $transaction->rollback();
361 CRM_Core_Error
::debug_log_message("returning since contribution status: is not handled");
362 echo "Failure: contribution status is not handled<p>";
370 * @param $transaction
373 public function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) {
374 $contribution = &$objects['contribution'];
376 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
378 $memberships = &$objects['membership'];
379 if (is_numeric($memberships)) {
380 $memberships = array($objects['membership']);
382 $participant = &$objects['participant'];
383 $event = &$objects['event'];
384 $changeToday = CRM_Utils_Array
::value('trxn_date', $input, self
::$_now);
385 $recurContrib = &$objects['contributionRecur'];
389 if ($input['component'] == 'contribute') {
390 if ($contribution->contribution_page_id
) {
391 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
392 $source = ts('Online Contribution') . ': ' . $values['title'];
394 elseif ($recurContrib && $recurContrib->id
) {
395 $contribution->contribution_page_id
= NULL;
396 $values['amount'] = $recurContrib->amount
;
397 $values['financial_type_id'] = $objects['contributionType']->id
;
398 $values['title'] = $source = ts('Offline Recurring Contribution');
399 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
400 $values['receipt_from_name'] = $domainValues[0];
401 $values['receipt_from_email'] = $domainValues[1];
403 if ($recurContrib && $recurContrib->id
) {
404 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
405 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
408 $contribution->source
= $source;
409 if (!empty($values['is_email_receipt'])) {
410 $contribution->receipt_date
= self
::$_now;
413 if (!empty($memberships)) {
414 $membershipsUpdate = array();
415 foreach ($memberships as $membershipTypeIdKey => $membership) {
419 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
420 $membership->membership_type_id
,
421 $membership->is_test
, $membership->id
424 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
425 // this picks up membership type changes during renewals
427 SELECT membership_type_id
428 FROM civicrm_membership_log
429 WHERE membership_id=$membership->id
432 $dao = new CRM_Core_DAO
;
435 if (!empty($dao->membership_type_id
)) {
436 $membership->membership_type_id
= $dao->membership_type_id
;
439 // else fall back to using current membership type
441 // else fall back to using current membership type
444 $num_terms = $contribution->getNumTermsByContributionAndMembershipType($membership->membership_type_id
, $primaryContributionID);
445 if ($currentMembership) {
448 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
449 * when Contribution mode is notify and membership is for renewal )
451 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
453 // @todo - we should pass membership_type_id instead of null here but not
454 // adding as not sure of testing
455 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
456 $changeToday, NULL, $num_terms
459 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
462 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $num_terms);
465 //get the status for membership.
466 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
471 $membership->membership_type_id
,
475 $formatedParams = array(
476 'status_id' => CRM_Utils_Array
::value('id', $calcStatus, 2),
477 'join_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('join_date', $dates), $format),
478 'start_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('start_date', $dates), $format),
479 'end_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('end_date', $dates), $format),
481 //we might be renewing membership,
482 //so make status override false.
483 $formatedParams['is_override'] = FALSE;
484 $membership->copyValues($formatedParams);
487 //updating the membership log
488 $membershipLog = array();
489 $membershipLog = $formatedParams;
491 $logStartDate = $formatedParams['start_date'];
492 if (!empty($dates['log_start_date'])) {
493 $logStartDate = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
494 $logStartDate = CRM_Utils_Date
::isoToMysql($logStartDate);
497 $membershipLog['start_date'] = $logStartDate;
498 $membershipLog['membership_id'] = $membership->id
;
499 $membershipLog['modified_id'] = $membership->contact_id
;
500 $membershipLog['modified_date'] = date('Ymd');
501 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
503 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
505 //update related Memberships.
506 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formatedParams);
508 //update the membership type key of membership relatedObjects array
509 //if it has changed after membership update
510 if ($membershipTypeIdKey != $membership->membership_type_id
) {
511 $membershipsUpdate[$membership->membership_type_id
] = $membership;
512 $contribution->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
513 unset($contribution->_relatedObjects
['membership'][$membershipTypeIdKey]);
514 unset($memberships[$membershipTypeIdKey]);
518 //update the memberships object with updated membershipTypeId data
519 //if membershipTypeId has changed after membership update
520 if (!empty($membershipsUpdate)) {
521 $memberships = $memberships +
$membershipsUpdate;
527 $eventParams = array('id' => $objects['event']->id
);
528 $values['event'] = array();
530 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
532 //get location details
533 $locationParams = array('entity_id' => $objects['event']->id
, 'entity_table' => 'civicrm_event');
534 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
536 $ufJoinParams = array(
537 'entity_table' => 'civicrm_event',
538 'entity_id' => $ids['event'],
539 'module' => 'CiviEvent',
544 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
546 $values['custom_pre_id'] = $custom_pre_id;
547 $values['custom_post_id'] = $custom_post_ids;
548 //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
549 //and cases involving status updation through ipn
550 $values['totalAmount'] = $input['amount'];
552 $contribution->source
= ts('Online Event Registration') . ': ' . $values['event']['title'];
554 if ($values['event']['is_email_confirm']) {
555 $contribution->receipt_date
= self
::$_now;
556 $values['is_email_receipt'] = 1;
558 if (empty($input['skipComponentSync'])) {
559 $participantStatuses = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'status_id', array(
560 'labelColumn' => 'name',
563 $participant->status_id
= $participantStatuses['Registered'];
565 $participant->save();
568 if (CRM_Utils_Array
::value('net_amount', $input, 0) == 0 &&
569 CRM_Utils_Array
::value('fee_amount', $input, 0) != 0
571 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
573 $addLineItems = FALSE;
574 if (empty($contribution->id
)) {
575 $addLineItems = TRUE;
577 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
578 'labelColumn' => 'name',
581 $contribution->contribution_status_id
= $contributionStatuses['Completed'];
582 $contribution->is_test
= $input['is_test'];
583 $contribution->fee_amount
= CRM_Utils_Array
::value('fee_amount', $input, 0);
584 $contribution->net_amount
= CRM_Utils_Array
::value('net_amount', $input, 0);
585 $contribution->trxn_id
= $input['trxn_id'];
586 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
587 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
588 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
589 $contribution->cancel_date
= 'null';
591 if (!empty($input['check_number'])) {
592 $contribution->check_number
= $input['check_number'];
595 if (!empty($input['payment_instrument_id'])) {
596 $contribution->payment_instrument_id
= $input['payment_instrument_id'];
599 if ($contribution->id
) {
600 $contributionId['id'] = $contribution->id
;
601 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues($contributionId, CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
603 $contribution->save();
605 //add new soft credit against current $contribution and
606 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
607 $this->addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
610 //add lineitems for recurring payments
611 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
613 $input['line_item'] = $this->addRecurLineItems($objects['contributionRecur']->id
, $contribution);
616 // this is just to prevent e-notices when we call recordFinancialAccounts - per comments on that line - intention is somewhat unclear
617 $input['line_item'] = array();
621 //copy initial contribution custom fields for recurring contributions
622 if ($recurContrib && $recurContrib->id
) {
623 $this->copyCustomValues($recurContrib->id
, $contribution->id
);
626 // next create the transaction record
627 $paymentProcessor = $paymentProcessorId = '';
628 if (isset($objects['paymentProcessor'])) {
629 if (is_array($objects['paymentProcessor'])) {
630 $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
631 $paymentProcessorId = $objects['paymentProcessor']['id'];
634 $paymentProcessor = $objects['paymentProcessor']->payment_processor_type
;
635 $paymentProcessorId = $objects['paymentProcessor']->id
;
638 //it's hard to see how it could reach this point without a contributon id as it is saved in line 511 above
639 // which raised the question as to whether this check preceded line 511 & if so whether something could be broken
640 // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code
641 // it would be good if someone added some comments or refactored this
642 if ($contribution->id
) {
643 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
644 'labelColumn' => 'name',
647 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&& -$input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
648 $input['payment_processor'] = $paymentProcessorId;
650 $input['contribution_status_id'] = $contributionStatuses['Completed'];
651 $input['total_amount'] = $input['amount'];
652 $input['contribution'] = $contribution;
653 $input['financial_type_id'] = $contribution->financial_type_id
;
655 if (!empty($contribution->_relatedObjects
['participant'])) {
656 $input['contribution_mode'] = 'participant';
657 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
658 $input['skipLineItem'] = 1;
660 elseif (!empty($contribution->_relatedObjects
['membership'])) {
661 $input['skipLineItem'] = TRUE;
662 $input['contribution_mode'] = 'membership';
664 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
665 // and subsequent payments. In this case the line items are created at $this->addRecurLineItems
666 // and since the contribution is saved prior to this line there is always a contribution-id,
667 // however there is never a prevContribution (which appears to mean original contribution not previous
668 // contribution - or preUpdateContributionObject most accurately)
669 // so, this is always called & only appears to succeed when prevContribution exists - which appears
670 // to mean "are we updating an exisitng pending contribution"
671 //I was able to make the unit test complete as fataling here doesn't prevent
672 // the contribution being created - but activities would not be created or emails sent
674 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
677 self
::updateRecurLinkedPledge($contribution);
679 // create an activity record
680 if ($input['component'] == 'contribute') {
682 $targetContactID = NULL;
683 if (!empty($ids['related_contact'])) {
684 $targetContactID = $contribution->contact_id
;
685 $contribution->contact_id
= $ids['related_contact'];
687 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
691 CRM_Activity_BAO_Activity
::addActivity($participant);
694 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
695 $transaction->commit();
697 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
698 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
699 if (!array_key_exists('is_email_receipt', $values) ||
700 $values['is_email_receipt'] == 1
702 self
::sendMail($input, $ids, $objects, $values, $recur, FALSE);
703 CRM_Core_Error
::debug_log_message("Receipt sent");
706 CRM_Core_Error
::debug_log_message("Success: Database updated");
707 if ($this->_isRecurring
) {
708 $this->sendRecurringStartOrEndNotification($ids, $recur);
717 public function getBillingID(&$ids) {
718 // get the billing location type
719 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
720 // CRM-8108 remove the ts around the Billing locationtype
721 //$ids['billing'] = array_search( ts('Billing'), $locationTypes );
722 $ids['billing'] = array_search('Billing', $locationTypes);
723 if (!$ids['billing']) {
724 CRM_Core_Error
::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
725 echo "Failure: Could not find billing location type<p>";
732 * Send receipt from contribution. Note that the compose message part has been moved to contribution
733 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
735 * @param array $input
736 * Incoming data from Payment processor.
738 * Related object IDs.
740 * @param array $values
741 * Values related to objects that have already been loaded.
743 * Is it part of a recurring contribution.
744 * @param bool $returnMessageText
745 * Should text be returned instead of sent. This.
746 * is because the function is also used to generate pdfs
750 public function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
751 $contribution = &$objects['contribution'];
752 $input['is_recur'] = $recur;
753 // set receipt from e-mail and name in value
754 if (!$returnMessageText) {
755 $session = CRM_Core_Session
::singleton();
756 $userID = $session->get('userID');
757 if (!empty($userID)) {
758 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
759 $values['receipt_from_email'] = $userEmail;
760 $values['receipt_from_name'] = $userName;
763 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
767 * Send start or end notification for recurring payments
771 public function sendRecurringStartOrEndNotification($ids, $recur) {
772 if ($this->_isFirstOrLastRecurringPayment
) {
773 $autoRenewMembership = FALSE;
775 isset($ids['membership']) && $ids['membership']
777 $autoRenewMembership = TRUE;
780 //send recurring Notification email for user
781 CRM_Contribute_BAO_ContributionPage
::recurringNotify($this->_isFirstOrLastRecurringPayment
,
783 $ids['contributionPage'],
791 * Update contribution status - this is only called from one place in the code &
792 * it is unclear whether it is a function on the way in or on the way out
794 * @param array $params
797 public function updateContributionStatus(&$params) {
798 // get minimum required values.
799 $statusId = CRM_Utils_Array
::value('contribution_status_id', $params);
800 $componentId = CRM_Utils_Array
::value('component_id', $params);
801 $componentName = CRM_Utils_Array
::value('componentName', $params);
802 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
804 if (!$contributionId ||
!$componentId ||
!$componentName ||
!$statusId) {
808 $input = $ids = $objects = array();
810 //get the required ids.
811 $ids['contribution'] = $contributionId;
813 if (!$ids['contact'] = CRM_Utils_Array
::value('contact_id', $params)) {
814 $ids['contact'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
820 if ($componentName == 'Event') {
822 $ids['participant'] = $componentId;
824 if (!$ids['event'] = CRM_Utils_Array
::value('event_id', $params)) {
825 $ids['event'] = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
832 if ($componentName == 'Membership') {
833 $name = 'contribute';
834 $ids['membership'] = $componentId;
836 $ids['contributionPage'] = NULL;
837 $ids['contributionRecur'] = NULL;
838 $input['component'] = $name;
840 $baseIPN = new CRM_Core_Payment_BaseIPN();
841 $transaction = new CRM_Core_Transaction();
843 // reset template values.
844 $template = CRM_Core_Smarty
::singleton();
845 $template->clearTemplateVars();
847 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
848 CRM_Core_Error
::fatal();
851 $contribution = &$objects['contribution'];
853 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
854 'labelColumn' => 'name',
857 $input['skipComponentSync'] = CRM_Utils_Array
::value('skipComponentSync', $params);
858 if ($statusId == $contributionStatuses['Cancelled']) {
859 $baseIPN->cancelled($objects, $transaction, $input);
860 $transaction->commit();
863 elseif ($statusId == $contributionStatuses['Failed']) {
864 $baseIPN->failed($objects, $transaction, $input);
865 $transaction->commit();
869 // status is not pending
870 if ($contribution->contribution_status_id
!= $contributionStatuses['Pending']) {
871 $transaction->commit();
875 //set values for ipn code.
879 'payment_instrument_id'
881 if (!$input[$field] = CRM_Utils_Array
::value($field, $params)) {
882 $input[$field] = $contribution->$field;
885 if (!$input['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $params)) {
886 $input['trxn_id'] = $contribution->invoice_id
;
888 if (!$input['amount'] = CRM_Utils_Array
::value('total_amount', $params)) {
889 $input['amount'] = $contribution->total_amount
;
891 $input['is_test'] = $contribution->is_test
;
892 $input['net_amount'] = $contribution->net_amount
;
893 if (!empty($input['fee_amount']) && !empty($input['amount'])) {
894 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
897 //complete the contribution.
898 $baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
900 // reset template values before processing next transactions
901 $template->clearTemplateVars();
907 * Update pledge associated with a recurring contribution
909 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
911 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
912 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
913 * it should be assumed they
914 * do so with the intention that all payments will be linked
916 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
917 * If not the contribution will also need to be linked to the pledge
920 * @param $contribution
922 public function updateRecurLinkedPledge(&$contribution) {
923 $returnProperties = array('id', 'pledge_id');
924 $paymentDetails = $paymentIDs = array();
926 if (CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id
,
927 $paymentDetails, $returnProperties
930 foreach ($paymentDetails as $key => $value) {
931 $paymentIDs[] = $value['id'];
932 $pledgeId = $value['pledge_id'];
936 //payment is not already linked - if it is linked with a pledge we need to create a link.
937 // return if it is not recurring contribution
938 if (!$contribution->contribution_recur_id
) {
942 $relatedContributions = new CRM_Contribute_DAO_Contribution();
943 $relatedContributions->contribution_recur_id
= $contribution->contribution_recur_id
;
944 $relatedContributions->find();
946 while ($relatedContributions->fetch()) {
947 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id
,
948 $paymentDetails, $returnProperties
952 if (empty($paymentDetails)) {
953 // payment is not linked with a pledge and neither are any other contributions on this
957 foreach ($paymentDetails as $key => $value) {
958 $pledgeId = $value['pledge_id'];
961 // we have a pledge now we need to get the oldest unpaid payment
962 $paymentDetails = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeId);
963 if (empty($paymentDetails['id'])) {
964 // we can assume this pledge is now completed
965 // return now so we don't create a core error & roll back
968 $paymentDetails['contribution_id'] = $contribution->id
;
969 $paymentDetails['status_id'] = $contribution->contribution_status_id
;
970 $paymentDetails['actual_amount'] = $contribution->total_amount
;
972 // put contribution against it
973 $payment = CRM_Pledge_BAO_PledgePayment
::add($paymentDetails);
974 $paymentIDs[] = $payment->id
;
977 // update pledge and corresponding payment statuses
978 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id
,
979 NULL, $contribution->total_amount
984 * @param int $recurId
985 * @param $contribution
989 public function addRecurLineItems($recurId, $contribution) {
992 $originalContributionID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
993 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($originalContributionID);
994 if (!empty($lineItems)) {
995 foreach ($lineItems as $key => $value) {
996 $priceField = new CRM_Price_DAO_PriceField();
997 $priceField->id
= $value['price_field_id'];
998 $priceField->find(TRUE);
999 $lineSets[$priceField->price_set_id
][] = $value;
1000 if ($value['entity_table'] == 'civicrm_membership') {
1002 civicrm_api3('membership_payment', 'create', array(
1003 'membership_id' => $value['entity_id'],
1004 'contribution_id' => $contribution->id
1007 catch (CiviCRM_API3_Exception
$e) {
1008 // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
1009 // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
1015 CRM_Price_BAO_LineItem
::processPriceSet($contribution->id
, $lineSets, $contribution);
1020 // function to copy custom data of the
1021 // initial contribution into its recurring contributions
1023 * @param int $recurId
1024 * @param int $targetContributionId
1026 public function copyCustomValues($recurId, $targetContributionId) {
1027 if ($recurId && $targetContributionId) {
1028 // get the initial contribution id of recur id
1029 $sourceContributionId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
1031 // if the same contribution is being proccessed then return
1032 if ($sourceContributionId == $targetContributionId) {
1035 // check if proper recurring contribution record is being processed
1036 $targetConRecurId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
1037 if ($targetConRecurId != $recurId) {
1042 $extends = array('Contribution');
1043 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
1045 foreach ($groupTree as $groupID => $group) {
1046 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
1047 foreach ($group['fields'] as $fieldID => $field) {
1048 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
1052 foreach ($table as $tableName => $tableColumns) {
1053 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
1054 $tableColumns[0] = $targetContributionId;
1055 $select = 'SELECT ' . implode(', ', $tableColumns);
1056 $from = ' FROM ' . $tableName;
1057 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
1058 $query = $insert . $select . $from . $where;
1059 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1065 // function to copy soft credit record of first recurring contribution
1066 // and add new soft credit against $targetContributionId
1068 * @param int $recurId
1069 * @param int $targetContributionId
1071 public function addrecurSoftCredit($recurId, $targetContributionId) {
1072 $contriID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
1074 $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
1075 $soft_contribution->contribution_id
= $contriID;
1077 //check if first recurring contribution has any associated soft credit
1078 if ($soft_contribution->find(TRUE)) {
1079 $soft_contribution->contribution_id
= $targetContributionId;
1080 unset($soft_contribution->id
);
1081 $soft_contribution->save();