3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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
55 * @param array $parameters
56 * @throws CRM_Core_Exceptions
58 function setInputParameters($parameters) {
59 if(!is_array($parameters)) {
60 throw new CRM_Core_Exception('Invalid input parameters');
62 $this->_inputParameters
= $parameters;
65 * Validate incoming data. This function is intended to ensure that incoming data matches
66 * It provides a form of pseudo-authentication - by checking the calling fn already knows
67 * the correct contact id & contribution id (this can be problematic when that has changed in
68 * the meantime for transactions that are delayed & contacts are merged in-between. e.g
69 * Paypal allows you to resend Instant Payment Notifications if you, for example, moved site
70 * and didn't update your IPN URL.
72 * @param array $input interpreted values from the values returned through the IPN
73 * @param array $ids more interpreted values (ids) from the values returned through the IPN
74 * @param array $objects an empty array that will be populated with loaded object
75 * @param boolean $required boolean Return FALSE if the relevant objects don't exist
76 * @param integer $paymentProcessorID Id of the payment processor ID in use
79 function validateData(&$input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
81 // make sure contact exists and is valid
82 $contact = new CRM_Contact_BAO_Contact();
83 $contact->id
= $ids['contact'];
84 if (!$contact->find(TRUE)) {
85 CRM_Core_Error
::debug_log_message("Could not find contact record: {$ids['contact']} in IPN request: ".print_r($input, TRUE));
86 echo "Failure: Could not find contact record: {$ids['contact']}<p>";
90 // make sure contribution exists and is valid
91 $contribution = new CRM_Contribute_BAO_Contribution();
92 $contribution->id
= $ids['contribution'];
93 if (!$contribution->find(TRUE)) {
94 CRM_Core_Error
::debug_log_message("Could not find contribution record: {$contribution->id} in IPN request: ".print_r($input, TRUE));
95 echo "Failure: Could not find contribution record for {$contribution->id}<p>";
98 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
100 $objects['contact'] = &$contact;
101 $objects['contribution'] = &$contribution;
102 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
110 * Load objects related to contribution
112 * @input array information from Payment processor
114 * @param array $objects
115 * @param boolean $required
116 * @param integer $paymentProcessorID
117 * @param array $error_handling
118 * @return multitype:number NULL |boolean
120 function loadObjects(&$input, &$ids, &$objects, $required, $paymentProcessorID, $error_handling = NULL) {
121 if (empty($error_handling)) {
122 // default options are that we log an error & echo it out
123 // note that we should refactor this error handling into error code @ some point
124 // but for now setting up enough separation so we can do unit tests
125 $error_handling = array(
130 $ids['paymentProcessor'] = $paymentProcessorID;
131 if (is_a($objects['contribution'], 'CRM_Contribute_BAO_Contribution')) {
132 $contribution = &$objects['contribution'];
135 //legacy support - functions are 'used' to be able to pass in a DAO
136 $contribution = new CRM_Contribute_BAO_Contribution();
137 $contribution->id
= CRM_Utils_Array
::value('contribution', $ids);
138 $contribution->find(TRUE);
139 $objects['contribution'] = &$contribution;
142 $success = $contribution->loadRelatedObjects($input, $ids, $required);
144 catch(Exception
$e) {
146 if (!empty($error_handling['log_error'])) {
147 CRM_Core_Error
::debug_log_message($e->getMessage());
149 if (!empty($error_handling['echo_error'])) {
150 echo ($e->getMessage());
152 if (!empty($error_handling['return_error'])) {
155 'error_message' => ($e->getMessage()),
159 $objects = array_merge($objects, $contribution->_relatedObjects
);
164 * Set contribution to failed
165 * @param array $objects
166 * @param object $transaction
167 * @param array $input
170 function failed(&$objects, &$transaction, $input = array()) {
171 $contribution = &$objects['contribution'];
172 $memberships = array();
173 if (!empty($objects['membership'])) {
174 $memberships = &$objects['membership'];
175 if (is_numeric($memberships)) {
176 $memberships = array($objects['membership']);
180 $addLineItems = FALSE;
181 if (empty($contribution->id
)) {
182 $addLineItems = TRUE;
184 $participant = &$objects['participant'];
186 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
187 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
188 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
189 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
190 $contribution->contribution_status_id
= array_search('Failed', $contributionStatus);
191 $contribution->save();
193 //add lineitems for recurring payments
194 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
195 $this->addrecurLineItems($objects['contributionRecur']->id
, $contribution->id
, CRM_Core_DAO
::$_nullArray);
198 //copy initial contribution custom fields for recurring contributions
199 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
200 $this->copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
203 if (empty($input['skipComponentSync'])) {
204 if (!empty($memberships)) {
205 // if transaction is failed then set "Cancelled" as membership status
206 $cancelStatusId = array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus());
207 foreach ($memberships as $membership) {
209 $membership->status_id
= $cancelStatusId;
212 //update related Memberships.
213 $params = array('status_id' => $cancelStatusId);
214 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
220 $participant->status_id
= 4;
221 $participant->save();
225 $transaction->commit();
226 CRM_Core_Error
::debug_log_message("Setting contribution status to failed");
227 //echo "Success: Setting contribution status to failed<p>";
232 * Handled pending contribution status
233 * @param array $objects
234 * @param object $transaction
237 function pending(&$objects, &$transaction) {
238 $transaction->commit();
239 CRM_Core_Error
::debug_log_message("returning since contribution status is pending");
240 echo "Success: Returning since contribution status is pending<p>";
244 function cancelled(&$objects, &$transaction, $input = array()) {
245 $contribution = &$objects['contribution'];
246 $memberships = &$objects['membership'];
247 if (is_numeric($memberships)) {
248 $memberships = array($objects['membership']);
251 $participant = &$objects['participant'];
252 $addLineItems = FALSE;
253 if (empty($contribution->id
)) {
254 $addLineItems = TRUE;
256 $contribution->contribution_status_id
= 3;
257 $contribution->cancel_date
= self
::$_now;
258 $contribution->cancel_reason
= CRM_Utils_Array
::value('reasonCode', $input);
259 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
260 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
261 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
262 $contribution->save();
264 //add lineitems for recurring payments
265 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
266 $this->addrecurLineItems($objects['contributionRecur']->id
, $contribution->id
, CRM_Core_DAO
::$_nullArray);
269 //copy initial contribution custom fields for recurring contributions
270 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
271 $this->copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
274 if (empty($input['skipComponentSync'])) {
275 if (!empty($memberships)) {
276 foreach ($memberships as $membership) {
278 $membership->status_id
= 6;
281 //update related Memberships.
282 $params = array('status_id' => 6);
283 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
289 $participant->status_id
= 4;
290 $participant->save();
293 $transaction->commit();
294 CRM_Core_Error
::debug_log_message("Setting contribution status to cancelled");
295 //echo "Success: Setting contribution status to cancelled<p>";
299 function unhandled(&$objects, &$transaction) {
300 $transaction->rollback();
301 // we dont handle this as yet
302 CRM_Core_Error
::debug_log_message("returning since contribution status: $status is not handled");
303 echo "Failure: contribution status $status is not handled<p>";
307 function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) {
308 $contribution = &$objects['contribution'];
309 $memberships = &$objects['membership'];
310 if (is_numeric($memberships)) {
311 $memberships = array($objects['membership']);
313 $participant = &$objects['participant'];
314 $event = &$objects['event'];
315 $changeToday = CRM_Utils_Array
::value('trxn_date', $input, self
::$_now);
316 $recurContrib = &$objects['contributionRecur'];
320 if ($input['component'] == 'contribute') {
321 if ($contribution->contribution_page_id
) {
322 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
323 $source = ts('Online Contribution') . ': ' . $values['title'];
325 elseif ($recurContrib && $recurContrib->id
) {
326 $contribution->contribution_page_id
= NULL;
327 $values['amount'] = $recurContrib->amount
;
328 $values['financial_type_id'] = $objects['contributionType']->id
;
329 $values['title'] = $source = ts('Offline Recurring Contribution');
330 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
331 $values['receipt_from_name'] = $domainValues[0];
332 $values['receipt_from_email'] = $domainValues[1];
334 if($recurContrib && $recurContrib->id
){
335 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
336 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
339 $contribution->source
= $source;
340 if (!empty($values['is_email_receipt'])) {
341 $contribution->receipt_date
= self
::$_now;
344 if (!empty($memberships)) {
345 $membershipsUpdate = array( );
346 foreach ($memberships as $membershipTypeIdKey => $membership) {
350 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
351 $membership->membership_type_id
,
352 $membership->is_test
, $membership->id
355 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
356 // this picks up membership type changes during renewals
358 SELECT membership_type_id
359 FROM civicrm_membership_log
360 WHERE membership_id=$membership->id
363 $dao = new CRM_Core_DAO
;
366 if (!empty($dao->membership_type_id
)) {
367 $membership->membership_type_id
= $dao->membership_type_id
;
370 // else fall back to using current membership type
372 // else fall back to using current membership type
375 if ($currentMembership) {
378 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
379 * when Contribution mode is notify and membership is for renewal )
381 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
383 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
386 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
389 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
);
392 //get the status for membership.
393 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
400 $formatedParams = array('status_id' => CRM_Utils_Array
::value('id', $calcStatus, 2),
401 'join_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('join_date', $dates), $format),
402 'start_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('start_date', $dates), $format),
403 'end_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('end_date', $dates), $format),
405 //we might be renewing membership,
406 //so make status override false.
407 $formatedParams['is_override'] = FALSE;
408 $membership->copyValues($formatedParams);
411 //updating the membership log
412 $membershipLog = array();
413 $membershipLog = $formatedParams;
415 $logStartDate = $formatedParams['start_date'];
416 if (!empty($dates['log_start_date'])) {
417 $logStartDate = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
418 $logStartDate = CRM_Utils_Date
::isoToMysql($logStartDate);
421 $membershipLog['start_date'] = $logStartDate;
422 $membershipLog['membership_id'] = $membership->id
;
423 $membershipLog['modified_id'] = $membership->contact_id
;
424 $membershipLog['modified_date'] = date('Ymd');
425 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
427 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
429 //update related Memberships.
430 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formatedParams);
432 //update the membership type key of membership relatedObjects array
433 //if it has changed after membership update
434 if ($membershipTypeIdKey != $membership->membership_type_id
) {
435 $membershipsUpdate[$membership->membership_type_id
] = $membership;
436 $contribution->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
437 unset($contribution->_relatedObjects
['membership'][$membershipTypeIdKey]);
438 unset($memberships[$membershipTypeIdKey]);
442 //update the memberships object with updated membershipTypeId data
443 //if membershipTypeId has changed after membership update
444 if (!empty($membershipsUpdate)) {
445 $memberships = $memberships +
$membershipsUpdate;
451 $eventParams = array('id' => $objects['event']->id
);
452 $values['event'] = array();
454 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
456 //get location details
457 $locationParams = array('entity_id' => $objects['event']->id
, 'entity_table' => 'civicrm_event');
458 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
460 $ufJoinParams = array(
461 'entity_table' => 'civicrm_event',
462 'entity_id' => $ids['event'],
463 'module' => 'CiviEvent',
468 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
470 $values['custom_pre_id'] = $custom_pre_id;
471 $values['custom_post_id'] = $custom_post_ids;
472 //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
473 //and cases involving status updation through ipn
474 $values['totalAmount'] = $input['amount'];
476 $contribution->source
= ts('Online Event Registration') . ': ' . $values['event']['title'];
478 if ($values['event']['is_email_confirm']) {
479 $contribution->receipt_date
= self
::$_now;
480 $values['is_email_receipt'] = 1;
482 if (empty($input['skipComponentSync'])) {
483 $participant->status_id
= 1;
485 $participant->save();
488 if (CRM_Utils_Array
::value('net_amount', $input, 0) == 0 &&
489 CRM_Utils_Array
::value('fee_amount', $input, 0) != 0
491 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
493 $addLineItems = FALSE;
494 if (empty($contribution->id
)) {
495 $addLineItems = TRUE;
498 $contribution->contribution_status_id
= 1;
499 $contribution->is_test
= $input['is_test'];
500 $contribution->fee_amount
= CRM_Utils_Array
::value('fee_amount', $input, 0);
501 $contribution->net_amount
= CRM_Utils_Array
::value('net_amount', $input, 0);
502 $contribution->trxn_id
= $input['trxn_id'];
503 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
504 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
505 $contribution->cancel_date
= 'null';
507 if (!empty($input['check_number'])) {
508 $contribution->check_number
= $input['check_number'];
511 if (!empty($input['payment_instrument_id'])) {
512 $contribution->payment_instrument_id
= $input['payment_instrument_id'];
515 if ($contribution->id
) {
516 $contributionId['id'] = $contribution->id
;
517 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues($contributionId, CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
519 $contribution->save();
521 //add lineitems for recurring payments
522 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
523 $this->addrecurLineItems($objects['contributionRecur']->id
, $contribution->id
, $input);
526 //copy initial contribution custom fields for recurring contributions
527 if ($recurContrib && $recurContrib->id
) {
528 $this->copyCustomValues($recurContrib->id
, $contribution->id
);
531 // next create the transaction record
532 $paymentProcessor = $paymentProcessorId = '';
533 if (isset($objects['paymentProcessor'])) {
534 if (is_array($objects['paymentProcessor'])) {
535 $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
536 $paymentProcessorId = $objects['paymentProcessor']['id'];
539 $paymentProcessor = $objects['paymentProcessor']->payment_processor_type
;
540 $paymentProcessorId = $objects['paymentProcessor']->id
;
543 //it's hard to see how it could reach this point without a contributon id as it is saved in line 511 above
544 // which raised the question as to whether this check preceded line 511 & if so whether something could be broken
545 // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code
546 // it would be good if someone added some comments or refactored this
547 if ($contribution->id
) {
548 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
549 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&&
550 - $input['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses))) {
551 $input['payment_processor'] = $paymentProcessorId;
553 $input['contribution_status_id'] = array_search('Completed', $contributionStatuses);
554 $input['total_amount'] = $input['amount'];
555 $input['contribution'] = $contribution;
556 $input['financial_type_id'] = $contribution->financial_type_id
;
558 if (!empty($contribution->_relatedObjects
['participant'])) {
559 $input['contribution_mode'] = 'participant';
560 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
561 $input['skipLineItem'] = 1;
563 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
564 // and subsequent payments. In this case the line items are created at $this->addrecurLineItems
565 // and since the contribution is saved prior to this line there is always a contribution-id,
566 // however there is never a prevContribution (which appears to mean original contribution not previous
567 // contribution - or preUpdateContributionObject most accurately)
568 // so, this is always called & only appears to succeed when prevContribution exists - which appears
569 // to mean "are we updating an exisitng pending contribution"
570 //I was able to make the unit test complete as fataling here doesn't prevent
571 // the contribution being created - but activities would not be created or emails sent
572 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
575 self
::updateRecurLinkedPledge($contribution);
577 // create an activity record
578 if ($input['component'] == 'contribute') {
580 $targetContactID = NULL;
581 if (!empty($ids['related_contact'])) {
582 $targetContactID = $contribution->contact_id
;
583 $contribution->contact_id
= $ids['related_contact'];
585 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
589 CRM_Activity_BAO_Activity
::addActivity($participant);
592 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
593 $transaction->commit();
595 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
596 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
597 if (!array_key_exists('is_email_receipt', $values) ||
598 $values['is_email_receipt'] == 1
600 self
::sendMail($input, $ids, $objects, $values, $recur, FALSE);
601 CRM_Core_Error
::debug_log_message("Receipt sent");
604 CRM_Core_Error
::debug_log_message("Success: Database updated");
607 function getBillingID(&$ids) {
608 // get the billing location type
609 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
610 // CRM-8108 remove the ts around the Billing locationtype
611 //$ids['billing'] = array_search( ts('Billing'), $locationTypes );
612 $ids['billing'] = array_search('Billing', $locationTypes);
613 if (!$ids['billing']) {
614 CRM_Core_Error
::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
615 echo "Failure: Could not find billing location type<p>";
622 * Send receipt from contribution. Note that the compose message part has been moved to contribution
623 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
625 * @params array $input Incoming data from Payment processor
626 * @params array $ids Related object IDs
627 * @params array $values values related to objects that have already been loaded
628 * @params bool $recur is it part of a recurring contribution
629 * @params bool $returnMessageText Should text be returned instead of sent. This
630 * is because the function is also used to generate pdfs
632 function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
633 $contribution = &$objects['contribution'];
634 $input['is_recur'] = $recur;
635 // set receipt from e-mail and name in value
636 if (!$returnMessageText) {
637 $session = CRM_Core_Session
::singleton();
638 $userID = $session->get('userID');
639 if (!empty($userID)) {
640 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
641 $values['receipt_from_email'] = $userEmail;
642 $values['receipt_from_name'] = $userName;
645 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
649 * Update contribution status - this is only called from one place in the code &
650 * it is unclear whether it is a function on the way in or on the way out
652 * @param unknown_type $params
653 * @return void|Ambigous <value, unknown, array>
655 function updateContributionStatus(&$params) {
656 // get minimum required values.
657 $statusId = CRM_Utils_Array
::value('contribution_status_id', $params);
658 $componentId = CRM_Utils_Array
::value('component_id', $params);
659 $componentName = CRM_Utils_Array
::value('componentName', $params);
660 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
662 if (!$contributionId ||
!$componentId ||
!$componentName ||
!$statusId) {
666 $input = $ids = $objects = array();
668 //get the required ids.
669 $ids['contribution'] = $contributionId;
671 if (!$ids['contact'] = CRM_Utils_Array
::value('contact_id', $params)) {
672 $ids['contact'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
678 if ($componentName == 'Event') {
680 $ids['participant'] = $componentId;
682 if (!$ids['event'] = CRM_Utils_Array
::value('event_id', $params)) {
683 $ids['event'] = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
690 if ($componentName == 'Membership') {
691 $name = 'contribute';
692 $ids['membership'] = $componentId;
694 $ids['contributionPage'] = NULL;
695 $ids['contributionRecur'] = NULL;
696 $input['component'] = $name;
698 $baseIPN = new CRM_Core_Payment_BaseIPN();
699 $transaction = new CRM_Core_Transaction();
701 // reset template values.
702 $template = CRM_Core_Smarty
::singleton();
703 $template->clearTemplateVars();
705 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
706 CRM_Core_Error
::fatal();
709 $contribution = &$objects['contribution'];
711 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
712 $input['skipComponentSync'] = CRM_Utils_Array
::value('skipComponentSync', $params);
713 if ($statusId == array_search('Cancelled', $contributionStatuses)) {
714 $baseIPN->cancelled($objects, $transaction, $input);
715 $transaction->commit();
718 elseif ($statusId == array_search('Failed', $contributionStatuses)) {
719 $baseIPN->failed($objects, $transaction, $input);
720 $transaction->commit();
724 // status is not pending
725 if ($contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)) {
726 $transaction->commit();
730 //set values for ipn code.
732 'fee_amount', 'check_number', 'payment_instrument_id') as $field) {
733 if (!$input[$field] = CRM_Utils_Array
::value($field, $params)) {
734 $input[$field] = $contribution->$field;
737 if (!$input['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $params)) {
738 $input['trxn_id'] = $contribution->invoice_id
;
740 if (!$input['amount'] = CRM_Utils_Array
::value('total_amount', $params)) {
741 $input['amount'] = $contribution->total_amount
;
743 $input['is_test'] = $contribution->is_test
;
744 $input['net_amount'] = $contribution->net_amount
;
745 if (!empty($input['fee_amount']) && !empty($input['amount'])) {
746 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
749 //complete the contribution.
750 $baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
752 // reset template values before processing next transactions
753 $template->clearTemplateVars();
759 * Update pledge associated with a recurring contribution
761 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
763 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
764 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
765 * it should be assumed they
766 * do so with the intention that all payments will be linked
768 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
769 * If not the contribution will also need to be linked to the pledge
771 function updateRecurLinkedPledge(&$contribution) {
772 $returnProperties = array('id', 'pledge_id');
773 $paymentDetails = $paymentIDs = array();
775 if (CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id
,
776 $paymentDetails, $returnProperties
778 foreach ($paymentDetails as $key => $value) {
779 $paymentIDs[] = $value['id'];
780 $pledgeId = $value['pledge_id'];
784 //payment is not already linked - if it is linked with a pledge we need to create a link.
785 // return if it is not recurring contribution
786 if (!$contribution->contribution_recur_id
) {
790 $relatedContributions = new CRM_Contribute_DAO_Contribution();
791 $relatedContributions->contribution_recur_id
= $contribution->contribution_recur_id
;
792 $relatedContributions->find();
794 while ($relatedContributions->fetch()) {
795 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id
,
796 $paymentDetails, $returnProperties
800 if (empty($paymentDetails)) {
801 // payment is not linked with a pledge and neither are any other contributions on this
805 foreach ($paymentDetails as $key => $value) {
806 $pledgeId = $value['pledge_id'];
809 // we have a pledge now we need to get the oldest unpaid payment
810 $paymentDetails = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeId);
811 if(empty($paymentDetails['id'])){
812 // we can assume this pledge is now completed
813 // return now so we don't create a core error & roll back
816 $paymentDetails['contribution_id'] = $contribution->id
;
817 $paymentDetails['status_id'] = $contribution->contribution_status_id
;
818 $paymentDetails['actual_amount'] = $contribution->total_amount
;
820 // put contribution against it
821 $payment = CRM_Pledge_BAO_PledgePayment
::add($paymentDetails);
822 $paymentIDs[] = $payment->id
;
825 // update pledge and corresponding payment statuses
826 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id
,
827 NULL, $contribution->total_amount
831 function addrecurLineItems($recurId, $contributionId, &$input) {
832 $lineSets = $lineItems = array();
834 //Get the first contribution id with recur id
836 $contriID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
837 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($contriID, 'contribution');
838 if (!empty($lineItems)) {
839 foreach ($lineItems as $key => $value) {
840 $pricesetID = new CRM_Price_DAO_PriceField();
841 $pricesetID->id
= $value['price_field_id'];
842 $pricesetID->find(TRUE);
843 $lineSets[$pricesetID->price_set_id
][] = $value;
846 if (!empty($input)) {
847 $input['line_item'] = $lineSets;
850 CRM_Price_BAO_LineItem
::processPriceSet($contributionId, $lineSets);
855 // function to copy custom data of the
856 // initial contribution into its recurring contributions
857 function copyCustomValues($recurId, $targetContributionId) {
858 if ($recurId && $targetContributionId) {
859 // get the initial contribution id of recur id
860 $sourceContributionId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
862 // if the same contribution is being proccessed then return
863 if ($sourceContributionId == $targetContributionId) {
866 // check if proper recurring contribution record is being processed
867 $targetConRecurId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
868 if ($targetConRecurId != $recurId) {
873 $extends = array('Contribution');
874 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
876 foreach ($groupTree as $groupID => $group) {
877 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
878 foreach ($group['fields'] as $fieldID => $field) {
879 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
883 foreach ($table as $tableName => $tableColumns) {
884 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
885 $tableColumns[0] = $targetContributionId;
886 $select = 'SELECT ' . implode(', ', $tableColumns);
887 $from = ' FROM ' . $tableName;
888 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
889 $query = $insert . $select . $from . $where;
890 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);