3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
33 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
36 * Static field for all the contribution information that we can potentially import
40 static $_importableFields = NULL;
43 * Static field for all the contribution information that we can potentially export
47 static $_exportableFields = NULL;
50 * Static field to hold financial trxn id's.
54 static $_trxnIDs = NULL;
57 * Field for all the objects related to this contribution
58 * @var array of objects (e.g membership object, participant object)
60 public $_relatedObjects = array();
63 * Field for the component - either 'event' (participant) or 'contribute'
64 * (any item related to a contribution page e.g. membership, pledge, contribution)
65 * This is used for composing messages because they have dependency on the
66 * contribution_page or event page - although over time we may eliminate that
68 * @var string component or event
70 public $_component = NULL;
73 * Possibly obsolete variable.
75 * If you use it please explain why it is set in the create function here.
79 public $trxn_result_code;
84 public function __construct() {
85 parent
::__construct();
89 * Takes an associative array and creates a contribution object.
91 * the function extract all the params it needs to initialize the create a
92 * contribution object. the params array could contain additional unused name/value
95 * @param array $params
96 * (reference ) an assoc array of name/value pairs.
98 * The array that holds all the db ids.
100 * @return \CRM_Contribute_BAO_Contribution
101 * @throws \CRM_Core_Exception
103 public static function add(&$params, $ids = array()) {
104 if (empty($params)) {
107 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
108 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
109 $duplicates = array();
110 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
111 $message = ts("Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: " . implode(', ', $duplicates));
112 throw new CRM_Core_Exception($message);
115 // first clean up all the money fields
116 $moneyFields = array(
120 'non_deductible_amount',
123 //if priceset is used, no need to cleanup money
124 if (!empty($params['skipCleanMoney'])) {
128 // @todo put a deprecated here - this should be done in the form layer.
129 $params['skipCleanMoney'] = FALSE;
130 Civi
::log()->warning('Deprecated code path. Money should always be clean before it hits the BAO.', array('civi.tag' => 'deprecated'));
133 foreach ($moneyFields as $field) {
134 if (isset($params[$field])) {
135 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
139 //set defaults in create mode
140 if (!$contributionID) {
141 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
143 if (empty($params['invoice_number'])) {
144 $nextContributionID = CRM_Core_DAO
::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
145 $params['invoice_number'] = self
::getInvoiceNumber($nextContributionID);
149 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
150 //if contribution is created with cancelled or refunded status, add credit note id
151 if (!empty($params['contribution_status_id'])) {
152 // @todo - should we include Chargeback? If so use self::isContributionStatusNegative($params['contribution_status_id'])
153 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
154 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
156 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
157 $params['creditnote_id'] = self
::createCreditNoteId();
162 // Since the fee amount is expecting this (later on) ensure it is always set.
163 // It would only not be set for an update where it is unchanged.
164 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', array('id' => $contributionID, 'return' => 'contribution_status_id'));
168 && CRM_Utils_Array
::value('membership_id', $params)
169 && self
::checkContributeSettings('deferred_revenue_enabled')
171 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
172 if ($memberStartDate) {
173 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
176 self
::calculateMissingAmountParams($params, $contributionID);
178 if (!empty($params['payment_instrument_id'])) {
179 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
180 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
181 $params['check_number'] = 'null';
185 $setPrevContribution = TRUE;
186 // CRM-13964 partial payment
187 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])) {
188 $partialAmtTotal = $params['partial_payment_total'];
189 $partialAmtPay = $params['partial_amount_to_pay'];
190 $params['total_amount'] = $partialAmtTotal;
191 if ($partialAmtPay < $partialAmtTotal) {
192 $params['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Partially paid');
193 $params['is_pay_later'] = 0;
194 $setPrevContribution = FALSE;
197 if ($contributionID && $setPrevContribution) {
198 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
201 if ($contributionID && !empty($params['revenue_recognition_date']) && !empty($params['prevContribution'])
202 && !($contributionStatus[$params['prevContribution']->contribution_status_id
] == 'Pending')
203 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
205 unset($params['revenue_recognition_date']);
208 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
209 isset($params['financial_type_id']))) {
210 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
213 if ($contributionID) {
214 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
217 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
219 $contribution = new CRM_Contribute_BAO_Contribution();
220 $contribution->copyValues($params);
222 $contribution->id
= $contributionID;
224 if (empty($contribution->id
)) {
225 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
226 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
227 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
231 $result = $contribution->save();
233 // Add financial_trxn details as part of fix for CRM-4724
234 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
235 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
237 //add Account details
238 $params['contribution'] = $contribution;
239 self
::recordFinancialAccounts($params);
241 if (self
::isUpdateToRecurringContribution($params)) {
242 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
243 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
244 $contributionStatus[$params['contribution_status_id']],
245 CRM_Utils_Array
::value('receive_date', $params)
249 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
251 if ($contributionID) {
252 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
255 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
262 * Is this contribution updating an existing recurring contribution.
264 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
265 * pending payment is being confirmed (or failing).
267 * @param array $params
271 public static function isUpdateToRecurringContribution($params) {
272 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
275 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
278 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
281 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
282 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
289 * Get defaults for new entity.
292 public static function getDefaults() {
294 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
295 FALSE, FALSE, FALSE, 'AND is_default = 1')
297 'contribution_status_id' => CRM_Core_Pseudoconstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
302 * Fetch the object and store the values in the values array.
304 * @param array $params
305 * Input parameters to find object.
306 * @param array $values
307 * Output values of the object.
309 * The array that holds all the db ids.
311 * @return CRM_Contribute_BAO_Contribution|null
312 * The found object or null
314 public static function getValues($params, &$values, &$ids) {
315 if (empty($params)) {
318 $contribution = new CRM_Contribute_BAO_Contribution();
320 $contribution->copyValues($params);
322 if ($contribution->find(TRUE)) {
323 $ids['contribution'] = $contribution->id
;
325 CRM_Core_DAO
::storeValues($contribution, $values);
327 return $contribution;
329 $null = NULL; // return by reference
334 * Get the values and resolve the most common mappings.
336 * Since contribution status is resolved in almost every function that calls getValues it makes
337 * sense to have an extra function to resolve it rather than repeat the code.
339 * Think carefully before adding more mappings to be resolved as there could be performance implications
340 * if this function starts to be called from more iterative functions.
342 * @param array $params
343 * Input parameters to find object.
346 * Array of the found contribution.
347 * @throws CRM_Core_Exception
349 public static function getValuesWithMappings($params) {
350 $values = $ids = array();
351 $contribution = self
::getValues($params, $values, $ids);
352 if (is_null($contribution)) {
353 throw new CRM_Core_Exception('No contribution found');
355 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
360 * Calculate net_amount & fee_amount if they are not set.
362 * Net amount should be total - fee.
363 * This should only be called for new contributions.
365 * @param array $params
366 * Params for a new contribution before they are saved.
367 * @param int|null $contributionID
368 * Contribution ID if we are dealing with an update.
370 * @throws \CiviCRM_API3_Exception
372 public static function calculateMissingAmountParams(&$params, $contributionID) {
373 if (!$contributionID && !isset($params['fee_amount'])) {
374 if (isset($params['total_amount']) && isset($params['net_amount'])) {
375 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
378 $params['fee_amount'] = 0;
381 if (!isset($params['net_amount'])) {
382 if (!$contributionID) {
383 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
386 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
387 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
388 // net_amount may need adjusting.
389 $contribution = civicrm_api3('Contribution', 'getsingle', array(
390 'id' => $contributionID,
391 'return' => array('total_amount', 'net_amount', 'fee_amount'),
393 $totalAmount = isset($params['total_amount']) ?
$params['total_amount'] : CRM_Utils_Array
::value('total_amount', $contribution);
394 $feeAmount = isset($params['fee_amount']) ?
$params['fee_amount'] : CRM_Utils_Array
::value('fee_amount', $contribution);
395 $params['net_amount'] = $totalAmount - $feeAmount;
403 * @param $billingLocationTypeID
407 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
408 $hasBillingField = FALSE;
409 $billingFields = array(
417 //build address array
418 $addressParams = array();
419 $addressParams['location_type_id'] = $billingLocationTypeID;
420 $addressParams['is_billing'] = 1;
422 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
423 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
424 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
425 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
427 foreach ($billingFields as $value) {
428 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
429 if (!empty($addressParams[$value])) {
430 $hasBillingField = TRUE;
433 return array($hasBillingField, $addressParams);
437 * Get address params ready to be passed to the payment processor.
439 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
440 * To create an address we need state_province_id.
442 * @param array $params
443 * @param int $billingLocationTypeID
447 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
448 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
449 foreach ($addressParams as $name => $field) {
450 if (substr($name, 0, 8) == 'billing_') {
451 $addressParams[substr($name, 9)] = $addressParams[$field];
454 return array($hasBillingField, $addressParams);
458 * Get the number of terms for this contribution for a given membership type
459 * based on querying the line item table and relevant price field values
460 * Note that any one contribution should only be able to have one line item relating to a particular membership
463 * @param int $membershipTypeID
465 * @param int $contributionID
469 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
470 $numTerms = CRM_Core_DAO
::singleValueQuery("
471 SELECT membership_num_terms FROM civicrm_line_item li
472 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
473 WHERE contribution_id = %1 AND membership_type_id = %2",
474 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
476 // default of 1 is precautionary
477 return empty($numTerms) ?
1 : $numTerms;
481 * Takes an associative array and creates a contribution object.
483 * @param array $params
484 * (reference ) an assoc array of name/value pairs.
486 * The array that holds all the db ids.
488 * @return CRM_Contribute_BAO_Contribution
490 public static function create(&$params, $ids = array()) {
491 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date', 'revenue_recognition_date');
492 foreach ($dateFields as $df) {
493 if (isset($params[$df])) {
494 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
498 $transaction = new CRM_Core_Transaction();
501 $contribution = self
::add($params, $ids);
503 catch (CRM_Core_Exception
$e) {
504 $transaction->rollback();
508 $params['contribution_id'] = $contribution->id
;
510 if (!empty($params['custom']) &&
511 is_array($params['custom'])
513 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
516 $session = CRM_Core_Session
::singleton();
518 if (!empty($params['note'])) {
520 'entity_table' => 'civicrm_contribution',
521 'note' => $params['note'],
522 'entity_id' => $contribution->id
,
523 'contact_id' => $session->get('userID'),
524 'modified_date' => date('Ymd'),
526 if (!$noteParams['contact_id']) {
527 $noteParams['contact_id'] = $params['contact_id'];
529 CRM_Core_BAO_Note
::add($noteParams);
532 // make entry in batch entity batch table
533 if (!empty($params['batch_id'])) {
534 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
535 $titleFields = array(
541 $retrieveRequired = 0;
542 foreach ($titleFields as $titleField) {
543 if (!isset($contribution->$titleField)) {
544 $retrieveRequired = 1;
548 if ($retrieveRequired == 1) {
549 $contribution->find(TRUE);
553 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
555 $transaction->commit();
557 $activity = civicrm_api3('Activity', 'get', array(
558 'source_record_id' => $contribution->id
,
559 'options' => array('limit' => 1),
561 'activity_type_id' => 'Contribution',
562 'return' => array('id', 'campaign'),
565 //CRM-18406: Update activity when edit contribution.
566 if ($activity['count']) {
567 // CRM-13237 : if activity record found, update it with campaign id of contribution
568 // @todo compare campaign ids first.
569 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity['id'], 'campaign_id', $contribution->campaign_id
);
570 $contribution->activity_id
= $activity['id'];
573 if (empty($contribution->contact_id
)) {
574 $contribution->find(TRUE);
576 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution');
578 // do not add to recent items for import, CRM-4399
579 if (empty($params['skipRecentView'])) {
580 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
581 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
583 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
584 $titleFields = array(
590 $retrieveRequired = 0;
591 foreach ($titleFields as $titleField) {
592 if (!isset($contribution->$titleField)) {
593 $retrieveRequired = 1;
597 if ($retrieveRequired == 1) {
598 $contribution->find(TRUE);
600 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
601 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
603 $recentOther = array();
604 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
605 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
606 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
610 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
611 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
612 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
616 // add the recently created Contribution
617 CRM_Utils_Recent
::add($title,
621 $contribution->contact_id
,
627 return $contribution;
631 * Get the values for pseudoconstants for name->value and reverse.
633 * @param array $defaults
634 * (reference) the default values, some of which need to be resolved.
635 * @param bool $reverse
636 * True if we want to resolve the values in the reverse direction (value -> name).
638 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
639 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
640 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
641 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
642 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
646 * Convert associative array names to values and vice-versa.
648 * This function is used by both the web form layer and the api. Note that
649 * the api needs the name => value conversion, also the view layer typically
650 * requires value => name conversion
652 * @param array $defaults
653 * @param string $property
654 * @param array $lookup
655 * @param bool $reverse
659 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
660 $id = $property . '_id';
662 $src = $reverse ?
$property : $id;
663 $dst = $reverse ?
$id : $property;
665 if (!array_key_exists($src, $defaults)) {
669 $look = $reverse ?
array_flip($lookup) : $lookup;
671 if (is_array($look)) {
672 if (!array_key_exists($defaults[$src], $look)) {
676 $defaults[$dst] = $look[$defaults[$src]];
681 * Retrieve DB object based on input parameters.
683 * It also stores all the retrieved values in the default array.
685 * @param array $params
686 * (reference ) an assoc array of name/value pairs.
687 * @param array $defaults
688 * (reference ) an assoc array to hold the name / value pairs.
689 * in a hierarchical manner
691 * (reference) the array that holds all the db ids.
693 * @return CRM_Contribute_BAO_Contribution
695 public static function retrieve(&$params, &$defaults, &$ids) {
696 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
697 return $contribution;
701 * Combine all the importable fields from the lower levels object.
703 * The ordering is important, since currently we do not have a weight
704 * scheme. Adding weight is super important and should be done in the
705 * next week or so, before this can be called complete.
707 * @param string $contactType
708 * @param bool $status
711 * array of importable Fields
713 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
714 if (!self
::$_importableFields) {
715 if (!self
::$_importableFields) {
716 self
::$_importableFields = array();
720 $fields = array('' => array('title' => ts('- do not import -')));
723 $fields = array('' => array('title' => ts('- Contribution Fields -')));
726 $note = CRM_Core_DAO_Note
::import();
727 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
728 unset($tmpFields['option_value']);
729 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
730 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
732 // Using new Dedupe rule.
734 'contact_type' => $contactType,
735 'used' => 'Unsupervised',
737 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
738 $tmpContactField = array();
739 if (is_array($fieldsArray)) {
740 foreach ($fieldsArray as $value) {
741 //skip if there is no dupe rule
742 if ($value == 'none') {
745 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
750 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
751 $tmpContactField[trim($value)] = $contactFields[trim($value)];
753 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
756 $title = $tmpContactField[trim($value)]['title'];
758 $tmpContactField[trim($value)]['title'] = $title;
762 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
763 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
764 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
765 $fields = array_merge($fields, $tmpContactField);
766 $fields = array_merge($fields, $tmpFields);
767 $fields = array_merge($fields, $note);
768 $fields = array_merge($fields, $optionFields);
769 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
770 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
771 self
::$_importableFields = $fields;
773 return self
::$_importableFields;
777 * Combine all the exportable fields from the lower level objects.
779 * @param bool $checkPermission
782 * array of exportable Fields
784 public static function &exportableFields($checkPermission = TRUE) {
785 if (!self
::$_exportableFields) {
786 if (!self
::$_exportableFields) {
787 self
::$_exportableFields = array();
790 $fields = CRM_Contribute_DAO_Contribution
::export();
791 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
792 $fields = array_merge(
794 CRM_Contribute_DAO_Product
::export(),
795 CRM_Contribute_DAO_ContributionProduct
::export(),
796 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
798 'contribution_product_id' => [
799 'title' => ts('Premium'),
800 'name' => 'contribution_product_id',
801 'where' => 'civicrm_product.id',
802 'data_type' => CRM_Utils_Type
::T_INT
,
807 $typeField = CRM_Financial_DAO_FinancialType
::export();
808 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
810 $contributionPage = array(
811 'contribution_page' => array(
812 'title' => ts('Contribution Page'),
813 'name' => 'contribution_page',
814 'where' => 'civicrm_contribution_page.title',
815 'data_type' => CRM_Utils_Type
::T_STRING
,
819 $contributionNote = array(
820 'contribution_note' => array(
821 'title' => ts('Contribution Note'),
822 'name' => 'contribution_note',
823 'data_type' => CRM_Utils_Type
::T_TEXT
,
827 $extraFields = array(
828 'contribution_batch' => array(
829 'title' => ts('Batch Name'),
834 $campaignTitle = array(
835 'contribution_campaign_title' => array(
836 'title' => ts('Campaign Title'),
837 'name' => 'campaign_title',
838 'where' => 'civicrm_campaign.title',
839 'data_type' => CRM_Utils_Type
::T_STRING
,
842 $softCreditFields = array(
843 'contribution_soft_credit_name' => array(
844 'name' => 'contribution_soft_credit_name',
845 'title' => ts('Soft Credit For'),
846 'where' => 'civicrm_contact_d.display_name',
847 'data_type' => CRM_Utils_Type
::T_STRING
,
849 'contribution_soft_credit_amount' => array(
850 'name' => 'contribution_soft_credit_amount',
851 'title' => ts('Soft Credit Amount'),
852 'where' => 'civicrm_contribution_soft.amount',
853 'data_type' => CRM_Utils_Type
::T_MONEY
,
855 'contribution_soft_credit_type' => array(
856 'name' => 'contribution_soft_credit_type',
857 'title' => ts('Soft Credit Type'),
858 'where' => 'contribution_softcredit_type.label',
859 'data_type' => CRM_Utils_Type
::T_STRING
,
861 'contribution_soft_credit_contribution_id' => array(
862 'name' => 'contribution_soft_credit_contribution_id',
863 'title' => ts('Soft Credit For Contribution ID'),
864 'where' => 'civicrm_contribution_soft.contribution_id',
865 'data_type' => CRM_Utils_Type
::T_INT
,
867 'contribution_soft_credit_contact_id' => array(
868 'name' => 'contribution_soft_credit_contact_id',
869 'title' => ts('Soft Credit For Contact ID'),
870 'where' => 'civicrm_contact_d.id',
871 'data_type' => CRM_Utils_Type
::T_INT
,
875 $fields = array_merge($fields, $typeField, $contributionPage,
876 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
877 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
880 self
::$_exportableFields = $fields;
883 return self
::$_exportableFields;
889 public function addSelectWhereClause() {
890 $whereClauses = parent
::addSelectWhereClause();
891 if ($whereClauses !== []) {
892 // In this case permisssions have been applied & we assume the
893 // financialaclreport is applying these
894 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
895 return $whereClauses;
898 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
899 return $whereClauses;
901 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
903 $whereClauses['financial_type_id'] = 'IN (0)';
906 $whereClauses['financial_type_id'] = [
907 'IN (' . implode(',', array_keys($types)) . ')'
910 return $whereClauses;
914 * @param null $status
915 * @param null $startDate
916 * @param null $endDate
920 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
924 $where[] = 'contribution_status_id = 1';
928 $where[] = 'contribution_status_id = 3';
933 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
936 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
938 $financialTypeACLJoin = '';
939 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
940 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
941 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
942 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
943 if ($financialTypes) {
944 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
945 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
948 $where[] = "c.financial_type_id IN (0)";
952 $whereCond = implode(' AND ', $where);
955 SELECT sum( total_amount ) as total_amount,
956 count( c.id ) as total_count,
958 FROM civicrm_contribution c
959 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
960 $financialTypeACLJoin
962 AND ( is_test = 0 OR is_test IS NULL )
963 AND contact.is_deleted = 0
967 $dao = CRM_Core_DAO
::executeQuery($query);
970 while ($dao->fetch()) {
971 $count +
= $dao->total_count
;
972 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
976 'amount' => implode(', ', $amount),
984 * Delete the indirect records associated with this contribution first.
989 * $results no of deleted Contribution on success, false otherwise
991 public static function deleteContribution($id) {
992 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
994 $transaction = new CRM_Core_Transaction();
997 //delete activity record
999 'source_record_id' => $id,
1000 // activity type id for contribution
1001 'activity_type_id' => 6,
1004 CRM_Activity_BAO_Activity
::deleteActivity($params);
1006 //delete billing address if exists for this contribution.
1007 self
::deleteAddress($id);
1009 //update pledge and pledge payment, CRM-3961
1010 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1012 // remove entry from civicrm_price_set_entity, CRM-5095
1013 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1014 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1016 // cleanup line items.
1017 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1019 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1020 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1022 if ($participantId) {
1023 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1026 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1030 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1031 $noteId = key($note);
1033 CRM_Core_BAO_Note
::del($noteId, FALSE);
1036 $dao = new CRM_Contribute_DAO_Contribution();
1039 $results = $dao->delete();
1041 $transaction->commit();
1043 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1045 // delete the recently created Contribution
1046 $contributionRecent = array(
1048 'type' => 'Contribution',
1050 CRM_Utils_Recent
::del($contributionRecent);
1056 * React to a financial transaction (payment) failure.
1058 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1059 * payments is important for forensic and outreach reasons.
1061 * @param int $contributionID
1062 * @param int $contactID
1063 * @param string $message
1065 * @throws \CiviCRM_API3_Exception
1067 public static function failPayment($contributionID, $contactID, $message) {
1068 civicrm_api3('activity', 'create', array(
1069 'activity_type_id' => 'Failed Payment',
1070 'details' => $message,
1071 'subject' => ts('Payment failed at payment processor'),
1072 'source_record_id' => $contributionID,
1073 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1077 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1078 civicrm_api3('contribution', 'create', array(
1079 'id' => $contributionID,
1080 'contribution_status_id' => 'Failed',
1085 * Check if there is a contribution with the same trxn_id or invoice_id.
1087 * @param array $input
1088 * An assoc array of name/value pairs.
1089 * @param array $duplicates
1090 * (reference) store ids of duplicate contribs.
1094 * true if duplicate, false otherwise
1096 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1098 $id = CRM_Utils_Array
::value('id', $input);
1100 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1101 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1107 $clause[] = "trxn_id = %1";
1108 $input[1] = array($trxn_id, 'String');
1112 $clause[] = "invoice_id = %2";
1113 $input[2] = array($invoice_id, 'String');
1116 if (empty($clause)) {
1120 $clause = implode(' OR ', $clause);
1122 $clause = "( $clause ) AND id != %3";
1123 $input[3] = array($id, 'Integer');
1126 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1127 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1129 while ($dao->fetch()) {
1130 $duplicates[] = $dao->id
;
1137 * Takes an associative array and creates a contribution_product object.
1139 * the function extract all the params it needs to initialize the create a
1140 * contribution_product object. the params array could contain additional unused name/value
1143 * @param array $params
1144 * (reference) an assoc array of name/value pairs.
1146 * @return CRM_Contribute_DAO_ContributionProduct
1148 public static function addPremium(&$params) {
1149 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1150 $contributionProduct->copyValues($params);
1151 return $contributionProduct->save();
1155 * Get list of contribution fields for profile.
1156 * For now we only allow custom contribution fields to be in
1159 * @param bool $addExtraFields
1160 * True if special fields needs to be added.
1163 * the list of contribution fields
1165 public static function getContributionFields($addExtraFields = TRUE) {
1166 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1167 // @todo remove this - this line was added because payment_instrument_id was not
1168 // set to exportable - but now it is.
1169 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1171 if ($addExtraFields) {
1172 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1175 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1177 foreach ($contributionFields as $key => $var) {
1178 if ($key == 'contribution_contact_id') {
1181 elseif ($key == 'contribution_campaign_id') {
1182 $var['title'] = ts('Campaign');
1184 $fields[$key] = $var;
1187 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1192 * Add extra fields specific to contribution.
1194 public static function getSpecialContributionFields() {
1195 $extraFields = array(
1196 'contribution_soft_credit_name' => array(
1197 'name' => 'contribution_soft_credit_name',
1198 'title' => ts('Soft Credit Name'),
1199 'headerPattern' => '/^soft_credit_name$/i',
1200 'where' => 'civicrm_contact_d.display_name',
1202 'contribution_soft_credit_email' => array(
1203 'name' => 'contribution_soft_credit_email',
1204 'title' => ts('Soft Credit Email'),
1205 'headerPattern' => '/^soft_credit_email$/i',
1206 'where' => 'soft_email.email',
1208 'contribution_soft_credit_phone' => array(
1209 'name' => 'contribution_soft_credit_phone',
1210 'title' => ts('Soft Credit Phone'),
1211 'headerPattern' => '/^soft_credit_phone$/i',
1212 'where' => 'soft_phone.phone',
1214 'contribution_soft_credit_contact_id' => array(
1215 'name' => 'contribution_soft_credit_contact_id',
1216 'title' => ts('Soft Credit Contact ID'),
1217 'headerPattern' => '/^soft_credit_contact_id$/i',
1218 'where' => 'civicrm_contribution_soft.contact_id',
1220 'contribution_pcp_title' => array(
1221 'name' => 'contribution_pcp_title',
1222 'title' => ts('Personal Campaign Page Title'),
1223 'headerPattern' => '/^contribution_pcp_title$/i',
1224 'where' => 'contribution_pcp.title',
1228 return $extraFields;
1232 * @param int $pageID
1236 public static function getCurrentandGoalAmount($pageID) {
1238 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1239 FROM civicrm_contribution_page p,
1240 civicrm_contribution c
1241 WHERE p.id = c.contribution_page_id
1243 AND c.cancel_date is null
1247 $config = CRM_Core_Config
::singleton();
1248 $params = array(1 => array($pageID, 'Integer'));
1249 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1251 if ($dao->fetch()) {
1252 return array($dao->goal
, $dao->total
);
1255 return array(NULL, NULL);
1260 * Get list of contributions which credit the passed in contact ID.
1262 * The returned array provides details about the original contribution & donor.
1264 * @todo - this is a confusing function called from one place. It has a test. It would be
1265 * nice to deprecate it.
1267 * @param int $honorId
1268 * In Honor of Contact ID.
1271 * list of contribution fields
1273 public static function getHonorContacts($honorId) {
1275 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1276 $honorDAO->contact_id
= $honorId;
1279 $type = CRM_Contribute_PseudoConstant
::financialType();
1281 while ($honorDAO->fetch()) {
1282 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1283 $contributionDAO->id
= $honorDAO->contribution_id
;
1285 if ($contributionDAO->find(TRUE)) {
1286 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1287 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1288 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1289 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1290 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1291 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1292 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1293 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1294 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1302 * Get the sort name of a contact for a particular contribution.
1305 * Id of the contribution.
1307 * @return null|string
1308 * sort name of the contact if found
1310 public static function sortName($id) {
1311 $id = CRM_Utils_Type
::escape($id, 'Integer');
1314 SELECT civicrm_contact.sort_name
1315 FROM civicrm_contribution, civicrm_contact
1316 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1317 AND civicrm_contribution.id = {$id}
1319 return CRM_Core_DAO
::singleValueQuery($query);
1323 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1325 * @param int|array $contactIDs
1329 public static function annual($contactIDs) {
1330 if (!is_array($contactIDs)) {
1331 // In practice I can't fine any evidence that this function is ever called with
1332 // anything other than a single contact id, but left like this due to .... fear.
1333 $contactIDs = explode(',', $contactIDs);
1336 $query = self
::getAnnualQuery($contactIDs);
1337 $dao = CRM_Core_DAO
::executeQuery($query);
1339 $amount = $average = array();
1340 while ($dao->fetch()) {
1341 if ($dao->count
> 0 && $dao->amount
> 0) {
1342 $count +
= $dao->count
;
1343 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1344 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1350 implode(', ', $amount),
1351 implode(', ', $average),
1354 return array(0, 0, 0);
1358 * Check if there is a contribution with the params passed in.
1360 * Used for trxn_id,invoice_id and contribution_id
1362 * @param array $params
1363 * An assoc array of name/value pairs.
1366 * contribution id if success else NULL
1368 public static function checkDuplicateIds($params) {
1369 $dao = new CRM_Contribute_DAO_Contribution();
1373 foreach ($params as $k => $v) {
1375 $clause[] = "$k = '$v'";
1378 $clause = implode(' AND ', $clause);
1379 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1380 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1382 while ($dao->fetch()) {
1390 * Get the contribution details for component export.
1392 * @param int $exportMode
1394 * @param array $componentIds
1400 public static function getContributionDetails($exportMode, $componentIds) {
1401 $paymentDetails = array();
1402 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1404 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1405 $componentSelect = " civicrm_participant_payment.participant_id id";
1406 $additionalClause = "
1407 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1408 AND civicrm_participant_payment.participant_id {$componentClause} )
1411 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1412 $componentSelect = " civicrm_membership_payment.membership_id id";
1413 $additionalClause = "
1414 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1415 AND civicrm_membership_payment.membership_id {$componentClause} )
1418 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1419 $componentSelect = " civicrm_pledge_payment.id id";
1420 $additionalClause = "
1421 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1422 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1426 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1427 trxn_id, {$componentSelect}
1428 FROM civicrm_contribution
1429 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1430 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1431 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1432 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1433 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1434 AND option_group_contribution_status.id = contribution_status.option_group_id )
1438 $dao = CRM_Core_DAO
::executeQuery($query);
1440 while ($dao->fetch()) {
1441 $paymentDetails[$dao->id
] = array(
1442 'total_amount' => $dao->total_amount
,
1443 'contribution_status' => $dao->status
,
1444 'receive_date' => $dao->receive_date
,
1445 'pay_instru' => $dao->payment_instrument
,
1446 'trxn_id' => $dao->trxn_id
,
1450 return $paymentDetails;
1454 * Create address associated with contribution record.
1456 * As long as there is one or more billing field in the parameters we will create the address.
1458 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1461 * @param array $params
1462 * @param int $billingLocationTypeID
1467 public static function createAddress($params, $billingLocationTypeID) {
1468 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1469 if ($hasBillingField) {
1470 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1471 return $address->id
;
1478 * Delete billing address record related contribution.
1480 * @param int $contributionId
1481 * @param int $contactId
1483 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1485 $contactJoin = NULL;
1487 if ($contributionId) {
1488 $clauses[] = "cc.id = {$contributionId}";
1492 $clauses[] = "cco.id = {$contactId}";
1493 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1496 if (empty($clauses)) {
1497 CRM_Core_Error
::fatal();
1500 $condition = implode(' OR ', $clauses);
1504 FROM civicrm_address ca
1505 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1509 $dao = CRM_Core_DAO
::executeQuery($query);
1511 while ($dao->fetch()) {
1512 $params = array('id' => $dao->id
);
1513 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1518 * This function check online pending contribution associated w/
1519 * Online Event Registration or Online Membership signup.
1521 * @param int $componentId
1522 * Participant/membership id.
1523 * @param string $componentName
1527 * pending contribution id.
1529 public static function checkOnlinePendingContribution($componentId, $componentName) {
1530 $contributionId = NULL;
1531 if (!$componentId ||
1532 !in_array($componentName, array('Event', 'Membership'))
1534 return $contributionId;
1537 if ($componentName == 'Event') {
1538 $idName = 'participant_id';
1539 $componentTable = 'civicrm_participant';
1540 $paymentTable = 'civicrm_participant_payment';
1541 $source = ts('Online Event Registration');
1544 if ($componentName == 'Membership') {
1545 $idName = 'membership_id';
1546 $componentTable = 'civicrm_membership';
1547 $paymentTable = 'civicrm_membership_payment';
1548 $source = ts('Online Contribution');
1551 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1554 SELECT component.id as {$idName},
1555 componentPayment.contribution_id as contribution_id,
1556 contribution.source source,
1557 contribution.contribution_status_id as contribution_status_id,
1558 contribution.is_pay_later as is_pay_later
1559 FROM $componentTable component
1560 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1561 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1562 WHERE component.id = {$componentId}";
1564 $dao = CRM_Core_DAO
::executeQuery($query);
1566 while ($dao->fetch()) {
1567 if ($dao->contribution_id
&&
1568 $dao->is_pay_later
&&
1569 $dao->contribution_status_id
== $pendingStatusId &&
1570 strpos($dao->source
, $source) !== FALSE
1572 $contributionId = $dao->contribution_id
;
1577 return $contributionId;
1581 * Update contribution as well as related objects.
1583 * This function by-passes hooks - to address this - don't use this function.
1587 * Use api contribute.completetransaction
1588 * For failures use failPayment (preferably exposing by api in the process).
1590 * @param array $params
1591 * @param bool $processContributionObject
1594 * @throws \Exception
1596 public static function transitionComponents($params, $processContributionObject = FALSE) {
1597 // get minimum required values.
1598 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1599 $componentId = CRM_Utils_Array
::value('component_id', $params);
1600 $componentName = CRM_Utils_Array
::value('componentName', $params);
1601 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1602 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1604 // if we already processed contribution object pass previous status id.
1605 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1607 $updateResult = array();
1609 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1611 // we process only ( Completed, Cancelled, or Failed ) contributions.
1612 if (!$contributionId ||
1613 !in_array($contributionStatusId, array(
1614 array_search('Completed', $contributionStatuses),
1615 array_search('Cancelled', $contributionStatuses),
1616 array_search('Failed', $contributionStatuses),
1619 return $updateResult;
1622 if (!$componentName ||
!$componentId) {
1623 // get the related component details.
1624 $componentDetails = self
::getComponentDetails($contributionId);
1627 $componentDetails['contact_id'] = $contactId;
1628 $componentDetails['component'] = $componentName;
1630 if ($componentName == 'event') {
1631 $componentDetails['participant'] = $componentId;
1634 $componentDetails['membership'] = $componentId;
1638 if (!empty($componentDetails['contact_id'])) {
1639 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1645 // do check for required ids.
1646 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1647 return $updateResult;
1650 //now we are ready w/ required ids, start processing.
1652 $baseIPN = new CRM_Core_Payment_BaseIPN();
1654 $input = $ids = $objects = array();
1656 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1657 $ids['contribution'] = $contributionId;
1658 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1659 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1660 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1661 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1662 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1663 $ids['contributionRecur'] = NULL;
1664 $ids['contributionPage'] = NULL;
1666 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1667 CRM_Core_Error
::fatal();
1670 $memberships = &$objects['membership'];
1671 $participant = &$objects['participant'];
1672 $pledgePayment = &$objects['pledge_payment'];
1673 $contribution = &$objects['contribution'];
1675 if ($pledgePayment) {
1676 $pledgePaymentIDs = array();
1677 foreach ($pledgePayment as $key => $object) {
1678 $pledgePaymentIDs[] = $object->id
;
1680 $pledgeID = $pledgePayment[0]->pledge_id
;
1683 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1686 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1687 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1692 // we might want to process contribution object.
1693 $processContribution = FALSE;
1694 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1695 if (is_array($memberships)) {
1696 foreach ($memberships as $membership) {
1698 //Update Membership status if there is no other completed contribution associated with the membership.
1699 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1700 foreach ($relatedContributions as $contriId) {
1701 if ($contriId == $contributionId) {
1704 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1705 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1709 if ($membership && $update) {
1710 $newStatus = array_search('Cancelled', $membershipStatuses);
1713 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1714 $activityParam = array(
1715 'subject' => "Status changed from {$allStatus[$membership->status_id]} to {$allStatus[$newStatus]}",
1716 'source_contact_id' => CRM_Core_Session
::singleton()->get('userID'),
1717 'target_contact_id' => $membership->contact_id
,
1718 'source_record_id' => $membership->id
,
1719 'activity_type_id' => 'Change Membership Status',
1720 'status_id' => 'Completed',
1721 'priority_id' => 'Normal',
1722 'activity_date_time' => 'now',
1725 $membership->status_id
= $newStatus;
1726 $membership->is_override
= TRUE;
1727 $membership->status_override_end_date
= 'null';
1728 $membership->save();
1729 civicrm_api3('activity', 'create', $activityParam);
1731 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1732 if ($processContributionObject) {
1733 $processContribution = TRUE;
1740 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1741 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1743 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1744 if ($processContributionObject) {
1745 $processContribution = TRUE;
1749 if ($pledgePayment) {
1750 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1752 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1753 if ($processContributionObject) {
1754 $processContribution = TRUE;
1758 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1759 if (is_array($memberships)) {
1760 foreach ($memberships as $membership) {
1762 //Update Membership status if there is no other completed contribution associated with the membership.
1763 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1764 foreach ($relatedContributions as $contriId) {
1765 if ($contriId == $contributionId) {
1768 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1769 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1773 if ($membership && $update) {
1774 $membership->status_id
= array_search('Expired', $membershipStatuses);
1775 $membership->is_override
= TRUE;
1776 $membership->status_override_end_date
= 'null';
1777 $membership->save();
1779 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1780 if ($processContributionObject) {
1781 $processContribution = TRUE;
1787 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1788 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1790 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1791 if ($processContributionObject) {
1792 $processContribution = TRUE;
1796 if ($pledgePayment) {
1797 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1799 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1800 if ($processContributionObject) {
1801 $processContribution = TRUE;
1805 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1807 // only pending contribution related object processed.
1808 if ($previousContriStatusId &&
1809 !in_array($contributionStatuses[$previousContriStatusId], array('Pending', 'Partially paid'))
1811 // this is case when we already processed contribution object.
1812 return $updateResult;
1814 elseif (!$previousContriStatusId &&
1815 !in_array($contributionStatuses[$contribution->contribution_status_id
], array('Pending', 'Partially paid'))
1817 // this is case when we are going to process contribution object later.
1818 return $updateResult;
1821 if (is_array($memberships)) {
1822 foreach ($memberships as $membership) {
1827 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1828 $membership->membership_type_id
,
1829 $membership->is_test
, $membership->id
1832 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1833 // this picks up membership type changes during renewals
1835 SELECT membership_type_id
1836 FROM civicrm_membership_log
1837 WHERE membership_id=$membership->id
1840 $dao = new CRM_Core_DAO();
1842 if ($dao->fetch()) {
1843 if (!empty($dao->membership_type_id
)) {
1844 $membership->membership_type_id
= $dao->membership_type_id
;
1845 $membership->save();
1848 // else fall back to using current membership type
1851 // Figure out number of terms
1853 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
1854 foreach ($lineitems as $lineitem) {
1855 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1856 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1858 // in case membership_num_terms comes through as null or zero
1859 $numterms = $numterms >= 1 ?
$numterms : 1;
1864 // CRM-15735-to update the membership status as per the contribution receive date
1866 $oldStatus = $membership->status_id
;
1867 if (!empty($params['receive_date'])) {
1868 $joinDate = $params['receive_date'];
1869 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1870 $membership->end_date
,
1871 $membership->join_date
,
1872 $params['receive_date'],
1874 $membership->membership_type_id
,
1877 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1878 $membership->save();
1881 if ($currentMembership) {
1882 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1883 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1884 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1887 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1890 //get the status for membership.
1891 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1893 $dates['join_date'],
1896 $membership->membership_type_id
,
1900 $formattedParams = array(
1901 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1902 array_search('Current', $membershipStatuses)
1904 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1905 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1906 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1909 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1911 $membership->copyValues($formattedParams);
1912 $membership->save();
1914 //updating the membership log
1915 $membershipLog = array();
1916 $membershipLog = $formattedParams;
1917 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1918 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1920 $membershipLog['start_date'] = $logStartDate;
1921 $membershipLog['membership_id'] = $membership->id
;
1922 $membershipLog['modified_id'] = $membership->contact_id
;
1923 $membershipLog['modified_date'] = date('Ymd');
1924 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1926 CRM_Member_BAO_MembershipLog
::add($membershipLog);
1928 //update related Memberships.
1929 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1931 foreach (array('Membership Signup', 'Membership Renewal') as $activityType) {
1932 $scheduledActivityID = CRM_Utils_Array
::value('id',
1933 civicrm_api3('Activity', 'Get',
1935 'source_record_id' => $membership->id
,
1936 'activity_type_id' => $activityType,
1937 'status_id' => 'Scheduled',
1940 'sort' => 'id DESC',
1945 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
1946 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
1947 if ($scheduledActivityID) {
1948 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, array('id' => $scheduledActivityID));
1953 // track membership status change if any
1954 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
1955 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1956 CRM_Activity_BAO_Activity
::addActivity($membership,
1957 'Change Membership Status',
1960 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
1961 'source_contact_id' => $membershipLog['modified_id'],
1962 'priority_id' => 'Normal',
1967 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1970 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1971 if ($processContributionObject) {
1972 $processContribution = TRUE;
1975 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1981 $updatedStatusId = array_search('Registered', $participantStatuses);
1982 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1984 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1985 if ($processContributionObject) {
1986 $processContribution = TRUE;
1990 if ($pledgePayment) {
1991 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1993 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1994 if ($processContributionObject) {
1995 $processContribution = TRUE;
2000 // process contribution object.
2001 if ($processContribution) {
2002 $contributionParams = array();
2009 'payment_instrument_id',
2012 'financial_type_id',
2013 'contribution_status_id',
2014 'non_deductible_amount',
2018 foreach ($fields as $field) {
2019 if (empty($params[$field])) {
2022 $contributionParams[$field] = $params[$field];
2025 $ids = array('contribution' => $contributionId);
2026 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2029 return $updateResult;
2033 * Returns all contribution related object ids.
2035 * @param $contributionId
2039 public static function getComponentDetails($contributionId) {
2040 $componentDetails = $pledgePayment = array();
2041 if (!$contributionId) {
2042 return $componentDetails;
2046 SELECT c.id as contribution_id,
2047 c.contact_id as contact_id,
2048 c.contribution_recur_id,
2049 mp.membership_id as membership_id,
2050 m.membership_type_id as membership_type_id,
2051 pp.participant_id as participant_id,
2052 p.event_id as event_id,
2053 pgp.id as pledge_payment_id
2054 FROM civicrm_contribution c
2055 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2056 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2057 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2058 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2059 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2060 WHERE c.id = $contributionId";
2062 $dao = CRM_Core_DAO
::executeQuery($query);
2063 $componentDetails = array();
2065 while ($dao->fetch()) {
2066 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2067 $componentDetails['contact_id'] = $dao->contact_id
;
2068 if ($dao->event_id
) {
2069 $componentDetails['event'] = $dao->event_id
;
2071 if ($dao->participant_id
) {
2072 $componentDetails['participant'] = $dao->participant_id
;
2074 if ($dao->membership_id
) {
2075 if (!isset($componentDetails['membership'])) {
2076 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
2078 $componentDetails['membership'][] = $dao->membership_id
;
2079 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2081 if ($dao->pledge_payment_id
) {
2082 $pledgePayment[] = $dao->pledge_payment_id
;
2084 if ($dao->contribution_recur_id
) {
2085 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2089 if ($pledgePayment) {
2090 $componentDetails['pledge_payment'] = $pledgePayment;
2093 return $componentDetails;
2097 * @param int $contactId
2098 * @param bool $includeSoftCredit
2100 * @return null|string
2102 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2106 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2107 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2108 $liWhere = " AND i.financial_type_id IN (0)";
2109 if (!empty($financialTypes)) {
2110 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2111 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2113 $contactContributionsSQL = "
2114 SELECT contribution.id AS id
2115 FROM civicrm_contribution contribution
2116 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2117 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2121 $contactSoftCreditContributionsSQL = "
2122 SELECT contribution.id
2123 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2124 ON ( contribution.id = softContribution.contribution_id )
2125 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2126 $query = "SELECT count( x.id ) count FROM ( ";
2127 $query .= $contactContributionsSQL;
2129 if ($includeSoftCredit) {
2130 $query .= " UNION ";
2131 $query .= $contactSoftCreditContributionsSQL;
2136 return CRM_Core_DAO
::singleValueQuery($query);
2140 * Repeat a transaction as part of a recurring series.
2142 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
2143 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
2144 * subsequent call to the contribution.completetransaction api.
2146 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
2148 * @param CRM_Contribute_BAO_Contribution $contribution
2149 * @param array $input
2150 * @param array $contributionParams
2151 * @param int $paymentProcessorID
2154 * @throws CiviCRM_API3_Exception
2156 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
2157 if (!empty($contribution->id
)) {
2160 if (empty($contribution->id
)) {
2161 // Unclear why this would only be set for repeats.
2162 if (!empty($input['amount'])) {
2163 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2166 if (!empty($contributionParams['contribution_recur_id'])) {
2167 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', array(
2168 'id' => $contributionParams['contribution_recur_id'],
2170 if (!empty($recurringContribution['campaign_id'])) {
2171 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2172 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2174 if (!empty($recurringContribution['financial_type_id'])) {
2175 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2176 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2179 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2180 $contributionParams['contribution_recur_id'],
2181 array_intersect_key($contributionParams, array('total_amount' => TRUE, 'financial_type_id' => TRUE))
2183 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2185 $contributionParams['status_id'] = 'Pending';
2186 if (isset($contributionParams['financial_type_id'])) {
2187 // Give precedence to passed in type.
2188 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2191 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2193 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2194 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2196 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2197 //do not create CC or BCC emails or profile notifications.
2198 //The if is just to be safe. Not sure if we can ever arrive with this unset
2199 // but per CRM-19478 it seems it can be 'null'
2200 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2201 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2204 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2205 $contribution->id
= $createContribution['id'];
2206 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2212 * Get individual id for onbehalf contribution.
2214 * @param int $contributionId
2216 * @param int $contributorId
2220 * containing organization id and individual id
2222 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2226 if (!$contributionId) {
2230 // fetch contributor id if null
2231 if (!$contributorId) {
2232 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2233 $contributionId, 'contact_id'
2237 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2238 $activityTypeId = array_search('Contribution', $activityTypeIds);
2240 if ($activityTypeId && $contributorId) {
2242 SELECT civicrm_activity_contact.contact_id
2243 FROM civicrm_activity_contact
2244 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2245 WHERE civicrm_activity.activity_type_id = %1
2246 AND civicrm_activity.source_record_id = %2
2247 AND civicrm_activity_contact.record_type_id = %3
2250 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2251 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2254 1 => array($activityTypeId, 'Integer'),
2255 2 => array($contributionId, 'Integer'),
2256 3 => array($sourceID, 'Integer'),
2259 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2261 // for on behalf contribution source is individual and contributor is organization
2262 if ($sourceContactId && $sourceContactId != $contributorId) {
2263 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2264 // get rel type id for employee of relation
2265 foreach ($relationshipTypeIds as $id => $typeVals) {
2266 if ($typeVals['name_a_b'] == 'Employee of') {
2267 $relationshipTypeId = $id;
2272 $rel = new CRM_Contact_DAO_Relationship();
2273 $rel->relationship_type_id
= $relationshipTypeId;
2274 $rel->contact_id_a
= $sourceContactId;
2275 $rel->contact_id_b
= $contributorId;
2276 if ($rel->find(TRUE)) {
2277 $ids['individual_id'] = $rel->contact_id_a
;
2278 $ids['organization_id'] = $rel->contact_id_b
;
2289 public static function getContributionDates() {
2290 $config = CRM_Core_Config
::singleton();
2291 $currentMonth = date('m');
2292 $currentDay = date('d');
2293 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2294 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2295 (int ) $config->fiscalYearStart
['d'] > $currentDay
2298 $year = date('Y') - 1;
2303 $year = array('Y' => $year);
2304 $yearDate = $config->fiscalYearStart
;
2305 $yearDate = array_merge($year, $yearDate);
2306 $yearDate = CRM_Utils_Date
::format($yearDate);
2308 $monthDate = date('Ym') . '01';
2314 'yearDate' => $yearDate,
2315 'monthDate' => $monthDate,
2320 * Load objects relations to contribution object.
2321 * Objects are stored in the $_relatedObjects property
2322 * In the first instance we are just moving functionality from BASEIpn -
2323 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2325 * Note that the unit test for the BaseIPN class tests this function
2327 * @param array $input
2328 * Input as delivered from Payment Processor.
2330 * Ids as Loaded by Payment Processor.
2331 * @param bool $loadAll
2332 * Load all related objects - even where id not passed in? (allows API to call this).
2337 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2339 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2340 if (empty($ids['contact']) && isset($this->contact_id
)) {
2341 $ids['contact'] = $this->contact_id
;
2344 if (empty($this->_component
)) {
2345 if (!empty($ids['event'])) {
2346 $this->_component
= 'event';
2349 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2353 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2354 // refactoring than anything else, and has unit test coverage.
2355 if (empty($this->financial_type_id
)) {
2359 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2364 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2365 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2366 $this->contribution_page_id
,
2369 if ($paymentProcessorID) {
2370 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2374 $ids['contributionType'] = $this->financial_type_id
;
2375 $ids['financialType'] = $this->financial_type_id
;
2376 if ($this->contribution_page_id
) {
2377 $ids['contributionPage'] = $this->contribution_page_id
;
2380 $this->loadRelatedEntitiesByID($ids);
2382 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2383 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2386 if (!empty($ids['pledge_payment'])) {
2387 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2388 if (empty($paymentID)) {
2391 $payment = new CRM_Pledge_BAO_PledgePayment();
2392 $payment->id
= $paymentID;
2393 if (!$payment->find(TRUE)) {
2394 throw new Exception("Could not find pledge payment record: " . $paymentID);
2396 $this->_relatedObjects
['pledge_payment'][] = $payment;
2400 $ids = $this->loadRelatedMembershipObjects($ids);
2402 if ($this->_component
!= 'contribute') {
2403 // we are in event mode
2404 // make sure event exists and is valid
2405 $event = new CRM_Event_BAO_Event();
2406 $event->id
= $ids['event'];
2407 if ($ids['event'] &&
2410 throw new Exception("Could not find event: " . $ids['event']);
2413 $this->_relatedObjects
['event'] = &$event;
2415 $participant = new CRM_Event_BAO_Participant();
2416 $participant->id
= $ids['participant'];
2417 if ($ids['participant'] &&
2418 !$participant->find(TRUE)
2420 throw new Exception("Could not find participant: " . $ids['participant']);
2422 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2424 $this->_relatedObjects
['participant'] = &$participant;
2426 // get the payment processor id from event - this is inaccurate see CRM-16923
2427 // in future we should look at throwing an exception here rather than an dubious guess.
2428 if (!$paymentProcessorID) {
2429 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2430 if ($paymentProcessorID) {
2431 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2436 if ($paymentProcessorID) {
2437 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2438 $this->is_test ?
'test' : 'live'
2440 $ids['paymentProcessor'] = $paymentProcessorID;
2441 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2444 // Add contribution id to $ids. CRM-20401
2445 $ids['contribution'] = $this->id
;
2450 * Create array of message information - ie. return html version, txt version, to field
2452 * @param array $input
2453 * Incoming information.
2454 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2455 * just check presence of recur object but maintaining legacy approach
2458 * IDs of related objects.
2459 * @param array $values
2460 * Any values that may have already been compiled by calling process.
2461 * This is augmented by values 'gathered' by gatherMessageValues
2462 * @param bool $returnMessageText
2463 * Distinguishes between whether to send message or return.
2464 * message text. We are working towards this function ALWAYS returning message text & calling
2465 * function doing emails / pdfs with it
2471 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2472 $this->loadRelatedObjects($input, $ids);
2474 if (empty($this->_component
)) {
2475 $this->_component
= CRM_Utils_Array
::value('component', $input);
2478 //not really sure what params might be passed in but lets merge em into values
2479 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2480 $values['is_email_receipt'] = $this->isEmailReceipt($input, $values);
2481 if (!empty($input['receipt_date'])) {
2482 $values['receipt_date'] = $input['receipt_date'];
2485 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2486 //what does recur 'mean here - to do with payment processor return functionality but
2487 // what is the importance
2488 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2489 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2491 $entityID = $entity = NULL;
2492 if (isset($ids['contribution'])) {
2493 $entity = 'contribution';
2494 $entityID = $ids['contribution'];
2496 if (!empty($ids['membership'])) {
2497 //not sure whether is is possible for this not to be an array - load related contacts loads an array but this code was expecting a string
2498 // the addition of the casting is in case it could get here & be a string. Added in 4.6 - maybe remove later? This AuthorizeNetIPN & PaypalIPN tests hit this
2499 // line having loaded an array
2500 $ids['membership'] = (array) $ids['membership'];
2501 $entity = 'membership';
2502 $entityID = $ids['membership'][0];
2505 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2506 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2507 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2509 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2510 //direct mode showing billing block, so use directIPN for temporary
2511 $template->assign('contributeMode', 'directIPN');
2514 // todo remove strtolower - check consistency
2515 if (strtolower($this->_component
) == 'event') {
2516 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2517 $values['event'] = array();
2519 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2521 //get location details
2522 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2523 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2525 $ufJoinParams = array(
2526 'entity_table' => 'civicrm_event',
2527 'entity_id' => $ids['event'],
2528 'module' => 'CiviEvent',
2531 list($custom_pre_id,
2533 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2535 $values['custom_pre_id'] = $custom_pre_id;
2536 $values['custom_post_id'] = $custom_post_ids;
2537 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2538 //and cases involving status updation through ipn
2539 // whatever that means!
2540 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2541 // perhaps we should throw an e-notice if amount is set & force total_amount?
2542 if (!empty($input['amount'])) {
2543 $values['totalAmount'] = $input['amount'];
2545 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2546 if ($values['event']['is_email_confirm']) {
2547 $values['is_email_receipt'] = 1;
2550 if (!empty($ids['contribution'])) {
2551 $values['contributionId'] = $ids['contribution'];
2554 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2555 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2559 $values['contribution_id'] = $this->id
;
2560 if (!empty($ids['related_contact'])) {
2561 $values['related_contact'] = $ids['related_contact'];
2562 if (isset($ids['onbehalf_dupe_alert'])) {
2563 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2565 $entityBlock = array(
2566 'contact_id' => $ids['contact'],
2567 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2568 'Home', 'id', 'name'
2571 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2572 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2575 if ($this->is_test
) {
2578 if (!empty($this->_relatedObjects
['membership'])) {
2579 foreach ($this->_relatedObjects
['membership'] as $membership) {
2580 if ($membership->id
) {
2581 $values['membership_id'] = $membership->id
;
2582 $values['isMembership'] = TRUE;
2583 $values['membership_assign'] = TRUE;
2585 // need to set the membership values here
2586 $template->assign('membership_name',
2587 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2589 $template->assign('mem_start_date', $membership->start_date
);
2590 $template->assign('mem_join_date', $membership->join_date
);
2591 $template->assign('mem_end_date', $membership->end_date
);
2592 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2593 $template->assign('mem_status', $membership_status);
2594 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2595 $values['is_pay_later'] = 1;
2597 // Pass amount to floatval as string '0.00' is considered a
2598 // valid amount and includes Fee section in the mail.
2599 if (isset($values['amount'])) {
2600 $values['amount'] = floatval($values['amount']);
2603 if (!empty($this->contribution_recur_id
) && $paymentObject) {
2604 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2605 $template->assign('cancelSubscriptionUrl', $url);
2606 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2607 $template->assign('updateSubscriptionBillingUrl', $url);
2608 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2609 $template->assign('updateSubscriptionUrl', $url);
2612 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2615 // otherwise if its about sending emails, continue sending without return, as we
2616 // don't want to exit the loop.
2621 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2627 * Gather values for contribution mail - this function has been created
2628 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2629 * Values related to the contribution in question are gathered
2631 * @param array $input
2632 * Input into function (probably from payment processor).
2633 * @param array $values
2635 * The set of ids related to the input.
2639 public function _gatherMessageValues($input, &$values, $ids = array()) {
2640 // set display address of contributor
2641 if ($this->address_id
) {
2642 $addressParams = array('id' => $this->address_id
);
2643 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2644 $addressDetails = array_values($addressDetails);
2646 // Else we assign the billing address of the contribution contact.
2648 $addressParams = array('contact_id' => $this->contact_id
, 'is_billing' => 1);
2649 $addressDetails = (array) CRM_Core_BAO_Address
::getValues($addressParams);
2650 $addressDetails = array_values($addressDetails);
2653 if (!empty($addressDetails[0]['display'])) {
2654 $values['address'] = $addressDetails[0]['display'];
2657 if ($this->_component
== 'contribute') {
2658 //get soft contributions
2659 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2660 if (!empty($softContributions)) {
2661 $values['softContributions'] = $softContributions['soft_credit'];
2663 if (isset($this->contribution_page_id
)) {
2664 // This is a call we want to use less, in favour of loading related objects.
2665 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
2666 if ($this->contribution_page_id
) {
2667 // This is precautionary as there are some legacy flows, but it should really be
2669 if (!isset($this->_relatedObjects
['contributionPage'])) {
2670 $this->loadRelatedEntitiesByID(array('contributionPage' => $this->contribution_page_id
));
2672 // CRM-8254 - override default currency if applicable
2673 $config = CRM_Core_Config
::singleton();
2674 $config->defaultCurrency
= CRM_Utils_Array
::value(
2677 $config->defaultCurrency
2681 // no contribution page -probably back office
2683 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2684 $values['title'] = 'Contribution';
2686 // set lineItem for contribution
2688 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
2689 if (!empty($lineItems)) {
2690 $firstLineItem = reset($lineItems);
2691 $priceSet = array();
2692 if (CRM_Utils_Array
::value('price_set_id', $firstLineItem)) {
2693 $priceSet = civicrm_api3('PriceSet', 'getsingle', array('id' => $firstLineItem['price_set_id'], 'return' => 'is_quick_config, id'));
2694 $values['priceSetID'] = $priceSet['id'];
2696 foreach ($lineItems as &$eachItem) {
2697 if (isset($this->_relatedObjects
['membership'])
2698 && is_array($this->_relatedObjects
['membership'])
2699 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2700 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2701 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2702 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2704 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
2705 // However, that does create upgrade pain so would be better to be phased in.
2706 $values['useForMember'] = empty($priceSet['is_quick_config']);
2708 $values['lineItem'][0] = $lineItems;
2712 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2716 // if this is onbehalf of contribution then set related contact
2717 if (!empty($relatedContact['individual_id'])) {
2718 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2723 $eventParams = array(
2724 'id' => $this->_relatedObjects
['event']->id
,
2726 $values['event'] = array();
2728 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2729 // add custom fields for event
2730 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $this->_relatedObjects
['event']->id
);
2732 $eventCustomGroup = array();
2733 foreach ($eventGroupTree as $key => $group) {
2734 if ($key === 'info') {
2738 foreach ($group['fields'] as $k => $customField) {
2739 $groupLabel = $group['title'];
2740 if (!empty($customField['customValue'])) {
2741 foreach ($customField['customValue'] as $customFieldValues) {
2742 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2747 $values['event']['customGroup'] = $eventCustomGroup;
2749 //get participant details
2750 $participantParams = array(
2751 'id' => $this->_relatedObjects
['participant']->id
,
2754 $values['participant'] = array();
2756 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2757 // add custom fields for event
2758 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $this->_relatedObjects
['participant']->id
);
2759 $participantCustomGroup = array();
2760 foreach ($participantGroupTree as $key => $group) {
2761 if ($key === 'info') {
2765 foreach ($group['fields'] as $k => $customField) {
2766 $groupLabel = $group['title'];
2767 if (!empty($customField['customValue'])) {
2768 foreach ($customField['customValue'] as $customFieldValues) {
2769 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2774 $values['participant']['customGroup'] = $participantCustomGroup;
2776 //get location details
2777 $locationParams = array(
2778 'entity_id' => $this->_relatedObjects
['event']->id
,
2779 'entity_table' => 'civicrm_event',
2781 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2783 $ufJoinParams = array(
2784 'entity_table' => 'civicrm_event',
2785 'entity_id' => $ids['event'],
2786 'module' => 'CiviEvent',
2789 list($custom_pre_id,
2791 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2793 $values['custom_pre_id'] = $custom_pre_id;
2794 $values['custom_post_id'] = $custom_post_ids;
2796 // set lineItem for event contribution
2798 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2799 if (!empty($participantIds)) {
2800 foreach ($participantIds as $pIDs) {
2801 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2802 if (!CRM_Utils_System
::isNull($lineItem)) {
2803 $values['lineItem'][] = $lineItem;
2810 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
2812 $customGroup = array();
2813 foreach ($groupTree as $key => $group) {
2814 if ($key === 'info') {
2818 foreach ($group['fields'] as $k => $customField) {
2819 $groupLabel = $group['title'];
2820 if (!empty($customField['customValue'])) {
2821 foreach ($customField['customValue'] as $customFieldValues) {
2822 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2827 $values['customGroup'] = $customGroup;
2829 $values['is_pay_later'] = $this->is_pay_later
;
2835 * Assign message variables to template but try to break the habit.
2837 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
2838 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
2839 * multiple recurring payments for processors like IATS that use tokens.
2841 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2842 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2843 * Note we send directly from this function in some cases because it is only partly refactored.
2845 * Don't call this function directly as the signature will change.
2849 * @param bool $returnMessageText
2853 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
2854 // @todo - this should have a better separation of concerns - ie.
2855 // gatherMessageValues should build an array of values to be assigned to the template
2856 // and this function should assign them (assigning null if not set).
2857 // the way the pcpParams & honor Params section works is a baby-step towards this.
2858 $template = CRM_Core_Smarty
::singleton();
2859 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2860 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2861 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2863 // For some unit tests contribution cannot contain paymentProcessor information
2864 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
2865 $template->assign('contributeMode', CRM_Utils_Array
::value($billingMode, CRM_Core_SelectValues
::contributeMode()));
2867 //assign honor information to receipt message
2868 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2870 $honorParams = ['soft_credit_type' => NULL, 'honor_block_is_active' => NULL];
2871 if (isset($softRecord['soft_credit'])) {
2872 //if id of contribution page is present
2873 if (!empty($values['id'])) {
2874 $values['honor'] = array(
2875 'honor_profile_values' => array(),
2876 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2877 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2880 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
2881 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
2884 //offline contribution
2885 $softCreditTypes = $softCredits = array();
2886 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2887 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2888 $softCredits[$key] = array(
2889 'Name' => $softCredit['contact_name'],
2890 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2893 $template->assign('softCreditTypes', $softCreditTypes);
2894 $template->assign('softCredits', $softCredits);
2898 $dao = new CRM_Contribute_DAO_ContributionProduct();
2899 $dao->contribution_id
= $this->id
;
2900 if ($dao->find(TRUE)) {
2901 $premiumId = $dao->product_id
;
2902 $template->assign('option', $dao->product_option
);
2904 $productDAO = new CRM_Contribute_DAO_Product();
2905 $productDAO->id
= $premiumId;
2906 $productDAO->find(TRUE);
2907 $template->assign('selectPremium', TRUE);
2908 $template->assign('product_name', $productDAO->name
);
2909 $template->assign('price', $productDAO->price
);
2910 $template->assign('sku', $productDAO->sku
);
2912 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2913 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2914 if (!$values['amount'] && isset($this->total_amount
)) {
2915 $values['amount'] = $this->total_amount
;
2918 $pcpParams = ['pcpBlock' => NULL, 'pcp_display_in_roll' => NULL, 'pcp_roll_nickname' => NULL, 'pcp_personal_note' => NULL, 'title' => NULL];
2920 if (strtolower($this->_component
) == 'contribute') {
2922 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2923 $softDAO->contribution_id
= $this->id
;
2924 if ($softDAO->find(TRUE)) {
2925 $pcpParams['pcpBlock'] = TRUE;
2926 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
2927 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
2928 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
2930 //assign the pcp page title for email subject
2931 $pcpDAO = new CRM_PCP_DAO_PCP();
2932 $pcpDAO->id
= $softDAO->pcp_id
;
2933 if ($pcpDAO->find(TRUE)) {
2934 $pcpParams['title'] = $pcpDAO->title
;
2938 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
2939 $template->assign($templateKey, $templateValue);
2942 if ($this->financial_type_id
) {
2943 $values['financial_type_id'] = $this->financial_type_id
;
2946 $template->assign('trxn_id', $this->trxn_id
);
2947 $template->assign('receive_date',
2948 CRM_Utils_Date
::processDate($this->receive_date
)
2950 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
2951 $template->assign('action', $this->is_test ?
1024 : 1);
2952 $template->assign('receipt_text',
2953 CRM_Utils_Array
::value('receipt_text',
2957 $template->assign('is_monetary', 1);
2958 $template->assign('is_recur', !empty($this->contribution_recur_id
));
2959 $template->assign('currency', $this->currency
);
2960 $template->assign('address', CRM_Utils_Address
::format($input));
2961 if (!empty($values['customGroup'])) {
2962 $template->assign('customGroup', $values['customGroup']);
2964 if (!empty($values['softContributions'])) {
2965 $template->assign('softContributions', $values['softContributions']);
2967 if ($this->_component
== 'event') {
2968 $template->assign('title', $values['event']['title']);
2969 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2970 $viewRoles = array();
2971 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2972 $viewRoles[] = $participantRoles[$v];
2974 $values['event']['participant_role'] = implode(', ', $viewRoles);
2975 $template->assign('event', $values['event']);
2976 $template->assign('participant', $values['participant']);
2977 $template->assign('location', $values['location']);
2978 $template->assign('customPre', $values['custom_pre_id']);
2979 $template->assign('customPost', $values['custom_post_id']);
2982 if ($this->_relatedObjects
['participant']->is_test
) {
2986 $values['params'] = array();
2987 //to get email of primary participant.
2988 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2989 $primaryAmount[] = array(
2990 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2991 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2993 //build an array of cId/pId of participants
2994 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2995 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2996 //send receipt to additional participant if exists
2997 if (count($additionalIDs)) {
2998 $template->assign('isPrimary', 0);
2999 $template->assign('customProfile', NULL);
3000 //set additionalParticipant true
3001 $values['params']['additionalParticipant'] = TRUE;
3002 foreach ($additionalIDs as $pId => $cId) {
3004 //to change the status pending to completed
3005 $additional = new CRM_Event_DAO_Participant();
3006 $additional->id
= $pId;
3007 $additional->contact_id
= $cId;
3008 $additional->find(TRUE);
3009 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3010 $additional->status_id
= 1;
3011 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3012 //if additional participant dont have email
3014 if (!$additionalParticipantInfo) {
3015 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3017 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
3018 $primaryAmount[] = array(
3019 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3020 'amount' => $additional->fee_amount
,
3022 $additional->save();
3023 $additional->free();
3024 $template->assign('amount', $amount);
3025 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3029 //build an array of custom profile and assigning it to template
3030 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3032 if (count($customProfile)) {
3033 $template->assign('customProfile', $customProfile);
3036 // for primary contact
3037 $values['params']['additionalParticipant'] = FALSE;
3038 $template->assign('isPrimary', 1);
3039 $template->assign('amount', $primaryAmount);
3040 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3041 if ($this->payment_instrument_id
) {
3042 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3043 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3045 // carry paylater, since we did not created billing,
3046 // so need to pull email from primary location, CRM-4395
3047 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3053 * Check whether payment processor supports
3054 * cancellation of contribution subscription
3056 * @param int $contributionId
3059 * @param bool $isNotCancelled
3063 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3064 $cacheKeyString = "$contributionId";
3065 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3067 static $supportsCancel = array();
3069 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3070 $supportsCancel[$cacheKeyString] = FALSE;
3071 $isCancelled = FALSE;
3073 if ($isNotCancelled) {
3074 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3077 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3078 if (!empty($paymentObject)) {
3079 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3082 return $supportsCancel[$cacheKeyString];
3086 * Check whether subscription is already cancelled.
3088 * @param int $contributionId
3092 * contribution status
3094 public static function isSubscriptionCancelled($contributionId) {
3096 SELECT cr.contribution_status_id
3097 FROM civicrm_contribution_recur cr
3098 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3099 WHERE con.id = %1 LIMIT 1";
3100 $params = array(1 => array($contributionId, 'Integer'));
3101 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3102 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
3103 if ($status == 'Cancelled') {
3110 * Create all financial accounts entry.
3112 * @param array $params
3113 * Contribution object, line item array and params for trxn.
3116 * @param array $financialTrxnValues
3118 * @return null|\CRM_Core_BAO_FinancialTrxn
3120 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3121 $skipRecords = $update = $return = $isRelatedId = FALSE;
3123 $additionalParticipantId = array();
3124 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3125 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3127 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3128 $entityId = $params['participant_id'];
3129 $entityTable = 'civicrm_participant';
3130 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3132 elseif (!empty($params['membership_id'])) {
3133 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3134 // are created off one contribution should be handled elsewhere
3135 $entityId = $params['membership_id'];
3136 $entityTable = 'civicrm_membership';
3139 $entityId = $params['contribution']->id
;
3140 $entityTable = 'civicrm_contribution';
3143 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3144 $isRelatedId = TRUE;
3147 $entityID[] = $entityId;
3148 if (!empty($additionalParticipantId)) {
3149 $entityID +
= $additionalParticipantId;
3151 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3152 if (empty($params['prevContribution'])) {
3159 $statusId = $params['contribution']->contribution_status_id
;
3160 // CRM-13964 partial payment
3161 if ($contributionStatus == 'Partially paid'
3162 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])
3164 $partialAmtPay = CRM_Utils_Rule
::cleanMoney($params['partial_amount_to_pay']);
3165 $partialAmtTotal = CRM_Utils_Rule
::cleanMoney($params['partial_payment_total']);
3167 $fromFinancialAccountId = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3168 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
3169 $params['total_amount'] = $partialAmtPay;
3171 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3172 if (empty($balanceTrxnInfo['trxn_id'])) {
3173 // create new balance transaction record
3174 $toFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3176 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3177 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3178 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3179 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3180 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3181 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3182 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3183 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3184 $balanceTrxnParams['status_id'] = $statusId;
3185 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3186 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3187 $balanceTrxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3188 $balanceTrxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3189 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3190 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3192 $balanceTrxnParams['is_payment'] = 1;
3194 if (!empty($params['payment_processor'])) {
3195 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3197 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3201 // build line item array if its not set in $params
3202 if (empty($params['line_item']) ||
$additionalParticipantId) {
3203 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3206 if ($contributionStatus != 'Failed' &&
3207 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3209 $skipRecords = TRUE;
3210 $pendingStatus = array(
3214 if (in_array($contributionStatus, $pendingStatus)) {
3215 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3216 $params['financial_type_id'],
3217 'Accounts Receivable Account is'
3220 elseif (!empty($params['payment_processor'])) {
3221 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3222 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', array(
3223 'id' => $params['payment_processor'],
3224 'return' => 'payment_instrument_id',
3227 elseif (!empty($params['payment_instrument_id'])) {
3228 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3231 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3232 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3233 $params['to_financial_account_id'] = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3236 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3237 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3238 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3240 //build financial transaction params
3241 $trxnParams = array(
3242 'contribution_id' => $params['contribution']->id
,
3243 'to_financial_account_id' => $params['to_financial_account_id'],
3244 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3245 'total_amount' => $totalAmount,
3246 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3247 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3248 'currency' => $params['contribution']->currency
,
3249 'trxn_id' => $params['contribution']->trxn_id
,
3250 'status_id' => $statusId,
3251 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3252 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3253 'pan_truncation' => CRM_Utils_Array
::value('pan_truncation', $params),
3254 'card_type_id' => CRM_Utils_Array
::value('card_type_id', $params),
3256 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3257 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3258 if (isset($params['refund_trxn_id'])) {
3259 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3260 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3263 //CRM-16259, set is_payment flag for non pending status
3264 if (!in_array($contributionStatus, $pendingStatus)) {
3265 $trxnParams['is_payment'] = 1;
3267 if (!empty($params['payment_processor'])) {
3268 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3271 if (isset($fromFinancialAccountId)) {
3272 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3275 // consider external values passed for recording transaction entry
3276 if (!empty($financialTrxnValues)) {
3277 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3279 if (empty($trxnParams['payment_processor_id'])) {
3280 unset($trxnParams['payment_processor_id']);
3283 $params['trxnParams'] = $trxnParams;
3285 if (!empty($params['prevContribution'])) {
3287 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3288 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3289 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3290 if (!isset($params['trxnParams']['trxn_id'])) {
3291 // Actually I have no idea why we are overwriting any values from the previous contribution.
3292 // (filling makes sense to me). However, only protecting this value as I really really know we
3293 // don't want this one overwritten.
3295 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3297 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3299 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3300 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3301 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3303 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3304 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3307 //if financial type is changed
3308 if (!empty($params['financial_type_id']) &&
3309 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3311 $accountRelationship = 'Income Account is';
3312 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3313 $accountRelationship = 'Deferred Revenue Account is';
3315 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3316 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3317 if ($oldFinancialAccount != $newFinancialAccount) {
3318 $params['total_amount'] = 0;
3319 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3320 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3321 $params['prevContribution']->financial_type_id
, $accountRelationship);
3324 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3325 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3326 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3329 self
::updateFinancialAccounts($params, 'changeFinancialType');
3330 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3331 $params['financial_account_id'] = $newFinancialAccount;
3332 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3333 self
::updateFinancialAccounts($params);
3334 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3336 $params['deferred_financial_account_id'] = $newFinancialAccount;
3340 //Update contribution status
3341 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3342 if (!isset($params['refund_trxn_id'])) {
3343 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3344 // gets preference over another so I am only 'protecting' a very specific tested flow
3345 // and letting natural justice take care of the rest.
3346 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3348 if (!empty($params['contribution_status_id']) &&
3349 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3351 //Update Financial Records
3352 self
::updateFinancialAccounts($params, 'changedStatus');
3356 // change Payment Instrument for a Completed contribution
3357 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3358 // instrument is null and now new payment instrument is added along with the payment
3359 if (!$params['contribution']->payment_instrument_id
) {
3360 $params['contribution']->find(TRUE);
3362 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3363 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3365 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3366 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3369 //if Change contribution amount
3370 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3371 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3372 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3373 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3374 if (isset($totalAmount) &&
3375 $totalAmount != $params['prevContribution']->total_amount
3377 //Update Financial Records
3378 $params['trxnParams']['from_financial_account_id'] = NULL;
3379 self
::updateFinancialAccounts($params, 'changedAmount');
3384 // Looks like we might have a data correction update.
3385 // This would be a case where a transaction id has been entered but it is incorrect &
3386 // the person goes back in & fixes it, as opposed to a new transaction.
3387 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3388 // the data fix scenario.
3390 if (isset($params['refund_trxn_id'])) {
3391 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3392 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3393 civicrm_api3('FinancialTrxn', 'create', array('id' => $refundIDs['financialTrxnId'], 'trxn_id' => $params['refund_trxn_id']));
3396 $cardType = CRM_Utils_Array
::value('card_type_id', $params);
3397 $panTruncation = CRM_Utils_Array
::value('pan_truncation', $params);
3398 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3403 // records finanical trxn and entity financial trxn
3404 // also make it available as return value
3405 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3406 $trxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3407 $trxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3408 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3409 $params['entity_id'] = $financialTxn->id
;
3410 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3411 self
::$_trxnIDs[] = $financialTxn->id
;
3415 // record line items and financial items
3416 if (empty($params['skipLineItem'])) {
3417 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3420 // create batch entry if batch_id is passed and
3421 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3422 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3423 $entityParams = array(
3424 'batch_id' => $params['batch_id'],
3425 'entity_table' => 'civicrm_financial_trxn',
3426 'entity_id' => $financialTxn->id
,
3428 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3431 // when a fee is charged
3432 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3433 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3436 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3437 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3439 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3440 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3441 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3443 unset($params['line_item']);
3444 self
::$_trxnIDs = NULL;
3449 * Update all financial accounts entry.
3451 * @param array $params
3452 * Contribution object, line item array and params for trxn.
3454 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3455 * adds unpredictability.
3457 * @param string $context
3461 public static function updateFinancialAccounts(&$params, $context = NULL) {
3463 $inputParams = $params;
3465 $currentContributionStatus = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
3466 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
3468 if (($previousContributionStatus == 'Pending'
3469 ||
$previousContributionStatus == 'In Progress')
3470 && $currentContributionStatus == 'Completed'
3471 && $context == 'changePaymentInstrument'
3475 if ((($previousContributionStatus == 'Partially paid'
3476 && $currentContributionStatus == 'Completed')
3477 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
3478 && $currentContributionStatus == 'Partially paid'))
3479 && $context == 'changedStatus'
3483 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3484 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3485 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3487 if ($context == 'changedStatus') {
3488 if ($previousContributionStatus == 'Completed'
3489 && (self
::isContributionStatusNegative($params['contribution']->contribution_status_id
))
3492 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3493 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3494 if (empty($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3495 $creditNoteId = self
::createCreditNoteId();
3496 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3499 elseif (($previousContributionStatus == 'Pending'
3500 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
3502 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3503 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
3505 if ($currentContributionStatus == 'Cancelled') {
3506 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3507 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3508 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3509 if (is_null($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3510 $creditNoteId = self
::createCreditNoteId();
3511 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3515 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3516 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3521 if ($context == 'changedStatus') {
3522 if (($previousContributionStatus == 'Pending'
3523 ||
$previousContributionStatus == 'In Progress')
3524 && ($currentContributionStatus == 'Completed')
3526 if (empty($params['line_item'])) {
3528 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3529 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3530 // & this can be removed
3533 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3534 // This is an update so original currency if none passed in.
3535 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
3537 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
3538 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3539 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3540 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
3541 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3542 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3544 $entityParams = array(
3545 'entity_table' => 'civicrm_financial_item',
3547 foreach ($params['line_item'] as $fieldId => $fields) {
3548 foreach ($fields as $fieldValueId => $lineItemDetails) {
3550 1 => array(CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'), 'Integer'),
3551 2 => array($lineItemDetails['id'], 'Integer'),
3553 CRM_Core_DAO
::executeQuery($query, $fparams);
3555 1 => array($lineItemDetails['id'], 'Integer'),
3557 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3558 while ($financialItem->fetch()) {
3559 $entityParams['entity_id'] = $financialItem->id
;
3560 $entityParams['amount'] = $financialItem->amount
;
3561 foreach (self
::$_trxnIDs as $tID) {
3562 $entityParams['financial_trxn_id'] = $tID;
3563 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3572 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3573 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3574 $params['entity_id'] = $trxn->id
;
3575 if ($context != 'changePaymentInstrument') {
3576 $itemParams['entity_table'] = 'civicrm_line_item';
3577 $trxnIds['id'] = $params['entity_id'];
3578 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution']->id
);
3579 foreach ($params['line_item'] as $fieldId => $fields) {
3580 foreach ($fields as $fieldValueId => $lineItemDetails) {
3581 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($lineItemDetails['id']);
3582 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3583 if ($params['contribution']->receive_date
) {
3584 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3587 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array
::value('financial_account_id', $prevFinancialItem));
3589 $currency = $params['prevContribution']->currency
;
3590 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3591 if ($params['contribution']->currency
) {
3592 $currency = $params['contribution']->currency
;
3594 $previousLineItemTotal = CRM_Utils_Array
::value('line_total', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
3595 $itemParams = array(
3596 'transaction_date' => $receiveDate,
3597 'contact_id' => $params['prevContribution']->contact_id
,
3598 'currency' => $currency,
3599 'amount' => self
::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
3600 'description' => CRM_Utils_Array
::value('description', $prevFinancialItem),
3601 'status_id' => $prevFinancialItem['status_id'],
3602 'financial_account_id' => $financialAccount,
3603 'entity_table' => 'civicrm_line_item',
3604 'entity_id' => $lineItemDetails['id'],
3606 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3607 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3608 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
3609 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
3611 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') ||
($context == 'changeFinancialType')) {
3612 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
3613 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3614 $taxAmount = (float) $lineItemDetails['tax_amount'];
3615 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
3616 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
3617 $taxAmount = CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
3619 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
3620 $taxAmount -= CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
3622 $itemParams['amount'] = self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * $taxAmount;
3623 $itemParams['description'] = $taxTerm;
3624 if ($lineItemDetails['financial_type_id']) {
3625 $itemParams['financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount(
3626 $lineItemDetails['financial_type_id'],
3627 'Sales Tax Account is'
3630 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3635 if ($context == 'changeFinancialType') {
3636 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3637 $params['skipLineItem'] = FALSE;
3638 foreach ($params['line_item'] as &$lineItems) {
3639 foreach ($lineItems as &$line) {
3640 $line['financial_type_id'] = $params['financial_type_id'];
3645 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, $context);
3649 * Is this contribution status a reversal.
3651 * If so we would expect to record a negative value in the financial_trxn table.
3653 * @param int $status_id
3657 public static function isContributionStatusNegative($status_id) {
3658 $reversalStatuses = array('Cancelled', 'Chargeback', 'Refunded');
3659 return in_array(CRM_Contribute_PseudoConstant
::contributionStatus($status_id, 'name'), $reversalStatuses);
3663 * Check status validation on update of a contribution.
3665 * @param array $values
3666 * Previous form values before submit.
3668 * @param array $fields
3669 * The input form values.
3671 * @param array $errors
3676 public static function checkStatusValidation($values, &$fields, &$errors) {
3677 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3678 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3679 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3683 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3684 $checkStatus = array(
3685 'Cancelled' => array('Completed', 'Refunded'),
3686 'Completed' => array('Cancelled', 'Refunded', 'Chargeback'),
3687 'Pending' => array('Cancelled', 'Completed', 'Failed', 'Partially paid'),
3688 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3689 'Refunded' => array('Cancelled', 'Completed'),
3690 'Partially paid' => array('Completed'),
3693 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3694 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, array()))
3696 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3697 1 => $contributionStatuses[$values['contribution_status_id']],
3698 2 => $contributionStatuses[$fields['contribution_status_id']],
3704 * Delete contribution of contact.
3708 * @param int $contactId
3712 public static function deleteContactContribution($contactId) {
3713 $contribution = new CRM_Contribute_DAO_Contribution();
3714 $contribution->contact_id
= $contactId;
3715 $contribution->find();
3716 while ($contribution->fetch()) {
3717 self
::deleteContribution($contribution->id
);
3722 * Get options for a given contribution field.
3723 * @see CRM_Core_DAO::buildOptions
3725 * @param string $fieldName
3726 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3727 * @param array $props whatever is known about this dao object.
3729 * @return array|bool
3731 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3732 $className = __CLASS__
;
3734 if (isset($props['orderColumn'])) {
3735 $params['orderColumn'] = $props['orderColumn'];
3737 switch ($fieldName) {
3738 // This field is not part of this object but the api supports it
3739 case 'payment_processor':
3740 $className = 'CRM_Contribute_BAO_ContributionPage';
3741 // Filter results by contribution page
3742 if (!empty($props['contribution_page_id'])) {
3743 $page = civicrm_api('contribution_page', 'getsingle', array(
3745 'id' => ($props['contribution_page_id']),
3747 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3748 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3752 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3753 case 'honor_type_id':
3754 $className = 'CRM_Contribute_BAO_ContributionSoft';
3755 $fieldName = 'soft_credit_type_id';
3756 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3759 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3763 * Validate financial type.
3767 * @param int $financialTypeId
3768 * Financial Type id.
3770 * @param string $relationName
3772 * @return array|bool
3774 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3775 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3777 if (!$financialAccount) {
3778 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3785 * Function to record additional payment for partial and refund contributions.
3787 * @param int $contributionId
3788 * is the invoice contribution id (got created after processing participant payment).
3789 * @param array $trxnsData
3790 * to take user provided input of transaction details.
3791 * @param string $paymentType
3792 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3793 * @param int $participantId
3794 * @param bool $updateStatus
3796 * @return null|object
3798 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL, $updateStatus = TRUE) {
3800 if ($paymentType == 'owed') {
3801 $financialTrxn = CRM_Financial_BAO_Payment
::recordPayment($contributionId, $trxnsData, $participantId);
3803 elseif ($paymentType == 'refund') {
3804 $financialTrxn = CRM_Financial_BAO_Payment
::recordRefundPayment($contributionId, $trxnsData, $updateStatus);
3805 if ($participantId) {
3806 // update participant status
3807 // @todo this doesn't make sense...
3808 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3809 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3810 foreach ($ids as $val) {
3811 $participantUpdate['id'] = $val;
3812 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3813 CRM_Event_BAO_Participant
::add($participantUpdate);
3818 // activity creation
3819 if (!empty($financialTrxn)) {
3820 if ($participantId) {
3821 $inputParams['id'] = $participantId;
3824 $component = 'event';
3825 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3826 $entityObj = $entityObj[$participantId];
3829 $entityObj = new CRM_Contribute_BAO_Contribution();
3830 $entityObj->id
= $contributionId;
3831 $entityObj->find(TRUE);
3832 $component = 'contribution';
3834 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3836 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3837 return $financialTrxn;
3845 * @param $activityType
3847 * @param int $contributionId
3849 * @throws CRM_Core_Exception
3851 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3852 if ($component == 'event') {
3853 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3856 $title = ts('Contribution');
3858 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3859 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3860 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3861 $targetCid = $entityObj->contact_id
;
3862 // source record id would be the contribution id
3863 $srcRecId = $contributionId;
3866 $activityParams = array(
3867 'source_contact_id' => $targetCid,
3868 'source_record_id' => $srcRecId,
3869 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
3870 'subject' => $subject,
3871 'activity_date_time' => $date,
3872 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
3873 'skipRecentView' => TRUE,
3876 // create activity with target contacts
3877 $session = CRM_Core_Session
::singleton();
3878 $id = $session->get('userID');
3880 $activityParams['source_contact_id'] = $id;
3881 $activityParams['target_contact_id'][] = $targetCid;
3884 CRM_Activity_BAO_Activity
::create($activityParams);
3888 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3892 * @param bool $getTrxnInfo
3893 * @param bool $usingLineTotal
3897 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3898 // @todo deprecate passing in component - always call with contribution.
3899 if ($component == 'event') {
3900 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3902 if (!$contributionId) {
3903 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3904 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3905 $id = $primaryParticipantId;
3907 if (!$contributionId) {
3912 elseif ($component == 'membership') {
3913 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
3916 $contributionId = $id;
3919 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3920 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3922 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3923 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3925 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3926 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
3929 $baseTrxnId = $total['trxn_id'];
3930 $total = $total['total_amount'];
3933 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
3935 $contribution = civicrm_api3('Contribution', 'getsingle', array('id' => $contributionId, 'return' => array('currency', 'is_pay_later', 'contribution_status_id', 'financial_type_id')));
3937 $info['payLater'] = $contribution['is_pay_later'];
3938 $info['contribution_status'] = $contribution['contribution_status'];
3939 $info['currency'] = $contribution['currency'];
3941 $financialTypeId = $contribution['financial_type_id'];
3942 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, 'Expense Account is');
3944 if ($paymentBalance == 0 && $info['payLater']) {
3945 // @todo - review - this looks very unlikely to be correct.
3946 // the balance should be correct based on payment transactions not
3948 $paymentBalance = $total;
3951 $info['total'] = $total;
3952 $info['paid'] = $total - $paymentBalance;
3953 $info['balance'] = $paymentBalance;
3955 $info['component'] = $component;
3957 if ($getTrxnInfo && $baseTrxnId) {
3958 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3960 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
3962 ft.payment_instrument_id,
3963 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
3965 FROM civicrm_contribution con
3966 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3967 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
3968 AND ft.to_financial_account_id != %2
3969 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
3970 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
3971 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
3973 WHERE con.id = %1 AND ft.is_payment = 1
3975 $queryParams = array(
3976 1 => array($contributionId, 'Integer'),
3977 2 => array($feeFinancialAccount, 'Integer'),
3979 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
3980 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3982 while ($resultDAO->fetch()) {
3983 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3984 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3985 if ($resultDAO->card_type_id
) {
3986 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
3987 $pantruncation = '';
3988 if ($resultDAO->pan_truncation
) {
3989 $pantruncation = ": {$resultDAO->pan_truncation}";
3991 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
3994 // show payment edit link only for payments done via backoffice form
3995 $paymentEditLink = '';
3996 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
3998 CRM_Core_Action
::UPDATE
=> array(
3999 'name' => "<i class='crm-i fa-pencil'></i>",
4000 'url' => 'civicrm/payment/edit',
4001 'class' => 'medium-popup',
4002 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
4003 'title' => ts('Edit Payment'),
4006 $paymentEditLink = CRM_Core_Action
::formLink(
4008 CRM_Core_Action
::mask(array(CRM_Core_Permission
::EDIT
)),
4010 'id' => $resultDAO->id
,
4011 'contribution_id' => $contributionId,
4017 'id' => $resultDAO->id
,
4018 'total_amount' => $resultDAO->total_amount
,
4019 'financial_type' => $resultDAO->financial_account
,
4020 'payment_instrument' => $paidByLabel,
4021 'receive_date' => $resultDAO->trxn_date
,
4022 'trxn_id' => $resultDAO->trxn_id
,
4023 'status' => $statuses[$resultDAO->status_id
],
4024 'currency' => $resultDAO->currency
,
4025 'action' => $paymentEditLink,
4027 if ($paidByName == 'Check') {
4028 $val['check_number'] = $resultDAO->check_number
;
4032 $info['transaction'] = $rows;
4035 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
4040 * Get the outstanding balance on a contribution.
4042 * @param int $contributionId
4043 * @param float $contributionTotal
4044 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
4048 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
4049 if ($contributionTotal === NULL) {
4050 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4053 return CRM_Utils_Money
::subtractCurrencies(
4055 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE) ?
: 0,
4056 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4061 * Get the tax amount (misnamed function).
4063 * @param array $params
4064 * @param bool $isLineItem
4068 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4069 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4071 // This function should be only called after standardisation (removal of
4072 // thousand separator & using a decimal point for cents separator.
4073 // However, we don't know if that is always true :-(
4074 // There is a deprecation notice tho :-)
4075 $unknownIfMoneyIsClean = empty($params['skipCleanMoney']) && !$isLineItem;
4076 // Update contribution.
4077 if (!empty($params['id'])) {
4078 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4079 // there are no tax implications - early return.
4080 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4083 if (empty($params['prevContribution'])) {
4084 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4087 foreach (array('total_amount', 'financial_type_id', 'fee_amount') as $field) {
4088 if (!isset($params[$field])) {
4089 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4090 // Tax amount gets added back on later....
4091 $params['total_amount'] = $params['prevContribution']->total_amount
-
4092 $params['prevContribution']->tax_amount
;
4095 $params[$field] = $params['prevContribution']->$field;
4096 if ($params[$field] != $params['prevContribution']->$field) {
4102 self
::calculateMissingAmountParams($params, $params['id']);
4103 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4104 // Assign tax Amount on update of contribution
4105 if (!empty($params['prevContribution']->tax_amount
)) {
4106 $params['tax_amount'] = 'null';
4107 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4108 foreach ($params['line_item'] as $setID => $priceField) {
4109 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4110 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4117 // New Contribution and update of contribution with tax rate financial type
4118 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4119 empty($params['skipLineItem']) && !$isLineItem
4121 $taxRateParams = $taxRates[$params['financial_type_id']];
4122 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams, $unknownIfMoneyIsClean);
4123 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4125 // Get Line Item on update of contribution
4126 if (isset($params['id'])) {
4127 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4130 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4132 foreach ($params['line_item'] as $setID => $priceField) {
4133 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4134 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4137 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4139 elseif (isset($params['api.line_item.create'])) {
4140 // Update total amount of contribution using lineItem
4141 $taxAmountArray = array();
4142 foreach ($params['api.line_item.create'] as $key => $value) {
4143 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4144 $taxRate = $taxRates[$value['financial_type_id']];
4145 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4146 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4149 $params['tax_amount'] = array_sum($taxAmountArray);
4150 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4153 // update line item of contrbution
4154 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4155 $taxRate = $taxRates[$params['financial_type_id']];
4156 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate, $unknownIfMoneyIsClean);
4157 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4164 * Check financial type validation on update of a contribution.
4166 * @param Integer $financialTypeId
4167 * Value of latest Financial Type.
4169 * @param Integer $contributionId
4172 * @param array $errors
4177 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4178 if (!empty($financialTypeId)) {
4179 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4180 if ($oldFinancialTypeId == $financialTypeId) {
4184 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4186 '1' => array($contributionId, 'Integer'),
4188 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4189 if ($result->N
> 1) {
4190 $errors['financial_type_id'] = ts('One or more line items have a different financial type than the contribution. Editing the financial type is not yet supported in this situation.');
4195 * Update related pledge payment payments.
4197 * This function has been refactored out of the back office contribution form and may
4198 * still overlap with other functions.
4200 * @param string $action
4201 * @param int $pledgePaymentID
4202 * @param int $contributionID
4203 * @param bool $adjustTotalAmount
4204 * @param float $total_amount
4205 * @param float $original_total_amount
4206 * @param int $contribution_status_id
4207 * @param int $original_contribution_status_id
4209 public static function updateRelatedPledge(
4215 $original_total_amount,
4216 $contribution_status_id,
4217 $original_contribution_status_id
4219 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4223 if ($pledgePaymentID) {
4224 //store contribution id in payment record.
4225 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4228 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4235 if (!$pledgePaymentID) {
4238 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4244 $updatePledgePaymentStatus = FALSE;
4246 // If either the status or the amount has changed we update the pledge status.
4247 if ($action & CRM_Core_Action
::ADD
) {
4248 $updatePledgePaymentStatus = TRUE;
4250 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4251 ($original_total_amount != $total_amount))
4253 $updatePledgePaymentStatus = TRUE;
4256 if ($updatePledgePaymentStatus) {
4257 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4258 array($pledgePaymentID),
4259 $contribution_status_id,
4268 * Compute the stats values
4272 * @param string $stat either 'mode' or 'median'
4273 * @param string $sql
4274 * @param string $alias of civicrm_contribution
4276 * @return array|null
4278 public static function computeStats($stat, $sql, $alias = NULL) {
4279 CRM_Core_Error
::deprecatedFunctionWarning('computeStats is now deprecated');
4284 * Is there only one line item attached to the contribution.
4290 * @throws \CiviCRM_API3_Exception
4292 public static function isSingleLineItem($id) {
4293 $lineItemCount = civicrm_api3('LineItem', 'getcount', array('contribution_id' => $id));
4294 return ($lineItemCount == 1);
4298 * Complete an order.
4300 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4302 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4304 * Moving it out of the BaseIPN class is just the first step.
4306 * @param array $input
4308 * @param array $objects
4309 * @param CRM_Core_Transaction $transaction
4311 * @param CRM_Contribute_BAO_Contribution $contribution
4315 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution) {
4316 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4317 // The previous details are used when calculating line items so keep it before any code that 'does something'
4318 if (!empty($contribution->id
)) {
4319 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4320 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4322 $inputContributionWhiteList = array(
4327 'payment_instrument_id',
4332 'contribution_status_id',
4336 if (self
::isSingleLineItem($primaryContributionID)) {
4337 $inputContributionWhiteList[] = 'financial_type_id';
4340 $participant = CRM_Utils_Array
::value('participant', $objects);
4341 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4342 $recurringContributionID = (empty($recurContrib->id
)) ?
NULL : $recurContrib->id
;
4343 $event = CRM_Utils_Array
::value('event', $objects);
4345 $paymentProcessorId = '';
4346 if (isset($objects['paymentProcessor'])) {
4347 if (is_array($objects['paymentProcessor'])) {
4348 $paymentProcessorId = $objects['paymentProcessor']['id'];
4351 $paymentProcessorId = $objects['paymentProcessor']->id
;
4355 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4357 $contributionParams = array_merge(array(
4358 'contribution_status_id' => $completedContributionStatusID,
4359 'source' => self
::getRecurringContributionDescription($contribution, $event),
4360 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4363 // CRM-20678 Ensure that the currency is correct in subseqent transcations.
4364 if (empty($contributionParams['currency']) && isset($objects['first_contribution']->currency
)) {
4365 $contributionParams['currency'] = $objects['first_contribution']->currency
;
4368 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
4370 // If paymentProcessor is not set then the payment_instrument_id would not be correct.
4371 // not clear when or if this would occur if you encounter this please fix here & add a unit test.
4372 if (empty($contributionParams['payment_instrument_id']) && isset($contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'])) {
4373 $contributionParams['payment_instrument_id'] = $contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'];
4376 if ($recurringContributionID) {
4377 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4379 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4381 if (empty($contributionParams['receive_date']) && $changeDate) {
4382 $contributionParams['receive_date'] = $changeDate;
4385 self
::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
4386 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4389 if (isset($input['is_email_receipt'])) {
4390 $values['is_email_receipt'] = $input['is_email_receipt'];
4393 if ($input['component'] == 'contribute') {
4394 if ($contribution->contribution_page_id
) {
4395 // Figure out what we gain from this.
4396 // Note that we may have overwritten the is_email_receipt input, fix that below.
4397 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4399 elseif ($recurContrib && $recurringContributionID) {
4400 $values['amount'] = $recurContrib->amount
;
4401 $values['financial_type_id'] = $objects['contributionType']->id
;
4402 $values['title'] = $source = ts('Offline Recurring Contribution');
4405 if (isset($input['is_email_receipt'])) {
4406 // CRM-19601 - we may have overwritten this above.
4407 $values['is_email_receipt'] = $input['is_email_receipt'];
4409 elseif ($recurContrib && $recurringContributionID) {
4410 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4411 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4412 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4415 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4416 self
::updateMembershipBasedOnCompletionOfContribution(
4418 $primaryContributionID,
4424 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4425 if ($event->is_email_confirm
) {
4426 // @todo this should be set by the function that sends the mail after sending.
4427 $contributionParams['receipt_date'] = $changeDate;
4429 $participantParams['id'] = $participant->id
;
4430 $participantParams['status_id'] = 'Registered';
4431 civicrm_api3('Participant', 'create', $participantParams);
4435 $contributionParams['id'] = $contribution->id
;
4437 // CRM-19309 - if you update the contribution here with financial_type_id it can/will mess with $lineItem
4438 // unsetting it here does NOT cause any other contribution test to fail!
4439 unset($contributionParams['financial_type_id']);
4440 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4442 // Add new soft credit against current $contribution.
4443 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4444 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4447 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4448 'labelColumn' => 'name',
4451 if (isset($input['prevContribution']) && (!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4452 $input['payment_processor'] = $paymentProcessorId;
4455 if (!empty($contribution->_relatedObjects
['participant'])) {
4456 $input['contribution_mode'] = 'participant';
4457 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4459 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4460 $input['contribution_mode'] = 'membership';
4461 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4462 $contribution->trxn_id
= CRM_Utils_Array
::value('trxn_id', $input);
4463 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4466 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4467 $transaction->commit();
4469 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution->id
, $recurringContributionID,
4470 $contributionParams['contribution_status_id'], $input['amount']);
4472 // create an activity record
4473 if ($input['component'] == 'contribute') {
4475 $targetContactID = NULL;
4476 if (!empty($ids['related_contact'])) {
4477 $targetContactID = $contribution->contact_id
;
4478 $contribution->contact_id
= $ids['related_contact'];
4480 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4483 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4484 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4485 if (!array_key_exists('is_email_receipt', $values) ||
4486 $values['is_email_receipt'] == 1
4488 civicrm_api3('Contribution', 'sendconfirmation', array(
4489 'id' => $contribution->id
,
4490 'payment_processor_id' => $paymentProcessorId,
4492 CRM_Core_Error
::debug_log_message("Receipt sent");
4495 CRM_Core_Error
::debug_log_message("Success: Database updated");
4496 return $contributionResult;
4500 * Send receipt from contribution.
4502 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4504 * Note that the compose message part has been moved to contribution
4505 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4507 * @param array $input
4508 * Incoming data from Payment processor.
4510 * Related object IDs.
4511 * @param int $contributionID
4512 * @param array $values
4513 * Values related to objects that have already been loaded.
4514 * @param bool $returnMessageText
4515 * Should text be returned instead of sent. This.
4516 * is because the function is also used to generate pdfs
4519 * @throws \CRM_Core_Exception
4520 * @throws \CiviCRM_API3_Exception
4522 public static function sendMail(&$input, &$ids, $contributionID, &$values,
4523 $returnMessageText = FALSE) {
4525 $contribution = new CRM_Contribute_BAO_Contribution();
4526 $contribution->id
= $contributionID;
4527 if (!$contribution->find(TRUE)) {
4528 throw new CRM_Core_Exception('Contribution does not exist');
4530 $contribution->loadRelatedObjects($input, $ids, TRUE);
4531 // set receipt from e-mail and name in value
4532 if (!$returnMessageText) {
4533 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4535 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4536 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4537 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4538 civicrm_api3('Contribution', 'create', array('receipt_date' => 'now', 'id' => $contribution->id
));
4544 * Generate From email and from name in an array values
4545 * @param array $input
4546 * @param \CRM_Contribute_BAO_Contribution $contribution
4549 public static function generateFromEmailAndName($input, $contribution) {
4550 // Use input value if supplied.
4551 if (!empty($input['receipt_from_email'])) {
4552 return array(CRM_Utils_array
::value('receipt_from_name', $input, ''), $input['receipt_from_email']);
4554 // if we are still empty see if we can use anything from a contribution page.
4555 $pageValues = array();
4556 if (!empty($contribution->contribution_page_id
)) {
4557 $pageValues = civicrm_api3('ContributionPage', 'getsingle', array('id' => $contribution->contribution_page_id
));
4559 // if we are still empty see if we can use anything from a contribution page.
4560 if (!empty($pageValues['receipt_from_email'])) {
4561 return array($pageValues['receipt_from_name'], $pageValues['receipt_from_email']);
4563 // If we are still empty fall back to the domain or logged in user information.
4564 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4568 * Generate credit note id with next avaible number
4573 public static function createCreditNoteId() {
4574 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4576 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution WHERE creditnote_id IS NOT NULL");
4577 $creditNoteId = NULL;
4581 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4582 $result = civicrm_api3('Contribution', 'getcount', array(
4584 'creditnote_id' => $creditNoteId,
4586 } while ($result > 0);
4588 return $creditNoteId;
4592 * Load related memberships.
4594 * Note that in theory it should be possible to retrieve these from the line_item table
4595 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4596 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4597 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4598 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4600 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4604 * @return array $ids
4608 public function loadRelatedMembershipObjects($ids = []) {
4610 SELECT membership_id
4611 FROM civicrm_membership_payment
4612 WHERE contribution_id = %1 ";
4613 $params = array(1 => array($this->id
, 'Integer'));
4614 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, array());
4616 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4617 while ($dao->fetch()) {
4618 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4619 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4623 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4624 foreach ($ids['membership'] as $id) {
4626 $membership = new CRM_Member_BAO_Membership();
4627 $membership->id
= $id;
4628 if (!$membership->find(TRUE)) {
4629 throw new Exception("Could not find membership record: $id");
4631 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4632 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4633 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4634 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4635 $membership->free();
4643 * This function is used to record partial payments for contribution
4645 * @param array $contribution
4647 * @param array $params
4649 * @return CRM_Financial_DAO_FinancialTrxn
4651 public static function recordPartialPayment($contribution, $params) {
4652 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
4653 $pendingStatus = array(
4654 array_search('Pending', $contributionStatuses),
4655 array_search('In Progress', $contributionStatuses),
4657 $statusId = array_search('Completed', $contributionStatuses);
4658 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $contribution), $pendingStatus)) {
4659 $balanceTrxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contribution['financial_type_id'], 'Accounts Receivable Account is');
4661 elseif (!empty($params['payment_processor'])) {
4662 $balanceTrxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contribution['payment_processor'], NULL, 'civicrm_payment_processor');
4664 elseif (!empty($params['payment_instrument_id'])) {
4665 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
4668 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
4669 $queryParams = array(1 => array($relationTypeId, 'Integer'));
4670 $balanceTrxnParams['to_financial_account_id'] = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
4672 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contribution['financial_type_id'], 'Accounts Receivable Account is');
4673 $balanceTrxnParams['from_financial_account_id'] = $fromFinancialAccountId;
4674 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4675 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4676 $balanceTrxnParams['trxn_date'] = CRM_Utils_Array
::value('trxn_date', $params, CRM_Utils_Array
::value('contribution_receive_date', $params, date('YmdHis')));
4677 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4678 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4679 $balanceTrxnParams['currency'] = $contribution['currency'];
4680 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4681 $balanceTrxnParams['status_id'] = $statusId;
4682 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4683 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4684 if ($fromFinancialAccountId != NULL &&
4685 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
4687 $balanceTrxnParams['is_payment'] = 1;
4689 if (!empty($params['payment_processor'])) {
4690 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4692 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4696 * Get the description (source field) for the recurring contribution.
4698 * @param CRM_Contribute_BAO_Contribution $contribution
4699 * @param CRM_Event_DAO_Event|null $event
4702 * @throws \CiviCRM_API3_Exception
4704 protected static function getRecurringContributionDescription($contribution, $event) {
4705 if (!empty($contribution->source
)) {
4706 return $contribution->source
;
4708 elseif (!empty($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
4709 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', array(
4710 'id' => $contribution->contribution_page_id
,
4711 'return' => 'title',
4713 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4716 return ts('Online Event Registration') . ': ' . $event->title
;
4718 elseif (!empty($contribution->contribution_recur_id
)) {
4719 return 'recurring contribution';
4725 * Function to add payments for contribution
4726 * for Partially Paid status
4728 * @param array $contributions
4729 * @param string $contributionStatusId
4732 public static function addPayments($contributions, $contributionStatusId = NULL) {
4733 // get financial trxn which is a payment
4734 $ftSql = "SELECT ft.id, ft.total_amount
4735 FROM civicrm_financial_trxn ft
4736 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
4737 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
4738 $contributionStatus = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4739 'labelColumn' => 'name',
4741 foreach ($contributions as $contribution) {
4742 if (!($contributionStatus[$contribution->contribution_status_id
] == 'Partially paid'
4743 || CRM_Utils_Array
::value($contributionStatusId, $contributionStatus) == 'Partially paid')
4747 $ftDao = CRM_Core_DAO
::executeQuery($ftSql, array(1 => array($contribution->id
, 'Integer')));
4750 // store financial item Proportionaly.
4751 $trxnParams = array(
4752 'total_amount' => $ftDao->total_amount
,
4753 'contribution_id' => $contribution->id
,
4755 self
::assignProportionalLineItems($trxnParams, $ftDao->id
, $contribution->total_amount
);
4760 * Function use to store line item proportionaly in
4761 * in entity financial trxn table
4763 * @param array $trxnParams
4765 * @param Integer $trxnId
4767 * @param float $contributionTotalAmount
4770 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4771 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4772 if (!empty($lineItems)) {
4773 // get financial item
4774 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4775 $entityParams = array(
4776 'contribution_total_amount' => $contributionTotalAmount,
4777 'trxn_total_amount' => $trxnParams['total_amount'],
4778 'trxn_id' => $trxnId,
4780 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4785 * Checks if line items total amounts
4786 * match the contribution total amount.
4788 * @param array $params
4789 * array of order params.
4791 * @throws \API_Exception
4793 public static function checkLineItems(&$params) {
4794 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
4795 $lineItemAmount = 0;
4797 foreach ($params['line_items'] as &$lineItems) {
4798 foreach ($lineItems['line_item'] as &$item) {
4799 if (empty($item['financial_type_id'])) {
4800 $item['financial_type_id'] = $params['financial_type_id'];
4802 $lineItemAmount +
= $item['line_total'] + CRM_Utils_Array
::value('tax_amount', $item, 0.00);
4806 if (!isset($totalAmount)) {
4807 $params['total_amount'] = $lineItemAmount;
4810 $currency = CRM_Utils_Array
::value('currency', $params, '');
4812 if (empty($currency)) {
4813 $currency = CRM_Core_Config
::singleton()->defaultCurrency
;
4816 if (!CRM_Utils_Money
::equals($totalAmount, $lineItemAmount, $currency)) {
4817 throw new CRM_Contribute_Exception_CheckLineItemsException();
4823 * Get the financial account for the item associated with the new transaction.
4825 * @param array $params
4826 * @param int $default
4830 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
4832 if (!empty($params['financial_account_id'])) {
4833 return $params['financial_account_id'];
4836 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4837 $preferredAccountsRelationships = array(
4838 'Refunded' => 'Credit/Contra Revenue Account is',
4839 'Chargeback' => 'Chargeback Account is',
4842 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4843 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4844 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4846 $preferredAccountsRelationships[$contributionStatus]
4854 * ContributionPage values were being imposed onto values.
4856 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4857 * REALLY didn't want superimposed. The rest are left there in their overkill out
4860 * The rationale for making this explicit is that it was a case of carefully set values being
4861 * seemingly randonly overwritten without much care. In general I think array randomly setting
4862 * variables en mass is risky.
4864 * @param array $values
4868 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4869 $contributionPageValues = array();
4870 CRM_Contribute_BAO_ContributionPage
::setValues(
4871 $this->contribution_page_id
,
4872 $contributionPageValues
4874 $valuesToCopy = array(
4875 // These are the values that I believe to be useful.
4878 'pay_later_receipt',
4880 'receipt_from_email',
4881 'receipt_from_name',
4885 'honoree_profile_id',
4886 'onbehalf_profile_id',
4887 'honor_block_is_active',
4888 // Kinda might be - but would be on the contribution...
4891 // Included for 'fear of regression' but can't justify any use for these....
4893 'payment_processor',
4894 'financial_type_id',
4895 'amount_block_is_active',
4900 'default_amount_id',
4904 'initial_amount_help_text',
4905 'initial_amount_label',
4907 'is_allow_other_amount',
4908 'is_billing_required',
4909 'is_confirm_enabled',
4910 'is_credit_card_only',
4912 'is_partial_payment',
4913 'is_recur_installments',
4914 'is_recur_interval',
4918 'min_initial_amount',
4919 'recur_frequency_unit',
4926 foreach ($valuesToCopy as $valueToCopy) {
4927 if (isset($contributionPageValues[$valueToCopy])) {
4928 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
4935 * Get values of CiviContribute Settings
4936 * and check if its enabled or not.
4937 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
4938 * in serialized form. Usually this should be stored as flat settings for each form fields
4939 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
4940 * settings we will live with an inconsistency because it's too hard to change for now.
4941 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
4944 * @param string $name
4945 * @param bool $checkInvoicing
4949 public static function checkContributeSettings($name = NULL, $checkInvoicing = FALSE) {
4950 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
4952 if ($checkInvoicing && !CRM_Utils_Array
::value('invoicing', $contributeSettings)) {
4957 return CRM_Utils_Array
::value($name, $contributeSettings);
4959 return $contributeSettings;
4963 * This function process contribution related objects.
4965 * @param int $contributionId
4966 * @param int $statusId
4967 * @param int|null $previousStatusId
4969 * @param string $receiveDate
4971 * @return null|string
4973 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
4975 if (!$contributionId ||
!$statusId) {
4980 'contribution_id' => $contributionId,
4981 'contribution_status_id' => $statusId,
4982 'previous_contribution_status_id' => $previousStatusId,
4983 'receive_date' => $receiveDate,
4986 $updateResult = CRM_Contribute_BAO_Contribution
::transitionComponents($params);
4988 if (!is_array($updateResult) ||
4989 !($updatedComponents = CRM_Utils_Array
::value('updatedComponents', $updateResult)) ||
4990 !is_array($updatedComponents) ||
4991 empty($updatedComponents)
4996 // get the user display name.
4998 SELECT display_name as displayName
4999 FROM civicrm_contact
5000 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
5001 WHERE civicrm_contribution.id = {$contributionId}";
5002 $userDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
5004 // get the status message for user.
5005 foreach ($updatedComponents as $componentName => $updatedStatusId) {
5007 if ($componentName == 'CiviMember') {
5008 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5009 CRM_Member_PseudoConstant
::membershipStatus()
5011 if ($updatedStatusName == 'Cancelled') {
5012 $statusMsg .= "<br />" . ts("Membership for %1 has been Cancelled.", array(1 => $userDisplayName));
5014 elseif ($updatedStatusName == 'Expired') {
5015 $statusMsg .= "<br />" . ts("Membership for %1 has been Expired.", array(1 => $userDisplayName));
5018 $endDate = CRM_Utils_Array
::value('membership_end_date', $updateResult);
5020 $statusMsg .= "<br />" . ts("Membership for %1 has been updated. The membership End Date is %2.",
5022 1 => $userDisplayName,
5030 if ($componentName == 'CiviEvent') {
5031 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5032 CRM_Event_PseudoConstant
::participantStatus()
5034 if ($updatedStatusName == 'Cancelled') {
5035 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", array(1 => $userDisplayName));
5037 elseif ($updatedStatusName == 'Registered') {
5038 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", array(1 => $userDisplayName));
5042 if ($componentName == 'CiviPledge') {
5043 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5044 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name')
5046 if ($updatedStatusName == 'Cancelled') {
5047 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", array(1 => $userDisplayName));
5049 elseif ($updatedStatusName == 'Failed') {
5050 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", array(1 => $userDisplayName));
5052 elseif ($updatedStatusName == 'Completed') {
5053 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", array(1 => $userDisplayName));
5062 * Get the contribution as it is in the database before being updated.
5064 * @param int $contributionID
5066 * @return \CRM_Contribute_BAO_Contribution|null
5068 private static function getOriginalContribution($contributionID) {
5069 return self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
5073 * Get the amount for the financial item row.
5075 * Helper function to start to break down recordFinancialTransactions for readability.
5077 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
5079 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
5080 * for historical reasons. Going forwards we can hope to add tests & improve readibility
5083 * @todo move recordFinancialAccounts & helper functions to their own class?
5085 * @param array $params
5086 * Params as passed to contribution.create
5088 * @param string $context
5089 * changeFinancialType| changedAmount
5090 * @param array $lineItemDetails
5092 * @param bool $isARefund
5093 * Is this a refund / negative transaction.
5097 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
5098 if ($context == 'changedAmount') {
5099 $lineTotal = $lineItemDetails['line_total'];
5100 if ($lineTotal != $previousLineItemTotal) {
5101 $lineTotal -= $previousLineItemTotal;
5105 elseif ($context == 'changeFinancialType') {
5106 return -$lineItemDetails['line_total'];
5108 elseif ($context == 'changedStatus') {
5109 $cancelledTaxAmount = 0;
5111 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
5113 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
5115 elseif ($context === NULL) {
5116 // erm, yes because? but, hey, it's tested.
5117 return $lineItemDetails['line_total'];
5119 elseif (empty($lineItemDetails['line_total'])) {
5120 // follow legacy code path
5122 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', array('civi.tag' => 'deprecated'));
5123 return $params['total_amount'];
5126 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
5131 * Get the multiplier for adjusting rows.
5133 * If we are dealing with a refund or cancellation then it will be a negative
5134 * amount to reflect the negative transaction.
5136 * If we are changing Financial Type it will be a negative amount to
5137 * adjust down the old type.
5139 * @param int $contribution_status_id
5140 * @param string $context
5144 protected static function getMultiplier($contribution_status_id, $context) {
5145 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
5152 * Does this transaction reflect a payment instrument change.
5154 * @param array $params
5155 * @param array $pendingStatuses
5159 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
5160 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
5162 if (array_key_exists('payment_instrument_id', $params)) {
5163 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
5164 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
5166 //check if status is changed from Pending to Completed
5167 // do not update payment instrument changes for Pending to Completed
5168 if (!($contributionStatus == 'Completed' &&
5169 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
5174 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
5175 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
5176 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
5180 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
5181 $params['contribution']->check_number
!= $params['prevContribution']->check_number
5183 // another special case when check number is changed, create new financial records
5184 // create financial trxn with negative amount
5192 * Update the memberships associated with a contribution if it has been completed.
5194 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
5195 * load them in this function. Code clean up would compensate for any minor performance implication.
5197 * @param \CRM_Contribute_BAO_Contribution $contribution
5198 * @param int $primaryContributionID
5199 * @param string $changeDate
5201 * @throws \CRM_Core_Exception
5202 * @throws \CiviCRM_API3_Exception
5204 public static function updateMembershipBasedOnCompletionOfContribution($contribution, $primaryContributionID, $changeDate) {
5205 $contribution->loadRelatedMembershipObjects();
5206 if (empty($contribution->_relatedObjects
['membership'])) {
5209 $memberships = $contribution->_relatedObjects
['membership'];
5210 foreach ($memberships as $membershipTypeIdKey => $membership) {
5212 $membershipParams = array(
5213 'id' => $membership->id
,
5214 'contact_id' => $membership->contact_id
,
5215 'is_test' => $membership->is_test
,
5216 'membership_type_id' => $membership->membership_type_id
,
5217 'membership_activity_status' => 'Completed',
5220 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
5221 $membershipParams['membership_type_id'],
5222 $membershipParams['is_test'],
5223 $membershipParams['id']
5226 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
5227 // this picks up membership type changes during renewals
5228 // @todo this is almost certainly an obsolete sql call, the pre-change
5229 // membership is accessible via $this->_relatedObjects
5231 SELECT membership_type_id
5232 FROM civicrm_membership_log
5233 WHERE membership_id={$membershipParams['id']}
5236 $dao = CRM_Core_DAO
::executeQuery($sql);
5237 if ($dao->fetch()) {
5238 if (!empty($dao->membership_type_id
)) {
5239 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
5244 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
5245 $membershipParams['membership_type_id'],
5246 $primaryContributionID
5248 // @todo remove all this stuff in favour of letting the api call further down handle in
5249 // (it is a duplication of what the api does).
5250 $dates = array_fill_keys(array(
5255 if ($currentMembership) {
5257 * Fixed FOR CRM-4433
5258 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
5259 * when Contribution mode is notify and membership is for renewal )
5261 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
5263 // @todo - we should pass membership_type_id instead of null here but not
5264 // adding as not sure of testing
5265 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
5266 $changeDate, NULL, $membershipParams['num_terms']
5268 $dates['join_date'] = $currentMembership['join_date'];
5271 //get the status for membership.
5272 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
5274 $dates['join_date'],
5277 $membershipParams['membership_type_id'],
5281 unset($dates['end_date']);
5282 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
5283 //we might be renewing membership,
5284 //so make status override false.
5285 $membershipParams['is_override'] = FALSE;
5286 $membershipParams['status_override_end_date'] = 'null';
5288 //CRM-17723 - reset static $relatedContactIds array()
5289 // @todo move it to Civi Statics.
5291 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
5292 civicrm_api3('Membership', 'create', $membershipParams);
5298 * Get payment links as they relate to a contribution.
5300 * If a payment can be made then include a payment link & if a refund is appropriate
5301 * then a refund link.
5304 * @param float $balance
5305 * @param string $contributionStatus
5307 * @return array $actionLinks Links array containing:
5311 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
5312 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
5313 // In general the balance is the best way to determine if a payment can be added or not,
5314 // but not for Failed contributions, where we don't accept additional payments at the moment.
5315 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
5316 // do accept more payments agains them.
5319 $actionLinks = array();
5320 if ((int) $balance > 0) {
5321 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
5322 $actionLinks[] = array(
5323 'url' => CRM_Utils_System
::url('civicrm/payment', array(
5329 'title' => ts('Submit Credit Card payment'),
5332 $actionLinks[] = array(
5333 'url' => CRM_Utils_System
::url('civicrm/payment', array(
5338 'title' => ts('Record Payment'),
5341 elseif ((int) $balance < 0) {
5342 $actionLinks[] = array(
5343 'url' => CRM_Utils_System
::url('civicrm/payment', array(
5348 'title' => ts('Record Refund'),
5351 return $actionLinks;
5355 * Get a query to determine the amount donated by the contact/s in the current financial year.
5357 * @param array $contactIDs
5361 public static function getAnnualQuery($contactIDs) {
5362 $contactIDs = implode(',', $contactIDs);
5363 $config = CRM_Core_Config
::singleton();
5364 $currentMonth = date('m');
5365 $currentDay = date('d');
5367 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
5369 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
5370 (int) $config->fiscalYearStart
['d'] > $currentDay
5373 $year = date('Y') - 1;
5378 $nextYear = $year +
1;
5380 if ($config->fiscalYearStart
) {
5381 $newFiscalYearStart = $config->fiscalYearStart
;
5382 if ($newFiscalYearStart['M'] < 10) {
5383 // This is just a clumsy way of adding padding.
5384 // @todo next round look for a nicer way.
5385 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
5387 if ($newFiscalYearStart['d'] < 10) {
5388 // This is just a clumsy way of adding padding.
5389 // @todo next round look for a nicer way.
5390 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
5392 $config->fiscalYearStart
= $newFiscalYearStart;
5393 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
5396 // First of January.
5399 $startDate = "$year$monthDay";
5400 $endDate = "$nextYear$monthDay";
5403 'contact_id' => 'IN (' . $contactIDs . ')',
5404 'is_test' => ' = 0',
5405 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
5407 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
5408 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
5411 foreach ($whereClauses as $key => $clause) {
5412 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
5414 $whereClauseString = implode(' AND ', $clauses);
5416 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5417 // this group by + having on contribution_status_id improves performance
5419 SELECT COUNT(*) as count,
5420 SUM(total_amount) as amount,
5421 AVG(total_amount) as average,
5423 FROM civicrm_contribution b
5424 WHERE " . $whereClauseString . "
5425 GROUP BY currency, contribution_status_id
5426 HAVING $havingClause
5432 * Assign Test Value.
5434 * @param string $fieldName
5435 * @param array $fieldDef
5436 * @param int $counter
5438 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5439 if ($fieldName == 'tax_amount') {
5440 $this->{$fieldName} = "0.00";
5442 elseif ($fieldName == 'net_amount') {
5443 $this->{$fieldName} = "2.00";
5445 elseif ($fieldName == 'total_amount') {
5446 $this->{$fieldName} = "3.00";
5448 elseif ($fieldName == 'fee_amount') {
5449 $this->{$fieldName} = "1.00";
5452 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5457 * Check if contribution has participant/membership payment.
5459 * @param int $contributionId
5464 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5465 // get line item for contribution
5466 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5467 // check if line item is for membership or participant
5468 foreach ($lineItems as $items) {
5469 if ($items['entity_table'] == 'civicrm_participant') {
5473 elseif ($items['entity_table'] == 'civicrm_membership') {
5485 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5487 * @param array $trxnParams
5488 * Financial trxn params
5489 * @param array $contributionParams
5490 * Contribution Params
5494 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5495 if (!self
::checkContributeSettings('always_post_to_accounts_receivable')) {
5498 $statusId = $contributionParams['contribution']->contribution_status_id
;
5499 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5500 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5501 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5502 // Return if contribution status is not completed.
5503 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5504 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5505 && $contributionParams['prevContribution']->is_pay_later
== 0
5511 $params = $trxnParams;
5512 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $contributionParams) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5513 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5514 $params['to_financial_account_id'] = $arAccountId;
5515 $params['status_id'] = array_search('Pending', $contributionStatuses);
5516 $params['is_payment'] = FALSE;
5517 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5518 self
::$_trxnIDs[] = $trxn->id
;
5519 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5523 * Calculate financial item amount when contribution is updated.
5525 * @param array $params
5526 * contribution params
5527 * @param array $amountParams
5529 * @param string $context
5533 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5534 if (!empty($params['is_quick_config'])) {
5535 $amount = $amountParams['item_amount'];
5537 $amount = $params['total_amount'];
5538 if ($context === NULL) {
5539 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5544 $amount = $amountParams['line_total'];
5545 if ($context == 'changedAmount') {
5546 $amount -= $amountParams['previous_line_total'];
5548 $amount *= $amountParams['diff'];
5554 * Retrieve Sales Tax Financial Accounts.
5560 public static function getSalesTaxFinancialAccounts() {
5561 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5562 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5563 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5564 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5565 $queryParams = array(1 => array($accountRel, 'Integer'));
5566 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5567 $financialAccount = array();
5568 while ($dao->fetch()) {
5569 $financialAccount[$dao->id
] = $dao->id
;
5571 return $financialAccount;
5575 * Create tax entry in civicrm_entity_financial_trxn table.
5577 * @param array $entityParams
5579 * @param array $eftParams
5582 public static function createProportionalEntry($entityParams, $eftParams) {
5584 if ($entityParams['contribution_total_amount'] != 0) {
5585 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5587 // Record Entity Financial Trxn; CRM-20145
5588 $eftParams['amount'] = CRM_Contribute_BAO_Contribution_Utils
::formatAmount($paid);
5589 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5593 * Create array of last financial item id's.
5595 * @param int $contributionId
5599 public static function getLastFinancialItemIds($contributionId) {
5600 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5601 FROM civicrm_financial_item fi
5602 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5603 WHERE li.contribution_id = %1";
5604 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($contributionId, 'Integer')));
5605 $ftIds = $taxItems = array();
5606 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5607 while ($dao->fetch()) {
5608 /* if sales tax item*/
5609 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5610 $taxItems[$dao->price_field_value_id
] = array(
5611 'financial_item_id' => $dao->id
,
5612 'amount' => $dao->tax_amount
,
5616 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5619 return array($ftIds, $taxItems);
5623 * Create proportional entries in civicrm_entity_financial_trxn.
5625 * @param array $entityParams
5627 * @param array $lineItems
5629 * @param array $ftIds
5631 * @param array $taxItems
5634 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5636 'entity_table' => 'civicrm_financial_item',
5637 'financial_trxn_id' => $entityParams['trxn_id'],
5639 foreach ($lineItems as $key => $value) {
5640 if ($value['qty'] == 0) {
5643 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5644 $entityParams['line_item_amount'] = $value['line_total'];
5645 self
::createProportionalEntry($entityParams, $eftParams);
5646 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5647 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5648 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5649 self
::createProportionalEntry($entityParams, $eftParams);
5655 * Load entities related to the contribution into $this->_relatedObjects.
5659 * @throws \CRM_Core_Exception
5661 protected function loadRelatedEntitiesByID($ids) {
5663 'contact' => 'CRM_Contact_BAO_Contact',
5664 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5665 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5666 'financialType' => 'CRM_Financial_BAO_FinancialType',
5667 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5669 foreach ($entities as $entity => $bao) {
5670 if (!empty($ids[$entity])) {
5671 $this->_relatedObjects
[$entity] = new $bao();
5672 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5673 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5674 throw new CRM_Core_Exception($entity . ' could not be loaded');
5681 * Should an email receipt be sent for this contribution when complete.
5683 * @param array $input
5687 protected function isEmailReceipt($input) {
5688 if (isset($input['is_email_receipt'])) {
5689 return $input['is_email_receipt'];
5691 if (!empty($this->_relatedObjects
['contribution_page_id'])) {
5692 return $this->_relatedObjects
['contribution_page_id']->is_email_receipt
;
5698 * Function to replace contribution tokens.
5700 * @param array $contributionIds
5702 * @param string $subject
5704 * @param array $subjectToken
5706 * @param string $text
5708 * @param string $html
5710 * @param array $messageToken
5712 * @param bool $escapeSmarty
5716 public static function replaceContributionTokens(
5725 if (empty($contributionIds)) {
5728 $contributionDetails = array();
5729 foreach ($contributionIds as $id) {
5730 $result = civicrm_api3('Contribution', 'get', array('id' => $id));
5731 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5732 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5733 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5735 return $contributionDetails;
5739 * Get invoice_number for contribution.
5741 * @param int $contributionID
5745 public static function getInvoiceNumber($contributionID) {
5746 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix', TRUE)) {
5747 return $invoicePrefix . $contributionID;