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;
52 public function __construct() {
53 self
::$_now = date('YmdHis');
57 * Store input array on the class
59 * @param array $parameters
61 * @throws CRM_Core_Exception
63 public function setInputParameters($parameters) {
64 if(!is_array($parameters)) {
65 throw new CRM_Core_Exception('Invalid input parameters');
67 $this->_inputParameters
= $parameters;
70 * Validate incoming data. 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.
89 public function validateData(&$input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
91 // make sure contact exists and is valid
92 $contact = new CRM_Contact_BAO_Contact();
93 $contact->id
= $ids['contact'];
94 if (!$contact->find(TRUE)) {
95 CRM_Core_Error
::debug_log_message("Could not find contact record: {$ids['contact']} in IPN request: ".print_r($input, TRUE));
96 echo "Failure: Could not find contact record: {$ids['contact']}<p>";
100 // make sure contribution exists and is valid
101 $contribution = new CRM_Contribute_BAO_Contribution();
102 $contribution->id
= $ids['contribution'];
103 if (!$contribution->find(TRUE)) {
104 CRM_Core_Error
::debug_log_message("Could not find contribution record: {$contribution->id} in IPN request: ".print_r($input, TRUE));
105 echo "Failure: Could not find contribution record for {$contribution->id}<p>";
108 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
110 $objects['contact'] = &$contact;
111 $objects['contribution'] = &$contribution;
112 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
115 //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
116 //current contribution. Here we ensure that the original contribution is available to the complete transaction function
117 //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
118 if (isset($objects['contributionRecur'])) {
119 $objects['first_contribution'] = $objects['contribution'];
125 * Load objects related to contribution
127 * @input array information from Payment processor
131 * @param array $objects
132 * @param bool $required
133 * @param int $paymentProcessorID
134 * @param array $error_handling
138 public function loadObjects(&$input, &$ids, &$objects, $required, $paymentProcessorID, $error_handling = NULL) {
139 if (empty($error_handling)) {
140 // default options are that we log an error & echo it out
141 // note that we should refactor this error handling into error code @ some point
142 // but for now setting up enough separation so we can do unit tests
143 $error_handling = array(
148 $ids['paymentProcessor'] = $paymentProcessorID;
149 if (is_a($objects['contribution'], 'CRM_Contribute_BAO_Contribution')) {
150 $contribution = &$objects['contribution'];
153 //legacy support - functions are 'used' to be able to pass in a DAO
154 $contribution = new CRM_Contribute_BAO_Contribution();
155 $contribution->id
= CRM_Utils_Array
::value('contribution', $ids);
156 $contribution->find(TRUE);
157 $objects['contribution'] = &$contribution;
160 $success = $contribution->loadRelatedObjects($input, $ids, $required);
162 catch(Exception
$e) {
164 if (!empty($error_handling['log_error'])) {
165 CRM_Core_Error
::debug_log_message($e->getMessage());
167 if (!empty($error_handling['echo_error'])) {
168 echo ($e->getMessage());
170 if (!empty($error_handling['return_error'])) {
173 'error_message' => ($e->getMessage()),
177 $objects = array_merge($objects, $contribution->_relatedObjects
);
182 * Set contribution to failed
183 * @param array $objects
184 * @param object $transaction
185 * @param array $input
188 public function failed(&$objects, &$transaction, $input = array()) {
189 $contribution = &$objects['contribution'];
190 $memberships = array();
191 if (!empty($objects['membership'])) {
192 $memberships = &$objects['membership'];
193 if (is_numeric($memberships)) {
194 $memberships = array($objects['membership']);
198 $addLineItems = FALSE;
199 if (empty($contribution->id
)) {
200 $addLineItems = TRUE;
202 $participant = &$objects['participant'];
205 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
206 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
207 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
208 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
209 $contribution->contribution_status_id
= $contributionStatuses['Failed'];
210 $contribution->save();
212 //add lineitems for recurring payments
213 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
214 $this->addRecurLineItems($objects['contributionRecur']->id
, $contribution);
217 //add new soft credit against current contribution id and
218 //copy initial contribution custom fields for recurring contributions
219 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
220 $this->addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
221 $this->copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
224 if (empty($input['skipComponentSync'])) {
225 if (!empty($memberships)) {
226 // if transaction is failed then set "Cancelled" as membership status
227 $membershipStatuses = CRM_Core_PseudoConstant
::get('CRM_Member_DAO_Membership', 'status_id', array('labelColumn' => 'name', 'flip' => 1));
228 foreach ($memberships as $membership) {
230 $membership->status_id
= $membershipStatuses['Cancelled'];
233 //update related Memberships.
234 $params = array('status_id' => $membershipStatuses['Cancelled']);
235 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
241 $participantStatuses = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'status_id', array('labelColumn' => 'name', 'flip' => 1));
242 $participant->status_id
= $participantStatuses['Cancelled'];
243 $participant->save();
247 $transaction->commit();
248 CRM_Core_Error
::debug_log_message("Setting contribution status to failed");
249 //echo "Success: Setting contribution status to failed<p>";
254 * Handled pending contribution status
255 * @param array $objects
256 * @param object $transaction
259 public function pending(&$objects, &$transaction) {
260 $transaction->commit();
261 CRM_Core_Error
::debug_log_message("returning since contribution status is pending");
262 echo "Success: Returning since contribution status is pending<p>";
268 * @param $transaction
269 * @param array $input
273 public function cancelled(&$objects, &$transaction, $input = array()) {
274 $contribution = &$objects['contribution'];
275 $memberships = &$objects['membership'];
276 if (is_numeric($memberships)) {
277 $memberships = array($objects['membership']);
280 $participant = &$objects['participant'];
281 $addLineItems = FALSE;
282 if (empty($contribution->id
)) {
283 $addLineItems = TRUE;
285 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
286 $contribution->contribution_status_id
= $contributionStatuses['Cancelled'];
287 $contribution->cancel_date
= self
::$_now;
288 $contribution->cancel_reason
= CRM_Utils_Array
::value('reasonCode', $input);
289 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
290 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
291 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
292 $contribution->save();
294 //add lineitems for recurring payments
295 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
296 $this->addRecurLineItems($objects['contributionRecur']->id
, $contribution);
299 //add new soft credit against current $contribution and
300 //copy initial contribution custom fields for recurring contributions
301 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
302 $this->addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
303 $this->copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
306 if (empty($input['skipComponentSync'])) {
307 if (!empty($memberships)) {
308 $membershipStatuses = CRM_Core_PseudoConstant
::get('CRM_Member_DAO_Membership', 'status_id', array('labelColumn' => 'name', 'flip' => 1));
309 foreach ($memberships as $membership) {
311 $membership->status_id
= $membershipStatuses['Cancelled'];
314 //update related Memberships.
315 $params = array('status_id' => $membershipStatuses['Cancelled']);
316 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
322 $participantStatuses = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'status_id', array('labelColumn' => 'name', 'flip' => 1));
323 $participant->status_id
= $participantStatuses['Cancelled'];
324 $participant->save();
327 $transaction->commit();
328 CRM_Core_Error
::debug_log_message("Setting contribution status to cancelled");
329 //echo "Success: Setting contribution status to cancelled<p>";
335 * @param $transaction
339 public function unhandled(&$objects, &$transaction) {
340 $transaction->rollback();
341 CRM_Core_Error
::debug_log_message("returning since contribution status: is not handled");
342 echo "Failure: contribution status is not handled<p>";
350 * @param $transaction
353 public function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) {
354 $contribution = &$objects['contribution'];
356 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
358 $memberships = &$objects['membership'];
359 if (is_numeric($memberships)) {
360 $memberships = array($objects['membership']);
362 $participant = &$objects['participant'];
363 $event = &$objects['event'];
364 $changeToday = CRM_Utils_Array
::value('trxn_date', $input, self
::$_now);
365 $recurContrib = &$objects['contributionRecur'];
369 if ($input['component'] == 'contribute') {
370 if ($contribution->contribution_page_id
) {
371 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
372 $source = ts('Online Contribution') . ': ' . $values['title'];
374 elseif ($recurContrib && $recurContrib->id
) {
375 $contribution->contribution_page_id
= NULL;
376 $values['amount'] = $recurContrib->amount
;
377 $values['financial_type_id'] = $objects['contributionType']->id
;
378 $values['title'] = $source = ts('Offline Recurring Contribution');
379 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
380 $values['receipt_from_name'] = $domainValues[0];
381 $values['receipt_from_email'] = $domainValues[1];
383 if($recurContrib && $recurContrib->id
){
384 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
385 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
388 $contribution->source
= $source;
389 if (!empty($values['is_email_receipt'])) {
390 $contribution->receipt_date
= self
::$_now;
393 if (!empty($memberships)) {
394 $membershipsUpdate = array();
395 foreach ($memberships as $membershipTypeIdKey => $membership) {
399 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
400 $membership->membership_type_id
,
401 $membership->is_test
, $membership->id
404 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
405 // this picks up membership type changes during renewals
407 SELECT membership_type_id
408 FROM civicrm_membership_log
409 WHERE membership_id=$membership->id
412 $dao = new CRM_Core_DAO
;
415 if (!empty($dao->membership_type_id
)) {
416 $membership->membership_type_id
= $dao->membership_type_id
;
419 // else fall back to using current membership type
421 // else fall back to using current membership type
424 $num_terms = $contribution->getNumTermsByContributionAndMembershipType($membership->membership_type_id
, $primaryContributionID);
425 if ($currentMembership) {
428 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
429 * when Contribution mode is notify and membership is for renewal )
431 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
433 // @todo - we should pass membership_type_id instead of null here but not
434 // adding as not sure of testing
435 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
436 $changeToday, NULL, $num_terms
439 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
442 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $num_terms);
445 //get the status for membership.
446 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
451 $membership->membership_type_id
,
455 $formatedParams = array(
456 'status_id' => CRM_Utils_Array
::value('id', $calcStatus, 2),
457 'join_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('join_date', $dates), $format),
458 'start_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('start_date', $dates), $format),
459 'end_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('end_date', $dates), $format),
461 //we might be renewing membership,
462 //so make status override false.
463 $formatedParams['is_override'] = FALSE;
464 $membership->copyValues($formatedParams);
467 //updating the membership log
468 $membershipLog = array();
469 $membershipLog = $formatedParams;
471 $logStartDate = $formatedParams['start_date'];
472 if (!empty($dates['log_start_date'])) {
473 $logStartDate = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
474 $logStartDate = CRM_Utils_Date
::isoToMysql($logStartDate);
477 $membershipLog['start_date'] = $logStartDate;
478 $membershipLog['membership_id'] = $membership->id
;
479 $membershipLog['modified_id'] = $membership->contact_id
;
480 $membershipLog['modified_date'] = date('Ymd');
481 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
483 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
485 //update related Memberships.
486 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formatedParams);
488 //update the membership type key of membership relatedObjects array
489 //if it has changed after membership update
490 if ($membershipTypeIdKey != $membership->membership_type_id
) {
491 $membershipsUpdate[$membership->membership_type_id
] = $membership;
492 $contribution->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
493 unset($contribution->_relatedObjects
['membership'][$membershipTypeIdKey]);
494 unset($memberships[$membershipTypeIdKey]);
498 //update the memberships object with updated membershipTypeId data
499 //if membershipTypeId has changed after membership update
500 if (!empty($membershipsUpdate)) {
501 $memberships = $memberships +
$membershipsUpdate;
507 $eventParams = array('id' => $objects['event']->id
);
508 $values['event'] = array();
510 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
512 //get location details
513 $locationParams = array('entity_id' => $objects['event']->id
, 'entity_table' => 'civicrm_event');
514 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
516 $ufJoinParams = array(
517 'entity_table' => 'civicrm_event',
518 'entity_id' => $ids['event'],
519 'module' => 'CiviEvent',
524 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
526 $values['custom_pre_id'] = $custom_pre_id;
527 $values['custom_post_id'] = $custom_post_ids;
528 //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
529 //and cases involving status updation through ipn
530 $values['totalAmount'] = $input['amount'];
532 $contribution->source
= ts('Online Event Registration') . ': ' . $values['event']['title'];
534 if ($values['event']['is_email_confirm']) {
535 $contribution->receipt_date
= self
::$_now;
536 $values['is_email_receipt'] = 1;
538 if (empty($input['skipComponentSync'])) {
539 $participantStatuses = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'status_id', array('labelColumn' => 'name', 'flip' => 1));
540 $participant->status_id
= $participantStatuses['Registered'];
542 $participant->save();
545 if (CRM_Utils_Array
::value('net_amount', $input, 0) == 0 &&
546 CRM_Utils_Array
::value('fee_amount', $input, 0) != 0
548 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
550 $addLineItems = FALSE;
551 if (empty($contribution->id
)) {
552 $addLineItems = TRUE;
554 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
555 $contribution->contribution_status_id
= $contributionStatuses['Completed'];
556 $contribution->is_test
= $input['is_test'];
557 $contribution->fee_amount
= CRM_Utils_Array
::value('fee_amount', $input, 0);
558 $contribution->net_amount
= CRM_Utils_Array
::value('net_amount', $input, 0);
559 $contribution->trxn_id
= $input['trxn_id'];
560 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
561 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
562 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
563 $contribution->cancel_date
= 'null';
565 if (!empty($input['check_number'])) {
566 $contribution->check_number
= $input['check_number'];
569 if (!empty($input['payment_instrument_id'])) {
570 $contribution->payment_instrument_id
= $input['payment_instrument_id'];
573 if ($contribution->id
) {
574 $contributionId['id'] = $contribution->id
;
575 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues($contributionId, CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
577 $contribution->save();
579 //add new soft credit against current $contribution and
580 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
581 $this->addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
584 //add lineitems for recurring payments
585 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
587 $input['line_item'] = $this->addRecurLineItems($objects['contributionRecur']->id
, $contribution);
590 // this is just to prevent e-notices when we call recordFinancialAccounts - per comments on that line - intention is somewhat unclear
591 $input['line_item'] = array();
595 //copy initial contribution custom fields for recurring contributions
596 if ($recurContrib && $recurContrib->id
) {
597 $this->copyCustomValues($recurContrib->id
, $contribution->id
);
600 // next create the transaction record
601 $paymentProcessor = $paymentProcessorId = '';
602 if (isset($objects['paymentProcessor'])) {
603 if (is_array($objects['paymentProcessor'])) {
604 $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
605 $paymentProcessorId = $objects['paymentProcessor']['id'];
608 $paymentProcessor = $objects['paymentProcessor']->payment_processor_type
;
609 $paymentProcessorId = $objects['paymentProcessor']->id
;
612 //it's hard to see how it could reach this point without a contributon id as it is saved in line 511 above
613 // which raised the question as to whether this check preceded line 511 & if so whether something could be broken
614 // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code
615 // it would be good if someone added some comments or refactored this
616 if ($contribution->id
) {
617 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
618 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&& - $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
619 $input['payment_processor'] = $paymentProcessorId;
621 $input['contribution_status_id'] = $contributionStatuses['Completed'];
622 $input['total_amount'] = $input['amount'];
623 $input['contribution'] = $contribution;
624 $input['financial_type_id'] = $contribution->financial_type_id
;
626 if (!empty($contribution->_relatedObjects
['participant'])) {
627 $input['contribution_mode'] = 'participant';
628 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
629 $input['skipLineItem'] = 1;
631 elseif (!empty($contribution->_relatedObjects
['membership'])) {
632 $input['skipLineItem'] = TRUE;
633 $input['contribution_mode'] = 'membership';
635 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
636 // and subsequent payments. In this case the line items are created at $this->addRecurLineItems
637 // and since the contribution is saved prior to this line there is always a contribution-id,
638 // however there is never a prevContribution (which appears to mean original contribution not previous
639 // contribution - or preUpdateContributionObject most accurately)
640 // so, this is always called & only appears to succeed when prevContribution exists - which appears
641 // to mean "are we updating an exisitng pending contribution"
642 //I was able to make the unit test complete as fataling here doesn't prevent
643 // the contribution being created - but activities would not be created or emails sent
645 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
648 self
::updateRecurLinkedPledge($contribution);
650 // create an activity record
651 if ($input['component'] == 'contribute') {
653 $targetContactID = NULL;
654 if (!empty($ids['related_contact'])) {
655 $targetContactID = $contribution->contact_id
;
656 $contribution->contact_id
= $ids['related_contact'];
658 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
662 CRM_Activity_BAO_Activity
::addActivity($participant);
665 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
666 $transaction->commit();
668 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
669 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
670 if (!array_key_exists('is_email_receipt', $values) ||
671 $values['is_email_receipt'] == 1
673 self
::sendMail($input, $ids, $objects, $values, $recur, FALSE);
674 CRM_Core_Error
::debug_log_message("Receipt sent");
677 CRM_Core_Error
::debug_log_message("Success: Database updated");
678 if ($this->_isRecurring
) {
679 $this->sendRecurringStartOrEndNotification($ids, $recur);
688 public function getBillingID(&$ids) {
689 // get the billing location type
690 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
691 // CRM-8108 remove the ts around the Billing locationtype
692 //$ids['billing'] = array_search( ts('Billing'), $locationTypes );
693 $ids['billing'] = array_search('Billing', $locationTypes);
694 if (!$ids['billing']) {
695 CRM_Core_Error
::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
696 echo "Failure: Could not find billing location type<p>";
703 * Send receipt from contribution. Note that the compose message part has been moved to contribution
704 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
706 * @param array $input
707 * Incoming data from Payment processor.
709 * Related object IDs.
711 * @param array $values
712 * Values related to objects that have already been loaded.
714 * Is it part of a recurring contribution.
715 * @param bool $returnMessageText
716 * Should text be returned instead of sent. This.
717 * is because the function is also used to generate pdfs
721 public function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
722 $contribution = &$objects['contribution'];
723 $input['is_recur'] = $recur;
724 // set receipt from e-mail and name in value
725 if (!$returnMessageText) {
726 $session = CRM_Core_Session
::singleton();
727 $userID = $session->get('userID');
728 if (!empty($userID)) {
729 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
730 $values['receipt_from_email'] = $userEmail;
731 $values['receipt_from_name'] = $userName;
734 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
738 * Send start or end notification for recurring payments
742 public function sendRecurringStartOrEndNotification($ids, $recur) {
743 if ($this->_isFirstOrLastRecurringPayment
) {
744 $autoRenewMembership = FALSE;
746 isset($ids['membership']) && $ids['membership']
748 $autoRenewMembership = TRUE;
751 //send recurring Notification email for user
752 CRM_Contribute_BAO_ContributionPage
::recurringNotify($this->_isFirstOrLastRecurringPayment
,
754 $ids['contributionPage'],
762 * Update contribution status - this is only called from one place in the code &
763 * it is unclear whether it is a function on the way in or on the way out
765 * @param unknown_type $params
766 * @return void|Ambigous <value, unknown, array>
768 public function updateContributionStatus(&$params) {
769 // get minimum required values.
770 $statusId = CRM_Utils_Array
::value('contribution_status_id', $params);
771 $componentId = CRM_Utils_Array
::value('component_id', $params);
772 $componentName = CRM_Utils_Array
::value('componentName', $params);
773 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
775 if (!$contributionId ||
!$componentId ||
!$componentName ||
!$statusId) {
779 $input = $ids = $objects = array();
781 //get the required ids.
782 $ids['contribution'] = $contributionId;
784 if (!$ids['contact'] = CRM_Utils_Array
::value('contact_id', $params)) {
785 $ids['contact'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
791 if ($componentName == 'Event') {
793 $ids['participant'] = $componentId;
795 if (!$ids['event'] = CRM_Utils_Array
::value('event_id', $params)) {
796 $ids['event'] = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
803 if ($componentName == 'Membership') {
804 $name = 'contribute';
805 $ids['membership'] = $componentId;
807 $ids['contributionPage'] = NULL;
808 $ids['contributionRecur'] = NULL;
809 $input['component'] = $name;
811 $baseIPN = new CRM_Core_Payment_BaseIPN();
812 $transaction = new CRM_Core_Transaction();
814 // reset template values.
815 $template = CRM_Core_Smarty
::singleton();
816 $template->clearTemplateVars();
818 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
819 CRM_Core_Error
::fatal();
822 $contribution = &$objects['contribution'];
824 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
825 $input['skipComponentSync'] = CRM_Utils_Array
::value('skipComponentSync', $params);
826 if ($statusId == $contributionStatuses['Cancelled']) {
827 $baseIPN->cancelled($objects, $transaction, $input);
828 $transaction->commit();
831 elseif ($statusId == $contributionStatuses['Failed']) {
832 $baseIPN->failed($objects, $transaction, $input);
833 $transaction->commit();
837 // status is not pending
838 if ($contribution->contribution_status_id
!= $contributionStatuses['Pending']) {
839 $transaction->commit();
843 //set values for ipn code.
845 'fee_amount', 'check_number', 'payment_instrument_id') as $field) {
846 if (!$input[$field] = CRM_Utils_Array
::value($field, $params)) {
847 $input[$field] = $contribution->$field;
850 if (!$input['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $params)) {
851 $input['trxn_id'] = $contribution->invoice_id
;
853 if (!$input['amount'] = CRM_Utils_Array
::value('total_amount', $params)) {
854 $input['amount'] = $contribution->total_amount
;
856 $input['is_test'] = $contribution->is_test
;
857 $input['net_amount'] = $contribution->net_amount
;
858 if (!empty($input['fee_amount']) && !empty($input['amount'])) {
859 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
862 //complete the contribution.
863 $baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
865 // reset template values before processing next transactions
866 $template->clearTemplateVars();
872 * Update pledge associated with a recurring contribution
874 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
876 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
877 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
878 * it should be assumed they
879 * do so with the intention that all payments will be linked
881 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
882 * If not the contribution will also need to be linked to the pledge
885 * @param $contribution
887 public function updateRecurLinkedPledge(&$contribution) {
888 $returnProperties = array('id', 'pledge_id');
889 $paymentDetails = $paymentIDs = array();
891 if (CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id
,
892 $paymentDetails, $returnProperties
894 foreach ($paymentDetails as $key => $value) {
895 $paymentIDs[] = $value['id'];
896 $pledgeId = $value['pledge_id'];
900 //payment is not already linked - if it is linked with a pledge we need to create a link.
901 // return if it is not recurring contribution
902 if (!$contribution->contribution_recur_id
) {
906 $relatedContributions = new CRM_Contribute_DAO_Contribution();
907 $relatedContributions->contribution_recur_id
= $contribution->contribution_recur_id
;
908 $relatedContributions->find();
910 while ($relatedContributions->fetch()) {
911 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id
,
912 $paymentDetails, $returnProperties
916 if (empty($paymentDetails)) {
917 // payment is not linked with a pledge and neither are any other contributions on this
921 foreach ($paymentDetails as $key => $value) {
922 $pledgeId = $value['pledge_id'];
925 // we have a pledge now we need to get the oldest unpaid payment
926 $paymentDetails = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeId);
927 if(empty($paymentDetails['id'])){
928 // we can assume this pledge is now completed
929 // return now so we don't create a core error & roll back
932 $paymentDetails['contribution_id'] = $contribution->id
;
933 $paymentDetails['status_id'] = $contribution->contribution_status_id
;
934 $paymentDetails['actual_amount'] = $contribution->total_amount
;
936 // put contribution against it
937 $payment = CRM_Pledge_BAO_PledgePayment
::add($paymentDetails);
938 $paymentIDs[] = $payment->id
;
941 // update pledge and corresponding payment statuses
942 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id
,
943 NULL, $contribution->total_amount
948 * @param int $recurId
949 * @param $contribution
953 public function addRecurLineItems($recurId, $contribution) {
956 $originalContributionID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
957 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($originalContributionID);
958 if (!empty($lineItems)) {
959 foreach ($lineItems as $key => $value) {
960 $priceField = new CRM_Price_DAO_PriceField();
961 $priceField->id
= $value['price_field_id'];
962 $priceField->find(TRUE);
963 $lineSets[$priceField->price_set_id
][] = $value;
964 if ($value['entity_table'] == 'civicrm_membership') {
966 civicrm_api3('membership_payment', 'create', array('membership_id' => $value['entity_id'], 'contribution_id' => $contribution->id
));
968 catch (CiviCRM_API3_Exception
$e) {
969 // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
970 // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
976 CRM_Price_BAO_LineItem
::processPriceSet($contribution->id
, $lineSets, $contribution);
981 // function to copy custom data of the
982 // initial contribution into its recurring contributions
984 * @param int $recurId
985 * @param int $targetContributionId
987 public function copyCustomValues($recurId, $targetContributionId) {
988 if ($recurId && $targetContributionId) {
989 // get the initial contribution id of recur id
990 $sourceContributionId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
992 // if the same contribution is being proccessed then return
993 if ($sourceContributionId == $targetContributionId) {
996 // check if proper recurring contribution record is being processed
997 $targetConRecurId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
998 if ($targetConRecurId != $recurId) {
1003 $extends = array('Contribution');
1004 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
1006 foreach ($groupTree as $groupID => $group) {
1007 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
1008 foreach ($group['fields'] as $fieldID => $field) {
1009 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
1013 foreach ($table as $tableName => $tableColumns) {
1014 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
1015 $tableColumns[0] = $targetContributionId;
1016 $select = 'SELECT ' . implode(', ', $tableColumns);
1017 $from = ' FROM ' . $tableName;
1018 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
1019 $query = $insert . $select . $from . $where;
1020 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1026 // function to copy soft credit record of first recurring contribution
1027 // and add new soft credit against $targetContributionId
1029 * @param int $recurId
1030 * @param int $targetContributionId
1032 public function addrecurSoftCredit($recurId, $targetContributionId) {
1033 $contriID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
1035 $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
1036 $soft_contribution->contribution_id
= $contriID;
1038 //check if first recurring contribution has any associated soft credit
1039 if ($soft_contribution->find(TRUE)) {
1040 $soft_contribution->contribution_id
= $targetContributionId;
1041 unset($soft_contribution->id
);
1042 $soft_contribution->save();