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 (CRM_Utils_Array
::value('log_error', $error_handling)) {
147 CRM_Core_Error
::debug_log_message($e->getMessage());
149 if (CRM_Utils_Array
::value('echo_error', $error_handling)) {
150 echo ($e->getMessage());
152 if (CRM_Utils_Array
::value('return_error', $error_handling)) {
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 (CRM_Utils_Array
::value('membership', $objects)) {
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 (CRM_Utils_Array
::value('contributionRecur', $objects) && $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 (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
200 $this->copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
203 if (!CRM_Utils_Array
::value('skipComponentSync', $input)) {
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 (CRM_Utils_Array
::value('contributionRecur', $objects) && $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 (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
271 $this->copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
274 if (!CRM_Utils_Array
::value('skipComponentSync', $input)) {
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 (CRM_Utils_Array
::value('is_email_receipt', $values)) {
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 (CRM_Utils_Array
::value('log_start_date', $dates)) {
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 (!CRM_Utils_Array
::value('skipComponentSync', $input)) {
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->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
506 $contribution->cancel_date
= 'null';
508 if (CRM_Utils_Array
::value('check_number', $input)) {
509 $contribution->check_number
= $input['check_number'];
512 if (CRM_Utils_Array
::value('payment_instrument_id', $input)) {
513 $contribution->payment_instrument_id
= $input['payment_instrument_id'];
516 if ($contribution->id
) {
517 $contributionId['id'] = $contribution->id
;
518 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues($contributionId, CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
520 $contribution->save();
522 //add lineitems for recurring payments
523 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
&& $addLineItems) {
524 $this->addrecurLineItems($objects['contributionRecur']->id
, $contribution->id
, $input);
527 //copy initial contribution custom fields for recurring contributions
528 if ($recurContrib && $recurContrib->id
) {
529 $this->copyCustomValues($recurContrib->id
, $contribution->id
);
532 // next create the transaction record
533 $paymentProcessor = $paymentProcessorId = '';
534 if (isset($objects['paymentProcessor'])) {
535 if (is_array($objects['paymentProcessor'])) {
536 $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
537 $paymentProcessorId = $objects['paymentProcessor']['id'];
540 $paymentProcessor = $objects['paymentProcessor']->payment_processor_type
;
541 $paymentProcessorId = $objects['paymentProcessor']->id
;
544 //it's hard to see how it could reach this point without a contributon id as it is saved in line 511 above
545 // which raised the question as to whether this check preceded line 511 & if so whether something could be broken
546 // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code
547 // it would be good if someone added some comments or refactored this
548 if ($contribution->id
) {
549 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
550 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&&
551 - $input['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses))) {
552 $input['payment_processor'] = $paymentProcessorId;
554 $input['contribution_status_id'] = array_search('Completed', $contributionStatuses);
555 $input['total_amount'] = $input['amount'];
556 $input['contribution'] = $contribution;
557 $input['financial_type_id'] = $contribution->financial_type_id
;
559 if (CRM_Utils_Array
::value('participant', $contribution->_relatedObjects
)) {
560 $input['contribution_mode'] = 'participant';
561 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
562 $input['skipLineItem'] = 1;
564 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
565 // and subsequent payments. In this case the line items are created at $this->addrecurLineItems
566 // and since the contribution is saved prior to this line there is always a contribution-id,
567 // however there is never a prevContribution (which appears to mean original contribution not previous
568 // contribution - or preUpdateContributionObject most accurately)
569 // so, this is always called & only appears to succeed when prevContribution exists - which appears
570 // to mean "are we updating an exisitng pending contribution"
571 //I was able to make the unit test complete as fataling here doesn't prevent
572 // the contribution being created - but activities would not be created or emails sent
573 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
576 self
::updateRecurLinkedPledge($contribution);
578 // create an activity record
579 if ($input['component'] == 'contribute') {
581 $targetContactID = NULL;
582 if (CRM_Utils_Array
::value('related_contact', $ids)) {
583 $targetContactID = $contribution->contact_id
;
584 $contribution->contact_id
= $ids['related_contact'];
586 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
590 CRM_Activity_BAO_Activity
::addActivity($participant);
593 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
594 $transaction->commit();
596 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
597 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
598 if (!array_key_exists('is_email_receipt', $values) ||
599 $values['is_email_receipt'] == 1
601 self
::sendMail($input, $ids, $objects, $values, $recur, FALSE);
602 CRM_Core_Error
::debug_log_message("Receipt sent");
605 CRM_Core_Error
::debug_log_message("Success: Database updated");
608 function getBillingID(&$ids) {
609 // get the billing location type
610 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
611 // CRM-8108 remove the ts around the Billing locationtype
612 //$ids['billing'] = array_search( ts('Billing'), $locationTypes );
613 $ids['billing'] = array_search('Billing', $locationTypes);
614 if (!$ids['billing']) {
615 CRM_Core_Error
::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
616 echo "Failure: Could not find billing location type<p>";
623 * Send receipt from contribution. Note that the compose message part has been moved to contribution
624 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
626 * @params array $input Incoming data from Payment processor
627 * @params array $ids Related object IDs
628 * @params array $values values related to objects that have already been loaded
629 * @params bool $recur is it part of a recurring contribution
630 * @params bool $returnMessageText Should text be returned instead of sent. This
631 * is because the function is also used to generate pdfs
633 function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
634 $contribution = &$objects['contribution'];
635 $input['is_recur'] = $recur;
636 // set receipt from e-mail and name in value
637 if (!$returnMessageText) {
638 $session = CRM_Core_Session
::singleton();
639 $userID = $session->get('userID');
640 if (!empty($userID)) {
641 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
642 $values['receipt_from_email'] = $userEmail;
643 $values['receipt_from_name'] = $userName;
646 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
650 * Update contribution status - this is only called from one place in the code &
651 * it is unclear whether it is a function on the way in or on the way out
653 * @param unknown_type $params
654 * @return void|Ambigous <value, unknown, array>
656 function updateContributionStatus(&$params) {
657 // get minimum required values.
658 $statusId = CRM_Utils_Array
::value('contribution_status_id', $params);
659 $componentId = CRM_Utils_Array
::value('component_id', $params);
660 $componentName = CRM_Utils_Array
::value('componentName', $params);
661 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
663 if (!$contributionId ||
!$componentId ||
!$componentName ||
!$statusId) {
667 $input = $ids = $objects = array();
669 //get the required ids.
670 $ids['contribution'] = $contributionId;
672 if (!$ids['contact'] = CRM_Utils_Array
::value('contact_id', $params)) {
673 $ids['contact'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
679 if ($componentName == 'Event') {
681 $ids['participant'] = $componentId;
683 if (!$ids['event'] = CRM_Utils_Array
::value('event_id', $params)) {
684 $ids['event'] = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
691 if ($componentName == 'Membership') {
692 $name = 'contribute';
693 $ids['membership'] = $componentId;
695 $ids['contributionPage'] = NULL;
696 $ids['contributionRecur'] = NULL;
697 $input['component'] = $name;
699 $baseIPN = new CRM_Core_Payment_BaseIPN();
700 $transaction = new CRM_Core_Transaction();
702 // reset template values.
703 $template = CRM_Core_Smarty
::singleton();
704 $template->clearTemplateVars();
706 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
707 CRM_Core_Error
::fatal();
710 $contribution = &$objects['contribution'];
712 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
713 $input['skipComponentSync'] = CRM_Utils_Array
::value('skipComponentSync', $params);
714 if ($statusId == array_search('Cancelled', $contributionStatuses)) {
715 $baseIPN->cancelled($objects, $transaction, $input);
716 $transaction->commit();
719 elseif ($statusId == array_search('Failed', $contributionStatuses)) {
720 $baseIPN->failed($objects, $transaction, $input);
721 $transaction->commit();
725 // status is not pending
726 if ($contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)) {
727 $transaction->commit();
731 //set values for ipn code.
733 'fee_amount', 'check_number', 'payment_instrument_id') as $field) {
734 if (!$input[$field] = CRM_Utils_Array
::value($field, $params)) {
735 $input[$field] = $contribution->$field;
738 if (!$input['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $params)) {
739 $input['trxn_id'] = $contribution->invoice_id
;
741 if (!$input['amount'] = CRM_Utils_Array
::value('total_amount', $params)) {
742 $input['amount'] = $contribution->total_amount
;
744 $input['is_test'] = $contribution->is_test
;
745 $input['net_amount'] = $contribution->net_amount
;
746 if (CRM_Utils_Array
::value('fee_amount', $input) && CRM_Utils_Array
::value('amount', $input)) {
747 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
750 //complete the contribution.
751 $baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
753 // reset template values before processing next transactions
754 $template->clearTemplateVars();
760 * Update pledge associated with a recurring contribution
762 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
764 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
765 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
766 * it should be assumed they
767 * do so with the intention that all payments will be linked
769 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
770 * If not the contribution will also need to be linked to the pledge
772 function updateRecurLinkedPledge(&$contribution) {
773 $returnProperties = array('id', 'pledge_id');
774 $paymentDetails = $paymentIDs = array();
776 if (CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id
,
777 $paymentDetails, $returnProperties
779 foreach ($paymentDetails as $key => $value) {
780 $paymentIDs[] = $value['id'];
781 $pledgeId = $value['pledge_id'];
785 //payment is not already linked - if it is linked with a pledge we need to create a link.
786 // return if it is not recurring contribution
787 if (!$contribution->contribution_recur_id
) {
791 $relatedContributions = new CRM_Contribute_DAO_Contribution();
792 $relatedContributions->contribution_recur_id
= $contribution->contribution_recur_id
;
793 $relatedContributions->find();
795 while ($relatedContributions->fetch()) {
796 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id
,
797 $paymentDetails, $returnProperties
801 if (empty($paymentDetails)) {
802 // payment is not linked with a pledge and neither are any other contributions on this
806 foreach ($paymentDetails as $key => $value) {
807 $pledgeId = $value['pledge_id'];
810 // we have a pledge now we need to get the oldest unpaid payment
811 $paymentDetails = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeId);
812 if(empty($paymentDetails['id'])){
813 // we can assume this pledge is now completed
814 // return now so we don't create a core error & roll back
817 $paymentDetails['contribution_id'] = $contribution->id
;
818 $paymentDetails['status_id'] = $contribution->contribution_status_id
;
819 $paymentDetails['actual_amount'] = $contribution->total_amount
;
821 // put contribution against it
822 $payment = CRM_Pledge_BAO_PledgePayment
::add($paymentDetails);
823 $paymentIDs[] = $payment->id
;
826 // update pledge and corresponding payment statuses
827 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id
,
828 NULL, $contribution->total_amount
832 function addrecurLineItems($recurId, $contributionId, &$input) {
833 $lineSets = $lineItems = array();
835 //Get the first contribution id with recur id
837 $contriID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
838 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($contriID, 'contribution');
839 if (!empty($lineItems)) {
840 foreach ($lineItems as $key => $value) {
841 $pricesetID = new CRM_Price_DAO_PriceField();
842 $pricesetID->id
= $value['price_field_id'];
843 $pricesetID->find(TRUE);
844 $lineSets[$pricesetID->price_set_id
][] = $value;
847 if (!empty($input)) {
848 $input['line_item'] = $lineSets;
851 CRM_Price_BAO_LineItem
::processPriceSet($contributionId, $lineSets);
856 // function to copy custom data of the
857 // initial contribution into its recurring contributions
858 function copyCustomValues($recurId, $targetContributionId) {
859 if ($recurId && $targetContributionId) {
860 // get the initial contribution id of recur id
861 $sourceContributionId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
863 // if the same contribution is being proccessed then return
864 if ($sourceContributionId == $targetContributionId) {
867 // check if proper recurring contribution record is being processed
868 $targetConRecurId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
869 if ($targetConRecurId != $recurId) {
874 $extends = array('Contribution');
875 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
877 foreach ($groupTree as $groupID => $group) {
878 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
879 foreach ($group['fields'] as $fieldID => $field) {
880 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
884 foreach ($table as $tableName => $tableColumns) {
885 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
886 $tableColumns[0] = $targetContributionId;
887 $select = 'SELECT ' . implode(', ', $tableColumns);
888 $from = ' FROM ' . $tableName;
889 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
890 $query = $insert . $select . $from . $where;
891 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);