3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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'];
200 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
201 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
202 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
203 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
204 $contribution->contribution_status_id
= $contributionStatuses['Failed'];
205 $contribution->save();
207 //add lineitems for recurring payments
208 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
209 $this->addRecurLineItems($objects['contributionRecur']->id
, $contribution);
212 //add new soft credit against current contribution id and
213 //copy initial contribution custom fields for recurring contributions
214 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
215 $this->addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
216 $this->copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
219 if (empty($input['skipComponentSync'])) {
220 if (!empty($memberships)) {
221 // if transaction is failed then set "Cancelled" as membership status
222 $membershipStatuses = CRM_Core_PseudoConstant
::get('CRM_Member_DAO_Membership', 'status_id', array('labelColumn' => 'name', 'flip' => 1));
223 foreach ($memberships as $membership) {
225 $membership->status_id
= $membershipStatuses['Cancelled'];
228 //update related Memberships.
229 $params = array('status_id' => $membershipStatuses['Cancelled']);
230 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
236 $participantStatuses = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'status_id', array('labelColumn' => 'name', 'flip' => 1));
237 $participant->status_id
= $participantStatuses['Cancelled'];
238 $participant->save();
242 $transaction->commit();
243 CRM_Core_Error
::debug_log_message("Setting contribution status to failed");
244 //echo "Success: Setting contribution status to failed<p>";
249 * Handled pending contribution status
250 * @param array $objects
251 * @param object $transaction
254 function pending(&$objects, &$transaction) {
255 $transaction->commit();
256 CRM_Core_Error
::debug_log_message("returning since contribution status is pending");
257 echo "Success: Returning since contribution status is pending<p>";
263 * @param $transaction
264 * @param array $input
268 function cancelled(&$objects, &$transaction, $input = array()) {
269 $contribution = &$objects['contribution'];
270 $memberships = &$objects['membership'];
271 if (is_numeric($memberships)) {
272 $memberships = array($objects['membership']);
275 $participant = &$objects['participant'];
276 $addLineItems = FALSE;
277 if (empty($contribution->id
)) {
278 $addLineItems = TRUE;
280 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
281 $contribution->contribution_status_id
= $contributionStatuses['Cancelled'];
282 $contribution->cancel_date
= self
::$_now;
283 $contribution->cancel_reason
= CRM_Utils_Array
::value('reasonCode', $input);
284 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
285 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
286 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
287 $contribution->save();
289 //add lineitems for recurring payments
290 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
291 $this->addRecurLineItems($objects['contributionRecur']->id
, $contribution);
294 //add new soft credit against current $contribution and
295 //copy initial contribution custom fields for recurring contributions
296 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
297 $this->addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
298 $this->copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
301 if (empty($input['skipComponentSync'])) {
302 if (!empty($memberships)) {
303 $membershipStatuses = CRM_Core_PseudoConstant
::get('CRM_Member_DAO_Membership', 'status_id', array('labelColumn' => 'name', 'flip' => 1));
304 foreach ($memberships as $membership) {
306 $membership->status_id
= $membershipStatuses['Cancelled'];
309 //update related Memberships.
310 $params = array('status_id' => $membershipStatuses['Cancelled']);
311 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
317 $participantStatuses = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'status_id', array('labelColumn' => 'name', 'flip' => 1));
318 $participant->status_id
= $participantStatuses['Cancelled'];
319 $participant->save();
322 $transaction->commit();
323 CRM_Core_Error
::debug_log_message("Setting contribution status to cancelled");
324 //echo "Success: Setting contribution status to cancelled<p>";
330 * @param $transaction
334 function unhandled(&$objects, &$transaction) {
335 $transaction->rollback();
336 CRM_Core_Error
::debug_log_message("returning since contribution status: is not handled");
337 echo "Failure: contribution status is not handled<p>";
345 * @param $transaction
348 function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) {
349 $contribution = &$objects['contribution'];
351 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
353 $memberships = &$objects['membership'];
354 if (is_numeric($memberships)) {
355 $memberships = array($objects['membership']);
357 $participant = &$objects['participant'];
358 $event = &$objects['event'];
359 $changeToday = CRM_Utils_Array
::value('trxn_date', $input, self
::$_now);
360 $recurContrib = &$objects['contributionRecur'];
364 if ($input['component'] == 'contribute') {
365 if ($contribution->contribution_page_id
) {
366 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
367 $source = ts('Online Contribution') . ': ' . $values['title'];
369 elseif ($recurContrib && $recurContrib->id
) {
370 $contribution->contribution_page_id
= NULL;
371 $values['amount'] = $recurContrib->amount
;
372 $values['financial_type_id'] = $objects['contributionType']->id
;
373 $values['title'] = $source = ts('Offline Recurring Contribution');
374 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
375 $values['receipt_from_name'] = $domainValues[0];
376 $values['receipt_from_email'] = $domainValues[1];
378 if($recurContrib && $recurContrib->id
){
379 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
380 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
383 $contribution->source
= $source;
384 if (!empty($values['is_email_receipt'])) {
385 $contribution->receipt_date
= self
::$_now;
388 if (!empty($memberships)) {
389 $membershipsUpdate = array( );
390 foreach ($memberships as $membershipTypeIdKey => $membership) {
394 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
395 $membership->membership_type_id
,
396 $membership->is_test
, $membership->id
399 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
400 // this picks up membership type changes during renewals
402 SELECT membership_type_id
403 FROM civicrm_membership_log
404 WHERE membership_id=$membership->id
407 $dao = new CRM_Core_DAO
;
410 if (!empty($dao->membership_type_id
)) {
411 $membership->membership_type_id
= $dao->membership_type_id
;
414 // else fall back to using current membership type
416 // else fall back to using current membership type
419 $num_terms = $contribution->getNumTermsByContributionAndMembershipType($membership->membership_type_id
, $primaryContributionID);
420 if ($currentMembership) {
423 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
424 * when Contribution mode is notify and membership is for renewal )
426 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
428 // @todo - we should pass membership_type_id instead of null here but not
429 // adding as not sure of testing
430 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
431 $changeToday, NULL, $num_terms
434 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
437 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $num_terms);
440 //get the status for membership.
441 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
446 $membership->membership_type_id
,
450 $formatedParams = array('status_id' => CRM_Utils_Array
::value('id', $calcStatus, 2),
451 'join_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('join_date', $dates), $format),
452 'start_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('start_date', $dates), $format),
453 'end_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('end_date', $dates), $format),
455 //we might be renewing membership,
456 //so make status override false.
457 $formatedParams['is_override'] = FALSE;
458 $membership->copyValues($formatedParams);
461 //updating the membership log
462 $membershipLog = array();
463 $membershipLog = $formatedParams;
465 $logStartDate = $formatedParams['start_date'];
466 if (!empty($dates['log_start_date'])) {
467 $logStartDate = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
468 $logStartDate = CRM_Utils_Date
::isoToMysql($logStartDate);
471 $membershipLog['start_date'] = $logStartDate;
472 $membershipLog['membership_id'] = $membership->id
;
473 $membershipLog['modified_id'] = $membership->contact_id
;
474 $membershipLog['modified_date'] = date('Ymd');
475 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
477 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
479 //update related Memberships.
480 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formatedParams);
482 //update the membership type key of membership relatedObjects array
483 //if it has changed after membership update
484 if ($membershipTypeIdKey != $membership->membership_type_id
) {
485 $membershipsUpdate[$membership->membership_type_id
] = $membership;
486 $contribution->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
487 unset($contribution->_relatedObjects
['membership'][$membershipTypeIdKey]);
488 unset($memberships[$membershipTypeIdKey]);
492 //update the memberships object with updated membershipTypeId data
493 //if membershipTypeId has changed after membership update
494 if (!empty($membershipsUpdate)) {
495 $memberships = $memberships +
$membershipsUpdate;
501 $eventParams = array('id' => $objects['event']->id
);
502 $values['event'] = array();
504 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
506 //get location details
507 $locationParams = array('entity_id' => $objects['event']->id
, 'entity_table' => 'civicrm_event');
508 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
510 $ufJoinParams = array(
511 'entity_table' => 'civicrm_event',
512 'entity_id' => $ids['event'],
513 'module' => 'CiviEvent',
518 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
520 $values['custom_pre_id'] = $custom_pre_id;
521 $values['custom_post_id'] = $custom_post_ids;
522 //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
523 //and cases involving status updation through ipn
524 $values['totalAmount'] = $input['amount'];
526 $contribution->source
= ts('Online Event Registration') . ': ' . $values['event']['title'];
528 if ($values['event']['is_email_confirm']) {
529 $contribution->receipt_date
= self
::$_now;
530 $values['is_email_receipt'] = 1;
532 if (empty($input['skipComponentSync'])) {
533 $participantStatuses = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'status_id', array('labelColumn' => 'name', 'flip' => 1));
534 $participant->status_id
= $participantStatuses['Registered'];
536 $participant->save();
539 if (CRM_Utils_Array
::value('net_amount', $input, 0) == 0 &&
540 CRM_Utils_Array
::value('fee_amount', $input, 0) != 0
542 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
544 $addLineItems = FALSE;
545 if (empty($contribution->id
)) {
546 $addLineItems = TRUE;
548 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
549 $contribution->contribution_status_id
= $contributionStatuses['Completed'];
550 $contribution->is_test
= $input['is_test'];
551 $contribution->fee_amount
= CRM_Utils_Array
::value('fee_amount', $input, 0);
552 $contribution->net_amount
= CRM_Utils_Array
::value('net_amount', $input, 0);
553 $contribution->trxn_id
= $input['trxn_id'];
554 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
555 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
556 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
557 $contribution->cancel_date
= 'null';
559 if (!empty($input['check_number'])) {
560 $contribution->check_number
= $input['check_number'];
563 if (!empty($input['payment_instrument_id'])) {
564 $contribution->payment_instrument_id
= $input['payment_instrument_id'];
567 if ($contribution->id
) {
568 $contributionId['id'] = $contribution->id
;
569 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues($contributionId, CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
571 $contribution->save();
573 //add new soft credit against current $contribution and
574 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
575 $this->addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
578 //add lineitems for recurring payments
579 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
581 $input ['line_item'] = $this->addRecurLineItems($objects['contributionRecur']->id
, $contribution);
584 // this is just to prevent e-notices when we call recordFinancialAccounts - per comments on that line - intention is somewhat unclear
585 $input['line_item'] = array();
589 //copy initial contribution custom fields for recurring contributions
590 if ($recurContrib && $recurContrib->id
) {
591 $this->copyCustomValues($recurContrib->id
, $contribution->id
);
594 // next create the transaction record
595 $paymentProcessor = $paymentProcessorId = '';
596 if (isset($objects['paymentProcessor'])) {
597 if (is_array($objects['paymentProcessor'])) {
598 $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
599 $paymentProcessorId = $objects['paymentProcessor']['id'];
602 $paymentProcessor = $objects['paymentProcessor']->payment_processor_type
;
603 $paymentProcessorId = $objects['paymentProcessor']->id
;
606 //it's hard to see how it could reach this point without a contributon id as it is saved in line 511 above
607 // which raised the question as to whether this check preceded line 511 & if so whether something could be broken
608 // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code
609 // it would be good if someone added some comments or refactored this
610 if ($contribution->id
) {
611 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
612 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&&
613 - $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
614 $input['payment_processor'] = $paymentProcessorId;
616 $input['contribution_status_id'] = $contributionStatuses['Completed'];
617 $input['total_amount'] = $input['amount'];
618 $input['contribution'] = $contribution;
619 $input['financial_type_id'] = $contribution->financial_type_id
;
621 if (!empty($contribution->_relatedObjects
['participant'])) {
622 $input['contribution_mode'] = 'participant';
623 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
624 $input['skipLineItem'] = 1;
626 elseif (!empty($contribution->_relatedObjects
['membership'])) {
627 $input['skipLineItem'] = TRUE;
628 $input['contribution_mode'] = 'membership';
630 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
631 // and subsequent payments. In this case the line items are created at $this->addRecurLineItems
632 // and since the contribution is saved prior to this line there is always a contribution-id,
633 // however there is never a prevContribution (which appears to mean original contribution not previous
634 // contribution - or preUpdateContributionObject most accurately)
635 // so, this is always called & only appears to succeed when prevContribution exists - which appears
636 // to mean "are we updating an exisitng pending contribution"
637 //I was able to make the unit test complete as fataling here doesn't prevent
638 // the contribution being created - but activities would not be created or emails sent
640 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
643 self
::updateRecurLinkedPledge($contribution);
645 // create an activity record
646 if ($input['component'] == 'contribute') {
648 $targetContactID = NULL;
649 if (!empty($ids['related_contact'])) {
650 $targetContactID = $contribution->contact_id
;
651 $contribution->contact_id
= $ids['related_contact'];
653 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
657 CRM_Activity_BAO_Activity
::addActivity($participant);
660 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
661 $transaction->commit();
663 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
664 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
665 if (!array_key_exists('is_email_receipt', $values) ||
666 $values['is_email_receipt'] == 1
668 self
::sendMail($input, $ids, $objects, $values, $recur, FALSE);
669 CRM_Core_Error
::debug_log_message("Receipt sent");
672 CRM_Core_Error
::debug_log_message("Success: Database updated");
673 if ($this->_isRecurring
) {
674 $this->sendRecurringStartOrEndNotification($ids, $recur);
683 function getBillingID(&$ids) {
684 // get the billing location type
685 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
686 // CRM-8108 remove the ts around the Billing locationtype
687 //$ids['billing'] = array_search( ts('Billing'), $locationTypes );
688 $ids['billing'] = array_search('Billing', $locationTypes);
689 if (!$ids['billing']) {
690 CRM_Core_Error
::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
691 echo "Failure: Could not find billing location type<p>";
698 * Send receipt from contribution. Note that the compose message part has been moved to contribution
699 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
701 * @param array $input Incoming data from Payment processor
702 * @param array $ids Related object IDs
704 * @param array $values values related to objects that have already been loaded
705 * @param bool $recur is it part of a recurring contribution
706 * @param bool $returnMessageText Should text be returned instead of sent. This
707 * is because the function is also used to generate pdfs
711 function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
712 $contribution = &$objects['contribution'];
713 $input['is_recur'] = $recur;
714 // set receipt from e-mail and name in value
715 if (!$returnMessageText) {
716 $session = CRM_Core_Session
::singleton();
717 $userID = $session->get('userID');
718 if (!empty($userID)) {
719 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
720 $values['receipt_from_email'] = $userEmail;
721 $values['receipt_from_name'] = $userName;
724 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
728 * Send start or end notification for recurring payments
732 function sendRecurringStartOrEndNotification($ids, $recur) {
733 if ($this->_isFirstOrLastRecurringPayment
) {
734 $autoRenewMembership = FALSE;
736 isset($ids['membership']) && $ids['membership']
738 $autoRenewMembership = TRUE;
741 //send recurring Notification email for user
742 CRM_Contribute_BAO_ContributionPage
::recurringNotify($this->_isFirstOrLastRecurringPayment
,
744 $ids['contributionPage'],
752 * Update contribution status - this is only called from one place in the code &
753 * it is unclear whether it is a function on the way in or on the way out
755 * @param unknown_type $params
756 * @return void|Ambigous <value, unknown, array>
758 function updateContributionStatus(&$params) {
759 // get minimum required values.
760 $statusId = CRM_Utils_Array
::value('contribution_status_id', $params);
761 $componentId = CRM_Utils_Array
::value('component_id', $params);
762 $componentName = CRM_Utils_Array
::value('componentName', $params);
763 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
765 if (!$contributionId ||
!$componentId ||
!$componentName ||
!$statusId) {
769 $input = $ids = $objects = array();
771 //get the required ids.
772 $ids['contribution'] = $contributionId;
774 if (!$ids['contact'] = CRM_Utils_Array
::value('contact_id', $params)) {
775 $ids['contact'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
781 if ($componentName == 'Event') {
783 $ids['participant'] = $componentId;
785 if (!$ids['event'] = CRM_Utils_Array
::value('event_id', $params)) {
786 $ids['event'] = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
793 if ($componentName == 'Membership') {
794 $name = 'contribute';
795 $ids['membership'] = $componentId;
797 $ids['contributionPage'] = NULL;
798 $ids['contributionRecur'] = NULL;
799 $input['component'] = $name;
801 $baseIPN = new CRM_Core_Payment_BaseIPN();
802 $transaction = new CRM_Core_Transaction();
804 // reset template values.
805 $template = CRM_Core_Smarty
::singleton();
806 $template->clearTemplateVars();
808 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
809 CRM_Core_Error
::fatal();
812 $contribution = &$objects['contribution'];
814 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name','flip' => 1));
815 $input['skipComponentSync'] = CRM_Utils_Array
::value('skipComponentSync', $params);
816 if ($statusId == $contributionStatuses['Cancelled']) {
817 $baseIPN->cancelled($objects, $transaction, $input);
818 $transaction->commit();
821 elseif ($statusId == $contributionStatuses['Failed']) {
822 $baseIPN->failed($objects, $transaction, $input);
823 $transaction->commit();
827 // status is not pending
828 if ($contribution->contribution_status_id
!= $contributionStatuses['Pending']) {
829 $transaction->commit();
833 //set values for ipn code.
835 'fee_amount', 'check_number', 'payment_instrument_id') as $field) {
836 if (!$input[$field] = CRM_Utils_Array
::value($field, $params)) {
837 $input[$field] = $contribution->$field;
840 if (!$input['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $params)) {
841 $input['trxn_id'] = $contribution->invoice_id
;
843 if (!$input['amount'] = CRM_Utils_Array
::value('total_amount', $params)) {
844 $input['amount'] = $contribution->total_amount
;
846 $input['is_test'] = $contribution->is_test
;
847 $input['net_amount'] = $contribution->net_amount
;
848 if (!empty($input['fee_amount']) && !empty($input['amount'])) {
849 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
852 //complete the contribution.
853 $baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
855 // reset template values before processing next transactions
856 $template->clearTemplateVars();
862 * Update pledge associated with a recurring contribution
864 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
866 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
867 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
868 * it should be assumed they
869 * do so with the intention that all payments will be linked
871 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
872 * If not the contribution will also need to be linked to the pledge
875 * @param $contribution
877 function updateRecurLinkedPledge(&$contribution) {
878 $returnProperties = array('id', 'pledge_id');
879 $paymentDetails = $paymentIDs = array();
881 if (CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id
,
882 $paymentDetails, $returnProperties
884 foreach ($paymentDetails as $key => $value) {
885 $paymentIDs[] = $value['id'];
886 $pledgeId = $value['pledge_id'];
890 //payment is not already linked - if it is linked with a pledge we need to create a link.
891 // return if it is not recurring contribution
892 if (!$contribution->contribution_recur_id
) {
896 $relatedContributions = new CRM_Contribute_DAO_Contribution();
897 $relatedContributions->contribution_recur_id
= $contribution->contribution_recur_id
;
898 $relatedContributions->find();
900 while ($relatedContributions->fetch()) {
901 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id
,
902 $paymentDetails, $returnProperties
906 if (empty($paymentDetails)) {
907 // payment is not linked with a pledge and neither are any other contributions on this
911 foreach ($paymentDetails as $key => $value) {
912 $pledgeId = $value['pledge_id'];
915 // we have a pledge now we need to get the oldest unpaid payment
916 $paymentDetails = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeId);
917 if(empty($paymentDetails['id'])){
918 // we can assume this pledge is now completed
919 // return now so we don't create a core error & roll back
922 $paymentDetails['contribution_id'] = $contribution->id
;
923 $paymentDetails['status_id'] = $contribution->contribution_status_id
;
924 $paymentDetails['actual_amount'] = $contribution->total_amount
;
926 // put contribution against it
927 $payment = CRM_Pledge_BAO_PledgePayment
::add($paymentDetails);
928 $paymentIDs[] = $payment->id
;
931 // update pledge and corresponding payment statuses
932 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id
,
933 NULL, $contribution->total_amount
938 * @param int $recurId
939 * @param $contribution
943 function addRecurLineItems($recurId, $contribution) {
946 $originalContributionID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
947 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($originalContributionID);
948 if (!empty($lineItems)) {
949 foreach ($lineItems as $key => $value) {
950 $priceField = new CRM_Price_DAO_PriceField();
951 $priceField->id
= $value['price_field_id'];
952 $priceField->find(TRUE);
953 $lineSets[$priceField->price_set_id
][] = $value;
954 if ($value['entity_table'] == 'civicrm_membership') {
956 civicrm_api3('membership_payment', 'create', array('membership_id' => $value['entity_id'], 'contribution_id' => $contribution->id
));
958 catch (CiviCRM_API3_Exception
$e) {
959 // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
960 // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
966 CRM_Price_BAO_LineItem
::processPriceSet($contribution->id
, $lineSets, $contribution);
971 // function to copy custom data of the
972 // initial contribution into its recurring contributions
974 * @param int $recurId
975 * @param int $targetContributionId
977 function copyCustomValues($recurId, $targetContributionId) {
978 if ($recurId && $targetContributionId) {
979 // get the initial contribution id of recur id
980 $sourceContributionId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
982 // if the same contribution is being proccessed then return
983 if ($sourceContributionId == $targetContributionId) {
986 // check if proper recurring contribution record is being processed
987 $targetConRecurId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
988 if ($targetConRecurId != $recurId) {
993 $extends = array('Contribution');
994 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
996 foreach ($groupTree as $groupID => $group) {
997 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
998 foreach ($group['fields'] as $fieldID => $field) {
999 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
1003 foreach ($table as $tableName => $tableColumns) {
1004 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
1005 $tableColumns[0] = $targetContributionId;
1006 $select = 'SELECT ' . implode(', ', $tableColumns);
1007 $from = ' FROM ' . $tableName;
1008 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
1009 $query = $insert . $select . $from . $where;
1010 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1016 // function to copy soft credit record of first recurring contribution
1017 // and add new soft credit against $targetContributionId
1019 * @param int $recurId
1020 * @param int $targetContributionId
1022 function addrecurSoftCredit($recurId, $targetContributionId) {
1023 $contriID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
1025 $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
1026 $soft_contribution->contribution_id
= $contriID;
1028 //check if first recurring contribution has any associated soft credit
1029 if ($soft_contribution->find(TRUE)) {
1030 $soft_contribution->contribution_id
= $targetContributionId;
1031 unset($soft_contribution->id
);
1032 $soft_contribution->save();