3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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();
49 function __construct() {
50 self
::$_now = date('YmdHis');
54 * Store input array on the class
56 * @param array $parameters
58 * @throws CRM_Core_Exception
60 function setInputParameters($parameters) {
61 if(!is_array($parameters)) {
62 throw new CRM_Core_Exception('Invalid input parameters');
64 $this->_inputParameters
= $parameters;
67 * Validate incoming data. This function is intended to ensure that incoming data matches
68 * It provides a form of pseudo-authentication - by checking the calling fn already knows
69 * the correct contact id & contribution id (this can be problematic when that has changed in
70 * the meantime for transactions that are delayed & contacts are merged in-between. e.g
71 * Paypal allows you to resend Instant Payment Notifications if you, for example, moved site
72 * and didn't update your IPN URL.
74 * @param array $input interpreted values from the values returned through the IPN
75 * @param array $ids more interpreted values (ids) from the values returned through the IPN
76 * @param array $objects an empty array that will be populated with loaded object
77 * @param boolean $required boolean Return FALSE if the relevant objects don't exist
78 * @param integer $paymentProcessorID Id of the payment processor ID in use
81 function validateData(&$input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
83 // make sure contact exists and is valid
84 $contact = new CRM_Contact_BAO_Contact();
85 $contact->id
= $ids['contact'];
86 if (!$contact->find(TRUE)) {
87 CRM_Core_Error
::debug_log_message("Could not find contact record: {$ids['contact']} in IPN request: ".print_r($input, TRUE));
88 echo "Failure: Could not find contact record: {$ids['contact']}<p>";
92 // make sure contribution exists and is valid
93 $contribution = new CRM_Contribute_BAO_Contribution();
94 $contribution->id
= $ids['contribution'];
95 if (!$contribution->find(TRUE)) {
96 CRM_Core_Error
::debug_log_message("Could not find contribution record: {$contribution->id} in IPN request: ".print_r($input, TRUE));
97 echo "Failure: Could not find contribution record for {$contribution->id}<p>";
100 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
102 $objects['contact'] = &$contact;
103 $objects['contribution'] = &$contribution;
104 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
112 * Load objects related to contribution
114 * @input array information from Payment processor
118 * @param array $objects
119 * @param boolean $required
120 * @param integer $paymentProcessorID
121 * @param array $error_handling
123 * @return multitype:number NULL |boolean
125 function loadObjects(&$input, &$ids, &$objects, $required, $paymentProcessorID, $error_handling = NULL) {
126 if (empty($error_handling)) {
127 // default options are that we log an error & echo it out
128 // note that we should refactor this error handling into error code @ some point
129 // but for now setting up enough separation so we can do unit tests
130 $error_handling = array(
135 $ids['paymentProcessor'] = $paymentProcessorID;
136 if (is_a($objects['contribution'], 'CRM_Contribute_BAO_Contribution')) {
137 $contribution = &$objects['contribution'];
140 //legacy support - functions are 'used' to be able to pass in a DAO
141 $contribution = new CRM_Contribute_BAO_Contribution();
142 $contribution->id
= CRM_Utils_Array
::value('contribution', $ids);
143 $contribution->find(TRUE);
144 $objects['contribution'] = &$contribution;
147 $success = $contribution->loadRelatedObjects($input, $ids, $required);
149 catch(Exception
$e) {
151 if (!empty($error_handling['log_error'])) {
152 CRM_Core_Error
::debug_log_message($e->getMessage());
154 if (!empty($error_handling['echo_error'])) {
155 echo ($e->getMessage());
157 if (!empty($error_handling['return_error'])) {
160 'error_message' => ($e->getMessage()),
164 $objects = array_merge($objects, $contribution->_relatedObjects
);
169 * Set contribution to failed
170 * @param array $objects
171 * @param object $transaction
172 * @param array $input
175 function failed(&$objects, &$transaction, $input = array()) {
176 $contribution = &$objects['contribution'];
177 $memberships = array();
178 if (!empty($objects['membership'])) {
179 $memberships = &$objects['membership'];
180 if (is_numeric($memberships)) {
181 $memberships = array($objects['membership']);
185 $addLineItems = FALSE;
186 if (empty($contribution->id
)) {
187 $addLineItems = TRUE;
189 $participant = &$objects['participant'];
191 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
192 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
193 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
194 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
195 $contribution->contribution_status_id
= array_search('Failed', $contributionStatus);
196 $contribution->save();
198 //add lineitems for recurring payments
199 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
200 $this->addrecurLineItems($objects['contributionRecur']->id
, $contribution->id
, CRM_Core_DAO
::$_nullArray);
203 //add new soft credit against current contribution id and
204 //copy initial contribution custom fields for recurring contributions
205 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
206 $this->addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
207 $this->copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
210 if (empty($input['skipComponentSync'])) {
211 if (!empty($memberships)) {
212 // if transaction is failed then set "Cancelled" as membership status
213 $cancelStatusId = array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus());
214 foreach ($memberships as $membership) {
216 $membership->status_id
= $cancelStatusId;
219 //update related Memberships.
220 $params = array('status_id' => $cancelStatusId);
221 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
227 $participant->status_id
= 4;
228 $participant->save();
232 $transaction->commit();
233 CRM_Core_Error
::debug_log_message("Setting contribution status to failed");
234 //echo "Success: Setting contribution status to failed<p>";
239 * Handled pending contribution status
240 * @param array $objects
241 * @param object $transaction
244 function pending(&$objects, &$transaction) {
245 $transaction->commit();
246 CRM_Core_Error
::debug_log_message("returning since contribution status is pending");
247 echo "Success: Returning since contribution status is pending<p>";
253 * @param $transaction
254 * @param array $input
258 function cancelled(&$objects, &$transaction, $input = array()) {
259 $contribution = &$objects['contribution'];
260 $memberships = &$objects['membership'];
261 if (is_numeric($memberships)) {
262 $memberships = array($objects['membership']);
265 $participant = &$objects['participant'];
266 $addLineItems = FALSE;
267 if (empty($contribution->id
)) {
268 $addLineItems = TRUE;
270 $contribution->contribution_status_id
= 3;
271 $contribution->cancel_date
= self
::$_now;
272 $contribution->cancel_reason
= CRM_Utils_Array
::value('reasonCode', $input);
273 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
274 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
275 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
276 $contribution->save();
278 //add lineitems for recurring payments
279 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
280 $this->addrecurLineItems($objects['contributionRecur']->id
, $contribution->id
, CRM_Core_DAO
::$_nullArray);
283 //add new soft credit against current $contribution and
284 //copy initial contribution custom fields for recurring contributions
285 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
286 $this->addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
287 $this->copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
290 if (empty($input['skipComponentSync'])) {
291 if (!empty($memberships)) {
292 foreach ($memberships as $membership) {
294 $membership->status_id
= 6;
297 //update related Memberships.
298 $params = array('status_id' => 6);
299 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
305 $participant->status_id
= 4;
306 $participant->save();
309 $transaction->commit();
310 CRM_Core_Error
::debug_log_message("Setting contribution status to cancelled");
311 //echo "Success: Setting contribution status to cancelled<p>";
317 * @param $transaction
321 function unhandled(&$objects, &$transaction) {
322 $transaction->rollback();
323 // we dont handle this as yet
324 CRM_Core_Error
::debug_log_message("returning since contribution status: $status is not handled");
325 echo "Failure: contribution status $status is not handled<p>";
333 * @param $transaction
336 function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) {
337 $contribution = &$objects['contribution'];
338 $memberships = &$objects['membership'];
339 if (is_numeric($memberships)) {
340 $memberships = array($objects['membership']);
342 $participant = &$objects['participant'];
343 $event = &$objects['event'];
344 $changeToday = CRM_Utils_Array
::value('trxn_date', $input, self
::$_now);
345 $recurContrib = &$objects['contributionRecur'];
349 if ($input['component'] == 'contribute') {
350 if ($contribution->contribution_page_id
) {
351 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
352 $source = ts('Online Contribution') . ': ' . $values['title'];
354 elseif ($recurContrib && $recurContrib->id
) {
355 $contribution->contribution_page_id
= NULL;
356 $values['amount'] = $recurContrib->amount
;
357 $values['financial_type_id'] = $objects['contributionType']->id
;
358 $values['title'] = $source = ts('Offline Recurring Contribution');
359 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
360 $values['receipt_from_name'] = $domainValues[0];
361 $values['receipt_from_email'] = $domainValues[1];
363 if($recurContrib && $recurContrib->id
){
364 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
365 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
368 $contribution->source
= $source;
369 if (!empty($values['is_email_receipt'])) {
370 $contribution->receipt_date
= self
::$_now;
373 if (!empty($memberships)) {
374 $membershipsUpdate = array( );
375 foreach ($memberships as $membershipTypeIdKey => $membership) {
379 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
380 $membership->membership_type_id
,
381 $membership->is_test
, $membership->id
384 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
385 // this picks up membership type changes during renewals
387 SELECT membership_type_id
388 FROM civicrm_membership_log
389 WHERE membership_id=$membership->id
392 $dao = new CRM_Core_DAO
;
395 if (!empty($dao->membership_type_id
)) {
396 $membership->membership_type_id
= $dao->membership_type_id
;
399 // else fall back to using current membership type
401 // else fall back to using current membership type
404 $num_terms = $contribution->getNumTermsByContributionAndMembershipType($membership->membership_type_id
);
405 if ($currentMembership) {
408 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
409 * when Contribution mode is notify and membership is for renewal )
411 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
413 // @todo - we should pass membership_type_id instead of null here but not
414 // adding as not sure of testing
415 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
416 $changeToday, NULL, $num_terms
419 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
422 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $num_terms);
425 //get the status for membership.
426 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
431 $membership->membership_type_id
,
435 $formatedParams = array('status_id' => CRM_Utils_Array
::value('id', $calcStatus, 2),
436 'join_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('join_date', $dates), $format),
437 'start_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('start_date', $dates), $format),
438 'end_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('end_date', $dates), $format),
440 //we might be renewing membership,
441 //so make status override false.
442 $formatedParams['is_override'] = FALSE;
443 $membership->copyValues($formatedParams);
446 //updating the membership log
447 $membershipLog = array();
448 $membershipLog = $formatedParams;
450 $logStartDate = $formatedParams['start_date'];
451 if (!empty($dates['log_start_date'])) {
452 $logStartDate = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
453 $logStartDate = CRM_Utils_Date
::isoToMysql($logStartDate);
456 $membershipLog['start_date'] = $logStartDate;
457 $membershipLog['membership_id'] = $membership->id
;
458 $membershipLog['modified_id'] = $membership->contact_id
;
459 $membershipLog['modified_date'] = date('Ymd');
460 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
462 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
464 //update related Memberships.
465 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formatedParams);
467 //update the membership type key of membership relatedObjects array
468 //if it has changed after membership update
469 if ($membershipTypeIdKey != $membership->membership_type_id
) {
470 $membershipsUpdate[$membership->membership_type_id
] = $membership;
471 $contribution->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
472 unset($contribution->_relatedObjects
['membership'][$membershipTypeIdKey]);
473 unset($memberships[$membershipTypeIdKey]);
477 //update the memberships object with updated membershipTypeId data
478 //if membershipTypeId has changed after membership update
479 if (!empty($membershipsUpdate)) {
480 $memberships = $memberships +
$membershipsUpdate;
486 $eventParams = array('id' => $objects['event']->id
);
487 $values['event'] = array();
489 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
491 //get location details
492 $locationParams = array('entity_id' => $objects['event']->id
, 'entity_table' => 'civicrm_event');
493 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
495 $ufJoinParams = array(
496 'entity_table' => 'civicrm_event',
497 'entity_id' => $ids['event'],
498 'module' => 'CiviEvent',
503 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
505 $values['custom_pre_id'] = $custom_pre_id;
506 $values['custom_post_id'] = $custom_post_ids;
507 //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
508 //and cases involving status updation through ipn
509 $values['totalAmount'] = $input['amount'];
511 $contribution->source
= ts('Online Event Registration') . ': ' . $values['event']['title'];
513 if ($values['event']['is_email_confirm']) {
514 $contribution->receipt_date
= self
::$_now;
515 $values['is_email_receipt'] = 1;
517 if (empty($input['skipComponentSync'])) {
518 $participant->status_id
= 1;
520 $participant->save();
523 if (CRM_Utils_Array
::value('net_amount', $input, 0) == 0 &&
524 CRM_Utils_Array
::value('fee_amount', $input, 0) != 0
526 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
528 $addLineItems = FALSE;
529 if (empty($contribution->id
)) {
530 $addLineItems = TRUE;
533 $contribution->contribution_status_id
= 1;
534 $contribution->is_test
= $input['is_test'];
535 $contribution->fee_amount
= CRM_Utils_Array
::value('fee_amount', $input, 0);
536 $contribution->net_amount
= CRM_Utils_Array
::value('net_amount', $input, 0);
537 $contribution->trxn_id
= $input['trxn_id'];
538 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
539 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
540 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
541 $contribution->cancel_date
= 'null';
543 if (!empty($input['check_number'])) {
544 $contribution->check_number
= $input['check_number'];
547 if (!empty($input['payment_instrument_id'])) {
548 $contribution->payment_instrument_id
= $input['payment_instrument_id'];
551 if ($contribution->id
) {
552 $contributionId['id'] = $contribution->id
;
553 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues($contributionId, CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
555 $contribution->save();
557 //add new soft credit against current $contribution and
558 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
559 $this->addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
562 //add lineitems for recurring payments
563 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
564 $this->addrecurLineItems($objects['contributionRecur']->id
, $contribution->id
, $input);
567 //copy initial contribution custom fields for recurring contributions
568 if ($recurContrib && $recurContrib->id
) {
569 $this->copyCustomValues($recurContrib->id
, $contribution->id
);
572 // next create the transaction record
573 $paymentProcessor = $paymentProcessorId = '';
574 if (isset($objects['paymentProcessor'])) {
575 if (is_array($objects['paymentProcessor'])) {
576 $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
577 $paymentProcessorId = $objects['paymentProcessor']['id'];
580 $paymentProcessor = $objects['paymentProcessor']->payment_processor_type
;
581 $paymentProcessorId = $objects['paymentProcessor']->id
;
584 //it's hard to see how it could reach this point without a contributon id as it is saved in line 511 above
585 // which raised the question as to whether this check preceded line 511 & if so whether something could be broken
586 // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code
587 // it would be good if someone added some comments or refactored this
588 if ($contribution->id
) {
589 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
590 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&&
591 - $input['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses))) {
592 $input['payment_processor'] = $paymentProcessorId;
594 $input['contribution_status_id'] = array_search('Completed', $contributionStatuses);
595 $input['total_amount'] = $input['amount'];
596 $input['contribution'] = $contribution;
597 $input['financial_type_id'] = $contribution->financial_type_id
;
599 if (!empty($contribution->_relatedObjects
['participant'])) {
600 $input['contribution_mode'] = 'participant';
601 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
602 $input['skipLineItem'] = 1;
604 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
605 // and subsequent payments. In this case the line items are created at $this->addrecurLineItems
606 // and since the contribution is saved prior to this line there is always a contribution-id,
607 // however there is never a prevContribution (which appears to mean original contribution not previous
608 // contribution - or preUpdateContributionObject most accurately)
609 // so, this is always called & only appears to succeed when prevContribution exists - which appears
610 // to mean "are we updating an exisitng pending contribution"
611 //I was able to make the unit test complete as fataling here doesn't prevent
612 // the contribution being created - but activities would not be created or emails sent
613 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
616 self
::updateRecurLinkedPledge($contribution);
618 // create an activity record
619 if ($input['component'] == 'contribute') {
621 $targetContactID = NULL;
622 if (!empty($ids['related_contact'])) {
623 $targetContactID = $contribution->contact_id
;
624 $contribution->contact_id
= $ids['related_contact'];
626 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
630 CRM_Activity_BAO_Activity
::addActivity($participant);
633 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
634 $transaction->commit();
636 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
637 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
638 if (!array_key_exists('is_email_receipt', $values) ||
639 $values['is_email_receipt'] == 1
641 self
::sendMail($input, $ids, $objects, $values, $recur, FALSE);
642 CRM_Core_Error
::debug_log_message("Receipt sent");
645 CRM_Core_Error
::debug_log_message("Success: Database updated");
653 function getBillingID(&$ids) {
654 // get the billing location type
655 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
656 // CRM-8108 remove the ts around the Billing locationtype
657 //$ids['billing'] = array_search( ts('Billing'), $locationTypes );
658 $ids['billing'] = array_search('Billing', $locationTypes);
659 if (!$ids['billing']) {
660 CRM_Core_Error
::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
661 echo "Failure: Could not find billing location type<p>";
668 * Send receipt from contribution. Note that the compose message part has been moved to contribution
669 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
671 * @params array $input Incoming data from Payment processor
672 * @params array $ids Related object IDs
673 * @params array $values values related to objects that have already been loaded
674 * @params bool $recur is it part of a recurring contribution
675 * @params bool $returnMessageText Should text be returned instead of sent. This
676 * is because the function is also used to generate pdfs
684 * @param bool $returnMessageText
688 function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
689 $contribution = &$objects['contribution'];
690 $input['is_recur'] = $recur;
691 // set receipt from e-mail and name in value
692 if (!$returnMessageText) {
693 $session = CRM_Core_Session
::singleton();
694 $userID = $session->get('userID');
695 if (!empty($userID)) {
696 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
697 $values['receipt_from_email'] = $userEmail;
698 $values['receipt_from_name'] = $userName;
701 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
705 * Update contribution status - this is only called from one place in the code &
706 * it is unclear whether it is a function on the way in or on the way out
708 * @param unknown_type $params
709 * @return void|Ambigous <value, unknown, array>
711 function updateContributionStatus(&$params) {
712 // get minimum required values.
713 $statusId = CRM_Utils_Array
::value('contribution_status_id', $params);
714 $componentId = CRM_Utils_Array
::value('component_id', $params);
715 $componentName = CRM_Utils_Array
::value('componentName', $params);
716 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
718 if (!$contributionId ||
!$componentId ||
!$componentName ||
!$statusId) {
722 $input = $ids = $objects = array();
724 //get the required ids.
725 $ids['contribution'] = $contributionId;
727 if (!$ids['contact'] = CRM_Utils_Array
::value('contact_id', $params)) {
728 $ids['contact'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
734 if ($componentName == 'Event') {
736 $ids['participant'] = $componentId;
738 if (!$ids['event'] = CRM_Utils_Array
::value('event_id', $params)) {
739 $ids['event'] = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
746 if ($componentName == 'Membership') {
747 $name = 'contribute';
748 $ids['membership'] = $componentId;
750 $ids['contributionPage'] = NULL;
751 $ids['contributionRecur'] = NULL;
752 $input['component'] = $name;
754 $baseIPN = new CRM_Core_Payment_BaseIPN();
755 $transaction = new CRM_Core_Transaction();
757 // reset template values.
758 $template = CRM_Core_Smarty
::singleton();
759 $template->clearTemplateVars();
761 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
762 CRM_Core_Error
::fatal();
765 $contribution = &$objects['contribution'];
767 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
768 $input['skipComponentSync'] = CRM_Utils_Array
::value('skipComponentSync', $params);
769 if ($statusId == array_search('Cancelled', $contributionStatuses)) {
770 $baseIPN->cancelled($objects, $transaction, $input);
771 $transaction->commit();
774 elseif ($statusId == array_search('Failed', $contributionStatuses)) {
775 $baseIPN->failed($objects, $transaction, $input);
776 $transaction->commit();
780 // status is not pending
781 if ($contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)) {
782 $transaction->commit();
786 //set values for ipn code.
788 'fee_amount', 'check_number', 'payment_instrument_id') as $field) {
789 if (!$input[$field] = CRM_Utils_Array
::value($field, $params)) {
790 $input[$field] = $contribution->$field;
793 if (!$input['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $params)) {
794 $input['trxn_id'] = $contribution->invoice_id
;
796 if (!$input['amount'] = CRM_Utils_Array
::value('total_amount', $params)) {
797 $input['amount'] = $contribution->total_amount
;
799 $input['is_test'] = $contribution->is_test
;
800 $input['net_amount'] = $contribution->net_amount
;
801 if (!empty($input['fee_amount']) && !empty($input['amount'])) {
802 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
805 //complete the contribution.
806 $baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
808 // reset template values before processing next transactions
809 $template->clearTemplateVars();
815 * Update pledge associated with a recurring contribution
817 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
819 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
820 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
821 * it should be assumed they
822 * do so with the intention that all payments will be linked
824 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
825 * If not the contribution will also need to be linked to the pledge
828 * @param $contribution
830 function updateRecurLinkedPledge(&$contribution) {
831 $returnProperties = array('id', 'pledge_id');
832 $paymentDetails = $paymentIDs = array();
834 if (CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id
,
835 $paymentDetails, $returnProperties
837 foreach ($paymentDetails as $key => $value) {
838 $paymentIDs[] = $value['id'];
839 $pledgeId = $value['pledge_id'];
843 //payment is not already linked - if it is linked with a pledge we need to create a link.
844 // return if it is not recurring contribution
845 if (!$contribution->contribution_recur_id
) {
849 $relatedContributions = new CRM_Contribute_DAO_Contribution();
850 $relatedContributions->contribution_recur_id
= $contribution->contribution_recur_id
;
851 $relatedContributions->find();
853 while ($relatedContributions->fetch()) {
854 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id
,
855 $paymentDetails, $returnProperties
859 if (empty($paymentDetails)) {
860 // payment is not linked with a pledge and neither are any other contributions on this
864 foreach ($paymentDetails as $key => $value) {
865 $pledgeId = $value['pledge_id'];
868 // we have a pledge now we need to get the oldest unpaid payment
869 $paymentDetails = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeId);
870 if(empty($paymentDetails['id'])){
871 // we can assume this pledge is now completed
872 // return now so we don't create a core error & roll back
875 $paymentDetails['contribution_id'] = $contribution->id
;
876 $paymentDetails['status_id'] = $contribution->contribution_status_id
;
877 $paymentDetails['actual_amount'] = $contribution->total_amount
;
879 // put contribution against it
880 $payment = CRM_Pledge_BAO_PledgePayment
::add($paymentDetails);
881 $paymentIDs[] = $payment->id
;
884 // update pledge and corresponding payment statuses
885 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id
,
886 NULL, $contribution->total_amount
892 * @param $contributionId
895 function addrecurLineItems($recurId, $contributionId, &$input) {
896 $lineSets = $lineItems = array();
898 //Get the first contribution id with recur id
900 $contriID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
901 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($contriID, 'contribution');
902 if (!empty($lineItems)) {
903 foreach ($lineItems as $key => $value) {
904 $pricesetID = new CRM_Price_DAO_PriceField();
905 $pricesetID->id
= $value['price_field_id'];
906 $pricesetID->find(TRUE);
907 $lineSets[$pricesetID->price_set_id
][] = $value;
910 if (!empty($input)) {
911 $input['line_item'] = $lineSets;
914 CRM_Price_BAO_LineItem
::processPriceSet($contributionId, $lineSets);
919 // function to copy custom data of the
920 // initial contribution into its recurring contributions
923 * @param $targetContributionId
925 function copyCustomValues($recurId, $targetContributionId) {
926 if ($recurId && $targetContributionId) {
927 // get the initial contribution id of recur id
928 $sourceContributionId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
930 // if the same contribution is being proccessed then return
931 if ($sourceContributionId == $targetContributionId) {
934 // check if proper recurring contribution record is being processed
935 $targetConRecurId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
936 if ($targetConRecurId != $recurId) {
941 $extends = array('Contribution');
942 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
944 foreach ($groupTree as $groupID => $group) {
945 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
946 foreach ($group['fields'] as $fieldID => $field) {
947 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
951 foreach ($table as $tableName => $tableColumns) {
952 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
953 $tableColumns[0] = $targetContributionId;
954 $select = 'SELECT ' . implode(', ', $tableColumns);
955 $from = ' FROM ' . $tableName;
956 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
957 $query = $insert . $select . $from . $where;
958 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
964 // function to copy soft credit record of first recurring contribution
965 // and add new soft credit against $targetContributionId
968 * @param $targetContributionId
970 function addrecurSoftCredit($recurId, $targetContributionId) {
971 $contriID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
973 $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
974 $soft_contribution->contribution_id
= $contriID;
976 //check if first recurring contribution has any associated soft credit
977 if ($soft_contribution->find(TRUE)) {
978 $soft_contribution->contribution_id
= $targetContributionId;
979 unset($soft_contribution->id
);
980 $soft_contribution->save();