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);
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);
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
) {
575 $input ['line_item'] = $this->addRecurLineItems($objects['contributionRecur']->id
, $contribution);
578 // this is just to prevent e-notices when we call recordFinancialAccounts - per comments on that line - intention is somewhat unclear
579 $input['line_item'] = array();
583 //copy initial contribution custom fields for recurring contributions
584 if ($recurContrib && $recurContrib->id
) {
585 $this->copyCustomValues($recurContrib->id
, $contribution->id
);
588 // next create the transaction record
589 $paymentProcessor = $paymentProcessorId = '';
590 if (isset($objects['paymentProcessor'])) {
591 if (is_array($objects['paymentProcessor'])) {
592 $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
593 $paymentProcessorId = $objects['paymentProcessor']['id'];
596 $paymentProcessor = $objects['paymentProcessor']->payment_processor_type
;
597 $paymentProcessorId = $objects['paymentProcessor']->id
;
600 //it's hard to see how it could reach this point without a contributon id as it is saved in line 511 above
601 // which raised the question as to whether this check preceded line 511 & if so whether something could be broken
602 // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code
603 // it would be good if someone added some comments or refactored this
604 if ($contribution->id
) {
605 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
606 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&&
607 - $input['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses))) {
608 $input['payment_processor'] = $paymentProcessorId;
610 $input['contribution_status_id'] = array_search('Completed', $contributionStatuses);
611 $input['total_amount'] = $input['amount'];
612 $input['contribution'] = $contribution;
613 $input['financial_type_id'] = $contribution->financial_type_id
;
615 if (!empty($contribution->_relatedObjects
['participant'])) {
616 $input['contribution_mode'] = 'participant';
617 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
618 $input['skipLineItem'] = 1;
620 elseif (!empty($contribution->_relatedObjects
['membership'])) {
621 $input['skipLineItem'] = TRUE;
622 $input['contribution_mode'] = 'membership';
624 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
625 // and subsequent payments. In this case the line items are created at $this->addRecurLineItems
626 // and since the contribution is saved prior to this line there is always a contribution-id,
627 // however there is never a prevContribution (which appears to mean original contribution not previous
628 // contribution - or preUpdateContributionObject most accurately)
629 // so, this is always called & only appears to succeed when prevContribution exists - which appears
630 // to mean "are we updating an exisitng pending contribution"
631 //I was able to make the unit test complete as fataling here doesn't prevent
632 // the contribution being created - but activities would not be created or emails sent
634 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
637 self
::updateRecurLinkedPledge($contribution);
639 // create an activity record
640 if ($input['component'] == 'contribute') {
642 $targetContactID = NULL;
643 if (!empty($ids['related_contact'])) {
644 $targetContactID = $contribution->contact_id
;
645 $contribution->contact_id
= $ids['related_contact'];
647 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
651 CRM_Activity_BAO_Activity
::addActivity($participant);
654 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
655 $transaction->commit();
657 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
658 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
659 if (!array_key_exists('is_email_receipt', $values) ||
660 $values['is_email_receipt'] == 1
662 self
::sendMail($input, $ids, $objects, $values, $recur, FALSE);
663 CRM_Core_Error
::debug_log_message("Receipt sent");
666 CRM_Core_Error
::debug_log_message("Success: Database updated");
667 if ($this->_isRecurring
) {
668 $this->sendRecurringStartOrEndNotification($ids, $recur);
677 function getBillingID(&$ids) {
678 // get the billing location type
679 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
680 // CRM-8108 remove the ts around the Billing locationtype
681 //$ids['billing'] = array_search( ts('Billing'), $locationTypes );
682 $ids['billing'] = array_search('Billing', $locationTypes);
683 if (!$ids['billing']) {
684 CRM_Core_Error
::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
685 echo "Failure: Could not find billing location type<p>";
692 * Send receipt from contribution. Note that the compose message part has been moved to contribution
693 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
695 * @params array $input Incoming data from Payment processor
696 * @params array $ids Related object IDs
697 * @params array $values values related to objects that have already been loaded
698 * @params bool $recur is it part of a recurring contribution
699 * @params bool $returnMessageText Should text be returned instead of sent. This
700 * is because the function is also used to generate pdfs
708 * @param bool $returnMessageText
712 function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
713 $contribution = &$objects['contribution'];
714 $input['is_recur'] = $recur;
715 // set receipt from e-mail and name in value
716 if (!$returnMessageText) {
717 $session = CRM_Core_Session
::singleton();
718 $userID = $session->get('userID');
719 if (!empty($userID)) {
720 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
721 $values['receipt_from_email'] = $userEmail;
722 $values['receipt_from_name'] = $userName;
725 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
729 * Send start or end notification for recurring payments
733 function sendRecurringStartOrEndNotification($ids, $recur) {
734 if ($this->_isFirstOrLastRecurringPayment
) {
735 $autoRenewMembership = FALSE;
737 isset($ids['membership']) && $ids['membership']
739 $autoRenewMembership = TRUE;
742 //send recurring Notification email for user
743 CRM_Contribute_BAO_ContributionPage
::recurringNotify($this->_isFirstOrLastRecurringPayment
,
745 $ids['contributionPage'],
753 * Update contribution status - this is only called from one place in the code &
754 * it is unclear whether it is a function on the way in or on the way out
756 * @param unknown_type $params
757 * @return void|Ambigous <value, unknown, array>
759 function updateContributionStatus(&$params) {
760 // get minimum required values.
761 $statusId = CRM_Utils_Array
::value('contribution_status_id', $params);
762 $componentId = CRM_Utils_Array
::value('component_id', $params);
763 $componentName = CRM_Utils_Array
::value('componentName', $params);
764 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
766 if (!$contributionId ||
!$componentId ||
!$componentName ||
!$statusId) {
770 $input = $ids = $objects = array();
772 //get the required ids.
773 $ids['contribution'] = $contributionId;
775 if (!$ids['contact'] = CRM_Utils_Array
::value('contact_id', $params)) {
776 $ids['contact'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
782 if ($componentName == 'Event') {
784 $ids['participant'] = $componentId;
786 if (!$ids['event'] = CRM_Utils_Array
::value('event_id', $params)) {
787 $ids['event'] = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
794 if ($componentName == 'Membership') {
795 $name = 'contribute';
796 $ids['membership'] = $componentId;
798 $ids['contributionPage'] = NULL;
799 $ids['contributionRecur'] = NULL;
800 $input['component'] = $name;
802 $baseIPN = new CRM_Core_Payment_BaseIPN();
803 $transaction = new CRM_Core_Transaction();
805 // reset template values.
806 $template = CRM_Core_Smarty
::singleton();
807 $template->clearTemplateVars();
809 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
810 CRM_Core_Error
::fatal();
813 $contribution = &$objects['contribution'];
815 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
816 $input['skipComponentSync'] = CRM_Utils_Array
::value('skipComponentSync', $params);
817 if ($statusId == array_search('Cancelled', $contributionStatuses)) {
818 $baseIPN->cancelled($objects, $transaction, $input);
819 $transaction->commit();
822 elseif ($statusId == array_search('Failed', $contributionStatuses)) {
823 $baseIPN->failed($objects, $transaction, $input);
824 $transaction->commit();
828 // status is not pending
829 if ($contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)) {
830 $transaction->commit();
834 //set values for ipn code.
836 'fee_amount', 'check_number', 'payment_instrument_id') as $field) {
837 if (!$input[$field] = CRM_Utils_Array
::value($field, $params)) {
838 $input[$field] = $contribution->$field;
841 if (!$input['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $params)) {
842 $input['trxn_id'] = $contribution->invoice_id
;
844 if (!$input['amount'] = CRM_Utils_Array
::value('total_amount', $params)) {
845 $input['amount'] = $contribution->total_amount
;
847 $input['is_test'] = $contribution->is_test
;
848 $input['net_amount'] = $contribution->net_amount
;
849 if (!empty($input['fee_amount']) && !empty($input['amount'])) {
850 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
853 //complete the contribution.
854 $baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
856 // reset template values before processing next transactions
857 $template->clearTemplateVars();
863 * Update pledge associated with a recurring contribution
865 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
867 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
868 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
869 * it should be assumed they
870 * do so with the intention that all payments will be linked
872 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
873 * If not the contribution will also need to be linked to the pledge
876 * @param $contribution
878 function updateRecurLinkedPledge(&$contribution) {
879 $returnProperties = array('id', 'pledge_id');
880 $paymentDetails = $paymentIDs = array();
882 if (CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id
,
883 $paymentDetails, $returnProperties
885 foreach ($paymentDetails as $key => $value) {
886 $paymentIDs[] = $value['id'];
887 $pledgeId = $value['pledge_id'];
891 //payment is not already linked - if it is linked with a pledge we need to create a link.
892 // return if it is not recurring contribution
893 if (!$contribution->contribution_recur_id
) {
897 $relatedContributions = new CRM_Contribute_DAO_Contribution();
898 $relatedContributions->contribution_recur_id
= $contribution->contribution_recur_id
;
899 $relatedContributions->find();
901 while ($relatedContributions->fetch()) {
902 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id
,
903 $paymentDetails, $returnProperties
907 if (empty($paymentDetails)) {
908 // payment is not linked with a pledge and neither are any other contributions on this
912 foreach ($paymentDetails as $key => $value) {
913 $pledgeId = $value['pledge_id'];
916 // we have a pledge now we need to get the oldest unpaid payment
917 $paymentDetails = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeId);
918 if(empty($paymentDetails['id'])){
919 // we can assume this pledge is now completed
920 // return now so we don't create a core error & roll back
923 $paymentDetails['contribution_id'] = $contribution->id
;
924 $paymentDetails['status_id'] = $contribution->contribution_status_id
;
925 $paymentDetails['actual_amount'] = $contribution->total_amount
;
927 // put contribution against it
928 $payment = CRM_Pledge_BAO_PledgePayment
::add($paymentDetails);
929 $paymentIDs[] = $payment->id
;
932 // update pledge and corresponding payment statuses
933 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id
,
934 NULL, $contribution->total_amount
940 * @param $contribution
942 * @internal param $contributionId
946 function addRecurLineItems($recurId, $contribution) {
949 $originalContributionID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
950 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($originalContributionID);
951 if (!empty($lineItems)) {
952 foreach ($lineItems as $key => $value) {
953 $priceField = new CRM_Price_DAO_PriceField();
954 $priceField->id
= $value['price_field_id'];
955 $priceField->find(TRUE);
956 $lineSets[$priceField->price_set_id
][] = $value;
957 if ($value['entity_table'] == 'civicrm_membership') {
959 civicrm_api3('membership_payment', 'create', array('membership_id' => $value['entity_id'], 'contribution_id' => $contribution->id
));
961 catch (CiviCRM_API3_Exception
$e) {
962 // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
963 // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
969 CRM_Price_BAO_LineItem
::processPriceSet($contribution->id
, $lineSets, $contribution);
974 // function to copy custom data of the
975 // initial contribution into its recurring contributions
978 * @param $targetContributionId
980 function copyCustomValues($recurId, $targetContributionId) {
981 if ($recurId && $targetContributionId) {
982 // get the initial contribution id of recur id
983 $sourceContributionId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
985 // if the same contribution is being proccessed then return
986 if ($sourceContributionId == $targetContributionId) {
989 // check if proper recurring contribution record is being processed
990 $targetConRecurId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
991 if ($targetConRecurId != $recurId) {
996 $extends = array('Contribution');
997 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
999 foreach ($groupTree as $groupID => $group) {
1000 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
1001 foreach ($group['fields'] as $fieldID => $field) {
1002 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
1006 foreach ($table as $tableName => $tableColumns) {
1007 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
1008 $tableColumns[0] = $targetContributionId;
1009 $select = 'SELECT ' . implode(', ', $tableColumns);
1010 $from = ' FROM ' . $tableName;
1011 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
1012 $query = $insert . $select . $from . $where;
1013 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1019 // function to copy soft credit record of first recurring contribution
1020 // and add new soft credit against $targetContributionId
1023 * @param $targetContributionId
1025 function addrecurSoftCredit($recurId, $targetContributionId) {
1026 $contriID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
1028 $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
1029 $soft_contribution->contribution_id
= $contriID;
1031 //check if first recurring contribution has any associated soft credit
1032 if ($soft_contribution->find(TRUE)) {
1033 $soft_contribution->contribution_id
= $targetContributionId;
1034 unset($soft_contribution->id
);
1035 $soft_contribution->save();