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\PaymentProcessor
;
20 * @copyright CiviCRM LLC https://civicrm.org/licensing
22 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
25 * Static field for all the contribution information that we can potentially import
29 public static $_importableFields = NULL;
32 * Static field for all the contribution information that we can potentially export
36 public static $_exportableFields = NULL;
39 * Static field to hold financial trxn id's.
43 public static $_trxnIDs = NULL;
46 * Field for all the objects related to this contribution.
49 * 1) deprecated function transitionComponents
50 * 2) function to send contribution receipts _assignMessageVariablesToTemplate
51 * 3) some invoice code that is copied from 2
52 * 4) odds & sods that need to be investigated and fixed.
54 * However, it is no longer used by completeOrder.
56 * @var \CRM_Member_BAO_Membership|\CRM_Event_BAO_Participant[]
60 public $_relatedObjects = [];
63 * Field for the component - either 'event' (participant) or 'contribute'
64 * (any item related to a contribution page e.g. membership, pledge, contribution)
65 * This is used for composing messages because they have dependency on the
66 * contribution_page or event page - although over time we may eliminate that
69 * "contribution"\"event"
71 public $_component = NULL;
74 * Possibly obsolete variable.
76 * If you use it please explain why it is set in the create function here.
80 public $trxn_result_code;
85 public function __construct() {
86 parent
::__construct();
90 * Takes an associative array and creates a contribution object.
92 * the function extract all the params it needs to initialize the create a
93 * contribution object. the params array could contain additional unused name/value
96 * @param array $params
97 * (reference ) an assoc array of name/value pairs.
99 * @return \CRM_Contribute_BAO_Contribution
100 * @throws \CRM_Core_Exception
101 * @throws \CiviCRM_API3_Exception
103 public static function add(&$params) {
104 if (empty($params)) {
108 $contributionID = $params['id'] ??
NULL;
109 $action = $contributionID ?
'edit' : 'create';
111 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
112 $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)]);
113 throw new CRM_Core_Exception($message);
116 //set defaults in create mode
117 if (!$contributionID) {
118 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
119 if (empty($params['invoice_number']) && CRM_Invoicing_Utils
::isInvoicingEnabled()) {
120 $nextContributionID = CRM_Core_DAO
::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
121 $params['invoice_number'] = self
::getInvoiceNumber($nextContributionID);
125 $contributionStatusID = $params['contribution_status_id'] ??
NULL;
126 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $contributionStatusID) === 'Partially paid' && empty($params['is_post_payment_create'])) {
127 CRM_Core_Error
::deprecatedFunctionWarning('Setting status to partially paid other than by using Payment.create is deprecated and unreliable');
129 if (!$contributionStatusID) {
130 // Since the fee amount is expecting this (later on) ensure it is always set.
131 // It would only not be set for an update where it is unchanged.
132 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', [
133 'id' => $contributionID,
134 'return' => 'contribution_status_id',
137 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['contribution_status_id']);
140 && !empty($params['membership_id'])
141 && Civi
::settings()->get('deferred_revenue_enabled')
143 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
144 if ($memberStartDate) {
145 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
148 self
::calculateMissingAmountParams($params, $contributionID);
150 if (!empty($params['payment_instrument_id'])) {
151 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
152 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
153 $params['check_number'] = 'null';
157 $setPrevContribution = TRUE;
158 if ($contributionID && $setPrevContribution) {
159 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
161 $previousContributionStatus = ($contributionID && !empty($params['prevContribution'])) ? CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['prevContribution']->contribution_status_id
) : NULL;
163 if ($contributionID && !empty($params['revenue_recognition_date'])
164 && !($previousContributionStatus === 'Pending')
165 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
167 unset($params['revenue_recognition_date']);
170 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
171 isset($params['financial_type_id']))) {
172 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
175 CRM_Utils_Hook
::pre($action, 'Contribution', $contributionID, $params);
177 $contribution = new CRM_Contribute_BAO_Contribution();
178 $contribution->copyValues($params);
180 $contribution->id
= $contributionID;
182 if (empty($contribution->id
)) {
183 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
184 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
185 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
189 $result = $contribution->save();
191 // Add financial_trxn details as part of fix for CRM-4724
192 $contribution->trxn_result_code
= $params['trxn_result_code'] ??
NULL;
193 $contribution->payment_processor
= $params['payment_processor'] ??
NULL;
195 //add Account details
196 $params['contribution'] = $contribution;
197 if (empty($params['is_post_payment_create'])) {
198 // If this is being called from the Payment.create api/ BAO then that Entity
199 // takes responsibility for the financial transactions. In fact calling Payment.create
200 // to add payments & having it call completetransaction and / or contribution.create
201 // to update related entities is the preferred flow.
202 // Note that leveraging this parameter for any other code flow is not supported and
203 // is likely to break in future and / or cause serious problems in your data.
204 // https://github.com/civicrm/civicrm-core/pull/14673
205 self
::recordFinancialAccounts($params);
208 if (self
::isUpdateToRecurringContribution($params)) {
209 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
210 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
212 $params['receive_date'] ??
NULL
216 $params['contribution_id'] = $contribution->id
;
218 if (!empty($params['custom']) &&
219 is_array($params['custom'])
221 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
, $action);
224 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
226 CRM_Utils_Hook
::post($action, 'Contribution', $contribution->id
, $contribution);
231 * Is this contribution updating an existing recurring contribution.
233 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
234 * pending payment is being confirmed (or failing).
236 * @param array $params
240 public static function isUpdateToRecurringContribution($params) {
241 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
244 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
247 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
250 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
251 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
258 * Get defaults for new entity.
262 public static function getDefaults() {
264 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
265 FALSE, FALSE, FALSE, 'AND is_default = 1')
267 'contribution_status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
268 'receive_date' => date('Y-m-d H:i:s'),
273 * Fetch the object and store the values in the values array.
275 * @param array $params
276 * Input parameters to find object.
277 * @param array $values
278 * Output values of the object.
280 * The array that holds all the db ids.
282 * @return CRM_Contribute_BAO_Contribution|null
283 * The found object or null
285 public static function getValues($params, &$values = [], &$ids = []) {
286 if (empty($params)) {
289 $contribution = new CRM_Contribute_BAO_Contribution();
291 $contribution->copyValues($params);
293 if ($contribution->find(TRUE)) {
294 $ids['contribution'] = $contribution->id
;
296 CRM_Core_DAO
::storeValues($contribution, $values);
298 return $contribution;
300 // return by reference
306 * Get the values and resolve the most common mappings.
308 * Since contribution status is resolved in almost every function that calls getValues it makes
309 * sense to have an extra function to resolve it rather than repeat the code.
311 * Think carefully before adding more mappings to be resolved as there could be performance implications
312 * if this function starts to be called from more iterative functions.
314 * @param array $params
315 * Input parameters to find object.
318 * Array of the found contribution.
319 * @throws CRM_Core_Exception
321 public static function getValuesWithMappings($params) {
323 $contribution = self
::getValues($params, $values, $ids);
324 if (is_null($contribution)) {
325 throw new CRM_Core_Exception('No contribution found');
327 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
332 * Calculate net_amount & fee_amount if they are not set.
334 * Net amount should be total - fee.
335 * This should only be called for new contributions.
337 * @param array $params
338 * Params for a new contribution before they are saved.
339 * @param int|null $contributionID
340 * Contribution ID if we are dealing with an update.
342 * @throws \CiviCRM_API3_Exception
344 public static function calculateMissingAmountParams(&$params, $contributionID) {
345 if (!$contributionID && !isset($params['fee_amount'])) {
346 if (isset($params['total_amount']) && isset($params['net_amount'])) {
347 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
350 $params['fee_amount'] = 0;
353 if (!isset($params['net_amount'])) {
354 if (!$contributionID) {
355 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
358 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
359 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
360 // net_amount may need adjusting.
361 $contribution = civicrm_api3('Contribution', 'getsingle', [
362 'id' => $contributionID,
363 'return' => ['total_amount', 'net_amount', 'fee_amount'],
365 $totalAmount = (isset($params['total_amount']) ?
(float) $params['total_amount'] : (float) CRM_Utils_Array
::value('total_amount', $contribution));
366 $feeAmount = (isset($params['fee_amount']) ?
(float) $params['fee_amount'] : (float) CRM_Utils_Array
::value('fee_amount', $contribution));
367 $params['net_amount'] = $totalAmount - $feeAmount;
375 * @param $billingLocationTypeID
379 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
380 $hasBillingField = FALSE;
389 //build address array
391 $addressParams['location_type_id'] = $billingLocationTypeID;
392 $addressParams['is_billing'] = 1;
394 $billingFirstName = $params['billing_first_name'] ??
NULL;
395 $billingMiddleName = $params['billing_middle_name'] ??
NULL;
396 $billingLastName = $params['billing_last_name'] ??
NULL;
397 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
399 foreach ($billingFields as $value) {
400 $addressParams[$value] = $params["billing_{$value}-{$billingLocationTypeID}"] ??
NULL;
401 if (!empty($addressParams[$value])) {
402 $hasBillingField = TRUE;
405 return [$hasBillingField, $addressParams];
409 * Get address params ready to be passed to the payment processor.
411 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
412 * To create an address we need state_province_id.
414 * @param array $params
415 * @param int $billingLocationTypeID
419 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
420 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
421 foreach ($addressParams as $name => $field) {
422 if (substr($name, 0, 8) == 'billing_') {
423 $addressParams[substr($name, 9)] = $addressParams[$field];
426 return [$hasBillingField, $addressParams];
430 * Get the number of terms for this contribution for a given membership type
431 * based on querying the line item table and relevant price field values
432 * Note that any one contribution should only be able to have one line item relating to a particular membership
435 * @param int $membershipTypeID
437 * @param int $contributionID
441 public static function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
442 $numTerms = CRM_Core_DAO
::singleValueQuery("
443 SELECT membership_num_terms FROM civicrm_line_item li
444 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
445 WHERE contribution_id = %1 AND membership_type_id = %2",
446 [1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']]
448 // default of 1 is precautionary
449 return empty($numTerms) ?
1 : $numTerms;
453 * Takes an associative array and creates a contribution object.
455 * @param array $params
456 * (reference ) an assoc array of name/value pairs.
458 * @return CRM_Contribute_BAO_Contribution
460 * @throws \API_Exception
461 * @throws \CRM_Core_Exception
462 * @throws \CiviCRM_API3_Exception
464 public static function create(&$params) {
466 $transaction = new CRM_Core_Transaction();
469 $contribution = self
::add($params);
471 catch (CRM_Core_Exception
$e) {
472 $transaction->rollback();
476 $params['contribution_id'] = $contribution->id
;
477 $session = CRM_Core_Session
::singleton();
479 if (!empty($params['note'])) {
481 'entity_table' => 'civicrm_contribution',
482 'note' => $params['note'],
483 'entity_id' => $contribution->id
,
484 'contact_id' => $session->get('userID'),
486 if (!$noteParams['contact_id']) {
487 $noteParams['contact_id'] = $params['contact_id'];
489 CRM_Core_BAO_Note
::add($noteParams);
492 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
494 $transaction->commit();
496 if (empty($contribution->contact_id
)) {
497 $contribution->find(TRUE);
500 $isCompleted = ('Completed' === CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
));
501 if (!empty($params['on_behalf'])
504 $existingActivity = Activity
::get(FALSE)->setWhere([
505 ['source_record_id', '=', $contribution->id
],
506 ['activity_type_id:name', '=', 'Contribution'],
507 ])->execute()->first();
509 $campaignParams = isset($params['campaign_id']) ?
['campaign_id' => ($params['campaign_id'] ??
NULL)] : [];
510 Activity
::save(FALSE)->addRecord(array_merge([
511 'activity_type_id:name' => 'Contribution',
512 'source_record_id' => $contribution->id
,
513 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ?
: $contribution->contact_id
,
514 'target_contact_id' => CRM_Core_Session
::getLoggedInContactID() ?
[$contribution->contact_id
] : [],
515 'activity_date_time' => $contribution->receive_date
,
516 'is_test' => (bool) $contribution->is_test
,
517 'status_id:name' => $isCompleted ?
'Completed' : 'Scheduled',
518 'skipRecentView' => TRUE,
519 'subject' => CRM_Activity_BAO_Activity
::getActivitySubject($contribution),
520 'id' => $existingActivity['id'] ??
NULL,
521 ], $campaignParams))->execute();
524 // do not add to recent items for import, CRM-4399
525 if (empty($params['skipRecentView'])) {
526 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
527 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
529 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
536 $retrieveRequired = 0;
537 foreach ($titleFields as $titleField) {
538 if (!isset($contribution->$titleField)) {
539 $retrieveRequired = 1;
543 if ($retrieveRequired == 1) {
544 $contribution->find(TRUE);
546 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
547 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
550 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
551 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
552 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
556 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
557 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
558 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
562 // add the recently created Contribution
563 CRM_Utils_Recent
::add($title,
567 $contribution->contact_id
,
573 return $contribution;
577 * Get the values for pseudoconstants for name->value and reverse.
579 * @param array $defaults
580 * (reference) the default values, some of which need to be resolved.
581 * @param bool $reverse
582 * True if we want to resolve the values in the reverse direction (value -> name).
584 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
585 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
586 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
587 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'), $reverse);
588 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
592 * Convert associative array names to values and vice-versa.
594 * This function is used by both the web form layer and the api. Note that
595 * the api needs the name => value conversion, also the view layer typically
596 * requires value => name conversion
598 * @param array $defaults
599 * @param string $property
600 * @param array $lookup
601 * @param bool $reverse
605 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
606 $id = $property . '_id';
608 $src = $reverse ?
$property : $id;
609 $dst = $reverse ?
$id : $property;
611 if (!array_key_exists($src, $defaults)) {
615 $look = $reverse ?
array_flip($lookup) : $lookup;
617 if (is_array($look)) {
618 if (!array_key_exists($defaults[$src], $look)) {
622 $defaults[$dst] = $look[$defaults[$src]];
627 * Retrieve DB object based on input parameters.
629 * It also stores all the retrieved values in the default array.
631 * @param array $params
632 * (reference ) an assoc array of name/value pairs.
633 * @param array $defaults
634 * (reference ) an assoc array to hold the name / value pairs.
635 * in a hierarchical manner
637 * (reference) the array that holds all the db ids.
639 * @return CRM_Contribute_BAO_Contribution
641 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
642 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
643 return $contribution;
647 * Combine all the importable fields from the lower levels object.
649 * The ordering is important, since currently we do not have a weight
650 * scheme. Adding weight is super important and should be done in the
651 * next week or so, before this can be called complete.
653 * @param string $contactType
654 * @param bool $status
657 * array of importable Fields
659 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
660 if (!self
::$_importableFields) {
661 if (!self
::$_importableFields) {
662 self
::$_importableFields = [];
666 $fields = ['' => ['title' => ts('- do not import -')]];
669 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
672 $note = CRM_Core_DAO_Note
::import();
673 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
674 unset($tmpFields['option_value']);
675 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
676 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
678 // Using new Dedupe rule.
680 'contact_type' => $contactType,
681 'used' => 'Unsupervised',
683 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
684 $tmpContactField = [];
685 if (is_array($fieldsArray)) {
686 foreach ($fieldsArray as $value) {
687 //skip if there is no dupe rule
688 if ($value == 'none') {
691 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
696 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
697 $tmpContactField[trim($value)] = $contactFields[trim($value)];
699 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
702 $title = $tmpContactField[trim($value)]['title'];
704 $tmpContactField[trim($value)]['title'] = $title;
708 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
709 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
710 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
711 $fields = array_merge($fields, $tmpContactField);
712 $fields = array_merge($fields, $tmpFields);
713 $fields = array_merge($fields, $note);
714 $fields = array_merge($fields, $optionFields);
715 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
716 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
717 self
::$_importableFields = $fields;
719 return self
::$_importableFields;
723 * Combine all the exportable fields from the lower level objects.
725 * @param bool $checkPermission
728 * array of exportable Fields
730 public static function &exportableFields($checkPermission = TRUE) {
731 if (!self
::$_exportableFields) {
732 if (!self
::$_exportableFields) {
733 self
::$_exportableFields = [];
736 $fields = CRM_Contribute_DAO_Contribution
::export();
737 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
738 $fields = array_merge(
740 CRM_Contribute_DAO_Product
::export(),
741 CRM_Contribute_DAO_ContributionProduct
::export(),
742 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
744 'contribution_product_id' => [
745 'title' => ts('Premium'),
746 'name' => 'contribution_product_id',
747 'where' => 'civicrm_product.id',
748 'data_type' => CRM_Utils_Type
::T_INT
,
754 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
756 $contributionPage = [
757 'contribution_page' => [
758 'title' => ts('Contribution Page'),
759 'name' => 'contribution_page',
760 'where' => 'civicrm_contribution_page.title',
761 'data_type' => CRM_Utils_Type
::T_STRING
,
765 $contributionNote = [
766 'contribution_note' => [
767 'title' => ts('Contribution Note'),
768 'name' => 'contribution_note',
769 'data_type' => CRM_Utils_Type
::T_TEXT
,
774 'contribution_batch' => [
775 'title' => ts('Batch Name'),
781 'contribution_campaign_title' => [
782 'title' => ts('Campaign Title'),
783 'name' => 'campaign_title',
784 'where' => 'civicrm_campaign.title',
785 'data_type' => CRM_Utils_Type
::T_STRING
,
788 $softCreditFields = [
789 'contribution_soft_credit_name' => [
790 'name' => 'contribution_soft_credit_name',
791 'title' => ts('Soft Credit For'),
792 'where' => 'civicrm_contact_d.display_name',
793 'data_type' => CRM_Utils_Type
::T_STRING
,
795 'contribution_soft_credit_amount' => [
796 'name' => 'contribution_soft_credit_amount',
797 'title' => ts('Soft Credit Amount'),
798 'where' => 'civicrm_contribution_soft.amount',
799 'data_type' => CRM_Utils_Type
::T_MONEY
,
801 'contribution_soft_credit_type' => [
802 'name' => 'contribution_soft_credit_type',
803 'title' => ts('Soft Credit Type'),
804 'where' => 'contribution_softcredit_type.label',
805 'data_type' => CRM_Utils_Type
::T_STRING
,
807 'contribution_soft_credit_contribution_id' => [
808 'name' => 'contribution_soft_credit_contribution_id',
809 'title' => ts('Soft Credit For Contribution ID'),
810 'where' => 'civicrm_contribution_soft.contribution_id',
811 'data_type' => CRM_Utils_Type
::T_INT
,
813 'contribution_soft_credit_contact_id' => [
814 'name' => 'contribution_soft_credit_contact_id',
815 'title' => ts('Soft Credit For Contact ID'),
816 'where' => 'civicrm_contact_d.id',
817 'data_type' => CRM_Utils_Type
::T_INT
,
821 $fields = array_merge($fields, $contributionPage,
822 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
823 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
826 self
::$_exportableFields = $fields;
829 return self
::$_exportableFields;
833 * Record an activity when a payment is received.
835 * @todo this is intended to be moved to payment BAO class as a protected function
836 * on that class. Currently being cleaned up. The addActivityForPayment doesn't really
837 * merit it's own function as it makes the code less rather than more readable.
839 * @param int $contributionId
840 * @param int $participantId
841 * @param string $totalAmount
842 * @param string $currency
843 * @param string $trxnDate
845 * @throws \CRM_Core_Exception
846 * @throws \CiviCRM_API3_Exception
848 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
849 $activityType = ($totalAmount < 0) ?
'Refund' : 'Payment';
851 if ($participantId) {
852 $inputParams['id'] = $participantId;
855 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
856 $entityObj = $entityObj[$participantId];
857 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
860 $entityObj = new CRM_Contribute_BAO_Contribution();
861 $entityObj->id
= $contributionId;
862 $entityObj->find(TRUE);
863 $title = ts('Contribution');
865 // @todo per block above this is not a logical splitting off of functionality.
866 self
::addActivityForPayment($entityObj->contact_id
, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
870 * Get the value for the To Financial Account.
872 * @param $contribution
877 public static function getToFinancialAccount($contribution, $params) {
878 if (!empty($params['payment_processor_id'])) {
879 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor_id'], NULL, 'civicrm_payment_processor');
881 if (!empty($params['payment_instrument_id'])) {
882 return CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
885 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
886 $queryParams = [1 => [$relationTypeId, 'Integer']];
887 return CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
892 * Get memberships related to the contribution.
894 * @param int $contributionID
898 protected static function getRelatedMemberships($contributionID) {
899 $membershipPayments = civicrm_api3('MembershipPayment', 'get', [
900 'return' => 'membership_id',
901 'contribution_id' => (int) $contributionID,
904 foreach ($membershipPayments as $membershipPayment) {
905 $membershipIDs[] = $membershipPayment['membership_id'];
907 if (empty($membershipIDs)) {
910 // We could combine this with the MembershipPayment.get - we'd
911 // need to re-wrangle the params (here or in the calling function)
912 // as they would then me membership.contact_id, membership.is_test etc
913 return civicrm_api3('Membership', 'get', [
914 'id' => ['IN' => $membershipIDs],
915 'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'],
920 * Cancel contribution.
922 * This function should only be called from transitioncomponents - it is an interim step in refactoring.
924 * @param $memberships
925 * @param $contributionId
926 * @param $membershipStatuses
927 * @param $participant
929 * @param $pledgePayment
931 * @param $pledgePaymentIDs
932 * @param $contributionStatusId
934 protected static function cancel($memberships, $contributionId, $membershipStatuses, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId) {
935 // @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
936 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
937 if (is_array($memberships)) {
938 foreach ($memberships as $membership) {
940 //Update Membership status if there is no other completed contribution associated with the membership.
941 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
942 foreach ($relatedContributions as $contriId) {
943 if ($contriId == $contributionId) {
946 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
947 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
951 if ($membership && $update) {
952 $newStatus = array_search('Cancelled', $membershipStatuses);
955 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
957 'subject' => "Status changed from {$allStatus[$membership->status_id]} to {$allStatus[$newStatus]}",
958 'source_contact_id' => CRM_Core_Session
::singleton()->get('userID'),
959 'target_contact_id' => $membership->contact_id
,
960 'source_record_id' => $membership->id
,
961 'activity_type_id' => 'Change Membership Status',
962 'status_id' => 'Completed',
963 'priority_id' => 'Normal',
964 'activity_date_time' => 'now',
967 $membership->status_id
= $newStatus;
968 $membership->is_override
= TRUE;
969 $membership->status_override_end_date
= 'null';
971 civicrm_api3('activity', 'create', $activityParam);
977 $updatedStatusId = array_search('Cancelled', $participantStatuses);
978 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
981 if ($pledgePayment) {
982 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
987 * Do any accounting updates required as a result of a contribution status change.
989 * Currently we have a bit of a roundabout where adding a payment results in this being called &
990 * this may attempt to add a payment. We need to resolve that....
992 * The 'right' way to add payments or refunds is through the Payment.create api. That api
993 * then updates the contribution but this process should not also record another financial trxn.
994 * Currently we have weak detection fot that scenario & where it is detected the first returned
995 * value is FALSE - meaning 'do not continue'.
997 * We should also look at the fact that the calling function - updateFinancialAccounts
998 * bunches together some disparate processes rather than having separate appropriate
1001 * @param array $params
1004 * Return indicates whether the updateFinancialAccounts function should continue.
1006 private static function updateFinancialAccountsOnContributionStatusChange(&$params) {
1007 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
1008 $currentContributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
1010 if ((($previousContributionStatus == 'Partially paid' && $currentContributionStatus == 'Completed')
1011 ||
($previousContributionStatus == 'Pending refund' && $currentContributionStatus == 'Completed')
1012 // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
1013 // why it is here or where it is handled instead.
1014 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
1015 && $currentContributionStatus == 'Partially paid'))
1020 if (self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
)) {
1021 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1022 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1024 elseif (($previousContributionStatus == 'Pending'
1025 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
1027 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
1028 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
1030 if ($currentContributionStatus == 'Cancelled') {
1031 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1032 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
1033 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1036 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1037 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
1041 if (($previousContributionStatus == 'Pending'
1042 ||
$previousContributionStatus == 'In Progress')
1043 && ($currentContributionStatus == 'Completed')
1045 if (empty($params['line_item'])) {
1047 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
1048 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
1049 // & this can be removed
1052 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1053 // This is an update so original currency if none passed in.
1054 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
1056 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
1057 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
1058 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1059 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
1061 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
1064 'entity_table' => 'civicrm_financial_item',
1066 foreach ($params['line_item'] as $fieldId => $fields) {
1067 foreach ($fields as $fieldValueId => $lineItemDetails) {
1068 self
::updateFinancialItemForLineItemToPaid($lineItemDetails['id']);
1070 1 => [$lineItemDetails['id'], 'Integer'],
1072 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
1073 while ($financialItem->fetch()) {
1074 $entityParams['entity_id'] = $financialItem->id
;
1075 $entityParams['amount'] = $financialItem->amount
;
1076 foreach (self
::$_trxnIDs as $tID) {
1077 $entityParams['financial_trxn_id'] = $tID;
1078 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
1089 * It is possible to override the membership id that is updated from the payment processor.
1091 * Historically Paypal does this & it still does if it determines data is messed up - see
1092 * https://lab.civicrm.org/dev/membership/issues/13
1094 * Read the comment block on repeattransaction for more information
1095 * about how things should work.
1097 * @param int $contributionID
1098 * @param array $input
1100 * @throws \CiviCRM_API3_Exception
1102 protected static function handleMembershipIDOverride($contributionID, $input) {
1103 if (!empty($input['membership_id'])) {
1104 Civi
::log()->debug('The related membership id has been overridden - this may impact data - see https://github.com/civicrm/civicrm-core/pull/15053');
1105 civicrm_api3('MembershipPayment', 'create', ['contribution_id' => $contributionID, 'membership_id' => $input['membership_id']]);
1110 * Update all financial items related to the line item tto have a status of paid.
1112 * @param int $lineItemID
1114 private static function updateFinancialItemForLineItemToPaid($lineItemID) {
1117 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1120 2 => [$lineItemID, 'Integer'],
1122 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
1123 CRM_Core_DAO
::executeQuery($query, $fparams);
1127 * Create the financial items for the line.
1129 * @param array $params
1130 * @param string $context
1131 * @param array $fields
1132 * @param array $previousLineItems
1133 * @param array $inputParams
1134 * @param bool $isARefund
1135 * @param array $trxnIds
1136 * @param int $fieldId
1140 private static function createFinancialItemsForLine($params, $context, $fields, array $previousLineItems, array $inputParams, bool $isARefund, $trxnIds, $fieldId): array {
1141 foreach ($fields as $fieldValueId => $lineItemDetails) {
1142 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($lineItemDetails['id']);
1143 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
1144 if ($params['contribution']->receive_date
) {
1145 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
1148 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array
::value('financial_account_id', $prevFinancialItem));
1150 $currency = $params['prevContribution']->currency
;
1151 if ($params['contribution']->currency
) {
1152 $currency = $params['contribution']->currency
;
1154 $previousLineItemTotal = CRM_Utils_Array
::value('line_total', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1156 'transaction_date' => $receiveDate,
1157 'contact_id' => $params['prevContribution']->contact_id
,
1158 'currency' => $currency,
1159 'amount' => self
::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
1160 'description' => $prevFinancialItem['description'] ??
NULL,
1161 'status_id' => $prevFinancialItem['status_id'],
1162 'financial_account_id' => $financialAccount,
1163 'entity_table' => 'civicrm_line_item',
1164 'entity_id' => $lineItemDetails['id'],
1166 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1167 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
1168 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
1170 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') ||
($context == 'changeFinancialType')) {
1171 $taxAmount = (float) $lineItemDetails['tax_amount'];
1172 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
1173 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
1174 $taxAmount = CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1176 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
1177 $taxAmount -= CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1179 if ($taxAmount != 0) {
1180 $itemParams['amount'] = self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * $taxAmount;
1181 $itemParams['description'] = CRM_Invoicing_Utils
::getTaxTerm();
1182 if ($lineItemDetails['financial_type_id']) {
1183 $itemParams['financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getSalesTaxFinancialAccount($lineItemDetails['financial_type_id']);
1185 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1193 * Does this contributtion status update represent a refund.
1195 * @param int $previousContributionStatusID
1196 * @param int $currentContributionStatusID
1200 private static function isContributionUpdateARefund($previousContributionStatusID, $currentContributionStatusID): bool {
1201 if ('Completed' !== CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $previousContributionStatusID)) {
1204 return self
::isContributionStatusNegative($currentContributionStatusID);
1208 * Get transaction information about the contribution.
1210 * @param int $contributionId
1211 * @param int $financialTypeID
1215 protected static function getContributionTransactionInformation($contributionId, int $financialTypeID) {
1217 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Expense Account is');
1219 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
1221 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
1223 ft.payment_instrument_id,
1224 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
1226 FROM civicrm_contribution con
1227 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
1228 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
1229 AND ft.to_financial_account_id != %2
1230 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
1231 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
1232 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
1234 WHERE con.id = %1 AND ft.is_payment = 1
1237 1 => [$contributionId, 'Integer'],
1238 2 => [$feeFinancialAccount, 'Integer'],
1240 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
1241 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label');
1243 while ($resultDAO->fetch()) {
1244 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1245 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1246 if ($resultDAO->card_type_id
) {
1247 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
1248 $pantruncation = '';
1249 if ($resultDAO->pan_truncation
) {
1250 $pantruncation = ": {$resultDAO->pan_truncation}";
1252 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
1255 // show payment edit link only for payments done via backoffice form
1256 $paymentEditLink = '';
1257 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
1259 CRM_Core_Action
::UPDATE
=> [
1260 'name' => ts('Edit Payment'),
1261 'icon' => 'fa-pencil',
1262 'url' => 'civicrm/payment/edit',
1263 'class' => 'medium-popup',
1264 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
1265 'title' => ts('Edit Payment'),
1268 $paymentEditLink = CRM_Core_Action
::formLink(
1270 CRM_Core_Action
::mask([CRM_Core_Permission
::EDIT
]),
1272 'id' => $resultDAO->id
,
1273 'contribution_id' => $contributionId,
1277 'Payment.edit.action',
1285 'id' => $resultDAO->id
,
1286 'total_amount' => $resultDAO->total_amount
,
1287 'financial_type' => $resultDAO->financial_account
,
1288 'payment_instrument' => $paidByLabel,
1289 'receive_date' => $resultDAO->trxn_date
,
1290 'trxn_id' => $resultDAO->trxn_id
,
1291 'status' => $statuses[$resultDAO->status_id
],
1292 'currency' => $resultDAO->currency
,
1293 'action' => $paymentEditLink,
1295 if ($paidByName == 'Check') {
1296 $val['check_number'] = $resultDAO->check_number
;
1304 * Should an email receipt be sent for this contribution on completion.
1306 * @param array $input
1307 * @param int $contributionPageID
1308 * @param int $recurringContributionID
1311 * @throws \API_Exception
1312 * @throws \Civi\API\Exception\UnauthorizedException
1314 protected static function isEmailReceipt(array $input, $contributionPageID, $recurringContributionID): bool {
1315 if (isset($input['is_email_receipt'])) {
1316 return (bool) $input['is_email_receipt'];
1318 if ($recurringContributionID) {
1319 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
1320 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
1321 // 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
1322 // Instance that had the table added via an upgrade in 4.1
1323 // see also https://github.com/civicrm/civicrm-svn/commit/7f39befd60bc735408d7866b02b3ac7fff1d4eea#diff-9ad8e290180451a2d6eacbd3d1ca7966R354
1324 // https://lab.civicrm.org/dev/core/issues/1245
1325 return (bool) ContributionRecur
::get(FALSE)->addWhere('id', '=', $recurringContributionID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt'];
1327 if ($contributionPageID) {
1328 return (bool) ContributionPage
::get(FALSE)->addWhere('id', '=', $contributionPageID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt'];
1330 // This would be the case for backoffice (where is_email_receipt is not passed in) or events, where Event::sendMail will filter
1336 * Process failed contribution.
1338 * @param $memberships
1339 * @param $contributionId
1340 * @param array $membershipStatuses
1341 * @param $participant
1342 * @param $pledgePayment
1344 * @param array $pledgePaymentIDs
1345 * @param $contributionStatusId
1347 * @throws \CRM_Core_Exception
1349 protected static function processFail($memberships, $contributionId, array $membershipStatuses, array $participant, $pledgePayment, $pledgeID, array $pledgePaymentIDs, $contributionStatusId): void
{
1350 if (is_array($memberships)) {
1351 foreach ($memberships as $membership) {
1353 //Update Membership status if there is no other completed contribution associated with the membership.
1354 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1355 foreach ($relatedContributions as $contriId) {
1356 if ($contriId == $contributionId) {
1359 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1360 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1364 if ($membership && $update) {
1365 $membership->status_id
= array_search('Expired', $membershipStatuses);
1366 $membership->is_override
= TRUE;
1367 $membership->status_override_end_date
= 'null';
1368 $membership->save();
1373 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1377 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1378 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1379 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1382 if ($pledgePayment) {
1383 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1390 public function addSelectWhereClause() {
1391 $whereClauses = parent
::addSelectWhereClause();
1392 if ($whereClauses !== []) {
1393 // In this case permisssions have been applied & we assume the
1394 // financialaclreport is applying these
1395 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
1396 return $whereClauses;
1399 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1400 return $whereClauses;
1402 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
1403 if (empty($types)) {
1404 $whereClauses['financial_type_id'] = 'IN (0)';
1407 $whereClauses['financial_type_id'] = [
1408 'IN (' . implode(',', array_keys($types)) . ')',
1411 return $whereClauses;
1415 * @param null $status
1416 * @param null $startDate
1417 * @param null $endDate
1419 * @return array|null
1421 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1425 $where[] = 'contribution_status_id = 1';
1429 $where[] = 'contribution_status_id = 3';
1434 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
1437 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
1439 $financialTypeACLJoin = '';
1440 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1441 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1442 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
1443 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1444 if ($financialTypes) {
1445 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1446 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1449 $where[] = "c.financial_type_id IN (0)";
1453 $whereCond = implode(' AND ', $where);
1456 SELECT sum( total_amount ) as total_amount,
1457 count( c.id ) as total_count,
1459 FROM civicrm_contribution c
1460 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1461 $financialTypeACLJoin
1463 AND ( is_test = 0 OR is_test IS NULL )
1464 AND contact.is_deleted = 0
1468 $dao = CRM_Core_DAO
::executeQuery($query);
1471 while ($dao->fetch()) {
1472 $count +
= $dao->total_count
;
1473 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
1477 'amount' => implode(', ', $amount),
1485 * Delete the indirect records associated with this contribution first.
1489 * @return mixed|null
1490 * $results no of deleted Contribution on success, false otherwise
1492 public static function deleteContribution($id) {
1493 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
1495 $transaction = new CRM_Core_Transaction();
1498 //delete activity record
1500 'source_record_id' => $id,
1501 // activity type id for contribution
1502 'activity_type_id' => 6,
1505 CRM_Activity_BAO_Activity
::deleteActivity($params);
1507 //delete billing address if exists for this contribution.
1508 self
::deleteAddress($id);
1510 //update pledge and pledge payment, CRM-3961
1511 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1513 // remove entry from civicrm_price_set_entity, CRM-5095
1514 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1515 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1517 // cleanup line items.
1518 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1520 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1521 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1523 if ($participantId) {
1524 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1527 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1531 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1532 $noteId = key($note);
1534 CRM_Core_BAO_Note
::del($noteId, FALSE);
1537 $dao = new CRM_Contribute_DAO_Contribution();
1540 $results = $dao->delete();
1542 $transaction->commit();
1544 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1546 // delete the recently created Contribution
1547 $contributionRecent = [
1549 'type' => 'Contribution',
1551 CRM_Utils_Recent
::del($contributionRecent);
1557 * React to a financial transaction (payment) failure.
1559 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1560 * payments is important for forensic and outreach reasons.
1562 * @param int $contributionID
1563 * @param int $contactID
1564 * @param string $message
1566 * @throws \CiviCRM_API3_Exception
1568 public static function failPayment($contributionID, $contactID, $message) {
1569 civicrm_api3('activity', 'create', [
1570 'activity_type_id' => 'Failed Payment',
1571 'details' => $message,
1572 'subject' => ts('Payment failed at payment processor'),
1573 'source_record_id' => $contributionID,
1574 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() : $contactID,
1577 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1578 civicrm_api3('contribution', 'create', [
1579 'id' => $contributionID,
1580 'contribution_status_id' => 'Failed',
1585 * Check if there is a contribution with the same trxn_id or invoice_id.
1587 * @param array $input
1588 * An assoc array of name/value pairs.
1589 * @param array $duplicates
1590 * (reference) store ids of duplicate contribs.
1594 * true if duplicate, false otherwise
1596 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1598 $id = $input['id'] ??
NULL;
1600 $trxn_id = $input['trxn_id'] ??
NULL;
1601 $invoice_id = $input['invoice_id'] ??
NULL;
1607 $clause[] = "trxn_id = %1";
1608 $input[1] = [$trxn_id, 'String'];
1612 $clause[] = "invoice_id = %2";
1613 $input[2] = [$invoice_id, 'String'];
1616 if (empty($clause)) {
1620 $clause = implode(' OR ', $clause);
1622 $clause = "( $clause ) AND id != %3";
1623 $input[3] = [$id, 'Integer'];
1626 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1627 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1629 while ($dao->fetch()) {
1630 $duplicates[] = $dao->id
;
1637 * Takes an associative array and creates a contribution_product object.
1639 * the function extract all the params it needs to initialize the create a
1640 * contribution_product object. the params array could contain additional unused name/value
1643 * @param array $params
1644 * (reference) an assoc array of name/value pairs.
1646 * @return CRM_Contribute_DAO_ContributionProduct
1648 public static function addPremium(&$params) {
1649 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1650 $contributionProduct->copyValues($params);
1651 return $contributionProduct->save();
1655 * Get list of contribution fields for profile.
1656 * For now we only allow custom contribution fields to be in
1659 * @param bool $addExtraFields
1660 * True if special fields needs to be added.
1663 * the list of contribution fields
1665 public static function getContributionFields($addExtraFields = TRUE) {
1666 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1667 // @todo remove this - this line was added because payment_instrument_id was not
1668 // set to exportable - but now it is.
1669 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1671 if ($addExtraFields) {
1672 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1675 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1677 foreach ($contributionFields as $key => $var) {
1678 if ($key == 'contribution_contact_id') {
1681 elseif ($key == 'contribution_campaign_id') {
1682 $var['title'] = ts('Campaign');
1684 $fields[$key] = $var;
1687 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1692 * Add extra fields specific to contribution.
1694 public static function getSpecialContributionFields() {
1696 'contribution_soft_credit_name' => [
1697 'name' => 'contribution_soft_credit_name',
1698 'title' => ts('Soft Credit Name'),
1699 'headerPattern' => '/^soft_credit_name$/i',
1700 'where' => 'civicrm_contact_d.display_name',
1702 'contribution_soft_credit_email' => [
1703 'name' => 'contribution_soft_credit_email',
1704 'title' => ts('Soft Credit Email'),
1705 'headerPattern' => '/^soft_credit_email$/i',
1706 'where' => 'soft_email.email',
1708 'contribution_soft_credit_phone' => [
1709 'name' => 'contribution_soft_credit_phone',
1710 'title' => ts('Soft Credit Phone'),
1711 'headerPattern' => '/^soft_credit_phone$/i',
1712 'where' => 'soft_phone.phone',
1714 'contribution_soft_credit_contact_id' => [
1715 'name' => 'contribution_soft_credit_contact_id',
1716 'title' => ts('Soft Credit Contact ID'),
1717 'headerPattern' => '/^soft_credit_contact_id$/i',
1718 'where' => 'civicrm_contribution_soft.contact_id',
1720 'contribution_pcp_title' => [
1721 'name' => 'contribution_pcp_title',
1722 'title' => ts('Personal Campaign Page Title'),
1723 'headerPattern' => '/^contribution_pcp_title$/i',
1724 'where' => 'contribution_pcp.title',
1728 return $extraFields;
1732 * @param int $pageID
1736 public static function getCurrentandGoalAmount($pageID) {
1738 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1739 FROM civicrm_contribution_page p,
1740 civicrm_contribution c
1741 WHERE p.id = c.contribution_page_id
1743 AND c.cancel_date is null
1747 $config = CRM_Core_Config
::singleton();
1748 $params = [1 => [$pageID, 'Integer']];
1749 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1751 if ($dao->fetch()) {
1752 return [$dao->goal
, $dao->total
];
1755 return [NULL, NULL];
1760 * Get list of contributions which credit the passed in contact ID.
1762 * The returned array provides details about the original contribution & donor.
1764 * @param int $honorId
1765 * In Honor of Contact ID.
1768 * list of contribution fields
1769 * @todo - this is a confusing function called from one place. It has a test. It would be
1770 * nice to deprecate it.
1773 public static function getHonorContacts($honorId) {
1775 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1776 $honorDAO->contact_id
= $honorId;
1779 $type = CRM_Contribute_PseudoConstant
::financialType();
1781 while ($honorDAO->fetch()) {
1782 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1783 $contributionDAO->id
= $honorDAO->contribution_id
;
1785 if ($contributionDAO->find(TRUE)) {
1786 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1787 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1788 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1789 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1790 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1791 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1792 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1793 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1794 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
, 'label');
1802 * Get the sort name of a contact for a particular contribution.
1805 * Id of the contribution.
1807 * @return null|string
1808 * sort name of the contact if found
1810 public static function sortName($id) {
1811 $id = CRM_Utils_Type
::escape($id, 'Integer');
1814 SELECT civicrm_contact.sort_name
1815 FROM civicrm_contribution, civicrm_contact
1816 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1817 AND civicrm_contribution.id = {$id}
1819 return CRM_Core_DAO
::singleValueQuery($query);
1823 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1825 * @param int|array $contactIDs
1829 public static function annual($contactIDs) {
1830 if (!is_array($contactIDs)) {
1831 // In practice I can't fine any evidence that this function is ever called with
1832 // anything other than a single contact id, but left like this due to .... fear.
1833 $contactIDs = explode(',', $contactIDs);
1836 $query = self
::getAnnualQuery($contactIDs);
1837 $dao = CRM_Core_DAO
::executeQuery($query);
1839 $amount = $average = [];
1840 while ($dao->fetch()) {
1841 if ($dao->count
> 0 && $dao->amount
> 0) {
1842 $count +
= $dao->count
;
1843 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1844 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1850 implode(', ', $amount),
1851 implode(', ', $average),
1858 * Check if there is a contribution with the params passed in.
1860 * Used for trxn_id,invoice_id and contribution_id
1862 * @param array $params
1863 * An assoc array of name/value pairs.
1866 * contribution id if success else NULL
1868 public static function checkDuplicateIds($params) {
1869 $dao = new CRM_Contribute_DAO_Contribution();
1873 foreach ($params as $k => $v) {
1875 $clause[] = "$k = '$v'";
1878 $clause = implode(' AND ', $clause);
1879 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1880 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1882 while ($dao->fetch()) {
1890 * Get the contribution details for component export.
1892 * @param int $exportMode
1894 * @param array $componentIds
1900 public static function getContributionDetails($exportMode, $componentIds) {
1901 $paymentDetails = [];
1902 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1904 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1905 $componentSelect = " civicrm_participant_payment.participant_id id";
1906 $additionalClause = "
1907 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1908 AND civicrm_participant_payment.participant_id {$componentClause} )
1911 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1912 $componentSelect = " civicrm_membership_payment.membership_id id";
1913 $additionalClause = "
1914 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1915 AND civicrm_membership_payment.membership_id {$componentClause} )
1918 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1919 $componentSelect = " civicrm_pledge_payment.id id";
1920 $additionalClause = "
1921 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1922 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1926 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1927 trxn_id, {$componentSelect}
1928 FROM civicrm_contribution
1929 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1930 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1931 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1932 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1933 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1934 AND option_group_contribution_status.id = contribution_status.option_group_id )
1938 $dao = CRM_Core_DAO
::executeQuery($query);
1940 while ($dao->fetch()) {
1941 $paymentDetails[$dao->id
] = [
1942 'total_amount' => $dao->total_amount
,
1943 'contribution_status' => $dao->status
,
1944 'receive_date' => $dao->receive_date
,
1945 'pay_instru' => $dao->payment_instrument
,
1946 'trxn_id' => $dao->trxn_id
,
1950 return $paymentDetails;
1954 * Create address associated with contribution record.
1956 * As long as there is one or more billing field in the parameters we will create the address.
1958 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1961 * @param array $params
1962 * @param int $billingLocationTypeID
1967 public static function createAddress($params, $billingLocationTypeID) {
1968 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1969 if ($hasBillingField) {
1970 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1971 return $address->id
;
1978 * Delete billing address record related contribution.
1980 * @param int $contributionId
1981 * @param int $contactId
1983 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1985 $contactJoin = NULL;
1987 if ($contributionId) {
1988 $clauses[] = "cc.id = {$contributionId}";
1992 $clauses[] = "cco.id = {$contactId}";
1993 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1996 if (empty($clauses)) {
1997 throw new CRM_Core_Exception('No Where clauses defined when deleting address');
2000 $condition = implode(' OR ', $clauses);
2004 FROM civicrm_address ca
2005 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
2009 $dao = CRM_Core_DAO
::executeQuery($query);
2011 while ($dao->fetch()) {
2012 $params = ['id' => $dao->id
];
2013 CRM_Core_BAO_Block
::blockDelete('Address', $params);
2018 * This function check online pending contribution associated w/
2019 * Online Event Registration or Online Membership signup.
2021 * @param int $componentId
2022 * Participant/membership id.
2023 * @param string $componentName
2027 * pending contribution id.
2029 public static function checkOnlinePendingContribution($componentId, $componentName) {
2030 $contributionId = NULL;
2031 if (!$componentId ||
2032 !in_array($componentName, ['Event', 'Membership'])
2034 return $contributionId;
2037 if ($componentName == 'Event') {
2038 $idName = 'participant_id';
2039 $componentTable = 'civicrm_participant';
2040 $paymentTable = 'civicrm_participant_payment';
2041 $source = ts('Online Event Registration');
2044 if ($componentName == 'Membership') {
2045 $idName = 'membership_id';
2046 $componentTable = 'civicrm_membership';
2047 $paymentTable = 'civicrm_membership_payment';
2048 $source = ts('Online Contribution');
2051 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
2054 SELECT component.id as {$idName},
2055 componentPayment.contribution_id as contribution_id,
2056 contribution.source source,
2057 contribution.contribution_status_id as contribution_status_id,
2058 contribution.is_pay_later as is_pay_later
2059 FROM $componentTable component
2060 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
2061 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
2062 WHERE component.id = {$componentId}";
2064 $dao = CRM_Core_DAO
::executeQuery($query);
2066 while ($dao->fetch()) {
2067 if ($dao->contribution_id
&&
2068 $dao->is_pay_later
&&
2069 $dao->contribution_status_id
== $pendingStatusId &&
2070 strpos($dao->source
, $source) !== FALSE
2072 $contributionId = $dao->contribution_id
;
2076 return $contributionId;
2080 * Update contribution as well as related objects.
2082 * This function by-passes hooks - to address this - don't use this function.
2084 * @param array $params
2086 * @throws CRM_Core_Exception
2087 * @throws \CiviCRM_API3_Exception
2090 * Use api contribute.completetransaction
2091 * For failures use failPayment (preferably exposing by api in the process).
2094 public static function transitionComponents($params) {
2095 // get minimum required values.
2096 $contactId = $params['contact_id'] ??
NULL;
2097 $componentId = $params['component_id'] ??
NULL;
2098 $componentName = $params['componentName'] ??
NULL;
2099 $contributionId = $params['contribution_id'] ??
NULL;
2100 $contributionStatusId = $params['contribution_status_id'] ??
NULL;
2102 // if we already processed contribution object pass previous status id.
2103 $previousContriStatusId = $params['previous_contribution_status_id'] ??
NULL;
2107 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2109 // we process only ( Completed, Cancelled, or Failed ) contributions.
2110 if (!$contributionId ||
2111 !in_array($contributionStatusId, [
2112 array_search('Completed', $contributionStatuses),
2113 array_search('Cancelled', $contributionStatuses),
2114 array_search('Failed', $contributionStatuses),
2120 if (!$componentName ||
!$componentId) {
2121 // get the related component details.
2122 $componentDetails = self
::getComponentDetails($contributionId);
2125 $componentDetails['contact_id'] = $contactId;
2126 $componentDetails['component'] = $componentName;
2128 if ($componentName == 'event') {
2129 $componentDetails['participant'] = $componentId;
2132 $componentDetails['membership'] = $componentId;
2136 if (!empty($componentDetails['contact_id'])) {
2137 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2143 // do check for required ids.
2144 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
2150 $input['component'] = $componentDetails['component'] ??
NULL;
2151 $ids['contribution'] = $contributionId;
2152 $ids['contact'] = $componentDetails['contact_id'] ??
NULL;
2153 $ids['membership'] = $componentDetails['membership'] ??
NULL;
2154 $ids['participant'] = $componentDetails['participant'] ??
NULL;
2155 $ids['event'] = $componentDetails['event'] ??
NULL;
2156 $ids['pledge_payment'] = $componentDetails['pledge_payment'] ??
NULL;
2157 $ids['contributionRecur'] = NULL;
2158 $ids['contributionPage'] = NULL;
2160 $contribution = new CRM_Contribute_BAO_Contribution();
2161 $contribution->id
= $ids['contribution'];
2162 $contribution->find();
2164 $contribution->loadRelatedObjects($input, $ids);
2166 $memberships = $contribution->_relatedObjects
['membership'] ??
[];
2167 $participant = $contribution->_relatedObjects
['participant'] ??
[];
2168 $pledgePayment = $contribution->_relatedObjects
['pledge_payment'] ??
[];
2170 $pledgeID = $oldStatus = NULL;
2171 $pledgePaymentIDs = [];
2172 if ($pledgePayment) {
2173 foreach ($pledgePayment as $key => $object) {
2174 $pledgePaymentIDs[] = $object->id
;
2176 $pledgeID = $pledgePayment[0]->pledge_id
;
2179 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
2182 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
2183 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
2188 // we might want to process contribution object.
2189 $processContribution = FALSE;
2190 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
2191 // Call interim cancel function - with a goal to cleaning up the signature on it and switching to a tested api Contribution.cancel function.
2192 self
::cancel($memberships, $contributionId, $membershipStatuses, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
2194 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
2195 self
::processFail($memberships, $contributionId, $membershipStatuses, $participant, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
2197 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
2199 // only pending contribution related object processed.
2200 if ($previousContriStatusId &&
2201 !in_array($contributionStatuses[$previousContriStatusId], [
2206 // this is case when we already processed contribution object.
2209 elseif (!$previousContriStatusId &&
2210 !in_array($contributionStatuses[$contribution->contribution_status_id
], [
2215 // this is case when we are going to process contribution object later.
2219 if (is_array($memberships)) {
2220 foreach ($memberships as $membership) {
2225 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
2226 $membership->membership_type_id
,
2227 $membership->is_test
, $membership->id
2230 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2231 // this picks up membership type changes during renewals
2233 SELECT membership_type_id
2234 FROM civicrm_membership_log
2235 WHERE membership_id=$membership->id
2238 $dao = CRM_Core_DAO
::executeQuery($sql);
2239 if ($dao->fetch()) {
2240 if (!empty($dao->membership_type_id
)) {
2241 $membership->membership_type_id
= $dao->membership_type_id
;
2242 $membership->save();
2245 // else fall back to using current membership type
2246 // Figure out number of terms
2248 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
2249 foreach ($lineitems as $lineitem) {
2250 if ($membership->membership_type_id
== ($lineitem['membership_type_id'] ??
NULL)) {
2251 $numterms = $lineitem['membership_num_terms'] ??
NULL;
2253 // in case membership_num_terms comes through as null or zero
2254 $numterms = $numterms >= 1 ?
$numterms : 1;
2259 // CRM-15735-to update the membership status as per the contribution receive date
2261 $oldStatus = $membership->status_id
;
2262 if (!empty($params['receive_date'])) {
2263 $joinDate = $params['receive_date'];
2264 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
2265 $membership->end_date
,
2266 $membership->join_date
,
2267 $params['receive_date'],
2269 $membership->membership_type_id
,
2272 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
2273 $membership->save();
2276 if ($currentMembership) {
2277 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2278 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
2279 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2282 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
2285 //get the status for membership.
2286 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
2288 $dates['join_date'],
2291 $membership->membership_type_id
,
2295 $formattedParams = [
2296 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
2297 array_search('Current', $membershipStatuses)
2299 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
2300 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
2301 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
2304 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
2306 $membership->copyValues($formattedParams);
2307 $membership->save();
2309 //updating the membership log
2310 $membershipLog = [];
2311 $membershipLog = $formattedParams;
2312 $logStartDate = CRM_Utils_Date
::customFormat($dates['log_start_date'] ??
NULL, $format);
2313 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
2315 $membershipLog['start_date'] = $logStartDate;
2316 $membershipLog['membership_id'] = $membership->id
;
2317 $membershipLog['modified_id'] = $membership->contact_id
;
2318 $membershipLog['modified_date'] = date('Ymd');
2319 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
2321 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2323 //update related Memberships.
2324 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2326 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2327 $scheduledActivityID = CRM_Utils_Array
::value('id',
2328 civicrm_api3('Activity', 'Get',
2330 'source_record_id' => $membership->id
,
2331 'activity_type_id' => $activityType,
2332 'status_id' => 'Scheduled',
2335 'sort' => 'id DESC',
2340 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2341 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2342 if ($scheduledActivityID) {
2343 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, ['id' => $scheduledActivityID]);
2348 // track membership status change if any
2349 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
2350 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2351 CRM_Activity_BAO_Activity
::addActivity($membership,
2352 'Change Membership Status',
2355 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2356 'source_contact_id' => $membershipLog['modified_id'],
2357 'priority_id' => 'Normal',
2362 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2368 $updatedStatusId = array_search('Registered', $participantStatuses);
2369 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2372 if ($pledgePayment) {
2373 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2377 // process contribution object.
2378 if ($processContribution) {
2379 $contributionParams = [];
2386 'payment_instrument_id',
2389 'financial_type_id',
2390 'contribution_status_id',
2391 'non_deductible_amount',
2395 foreach ($fields as $field) {
2396 if (empty($params[$field])) {
2399 $contributionParams[$field] = $params[$field];
2402 $contributionParams['id'] = $contributionId;
2403 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams);
2409 * Returns all contribution related object ids.
2411 * @param $contributionId
2415 public static function getComponentDetails($contributionId) {
2416 $componentDetails = $pledgePayment = [];
2417 if (!$contributionId) {
2418 return $componentDetails;
2422 SELECT c.id as contribution_id,
2423 c.contact_id as contact_id,
2424 c.contribution_recur_id,
2425 mp.membership_id as membership_id,
2426 m.membership_type_id as membership_type_id,
2427 pp.participant_id as participant_id,
2428 p.event_id as event_id,
2429 pgp.id as pledge_payment_id
2430 FROM civicrm_contribution c
2431 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2432 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2433 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2434 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2435 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2436 WHERE c.id = $contributionId";
2438 $dao = CRM_Core_DAO
::executeQuery($query);
2439 $componentDetails = [];
2441 while ($dao->fetch()) {
2442 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2443 $componentDetails['contact_id'] = $dao->contact_id
;
2444 if ($dao->event_id
) {
2445 $componentDetails['event'] = $dao->event_id
;
2447 if ($dao->participant_id
) {
2448 $componentDetails['participant'] = $dao->participant_id
;
2450 if ($dao->membership_id
) {
2451 if (!isset($componentDetails['membership'])) {
2452 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2454 $componentDetails['membership'][] = $dao->membership_id
;
2455 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2457 if ($dao->pledge_payment_id
) {
2458 $pledgePayment[] = $dao->pledge_payment_id
;
2460 if ($dao->contribution_recur_id
) {
2461 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2465 if ($pledgePayment) {
2466 $componentDetails['pledge_payment'] = $pledgePayment;
2469 return $componentDetails;
2473 * @param int $contactId
2474 * @param bool $includeSoftCredit
2476 * @return null|string
2478 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2482 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2483 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2484 $liWhere = " AND i.financial_type_id IN (0)";
2485 if (!empty($financialTypes)) {
2486 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2487 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2489 $contactContributionsSQL = "
2490 SELECT contribution.id AS id
2491 FROM civicrm_contribution contribution
2492 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2493 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2497 $contactSoftCreditContributionsSQL = "
2498 SELECT contribution.id
2499 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2500 ON ( contribution.id = softContribution.contribution_id )
2501 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2502 $query = "SELECT count( x.id ) count FROM ( ";
2503 $query .= $contactContributionsSQL;
2505 if ($includeSoftCredit) {
2506 $query .= " UNION ";
2507 $query .= $contactSoftCreditContributionsSQL;
2512 return CRM_Core_DAO
::singleValueQuery($query);
2516 * Repeat a transaction as part of a recurring series.
2519 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2520 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2521 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2522 * and associated entities.
2523 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2524 * which updates the various entities and sends appropriate emails.
2526 * Gaps in the above (@todo)
2527 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2528 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2529 * 3) Repeat transaction duplicates rather than calls Order.create
2530 * 4) Use of payment.create still limited - completetransaction is more common.
2531 * 5) the template transaction is tricky - historically we used the first contribution
2532 * linked to a recurring contribution. More recently that was changed to be the most recent.
2533 * Ideally it would be an actual template - not a contribution used as a template which
2534 * would give more appropriate flexibility. Note line_items have an entity so that table
2535 * could be used for the line item template - the difficulty is the custom fields...
2536 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2537 * to load the membership(s) referred to via line items in the template transactions. Any other
2538 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2539 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2540 * - membership_payment record
2541 * - civicrm_membership.contribution_recur_id
2543 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2544 * of historical processors since this has been handled 'forever' - specifically for paypal.
2545 * albeit by an even nastier mechanism than the current input override.
2546 * The count is out on how correct related entities wind up in this case.
2548 * @param CRM_Contribute_BAO_Contribution $contribution
2549 * @param array $input
2550 * @param array $contributionParams
2552 * @return bool|array
2553 * @throws CiviCRM_API3_Exception
2555 protected static function repeatTransaction(&$contribution, $input, $contributionParams) {
2556 if (!empty($contribution->id
)) {
2559 if (empty($contribution->id
)) {
2560 // Unclear why this would only be set for repeats.
2561 if (!empty($input['amount'])) {
2562 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2565 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2566 'id' => $contributionParams['contribution_recur_id'],
2568 if (!empty($recurringContribution['financial_type_id'])) {
2569 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2570 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2572 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2573 $contributionParams['contribution_recur_id'],
2574 array_intersect_key($contributionParams, [
2575 'total_amount' => TRUE,
2576 'financial_type_id' => TRUE,
2579 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2580 $contributionParams['status_id'] = 'Pending';
2582 if (isset($contributionParams['financial_type_id']) && count($input['line_item']) === 1) {
2583 // We permit the financial type to be overridden for single line items.
2584 // More comments on this are in getTemplateTransaction.
2585 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2588 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2590 foreach (['contact_id', 'currency', 'source', 'amount_level', 'address_id'] as $fieldName) {
2591 if (isset($templateContribution[$fieldName])) {
2592 $contributionParams[$fieldName] = $templateContribution[$fieldName];
2595 if (!empty($recurringContribution['campaign_id'])) {
2596 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2597 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2599 if (!isset($contributionParams['campaign_id']) && isset($templateContribution['campaign_id'])) {
2600 // Fall back on value from the previous contribution if not passed in as input
2601 // or loadable from the recurring contribution.
2602 $contributionParams['campaign_id'] = $templateContribution['campaign_id'];
2604 $contributionParams['source'] = $contributionParams['source'] ??
ts('Recurring contribution');
2606 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2607 //do not create CC or BCC emails or profile notifications.
2608 //The if is just to be safe. Not sure if we can ever arrive with this unset
2609 // but per CRM-19478 it seems it can be 'null'
2610 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2611 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2613 if (!empty($contribution->tax_amount
)) {
2614 $contributionParams['tax_amount'] = $contribution->tax_amount
;
2617 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2618 $contribution->id
= $createContribution['id'];
2619 $contribution->copyCustomFields($templateContribution['id'], $contribution->id
);
2620 self
::handleMembershipIDOverride($contribution->id
, $input);
2621 // Add new soft credit against current $contribution.
2622 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($contributionParams['contribution_recur_id'], $createContribution['id']);
2623 return $createContribution;
2628 * Get individual id for onbehalf contribution.
2630 * @param int $contributionId
2632 * @param int $contributorId
2636 * containing organization id and individual id
2638 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2642 if (!$contributionId) {
2646 // fetch contributor id if null
2647 if (!$contributorId) {
2648 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2649 $contributionId, 'contact_id'
2653 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2654 $activityTypeId = array_search('Contribution', $activityTypeIds);
2656 if ($activityTypeId && $contributorId) {
2658 SELECT civicrm_activity_contact.contact_id
2659 FROM civicrm_activity_contact
2660 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2661 WHERE civicrm_activity.activity_type_id = %1
2662 AND civicrm_activity.source_record_id = %2
2663 AND civicrm_activity_contact.record_type_id = %3
2666 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2667 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2670 1 => [$activityTypeId, 'Integer'],
2671 2 => [$contributionId, 'Integer'],
2672 3 => [$sourceID, 'Integer'],
2675 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2677 // for on behalf contribution source is individual and contributor is organization
2678 if ($sourceContactId && $sourceContactId != $contributorId) {
2679 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2680 // get rel type id for employee of relation
2681 foreach ($relationshipTypeIds as $id => $typeVals) {
2682 if ($typeVals['name_a_b'] == 'Employee of') {
2683 $relationshipTypeId = $id;
2688 $rel = new CRM_Contact_DAO_Relationship();
2689 $rel->relationship_type_id
= $relationshipTypeId;
2690 $rel->contact_id_a
= $sourceContactId;
2691 $rel->contact_id_b
= $contributorId;
2692 if ($rel->find(TRUE)) {
2693 $ids['individual_id'] = $rel->contact_id_a
;
2694 $ids['organization_id'] = $rel->contact_id_b
;
2705 public static function getContributionDates() {
2706 $config = CRM_Core_Config
::singleton();
2707 $currentMonth = date('m');
2708 $currentDay = date('d');
2709 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2710 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2711 (int ) $config->fiscalYearStart
['d'] > $currentDay
2714 $year = date('Y') - 1;
2719 $year = ['Y' => $year];
2720 $yearDate = $config->fiscalYearStart
;
2721 $yearDate = array_merge($year, $yearDate);
2722 $yearDate = CRM_Utils_Date
::format($yearDate);
2724 $monthDate = date('Ym') . '01';
2730 'yearDate' => $yearDate,
2731 'monthDate' => $monthDate,
2736 * Load objects relations to contribution object.
2737 * Objects are stored in the $_relatedObjects property
2738 * In the first instance we are just moving functionality from BASEIpn -
2740 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2742 * Note that the unit test for the BaseIPN class tests this function
2744 * @param array $input
2745 * Input as delivered from Payment Processor.
2747 * Ids as Loaded by Payment Processor.
2748 * @param bool $loadAll
2749 * Load all related objects - even where id not passed in? (allows API to call this).
2752 * @throws CRM_Core_Exception
2754 public function loadRelatedObjects($input, &$ids, $loadAll = FALSE) {
2755 // @todo deprecate this function - the steps should be
2756 // 1) add additional functions like 'getRelatedMemberships'
2757 // 2) switch all calls that refer to ->_relatedObjects to
2758 // using the helper functions
2759 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2760 // 4) make ->_relatedObjects protected
2761 // 5) hone up the individual functions to not use rely on this having been called
2762 // 6) deprecate like mad
2764 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2765 if (empty($ids['contact']) && isset($this->contact_id
)) {
2766 $ids['contact'] = $this->contact_id
;
2769 if (empty($this->_component
)) {
2770 if (!empty($ids['event'])) {
2771 $this->_component
= 'event';
2774 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2778 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2779 // refactoring than anything else, and has unit test coverage.
2780 if (empty($this->financial_type_id
)) {
2784 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2789 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2790 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2791 $this->contribution_page_id
,
2794 if ($paymentProcessorID) {
2795 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2799 $ids['contributionType'] = $this->financial_type_id
;
2800 $ids['financialType'] = $this->financial_type_id
;
2801 if ($this->contribution_page_id
) {
2802 $ids['contributionPage'] = $this->contribution_page_id
;
2805 $this->loadRelatedEntitiesByID($ids);
2807 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2808 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2811 if (!empty($ids['pledge_payment'])) {
2812 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2813 if (empty($paymentID)) {
2816 $payment = new CRM_Pledge_BAO_PledgePayment();
2817 $payment->id
= $paymentID;
2818 if (!$payment->find(TRUE)) {
2819 throw new CRM_Core_Exception("Could not find pledge payment record: " . $paymentID);
2821 $this->_relatedObjects
['pledge_payment'][] = $payment;
2825 // These are probably no longer accessed from anywhere
2826 // @todo remove this line, after ensuring not used.
2827 $ids = $this->loadRelatedMembershipObjects($ids);
2829 if ($this->_component
!= 'contribute') {
2830 // we are in event mode
2831 // make sure event exists and is valid
2832 $event = new CRM_Event_BAO_Event();
2833 $event->id
= $ids['event'];
2834 if ($ids['event'] &&
2837 throw new CRM_Core_Exception("Could not find event: " . $ids['event']);
2840 $this->_relatedObjects
['event'] = &$event;
2842 $participant = new CRM_Event_BAO_Participant();
2843 $participant->id
= $ids['participant'];
2844 if ($ids['participant'] &&
2845 !$participant->find(TRUE)
2847 throw new CRM_Core_Exception("Could not find participant: " . $ids['participant']);
2849 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2851 $this->_relatedObjects
['participant'] = &$participant;
2853 // get the payment processor id from event - this is inaccurate see CRM-16923
2854 // in future we should look at throwing an exception here rather than an dubious guess.
2855 if (!$paymentProcessorID) {
2856 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2857 if ($paymentProcessorID) {
2858 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2863 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds($this->id
);
2864 if (!empty($relatedContact['individual_id'])) {
2865 $ids['related_contact'] = $relatedContact['individual_id'];
2868 if ($paymentProcessorID) {
2869 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2870 $this->is_test ?
'test' : 'live'
2872 $ids['paymentProcessor'] = $paymentProcessorID;
2873 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2876 // Add contribution id to $ids. CRM-20401
2877 $ids['contribution'] = $this->id
;
2882 * Create array of message information - ie. return html version, txt version, to field
2884 * @param array $input
2885 * Incoming information.
2886 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2887 * just check presence of recur object but maintaining legacy approach
2890 * IDs of related objects.
2891 * @param array $values
2892 * Any values that may have already been compiled by calling process.
2893 * This is augmented by values 'gathered' by gatherMessageValues
2894 * @param bool $returnMessageText
2895 * Distinguishes between whether to send message or return.
2896 * message text. We are working towards this function ALWAYS returning message text & calling
2897 * function doing emails / pdfs with it
2903 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2904 $this->loadRelatedObjects($input, $ids);
2906 if (empty($this->_component
)) {
2907 $this->_component
= $input['component'] ??
NULL;
2910 //not really sure what params might be passed in but lets merge em into values
2911 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2912 $values['is_email_receipt'] = !$returnMessageText;
2913 foreach (['receipt_date', 'cc_receipt', 'bcc_receipt', 'receipt_from_name', 'receipt_from_email', 'receipt_text'] as $fld) {
2914 if (!empty($input[$fld])) {
2915 $values[$fld] = $input[$fld];
2919 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2920 //what does recur 'mean here - to do with payment processor return functionality but
2921 // what is the importance
2922 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2923 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2925 $entityID = $entity = NULL;
2926 if (isset($ids['contribution'])) {
2927 $entity = 'contribution';
2928 $entityID = $ids['contribution'];
2930 if (!empty($ids['membership'])) {
2931 //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
2932 // 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
2933 // line having loaded an array
2934 $ids['membership'] = (array) $ids['membership'];
2935 $entity = 'membership';
2936 $entityID = $ids['membership'][0];
2939 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2940 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2941 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2943 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2944 //direct mode showing billing block, so use directIPN for temporary
2945 $template->assign('contributeMode', 'directIPN');
2948 // todo remove strtolower - check consistency
2949 if (strtolower($this->_component
) == 'event') {
2950 $eventParams = ['id' => $this->_relatedObjects
['participant']->event_id
];
2951 $values['event'] = [];
2953 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2955 //get location details
2957 'entity_id' => $this->_relatedObjects
['participant']->event_id
,
2958 'entity_table' => 'civicrm_event',
2960 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2963 'entity_table' => 'civicrm_event',
2964 'entity_id' => $ids['event'],
2965 'module' => 'CiviEvent',
2968 list($custom_pre_id,
2970 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2972 $values['custom_pre_id'] = $custom_pre_id;
2973 $values['custom_post_id'] = $custom_post_ids;
2974 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2975 //and cases involving status updation through ipn
2976 // whatever that means!
2977 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2978 // perhaps we should throw an e-notice if amount is set & force total_amount?
2979 if (!empty($input['amount'])) {
2980 $values['totalAmount'] = $input['amount'];
2982 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2983 if ($values['event']['is_email_confirm']) {
2984 $values['is_email_receipt'] = 1;
2987 if (!empty($ids['contribution'])) {
2988 $values['contributionId'] = $ids['contribution'];
2991 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2992 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2996 $values['contribution_id'] = $this->id
;
2997 if (!empty($ids['related_contact'])) {
2998 $values['related_contact'] = $ids['related_contact'];
2999 if (isset($ids['onbehalf_dupe_alert'])) {
3000 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
3003 'contact_id' => $ids['contact'],
3004 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
3005 'Home', 'id', 'name'
3008 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
3009 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
3012 if ($this->is_test
) {
3015 if (!empty($this->_relatedObjects
['membership'])) {
3016 foreach ($this->_relatedObjects
['membership'] as $membership) {
3017 if ($membership->id
) {
3018 $values['membership_id'] = $membership->id
;
3019 $values['isMembership'] = TRUE;
3020 $values['membership_assign'] = TRUE;
3022 // need to set the membership values here
3023 $template->assign('membership_name',
3024 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
3026 $template->assign('mem_start_date', $membership->start_date
);
3027 $template->assign('mem_join_date', $membership->join_date
);
3028 $template->assign('mem_end_date', $membership->end_date
);
3029 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
3030 $template->assign('mem_status', $membership_status);
3031 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
3032 $values['is_pay_later'] = 1;
3034 // Pass amount to floatval as string '0.00' is considered a
3035 // valid amount and includes Fee section in the mail.
3036 if (isset($values['amount'])) {
3037 $values['amount'] = floatval($values['amount']);
3040 if (!empty($this->contribution_recur_id
) && $paymentObject) {
3041 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
3042 $template->assign('cancelSubscriptionUrl', $url);
3043 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
3044 $template->assign('updateSubscriptionBillingUrl', $url);
3045 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
3046 $template->assign('updateSubscriptionUrl', $url);
3049 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3052 // otherwise if its about sending emails, continue sending without return, as we
3053 // don't want to exit the loop.
3058 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3064 * Gather values for contribution mail - this function has been created
3065 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
3066 * Values related to the contribution in question are gathered
3068 * @param array $input
3069 * Input into function (probably from payment processor).
3070 * @param array $values
3072 * The set of ids related to the input.
3075 * @throws \CRM_Core_Exception
3077 public function _gatherMessageValues($input, &$values, $ids = []) {
3078 // set display address of contributor
3079 $values['billingName'] = '';
3080 if ($this->address_id
) {
3081 $addressDetails = CRM_Core_BAO_Address
::getValues(['id' => $this->address_id
], FALSE, 'id');
3082 $addressDetails = reset($addressDetails);
3083 $values['billingName'] = $addressDetails['name'] ??
'';
3085 // Else we assign the billing address of the contribution contact.
3087 $addressDetails = (array) CRM_Core_BAO_Address
::getValues(['contact_id' => $this->contact_id
, 'is_billing' => 1]);
3088 $addressDetails = reset($addressDetails);
3090 $values['address'] = $addressDetails['display'] ??
'';
3092 if ($this->_component
=== 'contribute') {
3093 //get soft contributions
3094 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
3095 if (!empty($softContributions)) {
3096 // For pcp soft credit, there is no 'soft_credit' member it comes
3097 // back in different array members, but shortly after returning from
3098 // this function it calls _assignMessageVariablesToTemplate which does
3099 // its own lookup of any pcp soft credit, so we can skip it here.
3100 $values['softContributions'] = $softContributions['soft_credit'] ??
NULL;
3102 if (isset($this->contribution_page_id
)) {
3103 // This is a call we want to use less, in favour of loading related objects.
3104 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
3105 if ($this->contribution_page_id
) {
3106 // This is precautionary as there are some legacy flows, but it should really be
3108 if (!isset($this->_relatedObjects
['contributionPage'])) {
3109 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id
]);
3111 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($values);
3114 // no contribution page -probably back office
3116 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
3117 $values['title'] = 'Contribution';
3119 // set lineItem for contribution
3121 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
3122 if (!empty($lineItems)) {
3123 $firstLineItem = reset($lineItems);
3125 if (!empty($firstLineItem['price_set_id'])) {
3126 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
3127 'id' => $firstLineItem['price_set_id'],
3128 'return' => 'is_quick_config, id',
3130 $values['priceSetID'] = $priceSet['id'];
3132 foreach ($lineItems as &$eachItem) {
3133 if (isset($this->_relatedObjects
['membership'])
3134 && is_array($this->_relatedObjects
['membership'])
3135 && array_key_exists($eachItem['entity_id'] . '_' . $eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
3136 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->join_date
);
3137 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->start_date
);
3138 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->end_date
);
3140 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
3141 // However, that does create upgrade pain so would be better to be phased in.
3142 $values['useForMember'] = empty($priceSet['is_quick_config']);
3144 $values['lineItem'][0] = $lineItems;
3148 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
3152 // if this is onbehalf of contribution then set related contact
3153 if (!empty($relatedContact['individual_id'])) {
3154 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
3158 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects
['participant']->id
, $this->id
));
3161 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
3164 foreach ($groupTree as $key => $group) {
3165 if ($key === 'info') {
3169 foreach ($group['fields'] as $k => $customField) {
3170 $groupLabel = $group['title'];
3171 if (!empty($customField['customValue'])) {
3172 foreach ($customField['customValue'] as $customFieldValues) {
3173 $customGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
3178 $values['customGroup'] = $customGroup;
3180 $values['is_pay_later'] = $this->is_pay_later
;
3186 * Assign message variables to template but try to break the habit.
3188 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3189 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3190 * multiple recurring payments for processors like IATS that use tokens.
3192 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3193 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
3194 * Note we send directly from this function in some cases because it is only partly refactored.
3196 * Don't call this function directly as the signature will change.
3200 * @param bool $returnMessageText
3204 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
3205 // @todo - this should have a better separation of concerns - ie.
3206 // gatherMessageValues should build an array of values to be assigned to the template
3207 // and this function should assign them (assigning null if not set).
3208 // the way the pcpParams & honor Params section works is a baby-step towards this.
3209 $template = CRM_Core_Smarty
::singleton();
3210 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
3211 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
3212 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
3213 $template->assign('billingName', $values['billingName']);
3215 // For some unit tests contribution cannot contain paymentProcessor information
3216 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
3217 $template->assign('contributeMode', CRM_Core_SelectValues
::contributeMode()[$billingMode] ??
NULL);
3219 //assign honor information to receipt message
3220 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
3223 'soft_credit_type' => NULL,
3224 'honor_block_is_active' => NULL,
3226 if (isset($softRecord['soft_credit'])) {
3227 //if id of contribution page is present
3228 if (!empty($values['id'])) {
3229 $values['honor'] = [
3230 'honor_profile_values' => [],
3231 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3232 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
3235 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3236 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
3239 //offline contribution
3240 $softCreditTypes = $softCredits = [];
3241 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3242 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3243 $softCredits[$key] = [
3244 'Name' => $softCredit['contact_name'],
3245 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
3248 $template->assign('softCreditTypes', $softCreditTypes);
3249 $template->assign('softCredits', $softCredits);
3253 $dao = new CRM_Contribute_DAO_ContributionProduct();
3254 $dao->contribution_id
= $this->id
;
3255 if ($dao->find(TRUE)) {
3256 $premiumId = $dao->product_id
;
3257 $template->assign('option', $dao->product_option
);
3259 $productDAO = new CRM_Contribute_DAO_Product();
3260 $productDAO->id
= $premiumId;
3261 $productDAO->find(TRUE);
3262 $template->assign('selectPremium', TRUE);
3263 $template->assign('product_name', $productDAO->name
);
3264 $template->assign('price', $productDAO->price
);
3265 $template->assign('sku', $productDAO->sku
);
3267 $template->assign('title', $values['title'] ??
NULL);
3268 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
3269 if (!$values['amount'] && isset($this->total_amount
)) {
3270 $values['amount'] = $this->total_amount
;
3275 'pcp_display_in_roll' => NULL,
3276 'pcp_roll_nickname' => NULL,
3277 'pcp_personal_note' => NULL,
3281 if (strtolower($this->_component
) == 'contribute') {
3283 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3284 $softDAO->contribution_id
= $this->id
;
3285 if ($softDAO->find(TRUE)) {
3286 $pcpParams['pcpBlock'] = TRUE;
3287 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
3288 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
3289 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
3291 //assign the pcp page title for email subject
3292 $pcpDAO = new CRM_PCP_DAO_PCP();
3293 $pcpDAO->id
= $softDAO->pcp_id
;
3294 if ($pcpDAO->find(TRUE)) {
3295 $pcpParams['title'] = $pcpDAO->title
;
3299 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3300 $template->assign($templateKey, $templateValue);
3303 if ($this->financial_type_id
) {
3304 $values['financial_type_id'] = $this->financial_type_id
;
3307 $template->assign('trxn_id', $this->trxn_id
);
3308 $template->assign('receive_date',
3309 CRM_Utils_Date
::processDate($this->receive_date
)
3311 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
3312 $template->assign('action', $this->is_test ?
1024 : 1);
3313 $template->assign('receipt_text', $values['receipt_text'] ??
NULL);
3314 $template->assign('is_monetary', 1);
3315 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3316 $template->assign('currency', $this->currency
);
3317 $template->assign('address', CRM_Utils_Address
::format($input));
3318 if (!empty($values['customGroup'])) {
3319 $template->assign('customGroup', $values['customGroup']);
3321 if (!empty($values['softContributions'])) {
3322 $template->assign('softContributions', $values['softContributions']);
3324 if ($this->_component
== 'event') {
3325 $template->assign('title', $values['event']['title']);
3326 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3328 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3329 $viewRoles[] = $participantRoles[$v];
3331 $values['event']['participant_role'] = implode(', ', $viewRoles);
3332 $template->assign('event', $values['event']);
3333 $template->assign('participant', $values['participant']);
3334 $template->assign('location', $values['location']);
3335 $template->assign('customPre', $values['custom_pre_id']);
3336 $template->assign('customPost', $values['custom_post_id']);
3339 if ($this->_relatedObjects
['participant']->is_test
) {
3343 $values['params'] = [];
3344 //to get email of primary participant.
3345 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3346 $primaryAmount[] = [
3347 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3348 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3350 //build an array of cId/pId of participants
3351 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3352 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3353 //send receipt to additional participant if exists
3354 if (count($additionalIDs)) {
3355 $template->assign('isPrimary', 0);
3356 $template->assign('customProfile', NULL);
3357 //set additionalParticipant true
3358 $values['params']['additionalParticipant'] = TRUE;
3359 foreach ($additionalIDs as $pId => $cId) {
3361 //to change the status pending to completed
3362 $additional = new CRM_Event_DAO_Participant();
3363 $additional->id
= $pId;
3364 $additional->contact_id
= $cId;
3365 $additional->find(TRUE);
3366 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3367 $additional->status_id
= 1;
3368 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3369 //if additional participant dont have email
3371 if (!$additionalParticipantInfo) {
3372 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3375 'label' => $additional->fee_level
,
3376 'amount' => $additional->fee_amount
,
3378 $primaryAmount[] = [
3379 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3380 'amount' => $additional->fee_amount
,
3382 $additional->save();
3383 $template->assign('amount', $amount);
3384 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3388 //build an array of custom profile and assigning it to template
3389 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3391 if (count($customProfile)) {
3392 $template->assign('customProfile', $customProfile);
3395 // for primary contact
3396 $values['params']['additionalParticipant'] = FALSE;
3397 $template->assign('isPrimary', 1);
3398 $template->assign('amount', $primaryAmount);
3399 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3400 if ($this->payment_instrument_id
) {
3401 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3402 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3404 // carry paylater, since we did not created billing,
3405 // so need to pull email from primary location, CRM-4395
3406 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3412 * Check whether payment processor supports
3413 * cancellation of contribution subscription
3415 * @param int $contributionId
3418 * @param bool $isNotCancelled
3422 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3423 $cacheKeyString = "$contributionId";
3424 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3426 static $supportsCancel = [];
3428 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3429 $supportsCancel[$cacheKeyString] = FALSE;
3430 $isCancelled = FALSE;
3432 if ($isNotCancelled) {
3433 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3436 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3437 if (!empty($paymentObject)) {
3438 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3441 return $supportsCancel[$cacheKeyString];
3445 * Check whether subscription is already cancelled.
3447 * @param int $contributionId
3451 * contribution status
3453 public static function isSubscriptionCancelled($contributionId) {
3455 SELECT cr.contribution_status_id
3456 FROM civicrm_contribution_recur cr
3457 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3458 WHERE con.id = %1 LIMIT 1";
3459 $params = [1 => [$contributionId, 'Integer']];
3460 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3461 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
3462 if ($status == 'Cancelled') {
3469 * Create all financial accounts entry.
3471 * @param array $params
3472 * Contribution object, line item array and params for trxn.
3475 * @param array $financialTrxnValues
3477 * @return null|\CRM_Core_BAO_FinancialTrxn
3479 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3480 $skipRecords = $update = $return = $isRelatedId = FALSE;
3481 $isUpdate = !empty($params['prevContribution']);
3483 $additionalParticipantId = [];
3484 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3485 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3487 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3488 $entityId = $params['participant_id'];
3489 $entityTable = 'civicrm_participant';
3490 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3492 elseif (!empty($params['membership_id'])) {
3493 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3494 // are created off one contribution should be handled elsewhere
3495 $entityId = $params['membership_id'];
3496 $entityTable = 'civicrm_membership';
3499 $entityId = $params['contribution']->id
;
3500 $entityTable = 'civicrm_contribution';
3503 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3504 $isRelatedId = TRUE;
3507 $entityID[] = $entityId;
3508 if (!empty($additionalParticipantId)) {
3509 $entityID +
= $additionalParticipantId;
3511 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3512 if (empty($params['prevContribution'])) {
3516 $statusId = $params['contribution']->contribution_status_id
;
3518 // build line item array if its not set in $params
3519 if (empty($params['line_item']) ||
$additionalParticipantId) {
3520 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3523 if ($contributionStatus != 'Failed' &&
3524 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3526 $skipRecords = TRUE;
3531 if (in_array($contributionStatus, $pendingStatus)) {
3532 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3533 $params['financial_type_id'],
3534 'Accounts Receivable Account is'
3537 elseif (!empty($params['payment_processor'])) {
3538 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3539 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3540 'id' => $params['payment_processor'],
3541 'return' => 'payment_instrument_id',
3544 elseif (!empty($params['payment_instrument_id'])) {
3545 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3548 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3549 $queryParams = [1 => [$relationTypeId, 'Integer']];
3550 $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);
3553 $totalAmount = $params['total_amount'] ??
NULL;
3554 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3555 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3557 //build financial transaction params
3559 'contribution_id' => $params['contribution']->id
,
3560 'to_financial_account_id' => $params['to_financial_account_id'],
3561 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3562 'total_amount' => $totalAmount,
3563 'fee_amount' => $params['fee_amount'] ??
NULL,
3564 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3565 'currency' => $params['contribution']->currency
,
3566 'trxn_id' => $params['contribution']->trxn_id
,
3567 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3568 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3569 // this should really default to completed (after discussion).
3570 'status_id' => $statusId,
3571 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3572 'check_number' => $params['check_number'] ??
NULL,
3573 'pan_truncation' => $params['pan_truncation'] ??
NULL,
3574 'card_type_id' => $params['card_type_id'] ??
NULL,
3576 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3577 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3578 if (isset($params['refund_trxn_id'])) {
3579 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3580 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3583 //CRM-16259, set is_payment flag for non pending status
3584 if (!in_array($contributionStatus, $pendingStatus)) {
3585 $trxnParams['is_payment'] = 1;
3587 if (!empty($params['payment_processor'])) {
3588 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3591 if (isset($fromFinancialAccountId)) {
3592 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3595 // consider external values passed for recording transaction entry
3596 if (!empty($financialTrxnValues)) {
3597 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3599 if (empty($trxnParams['payment_processor_id'])) {
3600 unset($trxnParams['payment_processor_id']);
3603 $params['trxnParams'] = $trxnParams;
3607 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3608 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3609 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3610 if (!isset($params['trxnParams']['trxn_id'])) {
3611 // Actually I have no idea why we are overwriting any values from the previous contribution.
3612 // (filling makes sense to me). However, only protecting this value as I really really know we
3613 // don't want this one overwritten.
3615 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3617 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3619 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3620 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3621 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3623 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3624 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3627 //if financial type is changed
3628 if (!empty($params['financial_type_id']) &&
3629 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3631 $accountRelationship = 'Income Account is';
3632 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3633 $accountRelationship = 'Deferred Revenue Account is';
3635 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3636 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3637 if ($oldFinancialAccount != $newFinancialAccount) {
3638 $params['total_amount'] = 0;
3639 // If we have a fee amount set reverse this as well.
3640 if (isset($params['fee_amount'])) {
3641 $params['trxnParams']['fee_amount'] = 0 - $params['fee_amount'];
3643 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3644 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3645 $params['prevContribution']->financial_type_id
, $accountRelationship);
3648 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3649 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3650 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3653 self
::updateFinancialAccounts($params, 'changeFinancialType');
3654 $params['skipLineItem'] = FALSE;
3655 foreach ($params['line_item'] as &$lineItems) {
3656 foreach ($lineItems as &$line) {
3657 $line['financial_type_id'] = $params['financial_type_id'];
3660 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType');
3661 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3662 $params['financial_account_id'] = $newFinancialAccount;
3663 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3664 // Set the transaction fee amount back to the original value for creating the new positive financial trxn.
3665 if (isset($params['fee_amount'])) {
3666 $params['trxnParams']['fee_amount'] = $params['fee_amount'];
3668 self
::updateFinancialAccounts($params);
3669 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE);
3670 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3672 $params['deferred_financial_account_id'] = $newFinancialAccount;
3676 //Update contribution status
3677 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3678 if (!isset($params['refund_trxn_id'])) {
3679 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3680 // gets preference over another so I am only 'protecting' a very specific tested flow
3681 // and letting natural justice take care of the rest.
3682 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3684 if (!empty($params['contribution_status_id']) &&
3685 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3687 //Update Financial Records
3688 $callUpdateFinancialAccounts = self
::updateFinancialAccountsOnContributionStatusChange($params);
3689 if ($callUpdateFinancialAccounts) {
3690 self
::updateFinancialAccounts($params, 'changedStatus');
3691 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus');
3696 // change Payment Instrument for a Completed contribution
3697 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3698 // instrument is null and now new payment instrument is added along with the payment
3699 if (!$params['contribution']->payment_instrument_id
) {
3700 $params['contribution']->find(TRUE);
3702 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3703 $params['trxnParams']['check_number'] = $params['check_number'] ??
NULL;
3705 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3706 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3709 //if Change contribution amount
3710 $params['trxnParams']['fee_amount'] = $params['fee_amount'] ??
NULL;
3711 $params['trxnParams']['net_amount'] = $params['net_amount'] ??
NULL;
3712 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3713 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3714 if (isset($totalAmount) &&
3715 $totalAmount != $params['prevContribution']->total_amount
3717 //Update Financial Records
3718 $params['trxnParams']['from_financial_account_id'] = NULL;
3719 self
::updateFinancialAccounts($params, 'changedAmount');
3720 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount');
3725 // Looks like we might have a data correction update.
3726 // This would be a case where a transaction id has been entered but it is incorrect &
3727 // the person goes back in & fixes it, as opposed to a new transaction.
3728 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3729 // the data fix scenario.
3731 if (isset($params['refund_trxn_id'])) {
3732 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3733 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3734 civicrm_api3('FinancialTrxn', 'create', [
3735 'id' => $refundIDs['financialTrxnId'],
3736 'trxn_id' => $params['refund_trxn_id'],
3740 $cardType = $params['card_type_id'] ??
NULL;
3741 $panTruncation = $params['pan_truncation'] ??
NULL;
3742 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3747 // records finanical trxn and entity financial trxn
3748 // also make it available as return value
3749 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3750 $trxnParams['pan_truncation'] = $params['pan_truncation'] ??
NULL;
3751 $trxnParams['card_type_id'] = $params['card_type_id'] ??
NULL;
3752 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3753 $params['entity_id'] = $financialTxn->id
;
3754 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3755 self
::$_trxnIDs[] = $financialTxn->id
;
3759 // record line items and financial items
3760 if (empty($params['skipLineItem'])) {
3761 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $isUpdate);
3764 // create batch entry if batch_id is passed and
3765 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3766 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3768 'batch_id' => $params['batch_id'],
3769 'entity_table' => 'civicrm_financial_trxn',
3770 'entity_id' => $financialTxn->id
,
3772 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3775 // when a fee is charged
3776 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3777 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3780 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3781 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3783 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3784 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3785 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3787 unset($params['line_item']);
3788 self
::$_trxnIDs = NULL;
3793 * Update all financial accounts entry.
3795 * @param array $params
3796 * Contribution object, line item array and params for trxn.
3798 * @param string $context
3801 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3802 * adds unpredictability.
3805 public static function updateFinancialAccounts(&$params, $context = NULL) {
3807 $inputParams = $params;
3808 $isARefund = self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
);
3810 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3811 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3812 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3815 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3816 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3817 $params['entity_id'] = $trxn->id
;
3819 $itemParams['entity_table'] = 'civicrm_line_item';
3820 $trxnIds['id'] = $params['entity_id'];
3821 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution']->id
);
3822 foreach ($params['line_item'] as $fieldId => $fields) {
3823 $params = self
::createFinancialItemsForLine($params, $context, $fields, $previousLineItems, $inputParams, $isARefund, $trxnIds, $fieldId);
3828 * Is this contribution status a reversal.
3830 * If so we would expect to record a negative value in the financial_trxn table.
3832 * @param int $status_id
3836 public static function isContributionStatusNegative($status_id) {
3837 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3838 return in_array(CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE);
3842 * Check status validation on update of a contribution.
3844 * @param array $values
3845 * Previous form values before submit.
3847 * @param array $fields
3848 * The input form values.
3850 * @param array $errors
3855 public static function checkStatusValidation($values, &$fields, &$errors) {
3856 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3857 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3858 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3862 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3864 'Cancelled' => ['Completed', 'Refunded'],
3865 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3866 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3867 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3868 'Refunded' => ['Cancelled', 'Completed'],
3869 'Partially paid' => ['Completed'],
3870 'Pending refund' => ['Completed', 'Refunded'],
3871 'Failed' => ['Pending'],
3874 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3875 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3877 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3878 1 => $contributionStatuses[$values['contribution_status_id']],
3879 2 => $contributionStatuses[$fields['contribution_status_id']],
3885 * Delete contribution of contact.
3887 * @see https://issues.civicrm.org/jira/browse/CRM-12155
3889 * @param int $contactId
3893 public static function deleteContactContribution($contactId) {
3894 $contribution = new CRM_Contribute_DAO_Contribution();
3895 $contribution->contact_id
= $contactId;
3896 $contribution->find();
3897 while ($contribution->fetch()) {
3898 self
::deleteContribution($contribution->id
);
3903 * Get options for a given contribution field.
3905 * @param string $fieldName
3906 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3907 * @param array $props whatever is known about this dao object.
3909 * @return array|bool
3910 * @see CRM_Core_DAO::buildOptions
3913 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3914 $className = __CLASS__
;
3916 if (isset($props['orderColumn'])) {
3917 $params['orderColumn'] = $props['orderColumn'];
3919 switch ($fieldName) {
3920 // This field is not part of this object but the api supports it
3921 case 'payment_processor':
3922 $className = 'CRM_Contribute_BAO_ContributionPage';
3923 // Filter results by contribution page
3924 if (!empty($props['contribution_page_id'])) {
3925 $page = civicrm_api('contribution_page', 'getsingle', [
3927 'id' => ($props['contribution_page_id']),
3929 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3930 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3934 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3935 case 'honor_type_id':
3936 $className = 'CRM_Contribute_BAO_ContributionSoft';
3937 $fieldName = 'soft_credit_type_id';
3938 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3941 case 'contribution_status_id':
3942 if ($context !== 'validate') {
3943 $params['condition'] = "v.name <> 'Template'";
3946 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3950 * Validate financial type.
3952 * @see https://issues.civicrm.org/jira/browse/CRM-13231
3954 * @param int $financialTypeId
3955 * Financial Type id.
3957 * @param string $relationName
3959 * @return array|bool
3961 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3962 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3964 if (!$financialAccount) {
3965 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3971 * @param int $targetCid
3972 * @param $activityType
3973 * @param string $title
3974 * @param int $contributionId
3975 * @param string $totalAmount
3976 * @param string $currency
3977 * @param string $trxn_date
3979 * @throws \CRM_Core_Exception
3980 * @throws \CiviCRM_API3_Exception
3982 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
3983 $paymentAmount = CRM_Utils_Money
::format($totalAmount, $currency);
3984 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3985 $date = CRM_Utils_Date
::isoToMysql($trxn_date);
3986 // source record id would be the contribution id
3987 $srcRecId = $contributionId;
3991 'source_contact_id' => $targetCid,
3992 'source_record_id' => $srcRecId,
3993 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
3994 'subject' => $subject,
3995 'activity_date_time' => $date,
3996 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
3997 'skipRecentView' => TRUE,
4000 // create activity with target contacts
4001 $session = CRM_Core_Session
::singleton();
4002 $id = $session->get('userID');
4004 $activityParams['source_contact_id'] = $id;
4005 $activityParams['target_contact_id'][] = $targetCid;
4007 civicrm_api3('Activity', 'create', $activityParams);
4011 * Get list of payments displayed by Contribute_Page_PaymentInfo.
4014 * @param string $component
4015 * @param bool $getTrxnInfo
4019 * @throws \CRM_Core_Exception
4020 * @throws \CiviCRM_API3_Exception
4022 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE) {
4023 // @todo deprecate passing in component - always call with contribution.
4024 if ($component == 'event') {
4025 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
4027 if (!$contributionId) {
4028 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4029 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4030 $id = $primaryParticipantId;
4032 if (!$contributionId) {
4037 elseif ($component == 'membership') {
4038 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
4041 $contributionId = $id;
4044 // The balance used to be calculated this way - we really want to remove this 'oldCalculation'
4045 // but need to unpick the whole trxn_id it's returning first.
4046 $oldCalculation = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
4047 $baseTrxnId = !empty($oldCalculation['trxn_id']) ?
$oldCalculation['trxn_id'] : NULL;
4049 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
4050 $baseTrxnId = $baseTrxnId['financialTrxnId'];
4052 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4054 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
4056 $contribution = civicrm_api3('Contribution', 'getsingle', [
4057 'id' => $contributionId,
4061 'contribution_status_id',
4062 'financial_type_id',
4066 $info['payLater'] = $contribution['is_pay_later'];
4067 $info['contribution_status'] = $contribution['contribution_status'];
4068 $info['currency'] = $contribution['currency'];
4070 $info['total'] = $total;
4071 $info['paid'] = $total - $paymentBalance;
4072 $info['balance'] = $paymentBalance;
4074 $info['component'] = $component;
4075 if ($getTrxnInfo && $baseTrxnId) {
4076 $info['transaction'] = self
::getContributionTransactionInformation($contributionId, $contribution['financial_type_id']);
4079 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
4084 * Get the outstanding balance on a contribution.
4086 * @param int $contributionId
4087 * @param float $contributionTotal
4088 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
4092 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
4093 if ($contributionTotal === NULL) {
4094 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4097 return (float) CRM_Utils_Money
::subtractCurrencies(
4099 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE),
4100 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4105 * Get the tax amount (misnamed function).
4107 * @param array $params
4110 * @throws \CiviCRM_API3_Exception
4112 protected static function checkTaxAmount($params) {
4113 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4115 // Update contribution.
4116 if (!empty($params['id'])) {
4117 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4118 // there are no tax implications - early return.
4119 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4122 if (empty($params['prevContribution'])) {
4123 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4126 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
4127 if (!isset($params[$field])) {
4128 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4129 // Tax amount gets added back on later....
4130 $params['total_amount'] = $params['prevContribution']->total_amount
-
4131 $params['prevContribution']->tax_amount
;
4134 $params[$field] = $params['prevContribution']->$field;
4135 if ($params[$field] != $params['prevContribution']->$field) {
4141 self
::calculateMissingAmountParams($params, $params['id']);
4142 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4143 // Assign tax Amount on update of contribution
4144 if (!empty($params['prevContribution']->tax_amount
)) {
4145 $params['tax_amount'] = 'null';
4146 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4147 foreach ($params['line_item'] as $setID => $priceField) {
4148 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4149 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4156 // New Contribution and update of contribution with tax rate financial type
4157 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4158 empty($params['skipLineItem'])) {
4159 $taxRateParams = $taxRates[$params['financial_type_id']];
4160 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams);
4161 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4163 // Get Line Item on update of contribution
4164 if (isset($params['id'])) {
4165 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4168 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4170 foreach ($params['line_item'] as $setID => $priceField) {
4171 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4172 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4175 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4177 elseif (isset($params['api.line_item.create'])) {
4178 // Update total amount of contribution using lineItem
4179 $taxAmountArray = [];
4180 foreach ($params['api.line_item.create'] as $key => $value) {
4181 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4182 $taxRate = $taxRates[$value['financial_type_id']];
4183 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4184 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4187 $params['tax_amount'] = array_sum($taxAmountArray);
4188 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4195 * Check financial type validation on update of a contribution.
4197 * @param int $financialTypeId
4198 * Value of latest Financial Type.
4200 * @param int $contributionId
4203 * @param array $errors
4208 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4209 if (!empty($financialTypeId)) {
4210 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4211 if ($oldFinancialTypeId == $financialTypeId) {
4215 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4217 '1' => [$contributionId, 'Integer'],
4219 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4220 if ($result->N
> 1) {
4221 $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.');
4226 * Update related pledge payment payments.
4228 * This function has been refactored out of the back office contribution form and may
4229 * still overlap with other functions.
4231 * @param string $action
4232 * @param int $pledgePaymentID
4233 * @param int $contributionID
4234 * @param bool $adjustTotalAmount
4235 * @param float $total_amount
4236 * @param float $original_total_amount
4237 * @param int $contribution_status_id
4238 * @param int $original_contribution_status_id
4240 public static function updateRelatedPledge(
4246 $original_total_amount,
4247 $contribution_status_id,
4248 $original_contribution_status_id
4250 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4254 if ($pledgePaymentID) {
4255 //store contribution id in payment record.
4256 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4259 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4266 if (!$pledgePaymentID) {
4269 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4275 $updatePledgePaymentStatus = FALSE;
4277 // If either the status or the amount has changed we update the pledge status.
4278 if ($action & CRM_Core_Action
::ADD
) {
4279 $updatePledgePaymentStatus = TRUE;
4281 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4282 ($original_total_amount != $total_amount))
4284 $updatePledgePaymentStatus = TRUE;
4287 if ($updatePledgePaymentStatus) {
4288 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4290 $contribution_status_id,
4299 * Is there only one line item attached to the contribution.
4305 * @throws \CiviCRM_API3_Exception
4307 public static function isSingleLineItem($id) {
4308 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
4309 return ($lineItemCount == 1);
4313 * Complete an order.
4315 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4317 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4319 * Moving it out of the BaseIPN class is just the first step.
4321 * @param array $input
4323 * @param \CRM_Contribute_BAO_Contribution $contribution
4324 * @param bool $isPostPaymentCreate
4325 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
4326 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
4327 * transitioning related elements).
4330 * @throws \CRM_Core_Exception
4331 * @throws \CiviCRM_API3_Exception
4333 public static function completeOrder($input, $ids, $contribution, $isPostPaymentCreate = FALSE) {
4334 $transaction = new CRM_Core_Transaction();
4335 // @todo see if we even need this - it's used further down to create an activity
4336 // but the BAO layer should create that - we just need to add a test to cover it & can
4337 // maybe remove $ids altogether.
4338 $contributionContactID = $ids['related_contact'];
4339 $participantID = $ids['participant'];
4340 $recurringContributionID = $ids['contributionRecur'];
4342 // Unset ids just to make it clear it's not used again.
4344 // The previous details are used when calculating line items so keep it before any code that 'does something'
4345 if (!empty($contribution->id
)) {
4346 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(['id' => $contribution->id
]);
4348 $inputContributionWhiteList = [
4353 'payment_instrument_id',
4358 'contribution_status_id',
4361 'financial_type_id',
4364 $paymentProcessorId = $input['payment_processor_id'] ??
NULL;
4366 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4368 $contributionParams = array_merge([
4369 'contribution_status_id' => $completedContributionStatusID,
4370 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4373 $contributionParams['payment_processor'] = $paymentProcessorId;
4375 if (empty($contributionParams['payment_instrument_id']) && $paymentProcessorId) {
4376 $contributionParams['payment_instrument_id'] = PaymentProcessor
::get(FALSE)->addWhere('id', '=', $paymentProcessorId)->addSelect('payment_instrument_id')->execute()->first()['payment_instrument_id'];
4379 if ($recurringContributionID) {
4380 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4382 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4384 $contributionResult = self
::repeatTransaction($contribution, $input, $contributionParams);
4385 $contributionID = (int) $contribution->id
;
4387 if ($input['component'] == 'contribute') {
4388 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4389 self
::updateMembershipBasedOnCompletionOfContribution(
4396 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4397 $participantParams['id'] = $participantID;
4398 $participantParams['status_id'] = 'Registered';
4399 civicrm_api3('Participant', 'create', $participantParams);
4403 $contributionParams['id'] = $contributionID;
4404 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
4406 if (!$contributionResult) {
4407 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4410 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4412 CRM_Core_Error
::debug_log_message('Contribution record updated successfully');
4413 $transaction->commit();
4415 // @todo - check if Contribution::create does this, test, remove.
4416 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contributionID, $recurringContributionID,
4417 $contributionParams['contribution_status_id'], $input['amount']);
4419 // create an activity record
4420 // @todo - check if Contribution::create does this, test, remove.
4421 if ($input['component'] == 'contribute') {
4423 $targetContactID = NULL;
4424 if ($contributionContactID) {
4425 $targetContactID = $contribution->contact_id
;
4426 $contribution->contact_id
= $contributionContactID;
4428 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution', $targetContactID);
4431 if (self
::isEmailReceipt($input, $contribution->contribution_page_id
, $recurringContributionID)) {
4432 civicrm_api3('Contribution', 'sendconfirmation', [
4433 'id' => $contributionID,
4434 'payment_processor_id' => $paymentProcessorId,
4436 CRM_Core_Error
::debug_log_message("Receipt sent");
4439 CRM_Core_Error
::debug_log_message("Success: Database updated");
4440 return $contributionResult;
4444 * Send receipt from contribution.
4446 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4448 * Note that the compose message part has been moved to contribution
4449 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4451 * @param array $input
4452 * Incoming data from Payment processor.
4454 * Related object IDs.
4455 * @param int $contributionID
4456 * @param bool $returnMessageText
4457 * Should text be returned instead of sent. This.
4458 * is because the function is also used to generate pdfs
4461 * @throws \CRM_Core_Exception
4462 * @throws \CiviCRM_API3_Exception
4463 * @throws \Exception
4465 public static function sendMail($input, $ids, $contributionID, $returnMessageText = FALSE) {
4467 $contribution = new CRM_Contribute_BAO_Contribution();
4468 $contribution->id
= $contributionID;
4469 if (!$contribution->find(TRUE)) {
4470 throw new CRM_Core_Exception('Contribution does not exist');
4472 $contribution->loadRelatedObjects($input, $ids, TRUE);
4473 // set receipt from e-mail and name in value
4474 if (!$returnMessageText) {
4475 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4477 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4478 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4479 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4480 civicrm_api3('Contribution', 'create', [
4481 'receipt_date' => 'now',
4482 'id' => $contribution->id
,
4489 * Generate From email and from name in an array values
4491 * @param array $input
4492 * @param \CRM_Contribute_BAO_Contribution $contribution
4496 public static function generateFromEmailAndName($input, $contribution) {
4497 // Use input value if supplied.
4498 if (!empty($input['receipt_from_email'])) {
4500 CRM_Utils_Array
::value('receipt_from_name', $input, ''),
4501 $input['receipt_from_email'],
4504 // if we are still empty see if we can use anything from a contribution page.
4506 if (!empty($contribution->contribution_page_id
)) {
4507 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id
]);
4509 // if we are still empty see if we can use anything from a contribution page.
4510 if (!empty($pageValues['receipt_from_email'])) {
4512 CRM_Utils_Array
::value('receipt_from_name', $pageValues),
4513 $pageValues['receipt_from_email'],
4516 // If we are still empty fall back to the domain or logged in user information.
4517 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4521 * Load related memberships.
4525 * @return array $ids
4530 * Note that in theory it should be possible to retrieve these from the line_item table
4531 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4532 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4533 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4534 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4536 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4539 public function loadRelatedMembershipObjects($ids = []) {
4541 SELECT membership_id
4542 FROM civicrm_membership_payment
4543 WHERE contribution_id = %1 ";
4544 $params = [1 => [$this->id
, 'Integer']];
4545 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, []);
4547 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4548 while ($dao->fetch()) {
4549 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4550 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4554 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4555 foreach ($ids['membership'] as $id) {
4557 $membership = new CRM_Member_BAO_Membership();
4558 $membership->id
= $id;
4559 if (!$membership->find(TRUE)) {
4560 throw new Exception("Could not find membership record: $id");
4562 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4563 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4564 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4565 $this->_relatedObjects
['membership'][$membership->id
. '_' . $membership->membership_type_id
] = $membership;
4574 * Function use to store line item proportionally in in entity financial trxn table
4576 * @param array $trxnParams
4578 * @param int $trxnId
4580 * @param float $contributionTotalAmount
4582 * @throws \CiviCRM_API3_Exception
4584 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4585 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4586 if (!empty($lineItems)) {
4587 // get financial item
4588 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4590 'contribution_total_amount' => $contributionTotalAmount,
4591 'trxn_total_amount' => $trxnParams['total_amount'],
4592 'trxn_id' => $trxnId,
4594 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4599 * Checks if line items total amounts
4600 * match the contribution total amount.
4602 * @param array $params
4603 * array of order params.
4605 * @throws \API_Exception
4607 public static function checkLineItems(&$params) {
4608 $totalAmount = $params['total_amount'] ??
NULL;
4609 $lineItemAmount = 0;
4611 foreach ($params['line_items'] as &$lineItems) {
4612 foreach ($lineItems['line_item'] as &$item) {
4613 if (empty($item['financial_type_id'])) {
4614 $item['financial_type_id'] = $params['financial_type_id'];
4616 $lineItemAmount +
= $item['line_total'] +
($item['tax_amount'] ??
0.00);
4620 if (!isset($totalAmount)) {
4621 $params['total_amount'] = $lineItemAmount;
4624 $currency = $params['currency'] ?? CRM_Core_Config
::singleton()->defaultCurrency
;
4626 if (!CRM_Utils_Money
::equals($totalAmount, $lineItemAmount, $currency)) {
4627 throw new CRM_Contribute_Exception_CheckLineItemsException();
4633 * Get the financial account for the item associated with the new transaction.
4635 * @param array $params
4636 * @param int $default
4640 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
4642 if (!empty($params['financial_account_id'])) {
4643 return $params['financial_account_id'];
4646 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4647 $preferredAccountsRelationships = [
4648 'Refunded' => 'Credit/Contra Revenue Account is',
4649 'Chargeback' => 'Chargeback Account is',
4652 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4653 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4654 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4656 $preferredAccountsRelationships[$contributionStatus]
4664 * ContributionPage values were being imposed onto values.
4666 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4667 * REALLY didn't want superimposed. The rest are left there in their overkill out
4670 * The rationale for making this explicit is that it was a case of carefully set values being
4671 * seemingly randonly overwritten without much care. In general I think array randomly setting
4672 * variables en mass is risky.
4674 * @param array $values
4678 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4679 $contributionPageValues = [];
4680 CRM_Contribute_BAO_ContributionPage
::setValues(
4681 $this->contribution_page_id
,
4682 $contributionPageValues
4685 // These are the values that I believe to be useful.
4688 'pay_later_receipt',
4690 'receipt_from_email',
4691 'receipt_from_name',
4695 'honoree_profile_id',
4696 'onbehalf_profile_id',
4697 'honor_block_is_active',
4698 // Kinda might be - but would be on the contribution...
4701 // Included for 'fear of regression' but can't justify any use for these....
4703 'payment_processor',
4704 'financial_type_id',
4705 'amount_block_is_active',
4710 'default_amount_id',
4714 'initial_amount_help_text',
4715 'initial_amount_label',
4717 'is_allow_other_amount',
4718 'is_billing_required',
4719 'is_confirm_enabled',
4720 'is_credit_card_only',
4722 'is_partial_payment',
4723 'is_recur_installments',
4724 'is_recur_interval',
4728 'min_initial_amount',
4729 'recur_frequency_unit',
4736 foreach ($valuesToCopy as $valueToCopy) {
4737 if (isset($contributionPageValues[$valueToCopy])) {
4738 if ($valueToCopy === 'title') {
4739 $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils
::getContributionPageTitle($this->contribution_page_id
);
4742 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
4750 * Get values of CiviContribute Settings
4751 * and check if its enabled or not.
4752 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
4753 * in serialized form. Usually this should be stored as flat settings for each form fields
4754 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
4755 * settings we will live with an inconsistency because it's too hard to change for now.
4756 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
4759 * @param string $name
4764 public static function checkContributeSettings($name) {
4765 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
4766 return $contributeSettings[$name] ??
NULL;
4770 * Get the contribution as it is in the database before being updated.
4772 * @param int $contributionID
4774 * @return \CRM_Contribute_BAO_Contribution|null
4776 private static function getOriginalContribution($contributionID) {
4777 return self
::getValues(['id' => $contributionID]);
4781 * Get the amount for the financial item row.
4783 * Helper function to start to break down recordFinancialTransactions for readability.
4785 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
4787 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
4788 * for historical reasons. Going forwards we can hope to add tests & improve readibility
4791 * @param array $params
4792 * Params as passed to contribution.create
4794 * @param string $context
4795 * changeFinancialType| changedAmount
4796 * @param array $lineItemDetails
4798 * @param bool $isARefund
4799 * Is this a refund / negative transaction.
4800 * @param int $previousLineItemTotal
4803 * @todo move recordFinancialAccounts & helper functions to their own class?
4806 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
4807 if ($context == 'changedAmount') {
4808 $lineTotal = $lineItemDetails['line_total'];
4809 if ($lineTotal != $previousLineItemTotal) {
4810 $lineTotal -= $previousLineItemTotal;
4814 elseif ($context == 'changeFinancialType') {
4815 return -$lineItemDetails['line_total'];
4817 elseif ($context == 'changedStatus') {
4818 $cancelledTaxAmount = 0;
4820 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
4822 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
4824 elseif ($context === NULL) {
4825 // erm, yes because? but, hey, it's tested.
4826 return $lineItemDetails['line_total'];
4828 elseif (empty($lineItemDetails['line_total'])) {
4829 // follow legacy code path
4831 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', ['civi.tag' => 'deprecated']);
4832 return $params['total_amount'];
4835 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
4840 * Get the multiplier for adjusting rows.
4842 * If we are dealing with a refund or cancellation then it will be a negative
4843 * amount to reflect the negative transaction.
4845 * If we are changing Financial Type it will be a negative amount to
4846 * adjust down the old type.
4848 * @param int $contribution_status_id
4849 * @param string $context
4853 protected static function getMultiplier($contribution_status_id, $context) {
4854 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
4861 * Does this transaction reflect a payment instrument change.
4863 * @param array $params
4864 * @param array $pendingStatuses
4868 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
4869 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
4871 if (array_key_exists('payment_instrument_id', $params)) {
4872 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
4873 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
4875 //check if status is changed from Pending to Completed
4876 // do not update payment instrument changes for Pending to Completed
4877 if (!($contributionStatus == 'Completed' &&
4878 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
4883 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
4884 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
4885 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
4889 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
4890 $params['contribution']->check_number
!= $params['prevContribution']->check_number
4892 // another special case when check number is changed, create new financial records
4893 // create financial trxn with negative amount
4901 * Update the memberships associated with a contribution if it has been completed.
4903 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
4904 * load them in this function. Code clean up would compensate for any minor performance implication.
4906 * @param int $contributionID
4907 * @param string $changeDate
4909 * @throws \CRM_Core_Exception
4910 * @throws \CiviCRM_API3_Exception
4912 public static function updateMembershipBasedOnCompletionOfContribution($contributionID, $changeDate) {
4913 $memberships = self
::getRelatedMemberships($contributionID);
4914 foreach ($memberships as $membership) {
4915 $membershipParams = [
4916 'id' => $membership['id'],
4917 'contact_id' => $membership['contact_id'],
4918 'is_test' => $membership['is_test'],
4919 'membership_type_id' => $membership['membership_type_id'],
4920 'membership_activity_status' => 'Completed',
4923 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4924 $membershipParams['membership_type_id'],
4925 $membershipParams['is_test'],
4926 $membershipParams['id']
4929 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4930 // this picks up membership type changes during renewals
4931 // @todo this is almost certainly an obsolete sql call, the pre-change
4932 // membership is accessible via $this->_relatedObjects
4934 SELECT membership_type_id
4935 FROM civicrm_membership_log
4936 WHERE membership_id={$membershipParams['id']}
4939 $dao = CRM_Core_DAO
::executeQuery($sql);
4940 if ($dao->fetch()) {
4941 if (!empty($dao->membership_type_id
)) {
4942 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4945 if (empty($membership['end_date']) ||
(int) $membership['status_id'] !== CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
4946 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
4947 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
4948 // 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.
4949 // ... except testCompleteTransactionMembershipPriceSetTwoTerms hits this line so the above is obviously not true....
4950 // @todo once apiv4 ships with core switch to that & find sanity.
4951 $membershipParams['num_terms'] = self
::getNumTermsByContributionAndMembershipType(
4952 $membershipParams['membership_type_id'],
4956 // @todo remove all this stuff in favour of letting the api call further down handle in
4957 // (it is a duplication of what the api does).
4958 $dates = array_fill_keys([
4963 if ($currentMembership) {
4965 * Fixed FOR CRM-4433
4966 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4967 * when Contribution mode is notify and membership is for renewal )
4969 // Test cover for this is in testRepeattransactionRenewMembershipOldMembership
4971 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4973 // @todo - we should pass membership_type_id instead of null here but not
4974 // adding as not sure of testing
4975 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4976 $changeDate, NULL, $membershipParams['num_terms']
4978 $dates['join_date'] = $currentMembership['join_date'];
4981 //get the status for membership.
4982 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4984 $dates['join_date'],
4987 $membershipParams['membership_type_id'],
4991 unset($dates['end_date']);
4992 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4993 //we might be renewing membership,
4994 //so make status override false.
4995 $membershipParams['is_override'] = FALSE;
4996 $membershipParams['status_override_end_date'] = 'null';
4997 civicrm_api3('Membership', 'create', $membershipParams);
5002 * Get payment links as they relate to a contribution.
5004 * If a payment can be made then include a payment link & if a refund is appropriate
5005 * then a refund link.
5008 * @param float $balance
5009 * @param string $contributionStatus
5012 * $actionLinks Links array containing:
5016 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
5017 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
5018 // In general the balance is the best way to determine if a payment can be added or not,
5019 // but not for Failed contributions, where we don't accept additional payments at the moment.
5020 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
5021 // do accept more payments agains them.
5026 'url' => CRM_Utils_System
::url('civicrm/payment', [
5032 'title' => ts('Record Payment'),
5035 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
5037 'url' => CRM_Utils_System
::url('civicrm/payment', [
5044 'title' => ts('Submit Credit Card payment'),
5048 'url' => CRM_Utils_System
::url('civicrm/payment', [
5054 'title' => ts('Record Refund'),
5056 return $actionLinks;
5060 * Get a query to determine the amount donated by the contact/s in the current financial year.
5062 * @param array $contactIDs
5066 public static function getAnnualQuery($contactIDs) {
5067 $contactIDs = implode(',', $contactIDs);
5068 $config = CRM_Core_Config
::singleton();
5069 $currentMonth = date('m');
5070 $currentDay = date('d');
5072 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
5074 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
5075 (int) $config->fiscalYearStart
['d'] > $currentDay
5078 $year = date('Y') - 1;
5083 $nextYear = $year +
1;
5085 if ($config->fiscalYearStart
) {
5086 $newFiscalYearStart = $config->fiscalYearStart
;
5087 if ($newFiscalYearStart['M'] < 10) {
5088 // This is just a clumsy way of adding padding.
5089 // @todo next round look for a nicer way.
5090 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
5092 if ($newFiscalYearStart['d'] < 10) {
5093 // This is just a clumsy way of adding padding.
5094 // @todo next round look for a nicer way.
5095 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
5097 $config->fiscalYearStart
= $newFiscalYearStart;
5098 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
5101 // First of January.
5104 $startDate = "$year$monthDay";
5105 $endDate = "$nextYear$monthDay";
5108 'contact_id' => 'IN (' . $contactIDs . ')',
5109 'is_test' => ' = 0',
5110 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
5112 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
5113 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
5116 foreach ($whereClauses as $key => $clause) {
5117 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
5119 $whereClauseString = implode(' AND ', $clauses);
5121 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5122 // this group by + having on contribution_status_id improves performance
5124 SELECT COUNT(*) as count,
5125 SUM(total_amount) as amount,
5126 AVG(total_amount) as average,
5128 FROM civicrm_contribution b
5129 WHERE " . $whereClauseString . "
5130 GROUP BY currency, contribution_status_id
5131 HAVING $havingClause
5137 * Assign Test Value.
5139 * @param string $fieldName
5140 * @param array $fieldDef
5141 * @param int $counter
5143 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5144 if ($fieldName == 'tax_amount') {
5145 $this->{$fieldName} = "0.00";
5147 elseif ($fieldName == 'net_amount') {
5148 $this->{$fieldName} = "2.00";
5150 elseif ($fieldName == 'total_amount') {
5151 $this->{$fieldName} = "3.00";
5153 elseif ($fieldName == 'fee_amount') {
5154 $this->{$fieldName} = "1.00";
5157 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5162 * Check if contribution has participant/membership payment.
5164 * @param int $contributionId
5169 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5170 // get line item for contribution
5171 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5172 // check if line item is for membership or participant
5173 foreach ($lineItems as $items) {
5174 if ($items['entity_table'] == 'civicrm_participant') {
5178 elseif ($items['entity_table'] == 'civicrm_membership') {
5190 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5192 * @param array $trxnParams
5193 * Financial trxn params
5194 * @param array $contributionParams
5195 * Contribution Params
5199 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5200 if (!Civi
::settings()->get('always_post_to_accounts_receivable')) {
5203 $statusId = $contributionParams['contribution']->contribution_status_id
;
5204 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5205 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5206 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5207 // Return if contribution status is not completed.
5208 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5209 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5210 && $contributionParams['prevContribution']->is_pay_later
== 0
5216 $params = $trxnParams;
5217 $financialTypeID = !empty($contributionParams['financial_type_id']) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5218 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5219 $params['to_financial_account_id'] = $arAccountId;
5220 $params['status_id'] = array_search('Pending', $contributionStatuses);
5221 $params['is_payment'] = FALSE;
5222 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5223 self
::$_trxnIDs[] = $trxn->id
;
5224 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5228 * Calculate financial item amount when contribution is updated.
5230 * @param array $params
5231 * contribution params
5232 * @param array $amountParams
5234 * @param string $context
5238 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5239 if (!empty($params['is_quick_config'])) {
5240 $amount = $amountParams['item_amount'];
5242 $amount = $params['total_amount'];
5243 if ($context === NULL) {
5244 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5249 $amount = $amountParams['line_total'];
5250 if ($context == 'changedAmount') {
5251 $amount -= $amountParams['previous_line_total'];
5253 $amount *= $amountParams['diff'];
5259 * Retrieve Sales Tax Financial Accounts.
5265 public static function getSalesTaxFinancialAccounts() {
5266 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5267 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5268 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5269 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5270 $queryParams = [1 => [$accountRel, 'Integer']];
5271 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5272 $financialAccount = [];
5273 while ($dao->fetch()) {
5274 $financialAccount[$dao->id
] = $dao->id
;
5276 return $financialAccount;
5280 * Create tax entry in civicrm_entity_financial_trxn table.
5282 * @param array $entityParams
5284 * @param array $eftParams
5286 * @throws \CiviCRM_API3_Exception
5288 public static function createProportionalEntry($entityParams, $eftParams) {
5290 if ($entityParams['contribution_total_amount'] != 0) {
5291 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5293 // Record Entity Financial Trxn; CRM-20145
5294 $eftParams['amount'] = $paid;
5295 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5299 * Create array of last financial item id's.
5301 * @param int $contributionId
5305 public static function getLastFinancialItemIds($contributionId) {
5306 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5307 FROM civicrm_financial_item fi
5308 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5309 WHERE li.contribution_id = %1";
5310 $dao = CRM_Core_DAO
::executeQuery($sql, [
5316 $ftIds = $taxItems = [];
5317 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5318 while ($dao->fetch()) {
5319 /* if sales tax item*/
5320 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5321 $taxItems[$dao->price_field_value_id
] = [
5322 'financial_item_id' => $dao->id
,
5323 'amount' => $dao->tax_amount
,
5327 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5330 return [$ftIds, $taxItems];
5334 * Create proportional entries in civicrm_entity_financial_trxn.
5336 * @param array $entityParams
5338 * @param array $lineItems
5340 * @param array $ftIds
5342 * @param array $taxItems
5344 * @throws \CiviCRM_API3_Exception
5346 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5348 'entity_table' => 'civicrm_financial_item',
5349 'financial_trxn_id' => $entityParams['trxn_id'],
5351 foreach ($lineItems as $key => $value) {
5352 if ($value['qty'] == 0) {
5355 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5356 $entityParams['line_item_amount'] = $value['line_total'];
5357 self
::createProportionalEntry($entityParams, $eftParams);
5358 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5359 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5360 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5361 self
::createProportionalEntry($entityParams, $eftParams);
5367 * Load entities related to the contribution into $this->_relatedObjects.
5371 * @throws \CRM_Core_Exception
5373 protected function loadRelatedEntitiesByID($ids) {
5375 'contact' => 'CRM_Contact_BAO_Contact',
5376 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5377 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5378 'financialType' => 'CRM_Financial_BAO_FinancialType',
5379 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5381 foreach ($entities as $entity => $bao) {
5382 if (!empty($ids[$entity])) {
5383 $this->_relatedObjects
[$entity] = new $bao();
5384 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5385 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5386 throw new CRM_Core_Exception($entity . ' could not be loaded');
5393 * Function to replace contribution tokens.
5395 * @param array $contributionIds
5397 * @param string $subject
5399 * @param array $subjectToken
5401 * @param string $text
5403 * @param string $html
5405 * @param array $messageToken
5407 * @param bool $escapeSmarty
5410 * @throws \CiviCRM_API3_Exception
5412 public static function replaceContributionTokens(
5421 if (empty($contributionIds)) {
5424 $contributionDetails = [];
5425 foreach ($contributionIds as $id) {
5426 $result = self
::getContributionTokenValues($id, $messageToken);
5427 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5428 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5429 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5431 return $contributionDetails;
5435 * Get the contribution fields for $id and display labels where
5436 * appropriate (if the token is present).
5439 * @param array $messageToken
5442 public static function getContributionTokenValues($id, $messageToken) {
5446 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5447 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5448 if (!empty($messageToken)) {
5449 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5450 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5451 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField
::displayValue($result['values'][$id][$fieldName], $fieldName);
5459 * Get invoice_number for contribution.
5461 * @param int $contributionID
5465 public static function getInvoiceNumber($contributionID) {
5466 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix')) {
5467 return $invoicePrefix . $contributionID;
5474 * Load the values needed for the event message.
5476 * @param int $eventID
5477 * @param int $participantID
5478 * @param int|null $contributionID
5481 * @throws \CRM_Core_Exception
5483 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5488 $values = ['event' => []];
5490 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
5491 // add custom fields for event
5492 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $eventID);
5494 $eventCustomGroup = [];
5495 foreach ($eventGroupTree as $key => $group) {
5496 if ($key === 'info') {
5500 foreach ($group['fields'] as $k => $customField) {
5501 $groupLabel = $group['title'];
5502 if (!empty($customField['customValue'])) {
5503 foreach ($customField['customValue'] as $customFieldValues) {
5504 $eventCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5509 $values['event']['customGroup'] = $eventCustomGroup;
5511 //get participant details
5512 $participantParams = [
5513 'id' => $participantID,
5516 $values['participant'] = [];
5518 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
5519 // add custom fields for event
5520 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $participantID);
5521 $participantCustomGroup = [];
5522 foreach ($participantGroupTree as $key => $group) {
5523 if ($key === 'info') {
5527 foreach ($group['fields'] as $k => $customField) {
5528 $groupLabel = $group['title'];
5529 if (!empty($customField['customValue'])) {
5530 foreach ($customField['customValue'] as $customFieldValues) {
5531 $participantCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5536 $values['participant']['customGroup'] = $participantCustomGroup;
5538 //get location details
5540 'entity_id' => $eventID,
5541 'entity_table' => 'civicrm_event',
5543 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
5546 'entity_table' => 'civicrm_event',
5547 'entity_id' => $eventID,
5548 'module' => 'CiviEvent',
5551 list($custom_pre_id,
5553 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
5555 $values['custom_pre_id'] = $custom_pre_id;
5556 $values['custom_post_id'] = $custom_post_ids;
5558 // set lineItem for event contribution
5559 if ($contributionID) {
5560 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($contributionID);
5561 if (!empty($participantIds)) {
5562 foreach ($participantIds as $pIDs) {
5563 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
5564 if (!CRM_Utils_System
::isNull($lineItem)) {
5565 $values['lineItem'][] = $lineItem;