3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
20 * Static field for all the contribution information that we can potentially import
24 public static $_importableFields = NULL;
27 * Static field for all the contribution information that we can potentially export
31 public static $_exportableFields = NULL;
34 * Static field to hold financial trxn id's.
38 public static $_trxnIDs = NULL;
41 * Field for all the objects related to this contribution
43 * @var \CRM_Member_BAO_Membership|\CRM_Event_BAO_Participant[]
45 public $_relatedObjects = [];
48 * Field for the component - either 'event' (participant) or 'contribute'
49 * (any item related to a contribution page e.g. membership, pledge, contribution)
50 * This is used for composing messages because they have dependency on the
51 * contribution_page or event page - although over time we may eliminate that
54 * "contribution"\"event"
56 public $_component = NULL;
59 * Possibly obsolete variable.
61 * If you use it please explain why it is set in the create function here.
65 public $trxn_result_code;
70 public function __construct() {
71 parent
::__construct();
75 * Takes an associative array and creates a contribution object.
77 * the function extract all the params it needs to initialize the create a
78 * contribution object. the params array could contain additional unused name/value
81 * @param array $params
82 * (reference ) an assoc array of name/value pairs.
84 * The array that holds all the db ids.
86 * @return \CRM_Contribute_BAO_Contribution
87 * @throws \CRM_Core_Exception
88 * @throws \CiviCRM_API3_Exception
90 public static function add(&$params, $ids = []) {
95 CRM_Core_Error
::deprecatedFunctionWarning('ids should not be passed into Contribution.add');
97 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
98 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
99 $action = $contributionID ?
'edit' : 'create';
101 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
102 $message = ts("Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: %1", [1 => implode(', ', $duplicates)]);
103 throw new CRM_Core_Exception($message);
106 // first clean up all the money fields
111 'non_deductible_amount',
114 //if priceset is used, no need to cleanup money
115 if (!empty($params['skipCleanMoney'])) {
119 // @todo put a deprecated here - this should be done in the form layer.
120 $params['skipCleanMoney'] = FALSE;
121 Civi
::log()->warning('Deprecated code path. Money should always be clean before it hits the BAO.', array('civi.tag' => 'deprecated'));
124 foreach ($moneyFields as $field) {
125 if (isset($params[$field])) {
126 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
130 //set defaults in create mode
131 if (!$contributionID) {
132 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
133 if (empty($params['invoice_number']) && CRM_Invoicing_Utils
::isInvoicingEnabled()) {
134 $nextContributionID = CRM_Core_DAO
::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
135 $params['invoice_number'] = self
::getInvoiceNumber($nextContributionID);
139 $contributionStatusID = $params['contribution_status_id'] ??
NULL;
140 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $contributionStatusID) === 'Partially paid' && empty($params['is_post_payment_create'])) {
141 CRM_Core_Error
::deprecatedFunctionWarning('Setting status to partially paid other than by using Payment.create is deprecated and unreliable');
143 if (!$contributionStatusID) {
144 // Since the fee amount is expecting this (later on) ensure it is always set.
145 // It would only not be set for an update where it is unchanged.
146 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', [
147 'id' => $contributionID,
148 'return' => 'contribution_status_id',
151 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['contribution_status_id']);
154 && CRM_Utils_Array
::value('membership_id', $params)
155 && Civi
::settings()->get('deferred_revenue_enabled')
157 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
158 if ($memberStartDate) {
159 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
162 self
::calculateMissingAmountParams($params, $contributionID);
164 if (!empty($params['payment_instrument_id'])) {
165 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
166 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
167 $params['check_number'] = 'null';
171 $setPrevContribution = TRUE;
172 // CRM-13964 partial payment
173 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])) {
174 CRM_Core_Error
::deprecatedFunctionWarning('partial_amount params are deprecated from Contribution.create - use Payment.create');
175 $partialAmtTotal = $params['partial_payment_total'];
176 $partialAmtPay = $params['partial_amount_to_pay'];
177 $params['total_amount'] = $partialAmtTotal;
178 if ($partialAmtPay < $partialAmtTotal) {
179 $params['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Partially paid');
180 $params['is_pay_later'] = 0;
181 $setPrevContribution = FALSE;
184 if ($contributionID && $setPrevContribution) {
185 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
187 $previousContributionStatus = ($contributionID && !empty($params['prevContribution'])) ? CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['prevContribution']->contribution_status_id
) : NULL;
189 if ($contributionID && !empty($params['revenue_recognition_date'])
190 && !($previousContributionStatus === 'Pending')
191 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
193 unset($params['revenue_recognition_date']);
196 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
197 isset($params['financial_type_id']))) {
198 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
201 CRM_Utils_Hook
::pre($action, 'Contribution', $contributionID, $params);
203 $contribution = new CRM_Contribute_BAO_Contribution();
204 $contribution->copyValues($params);
206 $contribution->id
= $contributionID;
208 if (empty($contribution->id
)) {
209 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
210 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
211 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
215 $result = $contribution->save();
217 // Add financial_trxn details as part of fix for CRM-4724
218 $contribution->trxn_result_code
= $params['trxn_result_code'] ??
NULL;
219 $contribution->payment_processor
= $params['payment_processor'] ??
NULL;
221 //add Account details
222 $params['contribution'] = $contribution;
223 if (empty($params['is_post_payment_create'])) {
224 // If this is being called from the Payment.create api/ BAO then that Entity
225 // takes responsibility for the financial transactions. In fact calling Payment.create
226 // to add payments & having it call completetransaction and / or contribution.create
227 // to update related entities is the preferred flow.
228 // Note that leveraging this parameter for any other code flow is not supported and
229 // is likely to break in future and / or cause serious problems in your data.
230 // https://github.com/civicrm/civicrm-core/pull/14673
231 self
::recordFinancialAccounts($params);
234 if (self
::isUpdateToRecurringContribution($params)) {
235 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
236 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
238 CRM_Utils_Array
::value('receive_date', $params)
242 $params['contribution_id'] = $contribution->id
;
244 if (!empty($params['custom']) &&
245 is_array($params['custom'])
247 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
, $action);
250 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
252 CRM_Utils_Hook
::post($action, 'Contribution', $contribution->id
, $contribution);
257 * Is this contribution updating an existing recurring contribution.
259 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
260 * pending payment is being confirmed (or failing).
262 * @param array $params
266 public static function isUpdateToRecurringContribution($params) {
267 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
270 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
273 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
276 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
277 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
284 * Get defaults for new entity.
288 public static function getDefaults() {
290 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
291 FALSE, FALSE, FALSE, 'AND is_default = 1')
293 'contribution_status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
294 'receive_date' => date('Y-m-d H:i:s'),
299 * Fetch the object and store the values in the values array.
301 * @param array $params
302 * Input parameters to find object.
303 * @param array $values
304 * Output values of the object.
306 * The array that holds all the db ids.
308 * @return CRM_Contribute_BAO_Contribution|null
309 * The found object or null
311 public static function getValues($params, &$values = [], &$ids = []) {
312 if (empty($params)) {
315 $contribution = new CRM_Contribute_BAO_Contribution();
317 $contribution->copyValues($params);
319 if ($contribution->find(TRUE)) {
320 $ids['contribution'] = $contribution->id
;
322 CRM_Core_DAO
::storeValues($contribution, $values);
324 return $contribution;
326 // return by reference
332 * Get the values and resolve the most common mappings.
334 * Since contribution status is resolved in almost every function that calls getValues it makes
335 * sense to have an extra function to resolve it rather than repeat the code.
337 * Think carefully before adding more mappings to be resolved as there could be performance implications
338 * if this function starts to be called from more iterative functions.
340 * @param array $params
341 * Input parameters to find object.
344 * Array of the found contribution.
345 * @throws CRM_Core_Exception
347 public static function getValuesWithMappings($params) {
349 $contribution = self
::getValues($params, $values, $ids);
350 if (is_null($contribution)) {
351 throw new CRM_Core_Exception('No contribution found');
353 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
358 * Calculate net_amount & fee_amount if they are not set.
360 * Net amount should be total - fee.
361 * This should only be called for new contributions.
363 * @param array $params
364 * Params for a new contribution before they are saved.
365 * @param int|null $contributionID
366 * Contribution ID if we are dealing with an update.
368 * @throws \CiviCRM_API3_Exception
370 public static function calculateMissingAmountParams(&$params, $contributionID) {
371 if (!$contributionID && !isset($params['fee_amount'])) {
372 if (isset($params['total_amount']) && isset($params['net_amount'])) {
373 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
376 $params['fee_amount'] = 0;
379 if (!isset($params['net_amount'])) {
380 if (!$contributionID) {
381 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
384 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
385 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
386 // net_amount may need adjusting.
387 $contribution = civicrm_api3('Contribution', 'getsingle', [
388 'id' => $contributionID,
389 'return' => ['total_amount', 'net_amount', 'fee_amount'],
391 $totalAmount = (isset($params['total_amount']) ?
(float) $params['total_amount'] : (float) CRM_Utils_Array
::value('total_amount', $contribution));
392 $feeAmount = (isset($params['fee_amount']) ?
(float) $params['fee_amount'] : (float) CRM_Utils_Array
::value('fee_amount', $contribution));
393 $params['net_amount'] = $totalAmount - $feeAmount;
401 * @param $billingLocationTypeID
405 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
406 $hasBillingField = FALSE;
415 //build address array
417 $addressParams['location_type_id'] = $billingLocationTypeID;
418 $addressParams['is_billing'] = 1;
420 $billingFirstName = $params['billing_first_name'] ??
NULL;
421 $billingMiddleName = $params['billing_middle_name'] ??
NULL;
422 $billingLastName = $params['billing_last_name'] ??
NULL;
423 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
425 foreach ($billingFields as $value) {
426 $addressParams[$value] = $params["billing_{$value}-{$billingLocationTypeID}"] ??
NULL;
427 if (!empty($addressParams[$value])) {
428 $hasBillingField = TRUE;
431 return [$hasBillingField, $addressParams];
435 * Get address params ready to be passed to the payment processor.
437 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
438 * To create an address we need state_province_id.
440 * @param array $params
441 * @param int $billingLocationTypeID
445 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
446 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
447 foreach ($addressParams as $name => $field) {
448 if (substr($name, 0, 8) == 'billing_') {
449 $addressParams[substr($name, 9)] = $addressParams[$field];
452 return [$hasBillingField, $addressParams];
456 * Get the number of terms for this contribution for a given membership type
457 * based on querying the line item table and relevant price field values
458 * Note that any one contribution should only be able to have one line item relating to a particular membership
461 * @param int $membershipTypeID
463 * @param int $contributionID
467 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
468 $numTerms = CRM_Core_DAO
::singleValueQuery("
469 SELECT membership_num_terms FROM civicrm_line_item li
470 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
471 WHERE contribution_id = %1 AND membership_type_id = %2",
472 [1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']]
474 // default of 1 is precautionary
475 return empty($numTerms) ?
1 : $numTerms;
479 * Takes an associative array and creates a contribution object.
481 * @param array $params
482 * (reference ) an assoc array of name/value pairs.
484 * The array that holds all the db ids.
486 * @return CRM_Contribute_BAO_Contribution
488 * @throws \CRM_Core_Exception
489 * @throws \CiviCRM_API3_Exception
491 public static function create(&$params, $ids = []) {
497 'revenue_recognition_date',
499 foreach ($dateFields as $df) {
500 if (isset($params[$df])) {
501 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
505 $transaction = new CRM_Core_Transaction();
508 if (!isset($params['id']) && isset($ids['contribution'])) {
509 CRM_Core_Error
::deprecatedFunctionWarning('ids should not be used for contribution create');
510 $params['id'] = $ids['contribution'];
512 $contribution = self
::add($params);
514 catch (CRM_Core_Exception
$e) {
515 $transaction->rollback();
519 $params['contribution_id'] = $contribution->id
;
520 $session = CRM_Core_Session
::singleton();
522 if (!empty($params['note'])) {
524 'entity_table' => 'civicrm_contribution',
525 'note' => $params['note'],
526 'entity_id' => $contribution->id
,
527 'contact_id' => $session->get('userID'),
529 if (!$noteParams['contact_id']) {
530 $noteParams['contact_id'] = $params['contact_id'];
532 CRM_Core_BAO_Note
::add($noteParams);
535 // make entry in batch entity batch table
536 if (!empty($params['batch_id'])) {
537 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
544 $retrieveRequired = 0;
545 foreach ($titleFields as $titleField) {
546 if (!isset($contribution->$titleField)) {
547 $retrieveRequired = 1;
551 if ($retrieveRequired == 1) {
552 $contribution->find(TRUE);
556 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
558 $transaction->commit();
560 $activity = civicrm_api3('Activity', 'get', [
561 'source_record_id' => $contribution->id
,
562 'options' => ['limit' => 1],
564 'activity_type_id' => 'Contribution',
565 'return' => ['id', 'campaign'],
568 //CRM-18406: Update activity when edit contribution.
569 if ($activity['count']) {
570 // CRM-13237 : if activity record found, update it with campaign id of contribution
571 // @todo compare campaign ids first.
572 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity['id'], 'campaign_id', $contribution->campaign_id
);
573 $contribution->activity_id
= $activity['id'];
576 if (empty($contribution->contact_id
)) {
577 $contribution->find(TRUE);
579 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution');
581 // do not add to recent items for import, CRM-4399
582 if (empty($params['skipRecentView'])) {
583 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
584 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
586 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
593 $retrieveRequired = 0;
594 foreach ($titleFields as $titleField) {
595 if (!isset($contribution->$titleField)) {
596 $retrieveRequired = 1;
600 if ($retrieveRequired == 1) {
601 $contribution->find(TRUE);
603 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
604 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
607 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
608 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
609 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
613 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
614 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
615 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
619 // add the recently created Contribution
620 CRM_Utils_Recent
::add($title,
624 $contribution->contact_id
,
630 return $contribution;
634 * Get the values for pseudoconstants for name->value and reverse.
636 * @param array $defaults
637 * (reference) the default values, some of which need to be resolved.
638 * @param bool $reverse
639 * True if we want to resolve the values in the reverse direction (value -> name).
641 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
642 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
643 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
644 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'), $reverse);
645 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
649 * Convert associative array names to values and vice-versa.
651 * This function is used by both the web form layer and the api. Note that
652 * the api needs the name => value conversion, also the view layer typically
653 * requires value => name conversion
655 * @param array $defaults
656 * @param string $property
657 * @param array $lookup
658 * @param bool $reverse
662 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
663 $id = $property . '_id';
665 $src = $reverse ?
$property : $id;
666 $dst = $reverse ?
$id : $property;
668 if (!array_key_exists($src, $defaults)) {
672 $look = $reverse ?
array_flip($lookup) : $lookup;
674 if (is_array($look)) {
675 if (!array_key_exists($defaults[$src], $look)) {
679 $defaults[$dst] = $look[$defaults[$src]];
684 * Retrieve DB object based on input parameters.
686 * It also stores all the retrieved values in the default array.
688 * @param array $params
689 * (reference ) an assoc array of name/value pairs.
690 * @param array $defaults
691 * (reference ) an assoc array to hold the name / value pairs.
692 * in a hierarchical manner
694 * (reference) the array that holds all the db ids.
696 * @return CRM_Contribute_BAO_Contribution
698 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
699 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
700 return $contribution;
704 * Combine all the importable fields from the lower levels object.
706 * The ordering is important, since currently we do not have a weight
707 * scheme. Adding weight is super important and should be done in the
708 * next week or so, before this can be called complete.
710 * @param string $contactType
711 * @param bool $status
714 * array of importable Fields
716 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
717 if (!self
::$_importableFields) {
718 if (!self
::$_importableFields) {
719 self
::$_importableFields = [];
723 $fields = ['' => ['title' => ts('- do not import -')]];
726 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
729 $note = CRM_Core_DAO_Note
::import();
730 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
731 unset($tmpFields['option_value']);
732 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
733 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
735 // Using new Dedupe rule.
737 'contact_type' => $contactType,
738 'used' => 'Unsupervised',
740 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
741 $tmpContactField = [];
742 if (is_array($fieldsArray)) {
743 foreach ($fieldsArray as $value) {
744 //skip if there is no dupe rule
745 if ($value == 'none') {
748 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
753 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
754 $tmpContactField[trim($value)] = $contactFields[trim($value)];
756 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
759 $title = $tmpContactField[trim($value)]['title'];
761 $tmpContactField[trim($value)]['title'] = $title;
765 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
766 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
767 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
768 $fields = array_merge($fields, $tmpContactField);
769 $fields = array_merge($fields, $tmpFields);
770 $fields = array_merge($fields, $note);
771 $fields = array_merge($fields, $optionFields);
772 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
773 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
774 self
::$_importableFields = $fields;
776 return self
::$_importableFields;
780 * Combine all the exportable fields from the lower level objects.
782 * @param bool $checkPermission
785 * array of exportable Fields
787 public static function &exportableFields($checkPermission = TRUE) {
788 if (!self
::$_exportableFields) {
789 if (!self
::$_exportableFields) {
790 self
::$_exportableFields = [];
793 $fields = CRM_Contribute_DAO_Contribution
::export();
794 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
795 $fields = array_merge(
797 CRM_Contribute_DAO_Product
::export(),
798 CRM_Contribute_DAO_ContributionProduct
::export(),
799 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
801 'contribution_product_id' => [
802 'title' => ts('Premium'),
803 'name' => 'contribution_product_id',
804 'where' => 'civicrm_product.id',
805 'data_type' => CRM_Utils_Type
::T_INT
,
811 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
813 $contributionPage = [
814 'contribution_page' => [
815 'title' => ts('Contribution Page'),
816 'name' => 'contribution_page',
817 'where' => 'civicrm_contribution_page.title',
818 'data_type' => CRM_Utils_Type
::T_STRING
,
822 $contributionNote = [
823 'contribution_note' => [
824 'title' => ts('Contribution Note'),
825 'name' => 'contribution_note',
826 'data_type' => CRM_Utils_Type
::T_TEXT
,
831 'contribution_batch' => [
832 'title' => ts('Batch Name'),
838 'contribution_campaign_title' => [
839 'title' => ts('Campaign Title'),
840 'name' => 'campaign_title',
841 'where' => 'civicrm_campaign.title',
842 'data_type' => CRM_Utils_Type
::T_STRING
,
845 $softCreditFields = [
846 'contribution_soft_credit_name' => [
847 'name' => 'contribution_soft_credit_name',
848 'title' => ts('Soft Credit For'),
849 'where' => 'civicrm_contact_d.display_name',
850 'data_type' => CRM_Utils_Type
::T_STRING
,
852 'contribution_soft_credit_amount' => [
853 'name' => 'contribution_soft_credit_amount',
854 'title' => ts('Soft Credit Amount'),
855 'where' => 'civicrm_contribution_soft.amount',
856 'data_type' => CRM_Utils_Type
::T_MONEY
,
858 'contribution_soft_credit_type' => [
859 'name' => 'contribution_soft_credit_type',
860 'title' => ts('Soft Credit Type'),
861 'where' => 'contribution_softcredit_type.label',
862 'data_type' => CRM_Utils_Type
::T_STRING
,
864 'contribution_soft_credit_contribution_id' => [
865 'name' => 'contribution_soft_credit_contribution_id',
866 'title' => ts('Soft Credit For Contribution ID'),
867 'where' => 'civicrm_contribution_soft.contribution_id',
868 'data_type' => CRM_Utils_Type
::T_INT
,
870 'contribution_soft_credit_contact_id' => [
871 'name' => 'contribution_soft_credit_contact_id',
872 'title' => ts('Soft Credit For Contact ID'),
873 'where' => 'civicrm_contact_d.id',
874 'data_type' => CRM_Utils_Type
::T_INT
,
878 $fields = array_merge($fields, $contributionPage,
879 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
880 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
883 self
::$_exportableFields = $fields;
886 return self
::$_exportableFields;
890 * Record an activity when a payment is received.
892 * @todo this is intended to be moved to payment BAO class as a protected function
893 * on that class. Currently being cleaned up. The addActivityForPayment doesn't really
894 * merit it's own function as it makes the code less rather than more readable.
896 * @param int $contributionId
897 * @param int $participantId
898 * @param string $totalAmount
899 * @param string $currency
900 * @param string $trxnDate
902 * @throws \CRM_Core_Exception
903 * @throws \CiviCRM_API3_Exception
905 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
906 $activityType = ($totalAmount < 0) ?
'Refund' : 'Payment';
908 if ($participantId) {
909 $inputParams['id'] = $participantId;
912 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
913 $entityObj = $entityObj[$participantId];
914 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
917 $entityObj = new CRM_Contribute_BAO_Contribution();
918 $entityObj->id
= $contributionId;
919 $entityObj->find(TRUE);
920 $title = ts('Contribution');
922 // @todo per block above this is not a logical splitting off of functionality.
923 self
::addActivityForPayment($entityObj->contact_id
, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
927 * Get the value for the To Financial Account.
929 * @param $contribution
934 public static function getToFinancialAccount($contribution, $params) {
935 if (!empty($params['payment_processor_id'])) {
936 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor_id'], NULL, 'civicrm_payment_processor');
938 if (!empty($params['payment_instrument_id'])) {
939 return CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
942 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
943 $queryParams = [1 => [$relationTypeId, 'Integer']];
944 return CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
949 * Get memberships related to the contribution.
951 * @param int $contributionID
955 protected static function getRelatedMemberships($contributionID) {
956 $membershipPayments = civicrm_api3('MembershipPayment', 'get', [
957 'return' => 'membership_id',
958 'contribution_id' => (int) $contributionID,
961 foreach ($membershipPayments as $membershipPayment) {
962 $membershipIDs[] = $membershipPayment['membership_id'];
964 if (empty($membershipIDs)) {
967 // We could combine this with the MembershipPayment.get - we'd
968 // need to re-wrangle the params (here or in the calling function)
969 // as they would then me membership.contact_id, membership.is_test etc
970 return civicrm_api3('Membership', 'get', [
971 'id' => ['IN' => $membershipIDs],
972 'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'],
977 * Cancel contribution.
979 * This function should only be called from transitioncomponents - it is an interim step in refactoring.
981 * @param $processContributionObject
982 * @param $memberships
983 * @param $contributionId
984 * @param $membershipStatuses
985 * @param $updateResult
986 * @param $participant
988 * @param $pledgePayment
990 * @param $pledgePaymentIDs
991 * @param $contributionStatusId
995 protected static function cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId) {
996 // @fixme https://lab.civicrm.org/dev/core/issues/927 Cancelling membership etc is not desirable for all use-cases and we should be able to disable it
997 $processContribution = FALSE;
998 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
999 if (is_array($memberships)) {
1000 foreach ($memberships as $membership) {
1002 //Update Membership status if there is no other completed contribution associated with the membership.
1003 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1004 foreach ($relatedContributions as $contriId) {
1005 if ($contriId == $contributionId) {
1008 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1009 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1013 if ($membership && $update) {
1014 $newStatus = array_search('Cancelled', $membershipStatuses);
1017 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1019 'subject' => "Status changed from {$allStatus[$membership->status_id]} to {$allStatus[$newStatus]}",
1020 'source_contact_id' => CRM_Core_Session
::singleton()->get('userID'),
1021 'target_contact_id' => $membership->contact_id
,
1022 'source_record_id' => $membership->id
,
1023 'activity_type_id' => 'Change Membership Status',
1024 'status_id' => 'Completed',
1025 'priority_id' => 'Normal',
1026 'activity_date_time' => 'now',
1029 $membership->status_id
= $newStatus;
1030 $membership->is_override
= TRUE;
1031 $membership->status_override_end_date
= 'null';
1032 $membership->save();
1033 civicrm_api3('activity', 'create', $activityParam);
1035 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1036 if ($processContributionObject) {
1037 $processContribution = TRUE;
1044 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1045 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1047 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1048 if ($processContributionObject) {
1049 $processContribution = TRUE;
1053 if ($pledgePayment) {
1054 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1056 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1057 if ($processContributionObject) {
1058 $processContribution = TRUE;
1061 return [$updateResult, $processContribution];
1065 * Do any accounting updates required as a result of a contribution status change.
1067 * Currently we have a bit of a roundabout where adding a payment results in this being called &
1068 * this may attempt to add a payment. We need to resolve that....
1070 * The 'right' way to add payments or refunds is through the Payment.create api. That api
1071 * then updates the contribution but this process should not also record another financial trxn.
1072 * Currently we have weak detection fot that scenario & where it is detected the first returned
1073 * value is FALSE - meaning 'do not continue'.
1075 * We should also look at the fact that the calling function - updateFinancialAccounts
1076 * bunches together some disparate processes rather than having separate appropriate
1079 * @param array $params
1082 * Return indicates whether the updateFinancialAccounts function should continue.
1084 private static function updateFinancialAccountsOnContributionStatusChange(&$params) {
1085 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
1086 $currentContributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
1088 if ((($previousContributionStatus == 'Partially paid' && $currentContributionStatus == 'Completed')
1089 ||
($previousContributionStatus == 'Pending refund' && $currentContributionStatus == 'Completed')
1090 // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
1091 // why it is here or where it is handled instead.
1092 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
1093 && $currentContributionStatus == 'Partially paid'))
1098 if (self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
)) {
1099 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1100 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1102 elseif (($previousContributionStatus == 'Pending'
1103 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
1105 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
1106 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
1108 if ($currentContributionStatus == 'Cancelled') {
1109 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1110 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
1111 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1114 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1115 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
1119 if (($previousContributionStatus == 'Pending'
1120 ||
$previousContributionStatus == 'In Progress')
1121 && ($currentContributionStatus == 'Completed')
1123 if (empty($params['line_item'])) {
1125 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
1126 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
1127 // & this can be removed
1130 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1131 // This is an update so original currency if none passed in.
1132 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
1134 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
1135 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
1136 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1137 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
1139 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
1142 'entity_table' => 'civicrm_financial_item',
1144 foreach ($params['line_item'] as $fieldId => $fields) {
1145 foreach ($fields as $fieldValueId => $lineItemDetails) {
1146 self
::updateFinancialItemForLineItemToPaid($lineItemDetails['id']);
1148 1 => [$lineItemDetails['id'], 'Integer'],
1150 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
1151 while ($financialItem->fetch()) {
1152 $entityParams['entity_id'] = $financialItem->id
;
1153 $entityParams['amount'] = $financialItem->amount
;
1154 foreach (self
::$_trxnIDs as $tID) {
1155 $entityParams['financial_trxn_id'] = $tID;
1156 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
1167 * It is possible to override the membership id that is updated from the payment processor.
1169 * Historically Paypal does this & it still does if it determines data is messed up - see
1170 * https://lab.civicrm.org/dev/membership/issues/13
1172 * Read the comment block on repeattransaction for more information
1173 * about how things should work.
1175 * @param int $contributionID
1176 * @param array $input
1178 * @throws \CiviCRM_API3_Exception
1180 protected static function handleMembershipIDOverride($contributionID, $input) {
1181 if (!empty($input['membership_id'])) {
1182 Civi
::log()->debug('The related membership id has been overridden - this may impact data - see https://github.com/civicrm/civicrm-core/pull/15053');
1183 civicrm_api3('MembershipPayment', 'create', ['contribution_id' => $contributionID, 'membership_id' => $input['membership_id']]);
1188 * Update all financial items related to the line item tto have a status of paid.
1190 * @param int $lineItemID
1192 private static function updateFinancialItemForLineItemToPaid($lineItemID) {
1195 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1198 2 => [$lineItemID, 'Integer'],
1200 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
1201 CRM_Core_DAO
::executeQuery($query, $fparams);
1205 * Create the financial items for the line.
1207 * @param array $params
1208 * @param string $context
1209 * @param array $fields
1210 * @param array $previousLineItems
1211 * @param array $inputParams
1212 * @param bool $isARefund
1213 * @param array $trxnIds
1214 * @param int $fieldId
1218 private static function createFinancialItemsForLine($params, $context, $fields, array $previousLineItems, array $inputParams, bool $isARefund, $trxnIds, $fieldId): array {
1219 foreach ($fields as $fieldValueId => $lineItemDetails) {
1220 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($lineItemDetails['id']);
1221 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
1222 if ($params['contribution']->receive_date
) {
1223 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
1226 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array
::value('financial_account_id', $prevFinancialItem));
1228 $currency = $params['prevContribution']->currency
;
1229 if ($params['contribution']->currency
) {
1230 $currency = $params['contribution']->currency
;
1232 $previousLineItemTotal = CRM_Utils_Array
::value('line_total', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1234 'transaction_date' => $receiveDate,
1235 'contact_id' => $params['prevContribution']->contact_id
,
1236 'currency' => $currency,
1237 'amount' => self
::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
1238 'description' => $prevFinancialItem['description'] ??
NULL,
1239 'status_id' => $prevFinancialItem['status_id'],
1240 'financial_account_id' => $financialAccount,
1241 'entity_table' => 'civicrm_line_item',
1242 'entity_id' => $lineItemDetails['id'],
1244 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1245 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
1246 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
1248 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') ||
($context == 'changeFinancialType')) {
1249 $taxAmount = (float) $lineItemDetails['tax_amount'];
1250 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
1251 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
1252 $taxAmount = CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1254 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
1255 $taxAmount -= CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1257 if ($taxAmount != 0) {
1258 $itemParams['amount'] = self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * $taxAmount;
1259 $itemParams['description'] = CRM_Invoicing_Utils
::getTaxTerm();
1260 if ($lineItemDetails['financial_type_id']) {
1261 $itemParams['financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getSalesTaxFinancialAccount($lineItemDetails['financial_type_id']);
1263 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1271 * Does this contributtion status update represent a refund.
1273 * @param int $previousContributionStatusID
1274 * @param int $currentContributionStatusID
1278 private static function isContributionUpdateARefund($previousContributionStatusID, $currentContributionStatusID): bool {
1279 if ('Completed' !== CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $previousContributionStatusID)) {
1282 return self
::isContributionStatusNegative($currentContributionStatusID);
1286 * Get transaction information about the contribution.
1288 * @param int $contributionId
1289 * @param int $financialTypeID
1293 protected static function getContributionTransactionInformation($contributionId, int $financialTypeID) {
1295 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Expense Account is');
1297 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
1299 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
1301 ft.payment_instrument_id,
1302 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
1304 FROM civicrm_contribution con
1305 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
1306 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
1307 AND ft.to_financial_account_id != %2
1308 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
1309 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
1310 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
1312 WHERE con.id = %1 AND ft.is_payment = 1
1315 1 => [$contributionId, 'Integer'],
1316 2 => [$feeFinancialAccount, 'Integer'],
1318 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
1319 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label');
1321 while ($resultDAO->fetch()) {
1322 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1323 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1324 if ($resultDAO->card_type_id
) {
1325 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
1326 $pantruncation = '';
1327 if ($resultDAO->pan_truncation
) {
1328 $pantruncation = ": {$resultDAO->pan_truncation}";
1330 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
1333 // show payment edit link only for payments done via backoffice form
1334 $paymentEditLink = '';
1335 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
1337 CRM_Core_Action
::UPDATE
=> [
1338 'name' => "<i class='crm-i fa-pencil'></i>",
1339 'url' => 'civicrm/payment/edit',
1340 'class' => 'medium-popup',
1341 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
1342 'title' => ts('Edit Payment'),
1345 $paymentEditLink = CRM_Core_Action
::formLink(
1347 CRM_Core_Action
::mask([CRM_Core_Permission
::EDIT
]),
1349 'id' => $resultDAO->id
,
1350 'contribution_id' => $contributionId,
1354 'Payment.edit.action',
1361 'id' => $resultDAO->id
,
1362 'total_amount' => $resultDAO->total_amount
,
1363 'financial_type' => $resultDAO->financial_account
,
1364 'payment_instrument' => $paidByLabel,
1365 'receive_date' => $resultDAO->trxn_date
,
1366 'trxn_id' => $resultDAO->trxn_id
,
1367 'status' => $statuses[$resultDAO->status_id
],
1368 'currency' => $resultDAO->currency
,
1369 'action' => $paymentEditLink,
1371 if ($paidByName == 'Check') {
1372 $val['check_number'] = $resultDAO->check_number
;
1382 public function addSelectWhereClause() {
1383 $whereClauses = parent
::addSelectWhereClause();
1384 if ($whereClauses !== []) {
1385 // In this case permisssions have been applied & we assume the
1386 // financialaclreport is applying these
1387 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
1388 return $whereClauses;
1391 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1392 return $whereClauses;
1394 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
1395 if (empty($types)) {
1396 $whereClauses['financial_type_id'] = 'IN (0)';
1399 $whereClauses['financial_type_id'] = [
1400 'IN (' . implode(',', array_keys($types)) . ')',
1403 return $whereClauses;
1407 * @param null $status
1408 * @param null $startDate
1409 * @param null $endDate
1411 * @return array|null
1413 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1417 $where[] = 'contribution_status_id = 1';
1421 $where[] = 'contribution_status_id = 3';
1426 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
1429 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
1431 $financialTypeACLJoin = '';
1432 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1433 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1434 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
1435 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1436 if ($financialTypes) {
1437 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1438 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1441 $where[] = "c.financial_type_id IN (0)";
1445 $whereCond = implode(' AND ', $where);
1448 SELECT sum( total_amount ) as total_amount,
1449 count( c.id ) as total_count,
1451 FROM civicrm_contribution c
1452 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1453 $financialTypeACLJoin
1455 AND ( is_test = 0 OR is_test IS NULL )
1456 AND contact.is_deleted = 0
1460 $dao = CRM_Core_DAO
::executeQuery($query);
1463 while ($dao->fetch()) {
1464 $count +
= $dao->total_count
;
1465 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
1469 'amount' => implode(', ', $amount),
1477 * Delete the indirect records associated with this contribution first.
1481 * @return mixed|null
1482 * $results no of deleted Contribution on success, false otherwise
1484 public static function deleteContribution($id) {
1485 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
1487 $transaction = new CRM_Core_Transaction();
1490 //delete activity record
1492 'source_record_id' => $id,
1493 // activity type id for contribution
1494 'activity_type_id' => 6,
1497 CRM_Activity_BAO_Activity
::deleteActivity($params);
1499 //delete billing address if exists for this contribution.
1500 self
::deleteAddress($id);
1502 //update pledge and pledge payment, CRM-3961
1503 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1505 // remove entry from civicrm_price_set_entity, CRM-5095
1506 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1507 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1509 // cleanup line items.
1510 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1512 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1513 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1515 if ($participantId) {
1516 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1519 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1523 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1524 $noteId = key($note);
1526 CRM_Core_BAO_Note
::del($noteId, FALSE);
1529 $dao = new CRM_Contribute_DAO_Contribution();
1532 $results = $dao->delete();
1534 $transaction->commit();
1536 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1538 // delete the recently created Contribution
1539 $contributionRecent = [
1541 'type' => 'Contribution',
1543 CRM_Utils_Recent
::del($contributionRecent);
1549 * React to a financial transaction (payment) failure.
1551 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1552 * payments is important for forensic and outreach reasons.
1554 * @param int $contributionID
1555 * @param int $contactID
1556 * @param string $message
1558 * @throws \CiviCRM_API3_Exception
1560 public static function failPayment($contributionID, $contactID, $message) {
1561 civicrm_api3('activity', 'create', [
1562 'activity_type_id' => 'Failed Payment',
1563 'details' => $message,
1564 'subject' => ts('Payment failed at payment processor'),
1565 'source_record_id' => $contributionID,
1566 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() : $contactID,
1569 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1570 civicrm_api3('contribution', 'create', [
1571 'id' => $contributionID,
1572 'contribution_status_id' => 'Failed',
1577 * Check if there is a contribution with the same trxn_id or invoice_id.
1579 * @param array $input
1580 * An assoc array of name/value pairs.
1581 * @param array $duplicates
1582 * (reference) store ids of duplicate contribs.
1586 * true if duplicate, false otherwise
1588 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1590 $id = $input['id'] ??
NULL;
1592 $trxn_id = $input['trxn_id'] ??
NULL;
1593 $invoice_id = $input['invoice_id'] ??
NULL;
1599 $clause[] = "trxn_id = %1";
1600 $input[1] = [$trxn_id, 'String'];
1604 $clause[] = "invoice_id = %2";
1605 $input[2] = [$invoice_id, 'String'];
1608 if (empty($clause)) {
1612 $clause = implode(' OR ', $clause);
1614 $clause = "( $clause ) AND id != %3";
1615 $input[3] = [$id, 'Integer'];
1618 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1619 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1621 while ($dao->fetch()) {
1622 $duplicates[] = $dao->id
;
1629 * Takes an associative array and creates a contribution_product object.
1631 * the function extract all the params it needs to initialize the create a
1632 * contribution_product object. the params array could contain additional unused name/value
1635 * @param array $params
1636 * (reference) an assoc array of name/value pairs.
1638 * @return CRM_Contribute_DAO_ContributionProduct
1640 public static function addPremium(&$params) {
1641 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1642 $contributionProduct->copyValues($params);
1643 return $contributionProduct->save();
1647 * Get list of contribution fields for profile.
1648 * For now we only allow custom contribution fields to be in
1651 * @param bool $addExtraFields
1652 * True if special fields needs to be added.
1655 * the list of contribution fields
1657 public static function getContributionFields($addExtraFields = TRUE) {
1658 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1659 // @todo remove this - this line was added because payment_instrument_id was not
1660 // set to exportable - but now it is.
1661 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1663 if ($addExtraFields) {
1664 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1667 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1669 foreach ($contributionFields as $key => $var) {
1670 if ($key == 'contribution_contact_id') {
1673 elseif ($key == 'contribution_campaign_id') {
1674 $var['title'] = ts('Campaign');
1676 $fields[$key] = $var;
1679 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1684 * Add extra fields specific to contribution.
1686 public static function getSpecialContributionFields() {
1688 'contribution_soft_credit_name' => [
1689 'name' => 'contribution_soft_credit_name',
1690 'title' => ts('Soft Credit Name'),
1691 'headerPattern' => '/^soft_credit_name$/i',
1692 'where' => 'civicrm_contact_d.display_name',
1694 'contribution_soft_credit_email' => [
1695 'name' => 'contribution_soft_credit_email',
1696 'title' => ts('Soft Credit Email'),
1697 'headerPattern' => '/^soft_credit_email$/i',
1698 'where' => 'soft_email.email',
1700 'contribution_soft_credit_phone' => [
1701 'name' => 'contribution_soft_credit_phone',
1702 'title' => ts('Soft Credit Phone'),
1703 'headerPattern' => '/^soft_credit_phone$/i',
1704 'where' => 'soft_phone.phone',
1706 'contribution_soft_credit_contact_id' => [
1707 'name' => 'contribution_soft_credit_contact_id',
1708 'title' => ts('Soft Credit Contact ID'),
1709 'headerPattern' => '/^soft_credit_contact_id$/i',
1710 'where' => 'civicrm_contribution_soft.contact_id',
1712 'contribution_pcp_title' => [
1713 'name' => 'contribution_pcp_title',
1714 'title' => ts('Personal Campaign Page Title'),
1715 'headerPattern' => '/^contribution_pcp_title$/i',
1716 'where' => 'contribution_pcp.title',
1720 return $extraFields;
1724 * @param int $pageID
1728 public static function getCurrentandGoalAmount($pageID) {
1730 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1731 FROM civicrm_contribution_page p,
1732 civicrm_contribution c
1733 WHERE p.id = c.contribution_page_id
1735 AND c.cancel_date is null
1739 $config = CRM_Core_Config
::singleton();
1740 $params = [1 => [$pageID, 'Integer']];
1741 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1743 if ($dao->fetch()) {
1744 return [$dao->goal
, $dao->total
];
1747 return [NULL, NULL];
1752 * Get list of contributions which credit the passed in contact ID.
1754 * The returned array provides details about the original contribution & donor.
1756 * @param int $honorId
1757 * In Honor of Contact ID.
1760 * list of contribution fields
1761 * @todo - this is a confusing function called from one place. It has a test. It would be
1762 * nice to deprecate it.
1765 public static function getHonorContacts($honorId) {
1767 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1768 $honorDAO->contact_id
= $honorId;
1771 $type = CRM_Contribute_PseudoConstant
::financialType();
1773 while ($honorDAO->fetch()) {
1774 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1775 $contributionDAO->id
= $honorDAO->contribution_id
;
1777 if ($contributionDAO->find(TRUE)) {
1778 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1779 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1780 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1781 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1782 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1783 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1784 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1785 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1786 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
, 'label');
1794 * Get the sort name of a contact for a particular contribution.
1797 * Id of the contribution.
1799 * @return null|string
1800 * sort name of the contact if found
1802 public static function sortName($id) {
1803 $id = CRM_Utils_Type
::escape($id, 'Integer');
1806 SELECT civicrm_contact.sort_name
1807 FROM civicrm_contribution, civicrm_contact
1808 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1809 AND civicrm_contribution.id = {$id}
1811 return CRM_Core_DAO
::singleValueQuery($query);
1815 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1817 * @param int|array $contactIDs
1821 public static function annual($contactIDs) {
1822 if (!is_array($contactIDs)) {
1823 // In practice I can't fine any evidence that this function is ever called with
1824 // anything other than a single contact id, but left like this due to .... fear.
1825 $contactIDs = explode(',', $contactIDs);
1828 $query = self
::getAnnualQuery($contactIDs);
1829 $dao = CRM_Core_DAO
::executeQuery($query);
1831 $amount = $average = [];
1832 while ($dao->fetch()) {
1833 if ($dao->count
> 0 && $dao->amount
> 0) {
1834 $count +
= $dao->count
;
1835 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1836 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1842 implode(', ', $amount),
1843 implode(', ', $average),
1850 * Check if there is a contribution with the params passed in.
1852 * Used for trxn_id,invoice_id and contribution_id
1854 * @param array $params
1855 * An assoc array of name/value pairs.
1858 * contribution id if success else NULL
1860 public static function checkDuplicateIds($params) {
1861 $dao = new CRM_Contribute_DAO_Contribution();
1865 foreach ($params as $k => $v) {
1867 $clause[] = "$k = '$v'";
1870 $clause = implode(' AND ', $clause);
1871 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1872 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1874 while ($dao->fetch()) {
1882 * Get the contribution details for component export.
1884 * @param int $exportMode
1886 * @param array $componentIds
1892 public static function getContributionDetails($exportMode, $componentIds) {
1893 $paymentDetails = [];
1894 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1896 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1897 $componentSelect = " civicrm_participant_payment.participant_id id";
1898 $additionalClause = "
1899 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1900 AND civicrm_participant_payment.participant_id {$componentClause} )
1903 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1904 $componentSelect = " civicrm_membership_payment.membership_id id";
1905 $additionalClause = "
1906 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1907 AND civicrm_membership_payment.membership_id {$componentClause} )
1910 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1911 $componentSelect = " civicrm_pledge_payment.id id";
1912 $additionalClause = "
1913 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1914 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1918 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1919 trxn_id, {$componentSelect}
1920 FROM civicrm_contribution
1921 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1922 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1923 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1924 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1925 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1926 AND option_group_contribution_status.id = contribution_status.option_group_id )
1930 $dao = CRM_Core_DAO
::executeQuery($query);
1932 while ($dao->fetch()) {
1933 $paymentDetails[$dao->id
] = [
1934 'total_amount' => $dao->total_amount
,
1935 'contribution_status' => $dao->status
,
1936 'receive_date' => $dao->receive_date
,
1937 'pay_instru' => $dao->payment_instrument
,
1938 'trxn_id' => $dao->trxn_id
,
1942 return $paymentDetails;
1946 * Create address associated with contribution record.
1948 * As long as there is one or more billing field in the parameters we will create the address.
1950 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1953 * @param array $params
1954 * @param int $billingLocationTypeID
1959 public static function createAddress($params, $billingLocationTypeID) {
1960 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1961 if ($hasBillingField) {
1962 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1963 return $address->id
;
1970 * Delete billing address record related contribution.
1972 * @param int $contributionId
1973 * @param int $contactId
1975 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1977 $contactJoin = NULL;
1979 if ($contributionId) {
1980 $clauses[] = "cc.id = {$contributionId}";
1984 $clauses[] = "cco.id = {$contactId}";
1985 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1988 if (empty($clauses)) {
1989 CRM_Core_Error
::fatal();
1992 $condition = implode(' OR ', $clauses);
1996 FROM civicrm_address ca
1997 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
2001 $dao = CRM_Core_DAO
::executeQuery($query);
2003 while ($dao->fetch()) {
2004 $params = ['id' => $dao->id
];
2005 CRM_Core_BAO_Block
::blockDelete('Address', $params);
2010 * This function check online pending contribution associated w/
2011 * Online Event Registration or Online Membership signup.
2013 * @param int $componentId
2014 * Participant/membership id.
2015 * @param string $componentName
2019 * pending contribution id.
2021 public static function checkOnlinePendingContribution($componentId, $componentName) {
2022 $contributionId = NULL;
2023 if (!$componentId ||
2024 !in_array($componentName, ['Event', 'Membership'])
2026 return $contributionId;
2029 if ($componentName == 'Event') {
2030 $idName = 'participant_id';
2031 $componentTable = 'civicrm_participant';
2032 $paymentTable = 'civicrm_participant_payment';
2033 $source = ts('Online Event Registration');
2036 if ($componentName == 'Membership') {
2037 $idName = 'membership_id';
2038 $componentTable = 'civicrm_membership';
2039 $paymentTable = 'civicrm_membership_payment';
2040 $source = ts('Online Contribution');
2043 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
2046 SELECT component.id as {$idName},
2047 componentPayment.contribution_id as contribution_id,
2048 contribution.source source,
2049 contribution.contribution_status_id as contribution_status_id,
2050 contribution.is_pay_later as is_pay_later
2051 FROM $componentTable component
2052 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
2053 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
2054 WHERE component.id = {$componentId}";
2056 $dao = CRM_Core_DAO
::executeQuery($query);
2058 while ($dao->fetch()) {
2059 if ($dao->contribution_id
&&
2060 $dao->is_pay_later
&&
2061 $dao->contribution_status_id
== $pendingStatusId &&
2062 strpos($dao->source
, $source) !== FALSE
2064 $contributionId = $dao->contribution_id
;
2068 return $contributionId;
2072 * Update contribution as well as related objects.
2074 * This function by-passes hooks - to address this - don't use this function.
2076 * @param array $params
2077 * @param bool $processContributionObject
2081 * @throws CRM_Core_Exception
2082 * @throws \CiviCRM_API3_Exception
2085 * Use api contribute.completetransaction
2086 * For failures use failPayment (preferably exposing by api in the process).
2089 public static function transitionComponents($params, $processContributionObject = FALSE) {
2090 // get minimum required values.
2091 $contactId = $params['contact_id'] ??
NULL;
2092 $componentId = $params['component_id'] ??
NULL;
2093 $componentName = $params['componentName'] ??
NULL;
2094 $contributionId = $params['contribution_id'] ??
NULL;
2095 $contributionStatusId = $params['contribution_status_id'] ??
NULL;
2097 // if we already processed contribution object pass previous status id.
2098 $previousContriStatusId = $params['previous_contribution_status_id'] ??
NULL;
2102 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2104 // we process only ( Completed, Cancelled, or Failed ) contributions.
2105 if (!$contributionId ||
2106 !in_array($contributionStatusId, [
2107 array_search('Completed', $contributionStatuses),
2108 array_search('Cancelled', $contributionStatuses),
2109 array_search('Failed', $contributionStatuses),
2112 return $updateResult;
2115 if (!$componentName ||
!$componentId) {
2116 // get the related component details.
2117 $componentDetails = self
::getComponentDetails($contributionId);
2120 $componentDetails['contact_id'] = $contactId;
2121 $componentDetails['component'] = $componentName;
2123 if ($componentName == 'event') {
2124 $componentDetails['participant'] = $componentId;
2127 $componentDetails['membership'] = $componentId;
2131 if (!empty($componentDetails['contact_id'])) {
2132 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2138 // do check for required ids.
2139 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
2140 return $updateResult;
2143 //now we are ready w/ required ids, start processing.
2145 $baseIPN = new CRM_Core_Payment_BaseIPN();
2147 $input = $ids = $objects = [];
2149 $input['component'] = $componentDetails['component'] ??
NULL;
2150 $ids['contribution'] = $contributionId;
2151 $ids['contact'] = $componentDetails['contact_id'] ??
NULL;
2152 $ids['membership'] = $componentDetails['membership'] ??
NULL;
2153 $ids['participant'] = $componentDetails['participant'] ??
NULL;
2154 $ids['event'] = $componentDetails['event'] ??
NULL;
2155 $ids['pledge_payment'] = $componentDetails['pledge_payment'] ??
NULL;
2156 $ids['contributionRecur'] = NULL;
2157 $ids['contributionPage'] = NULL;
2159 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
2160 CRM_Core_Error
::fatal();
2163 $memberships = &$objects['membership'];
2164 $participant = &$objects['participant'];
2165 $pledgePayment = &$objects['pledge_payment'];
2166 $contribution = &$objects['contribution'];
2167 $pledgeID = $oldStatus = NULL;
2168 $pledgePaymentIDs = [];
2169 if ($pledgePayment) {
2170 foreach ($pledgePayment as $key => $object) {
2171 $pledgePaymentIDs[] = $object->id
;
2173 $pledgeID = $pledgePayment[0]->pledge_id
;
2176 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
2179 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
2180 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
2185 // we might want to process contribution object.
2186 $processContribution = FALSE;
2187 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
2188 // Call interim cancel function - with a goal to cleaning up the signature on it and switching to a tested api Contribution.cancel function.
2189 list($updateResult, $processContribution) = self
::cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
2191 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
2192 if (is_array($memberships)) {
2193 foreach ($memberships as $membership) {
2195 //Update Membership status if there is no other completed contribution associated with the membership.
2196 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
2197 foreach ($relatedContributions as $contriId) {
2198 if ($contriId == $contributionId) {
2201 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
2202 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
2206 if ($membership && $update) {
2207 $membership->status_id
= array_search('Expired', $membershipStatuses);
2208 $membership->is_override
= TRUE;
2209 $membership->status_override_end_date
= 'null';
2210 $membership->save();
2212 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2213 if ($processContributionObject) {
2214 $processContribution = TRUE;
2220 $updatedStatusId = array_search('Cancelled', $participantStatuses);
2221 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2223 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2224 if ($processContributionObject) {
2225 $processContribution = TRUE;
2229 if ($pledgePayment) {
2230 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2232 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2233 if ($processContributionObject) {
2234 $processContribution = TRUE;
2238 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
2240 // only pending contribution related object processed.
2241 if ($previousContriStatusId &&
2242 !in_array($contributionStatuses[$previousContriStatusId], [
2247 // this is case when we already processed contribution object.
2248 return $updateResult;
2250 elseif (!$previousContriStatusId &&
2251 !in_array($contributionStatuses[$contribution->contribution_status_id
], [
2256 // this is case when we are going to process contribution object later.
2257 return $updateResult;
2260 if (is_array($memberships)) {
2261 foreach ($memberships as $membership) {
2266 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
2267 $membership->membership_type_id
,
2268 $membership->is_test
, $membership->id
2271 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2272 // this picks up membership type changes during renewals
2274 SELECT membership_type_id
2275 FROM civicrm_membership_log
2276 WHERE membership_id=$membership->id
2279 $dao = new CRM_Core_DAO();
2281 if ($dao->fetch()) {
2282 if (!empty($dao->membership_type_id
)) {
2283 $membership->membership_type_id
= $dao->membership_type_id
;
2284 $membership->save();
2287 // else fall back to using current membership type
2288 // Figure out number of terms
2290 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
2291 foreach ($lineitems as $lineitem) {
2292 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
2293 $numterms = $lineitem['membership_num_terms'] ??
NULL;
2295 // in case membership_num_terms comes through as null or zero
2296 $numterms = $numterms >= 1 ?
$numterms : 1;
2301 // CRM-15735-to update the membership status as per the contribution receive date
2303 $oldStatus = $membership->status_id
;
2304 if (!empty($params['receive_date'])) {
2305 $joinDate = $params['receive_date'];
2306 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
2307 $membership->end_date
,
2308 $membership->join_date
,
2309 $params['receive_date'],
2311 $membership->membership_type_id
,
2314 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
2315 $membership->save();
2318 if ($currentMembership) {
2319 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2320 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
2321 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2324 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
2327 //get the status for membership.
2328 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
2330 $dates['join_date'],
2333 $membership->membership_type_id
,
2337 $formattedParams = [
2338 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
2339 array_search('Current', $membershipStatuses)
2341 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
2342 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
2343 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
2346 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
2348 $membership->copyValues($formattedParams);
2349 $membership->save();
2351 //updating the membership log
2352 $membershipLog = [];
2353 $membershipLog = $formattedParams;
2354 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
2355 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
2357 $membershipLog['start_date'] = $logStartDate;
2358 $membershipLog['membership_id'] = $membership->id
;
2359 $membershipLog['modified_id'] = $membership->contact_id
;
2360 $membershipLog['modified_date'] = date('Ymd');
2361 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
2363 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2365 //update related Memberships.
2366 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2368 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2369 $scheduledActivityID = CRM_Utils_Array
::value('id',
2370 civicrm_api3('Activity', 'Get',
2372 'source_record_id' => $membership->id
,
2373 'activity_type_id' => $activityType,
2374 'status_id' => 'Scheduled',
2377 'sort' => 'id DESC',
2382 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2383 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2384 if ($scheduledActivityID) {
2385 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, ['id' => $scheduledActivityID]);
2390 // track membership status change if any
2391 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
2392 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2393 CRM_Activity_BAO_Activity
::addActivity($membership,
2394 'Change Membership Status',
2397 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2398 'source_contact_id' => $membershipLog['modified_id'],
2399 'priority_id' => 'Normal',
2404 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2405 if ($processContributionObject) {
2406 $processContribution = TRUE;
2409 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2415 $updatedStatusId = array_search('Registered', $participantStatuses);
2416 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2418 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2419 if ($processContributionObject) {
2420 $processContribution = TRUE;
2424 if ($pledgePayment) {
2425 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2427 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2428 if ($processContributionObject) {
2429 $processContribution = TRUE;
2434 // process contribution object.
2435 if ($processContribution) {
2436 $contributionParams = [];
2443 'payment_instrument_id',
2446 'financial_type_id',
2447 'contribution_status_id',
2448 'non_deductible_amount',
2452 foreach ($fields as $field) {
2453 if (empty($params[$field])) {
2456 $contributionParams[$field] = $params[$field];
2459 $contributionParams['id'] = $contributionId;
2460 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams);
2463 return $updateResult;
2467 * Returns all contribution related object ids.
2469 * @param $contributionId
2473 public static function getComponentDetails($contributionId) {
2474 $componentDetails = $pledgePayment = [];
2475 if (!$contributionId) {
2476 return $componentDetails;
2480 SELECT c.id as contribution_id,
2481 c.contact_id as contact_id,
2482 c.contribution_recur_id,
2483 mp.membership_id as membership_id,
2484 m.membership_type_id as membership_type_id,
2485 pp.participant_id as participant_id,
2486 p.event_id as event_id,
2487 pgp.id as pledge_payment_id
2488 FROM civicrm_contribution c
2489 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2490 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2491 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2492 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2493 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2494 WHERE c.id = $contributionId";
2496 $dao = CRM_Core_DAO
::executeQuery($query);
2497 $componentDetails = [];
2499 while ($dao->fetch()) {
2500 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2501 $componentDetails['contact_id'] = $dao->contact_id
;
2502 if ($dao->event_id
) {
2503 $componentDetails['event'] = $dao->event_id
;
2505 if ($dao->participant_id
) {
2506 $componentDetails['participant'] = $dao->participant_id
;
2508 if ($dao->membership_id
) {
2509 if (!isset($componentDetails['membership'])) {
2510 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2512 $componentDetails['membership'][] = $dao->membership_id
;
2513 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2515 if ($dao->pledge_payment_id
) {
2516 $pledgePayment[] = $dao->pledge_payment_id
;
2518 if ($dao->contribution_recur_id
) {
2519 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2523 if ($pledgePayment) {
2524 $componentDetails['pledge_payment'] = $pledgePayment;
2527 return $componentDetails;
2531 * @param int $contactId
2532 * @param bool $includeSoftCredit
2534 * @return null|string
2536 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2540 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2541 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2542 $liWhere = " AND i.financial_type_id IN (0)";
2543 if (!empty($financialTypes)) {
2544 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2545 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2547 $contactContributionsSQL = "
2548 SELECT contribution.id AS id
2549 FROM civicrm_contribution contribution
2550 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2551 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2555 $contactSoftCreditContributionsSQL = "
2556 SELECT contribution.id
2557 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2558 ON ( contribution.id = softContribution.contribution_id )
2559 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2560 $query = "SELECT count( x.id ) count FROM ( ";
2561 $query .= $contactContributionsSQL;
2563 if ($includeSoftCredit) {
2564 $query .= " UNION ";
2565 $query .= $contactSoftCreditContributionsSQL;
2570 return CRM_Core_DAO
::singleValueQuery($query);
2574 * Repeat a transaction as part of a recurring series.
2577 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2578 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2579 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2580 * and associated entities.
2581 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2582 * which updates the various entities and sends appropriate emails.
2584 * Gaps in the above (@todo)
2585 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2586 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2587 * 3) Repeat transaction duplicates rather than calls Order.create
2588 * 4) Use of payment.create still limited - completetransaction is more common.
2589 * 5) the template transaction is tricky - historically we used the first contribution
2590 * linked to a recurring contribution. More recently that was changed to be the most recent.
2591 * Ideally it would be an actual template - not a contribution used as a template which
2592 * would give more appropriate flexibility. Note line_items have an entity so that table
2593 * could be used for the line item template - the difficulty is the custom fields...
2594 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2595 * to load the membership(s) referred to via line items in the template transactions. Any other
2596 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2597 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2598 * - membership_payment record
2599 * - civicrm_membership.contribution_recur_id
2601 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2602 * of historical processors since this has been handled 'forever' - specifically for paypal.
2603 * albeit by an even nastier mechanism than the current input override.
2604 * The count is out on how correct related entities wind up in this case.
2606 * @param CRM_Contribute_BAO_Contribution $contribution
2607 * @param array $input
2608 * @param array $contributionParams
2609 * @param int $paymentProcessorID
2612 * @throws CiviCRM_API3_Exception
2614 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
2615 if (!empty($contribution->id
)) {
2618 if (empty($contribution->id
)) {
2619 // Unclear why this would only be set for repeats.
2620 if (!empty($input['amount'])) {
2621 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2624 if (!empty($contributionParams['contribution_recur_id'])) {
2625 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2626 'id' => $contributionParams['contribution_recur_id'],
2628 if (!empty($recurringContribution['campaign_id'])) {
2629 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2630 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2632 if (!empty($recurringContribution['financial_type_id'])) {
2633 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2634 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2637 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2638 $contributionParams['contribution_recur_id'],
2639 array_intersect_key($contributionParams, [
2640 'total_amount' => TRUE,
2641 'financial_type_id' => TRUE,
2644 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2646 $contributionParams['status_id'] = 'Pending';
2647 if (isset($contributionParams['financial_type_id'])) {
2648 // Give precedence to passed in type.
2649 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2652 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2654 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2655 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2657 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2658 //do not create CC or BCC emails or profile notifications.
2659 //The if is just to be safe. Not sure if we can ever arrive with this unset
2660 // but per CRM-19478 it seems it can be 'null'
2661 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2662 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2664 if (!empty($contribution->tax_amount
)) {
2665 $contributionParams['tax_amount'] = $contribution->tax_amount
;
2668 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2669 $contribution->id
= $createContribution['id'];
2670 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2671 self
::handleMembershipIDOverride($contribution->id
, $input);
2677 * Get individual id for onbehalf contribution.
2679 * @param int $contributionId
2681 * @param int $contributorId
2685 * containing organization id and individual id
2687 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2691 if (!$contributionId) {
2695 // fetch contributor id if null
2696 if (!$contributorId) {
2697 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2698 $contributionId, 'contact_id'
2702 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2703 $activityTypeId = array_search('Contribution', $activityTypeIds);
2705 if ($activityTypeId && $contributorId) {
2707 SELECT civicrm_activity_contact.contact_id
2708 FROM civicrm_activity_contact
2709 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2710 WHERE civicrm_activity.activity_type_id = %1
2711 AND civicrm_activity.source_record_id = %2
2712 AND civicrm_activity_contact.record_type_id = %3
2715 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2716 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2719 1 => [$activityTypeId, 'Integer'],
2720 2 => [$contributionId, 'Integer'],
2721 3 => [$sourceID, 'Integer'],
2724 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2726 // for on behalf contribution source is individual and contributor is organization
2727 if ($sourceContactId && $sourceContactId != $contributorId) {
2728 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2729 // get rel type id for employee of relation
2730 foreach ($relationshipTypeIds as $id => $typeVals) {
2731 if ($typeVals['name_a_b'] == 'Employee of') {
2732 $relationshipTypeId = $id;
2737 $rel = new CRM_Contact_DAO_Relationship();
2738 $rel->relationship_type_id
= $relationshipTypeId;
2739 $rel->contact_id_a
= $sourceContactId;
2740 $rel->contact_id_b
= $contributorId;
2741 if ($rel->find(TRUE)) {
2742 $ids['individual_id'] = $rel->contact_id_a
;
2743 $ids['organization_id'] = $rel->contact_id_b
;
2754 public static function getContributionDates() {
2755 $config = CRM_Core_Config
::singleton();
2756 $currentMonth = date('m');
2757 $currentDay = date('d');
2758 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2759 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2760 (int ) $config->fiscalYearStart
['d'] > $currentDay
2763 $year = date('Y') - 1;
2768 $year = ['Y' => $year];
2769 $yearDate = $config->fiscalYearStart
;
2770 $yearDate = array_merge($year, $yearDate);
2771 $yearDate = CRM_Utils_Date
::format($yearDate);
2773 $monthDate = date('Ym') . '01';
2779 'yearDate' => $yearDate,
2780 'monthDate' => $monthDate,
2785 * Load objects relations to contribution object.
2786 * Objects are stored in the $_relatedObjects property
2787 * In the first instance we are just moving functionality from BASEIpn -
2789 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2791 * Note that the unit test for the BaseIPN class tests this function
2793 * @param array $input
2794 * Input as delivered from Payment Processor.
2796 * Ids as Loaded by Payment Processor.
2797 * @param bool $loadAll
2798 * Load all related objects - even where id not passed in? (allows API to call this).
2803 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2804 // @todo deprecate this function - the steps should be
2805 // 1) add additional functions like 'getRelatedMemberships'
2806 // 2) switch all calls that refer to ->_relatedObjects to
2807 // using the helper functions
2808 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2809 // 4) make ->_relatedObjects protected
2810 // 5) hone up the individual functions to not use rely on this having been called
2811 // 6) deprecate like mad
2813 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2814 if (empty($ids['contact']) && isset($this->contact_id
)) {
2815 $ids['contact'] = $this->contact_id
;
2818 if (empty($this->_component
)) {
2819 if (!empty($ids['event'])) {
2820 $this->_component
= 'event';
2823 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2827 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2828 // refactoring than anything else, and has unit test coverage.
2829 if (empty($this->financial_type_id
)) {
2833 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2838 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2839 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2840 $this->contribution_page_id
,
2843 if ($paymentProcessorID) {
2844 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2848 $ids['contributionType'] = $this->financial_type_id
;
2849 $ids['financialType'] = $this->financial_type_id
;
2850 if ($this->contribution_page_id
) {
2851 $ids['contributionPage'] = $this->contribution_page_id
;
2854 $this->loadRelatedEntitiesByID($ids);
2856 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2857 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2860 if (!empty($ids['pledge_payment'])) {
2861 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2862 if (empty($paymentID)) {
2865 $payment = new CRM_Pledge_BAO_PledgePayment();
2866 $payment->id
= $paymentID;
2867 if (!$payment->find(TRUE)) {
2868 throw new Exception("Could not find pledge payment record: " . $paymentID);
2870 $this->_relatedObjects
['pledge_payment'][] = $payment;
2874 // These are probably no longer accessed from anywhere
2875 // @todo remove this line, after ensuring not used.
2876 $ids = $this->loadRelatedMembershipObjects($ids);
2878 if ($this->_component
!= 'contribute') {
2879 // we are in event mode
2880 // make sure event exists and is valid
2881 $event = new CRM_Event_BAO_Event();
2882 $event->id
= $ids['event'];
2883 if ($ids['event'] &&
2886 throw new Exception("Could not find event: " . $ids['event']);
2889 $this->_relatedObjects
['event'] = &$event;
2891 $participant = new CRM_Event_BAO_Participant();
2892 $participant->id
= $ids['participant'];
2893 if ($ids['participant'] &&
2894 !$participant->find(TRUE)
2896 throw new Exception("Could not find participant: " . $ids['participant']);
2898 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2900 $this->_relatedObjects
['participant'] = &$participant;
2902 // get the payment processor id from event - this is inaccurate see CRM-16923
2903 // in future we should look at throwing an exception here rather than an dubious guess.
2904 if (!$paymentProcessorID) {
2905 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2906 if ($paymentProcessorID) {
2907 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2912 if ($paymentProcessorID) {
2913 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2914 $this->is_test ?
'test' : 'live'
2916 $ids['paymentProcessor'] = $paymentProcessorID;
2917 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2920 // Add contribution id to $ids. CRM-20401
2921 $ids['contribution'] = $this->id
;
2926 * Create array of message information - ie. return html version, txt version, to field
2928 * @param array $input
2929 * Incoming information.
2930 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2931 * just check presence of recur object but maintaining legacy approach
2934 * IDs of related objects.
2935 * @param array $values
2936 * Any values that may have already been compiled by calling process.
2937 * This is augmented by values 'gathered' by gatherMessageValues
2938 * @param bool $returnMessageText
2939 * Distinguishes between whether to send message or return.
2940 * message text. We are working towards this function ALWAYS returning message text & calling
2941 * function doing emails / pdfs with it
2947 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2948 $this->loadRelatedObjects($input, $ids);
2950 if (empty($this->_component
)) {
2951 $this->_component
= $input['component'] ??
NULL;
2954 //not really sure what params might be passed in but lets merge em into values
2955 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2956 $values['is_email_receipt'] = $this->isEmailReceipt($input, $values);
2957 if (!empty($input['receipt_date'])) {
2958 $values['receipt_date'] = $input['receipt_date'];
2961 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2962 //what does recur 'mean here - to do with payment processor return functionality but
2963 // what is the importance
2964 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2965 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2967 $entityID = $entity = NULL;
2968 if (isset($ids['contribution'])) {
2969 $entity = 'contribution';
2970 $entityID = $ids['contribution'];
2972 if (!empty($ids['membership'])) {
2973 //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
2974 // 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
2975 // line having loaded an array
2976 $ids['membership'] = (array) $ids['membership'];
2977 $entity = 'membership';
2978 $entityID = $ids['membership'][0];
2981 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2982 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2983 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2985 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2986 //direct mode showing billing block, so use directIPN for temporary
2987 $template->assign('contributeMode', 'directIPN');
2990 // todo remove strtolower - check consistency
2991 if (strtolower($this->_component
) == 'event') {
2992 $eventParams = ['id' => $this->_relatedObjects
['participant']->event_id
];
2993 $values['event'] = [];
2995 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2997 //get location details
2999 'entity_id' => $this->_relatedObjects
['participant']->event_id
,
3000 'entity_table' => 'civicrm_event',
3002 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
3005 'entity_table' => 'civicrm_event',
3006 'entity_id' => $ids['event'],
3007 'module' => 'CiviEvent',
3010 list($custom_pre_id,
3012 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
3014 $values['custom_pre_id'] = $custom_pre_id;
3015 $values['custom_post_id'] = $custom_post_ids;
3016 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
3017 //and cases involving status updation through ipn
3018 // whatever that means!
3019 // total_amount appears to be the preferred input param & it is unclear why we support amount here
3020 // perhaps we should throw an e-notice if amount is set & force total_amount?
3021 if (!empty($input['amount'])) {
3022 $values['totalAmount'] = $input['amount'];
3024 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
3025 if ($values['event']['is_email_confirm']) {
3026 $values['is_email_receipt'] = 1;
3029 if (!empty($ids['contribution'])) {
3030 $values['contributionId'] = $ids['contribution'];
3033 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
3034 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
3038 $values['contribution_id'] = $this->id
;
3039 if (!empty($ids['related_contact'])) {
3040 $values['related_contact'] = $ids['related_contact'];
3041 if (isset($ids['onbehalf_dupe_alert'])) {
3042 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
3045 'contact_id' => $ids['contact'],
3046 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
3047 'Home', 'id', 'name'
3050 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
3051 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
3054 if ($this->is_test
) {
3057 if (!empty($this->_relatedObjects
['membership'])) {
3058 foreach ($this->_relatedObjects
['membership'] as $membership) {
3059 if ($membership->id
) {
3060 $values['membership_id'] = $membership->id
;
3061 $values['isMembership'] = TRUE;
3062 $values['membership_assign'] = TRUE;
3064 // need to set the membership values here
3065 $template->assign('membership_name',
3066 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
3068 $template->assign('mem_start_date', $membership->start_date
);
3069 $template->assign('mem_join_date', $membership->join_date
);
3070 $template->assign('mem_end_date', $membership->end_date
);
3071 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
3072 $template->assign('mem_status', $membership_status);
3073 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
3074 $values['is_pay_later'] = 1;
3076 // Pass amount to floatval as string '0.00' is considered a
3077 // valid amount and includes Fee section in the mail.
3078 if (isset($values['amount'])) {
3079 $values['amount'] = floatval($values['amount']);
3082 if (!empty($this->contribution_recur_id
) && $paymentObject) {
3083 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
3084 $template->assign('cancelSubscriptionUrl', $url);
3085 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
3086 $template->assign('updateSubscriptionBillingUrl', $url);
3087 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
3088 $template->assign('updateSubscriptionUrl', $url);
3091 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3094 // otherwise if its about sending emails, continue sending without return, as we
3095 // don't want to exit the loop.
3100 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3106 * Gather values for contribution mail - this function has been created
3107 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
3108 * Values related to the contribution in question are gathered
3110 * @param array $input
3111 * Input into function (probably from payment processor).
3112 * @param array $values
3114 * The set of ids related to the input.
3117 * @throws \CRM_Core_Exception
3119 public function _gatherMessageValues($input, &$values, $ids = []) {
3120 // set display address of contributor
3121 $values['billingName'] = '';
3122 if ($this->address_id
) {
3123 $addressDetails = CRM_Core_BAO_Address
::getValues(['id' => $this->address_id
], FALSE, 'id');
3124 $addressDetails = reset($addressDetails);
3125 $values['billingName'] = $addressDetails['name'] ??
'';
3127 // Else we assign the billing address of the contribution contact.
3129 $addressDetails = (array) CRM_Core_BAO_Address
::getValues(['contact_id' => $this->contact_id
, 'is_billing' => 1]);
3130 $addressDetails = reset($addressDetails);
3132 $values['address'] = $addressDetails['display'] ??
'';
3134 if ($this->_component
=== 'contribute') {
3135 //get soft contributions
3136 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
3137 if (!empty($softContributions)) {
3138 $values['softContributions'] = $softContributions['soft_credit'];
3140 if (isset($this->contribution_page_id
)) {
3141 // This is a call we want to use less, in favour of loading related objects.
3142 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
3143 if ($this->contribution_page_id
) {
3144 // This is precautionary as there are some legacy flows, but it should really be
3146 if (!isset($this->_relatedObjects
['contributionPage'])) {
3147 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id
]);
3149 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($values);
3152 // no contribution page -probably back office
3154 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
3155 $values['title'] = 'Contribution';
3157 // set lineItem for contribution
3159 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
3160 if (!empty($lineItems)) {
3161 $firstLineItem = reset($lineItems);
3163 if (!empty($firstLineItem['price_set_id'])) {
3164 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
3165 'id' => $firstLineItem['price_set_id'],
3166 'return' => 'is_quick_config, id',
3168 $values['priceSetID'] = $priceSet['id'];
3170 foreach ($lineItems as &$eachItem) {
3171 if (isset($this->_relatedObjects
['membership'])
3172 && is_array($this->_relatedObjects
['membership'])
3173 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
3174 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
3175 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
3176 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
3178 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
3179 // However, that does create upgrade pain so would be better to be phased in.
3180 $values['useForMember'] = empty($priceSet['is_quick_config']);
3182 $values['lineItem'][0] = $lineItems;
3186 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
3190 // if this is onbehalf of contribution then set related contact
3191 if (!empty($relatedContact['individual_id'])) {
3192 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
3196 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects
['participant']->id
, $this->id
));
3199 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
3202 foreach ($groupTree as $key => $group) {
3203 if ($key === 'info') {
3207 foreach ($group['fields'] as $k => $customField) {
3208 $groupLabel = $group['title'];
3209 if (!empty($customField['customValue'])) {
3210 foreach ($customField['customValue'] as $customFieldValues) {
3211 $customGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
3216 $values['customGroup'] = $customGroup;
3218 $values['is_pay_later'] = $this->is_pay_later
;
3224 * Assign message variables to template but try to break the habit.
3226 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3227 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3228 * multiple recurring payments for processors like IATS that use tokens.
3230 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3231 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
3232 * Note we send directly from this function in some cases because it is only partly refactored.
3234 * Don't call this function directly as the signature will change.
3238 * @param bool $returnMessageText
3242 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
3243 // @todo - this should have a better separation of concerns - ie.
3244 // gatherMessageValues should build an array of values to be assigned to the template
3245 // and this function should assign them (assigning null if not set).
3246 // the way the pcpParams & honor Params section works is a baby-step towards this.
3247 $template = CRM_Core_Smarty
::singleton();
3248 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
3249 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
3250 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
3251 $template->assign('billingName', $values['billingName']);
3253 // For some unit tests contribution cannot contain paymentProcessor information
3254 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
3255 $template->assign('contributeMode', CRM_Utils_Array
::value($billingMode, CRM_Core_SelectValues
::contributeMode()));
3257 //assign honor information to receipt message
3258 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
3261 'soft_credit_type' => NULL,
3262 'honor_block_is_active' => NULL,
3264 if (isset($softRecord['soft_credit'])) {
3265 //if id of contribution page is present
3266 if (!empty($values['id'])) {
3267 $values['honor'] = [
3268 'honor_profile_values' => [],
3269 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3270 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
3273 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3274 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
3277 //offline contribution
3278 $softCreditTypes = $softCredits = [];
3279 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3280 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3281 $softCredits[$key] = [
3282 'Name' => $softCredit['contact_name'],
3283 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
3286 $template->assign('softCreditTypes', $softCreditTypes);
3287 $template->assign('softCredits', $softCredits);
3291 $dao = new CRM_Contribute_DAO_ContributionProduct();
3292 $dao->contribution_id
= $this->id
;
3293 if ($dao->find(TRUE)) {
3294 $premiumId = $dao->product_id
;
3295 $template->assign('option', $dao->product_option
);
3297 $productDAO = new CRM_Contribute_DAO_Product();
3298 $productDAO->id
= $premiumId;
3299 $productDAO->find(TRUE);
3300 $template->assign('selectPremium', TRUE);
3301 $template->assign('product_name', $productDAO->name
);
3302 $template->assign('price', $productDAO->price
);
3303 $template->assign('sku', $productDAO->sku
);
3305 $template->assign('title', CRM_Utils_Array
::value('title', $values));
3306 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
3307 if (!$values['amount'] && isset($this->total_amount
)) {
3308 $values['amount'] = $this->total_amount
;
3313 'pcp_display_in_roll' => NULL,
3314 'pcp_roll_nickname' => NULL,
3315 'pcp_personal_note' => NULL,
3319 if (strtolower($this->_component
) == 'contribute') {
3321 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3322 $softDAO->contribution_id
= $this->id
;
3323 if ($softDAO->find(TRUE)) {
3324 $pcpParams['pcpBlock'] = TRUE;
3325 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
3326 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
3327 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
3329 //assign the pcp page title for email subject
3330 $pcpDAO = new CRM_PCP_DAO_PCP();
3331 $pcpDAO->id
= $softDAO->pcp_id
;
3332 if ($pcpDAO->find(TRUE)) {
3333 $pcpParams['title'] = $pcpDAO->title
;
3337 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3338 $template->assign($templateKey, $templateValue);
3341 if ($this->financial_type_id
) {
3342 $values['financial_type_id'] = $this->financial_type_id
;
3345 $template->assign('trxn_id', $this->trxn_id
);
3346 $template->assign('receive_date',
3347 CRM_Utils_Date
::processDate($this->receive_date
)
3349 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
3350 $template->assign('action', $this->is_test ?
1024 : 1);
3351 $template->assign('receipt_text',
3352 CRM_Utils_Array
::value('receipt_text',
3356 $template->assign('is_monetary', 1);
3357 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3358 $template->assign('currency', $this->currency
);
3359 $template->assign('address', CRM_Utils_Address
::format($input));
3360 if (!empty($values['customGroup'])) {
3361 $template->assign('customGroup', $values['customGroup']);
3363 if (!empty($values['softContributions'])) {
3364 $template->assign('softContributions', $values['softContributions']);
3366 if ($this->_component
== 'event') {
3367 $template->assign('title', $values['event']['title']);
3368 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3370 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3371 $viewRoles[] = $participantRoles[$v];
3373 $values['event']['participant_role'] = implode(', ', $viewRoles);
3374 $template->assign('event', $values['event']);
3375 $template->assign('participant', $values['participant']);
3376 $template->assign('location', $values['location']);
3377 $template->assign('customPre', $values['custom_pre_id']);
3378 $template->assign('customPost', $values['custom_post_id']);
3381 if ($this->_relatedObjects
['participant']->is_test
) {
3385 $values['params'] = [];
3386 //to get email of primary participant.
3387 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3388 $primaryAmount[] = [
3389 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3390 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3392 //build an array of cId/pId of participants
3393 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3394 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3395 //send receipt to additional participant if exists
3396 if (count($additionalIDs)) {
3397 $template->assign('isPrimary', 0);
3398 $template->assign('customProfile', NULL);
3399 //set additionalParticipant true
3400 $values['params']['additionalParticipant'] = TRUE;
3401 foreach ($additionalIDs as $pId => $cId) {
3403 //to change the status pending to completed
3404 $additional = new CRM_Event_DAO_Participant();
3405 $additional->id
= $pId;
3406 $additional->contact_id
= $cId;
3407 $additional->find(TRUE);
3408 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3409 $additional->status_id
= 1;
3410 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3411 //if additional participant dont have email
3413 if (!$additionalParticipantInfo) {
3414 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3417 'label' => $additional->fee_level
,
3418 'amount' => $additional->fee_amount
,
3420 $primaryAmount[] = [
3421 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3422 'amount' => $additional->fee_amount
,
3424 $additional->save();
3425 $template->assign('amount', $amount);
3426 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3430 //build an array of custom profile and assigning it to template
3431 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3433 if (count($customProfile)) {
3434 $template->assign('customProfile', $customProfile);
3437 // for primary contact
3438 $values['params']['additionalParticipant'] = FALSE;
3439 $template->assign('isPrimary', 1);
3440 $template->assign('amount', $primaryAmount);
3441 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3442 if ($this->payment_instrument_id
) {
3443 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3444 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3446 // carry paylater, since we did not created billing,
3447 // so need to pull email from primary location, CRM-4395
3448 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3454 * Check whether payment processor supports
3455 * cancellation of contribution subscription
3457 * @param int $contributionId
3460 * @param bool $isNotCancelled
3464 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3465 $cacheKeyString = "$contributionId";
3466 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3468 static $supportsCancel = [];
3470 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3471 $supportsCancel[$cacheKeyString] = FALSE;
3472 $isCancelled = FALSE;
3474 if ($isNotCancelled) {
3475 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3478 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3479 if (!empty($paymentObject)) {
3480 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3483 return $supportsCancel[$cacheKeyString];
3487 * Check whether subscription is already cancelled.
3489 * @param int $contributionId
3493 * contribution status
3495 public static function isSubscriptionCancelled($contributionId) {
3497 SELECT cr.contribution_status_id
3498 FROM civicrm_contribution_recur cr
3499 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3500 WHERE con.id = %1 LIMIT 1";
3501 $params = [1 => [$contributionId, 'Integer']];
3502 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3503 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
3504 if ($status == 'Cancelled') {
3511 * Create all financial accounts entry.
3513 * @param array $params
3514 * Contribution object, line item array and params for trxn.
3517 * @param array $financialTrxnValues
3519 * @return null|\CRM_Core_BAO_FinancialTrxn
3521 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3522 $skipRecords = $update = $return = $isRelatedId = FALSE;
3524 $additionalParticipantId = [];
3525 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3526 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3528 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3529 $entityId = $params['participant_id'];
3530 $entityTable = 'civicrm_participant';
3531 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3533 elseif (!empty($params['membership_id'])) {
3534 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3535 // are created off one contribution should be handled elsewhere
3536 $entityId = $params['membership_id'];
3537 $entityTable = 'civicrm_membership';
3540 $entityId = $params['contribution']->id
;
3541 $entityTable = 'civicrm_contribution';
3544 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3545 $isRelatedId = TRUE;
3548 $entityID[] = $entityId;
3549 if (!empty($additionalParticipantId)) {
3550 $entityID +
= $additionalParticipantId;
3552 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3553 if (empty($params['prevContribution'])) {
3560 $statusId = $params['contribution']->contribution_status_id
;
3561 // CRM-13964 partial payment
3562 if ($contributionStatus == 'Partially paid'
3563 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])
3565 CRM_Core_Error
::deprecatedFunctionWarning('partial_amount params are deprecated from Contribution.create - use Payment.create');
3566 $partialAmtPay = CRM_Utils_Rule
::cleanMoney($params['partial_amount_to_pay']);
3567 $partialAmtTotal = CRM_Utils_Rule
::cleanMoney($params['partial_payment_total']);
3569 $fromFinancialAccountId = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3570 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
3571 $params['total_amount'] = $partialAmtPay;
3573 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3574 if (empty($balanceTrxnInfo['trxn_id'])) {
3575 // create new balance transaction record
3576 $toFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3578 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3579 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3580 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3581 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3582 $balanceTrxnParams['fee_amount'] = $params['fee_amount'] ??
NULL;
3583 $balanceTrxnParams['net_amount'] = $params['net_amount'] ??
NULL;
3584 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3585 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3586 $balanceTrxnParams['status_id'] = $statusId;
3587 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3588 $balanceTrxnParams['check_number'] = $params['check_number'] ??
NULL;
3589 $balanceTrxnParams['pan_truncation'] = $params['pan_truncation'] ??
NULL;
3590 $balanceTrxnParams['card_type_id'] = $params['card_type_id'] ??
NULL;
3591 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3592 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3594 $balanceTrxnParams['is_payment'] = 1;
3596 if (!empty($params['payment_processor'])) {
3597 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3599 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3603 // build line item array if its not set in $params
3604 if (empty($params['line_item']) ||
$additionalParticipantId) {
3605 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3608 if ($contributionStatus != 'Failed' &&
3609 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3611 $skipRecords = TRUE;
3616 if (in_array($contributionStatus, $pendingStatus)) {
3617 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3618 $params['financial_type_id'],
3619 'Accounts Receivable Account is'
3622 elseif (!empty($params['payment_processor'])) {
3623 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3624 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3625 'id' => $params['payment_processor'],
3626 'return' => 'payment_instrument_id',
3629 elseif (!empty($params['payment_instrument_id'])) {
3630 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3633 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3634 $queryParams = [1 => [$relationTypeId, 'Integer']];
3635 $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);
3638 $totalAmount = $params['total_amount'] ??
NULL;
3639 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3640 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3642 //build financial transaction params
3644 'contribution_id' => $params['contribution']->id
,
3645 'to_financial_account_id' => $params['to_financial_account_id'],
3646 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3647 'total_amount' => $totalAmount,
3648 'fee_amount' => $params['fee_amount'] ??
NULL,
3649 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3650 'currency' => $params['contribution']->currency
,
3651 'trxn_id' => $params['contribution']->trxn_id
,
3652 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3653 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3654 // this should really default to completed (after discussion).
3655 'status_id' => $statusId,
3656 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3657 'check_number' => $params['check_number'] ??
NULL,
3658 'pan_truncation' => $params['pan_truncation'] ??
NULL,
3659 'card_type_id' => $params['card_type_id'] ??
NULL,
3661 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3662 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3663 if (isset($params['refund_trxn_id'])) {
3664 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3665 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3668 //CRM-16259, set is_payment flag for non pending status
3669 if (!in_array($contributionStatus, $pendingStatus)) {
3670 $trxnParams['is_payment'] = 1;
3672 if (!empty($params['payment_processor'])) {
3673 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3676 if (isset($fromFinancialAccountId)) {
3677 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3680 // consider external values passed for recording transaction entry
3681 if (!empty($financialTrxnValues)) {
3682 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3684 if (empty($trxnParams['payment_processor_id'])) {
3685 unset($trxnParams['payment_processor_id']);
3688 $params['trxnParams'] = $trxnParams;
3690 if (!empty($params['prevContribution'])) {
3692 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3693 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3694 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3695 if (!isset($params['trxnParams']['trxn_id'])) {
3696 // Actually I have no idea why we are overwriting any values from the previous contribution.
3697 // (filling makes sense to me). However, only protecting this value as I really really know we
3698 // don't want this one overwritten.
3700 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3702 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3704 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3705 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3706 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3708 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3709 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3712 //if financial type is changed
3713 if (!empty($params['financial_type_id']) &&
3714 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3716 $accountRelationship = 'Income Account is';
3717 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3718 $accountRelationship = 'Deferred Revenue Account is';
3720 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3721 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3722 if ($oldFinancialAccount != $newFinancialAccount) {
3723 $params['total_amount'] = 0;
3724 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3725 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3726 $params['prevContribution']->financial_type_id
, $accountRelationship);
3729 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3730 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3731 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3734 self
::updateFinancialAccounts($params, 'changeFinancialType');
3735 $params['skipLineItem'] = FALSE;
3736 foreach ($params['line_item'] as &$lineItems) {
3737 foreach ($lineItems as &$line) {
3738 $line['financial_type_id'] = $params['financial_type_id'];
3741 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType');
3742 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3743 $params['financial_account_id'] = $newFinancialAccount;
3744 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3745 self
::updateFinancialAccounts($params);
3746 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE);
3747 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3749 $params['deferred_financial_account_id'] = $newFinancialAccount;
3753 //Update contribution status
3754 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3755 if (!isset($params['refund_trxn_id'])) {
3756 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3757 // gets preference over another so I am only 'protecting' a very specific tested flow
3758 // and letting natural justice take care of the rest.
3759 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3761 if (!empty($params['contribution_status_id']) &&
3762 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3764 //Update Financial Records
3765 $callUpdateFinancialAccounts = self
::updateFinancialAccountsOnContributionStatusChange($params);
3766 if ($callUpdateFinancialAccounts) {
3767 self
::updateFinancialAccounts($params, 'changedStatus');
3768 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus');
3773 // change Payment Instrument for a Completed contribution
3774 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3775 // instrument is null and now new payment instrument is added along with the payment
3776 if (!$params['contribution']->payment_instrument_id
) {
3777 $params['contribution']->find(TRUE);
3779 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3780 $params['trxnParams']['check_number'] = $params['check_number'] ??
NULL;
3782 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3783 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3786 //if Change contribution amount
3787 $params['trxnParams']['fee_amount'] = $params['fee_amount'] ??
NULL;
3788 $params['trxnParams']['net_amount'] = $params['net_amount'] ??
NULL;
3789 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3790 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3791 if (isset($totalAmount) &&
3792 $totalAmount != $params['prevContribution']->total_amount
3794 //Update Financial Records
3795 $params['trxnParams']['from_financial_account_id'] = NULL;
3796 self
::updateFinancialAccounts($params, 'changedAmount');
3797 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount');
3802 // Looks like we might have a data correction update.
3803 // This would be a case where a transaction id has been entered but it is incorrect &
3804 // the person goes back in & fixes it, as opposed to a new transaction.
3805 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3806 // the data fix scenario.
3808 if (isset($params['refund_trxn_id'])) {
3809 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3810 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3811 civicrm_api3('FinancialTrxn', 'create', [
3812 'id' => $refundIDs['financialTrxnId'],
3813 'trxn_id' => $params['refund_trxn_id'],
3817 $cardType = $params['card_type_id'] ??
NULL;
3818 $panTruncation = $params['pan_truncation'] ??
NULL;
3819 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3824 // records finanical trxn and entity financial trxn
3825 // also make it available as return value
3826 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3827 $trxnParams['pan_truncation'] = $params['pan_truncation'] ??
NULL;
3828 $trxnParams['card_type_id'] = $params['card_type_id'] ??
NULL;
3829 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3830 $params['entity_id'] = $financialTxn->id
;
3831 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3832 self
::$_trxnIDs[] = $financialTxn->id
;
3836 // record line items and financial items
3837 if (empty($params['skipLineItem'])) {
3838 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3841 // create batch entry if batch_id is passed and
3842 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3843 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3845 'batch_id' => $params['batch_id'],
3846 'entity_table' => 'civicrm_financial_trxn',
3847 'entity_id' => $financialTxn->id
,
3849 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3852 // when a fee is charged
3853 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3854 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3857 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3858 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3860 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3861 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3862 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3864 unset($params['line_item']);
3865 self
::$_trxnIDs = NULL;
3870 * Update all financial accounts entry.
3872 * @param array $params
3873 * Contribution object, line item array and params for trxn.
3875 * @param string $context
3878 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3879 * adds unpredictability.
3882 public static function updateFinancialAccounts(&$params, $context = NULL) {
3884 $inputParams = $params;
3885 $isARefund = self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
);
3887 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3888 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3889 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3892 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3893 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3894 $params['entity_id'] = $trxn->id
;
3896 $itemParams['entity_table'] = 'civicrm_line_item';
3897 $trxnIds['id'] = $params['entity_id'];
3898 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution']->id
);
3899 foreach ($params['line_item'] as $fieldId => $fields) {
3900 $params = self
::createFinancialItemsForLine($params, $context, $fields, $previousLineItems, $inputParams, $isARefund, $trxnIds, $fieldId);
3905 * Is this contribution status a reversal.
3907 * If so we would expect to record a negative value in the financial_trxn table.
3909 * @param int $status_id
3913 public static function isContributionStatusNegative($status_id) {
3914 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3915 return in_array(CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE);
3919 * Check status validation on update of a contribution.
3921 * @param array $values
3922 * Previous form values before submit.
3924 * @param array $fields
3925 * The input form values.
3927 * @param array $errors
3932 public static function checkStatusValidation($values, &$fields, &$errors) {
3933 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3934 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3935 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3939 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3941 'Cancelled' => ['Completed', 'Refunded'],
3942 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3943 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3944 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3945 'Refunded' => ['Cancelled', 'Completed'],
3946 'Partially paid' => ['Completed'],
3947 'Pending refund' => ['Completed', 'Refunded'],
3950 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3951 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3953 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3954 1 => $contributionStatuses[$values['contribution_status_id']],
3955 2 => $contributionStatuses[$fields['contribution_status_id']],
3961 * Delete contribution of contact.
3965 * @param int $contactId
3969 public static function deleteContactContribution($contactId) {
3970 $contribution = new CRM_Contribute_DAO_Contribution();
3971 $contribution->contact_id
= $contactId;
3972 $contribution->find();
3973 while ($contribution->fetch()) {
3974 self
::deleteContribution($contribution->id
);
3979 * Get options for a given contribution field.
3981 * @param string $fieldName
3982 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3983 * @param array $props whatever is known about this dao object.
3985 * @return array|bool
3986 * @see CRM_Core_DAO::buildOptions
3989 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3990 $className = __CLASS__
;
3992 if (isset($props['orderColumn'])) {
3993 $params['orderColumn'] = $props['orderColumn'];
3995 switch ($fieldName) {
3996 // This field is not part of this object but the api supports it
3997 case 'payment_processor':
3998 $className = 'CRM_Contribute_BAO_ContributionPage';
3999 // Filter results by contribution page
4000 if (!empty($props['contribution_page_id'])) {
4001 $page = civicrm_api('contribution_page', 'getsingle', [
4003 'id' => ($props['contribution_page_id']),
4005 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
4006 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
4010 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
4011 case 'honor_type_id':
4012 $className = 'CRM_Contribute_BAO_ContributionSoft';
4013 $fieldName = 'soft_credit_type_id';
4014 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
4017 case 'contribution_status_id':
4018 if ($context !== 'validate') {
4019 $params['condition'] = "v.name <> 'Template'";
4022 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
4026 * Validate financial type.
4030 * @param int $financialTypeId
4031 * Financial Type id.
4033 * @param string $relationName
4035 * @return array|bool
4037 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
4038 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
4040 if (!$financialAccount) {
4041 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
4047 * @param int $targetCid
4048 * @param $activityType
4049 * @param string $title
4050 * @param int $contributionId
4051 * @param string $totalAmount
4052 * @param string $currency
4053 * @param string $trxn_date
4055 * @throws \CRM_Core_Exception
4056 * @throws \CiviCRM_API3_Exception
4058 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
4059 $paymentAmount = CRM_Utils_Money
::format($totalAmount, $currency);
4060 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
4061 $date = CRM_Utils_Date
::isoToMysql($trxn_date);
4062 // source record id would be the contribution id
4063 $srcRecId = $contributionId;
4067 'source_contact_id' => $targetCid,
4068 'source_record_id' => $srcRecId,
4069 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
4070 'subject' => $subject,
4071 'activity_date_time' => $date,
4072 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
4073 'skipRecentView' => TRUE,
4076 // create activity with target contacts
4077 $session = CRM_Core_Session
::singleton();
4078 $id = $session->get('userID');
4080 $activityParams['source_contact_id'] = $id;
4081 $activityParams['target_contact_id'][] = $targetCid;
4083 civicrm_api3('Activity', 'create', $activityParams);
4087 * Get list of payments displayed by Contribute_Page_PaymentInfo.
4090 * @param string $component
4091 * @param bool $getTrxnInfo
4095 * @throws \CRM_Core_Exception
4096 * @throws \CiviCRM_API3_Exception
4098 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE) {
4099 // @todo deprecate passing in component - always call with contribution.
4100 if ($component == 'event') {
4101 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
4103 if (!$contributionId) {
4104 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4105 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4106 $id = $primaryParticipantId;
4108 if (!$contributionId) {
4113 elseif ($component == 'membership') {
4114 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
4117 $contributionId = $id;
4120 // The balance used to be calculated this way - we really want to remove this 'oldCalculation'
4121 // but need to unpick the whole trxn_id it's returning first.
4122 $oldCalculation = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
4123 $baseTrxnId = !empty($oldCalculation['trxn_id']) ?
$oldCalculation['trxn_id'] : NULL;
4125 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
4126 $baseTrxnId = $baseTrxnId['financialTrxnId'];
4128 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4130 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
4132 $contribution = civicrm_api3('Contribution', 'getsingle', [
4133 'id' => $contributionId,
4137 'contribution_status_id',
4138 'financial_type_id',
4142 $info['payLater'] = $contribution['is_pay_later'];
4143 $info['contribution_status'] = $contribution['contribution_status'];
4144 $info['currency'] = $contribution['currency'];
4146 $info['total'] = $total;
4147 $info['paid'] = $total - $paymentBalance;
4148 $info['balance'] = $paymentBalance;
4150 $info['component'] = $component;
4151 if ($getTrxnInfo && $baseTrxnId) {
4152 $info['transaction'] = self
::getContributionTransactionInformation($contributionId, $contribution['financial_type_id']);
4155 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
4160 * Get the outstanding balance on a contribution.
4162 * @param int $contributionId
4163 * @param float $contributionTotal
4164 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
4168 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
4169 if ($contributionTotal === NULL) {
4170 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4173 return (float) CRM_Utils_Money
::subtractCurrencies(
4175 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE),
4176 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4181 * Get the tax amount (misnamed function).
4183 * @param array $params
4184 * @param bool $isLineItem
4188 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4189 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4191 // This function should be only called after standardisation (removal of
4192 // thousand separator & using a decimal point for cents separator.
4193 // However, we don't know if that is always true :-(
4194 // There is a deprecation notice tho :-)
4195 $unknownIfMoneyIsClean = empty($params['skipCleanMoney']) && !$isLineItem;
4196 // Update contribution.
4197 if (!empty($params['id'])) {
4198 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4199 // there are no tax implications - early return.
4200 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4203 if (empty($params['prevContribution'])) {
4204 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4207 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
4208 if (!isset($params[$field])) {
4209 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4210 // Tax amount gets added back on later....
4211 $params['total_amount'] = $params['prevContribution']->total_amount
-
4212 $params['prevContribution']->tax_amount
;
4215 $params[$field] = $params['prevContribution']->$field;
4216 if ($params[$field] != $params['prevContribution']->$field) {
4222 self
::calculateMissingAmountParams($params, $params['id']);
4223 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4224 // Assign tax Amount on update of contribution
4225 if (!empty($params['prevContribution']->tax_amount
)) {
4226 $params['tax_amount'] = 'null';
4227 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4228 foreach ($params['line_item'] as $setID => $priceField) {
4229 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4230 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4237 // New Contribution and update of contribution with tax rate financial type
4238 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4239 empty($params['skipLineItem']) && !$isLineItem
4241 $taxRateParams = $taxRates[$params['financial_type_id']];
4242 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams, $unknownIfMoneyIsClean);
4243 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4245 // Get Line Item on update of contribution
4246 if (isset($params['id'])) {
4247 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4250 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4252 foreach ($params['line_item'] as $setID => $priceField) {
4253 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4254 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4257 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4259 elseif (isset($params['api.line_item.create'])) {
4260 // Update total amount of contribution using lineItem
4261 $taxAmountArray = [];
4262 foreach ($params['api.line_item.create'] as $key => $value) {
4263 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4264 $taxRate = $taxRates[$value['financial_type_id']];
4265 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4266 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4269 $params['tax_amount'] = array_sum($taxAmountArray);
4270 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4273 // update line item of contrbution
4274 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4275 $taxRate = $taxRates[$params['financial_type_id']];
4276 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate, $unknownIfMoneyIsClean);
4277 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4284 * Check financial type validation on update of a contribution.
4286 * @param int $financialTypeId
4287 * Value of latest Financial Type.
4289 * @param int $contributionId
4292 * @param array $errors
4297 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4298 if (!empty($financialTypeId)) {
4299 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4300 if ($oldFinancialTypeId == $financialTypeId) {
4304 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4306 '1' => [$contributionId, 'Integer'],
4308 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4309 if ($result->N
> 1) {
4310 $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.');
4315 * Update related pledge payment payments.
4317 * This function has been refactored out of the back office contribution form and may
4318 * still overlap with other functions.
4320 * @param string $action
4321 * @param int $pledgePaymentID
4322 * @param int $contributionID
4323 * @param bool $adjustTotalAmount
4324 * @param float $total_amount
4325 * @param float $original_total_amount
4326 * @param int $contribution_status_id
4327 * @param int $original_contribution_status_id
4329 public static function updateRelatedPledge(
4335 $original_total_amount,
4336 $contribution_status_id,
4337 $original_contribution_status_id
4339 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4343 if ($pledgePaymentID) {
4344 //store contribution id in payment record.
4345 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4348 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4355 if (!$pledgePaymentID) {
4358 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4364 $updatePledgePaymentStatus = FALSE;
4366 // If either the status or the amount has changed we update the pledge status.
4367 if ($action & CRM_Core_Action
::ADD
) {
4368 $updatePledgePaymentStatus = TRUE;
4370 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4371 ($original_total_amount != $total_amount))
4373 $updatePledgePaymentStatus = TRUE;
4376 if ($updatePledgePaymentStatus) {
4377 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4379 $contribution_status_id,
4388 * Compute the stats values
4390 * @param string $stat either 'mode' or 'median'
4391 * @param string $sql
4392 * @param string $alias of civicrm_contribution
4394 * @return array|null
4398 public static function computeStats($stat, $sql, $alias = NULL) {
4399 CRM_Core_Error
::deprecatedFunctionWarning('computeStats is now deprecated');
4404 * Is there only one line item attached to the contribution.
4410 * @throws \CiviCRM_API3_Exception
4412 public static function isSingleLineItem($id) {
4413 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
4414 return ($lineItemCount == 1);
4418 * Complete an order.
4420 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4422 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4424 * Moving it out of the BaseIPN class is just the first step.
4426 * @param array $input
4428 * @param array $objects
4429 * @param CRM_Core_Transaction $transaction
4430 * @param CRM_Contribute_BAO_Contribution $contribution
4431 * @param bool $isPostPaymentCreate
4432 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
4433 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
4434 * transitioning related elements).
4437 * @throws \CRM_Core_Exception
4438 * @throws \CiviCRM_API3_Exception
4440 public static function completeOrder($input, &$ids, $objects, $transaction, $contribution, $isPostPaymentCreate = FALSE) {
4441 $primaryContributionID = $contribution->id ??
$objects['first_contribution']->id
;
4442 // The previous details are used when calculating line items so keep it before any code that 'does something'
4443 if (!empty($contribution->id
)) {
4444 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(['id' => $contribution->id
]);
4446 $inputContributionWhiteList = [
4451 'payment_instrument_id',
4456 'contribution_status_id',
4460 if (self
::isSingleLineItem($primaryContributionID)) {
4461 $inputContributionWhiteList[] = 'financial_type_id';
4464 $participant = $objects['participant'] ??
NULL;
4465 $recurContrib = $objects['contributionRecur'] ??
NULL;
4466 $recurringContributionID = (empty($recurContrib->id
)) ?
NULL : $recurContrib->id
;
4467 $event = $objects['event'] ??
NULL;
4469 $paymentProcessorId = '';
4470 if (isset($objects['paymentProcessor'])) {
4471 if (is_array($objects['paymentProcessor'])) {
4472 $paymentProcessorId = $objects['paymentProcessor']['id'];
4475 $paymentProcessorId = $objects['paymentProcessor']->id
;
4479 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4481 $contributionParams = array_merge([
4482 'contribution_status_id' => $completedContributionStatusID,
4483 'source' => self
::getRecurringContributionDescription($contribution, $event),
4484 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4487 // CRM-20678 Ensure that the currency is correct in subseqent transcations.
4488 if (empty($contributionParams['currency']) && isset($objects['first_contribution']->currency
)) {
4489 $contributionParams['currency'] = $objects['first_contribution']->currency
;
4492 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
4494 // If paymentProcessor is not set then the payment_instrument_id would not be correct.
4495 // not clear when or if this would occur if you encounter this please fix here & add a unit test.
4496 if (empty($contributionParams['payment_instrument_id']) && isset($contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'])) {
4497 $contributionParams['payment_instrument_id'] = $contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'];
4500 if ($recurringContributionID) {
4501 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4503 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4505 if (empty($contributionParams['receive_date']) && $changeDate) {
4506 $contributionParams['receive_date'] = $changeDate;
4509 self
::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
4510 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4513 if (isset($input['is_email_receipt'])) {
4514 $values['is_email_receipt'] = $input['is_email_receipt'];
4517 if ($input['component'] == 'contribute') {
4518 if ($contribution->contribution_page_id
) {
4519 // Figure out what we gain from this.
4520 // Note that we may have overwritten the is_email_receipt input, fix that below.
4521 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4523 elseif ($recurContrib && $recurringContributionID) {
4524 $values['amount'] = $recurContrib->amount
;
4525 $values['financial_type_id'] = $objects['contributionType']->id
;
4526 $values['title'] = $source = ts('Offline Recurring Contribution');
4529 if (isset($input['is_email_receipt'])) {
4530 // CRM-19601 - we may have overwritten this above.
4531 $values['is_email_receipt'] = $input['is_email_receipt'];
4533 elseif ($recurContrib && $recurringContributionID) {
4534 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4535 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4536 // dev/core#1245 this maybe not the desired effect because the default value for is_email_receipt is set to 0 rather than 1 in
4537 // Instance that had the table added via an upgrade in 4.1
4538 // see also https://github.com/civicrm/civicrm-svn/commit/7f39befd60bc735408d7866b02b3ac7fff1d4eea#diff-9ad8e290180451a2d6eacbd3d1ca7966R354
4539 // https://lab.civicrm.org/dev/core/issues/1245
4540 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4543 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4544 self
::updateMembershipBasedOnCompletionOfContribution(
4546 $primaryContributionID,
4552 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4553 if ($event->is_email_confirm
) {
4554 // @todo this should be set by the function that sends the mail after sending.
4555 $contributionParams['receipt_date'] = $changeDate;
4557 $participantParams['id'] = $participant->id
;
4558 $participantParams['status_id'] = 'Registered';
4559 civicrm_api3('Participant', 'create', $participantParams);
4563 $contributionParams['id'] = $contribution->id
;
4564 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
4566 // CRM-19309 - if you update the contribution here with financial_type_id it can/will mess with $lineItem
4567 // unsetting it here does NOT cause any other contribution test to fail!
4568 unset($contributionParams['financial_type_id']);
4569 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4571 // Add new soft credit against current $contribution.
4572 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
4573 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4576 if (empty($contribution->_relatedObjects
['participant']) && !empty($contribution->_relatedObjects
['membership'])) {
4577 // @fixme Can we remove this if altogether? - we removed the participant if / else and left relatedObjects['participant'] to ensure behaviour didn't change but it is probably not required.
4578 // @todo - use getRelatedMemberships instead
4579 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4580 $contribution->trxn_id
= $input['trxn_id'] ??
NULL;
4581 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4584 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4585 $transaction->commit();
4587 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution->id
, $recurringContributionID,
4588 $contributionParams['contribution_status_id'], $input['amount']);
4590 // create an activity record
4591 if ($input['component'] == 'contribute') {
4593 $targetContactID = NULL;
4594 if (!empty($ids['related_contact'])) {
4595 $targetContactID = $contribution->contact_id
;
4596 $contribution->contact_id
= $ids['related_contact'];
4598 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4601 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4602 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4603 if (!array_key_exists('is_email_receipt', $values) ||
4604 $values['is_email_receipt'] == 1
4606 civicrm_api3('Contribution', 'sendconfirmation', [
4607 'id' => $contribution->id
,
4608 'payment_processor_id' => $paymentProcessorId,
4610 CRM_Core_Error
::debug_log_message("Receipt sent");
4613 CRM_Core_Error
::debug_log_message("Success: Database updated");
4614 return $contributionResult;
4618 * Send receipt from contribution.
4620 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4622 * Note that the compose message part has been moved to contribution
4623 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4625 * @param array $input
4626 * Incoming data from Payment processor.
4628 * Related object IDs.
4629 * @param int $contributionID
4630 * @param array $values
4631 * Values related to objects that have already been loaded.
4632 * @param bool $returnMessageText
4633 * Should text be returned instead of sent. This.
4634 * is because the function is also used to generate pdfs
4637 * @throws \CRM_Core_Exception
4638 * @throws \CiviCRM_API3_Exception
4639 * @throws \Exception
4641 public static function sendMail(&$input, &$ids, $contributionID, &$values,
4642 $returnMessageText = FALSE) {
4644 $contribution = new CRM_Contribute_BAO_Contribution();
4645 $contribution->id
= $contributionID;
4646 if (!$contribution->find(TRUE)) {
4647 throw new CRM_Core_Exception('Contribution does not exist');
4649 $contribution->loadRelatedObjects($input, $ids, TRUE);
4650 // set receipt from e-mail and name in value
4651 if (!$returnMessageText) {
4652 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4654 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4655 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4656 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4657 civicrm_api3('Contribution', 'create', [
4658 'receipt_date' => 'now',
4659 'id' => $contribution->id
,
4666 * Generate From email and from name in an array values
4668 * @param array $input
4669 * @param \CRM_Contribute_BAO_Contribution $contribution
4673 public static function generateFromEmailAndName($input, $contribution) {
4674 // Use input value if supplied.
4675 if (!empty($input['receipt_from_email'])) {
4677 CRM_Utils_Array
::value('receipt_from_name', $input, ''),
4678 $input['receipt_from_email'],
4681 // if we are still empty see if we can use anything from a contribution page.
4683 if (!empty($contribution->contribution_page_id
)) {
4684 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id
]);
4686 // if we are still empty see if we can use anything from a contribution page.
4687 if (!empty($pageValues['receipt_from_email'])) {
4689 CRM_Utils_Array
::value('receipt_from_name', $pageValues),
4690 $pageValues['receipt_from_email'],
4693 // If we are still empty fall back to the domain or logged in user information.
4694 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4698 * Load related memberships.
4702 * @return array $ids
4707 * Note that in theory it should be possible to retrieve these from the line_item table
4708 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4709 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4710 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4711 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4713 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4716 public function loadRelatedMembershipObjects($ids = []) {
4718 SELECT membership_id
4719 FROM civicrm_membership_payment
4720 WHERE contribution_id = %1 ";
4721 $params = [1 => [$this->id
, 'Integer']];
4722 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, []);
4724 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4725 while ($dao->fetch()) {
4726 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4727 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4731 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4732 foreach ($ids['membership'] as $id) {
4734 $membership = new CRM_Member_BAO_Membership();
4735 $membership->id
= $id;
4736 if (!$membership->find(TRUE)) {
4737 throw new Exception("Could not find membership record: $id");
4739 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4740 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4741 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4742 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4750 * This function is used to record partial payments for contribution
4752 * @param array $contribution
4754 * @param array $params
4756 * @return CRM_Financial_DAO_FinancialTrxn
4758 public static function recordPartialPayment($contribution, $params) {
4759 CRM_Core_Error
::deprecatedFunctionWarning('use payment create api');
4760 $balanceTrxnParams['to_financial_account_id'] = self
::getToFinancialAccount($contribution, $params);
4761 $balanceTrxnParams['from_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($contribution['financial_type_id'], 'Accounts Receivable Account is');
4762 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4763 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4764 $balanceTrxnParams['trxn_date'] = CRM_Utils_Array
::value('trxn_date', $params, CRM_Utils_Array
::value('contribution_receive_date', $params, date('YmdHis')));
4765 $balanceTrxnParams['fee_amount'] = $params['fee_amount'] ??
NULL;
4766 $balanceTrxnParams['net_amount'] = $params['total_amount'] ??
NULL;
4767 $balanceTrxnParams['currency'] = $contribution['currency'];
4768 $balanceTrxnParams['trxn_id'] = $params['contribution_trxn_id'] ??
NULL;
4769 $balanceTrxnParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_FinancialTrxn', 'status_id', 'Completed');
4770 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4771 $balanceTrxnParams['check_number'] = $params['check_number'] ??
NULL;
4772 $balanceTrxnParams['is_payment'] = 1;
4774 if (!empty($params['payment_processor'])) {
4775 // I can't find evidence this is passed in - I was gonna just remove it but decided to deprecate as I see self::getToFinancialAccount
4776 // also anticipates it.
4777 CRM_Core_Error
::deprecatedFunctionWarning('passing payment_processor is deprecated - use payment_processor_id');
4778 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4780 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4784 * Get the description (source field) for the recurring contribution.
4786 * @param CRM_Contribute_BAO_Contribution $contribution
4787 * @param CRM_Event_DAO_Event|null $event
4790 * @throws \CiviCRM_API3_Exception
4792 protected static function getRecurringContributionDescription($contribution, $event) {
4793 if (!empty($contribution->source
)) {
4794 return $contribution->source
;
4796 elseif (!empty($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
4797 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', [
4798 'id' => $contribution->contribution_page_id
,
4799 'return' => 'title',
4801 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4804 return ts('Online Event Registration') . ': ' . $event->title
;
4806 elseif (!empty($contribution->contribution_recur_id
)) {
4807 return 'recurring contribution';
4813 * Function use to store line item proportionally in in entity financial trxn table
4815 * @param array $trxnParams
4817 * @param int $trxnId
4819 * @param float $contributionTotalAmount
4821 * @throws \CiviCRM_API3_Exception
4823 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4824 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4825 if (!empty($lineItems)) {
4826 // get financial item
4827 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4829 'contribution_total_amount' => $contributionTotalAmount,
4830 'trxn_total_amount' => $trxnParams['total_amount'],
4831 'trxn_id' => $trxnId,
4833 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4838 * Checks if line items total amounts
4839 * match the contribution total amount.
4841 * @param array $params
4842 * array of order params.
4844 * @throws \API_Exception
4846 public static function checkLineItems(&$params) {
4847 $totalAmount = $params['total_amount'] ??
NULL;
4848 $lineItemAmount = 0;
4850 foreach ($params['line_items'] as &$lineItems) {
4851 foreach ($lineItems['line_item'] as &$item) {
4852 if (empty($item['financial_type_id'])) {
4853 $item['financial_type_id'] = $params['financial_type_id'];
4855 $lineItemAmount +
= $item['line_total'] + CRM_Utils_Array
::value('tax_amount', $item, 0.00);
4859 if (!isset($totalAmount)) {
4860 $params['total_amount'] = $lineItemAmount;
4863 $currency = CRM_Utils_Array
::value('currency', $params, '');
4865 if (empty($currency)) {
4866 $currency = CRM_Core_Config
::singleton()->defaultCurrency
;
4869 if (!CRM_Utils_Money
::equals($totalAmount, $lineItemAmount, $currency)) {
4870 throw new CRM_Contribute_Exception_CheckLineItemsException();
4876 * Get the financial account for the item associated with the new transaction.
4878 * @param array $params
4879 * @param int $default
4883 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
4885 if (!empty($params['financial_account_id'])) {
4886 return $params['financial_account_id'];
4889 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4890 $preferredAccountsRelationships = [
4891 'Refunded' => 'Credit/Contra Revenue Account is',
4892 'Chargeback' => 'Chargeback Account is',
4895 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4896 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4897 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4899 $preferredAccountsRelationships[$contributionStatus]
4907 * ContributionPage values were being imposed onto values.
4909 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4910 * REALLY didn't want superimposed. The rest are left there in their overkill out
4913 * The rationale for making this explicit is that it was a case of carefully set values being
4914 * seemingly randonly overwritten without much care. In general I think array randomly setting
4915 * variables en mass is risky.
4917 * @param array $values
4921 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4922 $contributionPageValues = [];
4923 CRM_Contribute_BAO_ContributionPage
::setValues(
4924 $this->contribution_page_id
,
4925 $contributionPageValues
4928 // These are the values that I believe to be useful.
4931 'pay_later_receipt',
4933 'receipt_from_email',
4934 'receipt_from_name',
4938 'honoree_profile_id',
4939 'onbehalf_profile_id',
4940 'honor_block_is_active',
4941 // Kinda might be - but would be on the contribution...
4944 // Included for 'fear of regression' but can't justify any use for these....
4946 'payment_processor',
4947 'financial_type_id',
4948 'amount_block_is_active',
4953 'default_amount_id',
4957 'initial_amount_help_text',
4958 'initial_amount_label',
4960 'is_allow_other_amount',
4961 'is_billing_required',
4962 'is_confirm_enabled',
4963 'is_credit_card_only',
4965 'is_partial_payment',
4966 'is_recur_installments',
4967 'is_recur_interval',
4971 'min_initial_amount',
4972 'recur_frequency_unit',
4979 foreach ($valuesToCopy as $valueToCopy) {
4980 if (isset($contributionPageValues[$valueToCopy])) {
4981 if ($valueToCopy === 'title') {
4982 $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils
::getContributionPageTitle($this->contribution_page_id
);
4985 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
4993 * Get values of CiviContribute Settings
4994 * and check if its enabled or not.
4995 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
4996 * in serialized form. Usually this should be stored as flat settings for each form fields
4997 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
4998 * settings we will live with an inconsistency because it's too hard to change for now.
4999 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
5002 * @param string $name
5007 public static function checkContributeSettings($name) {
5008 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
5009 return $contributeSettings[$name] ??
NULL;
5013 * This function process contribution related objects.
5015 * @param int $contributionId
5016 * @param int $statusId
5017 * @param int|null $previousStatusId
5019 * @param string $receiveDate
5021 * @return null|string
5023 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
5025 if (!$contributionId ||
!$statusId) {
5030 'contribution_id' => $contributionId,
5031 'contribution_status_id' => $statusId,
5032 'previous_contribution_status_id' => $previousStatusId,
5033 'receive_date' => $receiveDate,
5036 $updateResult = CRM_Contribute_BAO_Contribution
::transitionComponents($params);
5038 if (!is_array($updateResult) ||
5039 !($updatedComponents = CRM_Utils_Array
::value('updatedComponents', $updateResult)) ||
5040 !is_array($updatedComponents) ||
5041 empty($updatedComponents)
5046 // get the user display name.
5048 SELECT display_name as displayName
5049 FROM civicrm_contact
5050 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
5051 WHERE civicrm_contribution.id = {$contributionId}";
5052 $userDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
5054 // get the status message for user.
5055 foreach ($updatedComponents as $componentName => $updatedStatusId) {
5057 if ($componentName == 'CiviMember') {
5058 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5059 CRM_Member_PseudoConstant
::membershipStatus()
5062 $statusNameMsgPart = 'updated';
5063 switch ($updatedStatusName) {
5066 $statusNameMsgPart = $updatedStatusName;
5070 $statusMsg .= "<br />" . ts("Membership for %1 has been %2.", [
5071 1 => $userDisplayName,
5072 2 => $statusNameMsgPart,
5076 if ($componentName == 'CiviEvent') {
5077 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5078 CRM_Event_PseudoConstant
::participantStatus()
5080 if ($updatedStatusName == 'Cancelled') {
5081 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", [1 => $userDisplayName]);
5083 elseif ($updatedStatusName == 'Registered') {
5084 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", [1 => $userDisplayName]);
5088 if ($componentName == 'CiviPledge') {
5089 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5090 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name')
5092 if ($updatedStatusName == 'Cancelled') {
5093 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", [1 => $userDisplayName]);
5095 elseif ($updatedStatusName == 'Failed') {
5096 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", [1 => $userDisplayName]);
5098 elseif ($updatedStatusName == 'Completed') {
5099 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", [1 => $userDisplayName]);
5108 * Get the contribution as it is in the database before being updated.
5110 * @param int $contributionID
5112 * @return \CRM_Contribute_BAO_Contribution|null
5114 private static function getOriginalContribution($contributionID) {
5115 return self
::getValues(['id' => $contributionID]);
5119 * Get the amount for the financial item row.
5121 * Helper function to start to break down recordFinancialTransactions for readability.
5123 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
5125 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
5126 * for historical reasons. Going forwards we can hope to add tests & improve readibility
5129 * @param array $params
5130 * Params as passed to contribution.create
5132 * @param string $context
5133 * changeFinancialType| changedAmount
5134 * @param array $lineItemDetails
5136 * @param bool $isARefund
5137 * Is this a refund / negative transaction.
5138 * @param int $previousLineItemTotal
5141 * @todo move recordFinancialAccounts & helper functions to their own class?
5144 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
5145 if ($context == 'changedAmount') {
5146 $lineTotal = $lineItemDetails['line_total'];
5147 if ($lineTotal != $previousLineItemTotal) {
5148 $lineTotal -= $previousLineItemTotal;
5152 elseif ($context == 'changeFinancialType') {
5153 return -$lineItemDetails['line_total'];
5155 elseif ($context == 'changedStatus') {
5156 $cancelledTaxAmount = 0;
5158 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
5160 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
5162 elseif ($context === NULL) {
5163 // erm, yes because? but, hey, it's tested.
5164 return $lineItemDetails['line_total'];
5166 elseif (empty($lineItemDetails['line_total'])) {
5167 // follow legacy code path
5169 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', ['civi.tag' => 'deprecated']);
5170 return $params['total_amount'];
5173 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
5178 * Get the multiplier for adjusting rows.
5180 * If we are dealing with a refund or cancellation then it will be a negative
5181 * amount to reflect the negative transaction.
5183 * If we are changing Financial Type it will be a negative amount to
5184 * adjust down the old type.
5186 * @param int $contribution_status_id
5187 * @param string $context
5191 protected static function getMultiplier($contribution_status_id, $context) {
5192 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
5199 * Does this transaction reflect a payment instrument change.
5201 * @param array $params
5202 * @param array $pendingStatuses
5206 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
5207 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
5209 if (array_key_exists('payment_instrument_id', $params)) {
5210 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
5211 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
5213 //check if status is changed from Pending to Completed
5214 // do not update payment instrument changes for Pending to Completed
5215 if (!($contributionStatus == 'Completed' &&
5216 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
5221 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
5222 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
5223 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
5227 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
5228 $params['contribution']->check_number
!= $params['prevContribution']->check_number
5230 // another special case when check number is changed, create new financial records
5231 // create financial trxn with negative amount
5239 * Update the memberships associated with a contribution if it has been completed.
5241 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
5242 * load them in this function. Code clean up would compensate for any minor performance implication.
5244 * @param \CRM_Contribute_BAO_Contribution $contribution
5245 * @param int $primaryContributionID
5246 * @param string $changeDate
5248 * @throws \CRM_Core_Exception
5249 * @throws \CiviCRM_API3_Exception
5251 public static function updateMembershipBasedOnCompletionOfContribution($contribution, $primaryContributionID, $changeDate) {
5252 $memberships = self
::getRelatedMemberships($contribution->id
);
5253 foreach ($memberships as $membership) {
5254 $membershipParams = [
5255 'id' => $membership['id'],
5256 'contact_id' => $membership['contact_id'],
5257 'is_test' => $membership['is_test'],
5258 'membership_type_id' => $membership['membership_type_id'],
5259 'membership_activity_status' => 'Completed',
5262 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
5263 $membershipParams['membership_type_id'],
5264 $membershipParams['is_test'],
5265 $membershipParams['id']
5268 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
5269 // this picks up membership type changes during renewals
5270 // @todo this is almost certainly an obsolete sql call, the pre-change
5271 // membership is accessible via $this->_relatedObjects
5273 SELECT membership_type_id
5274 FROM civicrm_membership_log
5275 WHERE membership_id={$membershipParams['id']}
5278 $dao = CRM_Core_DAO
::executeQuery($sql);
5279 if ($dao->fetch()) {
5280 if (!empty($dao->membership_type_id
)) {
5281 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
5284 if (empty($membership['end_date']) ||
(int) $membership['status_id'] !== CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
5285 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
5286 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
5287 // The api assumes num_terms is a special sauce for 'is_renewal' so we need to not pass it when updating a pending to completed.
5288 // @todo once apiv4 ships with core switch to that & find sanity.
5289 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
5290 $membershipParams['membership_type_id'],
5291 $primaryContributionID
5294 // @todo remove all this stuff in favour of letting the api call further down handle in
5295 // (it is a duplication of what the api does).
5296 $dates = array_fill_keys([
5301 if ($currentMembership) {
5303 * Fixed FOR CRM-4433
5304 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
5305 * when Contribution mode is notify and membership is for renewal )
5307 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
5309 // @todo - we should pass membership_type_id instead of null here but not
5310 // adding as not sure of testing
5311 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
5312 $changeDate, NULL, $membershipParams['num_terms']
5314 $dates['join_date'] = $currentMembership['join_date'];
5317 //get the status for membership.
5318 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
5320 $dates['join_date'],
5323 $membershipParams['membership_type_id'],
5327 unset($dates['end_date']);
5328 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
5329 //we might be renewing membership,
5330 //so make status override false.
5331 $membershipParams['is_override'] = FALSE;
5332 $membershipParams['status_override_end_date'] = 'null';
5334 //CRM-17723 - reset static $relatedContactIds array()
5335 // @todo move it to Civi Statics.
5337 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
5338 civicrm_api3('Membership', 'create', $membershipParams);
5343 * Get payment links as they relate to a contribution.
5345 * If a payment can be made then include a payment link & if a refund is appropriate
5346 * then a refund link.
5349 * @param float $balance
5350 * @param string $contributionStatus
5353 * $actionLinks Links array containing:
5357 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
5358 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
5359 // In general the balance is the best way to determine if a payment can be added or not,
5360 // but not for Failed contributions, where we don't accept additional payments at the moment.
5361 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
5362 // do accept more payments agains them.
5367 'url' => CRM_Utils_System
::url('civicrm/payment', [
5373 'title' => ts('Record Payment'),
5376 if ((int) $balance > 0) {
5377 // @todo - this should be possible even if not > 0 - test & remove this if.
5378 // it is possible to 'overpay' in the real world & we honor that.
5379 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
5381 'url' => CRM_Utils_System
::url('civicrm/payment', [
5388 'title' => ts('Submit Credit Card payment'),
5392 elseif ((int) $balance < 0) {
5393 // @todo - in the future remove this IF - OK to refund money even when not due since
5396 'url' => CRM_Utils_System
::url('civicrm/payment', [
5402 'title' => ts('Record Refund'),
5405 return $actionLinks;
5409 * Get a query to determine the amount donated by the contact/s in the current financial year.
5411 * @param array $contactIDs
5415 public static function getAnnualQuery($contactIDs) {
5416 $contactIDs = implode(',', $contactIDs);
5417 $config = CRM_Core_Config
::singleton();
5418 $currentMonth = date('m');
5419 $currentDay = date('d');
5421 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
5423 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
5424 (int) $config->fiscalYearStart
['d'] > $currentDay
5427 $year = date('Y') - 1;
5432 $nextYear = $year +
1;
5434 if ($config->fiscalYearStart
) {
5435 $newFiscalYearStart = $config->fiscalYearStart
;
5436 if ($newFiscalYearStart['M'] < 10) {
5437 // This is just a clumsy way of adding padding.
5438 // @todo next round look for a nicer way.
5439 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
5441 if ($newFiscalYearStart['d'] < 10) {
5442 // This is just a clumsy way of adding padding.
5443 // @todo next round look for a nicer way.
5444 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
5446 $config->fiscalYearStart
= $newFiscalYearStart;
5447 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
5450 // First of January.
5453 $startDate = "$year$monthDay";
5454 $endDate = "$nextYear$monthDay";
5457 'contact_id' => 'IN (' . $contactIDs . ')',
5458 'is_test' => ' = 0',
5459 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
5461 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
5462 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
5465 foreach ($whereClauses as $key => $clause) {
5466 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
5468 $whereClauseString = implode(' AND ', $clauses);
5470 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5471 // this group by + having on contribution_status_id improves performance
5473 SELECT COUNT(*) as count,
5474 SUM(total_amount) as amount,
5475 AVG(total_amount) as average,
5477 FROM civicrm_contribution b
5478 WHERE " . $whereClauseString . "
5479 GROUP BY currency, contribution_status_id
5480 HAVING $havingClause
5486 * Assign Test Value.
5488 * @param string $fieldName
5489 * @param array $fieldDef
5490 * @param int $counter
5492 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5493 if ($fieldName == 'tax_amount') {
5494 $this->{$fieldName} = "0.00";
5496 elseif ($fieldName == 'net_amount') {
5497 $this->{$fieldName} = "2.00";
5499 elseif ($fieldName == 'total_amount') {
5500 $this->{$fieldName} = "3.00";
5502 elseif ($fieldName == 'fee_amount') {
5503 $this->{$fieldName} = "1.00";
5506 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5511 * Check if contribution has participant/membership payment.
5513 * @param int $contributionId
5518 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5519 // get line item for contribution
5520 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5521 // check if line item is for membership or participant
5522 foreach ($lineItems as $items) {
5523 if ($items['entity_table'] == 'civicrm_participant') {
5527 elseif ($items['entity_table'] == 'civicrm_membership') {
5539 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5541 * @param array $trxnParams
5542 * Financial trxn params
5543 * @param array $contributionParams
5544 * Contribution Params
5548 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5549 if (!Civi
::settings()->get('always_post_to_accounts_receivable')) {
5552 $statusId = $contributionParams['contribution']->contribution_status_id
;
5553 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5554 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5555 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5556 // Return if contribution status is not completed.
5557 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5558 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5559 && $contributionParams['prevContribution']->is_pay_later
== 0
5565 $params = $trxnParams;
5566 $financialTypeID = !empty($contributionParams['financial_type_id']) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5567 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5568 $params['to_financial_account_id'] = $arAccountId;
5569 $params['status_id'] = array_search('Pending', $contributionStatuses);
5570 $params['is_payment'] = FALSE;
5571 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5572 self
::$_trxnIDs[] = $trxn->id
;
5573 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5577 * Calculate financial item amount when contribution is updated.
5579 * @param array $params
5580 * contribution params
5581 * @param array $amountParams
5583 * @param string $context
5587 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5588 if (!empty($params['is_quick_config'])) {
5589 $amount = $amountParams['item_amount'];
5591 $amount = $params['total_amount'];
5592 if ($context === NULL) {
5593 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5598 $amount = $amountParams['line_total'];
5599 if ($context == 'changedAmount') {
5600 $amount -= $amountParams['previous_line_total'];
5602 $amount *= $amountParams['diff'];
5608 * Retrieve Sales Tax Financial Accounts.
5614 public static function getSalesTaxFinancialAccounts() {
5615 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5616 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5617 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5618 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5619 $queryParams = [1 => [$accountRel, 'Integer']];
5620 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5621 $financialAccount = [];
5622 while ($dao->fetch()) {
5623 $financialAccount[$dao->id
] = $dao->id
;
5625 return $financialAccount;
5629 * Create tax entry in civicrm_entity_financial_trxn table.
5631 * @param array $entityParams
5633 * @param array $eftParams
5635 * @throws \CiviCRM_API3_Exception
5637 public static function createProportionalEntry($entityParams, $eftParams) {
5639 if ($entityParams['contribution_total_amount'] != 0) {
5640 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5642 // Record Entity Financial Trxn; CRM-20145
5643 $eftParams['amount'] = CRM_Contribute_BAO_Contribution_Utils
::formatAmount($paid);
5644 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5648 * Create array of last financial item id's.
5650 * @param int $contributionId
5654 public static function getLastFinancialItemIds($contributionId) {
5655 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5656 FROM civicrm_financial_item fi
5657 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5658 WHERE li.contribution_id = %1";
5659 $dao = CRM_Core_DAO
::executeQuery($sql, [
5665 $ftIds = $taxItems = [];
5666 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5667 while ($dao->fetch()) {
5668 /* if sales tax item*/
5669 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5670 $taxItems[$dao->price_field_value_id
] = [
5671 'financial_item_id' => $dao->id
,
5672 'amount' => $dao->tax_amount
,
5676 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5679 return [$ftIds, $taxItems];
5683 * Create proportional entries in civicrm_entity_financial_trxn.
5685 * @param array $entityParams
5687 * @param array $lineItems
5689 * @param array $ftIds
5691 * @param array $taxItems
5693 * @throws \CiviCRM_API3_Exception
5695 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5697 'entity_table' => 'civicrm_financial_item',
5698 'financial_trxn_id' => $entityParams['trxn_id'],
5700 foreach ($lineItems as $key => $value) {
5701 if ($value['qty'] == 0) {
5704 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5705 $entityParams['line_item_amount'] = $value['line_total'];
5706 self
::createProportionalEntry($entityParams, $eftParams);
5707 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5708 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5709 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5710 self
::createProportionalEntry($entityParams, $eftParams);
5716 * Load entities related to the contribution into $this->_relatedObjects.
5720 * @throws \CRM_Core_Exception
5722 protected function loadRelatedEntitiesByID($ids) {
5724 'contact' => 'CRM_Contact_BAO_Contact',
5725 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5726 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5727 'financialType' => 'CRM_Financial_BAO_FinancialType',
5728 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5730 foreach ($entities as $entity => $bao) {
5731 if (!empty($ids[$entity])) {
5732 $this->_relatedObjects
[$entity] = new $bao();
5733 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5734 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5735 throw new CRM_Core_Exception($entity . ' could not be loaded');
5742 * Should an email receipt be sent for this contribution when complete.
5744 * @param array $input
5748 protected function isEmailReceipt($input) {
5749 if (isset($input['is_email_receipt'])) {
5750 return $input['is_email_receipt'];
5752 if (!empty($this->_relatedObjects
['contribution_page_id'])) {
5753 return $this->_relatedObjects
['contribution_page_id']->is_email_receipt
;
5759 * Function to replace contribution tokens.
5761 * @param array $contributionIds
5763 * @param string $subject
5765 * @param array $subjectToken
5767 * @param string $text
5769 * @param string $html
5771 * @param array $messageToken
5773 * @param bool $escapeSmarty
5776 * @throws \CiviCRM_API3_Exception
5778 public static function replaceContributionTokens(
5787 if (empty($contributionIds)) {
5790 $contributionDetails = [];
5791 foreach ($contributionIds as $id) {
5792 $result = self
::getContributionTokenValues($id, $messageToken);
5793 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5794 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5795 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5797 return $contributionDetails;
5801 * Get the contribution fields for $id and display labels where
5802 * appropriate (if the token is present).
5805 * @param array $messageToken
5808 public static function getContributionTokenValues($id, $messageToken) {
5812 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5813 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5814 if (!empty($messageToken)) {
5815 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5816 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5817 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField
::displayValue($result['values'][$id][$fieldName], $fieldName);
5825 * Get invoice_number for contribution.
5827 * @param int $contributionID
5831 public static function getInvoiceNumber($contributionID) {
5832 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix')) {
5833 return $invoicePrefix . $contributionID;
5840 * Load the values needed for the event message.
5842 * @param int $eventID
5843 * @param int $participantID
5844 * @param int|null $contributionID
5847 * @throws \CRM_Core_Exception
5849 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5854 $values = ['event' => []];
5856 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
5857 // add custom fields for event
5858 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $eventID);
5860 $eventCustomGroup = [];
5861 foreach ($eventGroupTree as $key => $group) {
5862 if ($key === 'info') {
5866 foreach ($group['fields'] as $k => $customField) {
5867 $groupLabel = $group['title'];
5868 if (!empty($customField['customValue'])) {
5869 foreach ($customField['customValue'] as $customFieldValues) {
5870 $eventCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5875 $values['event']['customGroup'] = $eventCustomGroup;
5877 //get participant details
5878 $participantParams = [
5879 'id' => $participantID,
5882 $values['participant'] = [];
5884 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
5885 // add custom fields for event
5886 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $participantID);
5887 $participantCustomGroup = [];
5888 foreach ($participantGroupTree as $key => $group) {
5889 if ($key === 'info') {
5893 foreach ($group['fields'] as $k => $customField) {
5894 $groupLabel = $group['title'];
5895 if (!empty($customField['customValue'])) {
5896 foreach ($customField['customValue'] as $customFieldValues) {
5897 $participantCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5902 $values['participant']['customGroup'] = $participantCustomGroup;
5904 //get location details
5906 'entity_id' => $eventID,
5907 'entity_table' => 'civicrm_event',
5909 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
5912 'entity_table' => 'civicrm_event',
5913 'entity_id' => $eventID,
5914 'module' => 'CiviEvent',
5917 list($custom_pre_id,
5919 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
5921 $values['custom_pre_id'] = $custom_pre_id;
5922 $values['custom_post_id'] = $custom_post_ids;
5924 // set lineItem for event contribution
5925 if ($contributionID) {
5926 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($contributionID);
5927 if (!empty($participantIds)) {
5928 foreach ($participantIds as $pIDs) {
5929 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
5930 if (!CRM_Utils_System
::isNull($lineItem)) {
5931 $values['lineItem'][] = $lineItem;