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 +--------------------------------------------------------------------+
12 use Civi\Api4\Activity
;
13 use Civi\Api4\ContributionPage
;
14 use Civi\Api4\ContributionRecur
;
15 use Civi\Api4\Participant
;
16 use Civi\Api4\PaymentProcessor
;
21 * @copyright CiviCRM LLC https://civicrm.org/licensing
23 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
26 * Static field for all the contribution information that we can potentially import
30 public static $_importableFields = NULL;
33 * Static field for all the contribution information that we can potentially export
37 public static $_exportableFields = NULL;
40 * Static field to hold financial trxn id's.
44 public static $_trxnIDs = NULL;
47 * Field for all the objects related to this contribution.
50 * 1) deprecated function transitionComponents
51 * 2) function to send contribution receipts _assignMessageVariablesToTemplate
52 * 3) some invoice code that is copied from 2
53 * 4) odds & sods that need to be investigated and fixed.
55 * However, it is no longer used by completeOrder.
57 * @var \CRM_Member_BAO_Membership|\CRM_Event_BAO_Participant[]
61 public $_relatedObjects = [];
64 * Field for the component - either 'event' (participant) or 'contribute'
65 * (any item related to a contribution page e.g. membership, pledge, contribution)
66 * This is used for composing messages because they have dependency on the
67 * contribution_page or event page - although over time we may eliminate that
70 * "contribution"\"event"
72 public $_component = NULL;
75 * Possibly obsolete variable.
77 * If you use it please explain why it is set in the create function here.
81 public $trxn_result_code;
86 public function __construct() {
87 parent
::__construct();
91 * Takes an associative array and creates a contribution object.
93 * the function extract all the params it needs to initialize the create a
94 * contribution object. the params array could contain additional unused name/value
97 * @param array $params
98 * (reference ) an assoc array of name/value pairs.
100 * @return \CRM_Contribute_BAO_Contribution
101 * @throws \CRM_Core_Exception
102 * @throws \CiviCRM_API3_Exception
104 public static function add(&$params) {
105 if (empty($params)) {
109 $contributionID = $params['id'] ??
NULL;
110 $action = $contributionID ?
'edit' : 'create';
112 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
113 $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)]);
114 throw new CRM_Core_Exception($message);
117 //set defaults in create mode
118 if (!$contributionID) {
119 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
120 if (empty($params['invoice_number']) && CRM_Invoicing_Utils
::isInvoicingEnabled()) {
121 $nextContributionID = CRM_Core_DAO
::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
122 $params['invoice_number'] = self
::getInvoiceNumber($nextContributionID);
126 $contributionStatusID = $params['contribution_status_id'] ??
NULL;
127 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $contributionStatusID) === 'Partially paid' && empty($params['is_post_payment_create'])) {
128 CRM_Core_Error
::deprecatedFunctionWarning('Setting status to partially paid other than by using Payment.create is deprecated and unreliable');
130 if (!$contributionStatusID) {
131 // Since the fee amount is expecting this (later on) ensure it is always set.
132 // It would only not be set for an update where it is unchanged.
133 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', [
134 'id' => $contributionID,
135 'return' => 'contribution_status_id',
138 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['contribution_status_id']);
141 && !empty($params['membership_id'])
142 && Civi
::settings()->get('deferred_revenue_enabled')
144 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
145 if ($memberStartDate) {
146 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
149 self
::calculateMissingAmountParams($params, $contributionID);
151 if (!empty($params['payment_instrument_id'])) {
152 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
153 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
154 $params['check_number'] = 'null';
158 $setPrevContribution = TRUE;
159 if ($contributionID && $setPrevContribution) {
160 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
162 $previousContributionStatus = ($contributionID && !empty($params['prevContribution'])) ? CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['prevContribution']->contribution_status_id
) : NULL;
164 if ($contributionID && !empty($params['revenue_recognition_date'])
165 && !($previousContributionStatus === 'Pending')
166 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
168 unset($params['revenue_recognition_date']);
171 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
172 isset($params['financial_type_id']))) {
173 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
176 CRM_Utils_Hook
::pre($action, 'Contribution', $contributionID, $params);
178 $contribution = new CRM_Contribute_BAO_Contribution();
179 $contribution->copyValues($params);
181 $contribution->id
= $contributionID;
183 if (empty($contribution->id
)) {
184 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
185 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
186 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
190 $result = $contribution->save();
192 // Add financial_trxn details as part of fix for CRM-4724
193 $contribution->trxn_result_code
= $params['trxn_result_code'] ??
NULL;
194 $contribution->payment_processor
= $params['payment_processor'] ??
NULL;
196 //add Account details
197 $params['contribution'] = $contribution;
198 if (empty($params['is_post_payment_create'])) {
199 // If this is being called from the Payment.create api/ BAO then that Entity
200 // takes responsibility for the financial transactions. In fact calling Payment.create
201 // to add payments & having it call completetransaction and / or contribution.create
202 // to update related entities is the preferred flow.
203 // Note that leveraging this parameter for any other code flow is not supported and
204 // is likely to break in future and / or cause serious problems in your data.
205 // https://github.com/civicrm/civicrm-core/pull/14673
206 self
::recordFinancialAccounts($params);
209 if (self
::isUpdateToRecurringContribution($params)) {
210 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
211 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
213 $params['receive_date'] ??
NULL
217 $params['contribution_id'] = $contribution->id
;
219 if (!empty($params['custom']) &&
220 is_array($params['custom'])
222 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
, $action);
225 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
227 CRM_Utils_Hook
::post($action, 'Contribution', $contribution->id
, $contribution);
232 * Is this contribution updating an existing recurring contribution.
234 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
235 * pending payment is being confirmed (or failing).
237 * @param array $params
241 public static function isUpdateToRecurringContribution($params) {
242 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
245 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
248 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
251 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
252 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
259 * Get defaults for new entity.
263 public static function getDefaults() {
265 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
266 FALSE, FALSE, FALSE, 'AND is_default = 1')
268 'contribution_status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
269 'receive_date' => date('Y-m-d H:i:s'),
274 * Fetch the object and store the values in the values array.
276 * @param array $params
277 * Input parameters to find object.
278 * @param array $values
279 * Output values of the object.
281 * The array that holds all the db ids.
283 * @return CRM_Contribute_BAO_Contribution|null
284 * The found object or null
286 public static function getValues($params, &$values = [], &$ids = []) {
287 if (empty($params)) {
290 $contribution = new CRM_Contribute_BAO_Contribution();
292 $contribution->copyValues($params);
294 if ($contribution->find(TRUE)) {
295 $ids['contribution'] = $contribution->id
;
297 CRM_Core_DAO
::storeValues($contribution, $values);
299 return $contribution;
301 // return by reference
307 * Get the values and resolve the most common mappings.
309 * Since contribution status is resolved in almost every function that calls getValues it makes
310 * sense to have an extra function to resolve it rather than repeat the code.
312 * Think carefully before adding more mappings to be resolved as there could be performance implications
313 * if this function starts to be called from more iterative functions.
315 * @param array $params
316 * Input parameters to find object.
319 * Array of the found contribution.
320 * @throws CRM_Core_Exception
322 public static function getValuesWithMappings($params) {
324 $contribution = self
::getValues($params, $values, $ids);
325 if (is_null($contribution)) {
326 throw new CRM_Core_Exception('No contribution found');
328 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
333 * Calculate net_amount & fee_amount if they are not set.
335 * Net amount should be total - fee.
336 * This should only be called for new contributions.
338 * @param array $params
339 * Params for a new contribution before they are saved.
340 * @param int|null $contributionID
341 * Contribution ID if we are dealing with an update.
343 * @throws \CiviCRM_API3_Exception
345 public static function calculateMissingAmountParams(&$params, $contributionID) {
346 if (!$contributionID && !isset($params['fee_amount'])) {
347 if (isset($params['total_amount']) && isset($params['net_amount'])) {
348 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
351 $params['fee_amount'] = 0;
354 if (!isset($params['net_amount'])) {
355 if (!$contributionID) {
356 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
359 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
360 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
361 // net_amount may need adjusting.
362 $contribution = civicrm_api3('Contribution', 'getsingle', [
363 'id' => $contributionID,
364 'return' => ['total_amount', 'net_amount', 'fee_amount'],
366 $totalAmount = (isset($params['total_amount']) ?
(float) $params['total_amount'] : (float) CRM_Utils_Array
::value('total_amount', $contribution));
367 $feeAmount = (isset($params['fee_amount']) ?
(float) $params['fee_amount'] : (float) CRM_Utils_Array
::value('fee_amount', $contribution));
368 $params['net_amount'] = $totalAmount - $feeAmount;
376 * @param $billingLocationTypeID
380 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
381 $hasBillingField = FALSE;
390 //build address array
392 $addressParams['location_type_id'] = $billingLocationTypeID;
393 $addressParams['is_billing'] = 1;
395 $billingFirstName = $params['billing_first_name'] ??
NULL;
396 $billingMiddleName = $params['billing_middle_name'] ??
NULL;
397 $billingLastName = $params['billing_last_name'] ??
NULL;
398 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
400 foreach ($billingFields as $value) {
401 $addressParams[$value] = $params["billing_{$value}-{$billingLocationTypeID}"] ??
NULL;
402 if (!empty($addressParams[$value])) {
403 $hasBillingField = TRUE;
406 return [$hasBillingField, $addressParams];
410 * Get address params ready to be passed to the payment processor.
412 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
413 * To create an address we need state_province_id.
415 * @param array $params
416 * @param int $billingLocationTypeID
420 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
421 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
422 foreach ($addressParams as $name => $field) {
423 if (substr($name, 0, 8) == 'billing_') {
424 $addressParams[substr($name, 9)] = $addressParams[$field];
427 return [$hasBillingField, $addressParams];
431 * Get the number of terms for this contribution for a given membership type
432 * based on querying the line item table and relevant price field values
433 * Note that any one contribution should only be able to have one line item relating to a particular membership
436 * @param int $membershipTypeID
438 * @param int $contributionID
442 public static function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
443 $numTerms = CRM_Core_DAO
::singleValueQuery("
444 SELECT membership_num_terms FROM civicrm_line_item li
445 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
446 WHERE contribution_id = %1 AND membership_type_id = %2",
447 [1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']]
449 // default of 1 is precautionary
450 return empty($numTerms) ?
1 : $numTerms;
454 * Takes an associative array and creates a contribution object.
456 * @param array $params
457 * (reference ) an assoc array of name/value pairs.
459 * @return CRM_Contribute_BAO_Contribution
461 * @throws \API_Exception
462 * @throws \CRM_Core_Exception
463 * @throws \CiviCRM_API3_Exception
465 public static function create(&$params) {
467 $transaction = new CRM_Core_Transaction();
470 $contribution = self
::add($params);
472 catch (CRM_Core_Exception
$e) {
473 $transaction->rollback();
477 $params['contribution_id'] = $contribution->id
;
478 $session = CRM_Core_Session
::singleton();
480 if (!empty($params['note'])) {
482 'entity_table' => 'civicrm_contribution',
483 'note' => $params['note'],
484 'entity_id' => $contribution->id
,
485 'contact_id' => $session->get('userID'),
487 if (!$noteParams['contact_id']) {
488 $noteParams['contact_id'] = $params['contact_id'];
490 CRM_Core_BAO_Note
::add($noteParams);
493 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
495 $transaction->commit();
497 if (empty($contribution->contact_id
)) {
498 $contribution->find(TRUE);
501 $isCompleted = ('Completed' === CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
));
502 if (!empty($params['on_behalf'])
505 $existingActivity = Activity
::get(FALSE)->setWhere([
506 ['source_record_id', '=', $contribution->id
],
507 ['activity_type_id:name', '=', 'Contribution'],
508 ])->execute()->first();
510 $campaignParams = isset($params['campaign_id']) ?
['campaign_id' => ($params['campaign_id'] ??
NULL)] : [];
511 Activity
::save(FALSE)->addRecord(array_merge([
512 'activity_type_id:name' => 'Contribution',
513 'source_record_id' => $contribution->id
,
514 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ?
: $contribution->contact_id
,
515 'target_contact_id' => CRM_Core_Session
::getLoggedInContactID() ?
[$contribution->contact_id
] : [],
516 'activity_date_time' => $contribution->receive_date
,
517 'is_test' => (bool) $contribution->is_test
,
518 'status_id:name' => $isCompleted ?
'Completed' : 'Scheduled',
519 'skipRecentView' => TRUE,
520 'subject' => CRM_Activity_BAO_Activity
::getActivitySubject($contribution),
521 'id' => $existingActivity['id'] ??
NULL,
522 ], $campaignParams))->execute();
525 // do not add to recent items for import, CRM-4399
526 if (empty($params['skipRecentView'])) {
527 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
528 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
530 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
537 $retrieveRequired = 0;
538 foreach ($titleFields as $titleField) {
539 if (!isset($contribution->$titleField)) {
540 $retrieveRequired = 1;
544 if ($retrieveRequired == 1) {
545 $contribution->find(TRUE);
547 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
548 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
551 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
552 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
553 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
557 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
558 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
559 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
563 // add the recently created Contribution
564 CRM_Utils_Recent
::add($title,
568 $contribution->contact_id
,
574 return $contribution;
578 * Get the values for pseudoconstants for name->value and reverse.
580 * @param array $defaults
581 * (reference) the default values, some of which need to be resolved.
582 * @param bool $reverse
583 * True if we want to resolve the values in the reverse direction (value -> name).
585 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
586 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
587 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
588 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'), $reverse);
589 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
593 * Convert associative array names to values and vice-versa.
595 * This function is used by both the web form layer and the api. Note that
596 * the api needs the name => value conversion, also the view layer typically
597 * requires value => name conversion
599 * @param array $defaults
600 * @param string $property
601 * @param array $lookup
602 * @param bool $reverse
606 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
607 $id = $property . '_id';
609 $src = $reverse ?
$property : $id;
610 $dst = $reverse ?
$id : $property;
612 if (!array_key_exists($src, $defaults)) {
616 $look = $reverse ?
array_flip($lookup) : $lookup;
618 if (is_array($look)) {
619 if (!array_key_exists($defaults[$src], $look)) {
623 $defaults[$dst] = $look[$defaults[$src]];
628 * Retrieve DB object based on input parameters.
630 * It also stores all the retrieved values in the default array.
632 * @param array $params
633 * (reference ) an assoc array of name/value pairs.
634 * @param array $defaults
635 * (reference ) an assoc array to hold the name / value pairs.
636 * in a hierarchical manner
638 * (reference) the array that holds all the db ids.
640 * @return CRM_Contribute_BAO_Contribution
642 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
643 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
644 return $contribution;
648 * Combine all the importable fields from the lower levels object.
650 * The ordering is important, since currently we do not have a weight
651 * scheme. Adding weight is super important and should be done in the
652 * next week or so, before this can be called complete.
654 * @param string $contactType
655 * @param bool $status
658 * array of importable Fields
660 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
661 if (!self
::$_importableFields) {
662 if (!self
::$_importableFields) {
663 self
::$_importableFields = [];
667 $fields = ['' => ['title' => ts('- do not import -')]];
670 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
673 $note = CRM_Core_DAO_Note
::import();
674 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
675 unset($tmpFields['option_value']);
676 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
677 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
679 // Using new Dedupe rule.
681 'contact_type' => $contactType,
682 'used' => 'Unsupervised',
684 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
685 $tmpContactField = [];
686 if (is_array($fieldsArray)) {
687 foreach ($fieldsArray as $value) {
688 //skip if there is no dupe rule
689 if ($value == 'none') {
692 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
697 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
698 $tmpContactField[trim($value)] = $contactFields[trim($value)];
700 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
703 $title = $tmpContactField[trim($value)]['title'];
705 $tmpContactField[trim($value)]['title'] = $title;
709 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
710 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
711 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
712 $fields = array_merge($fields, $tmpContactField);
713 $fields = array_merge($fields, $tmpFields);
714 $fields = array_merge($fields, $note);
715 $fields = array_merge($fields, $optionFields);
716 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
717 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
718 self
::$_importableFields = $fields;
720 return self
::$_importableFields;
724 * Combine all the exportable fields from the lower level objects.
726 * @param bool $checkPermission
729 * array of exportable Fields
731 public static function &exportableFields($checkPermission = TRUE) {
732 if (!self
::$_exportableFields) {
733 if (!self
::$_exportableFields) {
734 self
::$_exportableFields = [];
737 $fields = CRM_Contribute_DAO_Contribution
::export();
738 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
739 $fields = array_merge(
741 CRM_Contribute_DAO_Product
::export(),
742 CRM_Contribute_DAO_ContributionProduct
::export(),
743 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
745 'contribution_product_id' => [
746 'title' => ts('Premium'),
747 'name' => 'contribution_product_id',
748 'where' => 'civicrm_product.id',
749 'data_type' => CRM_Utils_Type
::T_INT
,
755 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
757 $contributionPage = [
758 'contribution_page' => [
759 'title' => ts('Contribution Page'),
760 'name' => 'contribution_page',
761 'where' => 'civicrm_contribution_page.title',
762 'data_type' => CRM_Utils_Type
::T_STRING
,
766 $contributionNote = [
767 'contribution_note' => [
768 'title' => ts('Contribution Note'),
769 'name' => 'contribution_note',
770 'data_type' => CRM_Utils_Type
::T_TEXT
,
775 'contribution_batch' => [
776 'title' => ts('Batch Name'),
782 'contribution_campaign_title' => [
783 'title' => ts('Campaign Title'),
784 'name' => 'campaign_title',
785 'where' => 'civicrm_campaign.title',
786 'data_type' => CRM_Utils_Type
::T_STRING
,
789 $softCreditFields = [
790 'contribution_soft_credit_name' => [
791 'name' => 'contribution_soft_credit_name',
792 'title' => ts('Soft Credit For'),
793 'where' => 'civicrm_contact_d.display_name',
794 'data_type' => CRM_Utils_Type
::T_STRING
,
796 'contribution_soft_credit_amount' => [
797 'name' => 'contribution_soft_credit_amount',
798 'title' => ts('Soft Credit Amount'),
799 'where' => 'civicrm_contribution_soft.amount',
800 'data_type' => CRM_Utils_Type
::T_MONEY
,
802 'contribution_soft_credit_type' => [
803 'name' => 'contribution_soft_credit_type',
804 'title' => ts('Soft Credit Type'),
805 'where' => 'contribution_softcredit_type.label',
806 'data_type' => CRM_Utils_Type
::T_STRING
,
808 'contribution_soft_credit_contribution_id' => [
809 'name' => 'contribution_soft_credit_contribution_id',
810 'title' => ts('Soft Credit For Contribution ID'),
811 'where' => 'civicrm_contribution_soft.contribution_id',
812 'data_type' => CRM_Utils_Type
::T_INT
,
814 'contribution_soft_credit_contact_id' => [
815 'name' => 'contribution_soft_credit_contact_id',
816 'title' => ts('Soft Credit For Contact ID'),
817 'where' => 'civicrm_contact_d.id',
818 'data_type' => CRM_Utils_Type
::T_INT
,
822 $fields = array_merge($fields, $contributionPage,
823 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
824 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
827 self
::$_exportableFields = $fields;
830 return self
::$_exportableFields;
834 * Record an activity when a payment is received.
836 * @todo this is intended to be moved to payment BAO class as a protected function
837 * on that class. Currently being cleaned up. The addActivityForPayment doesn't really
838 * merit it's own function as it makes the code less rather than more readable.
840 * @param int $contributionId
841 * @param int $participantId
842 * @param string $totalAmount
843 * @param string $currency
844 * @param string $trxnDate
846 * @throws \CRM_Core_Exception
847 * @throws \CiviCRM_API3_Exception
849 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
850 $activityType = ($totalAmount < 0) ?
'Refund' : 'Payment';
852 if ($participantId) {
853 $inputParams['id'] = $participantId;
856 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
857 $entityObj = $entityObj[$participantId];
858 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
861 $entityObj = new CRM_Contribute_BAO_Contribution();
862 $entityObj->id
= $contributionId;
863 $entityObj->find(TRUE);
864 $title = ts('Contribution');
866 // @todo per block above this is not a logical splitting off of functionality.
867 self
::addActivityForPayment($entityObj->contact_id
, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
871 * Get the value for the To Financial Account.
873 * @param $contribution
878 public static function getToFinancialAccount($contribution, $params) {
879 if (!empty($params['payment_processor_id'])) {
880 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor_id'], NULL, 'civicrm_payment_processor');
882 if (!empty($params['payment_instrument_id'])) {
883 return CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
886 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
887 $queryParams = [1 => [$relationTypeId, 'Integer']];
888 return CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
893 * Get memberships related to the contribution.
895 * @param int $contributionID
899 protected static function getRelatedMemberships($contributionID) {
900 $membershipPayments = civicrm_api3('MembershipPayment', 'get', [
901 'return' => 'membership_id',
902 'contribution_id' => (int) $contributionID,
905 foreach ($membershipPayments as $membershipPayment) {
906 $membershipIDs[] = $membershipPayment['membership_id'];
908 if (empty($membershipIDs)) {
911 // We could combine this with the MembershipPayment.get - we'd
912 // need to re-wrangle the params (here or in the calling function)
913 // as they would then me membership.contact_id, membership.is_test etc
914 return civicrm_api3('Membership', 'get', [
915 'id' => ['IN' => $membershipIDs],
916 'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'],
921 * Cancel contribution.
923 * This function should only be called from transitioncomponents - it is an interim step in refactoring.
925 * @param $memberships
926 * @param $contributionId
927 * @param $membershipStatuses
928 * @param $participant
930 * @param $pledgePayment
932 * @param $pledgePaymentIDs
933 * @param $contributionStatusId
935 protected static function cancel($memberships, $contributionId, $membershipStatuses, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId) {
936 // @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
937 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
939 $updatedStatusId = array_search('Cancelled', $participantStatuses);
940 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
943 if ($pledgePayment) {
944 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
949 * Do any accounting updates required as a result of a contribution status change.
951 * Currently we have a bit of a roundabout where adding a payment results in this being called &
952 * this may attempt to add a payment. We need to resolve that....
954 * The 'right' way to add payments or refunds is through the Payment.create api. That api
955 * then updates the contribution but this process should not also record another financial trxn.
956 * Currently we have weak detection fot that scenario & where it is detected the first returned
957 * value is FALSE - meaning 'do not continue'.
959 * We should also look at the fact that the calling function - updateFinancialAccounts
960 * bunches together some disparate processes rather than having separate appropriate
963 * @param array $params
966 * Return indicates whether the updateFinancialAccounts function should continue.
968 private static function updateFinancialAccountsOnContributionStatusChange(&$params) {
969 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
970 $currentContributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
972 if ((($previousContributionStatus == 'Partially paid' && $currentContributionStatus == 'Completed')
973 ||
($previousContributionStatus == 'Pending refund' && $currentContributionStatus == 'Completed')
974 // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
975 // why it is here or where it is handled instead.
976 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
977 && $currentContributionStatus == 'Partially paid'))
982 if (self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
)) {
983 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
984 $params['trxnParams']['total_amount'] = -$params['total_amount'];
986 elseif (($previousContributionStatus == 'Pending'
987 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
989 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
990 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
992 if ($currentContributionStatus == 'Cancelled') {
993 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
994 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
995 $params['trxnParams']['total_amount'] = -$params['total_amount'];
998 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
999 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
1003 if (($previousContributionStatus == 'Pending'
1004 ||
$previousContributionStatus == 'In Progress')
1005 && ($currentContributionStatus == 'Completed')
1007 if (empty($params['line_item'])) {
1009 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
1010 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
1011 // & this can be removed
1014 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1015 // This is an update so original currency if none passed in.
1016 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
1018 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
1019 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
1020 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1021 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
1023 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
1026 'entity_table' => 'civicrm_financial_item',
1028 foreach ($params['line_item'] as $fieldId => $fields) {
1029 foreach ($fields as $fieldValueId => $lineItemDetails) {
1030 self
::updateFinancialItemForLineItemToPaid($lineItemDetails['id']);
1032 1 => [$lineItemDetails['id'], 'Integer'],
1034 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
1035 while ($financialItem->fetch()) {
1036 $entityParams['entity_id'] = $financialItem->id
;
1037 $entityParams['amount'] = $financialItem->amount
;
1038 foreach (self
::$_trxnIDs as $tID) {
1039 $entityParams['financial_trxn_id'] = $tID;
1040 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
1051 * It is possible to override the membership id that is updated from the payment processor.
1053 * Historically Paypal does this & it still does if it determines data is messed up - see
1054 * https://lab.civicrm.org/dev/membership/issues/13
1056 * Read the comment block on repeattransaction for more information
1057 * about how things should work.
1059 * @param int $contributionID
1060 * @param array $input
1062 * @throws \CiviCRM_API3_Exception
1064 protected static function handleMembershipIDOverride($contributionID, $input) {
1065 if (!empty($input['membership_id'])) {
1066 Civi
::log()->debug('The related membership id has been overridden - this may impact data - see https://github.com/civicrm/civicrm-core/pull/15053');
1067 civicrm_api3('MembershipPayment', 'create', ['contribution_id' => $contributionID, 'membership_id' => $input['membership_id']]);
1072 * Update all financial items related to the line item tto have a status of paid.
1074 * @param int $lineItemID
1076 private static function updateFinancialItemForLineItemToPaid($lineItemID) {
1079 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1082 2 => [$lineItemID, 'Integer'],
1084 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
1085 CRM_Core_DAO
::executeQuery($query, $fparams);
1089 * Create the financial items for the line.
1091 * @param array $params
1092 * @param string $context
1093 * @param array $fields
1094 * @param array $previousLineItems
1095 * @param array $inputParams
1096 * @param bool $isARefund
1097 * @param array $trxnIds
1098 * @param int $fieldId
1102 private static function createFinancialItemsForLine($params, $context, $fields, array $previousLineItems, array $inputParams, bool $isARefund, $trxnIds, $fieldId): array {
1103 foreach ($fields as $fieldValueId => $lineItemDetails) {
1104 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($lineItemDetails['id']);
1105 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
1106 if ($params['contribution']->receive_date
) {
1107 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
1110 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array
::value('financial_account_id', $prevFinancialItem));
1112 $currency = $params['prevContribution']->currency
;
1113 if ($params['contribution']->currency
) {
1114 $currency = $params['contribution']->currency
;
1116 $previousLineItemTotal = CRM_Utils_Array
::value('line_total', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1118 'transaction_date' => $receiveDate,
1119 'contact_id' => $params['prevContribution']->contact_id
,
1120 'currency' => $currency,
1121 'amount' => self
::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
1122 'description' => $prevFinancialItem['description'] ??
NULL,
1123 'status_id' => $prevFinancialItem['status_id'],
1124 'financial_account_id' => $financialAccount,
1125 'entity_table' => 'civicrm_line_item',
1126 'entity_id' => $lineItemDetails['id'],
1128 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1129 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
1130 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
1132 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') ||
($context == 'changeFinancialType')) {
1133 $taxAmount = (float) $lineItemDetails['tax_amount'];
1134 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
1135 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
1136 $taxAmount = CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1138 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
1139 $taxAmount -= CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1141 if ($taxAmount != 0) {
1142 $itemParams['amount'] = self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * $taxAmount;
1143 $itemParams['description'] = CRM_Invoicing_Utils
::getTaxTerm();
1144 if ($lineItemDetails['financial_type_id']) {
1145 $itemParams['financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getSalesTaxFinancialAccount($lineItemDetails['financial_type_id']);
1147 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1155 * Does this contributtion status update represent a refund.
1157 * @param int $previousContributionStatusID
1158 * @param int $currentContributionStatusID
1162 private static function isContributionUpdateARefund($previousContributionStatusID, $currentContributionStatusID): bool {
1163 if ('Completed' !== CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $previousContributionStatusID)) {
1166 return self
::isContributionStatusNegative($currentContributionStatusID);
1170 * Get transaction information about the contribution.
1172 * @param int $contributionId
1173 * @param int $financialTypeID
1177 protected static function getContributionTransactionInformation($contributionId, int $financialTypeID) {
1179 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Expense Account is');
1181 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
1183 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
1185 ft.payment_instrument_id,
1186 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
1188 FROM civicrm_contribution con
1189 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
1190 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
1191 AND ft.to_financial_account_id != %2
1192 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
1193 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
1194 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
1196 WHERE con.id = %1 AND ft.is_payment = 1
1199 1 => [$contributionId, 'Integer'],
1200 2 => [$feeFinancialAccount, 'Integer'],
1202 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
1203 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label');
1205 while ($resultDAO->fetch()) {
1206 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1207 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1208 if ($resultDAO->card_type_id
) {
1209 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
1210 $pantruncation = '';
1211 if ($resultDAO->pan_truncation
) {
1212 $pantruncation = ": {$resultDAO->pan_truncation}";
1214 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
1217 // show payment edit link only for payments done via backoffice form
1218 $paymentEditLink = '';
1219 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
1221 CRM_Core_Action
::UPDATE
=> [
1222 'name' => ts('Edit Payment'),
1223 'icon' => 'fa-pencil',
1224 'url' => 'civicrm/payment/edit',
1225 'class' => 'medium-popup',
1226 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
1227 'title' => ts('Edit Payment'),
1230 $paymentEditLink = CRM_Core_Action
::formLink(
1232 CRM_Core_Action
::mask([CRM_Core_Permission
::EDIT
]),
1234 'id' => $resultDAO->id
,
1235 'contribution_id' => $contributionId,
1239 'Payment.edit.action',
1247 'id' => $resultDAO->id
,
1248 'total_amount' => $resultDAO->total_amount
,
1249 'financial_type' => $resultDAO->financial_account
,
1250 'payment_instrument' => $paidByLabel,
1251 'receive_date' => $resultDAO->trxn_date
,
1252 'trxn_id' => $resultDAO->trxn_id
,
1253 'status' => $statuses[$resultDAO->status_id
],
1254 'currency' => $resultDAO->currency
,
1255 'action' => $paymentEditLink,
1257 if ($paidByName == 'Check') {
1258 $val['check_number'] = $resultDAO->check_number
;
1266 * Should an email receipt be sent for this contribution on completion.
1268 * @param array $input
1269 * @param int $contributionPageID
1270 * @param int $recurringContributionID
1273 * @throws \API_Exception
1274 * @throws \Civi\API\Exception\UnauthorizedException
1276 protected static function isEmailReceipt(array $input, $contributionPageID, $recurringContributionID): bool {
1277 if (isset($input['is_email_receipt'])) {
1278 return (bool) $input['is_email_receipt'];
1280 if ($recurringContributionID) {
1281 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
1282 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
1283 // 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
1284 // Instance that had the table added via an upgrade in 4.1
1285 // see also https://github.com/civicrm/civicrm-svn/commit/7f39befd60bc735408d7866b02b3ac7fff1d4eea#diff-9ad8e290180451a2d6eacbd3d1ca7966R354
1286 // https://lab.civicrm.org/dev/core/issues/1245
1287 return (bool) ContributionRecur
::get(FALSE)->addWhere('id', '=', $recurringContributionID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt'];
1289 if ($contributionPageID) {
1290 return (bool) ContributionPage
::get(FALSE)->addWhere('id', '=', $contributionPageID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt'];
1292 // This would be the case for backoffice (where is_email_receipt is not passed in) or events, where Event::sendMail will filter
1298 * Process failed contribution.
1300 * @param $memberships
1301 * @param $contributionId
1302 * @param array $membershipStatuses
1303 * @param $participant
1304 * @param $pledgePayment
1306 * @param array $pledgePaymentIDs
1307 * @param $contributionStatusId
1309 * @throws \CRM_Core_Exception
1311 protected static function processFail($memberships, $contributionId, array $membershipStatuses, array $participant, $pledgePayment, $pledgeID, array $pledgePaymentIDs, $contributionStatusId): void
{
1312 if (is_array($memberships)) {
1313 foreach ($memberships as $membership) {
1315 //Update Membership status if there is no other completed contribution associated with the membership.
1316 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1317 foreach ($relatedContributions as $contriId) {
1318 if ($contriId == $contributionId) {
1321 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1322 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1326 if ($membership && $update) {
1327 $membership->status_id
= array_search('Expired', $membershipStatuses);
1328 $membership->is_override
= TRUE;
1329 $membership->status_override_end_date
= 'null';
1330 $membership->save();
1335 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1339 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1340 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1341 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1344 if ($pledgePayment) {
1345 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1352 public function addSelectWhereClause() {
1353 $whereClauses = parent
::addSelectWhereClause();
1354 if ($whereClauses !== []) {
1355 // In this case permisssions have been applied & we assume the
1356 // financialaclreport is applying these
1357 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
1358 return $whereClauses;
1361 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1362 return $whereClauses;
1364 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
1365 if (empty($types)) {
1366 $whereClauses['financial_type_id'] = 'IN (0)';
1369 $whereClauses['financial_type_id'] = [
1370 'IN (' . implode(',', array_keys($types)) . ')',
1373 return $whereClauses;
1377 * @param null $status
1378 * @param null $startDate
1379 * @param null $endDate
1381 * @return array|null
1383 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1387 $where[] = 'contribution_status_id = 1';
1391 $where[] = 'contribution_status_id = 3';
1396 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
1399 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
1401 $financialTypeACLJoin = '';
1402 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1403 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1404 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
1405 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1406 if ($financialTypes) {
1407 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1408 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1411 $where[] = "c.financial_type_id IN (0)";
1415 $whereCond = implode(' AND ', $where);
1418 SELECT sum( total_amount ) as total_amount,
1419 count( c.id ) as total_count,
1421 FROM civicrm_contribution c
1422 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1423 $financialTypeACLJoin
1425 AND ( is_test = 0 OR is_test IS NULL )
1426 AND contact.is_deleted = 0
1430 $dao = CRM_Core_DAO
::executeQuery($query);
1433 while ($dao->fetch()) {
1434 $count +
= $dao->total_count
;
1435 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
1439 'amount' => implode(', ', $amount),
1447 * Delete the indirect records associated with this contribution first.
1451 * @return mixed|null
1452 * $results no of deleted Contribution on success, false otherwise
1454 public static function deleteContribution($id) {
1455 CRM_Utils_Hook
::pre('delete', 'Contribution', $id);
1457 $transaction = new CRM_Core_Transaction();
1460 //delete activity record
1462 'source_record_id' => $id,
1463 // activity type id for contribution
1464 'activity_type_id' => 6,
1467 CRM_Activity_BAO_Activity
::deleteActivity($params);
1469 //delete billing address if exists for this contribution.
1470 self
::deleteAddress($id);
1472 //update pledge and pledge payment, CRM-3961
1473 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1475 // remove entry from civicrm_price_set_entity, CRM-5095
1476 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1477 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1479 // cleanup line items.
1480 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1482 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1483 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1485 if ($participantId) {
1486 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1489 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1493 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1494 $noteId = key($note);
1496 CRM_Core_BAO_Note
::del($noteId, FALSE);
1499 $dao = new CRM_Contribute_DAO_Contribution();
1502 $results = $dao->delete();
1504 $transaction->commit();
1506 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1508 // delete the recently created Contribution
1509 $contributionRecent = [
1511 'type' => 'Contribution',
1513 CRM_Utils_Recent
::del($contributionRecent);
1519 * React to a financial transaction (payment) failure.
1521 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1522 * payments is important for forensic and outreach reasons.
1524 * @param int $contributionID
1525 * @param int $contactID
1526 * @param string $message
1528 * @throws \CiviCRM_API3_Exception
1530 public static function failPayment($contributionID, $contactID, $message) {
1531 civicrm_api3('activity', 'create', [
1532 'activity_type_id' => 'Failed Payment',
1533 'details' => $message,
1534 'subject' => ts('Payment failed at payment processor'),
1535 'source_record_id' => $contributionID,
1536 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() : $contactID,
1539 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1540 civicrm_api3('contribution', 'create', [
1541 'id' => $contributionID,
1542 'contribution_status_id' => 'Failed',
1547 * Check if there is a contribution with the same trxn_id or invoice_id.
1549 * @param array $input
1550 * An assoc array of name/value pairs.
1551 * @param array $duplicates
1552 * (reference) store ids of duplicate contribs.
1556 * true if duplicate, false otherwise
1558 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1560 $id = $input['id'] ??
NULL;
1562 $trxn_id = $input['trxn_id'] ??
NULL;
1563 $invoice_id = $input['invoice_id'] ??
NULL;
1569 $clause[] = "trxn_id = %1";
1570 $input[1] = [$trxn_id, 'String'];
1574 $clause[] = "invoice_id = %2";
1575 $input[2] = [$invoice_id, 'String'];
1578 if (empty($clause)) {
1582 $clause = implode(' OR ', $clause);
1584 $clause = "( $clause ) AND id != %3";
1585 $input[3] = [$id, 'Integer'];
1588 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1589 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1591 while ($dao->fetch()) {
1592 $duplicates[] = $dao->id
;
1599 * Takes an associative array and creates a contribution_product object.
1601 * the function extract all the params it needs to initialize the create a
1602 * contribution_product object. the params array could contain additional unused name/value
1605 * @param array $params
1606 * (reference) an assoc array of name/value pairs.
1608 * @return CRM_Contribute_DAO_ContributionProduct
1610 public static function addPremium(&$params) {
1611 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1612 $contributionProduct->copyValues($params);
1613 return $contributionProduct->save();
1617 * Get list of contribution fields for profile.
1618 * For now we only allow custom contribution fields to be in
1621 * @param bool $addExtraFields
1622 * True if special fields needs to be added.
1625 * the list of contribution fields
1627 public static function getContributionFields($addExtraFields = TRUE) {
1628 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1629 // @todo remove this - this line was added because payment_instrument_id was not
1630 // set to exportable - but now it is.
1631 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1633 if ($addExtraFields) {
1634 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1637 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1639 foreach ($contributionFields as $key => $var) {
1640 if ($key == 'contribution_contact_id') {
1643 elseif ($key == 'contribution_campaign_id') {
1644 $var['title'] = ts('Campaign');
1646 $fields[$key] = $var;
1649 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1654 * Add extra fields specific to contribution.
1656 public static function getSpecialContributionFields() {
1658 'contribution_soft_credit_name' => [
1659 'name' => 'contribution_soft_credit_name',
1660 'title' => ts('Soft Credit Name'),
1661 'headerPattern' => '/^soft_credit_name$/i',
1662 'where' => 'civicrm_contact_d.display_name',
1664 'contribution_soft_credit_email' => [
1665 'name' => 'contribution_soft_credit_email',
1666 'title' => ts('Soft Credit Email'),
1667 'headerPattern' => '/^soft_credit_email$/i',
1668 'where' => 'soft_email.email',
1670 'contribution_soft_credit_phone' => [
1671 'name' => 'contribution_soft_credit_phone',
1672 'title' => ts('Soft Credit Phone'),
1673 'headerPattern' => '/^soft_credit_phone$/i',
1674 'where' => 'soft_phone.phone',
1676 'contribution_soft_credit_contact_id' => [
1677 'name' => 'contribution_soft_credit_contact_id',
1678 'title' => ts('Soft Credit Contact ID'),
1679 'headerPattern' => '/^soft_credit_contact_id$/i',
1680 'where' => 'civicrm_contribution_soft.contact_id',
1682 'contribution_pcp_title' => [
1683 'name' => 'contribution_pcp_title',
1684 'title' => ts('Personal Campaign Page Title'),
1685 'headerPattern' => '/^contribution_pcp_title$/i',
1686 'where' => 'contribution_pcp.title',
1690 return $extraFields;
1694 * @param int $pageID
1698 public static function getCurrentandGoalAmount($pageID) {
1700 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1701 FROM civicrm_contribution_page p,
1702 civicrm_contribution c
1703 WHERE p.id = c.contribution_page_id
1705 AND c.cancel_date is null
1709 $config = CRM_Core_Config
::singleton();
1710 $params = [1 => [$pageID, 'Integer']];
1711 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1713 if ($dao->fetch()) {
1714 return [$dao->goal
, $dao->total
];
1717 return [NULL, NULL];
1722 * Get list of contributions which credit the passed in contact ID.
1724 * The returned array provides details about the original contribution & donor.
1726 * @param int $honorId
1727 * In Honor of Contact ID.
1730 * list of contribution fields
1731 * @todo - this is a confusing function called from one place. It has a test. It would be
1732 * nice to deprecate it.
1735 public static function getHonorContacts($honorId) {
1737 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1738 $honorDAO->contact_id
= $honorId;
1741 $type = CRM_Contribute_PseudoConstant
::financialType();
1743 while ($honorDAO->fetch()) {
1744 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1745 $contributionDAO->id
= $honorDAO->contribution_id
;
1747 if ($contributionDAO->find(TRUE)) {
1748 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1749 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1750 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1751 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1752 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1753 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1754 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1755 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1756 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
, 'label');
1764 * Get the sort name of a contact for a particular contribution.
1767 * Id of the contribution.
1769 * @return null|string
1770 * sort name of the contact if found
1772 public static function sortName($id) {
1773 $id = CRM_Utils_Type
::escape($id, 'Integer');
1776 SELECT civicrm_contact.sort_name
1777 FROM civicrm_contribution, civicrm_contact
1778 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1779 AND civicrm_contribution.id = {$id}
1781 return CRM_Core_DAO
::singleValueQuery($query);
1785 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1787 * @param int|array $contactIDs
1791 public static function annual($contactIDs) {
1792 if (!is_array($contactIDs)) {
1793 // In practice I can't fine any evidence that this function is ever called with
1794 // anything other than a single contact id, but left like this due to .... fear.
1795 $contactIDs = explode(',', $contactIDs);
1798 $query = self
::getAnnualQuery($contactIDs);
1799 $dao = CRM_Core_DAO
::executeQuery($query);
1801 $amount = $average = [];
1802 while ($dao->fetch()) {
1803 if ($dao->count
> 0 && $dao->amount
> 0) {
1804 $count +
= $dao->count
;
1805 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1806 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1812 implode(', ', $amount),
1813 implode(', ', $average),
1820 * Check if there is a contribution with the params passed in.
1822 * Used for trxn_id,invoice_id and contribution_id
1824 * @param array $params
1825 * An assoc array of name/value pairs.
1828 * contribution id if success else NULL
1830 public static function checkDuplicateIds($params) {
1831 $dao = new CRM_Contribute_DAO_Contribution();
1835 foreach ($params as $k => $v) {
1837 $clause[] = "$k = '$v'";
1840 $clause = implode(' AND ', $clause);
1841 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1842 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1844 while ($dao->fetch()) {
1852 * Get the contribution details for component export.
1854 * @param int $exportMode
1856 * @param array $componentIds
1862 public static function getContributionDetails($exportMode, $componentIds) {
1863 $paymentDetails = [];
1864 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1866 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1867 $componentSelect = " civicrm_participant_payment.participant_id id";
1868 $additionalClause = "
1869 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1870 AND civicrm_participant_payment.participant_id {$componentClause} )
1873 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1874 $componentSelect = " civicrm_membership_payment.membership_id id";
1875 $additionalClause = "
1876 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1877 AND civicrm_membership_payment.membership_id {$componentClause} )
1880 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1881 $componentSelect = " civicrm_pledge_payment.id id";
1882 $additionalClause = "
1883 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1884 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1888 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1889 trxn_id, {$componentSelect}
1890 FROM civicrm_contribution
1891 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1892 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1893 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1894 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1895 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1896 AND option_group_contribution_status.id = contribution_status.option_group_id )
1900 $dao = CRM_Core_DAO
::executeQuery($query);
1902 while ($dao->fetch()) {
1903 $paymentDetails[$dao->id
] = [
1904 'total_amount' => $dao->total_amount
,
1905 'contribution_status' => $dao->status
,
1906 'receive_date' => $dao->receive_date
,
1907 'pay_instru' => $dao->payment_instrument
,
1908 'trxn_id' => $dao->trxn_id
,
1912 return $paymentDetails;
1916 * Create address associated with contribution record.
1918 * As long as there is one or more billing field in the parameters we will create the address.
1920 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1923 * @param array $params
1924 * @param int $billingLocationTypeID
1929 public static function createAddress($params, $billingLocationTypeID) {
1930 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1931 if ($hasBillingField) {
1932 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1933 return $address->id
;
1940 * Delete billing address record related contribution.
1942 * @param int $contributionId
1943 * @param int $contactId
1945 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1947 $contactJoin = NULL;
1949 if ($contributionId) {
1950 $clauses[] = "cc.id = {$contributionId}";
1954 $clauses[] = "cco.id = {$contactId}";
1955 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1958 if (empty($clauses)) {
1959 throw new CRM_Core_Exception('No Where clauses defined when deleting address');
1962 $condition = implode(' OR ', $clauses);
1966 FROM civicrm_address ca
1967 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1971 $dao = CRM_Core_DAO
::executeQuery($query);
1973 while ($dao->fetch()) {
1974 $params = ['id' => $dao->id
];
1975 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1980 * This function check online pending contribution associated w/
1981 * Online Event Registration or Online Membership signup.
1983 * @param int $componentId
1984 * Participant/membership id.
1985 * @param string $componentName
1989 * pending contribution id.
1991 public static function checkOnlinePendingContribution($componentId, $componentName) {
1992 $contributionId = NULL;
1993 if (!$componentId ||
1994 !in_array($componentName, ['Event', 'Membership'])
1996 return $contributionId;
1999 if ($componentName == 'Event') {
2000 $idName = 'participant_id';
2001 $componentTable = 'civicrm_participant';
2002 $paymentTable = 'civicrm_participant_payment';
2003 $source = ts('Online Event Registration');
2006 if ($componentName == 'Membership') {
2007 $idName = 'membership_id';
2008 $componentTable = 'civicrm_membership';
2009 $paymentTable = 'civicrm_membership_payment';
2010 $source = ts('Online Contribution');
2013 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
2016 SELECT component.id as {$idName},
2017 componentPayment.contribution_id as contribution_id,
2018 contribution.source source,
2019 contribution.contribution_status_id as contribution_status_id,
2020 contribution.is_pay_later as is_pay_later
2021 FROM $componentTable component
2022 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
2023 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
2024 WHERE component.id = {$componentId}";
2026 $dao = CRM_Core_DAO
::executeQuery($query);
2028 while ($dao->fetch()) {
2029 if ($dao->contribution_id
&&
2030 $dao->is_pay_later
&&
2031 $dao->contribution_status_id
== $pendingStatusId &&
2032 strpos($dao->source
, $source) !== FALSE
2034 $contributionId = $dao->contribution_id
;
2038 return $contributionId;
2042 * Update contribution as well as related objects.
2044 * This function by-passes hooks - to address this - don't use this function.
2046 * @param array $params
2048 * @throws CRM_Core_Exception
2049 * @throws \CiviCRM_API3_Exception
2052 * Use api contribute.completetransaction
2053 * For failures use failPayment (preferably exposing by api in the process).
2056 public static function transitionComponents($params) {
2057 // get minimum required values.
2058 $contactId = $params['contact_id'] ??
NULL;
2059 $componentId = $params['component_id'] ??
NULL;
2060 $componentName = $params['componentName'] ??
NULL;
2061 $contributionId = $params['contribution_id'] ??
NULL;
2062 $contributionStatusId = $params['contribution_status_id'] ??
NULL;
2064 // if we already processed contribution object pass previous status id.
2065 $previousContriStatusId = $params['previous_contribution_status_id'] ??
NULL;
2067 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2069 // we process only ( Completed, Cancelled, or Failed ) contributions.
2070 if (!$contributionId ||
2071 !in_array($contributionStatusId, [
2072 array_search('Completed', $contributionStatuses),
2073 array_search('Cancelled', $contributionStatuses),
2074 array_search('Failed', $contributionStatuses),
2080 if (!$componentName ||
!$componentId) {
2081 // get the related component details.
2082 $componentDetails = self
::getComponentDetails($contributionId);
2085 $componentDetails['contact_id'] = $contactId;
2086 $componentDetails['component'] = $componentName;
2088 if ($componentName == 'event') {
2089 $componentDetails['participant'] = $componentId;
2092 $componentDetails['membership'] = $componentId;
2096 if (!empty($componentDetails['contact_id'])) {
2097 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2103 // do check for required ids.
2104 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
2110 $input['component'] = $componentDetails['component'] ??
NULL;
2111 $ids['contribution'] = $contributionId;
2112 $ids['contact'] = $componentDetails['contact_id'] ??
NULL;
2113 $ids['membership'] = $componentDetails['membership'] ??
NULL;
2114 $ids['participant'] = $componentDetails['participant'] ??
NULL;
2115 $ids['event'] = $componentDetails['event'] ??
NULL;
2116 $ids['pledge_payment'] = $componentDetails['pledge_payment'] ??
NULL;
2117 $ids['contributionRecur'] = NULL;
2118 $ids['contributionPage'] = NULL;
2120 $contribution = new CRM_Contribute_BAO_Contribution();
2121 $contribution->id
= $ids['contribution'];
2122 $contribution->find();
2124 $contribution->loadRelatedObjects($input, $ids);
2126 $memberships = $contribution->_relatedObjects
['membership'] ??
[];
2127 $participant = $contribution->_relatedObjects
['participant'] ??
[];
2128 $pledgePayment = $contribution->_relatedObjects
['pledge_payment'] ??
[];
2130 $pledgeID = $oldStatus = NULL;
2131 $pledgePaymentIDs = [];
2132 if ($pledgePayment) {
2133 foreach ($pledgePayment as $key => $object) {
2134 $pledgePaymentIDs[] = $object->id
;
2136 $pledgeID = $pledgePayment[0]->pledge_id
;
2139 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
2142 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
2143 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
2148 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
2149 // Call interim cancel function - with a goal to cleaning up the signature on it and switching to a tested api Contribution.cancel function.
2150 self
::cancel($memberships, $contributionId, $membershipStatuses, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
2152 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
2153 self
::processFail($memberships, $contributionId, $membershipStatuses, $participant, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
2155 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
2157 // only pending contribution related object processed.
2158 if ($previousContriStatusId &&
2159 !in_array($contributionStatuses[$previousContriStatusId], [
2164 // this is case when we already processed contribution object.
2167 elseif (!$previousContriStatusId &&
2168 !in_array($contributionStatuses[$contribution->contribution_status_id
], [
2173 // this is case when we are going to process contribution object later.
2177 if (is_array($memberships)) {
2178 foreach ($memberships as $membership) {
2183 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
2184 $membership->membership_type_id
,
2185 $membership->is_test
, $membership->id
2188 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2189 // this picks up membership type changes during renewals
2191 SELECT membership_type_id
2192 FROM civicrm_membership_log
2193 WHERE membership_id=$membership->id
2196 $dao = CRM_Core_DAO
::executeQuery($sql);
2197 if ($dao->fetch()) {
2198 if (!empty($dao->membership_type_id
)) {
2199 $membership->membership_type_id
= $dao->membership_type_id
;
2200 $membership->save();
2203 // else fall back to using current membership type
2204 // Figure out number of terms
2206 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
2207 foreach ($lineitems as $lineitem) {
2208 if ($membership->membership_type_id
== ($lineitem['membership_type_id'] ??
NULL)) {
2209 $numterms = $lineitem['membership_num_terms'] ??
NULL;
2211 // in case membership_num_terms comes through as null or zero
2212 $numterms = $numterms >= 1 ?
$numterms : 1;
2217 // CRM-15735-to update the membership status as per the contribution receive date
2219 $oldStatus = $membership->status_id
;
2220 if (!empty($params['receive_date'])) {
2221 $joinDate = $params['receive_date'];
2222 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
2223 $membership->end_date
,
2224 $membership->join_date
,
2225 $params['receive_date'],
2227 $membership->membership_type_id
,
2230 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
2231 $membership->save();
2234 if ($currentMembership) {
2235 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2236 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
2237 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2240 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
2243 //get the status for membership.
2244 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
2246 $dates['join_date'],
2249 $membership->membership_type_id
,
2253 $formattedParams = [
2254 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
2255 array_search('Current', $membershipStatuses)
2257 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
2258 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
2259 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
2262 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
2264 $membership->copyValues($formattedParams);
2265 $membership->save();
2267 //updating the membership log
2268 $membershipLog = [];
2269 $membershipLog = $formattedParams;
2270 $logStartDate = CRM_Utils_Date
::customFormat($dates['log_start_date'] ??
NULL, $format);
2271 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
2273 $membershipLog['start_date'] = $logStartDate;
2274 $membershipLog['membership_id'] = $membership->id
;
2275 $membershipLog['modified_id'] = $membership->contact_id
;
2276 $membershipLog['modified_date'] = date('Ymd');
2277 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
2279 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2281 //update related Memberships.
2282 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2284 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2285 $scheduledActivityID = CRM_Utils_Array
::value('id',
2286 civicrm_api3('Activity', 'Get',
2288 'source_record_id' => $membership->id
,
2289 'activity_type_id' => $activityType,
2290 'status_id' => 'Scheduled',
2293 'sort' => 'id DESC',
2298 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2299 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2300 if ($scheduledActivityID) {
2301 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, ['id' => $scheduledActivityID]);
2306 // track membership status change if any
2307 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
2308 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2309 CRM_Activity_BAO_Activity
::addActivity($membership,
2310 'Change Membership Status',
2313 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2314 'source_contact_id' => $membershipLog['modified_id'],
2315 'priority_id' => 'Normal',
2320 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2326 $updatedStatusId = array_search('Registered', $participantStatuses);
2327 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2330 if ($pledgePayment) {
2331 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2338 * Returns all contribution related object ids.
2340 * @param $contributionId
2344 public static function getComponentDetails($contributionId) {
2345 $componentDetails = $pledgePayment = [];
2346 if (!$contributionId) {
2347 return $componentDetails;
2351 SELECT c.id as contribution_id,
2352 c.contact_id as contact_id,
2353 c.contribution_recur_id,
2354 mp.membership_id as membership_id,
2355 m.membership_type_id as membership_type_id,
2356 pp.participant_id as participant_id,
2357 p.event_id as event_id,
2358 pgp.id as pledge_payment_id
2359 FROM civicrm_contribution c
2360 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2361 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2362 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2363 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2364 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2365 WHERE c.id = $contributionId";
2367 $dao = CRM_Core_DAO
::executeQuery($query);
2368 $componentDetails = [];
2370 while ($dao->fetch()) {
2371 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2372 $componentDetails['contact_id'] = $dao->contact_id
;
2373 if ($dao->event_id
) {
2374 $componentDetails['event'] = $dao->event_id
;
2376 if ($dao->participant_id
) {
2377 $componentDetails['participant'] = $dao->participant_id
;
2379 if ($dao->membership_id
) {
2380 if (!isset($componentDetails['membership'])) {
2381 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2383 $componentDetails['membership'][] = $dao->membership_id
;
2384 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2386 if ($dao->pledge_payment_id
) {
2387 $pledgePayment[] = $dao->pledge_payment_id
;
2389 if ($dao->contribution_recur_id
) {
2390 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2394 if ($pledgePayment) {
2395 $componentDetails['pledge_payment'] = $pledgePayment;
2398 return $componentDetails;
2402 * @param int $contactId
2403 * @param bool $includeSoftCredit
2405 * @return null|string
2407 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2411 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2412 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2413 $liWhere = " AND i.financial_type_id IN (0)";
2414 if (!empty($financialTypes)) {
2415 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2416 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2418 $contactContributionsSQL = "
2419 SELECT contribution.id AS id
2420 FROM civicrm_contribution contribution
2421 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2422 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2426 $contactSoftCreditContributionsSQL = "
2427 SELECT contribution.id
2428 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2429 ON ( contribution.id = softContribution.contribution_id )
2430 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2431 $query = "SELECT count( x.id ) count FROM ( ";
2432 $query .= $contactContributionsSQL;
2434 if ($includeSoftCredit) {
2435 $query .= " UNION ";
2436 $query .= $contactSoftCreditContributionsSQL;
2441 return CRM_Core_DAO
::singleValueQuery($query);
2445 * Repeat a transaction as part of a recurring series.
2448 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2449 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2450 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2451 * and associated entities.
2452 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2453 * which updates the various entities and sends appropriate emails.
2455 * Gaps in the above (@todo)
2456 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2457 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2458 * 3) Repeat transaction duplicates rather than calls Order.create
2459 * 4) Use of payment.create still limited - completetransaction is more common.
2460 * 5) the template transaction is tricky - historically we used the first contribution
2461 * linked to a recurring contribution. More recently that was changed to be the most recent.
2462 * Ideally it would be an actual template - not a contribution used as a template which
2463 * would give more appropriate flexibility. Note line_items have an entity so that table
2464 * could be used for the line item template - the difficulty is the custom fields...
2465 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2466 * to load the membership(s) referred to via line items in the template transactions. Any other
2467 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2468 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2469 * - membership_payment record
2470 * - civicrm_membership.contribution_recur_id
2472 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2473 * of historical processors since this has been handled 'forever' - specifically for paypal.
2474 * albeit by an even nastier mechanism than the current input override.
2475 * The count is out on how correct related entities wind up in this case.
2477 * @param CRM_Contribute_BAO_Contribution $contribution
2478 * @param array $input
2479 * @param array $contributionParams
2481 * @return bool|array
2482 * @throws CiviCRM_API3_Exception
2484 protected static function repeatTransaction(&$contribution, $input, $contributionParams) {
2485 if (!empty($contribution->id
)) {
2488 if (empty($contribution->id
)) {
2489 // Unclear why this would only be set for repeats.
2490 if (!empty($input['amount'])) {
2491 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2494 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2495 'id' => $contributionParams['contribution_recur_id'],
2497 if (!empty($recurringContribution['financial_type_id'])) {
2498 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2499 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2501 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2502 $contributionParams['contribution_recur_id'],
2503 array_intersect_key($contributionParams, [
2504 'total_amount' => TRUE,
2505 'financial_type_id' => TRUE,
2508 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2509 $contributionParams['status_id'] = 'Pending';
2511 if (isset($contributionParams['financial_type_id']) && count($input['line_item']) === 1) {
2512 // We permit the financial type to be overridden for single line items.
2513 // More comments on this are in getTemplateTransaction.
2514 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2517 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2519 foreach (['contact_id', 'currency', 'source', 'amount_level', 'address_id'] as $fieldName) {
2520 if (isset($templateContribution[$fieldName])) {
2521 $contributionParams[$fieldName] = $templateContribution[$fieldName];
2524 if (!empty($recurringContribution['campaign_id'])) {
2525 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2526 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2528 if (!isset($contributionParams['campaign_id']) && isset($templateContribution['campaign_id'])) {
2529 // Fall back on value from the previous contribution if not passed in as input
2530 // or loadable from the recurring contribution.
2531 $contributionParams['campaign_id'] = $templateContribution['campaign_id'];
2533 $contributionParams['source'] = $contributionParams['source'] ?
: ts('Recurring contribution');
2535 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2536 //do not create CC or BCC emails or profile notifications.
2537 //The if is just to be safe. Not sure if we can ever arrive with this unset
2538 // but per CRM-19478 it seems it can be 'null'
2539 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2540 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2542 if (!empty($contribution->tax_amount
)) {
2543 $contributionParams['tax_amount'] = $contribution->tax_amount
;
2546 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2547 $contribution->id
= $createContribution['id'];
2548 $contribution->copyCustomFields($templateContribution['id'], $contribution->id
);
2549 self
::handleMembershipIDOverride($contribution->id
, $input);
2550 // Add new soft credit against current $contribution.
2551 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($contributionParams['contribution_recur_id'], $createContribution['id']);
2552 return $createContribution;
2557 * Get individual id for onbehalf contribution.
2559 * @param int $contributionId
2561 * @param int $contributorId
2565 * containing organization id and individual id
2567 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2571 if (!$contributionId) {
2575 // fetch contributor id if null
2576 if (!$contributorId) {
2577 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2578 $contributionId, 'contact_id'
2582 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2583 $activityTypeId = array_search('Contribution', $activityTypeIds);
2585 if ($activityTypeId && $contributorId) {
2587 SELECT civicrm_activity_contact.contact_id
2588 FROM civicrm_activity_contact
2589 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2590 WHERE civicrm_activity.activity_type_id = %1
2591 AND civicrm_activity.source_record_id = %2
2592 AND civicrm_activity_contact.record_type_id = %3
2595 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2596 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2599 1 => [$activityTypeId, 'Integer'],
2600 2 => [$contributionId, 'Integer'],
2601 3 => [$sourceID, 'Integer'],
2604 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2606 // for on behalf contribution source is individual and contributor is organization
2607 if ($sourceContactId && $sourceContactId != $contributorId) {
2608 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2609 // get rel type id for employee of relation
2610 foreach ($relationshipTypeIds as $id => $typeVals) {
2611 if ($typeVals['name_a_b'] == 'Employee of') {
2612 $relationshipTypeId = $id;
2617 $rel = new CRM_Contact_DAO_Relationship();
2618 $rel->relationship_type_id
= $relationshipTypeId;
2619 $rel->contact_id_a
= $sourceContactId;
2620 $rel->contact_id_b
= $contributorId;
2621 if ($rel->find(TRUE)) {
2622 $ids['individual_id'] = $rel->contact_id_a
;
2623 $ids['organization_id'] = $rel->contact_id_b
;
2634 public static function getContributionDates() {
2635 $config = CRM_Core_Config
::singleton();
2636 $currentMonth = date('m');
2637 $currentDay = date('d');
2638 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2639 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2640 (int ) $config->fiscalYearStart
['d'] > $currentDay
2643 $year = date('Y') - 1;
2648 $year = ['Y' => $year];
2649 $yearDate = $config->fiscalYearStart
;
2650 $yearDate = array_merge($year, $yearDate);
2651 $yearDate = CRM_Utils_Date
::format($yearDate);
2653 $monthDate = date('Ym') . '01';
2659 'yearDate' => $yearDate,
2660 'monthDate' => $monthDate,
2665 * Load objects relations to contribution object.
2666 * Objects are stored in the $_relatedObjects property
2667 * In the first instance we are just moving functionality from BASEIpn -
2669 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2671 * Note that the unit test for the BaseIPN class tests this function
2673 * @param array $input
2674 * Input as delivered from Payment Processor.
2676 * Ids as Loaded by Payment Processor.
2677 * @param bool $loadAll
2678 * Load all related objects - even where id not passed in? (allows API to call this).
2681 * @throws CRM_Core_Exception
2683 public function loadRelatedObjects($input, &$ids, $loadAll = FALSE) {
2684 // @todo deprecate this function - the steps should be
2685 // 1) add additional functions like 'getRelatedMemberships'
2686 // 2) switch all calls that refer to ->_relatedObjects to
2687 // using the helper functions
2688 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2689 // 4) make ->_relatedObjects protected
2690 // 5) hone up the individual functions to not use rely on this having been called
2691 // 6) deprecate like mad
2693 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2694 if (empty($ids['contact']) && isset($this->contact_id
)) {
2695 $ids['contact'] = $this->contact_id
;
2698 if (empty($this->_component
)) {
2699 if (!empty($ids['event'])) {
2700 $this->_component
= 'event';
2703 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2707 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2708 // refactoring than anything else, and has unit test coverage.
2709 if (empty($this->financial_type_id
)) {
2713 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2718 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2719 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2720 $this->contribution_page_id
,
2723 if ($paymentProcessorID) {
2724 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2728 $ids['contributionType'] = $this->financial_type_id
;
2729 $ids['financialType'] = $this->financial_type_id
;
2730 if ($this->contribution_page_id
) {
2731 $ids['contributionPage'] = $this->contribution_page_id
;
2734 $this->loadRelatedEntitiesByID($ids);
2736 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2737 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2740 if (!empty($ids['pledge_payment'])) {
2741 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2742 if (empty($paymentID)) {
2745 $payment = new CRM_Pledge_BAO_PledgePayment();
2746 $payment->id
= $paymentID;
2747 if (!$payment->find(TRUE)) {
2748 throw new CRM_Core_Exception("Could not find pledge payment record: " . $paymentID);
2750 $this->_relatedObjects
['pledge_payment'][] = $payment;
2754 // These are probably no longer accessed from anywhere
2755 // @todo remove this line, after ensuring not used.
2756 $ids = $this->loadRelatedMembershipObjects($ids);
2758 if ($this->_component
!= 'contribute') {
2759 // we are in event mode
2760 // make sure event exists and is valid
2761 $event = new CRM_Event_BAO_Event();
2762 $event->id
= $ids['event'];
2763 if ($ids['event'] &&
2766 throw new CRM_Core_Exception("Could not find event: " . $ids['event']);
2769 $this->_relatedObjects
['event'] = &$event;
2771 $participant = new CRM_Event_BAO_Participant();
2772 $participant->id
= $ids['participant'];
2773 if ($ids['participant'] &&
2774 !$participant->find(TRUE)
2776 throw new CRM_Core_Exception("Could not find participant: " . $ids['participant']);
2778 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2780 $this->_relatedObjects
['participant'] = &$participant;
2782 // get the payment processor id from event - this is inaccurate see CRM-16923
2783 // in future we should look at throwing an exception here rather than an dubious guess.
2784 if (!$paymentProcessorID) {
2785 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2786 if ($paymentProcessorID) {
2787 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2792 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds($this->id
);
2793 if (!empty($relatedContact['individual_id'])) {
2794 $ids['related_contact'] = $relatedContact['individual_id'];
2797 if ($paymentProcessorID) {
2798 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2799 $this->is_test ?
'test' : 'live'
2801 $ids['paymentProcessor'] = $paymentProcessorID;
2802 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2805 // Add contribution id to $ids. CRM-20401
2806 $ids['contribution'] = $this->id
;
2811 * Create array of message information - ie. return html version, txt version, to field
2813 * @param array $input
2814 * Incoming information.
2815 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2816 * just check presence of recur object but maintaining legacy approach
2819 * IDs of related objects.
2820 * @param array $values
2821 * Any values that may have already been compiled by calling process.
2822 * This is augmented by values 'gathered' by gatherMessageValues
2823 * @param bool $returnMessageText
2824 * Distinguishes between whether to send message or return.
2825 * message text. We are working towards this function ALWAYS returning message text & calling
2826 * function doing emails / pdfs with it
2832 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2833 $this->loadRelatedObjects($input, $ids);
2835 if (empty($this->_component
)) {
2836 $this->_component
= $input['component'] ??
NULL;
2839 //not really sure what params might be passed in but lets merge em into values
2840 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2841 $values['is_email_receipt'] = !$returnMessageText;
2842 foreach (['receipt_date', 'cc_receipt', 'bcc_receipt', 'receipt_from_name', 'receipt_from_email', 'receipt_text'] as $fld) {
2843 if (!empty($input[$fld])) {
2844 $values[$fld] = $input[$fld];
2848 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2849 //what does recur 'mean here - to do with payment processor return functionality but
2850 // what is the importance
2851 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2852 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2854 $entityID = $entity = NULL;
2855 if (isset($ids['contribution'])) {
2856 $entity = 'contribution';
2857 $entityID = $ids['contribution'];
2859 if (!empty($ids['membership'])) {
2860 //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
2861 // 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
2862 // line having loaded an array
2863 $ids['membership'] = (array) $ids['membership'];
2864 $entity = 'membership';
2865 $entityID = $ids['membership'][0];
2868 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2869 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2870 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2872 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2873 //direct mode showing billing block, so use directIPN for temporary
2874 $template->assign('contributeMode', 'directIPN');
2877 // todo remove strtolower - check consistency
2878 if (strtolower($this->_component
) == 'event') {
2879 $eventParams = ['id' => $this->_relatedObjects
['participant']->event_id
];
2880 $values['event'] = [];
2882 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2884 //get location details
2886 'entity_id' => $this->_relatedObjects
['participant']->event_id
,
2887 'entity_table' => 'civicrm_event',
2889 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2892 'entity_table' => 'civicrm_event',
2893 'entity_id' => $ids['event'],
2894 'module' => 'CiviEvent',
2897 list($custom_pre_id,
2899 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2901 $values['custom_pre_id'] = $custom_pre_id;
2902 $values['custom_post_id'] = $custom_post_ids;
2903 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2904 //and cases involving status updation through ipn
2905 // whatever that means!
2906 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2907 // perhaps we should throw an e-notice if amount is set & force total_amount?
2908 if (!empty($input['amount'])) {
2909 $values['totalAmount'] = $input['amount'];
2911 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2912 if ($values['event']['is_email_confirm']) {
2913 $values['is_email_receipt'] = 1;
2916 if (!empty($ids['contribution'])) {
2917 $values['contributionId'] = $ids['contribution'];
2920 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2921 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2925 $values['contribution_id'] = $this->id
;
2926 if (!empty($ids['related_contact'])) {
2927 $values['related_contact'] = $ids['related_contact'];
2928 if (isset($ids['onbehalf_dupe_alert'])) {
2929 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2932 'contact_id' => $ids['contact'],
2933 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2934 'Home', 'id', 'name'
2937 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2938 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2941 if ($this->is_test
) {
2944 if (!empty($this->_relatedObjects
['membership'])) {
2945 foreach ($this->_relatedObjects
['membership'] as $membership) {
2946 if ($membership->id
) {
2947 $values['membership_id'] = $membership->id
;
2948 $values['isMembership'] = TRUE;
2949 $values['membership_assign'] = TRUE;
2951 // need to set the membership values here
2952 $template->assign('membership_name',
2953 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2955 $template->assign('mem_start_date', $membership->start_date
);
2956 $template->assign('mem_join_date', $membership->join_date
);
2957 $template->assign('mem_end_date', $membership->end_date
);
2958 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2959 $template->assign('mem_status', $membership_status);
2960 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2961 $values['is_pay_later'] = 1;
2963 // Pass amount to floatval as string '0.00' is considered a
2964 // valid amount and includes Fee section in the mail.
2965 if (isset($values['amount'])) {
2966 $values['amount'] = floatval($values['amount']);
2969 if (!empty($this->contribution_recur_id
) && $paymentObject) {
2970 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2971 $template->assign('cancelSubscriptionUrl', $url);
2972 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2973 $template->assign('updateSubscriptionBillingUrl', $url);
2974 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2975 $template->assign('updateSubscriptionUrl', $url);
2978 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2981 // otherwise if its about sending emails, continue sending without return, as we
2982 // don't want to exit the loop.
2987 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2993 * Gather values for contribution mail - this function has been created
2994 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2995 * Values related to the contribution in question are gathered
2997 * @param array $input
2998 * Input into function (probably from payment processor).
2999 * @param array $values
3001 * The set of ids related to the input.
3004 * @throws \CRM_Core_Exception
3006 public function _gatherMessageValues($input, &$values, $ids = []) {
3007 // set display address of contributor
3008 $values['billingName'] = '';
3009 if ($this->address_id
) {
3010 $addressDetails = CRM_Core_BAO_Address
::getValues(['id' => $this->address_id
], FALSE, 'id');
3011 $addressDetails = reset($addressDetails);
3012 $values['billingName'] = $addressDetails['name'] ??
'';
3014 // Else we assign the billing address of the contribution contact.
3016 $addressDetails = (array) CRM_Core_BAO_Address
::getValues(['contact_id' => $this->contact_id
, 'is_billing' => 1]);
3017 $addressDetails = reset($addressDetails);
3019 $values['address'] = $addressDetails['display'] ??
'';
3021 if ($this->_component
=== 'contribute') {
3022 //get soft contributions
3023 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
3024 if (!empty($softContributions)) {
3025 // For pcp soft credit, there is no 'soft_credit' member it comes
3026 // back in different array members, but shortly after returning from
3027 // this function it calls _assignMessageVariablesToTemplate which does
3028 // its own lookup of any pcp soft credit, so we can skip it here.
3029 $values['softContributions'] = $softContributions['soft_credit'] ??
NULL;
3031 if (isset($this->contribution_page_id
)) {
3032 // This is a call we want to use less, in favour of loading related objects.
3033 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
3034 if ($this->contribution_page_id
) {
3035 // This is precautionary as there are some legacy flows, but it should really be
3037 if (!isset($this->_relatedObjects
['contributionPage'])) {
3038 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id
]);
3040 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($values);
3043 // no contribution page -probably back office
3045 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
3046 $values['title'] = 'Contribution';
3048 // set lineItem for contribution
3050 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
3051 if (!empty($lineItems)) {
3052 $firstLineItem = reset($lineItems);
3054 if (!empty($firstLineItem['price_set_id'])) {
3055 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
3056 'id' => $firstLineItem['price_set_id'],
3057 'return' => 'is_quick_config, id',
3059 $values['priceSetID'] = $priceSet['id'];
3061 foreach ($lineItems as &$eachItem) {
3062 if (isset($this->_relatedObjects
['membership'])
3063 && is_array($this->_relatedObjects
['membership'])
3064 && array_key_exists($eachItem['entity_id'] . '_' . $eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
3065 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->join_date
);
3066 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->start_date
);
3067 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->end_date
);
3069 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
3070 // However, that does create upgrade pain so would be better to be phased in.
3071 $values['useForMember'] = empty($priceSet['is_quick_config']);
3073 $values['lineItem'][0] = $lineItems;
3077 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
3081 // if this is onbehalf of contribution then set related contact
3082 if (!empty($relatedContact['individual_id'])) {
3083 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
3087 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects
['participant']->id
, $this->id
));
3090 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
3093 foreach ($groupTree as $key => $group) {
3094 if ($key === 'info') {
3098 foreach ($group['fields'] as $k => $customField) {
3099 $groupLabel = $group['title'];
3100 if (!empty($customField['customValue'])) {
3101 foreach ($customField['customValue'] as $customFieldValues) {
3102 $customGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
3107 $values['customGroup'] = $customGroup;
3109 $values['is_pay_later'] = $this->is_pay_later
;
3115 * Assign message variables to template but try to break the habit.
3117 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3118 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3119 * multiple recurring payments for processors like IATS that use tokens.
3121 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3122 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
3123 * Note we send directly from this function in some cases because it is only partly refactored.
3125 * Don't call this function directly as the signature will change.
3129 * @param bool $returnMessageText
3133 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
3134 // @todo - this should have a better separation of concerns - ie.
3135 // gatherMessageValues should build an array of values to be assigned to the template
3136 // and this function should assign them (assigning null if not set).
3137 // the way the pcpParams & honor Params section works is a baby-step towards this.
3138 $template = CRM_Core_Smarty
::singleton();
3139 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
3140 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
3141 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
3142 $template->assign('billingName', $values['billingName']);
3144 // For some unit tests contribution cannot contain paymentProcessor information
3145 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
3146 $template->assign('contributeMode', CRM_Core_SelectValues
::contributeMode()[$billingMode] ??
NULL);
3148 //assign honor information to receipt message
3149 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
3152 'soft_credit_type' => NULL,
3153 'honor_block_is_active' => NULL,
3155 if (isset($softRecord['soft_credit'])) {
3156 //if id of contribution page is present
3157 if (!empty($values['id'])) {
3158 $values['honor'] = [
3159 'honor_profile_values' => [],
3160 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3161 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
3164 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3165 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
3168 //offline contribution
3169 $softCreditTypes = $softCredits = [];
3170 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3171 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3172 $softCredits[$key] = [
3173 'Name' => $softCredit['contact_name'],
3174 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
3177 $template->assign('softCreditTypes', $softCreditTypes);
3178 $template->assign('softCredits', $softCredits);
3182 $dao = new CRM_Contribute_DAO_ContributionProduct();
3183 $dao->contribution_id
= $this->id
;
3184 if ($dao->find(TRUE)) {
3185 $premiumId = $dao->product_id
;
3186 $template->assign('option', $dao->product_option
);
3188 $productDAO = new CRM_Contribute_DAO_Product();
3189 $productDAO->id
= $premiumId;
3190 $productDAO->find(TRUE);
3191 $template->assign('selectPremium', TRUE);
3192 $template->assign('product_name', $productDAO->name
);
3193 $template->assign('price', $productDAO->price
);
3194 $template->assign('sku', $productDAO->sku
);
3196 $template->assign('title', $values['title'] ??
NULL);
3197 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
3198 if (!$values['amount'] && isset($this->total_amount
)) {
3199 $values['amount'] = $this->total_amount
;
3204 'pcp_display_in_roll' => NULL,
3205 'pcp_roll_nickname' => NULL,
3206 'pcp_personal_note' => NULL,
3210 if (strtolower($this->_component
) == 'contribute') {
3212 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3213 $softDAO->contribution_id
= $this->id
;
3214 if ($softDAO->find(TRUE)) {
3215 $pcpParams['pcpBlock'] = TRUE;
3216 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
3217 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
3218 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
3220 //assign the pcp page title for email subject
3221 $pcpDAO = new CRM_PCP_DAO_PCP();
3222 $pcpDAO->id
= $softDAO->pcp_id
;
3223 if ($pcpDAO->find(TRUE)) {
3224 $pcpParams['title'] = $pcpDAO->title
;
3228 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3229 $template->assign($templateKey, $templateValue);
3232 if ($this->financial_type_id
) {
3233 $values['financial_type_id'] = $this->financial_type_id
;
3236 $template->assign('trxn_id', $this->trxn_id
);
3237 $template->assign('receive_date',
3238 CRM_Utils_Date
::processDate($this->receive_date
)
3240 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
3241 $template->assign('action', $this->is_test ?
1024 : 1);
3242 $template->assign('receipt_text', $values['receipt_text'] ??
NULL);
3243 $template->assign('is_monetary', 1);
3244 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3245 $template->assign('currency', $this->currency
);
3246 $template->assign('address', CRM_Utils_Address
::format($input));
3247 if (!empty($values['customGroup'])) {
3248 $template->assign('customGroup', $values['customGroup']);
3250 if (!empty($values['softContributions'])) {
3251 $template->assign('softContributions', $values['softContributions']);
3253 if ($this->_component
== 'event') {
3254 $template->assign('title', $values['event']['title']);
3255 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3257 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3258 $viewRoles[] = $participantRoles[$v];
3260 $values['event']['participant_role'] = implode(', ', $viewRoles);
3261 $template->assign('event', $values['event']);
3262 $template->assign('participant', $values['participant']);
3263 $template->assign('location', $values['location']);
3264 $template->assign('customPre', $values['custom_pre_id']);
3265 $template->assign('customPost', $values['custom_post_id']);
3268 if ($this->_relatedObjects
['participant']->is_test
) {
3272 $values['params'] = [];
3273 //to get email of primary participant.
3274 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3275 $primaryAmount[] = [
3276 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3277 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3279 //build an array of cId/pId of participants
3280 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3281 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3282 //send receipt to additional participant if exists
3283 if (count($additionalIDs)) {
3284 $template->assign('isPrimary', 0);
3285 $template->assign('customProfile', NULL);
3286 //set additionalParticipant true
3287 $values['params']['additionalParticipant'] = TRUE;
3288 foreach ($additionalIDs as $pId => $cId) {
3290 //to change the status pending to completed
3291 $additional = new CRM_Event_DAO_Participant();
3292 $additional->id
= $pId;
3293 $additional->contact_id
= $cId;
3294 $additional->find(TRUE);
3295 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3296 $additional->status_id
= 1;
3297 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3298 //if additional participant dont have email
3300 if (!$additionalParticipantInfo) {
3301 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3304 'label' => $additional->fee_level
,
3305 'amount' => $additional->fee_amount
,
3307 $primaryAmount[] = [
3308 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3309 'amount' => $additional->fee_amount
,
3311 $additional->save();
3312 $template->assign('amount', $amount);
3313 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3317 //build an array of custom profile and assigning it to template
3318 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3320 if (count($customProfile)) {
3321 $template->assign('customProfile', $customProfile);
3324 // for primary contact
3325 $values['params']['additionalParticipant'] = FALSE;
3326 $template->assign('isPrimary', 1);
3327 $template->assign('amount', $primaryAmount);
3328 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3329 if ($this->payment_instrument_id
) {
3330 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3331 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3333 // carry paylater, since we did not created billing,
3334 // so need to pull email from primary location, CRM-4395
3335 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3341 * Check whether payment processor supports
3342 * cancellation of contribution subscription
3344 * @param int $contributionId
3347 * @param bool $isNotCancelled
3351 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3352 $cacheKeyString = "$contributionId";
3353 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3355 static $supportsCancel = [];
3357 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3358 $supportsCancel[$cacheKeyString] = FALSE;
3359 $isCancelled = FALSE;
3361 if ($isNotCancelled) {
3362 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3365 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3366 if (!empty($paymentObject)) {
3367 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3370 return $supportsCancel[$cacheKeyString];
3374 * Check whether subscription is already cancelled.
3376 * @param int $contributionId
3380 * contribution status
3382 public static function isSubscriptionCancelled($contributionId) {
3384 SELECT cr.contribution_status_id
3385 FROM civicrm_contribution_recur cr
3386 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3387 WHERE con.id = %1 LIMIT 1";
3388 $params = [1 => [$contributionId, 'Integer']];
3389 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3390 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
3391 if ($status == 'Cancelled') {
3398 * Create all financial accounts entry.
3400 * @param array $params
3401 * Contribution object, line item array and params for trxn.
3404 * @param array $financialTrxnValues
3406 * @return null|\CRM_Core_BAO_FinancialTrxn
3408 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3409 $skipRecords = $update = $return = $isRelatedId = FALSE;
3410 $isUpdate = !empty($params['prevContribution']);
3412 $additionalParticipantId = [];
3413 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3414 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3416 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3417 $entityId = $params['participant_id'];
3418 $entityTable = 'civicrm_participant';
3419 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3421 elseif (!empty($params['membership_id'])) {
3422 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3423 // are created off one contribution should be handled elsewhere
3424 $entityId = $params['membership_id'];
3425 $entityTable = 'civicrm_membership';
3428 $entityId = $params['contribution']->id
;
3429 $entityTable = 'civicrm_contribution';
3432 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3433 $isRelatedId = TRUE;
3436 $entityID[] = $entityId;
3437 if (!empty($additionalParticipantId)) {
3438 $entityID +
= $additionalParticipantId;
3440 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3441 if (empty($params['prevContribution'])) {
3445 $statusId = $params['contribution']->contribution_status_id
;
3447 // build line item array if its not set in $params
3448 if (empty($params['line_item']) ||
$additionalParticipantId) {
3449 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3452 if ($contributionStatus != 'Failed' &&
3453 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3455 $skipRecords = TRUE;
3460 if (in_array($contributionStatus, $pendingStatus)) {
3461 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3462 $params['financial_type_id'],
3463 'Accounts Receivable Account is'
3466 elseif (!empty($params['payment_processor'])) {
3467 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3468 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3469 'id' => $params['payment_processor'],
3470 'return' => 'payment_instrument_id',
3473 elseif (!empty($params['payment_instrument_id'])) {
3474 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3477 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3478 $queryParams = [1 => [$relationTypeId, 'Integer']];
3479 $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);
3482 $totalAmount = $params['total_amount'] ??
NULL;
3483 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3484 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3486 //build financial transaction params
3488 'contribution_id' => $params['contribution']->id
,
3489 'to_financial_account_id' => $params['to_financial_account_id'],
3490 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3491 'total_amount' => $totalAmount,
3492 'fee_amount' => $params['fee_amount'] ??
NULL,
3493 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3494 'currency' => $params['contribution']->currency
,
3495 'trxn_id' => $params['contribution']->trxn_id
,
3496 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3497 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3498 // this should really default to completed (after discussion).
3499 'status_id' => $statusId,
3500 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3501 'check_number' => $params['check_number'] ??
NULL,
3502 'pan_truncation' => $params['pan_truncation'] ??
NULL,
3503 'card_type_id' => $params['card_type_id'] ??
NULL,
3505 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3506 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3507 if (isset($params['refund_trxn_id'])) {
3508 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3509 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3512 //CRM-16259, set is_payment flag for non pending status
3513 if (!in_array($contributionStatus, $pendingStatus)) {
3514 $trxnParams['is_payment'] = 1;
3516 if (!empty($params['payment_processor'])) {
3517 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3520 if (isset($fromFinancialAccountId)) {
3521 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3524 // consider external values passed for recording transaction entry
3525 if (!empty($financialTrxnValues)) {
3526 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3528 if (empty($trxnParams['payment_processor_id'])) {
3529 unset($trxnParams['payment_processor_id']);
3532 $params['trxnParams'] = $trxnParams;
3536 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3537 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3538 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3539 if (!isset($params['trxnParams']['trxn_id'])) {
3540 // Actually I have no idea why we are overwriting any values from the previous contribution.
3541 // (filling makes sense to me). However, only protecting this value as I really really know we
3542 // don't want this one overwritten.
3544 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3546 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3548 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3549 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3550 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3552 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3553 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3556 //if financial type is changed
3557 if (!empty($params['financial_type_id']) &&
3558 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3560 $accountRelationship = 'Income Account is';
3561 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3562 $accountRelationship = 'Deferred Revenue Account is';
3564 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3565 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3566 if ($oldFinancialAccount != $newFinancialAccount) {
3567 $params['total_amount'] = 0;
3568 // If we have a fee amount set reverse this as well.
3569 if (isset($params['fee_amount'])) {
3570 $params['trxnParams']['fee_amount'] = 0 - $params['fee_amount'];
3572 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3573 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3574 $params['prevContribution']->financial_type_id
, $accountRelationship);
3577 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3578 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3579 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3582 self
::updateFinancialAccounts($params, 'changeFinancialType');
3583 $params['skipLineItem'] = FALSE;
3584 foreach ($params['line_item'] as &$lineItems) {
3585 foreach ($lineItems as &$line) {
3586 $line['financial_type_id'] = $params['financial_type_id'];
3589 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType');
3590 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3591 $params['financial_account_id'] = $newFinancialAccount;
3592 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3593 // Set the transaction fee amount back to the original value for creating the new positive financial trxn.
3594 if (isset($params['fee_amount'])) {
3595 $params['trxnParams']['fee_amount'] = $params['fee_amount'];
3597 self
::updateFinancialAccounts($params);
3598 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE);
3599 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3601 $params['deferred_financial_account_id'] = $newFinancialAccount;
3605 //Update contribution status
3606 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3607 if (!isset($params['refund_trxn_id'])) {
3608 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3609 // gets preference over another so I am only 'protecting' a very specific tested flow
3610 // and letting natural justice take care of the rest.
3611 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3613 if (!empty($params['contribution_status_id']) &&
3614 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3616 //Update Financial Records
3617 $callUpdateFinancialAccounts = self
::updateFinancialAccountsOnContributionStatusChange($params);
3618 if ($callUpdateFinancialAccounts) {
3619 self
::updateFinancialAccounts($params, 'changedStatus');
3620 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus');
3625 // change Payment Instrument for a Completed contribution
3626 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3627 // instrument is null and now new payment instrument is added along with the payment
3628 if (!$params['contribution']->payment_instrument_id
) {
3629 $params['contribution']->find(TRUE);
3631 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3632 $params['trxnParams']['check_number'] = $params['check_number'] ??
NULL;
3634 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3635 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3638 //if Change contribution amount
3639 $params['trxnParams']['fee_amount'] = $params['fee_amount'] ??
NULL;
3640 $params['trxnParams']['net_amount'] = $params['net_amount'] ??
NULL;
3641 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3642 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3643 if (isset($totalAmount) &&
3644 $totalAmount != $params['prevContribution']->total_amount
3646 //Update Financial Records
3647 $params['trxnParams']['from_financial_account_id'] = NULL;
3648 self
::updateFinancialAccounts($params, 'changedAmount');
3649 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount');
3654 // Looks like we might have a data correction update.
3655 // This would be a case where a transaction id has been entered but it is incorrect &
3656 // the person goes back in & fixes it, as opposed to a new transaction.
3657 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3658 // the data fix scenario.
3660 if (isset($params['refund_trxn_id'])) {
3661 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3662 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3663 civicrm_api3('FinancialTrxn', 'create', [
3664 'id' => $refundIDs['financialTrxnId'],
3665 'trxn_id' => $params['refund_trxn_id'],
3669 $cardType = $params['card_type_id'] ??
NULL;
3670 $panTruncation = $params['pan_truncation'] ??
NULL;
3671 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3676 // records finanical trxn and entity financial trxn
3677 // also make it available as return value
3678 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3679 $trxnParams['pan_truncation'] = $params['pan_truncation'] ??
NULL;
3680 $trxnParams['card_type_id'] = $params['card_type_id'] ??
NULL;
3681 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3682 $params['entity_id'] = $financialTxn->id
;
3683 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3684 self
::$_trxnIDs[] = $financialTxn->id
;
3688 // record line items and financial items
3689 if (empty($params['skipLineItem'])) {
3690 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $isUpdate);
3693 // create batch entry if batch_id is passed and
3694 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3695 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3697 'batch_id' => $params['batch_id'],
3698 'entity_table' => 'civicrm_financial_trxn',
3699 'entity_id' => $financialTxn->id
,
3701 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3704 // when a fee is charged
3705 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3706 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3709 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3710 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3712 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3713 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3714 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3716 unset($params['line_item']);
3717 self
::$_trxnIDs = NULL;
3722 * Update all financial accounts entry.
3724 * @param array $params
3725 * Contribution object, line item array and params for trxn.
3727 * @param string $context
3730 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3731 * adds unpredictability.
3734 public static function updateFinancialAccounts(&$params, $context = NULL) {
3736 $inputParams = $params;
3737 $isARefund = self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
);
3739 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3740 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3741 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3744 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3745 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3746 $params['entity_id'] = $trxn->id
;
3748 $itemParams['entity_table'] = 'civicrm_line_item';
3749 $trxnIds['id'] = $params['entity_id'];
3750 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution']->id
);
3751 foreach ($params['line_item'] as $fieldId => $fields) {
3752 $params = self
::createFinancialItemsForLine($params, $context, $fields, $previousLineItems, $inputParams, $isARefund, $trxnIds, $fieldId);
3757 * Is this contribution status a reversal.
3759 * If so we would expect to record a negative value in the financial_trxn table.
3761 * @param int $status_id
3765 public static function isContributionStatusNegative($status_id) {
3766 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3767 return in_array(CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE);
3771 * Check status validation on update of a contribution.
3773 * @param array $values
3774 * Previous form values before submit.
3776 * @param array $fields
3777 * The input form values.
3779 * @param array $errors
3784 public static function checkStatusValidation($values, &$fields, &$errors) {
3785 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3786 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3787 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3791 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3793 'Cancelled' => ['Completed', 'Refunded'],
3794 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3795 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3796 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3797 'Refunded' => ['Cancelled', 'Completed'],
3798 'Partially paid' => ['Completed'],
3799 'Pending refund' => ['Completed', 'Refunded'],
3800 'Failed' => ['Pending'],
3803 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3804 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3806 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3807 1 => $contributionStatuses[$values['contribution_status_id']],
3808 2 => $contributionStatuses[$fields['contribution_status_id']],
3814 * Delete contribution of contact.
3816 * @see https://issues.civicrm.org/jira/browse/CRM-12155
3818 * @param int $contactId
3822 public static function deleteContactContribution($contactId) {
3823 $contribution = new CRM_Contribute_DAO_Contribution();
3824 $contribution->contact_id
= $contactId;
3825 $contribution->find();
3826 while ($contribution->fetch()) {
3827 self
::deleteContribution($contribution->id
);
3832 * Get options for a given contribution field.
3834 * @param string $fieldName
3835 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3836 * @param array $props whatever is known about this dao object.
3838 * @return array|bool
3839 * @see CRM_Core_DAO::buildOptions
3842 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3843 $className = __CLASS__
;
3845 if (isset($props['orderColumn'])) {
3846 $params['orderColumn'] = $props['orderColumn'];
3848 switch ($fieldName) {
3849 // This field is not part of this object but the api supports it
3850 case 'payment_processor':
3851 $className = 'CRM_Contribute_BAO_ContributionPage';
3852 // Filter results by contribution page
3853 if (!empty($props['contribution_page_id'])) {
3854 $page = civicrm_api('contribution_page', 'getsingle', [
3856 'id' => ($props['contribution_page_id']),
3858 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3859 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3863 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3864 case 'honor_type_id':
3865 $className = 'CRM_Contribute_BAO_ContributionSoft';
3866 $fieldName = 'soft_credit_type_id';
3867 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3870 case 'contribution_status_id':
3871 if ($context !== 'validate') {
3872 $params['condition'] = "v.name <> 'Template'";
3875 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3879 * Validate financial type.
3881 * @see https://issues.civicrm.org/jira/browse/CRM-13231
3883 * @param int $financialTypeId
3884 * Financial Type id.
3886 * @param string $relationName
3888 * @return array|bool
3890 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3891 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3893 if (!$financialAccount) {
3894 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3900 * @param int $targetCid
3901 * @param $activityType
3902 * @param string $title
3903 * @param int $contributionId
3904 * @param string $totalAmount
3905 * @param string $currency
3906 * @param string $trxn_date
3908 * @throws \CRM_Core_Exception
3909 * @throws \CiviCRM_API3_Exception
3911 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
3912 $paymentAmount = CRM_Utils_Money
::format($totalAmount, $currency);
3913 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3914 $date = CRM_Utils_Date
::isoToMysql($trxn_date);
3915 // source record id would be the contribution id
3916 $srcRecId = $contributionId;
3920 'source_contact_id' => $targetCid,
3921 'source_record_id' => $srcRecId,
3922 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
3923 'subject' => $subject,
3924 'activity_date_time' => $date,
3925 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
3926 'skipRecentView' => TRUE,
3929 // create activity with target contacts
3930 $session = CRM_Core_Session
::singleton();
3931 $id = $session->get('userID');
3933 $activityParams['source_contact_id'] = $id;
3934 $activityParams['target_contact_id'][] = $targetCid;
3936 civicrm_api3('Activity', 'create', $activityParams);
3940 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3943 * @param string $component
3944 * @param bool $getTrxnInfo
3948 * @throws \CRM_Core_Exception
3949 * @throws \CiviCRM_API3_Exception
3951 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE) {
3952 // @todo deprecate passing in component - always call with contribution.
3953 if ($component == 'event') {
3954 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3956 if (!$contributionId) {
3957 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3958 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3959 $id = $primaryParticipantId;
3961 if (!$contributionId) {
3966 elseif ($component == 'membership') {
3967 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
3970 $contributionId = $id;
3973 // The balance used to be calculated this way - we really want to remove this 'oldCalculation'
3974 // but need to unpick the whole trxn_id it's returning first.
3975 $oldCalculation = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3976 $baseTrxnId = !empty($oldCalculation['trxn_id']) ?
$oldCalculation['trxn_id'] : NULL;
3978 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3979 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3981 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
3983 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
3985 $contribution = civicrm_api3('Contribution', 'getsingle', [
3986 'id' => $contributionId,
3990 'contribution_status_id',
3991 'financial_type_id',
3995 $info['payLater'] = $contribution['is_pay_later'];
3996 $info['contribution_status'] = $contribution['contribution_status'];
3997 $info['currency'] = $contribution['currency'];
3999 $info['total'] = $total;
4000 $info['paid'] = $total - $paymentBalance;
4001 $info['balance'] = $paymentBalance;
4003 $info['component'] = $component;
4004 if ($getTrxnInfo && $baseTrxnId) {
4005 $info['transaction'] = self
::getContributionTransactionInformation($contributionId, $contribution['financial_type_id']);
4008 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
4013 * Get the outstanding balance on a contribution.
4015 * @param int $contributionId
4016 * @param float $contributionTotal
4017 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
4021 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
4022 if ($contributionTotal === NULL) {
4023 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4026 return (float) CRM_Utils_Money
::subtractCurrencies(
4028 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE),
4029 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4034 * Get the tax amount (misnamed function).
4036 * @param array $params
4039 * @throws \CiviCRM_API3_Exception
4041 protected static function checkTaxAmount($params) {
4042 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4044 // Update contribution.
4045 if (!empty($params['id'])) {
4046 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4047 // there are no tax implications - early return.
4048 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4051 if (empty($params['prevContribution'])) {
4052 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4055 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
4056 if (!isset($params[$field])) {
4057 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4058 // Tax amount gets added back on later....
4059 $params['total_amount'] = $params['prevContribution']->total_amount
-
4060 $params['prevContribution']->tax_amount
;
4063 $params[$field] = $params['prevContribution']->$field;
4064 if ($params[$field] != $params['prevContribution']->$field) {
4070 self
::calculateMissingAmountParams($params, $params['id']);
4071 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4072 // Assign tax Amount on update of contribution
4073 if (!empty($params['prevContribution']->tax_amount
)) {
4074 $params['tax_amount'] = 'null';
4075 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4076 foreach ($params['line_item'] as $setID => $priceField) {
4077 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4078 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4085 // New Contribution and update of contribution with tax rate financial type
4086 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4087 empty($params['skipLineItem'])) {
4088 $taxRateParams = $taxRates[$params['financial_type_id']];
4089 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams);
4090 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4092 // Get Line Item on update of contribution
4093 if (isset($params['id'])) {
4094 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4097 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4099 foreach ($params['line_item'] as $setID => $priceField) {
4100 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4101 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4104 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4106 elseif (isset($params['api.line_item.create'])) {
4107 // Update total amount of contribution using lineItem
4108 $taxAmountArray = [];
4109 foreach ($params['api.line_item.create'] as $key => $value) {
4110 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4111 $taxRate = $taxRates[$value['financial_type_id']];
4112 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4113 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4116 $params['tax_amount'] = array_sum($taxAmountArray);
4117 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4124 * Check financial type validation on update of a contribution.
4126 * @param int $financialTypeId
4127 * Value of latest Financial Type.
4129 * @param int $contributionId
4132 * @param array $errors
4137 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4138 if (!empty($financialTypeId)) {
4139 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4140 if ($oldFinancialTypeId == $financialTypeId) {
4144 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4146 '1' => [$contributionId, 'Integer'],
4148 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4149 if ($result->N
> 1) {
4150 $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.');
4155 * Update related pledge payment payments.
4157 * This function has been refactored out of the back office contribution form and may
4158 * still overlap with other functions.
4160 * @param string $action
4161 * @param int $pledgePaymentID
4162 * @param int $contributionID
4163 * @param bool $adjustTotalAmount
4164 * @param float $total_amount
4165 * @param float $original_total_amount
4166 * @param int $contribution_status_id
4167 * @param int $original_contribution_status_id
4169 public static function updateRelatedPledge(
4175 $original_total_amount,
4176 $contribution_status_id,
4177 $original_contribution_status_id
4179 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4183 if ($pledgePaymentID) {
4184 //store contribution id in payment record.
4185 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4188 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4195 if (!$pledgePaymentID) {
4198 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4204 $updatePledgePaymentStatus = FALSE;
4206 // If either the status or the amount has changed we update the pledge status.
4207 if ($action & CRM_Core_Action
::ADD
) {
4208 $updatePledgePaymentStatus = TRUE;
4210 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4211 ($original_total_amount != $total_amount))
4213 $updatePledgePaymentStatus = TRUE;
4216 if ($updatePledgePaymentStatus) {
4217 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4219 $contribution_status_id,
4228 * Is there only one line item attached to the contribution.
4234 * @throws \CiviCRM_API3_Exception
4236 public static function isSingleLineItem($id) {
4237 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
4238 return ($lineItemCount == 1);
4242 * Complete an order.
4244 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4246 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4248 * Moving it out of the BaseIPN class is just the first step.
4250 * @param array $input
4252 * @param \CRM_Contribute_BAO_Contribution $contribution
4253 * @param bool $isPostPaymentCreate
4254 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
4255 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
4256 * transitioning related elements).
4259 * @throws \CRM_Core_Exception
4260 * @throws \CiviCRM_API3_Exception
4262 public static function completeOrder($input, $ids, $contribution, $isPostPaymentCreate = FALSE) {
4263 $transaction = new CRM_Core_Transaction();
4264 // @todo see if we even need this - it's used further down to create an activity
4265 // but the BAO layer should create that - we just need to add a test to cover it & can
4266 // maybe remove $ids altogether.
4267 $contributionContactID = $ids['related_contact'];
4268 $participantID = $ids['participant'];
4269 $recurringContributionID = $ids['contributionRecur'];
4271 // Unset ids just to make it clear it's not used again.
4273 // The previous details are used when calculating line items so keep it before any code that 'does something'
4274 if (!empty($contribution->id
)) {
4275 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(['id' => $contribution->id
]);
4277 $inputContributionWhiteList = [
4282 'payment_instrument_id',
4287 'contribution_status_id',
4290 'financial_type_id',
4293 $paymentProcessorId = $input['payment_processor_id'] ??
NULL;
4295 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4297 $contributionParams = array_merge([
4298 'contribution_status_id' => $completedContributionStatusID,
4299 'source' => self
::getRecurringContributionDescription($contribution, $participantID),
4300 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4303 $contributionParams['payment_processor'] = $paymentProcessorId;
4305 if (empty($contributionParams['payment_instrument_id']) && $paymentProcessorId) {
4306 $contributionParams['payment_instrument_id'] = PaymentProcessor
::get(FALSE)->addWhere('id', '=', $paymentProcessorId)->addSelect('payment_instrument_id')->execute()->first()['payment_instrument_id'];
4309 if ($recurringContributionID) {
4310 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4312 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4314 $contributionResult = self
::repeatTransaction($contribution, $input, $contributionParams);
4315 $contributionID = (int) $contribution->id
;
4317 if ($input['component'] == 'contribute') {
4318 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4319 self
::updateMembershipBasedOnCompletionOfContribution(
4326 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4327 $participantParams['id'] = $participantID;
4328 $participantParams['status_id'] = 'Registered';
4329 civicrm_api3('Participant', 'create', $participantParams);
4333 $contributionParams['id'] = $contributionID;
4334 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
4336 if (!$contributionResult) {
4337 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4340 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4342 CRM_Core_Error
::debug_log_message('Contribution record updated successfully');
4343 $transaction->commit();
4345 // @todo - check if Contribution::create does this, test, remove.
4346 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contributionID, $recurringContributionID,
4347 $contributionParams['contribution_status_id'], $input['amount']);
4349 // create an activity record
4350 // @todo - check if Contribution::create does this, test, remove.
4351 if ($input['component'] == 'contribute') {
4353 $targetContactID = NULL;
4354 if ($contributionContactID) {
4355 $targetContactID = $contribution->contact_id
;
4356 $contribution->contact_id
= $contributionContactID;
4358 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution', $targetContactID);
4361 if (self
::isEmailReceipt($input, $contribution->contribution_page_id
, $recurringContributionID)) {
4362 civicrm_api3('Contribution', 'sendconfirmation', [
4363 'id' => $contributionID,
4364 'payment_processor_id' => $paymentProcessorId,
4366 CRM_Core_Error
::debug_log_message("Receipt sent");
4369 CRM_Core_Error
::debug_log_message("Success: Database updated");
4370 return $contributionResult;
4374 * Send receipt from contribution.
4376 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4378 * Note that the compose message part has been moved to contribution
4379 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4381 * @param array $input
4382 * Incoming data from Payment processor.
4384 * Related object IDs.
4385 * @param int $contributionID
4386 * @param bool $returnMessageText
4387 * Should text be returned instead of sent. This.
4388 * is because the function is also used to generate pdfs
4391 * @throws \CRM_Core_Exception
4392 * @throws \CiviCRM_API3_Exception
4393 * @throws \Exception
4395 public static function sendMail($input, $ids, $contributionID, $returnMessageText = FALSE) {
4397 $contribution = new CRM_Contribute_BAO_Contribution();
4398 $contribution->id
= $contributionID;
4399 if (!$contribution->find(TRUE)) {
4400 throw new CRM_Core_Exception('Contribution does not exist');
4402 $contribution->loadRelatedObjects($input, $ids, TRUE);
4403 // set receipt from e-mail and name in value
4404 if (!$returnMessageText) {
4405 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4407 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4408 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4409 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4410 civicrm_api3('Contribution', 'create', [
4411 'receipt_date' => 'now',
4412 'id' => $contribution->id
,
4419 * Generate From email and from name in an array values
4421 * @param array $input
4422 * @param \CRM_Contribute_BAO_Contribution $contribution
4426 public static function generateFromEmailAndName($input, $contribution) {
4427 // Use input value if supplied.
4428 if (!empty($input['receipt_from_email'])) {
4430 CRM_Utils_Array
::value('receipt_from_name', $input, ''),
4431 $input['receipt_from_email'],
4434 // if we are still empty see if we can use anything from a contribution page.
4436 if (!empty($contribution->contribution_page_id
)) {
4437 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id
]);
4439 // if we are still empty see if we can use anything from a contribution page.
4440 if (!empty($pageValues['receipt_from_email'])) {
4442 CRM_Utils_Array
::value('receipt_from_name', $pageValues),
4443 $pageValues['receipt_from_email'],
4446 // If we are still empty fall back to the domain or logged in user information.
4447 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4451 * Load related memberships.
4455 * @return array $ids
4460 * Note that in theory it should be possible to retrieve these from the line_item table
4461 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4462 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4463 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4464 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4466 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4469 public function loadRelatedMembershipObjects($ids = []) {
4471 SELECT membership_id
4472 FROM civicrm_membership_payment
4473 WHERE contribution_id = %1 ";
4474 $params = [1 => [$this->id
, 'Integer']];
4475 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, []);
4477 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4478 while ($dao->fetch()) {
4479 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4480 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4484 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4485 foreach ($ids['membership'] as $id) {
4487 $membership = new CRM_Member_BAO_Membership();
4488 $membership->id
= $id;
4489 if (!$membership->find(TRUE)) {
4490 throw new Exception("Could not find membership record: $id");
4492 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4493 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4494 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4495 $this->_relatedObjects
['membership'][$membership->id
. '_' . $membership->membership_type_id
] = $membership;
4504 * Get the description (source field) for the recurring contribution.
4506 * @param CRM_Contribute_BAO_Contribution $contribution
4507 * @param int|null $participantID
4510 * @throws \CiviCRM_API3_Exception
4511 * @throws \API_Exception
4513 protected static function getRecurringContributionDescription($contribution, $participantID) {
4514 if (!empty($contribution->source
)) {
4515 return $contribution->source
;
4517 elseif (!empty($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
4518 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', [
4519 'id' => $contribution->contribution_page_id
,
4520 'return' => 'title',
4522 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4524 elseif ($participantID) {
4525 $eventTitle = Participant
::get(FALSE)
4526 ->addSelect('event.title')
4527 ->addWhere('id', '=', (int) $participantID)
4528 ->execute()->first()['event.title'];
4529 return ts('Online Event Registration') . ': ' . $eventTitle;
4531 elseif (!empty($contribution->contribution_recur_id
)) {
4532 return 'recurring contribution';
4538 * Function use to store line item proportionally in in entity financial trxn table
4540 * @param array $trxnParams
4542 * @param int $trxnId
4544 * @param float $contributionTotalAmount
4546 * @throws \CiviCRM_API3_Exception
4548 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4549 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4550 if (!empty($lineItems)) {
4551 // get financial item
4552 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4554 'contribution_total_amount' => $contributionTotalAmount,
4555 'trxn_total_amount' => $trxnParams['total_amount'],
4556 'trxn_id' => $trxnId,
4558 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4563 * Checks if line items total amounts
4564 * match the contribution total amount.
4566 * @param array $params
4567 * array of order params.
4569 * @throws \API_Exception
4571 public static function checkLineItems(&$params) {
4572 $totalAmount = $params['total_amount'] ??
NULL;
4573 $lineItemAmount = 0;
4575 foreach ($params['line_items'] as &$lineItems) {
4576 foreach ($lineItems['line_item'] as &$item) {
4577 if (empty($item['financial_type_id'])) {
4578 $item['financial_type_id'] = $params['financial_type_id'];
4580 $lineItemAmount +
= $item['line_total'] +
($item['tax_amount'] ??
0.00);
4584 if (!isset($totalAmount)) {
4585 $params['total_amount'] = $lineItemAmount;
4588 $currency = $params['currency'] ?? CRM_Core_Config
::singleton()->defaultCurrency
;
4590 if (!CRM_Utils_Money
::equals($totalAmount, $lineItemAmount, $currency)) {
4591 throw new CRM_Contribute_Exception_CheckLineItemsException();
4597 * Get the financial account for the item associated with the new transaction.
4599 * @param array $params
4600 * @param int $default
4604 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
4606 if (!empty($params['financial_account_id'])) {
4607 return $params['financial_account_id'];
4610 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4611 $preferredAccountsRelationships = [
4612 'Refunded' => 'Credit/Contra Revenue Account is',
4613 'Chargeback' => 'Chargeback Account is',
4616 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4617 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4618 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4620 $preferredAccountsRelationships[$contributionStatus]
4628 * ContributionPage values were being imposed onto values.
4630 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4631 * REALLY didn't want superimposed. The rest are left there in their overkill out
4634 * The rationale for making this explicit is that it was a case of carefully set values being
4635 * seemingly randonly overwritten without much care. In general I think array randomly setting
4636 * variables en mass is risky.
4638 * @param array $values
4642 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4643 $contributionPageValues = [];
4644 CRM_Contribute_BAO_ContributionPage
::setValues(
4645 $this->contribution_page_id
,
4646 $contributionPageValues
4649 // These are the values that I believe to be useful.
4652 'pay_later_receipt',
4654 'receipt_from_email',
4655 'receipt_from_name',
4659 'honoree_profile_id',
4660 'onbehalf_profile_id',
4661 'honor_block_is_active',
4662 // Kinda might be - but would be on the contribution...
4665 // Included for 'fear of regression' but can't justify any use for these....
4667 'payment_processor',
4668 'financial_type_id',
4669 'amount_block_is_active',
4674 'default_amount_id',
4678 'initial_amount_help_text',
4679 'initial_amount_label',
4681 'is_allow_other_amount',
4682 'is_billing_required',
4683 'is_confirm_enabled',
4684 'is_credit_card_only',
4686 'is_partial_payment',
4687 'is_recur_installments',
4688 'is_recur_interval',
4692 'min_initial_amount',
4693 'recur_frequency_unit',
4700 foreach ($valuesToCopy as $valueToCopy) {
4701 if (isset($contributionPageValues[$valueToCopy])) {
4702 if ($valueToCopy === 'title') {
4703 $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils
::getContributionPageTitle($this->contribution_page_id
);
4706 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
4714 * Get values of CiviContribute Settings
4715 * and check if its enabled or not.
4716 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
4717 * in serialized form. Usually this should be stored as flat settings for each form fields
4718 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
4719 * settings we will live with an inconsistency because it's too hard to change for now.
4720 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
4723 * @param string $name
4728 public static function checkContributeSettings($name) {
4729 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
4730 return $contributeSettings[$name] ??
NULL;
4734 * Get the contribution as it is in the database before being updated.
4736 * @param int $contributionID
4738 * @return \CRM_Contribute_BAO_Contribution|null
4740 private static function getOriginalContribution($contributionID) {
4741 return self
::getValues(['id' => $contributionID]);
4745 * Get the amount for the financial item row.
4747 * Helper function to start to break down recordFinancialTransactions for readability.
4749 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
4751 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
4752 * for historical reasons. Going forwards we can hope to add tests & improve readibility
4755 * @param array $params
4756 * Params as passed to contribution.create
4758 * @param string $context
4759 * changeFinancialType| changedAmount
4760 * @param array $lineItemDetails
4762 * @param bool $isARefund
4763 * Is this a refund / negative transaction.
4764 * @param int $previousLineItemTotal
4767 * @todo move recordFinancialAccounts & helper functions to their own class?
4770 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
4771 if ($context == 'changedAmount') {
4772 $lineTotal = $lineItemDetails['line_total'];
4773 if ($lineTotal != $previousLineItemTotal) {
4774 $lineTotal -= $previousLineItemTotal;
4778 elseif ($context == 'changeFinancialType') {
4779 return -$lineItemDetails['line_total'];
4781 elseif ($context == 'changedStatus') {
4782 $cancelledTaxAmount = 0;
4784 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
4786 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
4788 elseif ($context === NULL) {
4789 // erm, yes because? but, hey, it's tested.
4790 return $lineItemDetails['line_total'];
4792 elseif (empty($lineItemDetails['line_total'])) {
4793 // follow legacy code path
4795 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', ['civi.tag' => 'deprecated']);
4796 return $params['total_amount'];
4799 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
4804 * Get the multiplier for adjusting rows.
4806 * If we are dealing with a refund or cancellation then it will be a negative
4807 * amount to reflect the negative transaction.
4809 * If we are changing Financial Type it will be a negative amount to
4810 * adjust down the old type.
4812 * @param int $contribution_status_id
4813 * @param string $context
4817 protected static function getMultiplier($contribution_status_id, $context) {
4818 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
4825 * Does this transaction reflect a payment instrument change.
4827 * @param array $params
4828 * @param array $pendingStatuses
4832 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
4833 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
4835 if (array_key_exists('payment_instrument_id', $params)) {
4836 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
4837 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
4839 //check if status is changed from Pending to Completed
4840 // do not update payment instrument changes for Pending to Completed
4841 if (!($contributionStatus == 'Completed' &&
4842 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
4847 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
4848 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
4849 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
4853 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
4854 $params['contribution']->check_number
!= $params['prevContribution']->check_number
4856 // another special case when check number is changed, create new financial records
4857 // create financial trxn with negative amount
4865 * Update the memberships associated with a contribution if it has been completed.
4867 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
4868 * load them in this function. Code clean up would compensate for any minor performance implication.
4870 * @param int $contributionID
4871 * @param string $changeDate
4873 * @throws \CRM_Core_Exception
4874 * @throws \CiviCRM_API3_Exception
4876 public static function updateMembershipBasedOnCompletionOfContribution($contributionID, $changeDate) {
4877 $memberships = self
::getRelatedMemberships($contributionID);
4878 foreach ($memberships as $membership) {
4879 $membershipParams = [
4880 'id' => $membership['id'],
4881 'contact_id' => $membership['contact_id'],
4882 'is_test' => $membership['is_test'],
4883 'membership_type_id' => $membership['membership_type_id'],
4884 'membership_activity_status' => 'Completed',
4887 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4888 $membershipParams['membership_type_id'],
4889 $membershipParams['is_test'],
4890 $membershipParams['id']
4893 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4894 // this picks up membership type changes during renewals
4895 // @todo this is almost certainly an obsolete sql call, the pre-change
4896 // membership is accessible via $this->_relatedObjects
4898 SELECT membership_type_id
4899 FROM civicrm_membership_log
4900 WHERE membership_id={$membershipParams['id']}
4903 $dao = CRM_Core_DAO
::executeQuery($sql);
4904 if ($dao->fetch()) {
4905 if (!empty($dao->membership_type_id
)) {
4906 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4909 if (empty($membership['end_date']) ||
(int) $membership['status_id'] !== CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
4910 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
4911 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
4912 // 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.
4913 // ... except testCompleteTransactionMembershipPriceSetTwoTerms hits this line so the above is obviously not true....
4914 // @todo once apiv4 ships with core switch to that & find sanity.
4915 $membershipParams['num_terms'] = self
::getNumTermsByContributionAndMembershipType(
4916 $membershipParams['membership_type_id'],
4920 // @todo remove all this stuff in favour of letting the api call further down handle in
4921 // (it is a duplication of what the api does).
4922 $dates = array_fill_keys([
4927 if ($currentMembership) {
4929 * Fixed FOR CRM-4433
4930 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4931 * when Contribution mode is notify and membership is for renewal )
4933 // Test cover for this is in testRepeattransactionRenewMembershipOldMembership
4935 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4937 // @todo - we should pass membership_type_id instead of null here but not
4938 // adding as not sure of testing
4939 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4940 $changeDate, NULL, $membershipParams['num_terms']
4942 $dates['join_date'] = $currentMembership['join_date'];
4945 //get the status for membership.
4946 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4948 $dates['join_date'],
4951 $membershipParams['membership_type_id'],
4955 unset($dates['end_date']);
4956 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4957 //we might be renewing membership,
4958 //so make status override false.
4959 $membershipParams['is_override'] = FALSE;
4960 $membershipParams['status_override_end_date'] = 'null';
4961 civicrm_api3('Membership', 'create', $membershipParams);
4966 * Get payment links as they relate to a contribution.
4968 * If a payment can be made then include a payment link & if a refund is appropriate
4969 * then a refund link.
4972 * @param float $balance
4973 * @param string $contributionStatus
4976 * $actionLinks Links array containing:
4980 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
4981 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
4982 // In general the balance is the best way to determine if a payment can be added or not,
4983 // but not for Failed contributions, where we don't accept additional payments at the moment.
4984 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
4985 // do accept more payments agains them.
4990 'url' => CRM_Utils_System
::url('civicrm/payment', [
4996 'title' => ts('Record Payment'),
4999 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
5001 'url' => CRM_Utils_System
::url('civicrm/payment', [
5008 'title' => ts('Submit Credit Card payment'),
5012 'url' => CRM_Utils_System
::url('civicrm/payment', [
5018 'title' => ts('Record Refund'),
5020 return $actionLinks;
5024 * Get a query to determine the amount donated by the contact/s in the current financial year.
5026 * @param array $contactIDs
5030 public static function getAnnualQuery($contactIDs) {
5031 $contactIDs = implode(',', $contactIDs);
5032 $config = CRM_Core_Config
::singleton();
5033 $currentMonth = date('m');
5034 $currentDay = date('d');
5036 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
5038 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
5039 (int) $config->fiscalYearStart
['d'] > $currentDay
5042 $year = date('Y') - 1;
5047 $nextYear = $year +
1;
5049 if ($config->fiscalYearStart
) {
5050 $newFiscalYearStart = $config->fiscalYearStart
;
5051 if ($newFiscalYearStart['M'] < 10) {
5052 // This is just a clumsy way of adding padding.
5053 // @todo next round look for a nicer way.
5054 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
5056 if ($newFiscalYearStart['d'] < 10) {
5057 // This is just a clumsy way of adding padding.
5058 // @todo next round look for a nicer way.
5059 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
5061 $config->fiscalYearStart
= $newFiscalYearStart;
5062 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
5065 // First of January.
5068 $startDate = "$year$monthDay";
5069 $endDate = "$nextYear$monthDay";
5072 'contact_id' => 'IN (' . $contactIDs . ')',
5073 'is_test' => ' = 0',
5074 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
5076 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
5077 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
5080 foreach ($whereClauses as $key => $clause) {
5081 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
5083 $whereClauseString = implode(' AND ', $clauses);
5085 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5086 // this group by + having on contribution_status_id improves performance
5088 SELECT COUNT(*) as count,
5089 SUM(total_amount) as amount,
5090 AVG(total_amount) as average,
5092 FROM civicrm_contribution b
5093 WHERE " . $whereClauseString . "
5094 GROUP BY currency, contribution_status_id
5095 HAVING $havingClause
5101 * Assign Test Value.
5103 * @param string $fieldName
5104 * @param array $fieldDef
5105 * @param int $counter
5107 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5108 if ($fieldName == 'tax_amount') {
5109 $this->{$fieldName} = "0.00";
5111 elseif ($fieldName == 'net_amount') {
5112 $this->{$fieldName} = "2.00";
5114 elseif ($fieldName == 'total_amount') {
5115 $this->{$fieldName} = "3.00";
5117 elseif ($fieldName == 'fee_amount') {
5118 $this->{$fieldName} = "1.00";
5121 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5126 * Check if contribution has participant/membership payment.
5128 * @param int $contributionId
5133 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5134 // get line item for contribution
5135 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5136 // check if line item is for membership or participant
5137 foreach ($lineItems as $items) {
5138 if ($items['entity_table'] == 'civicrm_participant') {
5142 elseif ($items['entity_table'] == 'civicrm_membership') {
5154 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5156 * @param array $trxnParams
5157 * Financial trxn params
5158 * @param array $contributionParams
5159 * Contribution Params
5163 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5164 if (!Civi
::settings()->get('always_post_to_accounts_receivable')) {
5167 $statusId = $contributionParams['contribution']->contribution_status_id
;
5168 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5169 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5170 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5171 // Return if contribution status is not completed.
5172 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5173 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5174 && $contributionParams['prevContribution']->is_pay_later
== 0
5180 $params = $trxnParams;
5181 $financialTypeID = !empty($contributionParams['financial_type_id']) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5182 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5183 $params['to_financial_account_id'] = $arAccountId;
5184 $params['status_id'] = array_search('Pending', $contributionStatuses);
5185 $params['is_payment'] = FALSE;
5186 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5187 self
::$_trxnIDs[] = $trxn->id
;
5188 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5192 * Calculate financial item amount when contribution is updated.
5194 * @param array $params
5195 * contribution params
5196 * @param array $amountParams
5198 * @param string $context
5202 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5203 if (!empty($params['is_quick_config'])) {
5204 $amount = $amountParams['item_amount'];
5206 $amount = $params['total_amount'];
5207 if ($context === NULL) {
5208 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5213 $amount = $amountParams['line_total'];
5214 if ($context == 'changedAmount') {
5215 $amount -= $amountParams['previous_line_total'];
5217 $amount *= $amountParams['diff'];
5223 * Retrieve Sales Tax Financial Accounts.
5229 public static function getSalesTaxFinancialAccounts() {
5230 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5231 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5232 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5233 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5234 $queryParams = [1 => [$accountRel, 'Integer']];
5235 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5236 $financialAccount = [];
5237 while ($dao->fetch()) {
5238 $financialAccount[$dao->id
] = $dao->id
;
5240 return $financialAccount;
5244 * Create tax entry in civicrm_entity_financial_trxn table.
5246 * @param array $entityParams
5248 * @param array $eftParams
5250 * @throws \CiviCRM_API3_Exception
5252 public static function createProportionalEntry($entityParams, $eftParams) {
5254 if ($entityParams['contribution_total_amount'] != 0) {
5255 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5257 // Record Entity Financial Trxn; CRM-20145
5258 $eftParams['amount'] = $paid;
5259 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5263 * Create array of last financial item id's.
5265 * @param int $contributionId
5269 public static function getLastFinancialItemIds($contributionId) {
5270 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5271 FROM civicrm_financial_item fi
5272 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5273 WHERE li.contribution_id = %1";
5274 $dao = CRM_Core_DAO
::executeQuery($sql, [
5280 $ftIds = $taxItems = [];
5281 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5282 while ($dao->fetch()) {
5283 /* if sales tax item*/
5284 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5285 $taxItems[$dao->price_field_value_id
] = [
5286 'financial_item_id' => $dao->id
,
5287 'amount' => $dao->tax_amount
,
5291 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5294 return [$ftIds, $taxItems];
5298 * Create proportional entries in civicrm_entity_financial_trxn.
5300 * @param array $entityParams
5302 * @param array $lineItems
5304 * @param array $ftIds
5306 * @param array $taxItems
5308 * @throws \CiviCRM_API3_Exception
5310 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5312 'entity_table' => 'civicrm_financial_item',
5313 'financial_trxn_id' => $entityParams['trxn_id'],
5315 foreach ($lineItems as $key => $value) {
5316 if ($value['qty'] == 0) {
5319 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5320 $entityParams['line_item_amount'] = $value['line_total'];
5321 self
::createProportionalEntry($entityParams, $eftParams);
5322 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5323 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5324 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5325 self
::createProportionalEntry($entityParams, $eftParams);
5331 * Load entities related to the contribution into $this->_relatedObjects.
5335 * @throws \CRM_Core_Exception
5337 protected function loadRelatedEntitiesByID($ids) {
5339 'contact' => 'CRM_Contact_BAO_Contact',
5340 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5341 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5342 'financialType' => 'CRM_Financial_BAO_FinancialType',
5343 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5345 foreach ($entities as $entity => $bao) {
5346 if (!empty($ids[$entity])) {
5347 $this->_relatedObjects
[$entity] = new $bao();
5348 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5349 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5350 throw new CRM_Core_Exception($entity . ' could not be loaded');
5357 * Function to replace contribution tokens.
5359 * @param array $contributionIds
5361 * @param string $subject
5363 * @param array $subjectToken
5365 * @param string $text
5367 * @param string $html
5369 * @param array $messageToken
5371 * @param bool $escapeSmarty
5374 * @throws \CiviCRM_API3_Exception
5376 public static function replaceContributionTokens(
5385 if (empty($contributionIds)) {
5388 $contributionDetails = [];
5389 foreach ($contributionIds as $id) {
5390 $result = self
::getContributionTokenValues($id, $messageToken);
5391 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5392 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5393 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5395 return $contributionDetails;
5399 * Get the contribution fields for $id and display labels where
5400 * appropriate (if the token is present).
5403 * @param array $messageToken
5406 public static function getContributionTokenValues($id, $messageToken) {
5410 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5411 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5412 if (!empty($messageToken)) {
5413 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5414 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5415 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField
::displayValue($result['values'][$id][$fieldName], $fieldName);
5423 * Get invoice_number for contribution.
5425 * @param int $contributionID
5429 public static function getInvoiceNumber($contributionID) {
5430 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix')) {
5431 return $invoicePrefix . $contributionID;
5438 * Load the values needed for the event message.
5440 * @param int $eventID
5441 * @param int $participantID
5442 * @param int|null $contributionID
5445 * @throws \CRM_Core_Exception
5447 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5452 $values = ['event' => []];
5454 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
5455 // add custom fields for event
5456 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $eventID);
5458 $eventCustomGroup = [];
5459 foreach ($eventGroupTree as $key => $group) {
5460 if ($key === 'info') {
5464 foreach ($group['fields'] as $k => $customField) {
5465 $groupLabel = $group['title'];
5466 if (!empty($customField['customValue'])) {
5467 foreach ($customField['customValue'] as $customFieldValues) {
5468 $eventCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5473 $values['event']['customGroup'] = $eventCustomGroup;
5475 //get participant details
5476 $participantParams = [
5477 'id' => $participantID,
5480 $values['participant'] = [];
5482 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
5483 // add custom fields for event
5484 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $participantID);
5485 $participantCustomGroup = [];
5486 foreach ($participantGroupTree as $key => $group) {
5487 if ($key === 'info') {
5491 foreach ($group['fields'] as $k => $customField) {
5492 $groupLabel = $group['title'];
5493 if (!empty($customField['customValue'])) {
5494 foreach ($customField['customValue'] as $customFieldValues) {
5495 $participantCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5500 $values['participant']['customGroup'] = $participantCustomGroup;
5502 //get location details
5504 'entity_id' => $eventID,
5505 'entity_table' => 'civicrm_event',
5507 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
5510 'entity_table' => 'civicrm_event',
5511 'entity_id' => $eventID,
5512 'module' => 'CiviEvent',
5515 list($custom_pre_id,
5517 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
5519 $values['custom_pre_id'] = $custom_pre_id;
5520 $values['custom_post_id'] = $custom_post_ids;
5522 // set lineItem for event contribution
5523 if ($contributionID) {
5524 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($contributionID);
5525 if (!empty($participantIds)) {
5526 foreach ($participantIds as $pIDs) {
5527 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
5528 if (!CRM_Utils_System
::isNull($lineItem)) {
5529 $values['lineItem'][] = $lineItem;