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();
46 protected $_isRecurring = FALSE;
48 protected $_isFirstOrLastRecurringPayment = FALSE;
52 function __construct() {
53 self
::$_now = date('YmdHis');
57 * Store input array on the class
59 * @param array $parameters
61 * @throws CRM_Core_Exception
63 function setInputParameters($parameters) {
64 if(!is_array($parameters)) {
65 throw new CRM_Core_Exception('Invalid input parameters');
67 $this->_inputParameters
= $parameters;
70 * Validate incoming data. This function is intended to ensure that incoming data matches
71 * It provides a form of pseudo-authentication - by checking the calling fn already knows
72 * the correct contact id & contribution id (this can be problematic when that has changed in
73 * the meantime for transactions that are delayed & contacts are merged in-between. e.g
74 * Paypal allows you to resend Instant Payment Notifications if you, for example, moved site
75 * and didn't update your IPN URL.
77 * @param array $input interpreted values from the values returned through the IPN
78 * @param array $ids more interpreted values (ids) from the values returned through the IPN
79 * @param array $objects an empty array that will be populated with loaded object
80 * @param boolean $required boolean Return FALSE if the relevant objects don't exist
81 * @param integer $paymentProcessorID Id of the payment processor ID in use
84 function validateData(&$input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
86 // make sure contact exists and is valid
87 $contact = new CRM_Contact_BAO_Contact();
88 $contact->id
= $ids['contact'];
89 if (!$contact->find(TRUE)) {
90 CRM_Core_Error
::debug_log_message("Could not find contact record: {$ids['contact']} in IPN request: ".print_r($input, TRUE));
91 echo "Failure: Could not find contact record: {$ids['contact']}<p>";
95 // make sure contribution exists and is valid
96 $contribution = new CRM_Contribute_BAO_Contribution();
97 $contribution->id
= $ids['contribution'];
98 if (!$contribution->find(TRUE)) {
99 CRM_Core_Error
::debug_log_message("Could not find contribution record: {$contribution->id} in IPN request: ".print_r($input, TRUE));
100 echo "Failure: Could not find contribution record for {$contribution->id}<p>";
103 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
105 $objects['contact'] = &$contact;
106 $objects['contribution'] = &$contribution;
107 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
110 //the process is that the loadObjects is kind of hacked by loading the objects for the original contribution and then somewhat inconsistently using them for the
111 //current contribution. Here we ensure that the original contribution is available to the complete transaction function
112 //we don't want to fix this in the payment processor classes because we would have to fix all of them - so better to fix somewhere central
113 if (isset($objects['contributionRecur'])) {
114 $objects['first_contribution'] = $objects['contribution'];
120 * Load objects related to contribution
122 * @input array information from Payment processor
126 * @param array $objects
127 * @param boolean $required
128 * @param integer $paymentProcessorID
129 * @param array $error_handling
131 * @return multitype:number NULL |boolean
133 function loadObjects(&$input, &$ids, &$objects, $required, $paymentProcessorID, $error_handling = NULL) {
134 if (empty($error_handling)) {
135 // default options are that we log an error & echo it out
136 // note that we should refactor this error handling into error code @ some point
137 // but for now setting up enough separation so we can do unit tests
138 $error_handling = array(
143 $ids['paymentProcessor'] = $paymentProcessorID;
144 if (is_a($objects['contribution'], 'CRM_Contribute_BAO_Contribution')) {
145 $contribution = &$objects['contribution'];
148 //legacy support - functions are 'used' to be able to pass in a DAO
149 $contribution = new CRM_Contribute_BAO_Contribution();
150 $contribution->id
= CRM_Utils_Array
::value('contribution', $ids);
151 $contribution->find(TRUE);
152 $objects['contribution'] = &$contribution;
155 $success = $contribution->loadRelatedObjects($input, $ids, $required);
157 catch(Exception
$e) {
159 if (!empty($error_handling['log_error'])) {
160 CRM_Core_Error
::debug_log_message($e->getMessage());
162 if (!empty($error_handling['echo_error'])) {
163 echo ($e->getMessage());
165 if (!empty($error_handling['return_error'])) {
168 'error_message' => ($e->getMessage()),
172 $objects = array_merge($objects, $contribution->_relatedObjects
);
177 * Set contribution to failed
178 * @param array $objects
179 * @param object $transaction
180 * @param array $input
183 function failed(&$objects, &$transaction, $input = array()) {
184 $contribution = &$objects['contribution'];
185 $memberships = array();
186 if (!empty($objects['membership'])) {
187 $memberships = &$objects['membership'];
188 if (is_numeric($memberships)) {
189 $memberships = array($objects['membership']);
193 $addLineItems = FALSE;
194 if (empty($contribution->id
)) {
195 $addLineItems = TRUE;
197 $participant = &$objects['participant'];
199 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
200 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
201 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
202 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
203 $contribution->contribution_status_id
= array_search('Failed', $contributionStatus);
204 $contribution->save();
206 //add lineitems for recurring payments
207 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
208 $this->addrecurLineItems($objects['contributionRecur']->id
, $contribution->id
, CRM_Core_DAO
::$_nullArray);
211 //add new soft credit against current contribution id and
212 //copy initial contribution custom fields for recurring contributions
213 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
214 $this->addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
215 $this->copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
218 if (empty($input['skipComponentSync'])) {
219 if (!empty($memberships)) {
220 // if transaction is failed then set "Cancelled" as membership status
221 $cancelStatusId = array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus());
222 foreach ($memberships as $membership) {
224 $membership->status_id
= $cancelStatusId;
227 //update related Memberships.
228 $params = array('status_id' => $cancelStatusId);
229 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
235 $participant->status_id
= 4;
236 $participant->save();
240 $transaction->commit();
241 CRM_Core_Error
::debug_log_message("Setting contribution status to failed");
242 //echo "Success: Setting contribution status to failed<p>";
247 * Handled pending contribution status
248 * @param array $objects
249 * @param object $transaction
252 function pending(&$objects, &$transaction) {
253 $transaction->commit();
254 CRM_Core_Error
::debug_log_message("returning since contribution status is pending");
255 echo "Success: Returning since contribution status is pending<p>";
261 * @param $transaction
262 * @param array $input
266 function cancelled(&$objects, &$transaction, $input = array()) {
267 $contribution = &$objects['contribution'];
268 $memberships = &$objects['membership'];
269 if (is_numeric($memberships)) {
270 $memberships = array($objects['membership']);
273 $participant = &$objects['participant'];
274 $addLineItems = FALSE;
275 if (empty($contribution->id
)) {
276 $addLineItems = TRUE;
278 $contribution->contribution_status_id
= 3;
279 $contribution->cancel_date
= self
::$_now;
280 $contribution->cancel_reason
= CRM_Utils_Array
::value('reasonCode', $input);
281 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
282 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
283 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
284 $contribution->save();
286 //add lineitems for recurring payments
287 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
288 $this->addrecurLineItems($objects['contributionRecur']->id
, $contribution->id
, CRM_Core_DAO
::$_nullArray);
291 //add new soft credit against current $contribution and
292 //copy initial contribution custom fields for recurring contributions
293 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
294 $this->addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
295 $this->copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
298 if (empty($input['skipComponentSync'])) {
299 if (!empty($memberships)) {
300 foreach ($memberships as $membership) {
302 $membership->status_id
= 6;
305 //update related Memberships.
306 $params = array('status_id' => 6);
307 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
313 $participant->status_id
= 4;
314 $participant->save();
317 $transaction->commit();
318 CRM_Core_Error
::debug_log_message("Setting contribution status to cancelled");
319 //echo "Success: Setting contribution status to cancelled<p>";
325 * @param $transaction
329 function unhandled(&$objects, &$transaction) {
330 $transaction->rollback();
331 CRM_Core_Error
::debug_log_message("returning since contribution status: is not handled");
332 echo "Failure: contribution status is not handled<p>";
340 * @param $transaction
343 function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) {
344 $contribution = &$objects['contribution'];
346 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
348 $memberships = &$objects['membership'];
349 if (is_numeric($memberships)) {
350 $memberships = array($objects['membership']);
352 $participant = &$objects['participant'];
353 $event = &$objects['event'];
354 $changeToday = CRM_Utils_Array
::value('trxn_date', $input, self
::$_now);
355 $recurContrib = &$objects['contributionRecur'];
359 if ($input['component'] == 'contribute') {
360 if ($contribution->contribution_page_id
) {
361 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
362 $source = ts('Online Contribution') . ': ' . $values['title'];
364 elseif ($recurContrib && $recurContrib->id
) {
365 $contribution->contribution_page_id
= NULL;
366 $values['amount'] = $recurContrib->amount
;
367 $values['financial_type_id'] = $objects['contributionType']->id
;
368 $values['title'] = $source = ts('Offline Recurring Contribution');
369 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
370 $values['receipt_from_name'] = $domainValues[0];
371 $values['receipt_from_email'] = $domainValues[1];
373 if($recurContrib && $recurContrib->id
){
374 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
375 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
378 $contribution->source
= $source;
379 if (!empty($values['is_email_receipt'])) {
380 $contribution->receipt_date
= self
::$_now;
383 if (!empty($memberships)) {
384 $membershipsUpdate = array( );
385 foreach ($memberships as $membershipTypeIdKey => $membership) {
389 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
390 $membership->membership_type_id
,
391 $membership->is_test
, $membership->id
394 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
395 // this picks up membership type changes during renewals
397 SELECT membership_type_id
398 FROM civicrm_membership_log
399 WHERE membership_id=$membership->id
402 $dao = new CRM_Core_DAO
;
405 if (!empty($dao->membership_type_id
)) {
406 $membership->membership_type_id
= $dao->membership_type_id
;
409 // else fall back to using current membership type
411 // else fall back to using current membership type
414 $num_terms = $contribution->getNumTermsByContributionAndMembershipType($membership->membership_type_id
, $primaryContributionID);
415 if ($currentMembership) {
418 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
419 * when Contribution mode is notify and membership is for renewal )
421 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
423 // @todo - we should pass membership_type_id instead of null here but not
424 // adding as not sure of testing
425 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
426 $changeToday, NULL, $num_terms
429 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
432 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $num_terms);
435 //get the status for membership.
436 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
441 $membership->membership_type_id
,
445 $formatedParams = array('status_id' => CRM_Utils_Array
::value('id', $calcStatus, 2),
446 'join_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('join_date', $dates), $format),
447 'start_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('start_date', $dates), $format),
448 'end_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('end_date', $dates), $format),
450 //we might be renewing membership,
451 //so make status override false.
452 $formatedParams['is_override'] = FALSE;
453 $membership->copyValues($formatedParams);
456 //updating the membership log
457 $membershipLog = array();
458 $membershipLog = $formatedParams;
460 $logStartDate = $formatedParams['start_date'];
461 if (!empty($dates['log_start_date'])) {
462 $logStartDate = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
463 $logStartDate = CRM_Utils_Date
::isoToMysql($logStartDate);
466 $membershipLog['start_date'] = $logStartDate;
467 $membershipLog['membership_id'] = $membership->id
;
468 $membershipLog['modified_id'] = $membership->contact_id
;
469 $membershipLog['modified_date'] = date('Ymd');
470 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
472 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
474 //update related Memberships.
475 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formatedParams);
477 //update the membership type key of membership relatedObjects array
478 //if it has changed after membership update
479 if ($membershipTypeIdKey != $membership->membership_type_id
) {
480 $membershipsUpdate[$membership->membership_type_id
] = $membership;
481 $contribution->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
482 unset($contribution->_relatedObjects
['membership'][$membershipTypeIdKey]);
483 unset($memberships[$membershipTypeIdKey]);
487 //update the memberships object with updated membershipTypeId data
488 //if membershipTypeId has changed after membership update
489 if (!empty($membershipsUpdate)) {
490 $memberships = $memberships +
$membershipsUpdate;
496 $eventParams = array('id' => $objects['event']->id
);
497 $values['event'] = array();
499 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
501 //get location details
502 $locationParams = array('entity_id' => $objects['event']->id
, 'entity_table' => 'civicrm_event');
503 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
505 $ufJoinParams = array(
506 'entity_table' => 'civicrm_event',
507 'entity_id' => $ids['event'],
508 'module' => 'CiviEvent',
513 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
515 $values['custom_pre_id'] = $custom_pre_id;
516 $values['custom_post_id'] = $custom_post_ids;
517 //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
518 //and cases involving status updation through ipn
519 $values['totalAmount'] = $input['amount'];
521 $contribution->source
= ts('Online Event Registration') . ': ' . $values['event']['title'];
523 if ($values['event']['is_email_confirm']) {
524 $contribution->receipt_date
= self
::$_now;
525 $values['is_email_receipt'] = 1;
527 if (empty($input['skipComponentSync'])) {
528 $participant->status_id
= 1;
530 $participant->save();
533 if (CRM_Utils_Array
::value('net_amount', $input, 0) == 0 &&
534 CRM_Utils_Array
::value('fee_amount', $input, 0) != 0
536 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
538 $addLineItems = FALSE;
539 if (empty($contribution->id
)) {
540 $addLineItems = TRUE;
543 $contribution->contribution_status_id
= 1;
544 $contribution->is_test
= $input['is_test'];
545 $contribution->fee_amount
= CRM_Utils_Array
::value('fee_amount', $input, 0);
546 $contribution->net_amount
= CRM_Utils_Array
::value('net_amount', $input, 0);
547 $contribution->trxn_id
= $input['trxn_id'];
548 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
549 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
550 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
551 $contribution->cancel_date
= 'null';
553 if (!empty($input['check_number'])) {
554 $contribution->check_number
= $input['check_number'];
557 if (!empty($input['payment_instrument_id'])) {
558 $contribution->payment_instrument_id
= $input['payment_instrument_id'];
561 if ($contribution->id
) {
562 $contributionId['id'] = $contribution->id
;
563 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues($contributionId, CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
565 $contribution->save();
567 //add new soft credit against current $contribution and
568 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
569 $this->addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
572 //add lineitems for recurring payments
573 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
574 $this->addrecurLineItems($objects['contributionRecur']->id
, $contribution->id
, $input);
577 //copy initial contribution custom fields for recurring contributions
578 if ($recurContrib && $recurContrib->id
) {
579 $this->copyCustomValues($recurContrib->id
, $contribution->id
);
582 // next create the transaction record
583 $paymentProcessor = $paymentProcessorId = '';
584 if (isset($objects['paymentProcessor'])) {
585 if (is_array($objects['paymentProcessor'])) {
586 $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
587 $paymentProcessorId = $objects['paymentProcessor']['id'];
590 $paymentProcessor = $objects['paymentProcessor']->payment_processor_type
;
591 $paymentProcessorId = $objects['paymentProcessor']->id
;
594 //it's hard to see how it could reach this point without a contributon id as it is saved in line 511 above
595 // which raised the question as to whether this check preceded line 511 & if so whether something could be broken
596 // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code
597 // it would be good if someone added some comments or refactored this
598 if ($contribution->id
) {
599 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
600 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&&
601 - $input['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses))) {
602 $input['payment_processor'] = $paymentProcessorId;
604 $input['contribution_status_id'] = array_search('Completed', $contributionStatuses);
605 $input['total_amount'] = $input['amount'];
606 $input['contribution'] = $contribution;
607 $input['financial_type_id'] = $contribution->financial_type_id
;
609 if (!empty($contribution->_relatedObjects
['participant'])) {
610 $input['contribution_mode'] = 'participant';
611 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
612 $input['skipLineItem'] = 1;
614 elseif (!empty($contribution->_relatedObjects
['membership'])) {
615 $input['skipLineItem'] = TRUE;
616 $input['contribution_mode'] = 'membership';
618 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
619 // and subsequent payments. In this case the line items are created at $this->addrecurLineItems
620 // and since the contribution is saved prior to this line there is always a contribution-id,
621 // however there is never a prevContribution (which appears to mean original contribution not previous
622 // contribution - or preUpdateContributionObject most accurately)
623 // so, this is always called & only appears to succeed when prevContribution exists - which appears
624 // to mean "are we updating an exisitng pending contribution"
625 //I was able to make the unit test complete as fataling here doesn't prevent
626 // the contribution being created - but activities would not be created or emails sent
627 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
630 self
::updateRecurLinkedPledge($contribution);
632 // create an activity record
633 if ($input['component'] == 'contribute') {
635 $targetContactID = NULL;
636 if (!empty($ids['related_contact'])) {
637 $targetContactID = $contribution->contact_id
;
638 $contribution->contact_id
= $ids['related_contact'];
640 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
644 CRM_Activity_BAO_Activity
::addActivity($participant);
647 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
648 $transaction->commit();
650 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
651 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
652 if (!array_key_exists('is_email_receipt', $values) ||
653 $values['is_email_receipt'] == 1
655 self
::sendMail($input, $ids, $objects, $values, $recur, FALSE);
656 CRM_Core_Error
::debug_log_message("Receipt sent");
659 CRM_Core_Error
::debug_log_message("Success: Database updated");
660 if ($this->_isRecurring
) {
661 $this->sendRecurringStartOrEndNotification($ids, $recur);
670 function getBillingID(&$ids) {
671 // get the billing location type
672 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
673 // CRM-8108 remove the ts around the Billing locationtype
674 //$ids['billing'] = array_search( ts('Billing'), $locationTypes );
675 $ids['billing'] = array_search('Billing', $locationTypes);
676 if (!$ids['billing']) {
677 CRM_Core_Error
::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
678 echo "Failure: Could not find billing location type<p>";
685 * Send receipt from contribution. Note that the compose message part has been moved to contribution
686 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
688 * @params array $input Incoming data from Payment processor
689 * @params array $ids Related object IDs
690 * @params array $values values related to objects that have already been loaded
691 * @params bool $recur is it part of a recurring contribution
692 * @params bool $returnMessageText Should text be returned instead of sent. This
693 * is because the function is also used to generate pdfs
701 * @param bool $returnMessageText
705 function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
706 $contribution = &$objects['contribution'];
707 $input['is_recur'] = $recur;
708 // set receipt from e-mail and name in value
709 if (!$returnMessageText) {
710 $session = CRM_Core_Session
::singleton();
711 $userID = $session->get('userID');
712 if (!empty($userID)) {
713 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
714 $values['receipt_from_email'] = $userEmail;
715 $values['receipt_from_name'] = $userName;
718 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
722 * Send start or end notification for recurring payments
726 function sendRecurringStartOrEndNotification($ids, $recur) {
727 if ($this->_isFirstOrLastRecurringPayment
) {
728 $autoRenewMembership = FALSE;
730 isset($ids['membership']) && $ids['membership']
732 $autoRenewMembership = TRUE;
735 //send recurring Notification email for user
736 CRM_Contribute_BAO_ContributionPage
::recurringNotify($this->_isFirstOrLastRecurringPayment
,
738 $ids['contributionPage'],
746 * Update contribution status - this is only called from one place in the code &
747 * it is unclear whether it is a function on the way in or on the way out
749 * @param unknown_type $params
750 * @return void|Ambigous <value, unknown, array>
752 function updateContributionStatus(&$params) {
753 // get minimum required values.
754 $statusId = CRM_Utils_Array
::value('contribution_status_id', $params);
755 $componentId = CRM_Utils_Array
::value('component_id', $params);
756 $componentName = CRM_Utils_Array
::value('componentName', $params);
757 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
759 if (!$contributionId ||
!$componentId ||
!$componentName ||
!$statusId) {
763 $input = $ids = $objects = array();
765 //get the required ids.
766 $ids['contribution'] = $contributionId;
768 if (!$ids['contact'] = CRM_Utils_Array
::value('contact_id', $params)) {
769 $ids['contact'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
775 if ($componentName == 'Event') {
777 $ids['participant'] = $componentId;
779 if (!$ids['event'] = CRM_Utils_Array
::value('event_id', $params)) {
780 $ids['event'] = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
787 if ($componentName == 'Membership') {
788 $name = 'contribute';
789 $ids['membership'] = $componentId;
791 $ids['contributionPage'] = NULL;
792 $ids['contributionRecur'] = NULL;
793 $input['component'] = $name;
795 $baseIPN = new CRM_Core_Payment_BaseIPN();
796 $transaction = new CRM_Core_Transaction();
798 // reset template values.
799 $template = CRM_Core_Smarty
::singleton();
800 $template->clearTemplateVars();
802 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
803 CRM_Core_Error
::fatal();
806 $contribution = &$objects['contribution'];
808 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
809 $input['skipComponentSync'] = CRM_Utils_Array
::value('skipComponentSync', $params);
810 if ($statusId == array_search('Cancelled', $contributionStatuses)) {
811 $baseIPN->cancelled($objects, $transaction, $input);
812 $transaction->commit();
815 elseif ($statusId == array_search('Failed', $contributionStatuses)) {
816 $baseIPN->failed($objects, $transaction, $input);
817 $transaction->commit();
821 // status is not pending
822 if ($contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)) {
823 $transaction->commit();
827 //set values for ipn code.
829 'fee_amount', 'check_number', 'payment_instrument_id') as $field) {
830 if (!$input[$field] = CRM_Utils_Array
::value($field, $params)) {
831 $input[$field] = $contribution->$field;
834 if (!$input['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $params)) {
835 $input['trxn_id'] = $contribution->invoice_id
;
837 if (!$input['amount'] = CRM_Utils_Array
::value('total_amount', $params)) {
838 $input['amount'] = $contribution->total_amount
;
840 $input['is_test'] = $contribution->is_test
;
841 $input['net_amount'] = $contribution->net_amount
;
842 if (!empty($input['fee_amount']) && !empty($input['amount'])) {
843 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
846 //complete the contribution.
847 $baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
849 // reset template values before processing next transactions
850 $template->clearTemplateVars();
856 * Update pledge associated with a recurring contribution
858 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
860 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
861 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
862 * it should be assumed they
863 * do so with the intention that all payments will be linked
865 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
866 * If not the contribution will also need to be linked to the pledge
869 * @param $contribution
871 function updateRecurLinkedPledge(&$contribution) {
872 $returnProperties = array('id', 'pledge_id');
873 $paymentDetails = $paymentIDs = array();
875 if (CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id
,
876 $paymentDetails, $returnProperties
878 foreach ($paymentDetails as $key => $value) {
879 $paymentIDs[] = $value['id'];
880 $pledgeId = $value['pledge_id'];
884 //payment is not already linked - if it is linked with a pledge we need to create a link.
885 // return if it is not recurring contribution
886 if (!$contribution->contribution_recur_id
) {
890 $relatedContributions = new CRM_Contribute_DAO_Contribution();
891 $relatedContributions->contribution_recur_id
= $contribution->contribution_recur_id
;
892 $relatedContributions->find();
894 while ($relatedContributions->fetch()) {
895 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id
,
896 $paymentDetails, $returnProperties
900 if (empty($paymentDetails)) {
901 // payment is not linked with a pledge and neither are any other contributions on this
905 foreach ($paymentDetails as $key => $value) {
906 $pledgeId = $value['pledge_id'];
909 // we have a pledge now we need to get the oldest unpaid payment
910 $paymentDetails = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeId);
911 if(empty($paymentDetails['id'])){
912 // we can assume this pledge is now completed
913 // return now so we don't create a core error & roll back
916 $paymentDetails['contribution_id'] = $contribution->id
;
917 $paymentDetails['status_id'] = $contribution->contribution_status_id
;
918 $paymentDetails['actual_amount'] = $contribution->total_amount
;
920 // put contribution against it
921 $payment = CRM_Pledge_BAO_PledgePayment
::add($paymentDetails);
922 $paymentIDs[] = $payment->id
;
925 // update pledge and corresponding payment statuses
926 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id
,
927 NULL, $contribution->total_amount
933 * @param $contributionId
936 function addrecurLineItems($recurId, $contributionId, &$input) {
937 $lineSets = $lineItems = array();
939 //Get the first contribution id with recur id
941 $contriID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
942 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($contriID, 'contribution');
943 if (!empty($lineItems)) {
944 foreach ($lineItems as $key => $value) {
945 $pricesetID = new CRM_Price_DAO_PriceField();
946 $pricesetID->id
= $value['price_field_id'];
947 $pricesetID->find(TRUE);
948 $lineSets[$pricesetID->price_set_id
][] = $value;
951 if (!empty($input)) {
952 $input['line_item'] = $lineSets;
955 CRM_Price_BAO_LineItem
::processPriceSet($contributionId, $lineSets);
960 // function to copy custom data of the
961 // initial contribution into its recurring contributions
964 * @param $targetContributionId
966 function copyCustomValues($recurId, $targetContributionId) {
967 if ($recurId && $targetContributionId) {
968 // get the initial contribution id of recur id
969 $sourceContributionId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
971 // if the same contribution is being proccessed then return
972 if ($sourceContributionId == $targetContributionId) {
975 // check if proper recurring contribution record is being processed
976 $targetConRecurId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
977 if ($targetConRecurId != $recurId) {
982 $extends = array('Contribution');
983 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
985 foreach ($groupTree as $groupID => $group) {
986 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
987 foreach ($group['fields'] as $fieldID => $field) {
988 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
992 foreach ($table as $tableName => $tableColumns) {
993 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
994 $tableColumns[0] = $targetContributionId;
995 $select = 'SELECT ' . implode(', ', $tableColumns);
996 $from = ' FROM ' . $tableName;
997 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
998 $query = $insert . $select . $from . $where;
999 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1005 // function to copy soft credit record of first recurring contribution
1006 // and add new soft credit against $targetContributionId
1009 * @param $targetContributionId
1011 function addrecurSoftCredit($recurId, $targetContributionId) {
1012 $contriID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
1014 $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
1015 $soft_contribution->contribution_id
= $contriID;
1017 //check if first recurring contribution has any associated soft credit
1018 if ($soft_contribution->find(TRUE)) {
1019 $soft_contribution->contribution_id
= $targetContributionId;
1020 unset($soft_contribution->id
);
1021 $soft_contribution->save();