3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
35 class CRM_Core_Payment_BaseIPN
{
38 function __construct() {
39 self
::$_now = date('YmdHis');
42 function validateData(&$input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
44 // make sure contact exists and is valid
45 $contact = new CRM_Contact_DAO_Contact();
46 $contact->id
= $ids['contact'];
47 if (!$contact->find(TRUE)) {
48 CRM_Core_Error
::debug_log_message("Could not find contact record: {$ids['contact']} in IPN request: ".print_r($input, TRUE));
49 echo "Failure: Could not find contact record: {$ids['contact']}<p>";
53 // make sure contribution exists and is valid
54 $contribution = new CRM_Contribute_DAO_Contribution();
55 $contribution->id
= $ids['contribution'];
56 if (!$contribution->find(TRUE)) {
57 CRM_Core_Error
::debug_log_message("Could not find contribution record: {$contribution->id} in IPN request: ".print_r($input, TRUE));
58 echo "Failure: Could not find contribution record for {$contribution->id}<p>";
61 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
63 $objects['contact'] = &$contact;
64 $objects['contribution'] = &$contribution;
65 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
72 function createContact(&$input, &$ids, &$objects) {
74 $billingID = $ids['billing'];
78 "street_address-{$billingID}",
81 "postal_code-{$billingID}",
82 "country-{$billingID}",
84 foreach ($lookup as $name) {
85 $params[$name] = $input[$name];
87 if (!empty($params)) {
88 // update contact record
89 $contact = CRM_Contact_BAO_Contact
::createProfileContact($params, CRM_Core_DAO
::$_nullArray, $ids['contact']);
96 * Load objects related to contribution
98 * @input array information from Payment processor
100 function loadObjects(&$input, &$ids, &$objects, $required, $paymentProcessorID, $error_handling = NULL) {
101 if (empty($error_handling)) {
102 // default options are that we log an error & echo it out
103 // note that we should refactor this error handling into error code @ some point
104 // but for now setting up enough separation so we can do unit tests
105 $error_handling = array(
110 $ids['paymentProcessor'] = $paymentProcessorID;
111 if (is_a($objects['contribution'], 'CRM_Contribute_BAO_Contribution')) {
112 $contribution = &$objects['contribution'];
115 //legacy support - functions are 'used' to be able to pass in a DAO
116 $contribution = new CRM_Contribute_BAO_Contribution();
117 $contribution->id
= CRM_Utils_Array
::value('contribution', $ids);
118 $contribution->find(TRUE);
119 $objects['contribution'] = &$contribution;
122 $success = $contribution->loadRelatedObjects($input, $ids, $required);
125 if (CRM_Utils_Array
::value('log_error', $error_handling)) {
126 CRM_Core_Error
::debug_log_message($e->getMessage());
128 if (CRM_Utils_Array
::value('echo_error', $error_handling)) {
129 echo ($e->getMessage());
131 if (CRM_Utils_Array
::value('return_error', $error_handling)) {
134 'error_message' => ($e->getMessage()),
138 $objects = array_merge($objects, $contribution->_relatedObjects
);
142 function failed(&$objects, &$transaction, $input = array()) {
143 $contribution = &$objects['contribution'];
144 $memberships = array();
145 if (CRM_Utils_Array
::value('membership', $objects)) {
146 $memberships = &$objects['membership'];
147 if (is_numeric($memberships)) {
148 $memberships = array($objects['membership']);
152 $addLineItems = FALSE;
153 if (empty($contribution->id
)) {
154 $addLineItems = TRUE;
156 $participant = &$objects['participant'];
158 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
159 $contribution->contribution_status_id
= array_search('Failed', $contributionStatus);
160 $contribution->save();
162 //add lineitems for recurring payments
163 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
&& $addLineItems) {
164 $this->addrecurLineItems($objects['contributionRecur']->id
, $contribution->id
);
167 //copy initial contribution custom fields for recurring contributions
168 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
169 $this->copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
172 if (!CRM_Utils_Array
::value('skipComponentSync', $input)) {
173 if (!empty($memberships)) {
174 foreach ($memberships as $membership) {
176 $membership->status_id
= 4;
179 //update related Memberships.
180 $params = array('status_id' => 4);
181 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
187 $participant->status_id
= 4;
188 $participant->save();
192 $transaction->commit();
193 CRM_Core_Error
::debug_log_message("Setting contribution status to failed");
194 //echo "Success: Setting contribution status to failed<p>";
198 function pending(&$objects, &$transaction) {
199 $transaction->commit();
200 CRM_Core_Error
::debug_log_message("returning since contribution status is pending");
201 echo "Success: Returning since contribution status is pending<p>";
205 function cancelled(&$objects, &$transaction, $input = array()) {
206 $contribution = &$objects['contribution'];
207 $memberships = &$objects['membership'];
208 if (is_numeric($memberships)) {
209 $memberships = array($objects['membership']);
212 $participant = &$objects['participant'];
213 $addLineItems = FALSE;
214 if (empty($contribution->id
)) {
215 $addLineItems = TRUE;
217 $contribution->contribution_status_id
= 3;
218 $contribution->cancel_date
= self
::$_now;
219 $contribution->cancel_reason
= CRM_Utils_Array
::value('reasonCode', $input);
220 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
221 $contribution->receipt_date
= CRM_Utils_Date
::isoToMysql($contribution->receipt_date
);
222 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
223 $contribution->save();
225 //add lineitems for recurring payments
226 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
&& $addLineItems) {
227 $this->addrecurLineItems($objects['contributionRecur']->id
, $contribution->id
);
230 //copy initial contribution custom fields for recurring contributions
231 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
232 $this->copyCustomValues($objects['contributionRecur']->id
, $contribution->id
);
235 if (!CRM_Utils_Array
::value('skipComponentSync', $input)) {
236 if (!empty($memberships)) {
237 foreach ($memberships as $membership) {
239 $membership->status_id
= 6;
242 //update related Memberships.
243 $params = array('status_id' => 6);
244 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
250 $participant->status_id
= 4;
251 $participant->save();
254 $transaction->commit();
255 CRM_Core_Error
::debug_log_message("Setting contribution status to cancelled");
256 //echo "Success: Setting contribution status to cancelled<p>";
260 function unhandled(&$objects, &$transaction) {
261 $transaction->rollback();
262 // we dont handle this as yet
263 CRM_Core_Error
::debug_log_message("returning since contribution status: $status is not handled");
264 echo "Failure: contribution status $status is not handled<p>";
268 function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) {
269 $contribution = &$objects['contribution'];
270 $memberships = &$objects['membership'];
271 if (is_numeric($memberships)) {
272 $memberships = array($objects['membership']);
274 $participant = &$objects['participant'];
275 $event = &$objects['event'];
276 $changeToday = CRM_Utils_Array
::value('trxn_date', $input, self
::$_now);
277 $recurContrib = &$objects['contributionRecur'];
281 if ($input['component'] == 'contribute') {
282 if ($contribution->contribution_page_id
) {
283 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
284 $source = ts('Online Contribution') . ': ' . $values['title'];
286 elseif ($recurContrib && $recurContrib->id
) {
287 $contribution->contribution_page_id
= NULL;
288 $values['amount'] = $recurContrib->amount
;
289 $values['financial_type_id'] = $objects['contributionType']->id
;
290 $values['title'] = $source = ts('Offline Recurring Contribution');
291 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
292 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
293 $values['receipt_from_name'] = $domainValues[0];
294 $values['receipt_from_email'] = $domainValues[1];
297 $contribution->source
= $source;
298 if (CRM_Utils_Array
::value('is_email_receipt', $values)) {
299 $contribution->receipt_date
= self
::$_now;
302 if (!empty($memberships)) {
303 $membershipsUpdate = array( );
304 foreach ($memberships as $membershipTypeIdKey => $membership) {
308 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
309 $membership->membership_type_id
,
310 $membership->is_test
, $membership->id
313 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
314 // this picks up membership type changes during renewals
316 SELECT membership_type_id
317 FROM civicrm_membership_log
318 WHERE membership_id=$membership->id
321 $dao = new CRM_Core_DAO
;
324 if (!empty($dao->membership_type_id
)) {
325 $membership->membership_type_id
= $dao->membership_type_id
;
328 // else fall back to using current membership type
330 // else fall back to using current membership type
333 if ($currentMembership) {
336 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
337 * when Contribution mode is notify and membership is for renewal )
339 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
341 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
344 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
347 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
);
350 //get the status for membership.
351 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
358 $formatedParams = array('status_id' => CRM_Utils_Array
::value('id', $calcStatus, 2),
359 'join_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('join_date', $dates), $format),
360 'start_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('start_date', $dates), $format),
361 'end_date' => CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('end_date', $dates), $format),
363 //we might be renewing membership,
364 //so make status override false.
365 $formatedParams['is_override'] = FALSE;
366 $membership->copyValues($formatedParams);
369 //updating the membership log
370 $membershipLog = array();
371 $membershipLog = $formatedParams;
373 $logStartDate = $formatedParams['start_date'];
374 if (CRM_Utils_Array
::value('log_start_date', $dates)) {
375 $logStartDate = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
376 $logStartDate = CRM_Utils_Date
::isoToMysql($logStartDate);
379 $membershipLog['start_date'] = $logStartDate;
380 $membershipLog['membership_id'] = $membership->id
;
381 $membershipLog['modified_id'] = $membership->contact_id
;
382 $membershipLog['modified_date'] = date('Ymd');
383 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
385 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
387 //update related Memberships.
388 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formatedParams);
390 //update the membership type key of membership relatedObjects array
391 //if it has changed after membership update
392 if ($membershipTypeIdKey != $membership->membership_type_id
) {
393 $membershipsUpdate[$membership->membership_type_id
] = $membership;
394 $contribution->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
395 unset($contribution->_relatedObjects
['membership'][$membershipTypeIdKey]);
396 unset($memberships[$membershipTypeIdKey]);
400 //update the memberships object with updated membershipTypeId data
401 //if membershipTypeId has changed after membership update
402 if (!empty($membershipsUpdate)) {
403 $memberships = $memberships +
$membershipsUpdate;
409 $eventParams = array('id' => $objects['event']->id
);
410 $values['event'] = array();
412 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
414 //get location details
415 $locationParams = array('entity_id' => $objects['event']->id
, 'entity_table' => 'civicrm_event');
416 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
418 $ufJoinParams = array(
419 'entity_table' => 'civicrm_event',
420 'entity_id' => $ids['event'],
421 'module' => 'CiviEvent',
426 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
428 $values['custom_pre_id'] = $custom_pre_id;
429 $values['custom_post_id'] = $custom_post_ids;
431 $contribution->source
= ts('Online Event Registration') . ': ' . $values['event']['title'];
433 if ($values['event']['is_email_confirm']) {
434 $contribution->receipt_date
= self
::$_now;
435 $values['is_email_receipt'] = 1;
437 if (!CRM_Utils_Array
::value('skipComponentSync', $input)) {
438 $participant->status_id
= 1;
440 $participant->save();
443 if (CRM_Utils_Array
::value('net_amount', $input, 0) == 0 &&
444 CRM_Utils_Array
::value('fee_amount', $input, 0) != 0
446 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
448 $addLineItems = FALSE;
449 if (empty($contribution->id
)) {
450 $addLineItems = TRUE;
453 $contribution->contribution_status_id
= 1;
454 $contribution->is_test
= $input['is_test'];
455 $contribution->fee_amount
= CRM_Utils_Array
::value('fee_amount', $input, 0);
456 $contribution->net_amount
= CRM_Utils_Array
::value('net_amount', $input, 0);
457 $contribution->trxn_id
= $input['trxn_id'];
458 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
459 $contribution->thankyou_date
= CRM_Utils_Date
::isoToMysql($contribution->thankyou_date
);
460 $contribution->cancel_date
= 'null';
462 if (CRM_Utils_Array
::value('check_number', $input)) {
463 $contribution->check_number
= $input['check_number'];
466 if (CRM_Utils_Array
::value('payment_instrument_id', $input)) {
467 $contribution->payment_instrument_id
= $input['payment_instrument_id'];
470 if ($contribution->id
) {
471 $contributionId['id'] = $contribution->id
;
472 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues($contributionId, CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
474 $contribution->save();
476 //add lineitems for recurring payments
477 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
&& $addLineItems) {
478 $this->addrecurLineItems($objects['contributionRecur']->id
, $contribution->id
);
481 //copy initial contribution custom fields for recurring contributions
482 if ($recurContrib && $recurContrib->id
) {
483 $this->copyCustomValues($recurContrib->id
, $contribution->id
);
486 // next create the transaction record
487 $paymentProcessor = $paymentProcessorId = '';
488 if (isset($objects['paymentProcessor'])) {
489 if (is_array($objects['paymentProcessor'])) {
490 $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
491 $paymentProcessorId = $objects['paymentProcessor']['id'];
494 $paymentProcessor = $objects['paymentProcessor']->payment_processor_type
;
495 $paymentProcessorId = $objects['paymentProcessor']->id
;
499 if ($contribution->id
) {
500 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
501 if (!$input['prevContribution']->is_pay_later
&&
502 $input['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)) {
503 $input['payment_processor'] = $paymentProcessorId;
505 $input['total_amount'] = $input['amount'];
506 $input['contribution'] = $contribution;
507 $input['financial_type_id'] = $contribution->financial_type_id
;
509 if (CRM_Utils_Array
::value('participant', $contribution->_relatedObjects
)) {
510 $input['contribution_mode'] = 'participant';
511 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
512 $input['skipLineItem'] = 1;
515 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
518 self
::updateRecurLinkedPledge($contribution);
520 // create an activity record
521 if ($input['component'] == 'contribute') {
523 $targetContactID = NULL;
524 if (CRM_Utils_Array
::value('related_contact', $ids)) {
525 $targetContactID = $contribution->contact_id
;
526 $contribution->contact_id
= $ids['related_contact'];
528 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
532 CRM_Activity_BAO_Activity
::addActivity($participant);
535 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
536 $transaction->commit();
538 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
539 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
540 if (!array_key_exists('is_email_receipt', $values) ||
541 $values['is_email_receipt'] == 1
543 self
::sendMail($input, $ids, $objects, $values, $recur, FALSE);
544 CRM_Core_Error
::debug_log_message("Receipt sent");
547 CRM_Core_Error
::debug_log_message("Success: Database updated");
550 function getBillingID(&$ids) {
551 // get the billing location type
552 $locationTypes = CRM_Core_PseudoConstant
::locationType();
553 // CRM-8108 remove the ts around the Billing locationtype
554 //$ids['billing'] = array_search( ts('Billing'), $locationTypes );
555 $ids['billing'] = array_search('Billing', $locationTypes);
556 if (!$ids['billing']) {
557 CRM_Core_Error
::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
558 echo "Failure: Could not find billing location type<p>";
565 * Send receipt from contribution. Note that the compose message part has been moved to contribution
566 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
568 * @params array $input Incoming data from Payment processor
569 * @params array $ids Related object IDs
570 * @params array $values values related to objects that have already been loaded
571 * @params bool $recur is it part of a recurring contribution
572 * @params bool $returnMessageText Should text be returned instead of sent. This
573 * is because the function is also used to generate pdfs
575 function sendMail(&$input, &$ids, &$objects, &$values, $recur = FALSE, $returnMessageText = FALSE) {
576 $contribution = &$objects['contribution'];
577 $input['is_recur'] = $recur;
578 // set receipt from e-mail and name in value
579 if (!$returnMessageText) {
580 $session = CRM_Core_Session
::singleton();
581 $userID = $session->get('userID');
582 if (!empty($userID)) {
583 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
584 $values['receipt_from_email'] = $userEmail;
585 $values['receipt_from_name'] = $userName;
588 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
591 function updateContributionStatus(&$params) {
592 // get minimum required values.
593 $statusId = CRM_Utils_Array
::value('contribution_status_id', $params);
594 $componentId = CRM_Utils_Array
::value('component_id', $params);
595 $componentName = CRM_Utils_Array
::value('componentName', $params);
596 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
598 if (!$contributionId ||
!$componentId ||
!$componentName ||
!$statusId) {
602 $input = $ids = $objects = array();
604 //get the required ids.
605 $ids['contribution'] = $contributionId;
607 if (!$ids['contact'] = CRM_Utils_Array
::value('contact_id', $params)) {
608 $ids['contact'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
614 if ($componentName == 'Event') {
616 $ids['participant'] = $componentId;
618 if (!$ids['event'] = CRM_Utils_Array
::value('event_id', $params)) {
619 $ids['event'] = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
626 if ($componentName == 'Membership') {
627 $name = 'contribute';
628 $ids['membership'] = $componentId;
630 $ids['contributionPage'] = NULL;
631 $ids['contributionRecur'] = NULL;
632 $input['component'] = $name;
634 $baseIPN = new CRM_Core_Payment_BaseIPN();
635 $transaction = new CRM_Core_Transaction();
637 // reset template values.
638 $template = CRM_Core_Smarty
::singleton();
639 $template->clearTemplateVars();
641 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
642 CRM_Core_Error
::fatal();
645 $contribution = &$objects['contribution'];
647 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
648 $input['skipComponentSync'] = CRM_Utils_Array
::value('skipComponentSync', $params);
649 if ($statusId == array_search('Cancelled', $contributionStatuses)) {
650 $baseIPN->cancelled($objects, $transaction, $input);
651 $transaction->commit();
654 elseif ($statusId == array_search('Failed', $contributionStatuses)) {
655 $baseIPN->failed($objects, $transaction, $input);
656 $transaction->commit();
660 // status is not pending
661 if ($contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)) {
662 $transaction->commit();
666 //set values for ipn code.
668 'fee_amount', 'check_number', 'payment_instrument_id') as $field) {
669 if (!$input[$field] = CRM_Utils_Array
::value($field, $params)) {
670 $input[$field] = $contribution->$field;
673 if (!$input['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $params)) {
674 $input['trxn_id'] = $contribution->invoice_id
;
676 if (!$input['amount'] = CRM_Utils_Array
::value('total_amount', $params)) {
677 $input['amount'] = $contribution->total_amount
;
679 $input['is_test'] = $contribution->is_test
;
680 $input['net_amount'] = $contribution->net_amount
;
681 if (CRM_Utils_Array
::value('fee_amount', $input) && CRM_Utils_Array
::value('amount', $input)) {
682 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
685 //complete the contribution.
686 $baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
688 // reset template values before processing next transactions
689 $template->clearTemplateVars();
695 * Update pledge associated with a recurring contribution
697 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
699 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
700 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
701 * it should be assumed they
702 * do so with the intention that all payments will be linked
704 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
705 * If not the contribution will also need to be linked to the pledge
707 function updateRecurLinkedPledge(&$contribution) {
708 $returnProperties = array('id', 'pledge_id');
709 $paymentDetails = $paymentIDs = array();
711 if (CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id
,
712 $paymentDetails, $returnProperties
714 foreach ($paymentDetails as $key => $value) {
715 $paymentIDs[] = $value['id'];
716 $pledgeId = $value['pledge_id'];
720 //payment is not already linked - if it is linked with a pledge we need to create a link.
721 // return if it is not recurring contribution
722 if (!$contribution->contribution_recur_id
) {
726 $relatedContributions = new CRM_Contribute_DAO_Contribution();
727 $relatedContributions->contribution_recur_id
= $contribution->contribution_recur_id
;
728 $relatedContributions->find();
730 while ($relatedContributions->fetch()) {
731 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id
,
732 $paymentDetails, $returnProperties
736 if (empty($paymentDetails)) {
737 // payment is not linked with a pledge and neither are any other contributions on this
741 foreach ($paymentDetails as $key => $value) {
742 $pledgeId = $value['pledge_id'];
745 // we have a pledge now we need to get the oldest unpaid payment
746 $paymentDetails = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeId);
747 if(empty($paymentDetails['id'])){
748 // we can assume this pledge is now completed
749 // return now so we don't create a core error & roll back
752 $paymentDetails['contribution_id'] = $contribution->id
;
753 $paymentDetails['status_id'] = $contribution->contribution_status_id
;
754 $paymentDetails['actual_amount'] = $contribution->total_amount
;
756 // put contribution against it
757 $payment = CRM_Pledge_BAO_PledgePayment
::add($paymentDetails);
758 $paymentIDs[] = $payment->id
;
761 // update pledge and corresponding payment statuses
762 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id
,
763 NULL, $contribution->total_amount
767 function addrecurLineItems($recurId, $contributionId) {
768 $lineSets = $lineItems = array();
770 //Get the first contribution id with recur id
772 $contriID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
773 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($contriID, 'contribution');
774 if (!empty($lineItems)) {
775 foreach ($lineItems as $key => $value) {
776 $pricesetID = new CRM_Price_DAO_Field();
777 $pricesetID->id
= $value['price_field_id'];
778 $pricesetID->find(TRUE);
779 $lineSets[$pricesetID->price_set_id
][] = $value;
783 CRM_Price_BAO_LineItem
::processPriceSet($contributionId, $lineSets);
787 // function to copy custom data of the
788 // initial contribution into its recurring contributions
789 function copyCustomValues($recurId, $targetContributionId) {
790 if ($recurId && $targetContributionId) {
791 // get the initial contribution id of recur id
792 $sourceContributionId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
794 // if the same contribution is being proccessed then return
795 if ($sourceContributionId == $targetContributionId) {
798 // check if proper recurring contribution record is being processed
799 $targetConRecurId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
800 if ($targetConRecurId != $recurId) {
805 $extends = array('Contribution');
806 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
808 foreach ($groupTree as $groupID => $group) {
809 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
810 foreach ($group['fields'] as $fieldID => $field) {
811 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
815 foreach ($table as $tableName => $tableColumns) {
816 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
817 $tableColumns[0] = $targetContributionId;
818 $select = 'SELECT ' . implode(', ', $tableColumns);
819 $from = ' FROM ' . $tableName;
820 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
821 $query = $insert . $select . $from . $where;
822 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);