3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
12 use Civi\Api4\Activity
;
13 use Civi\Api4\ContributionPage
;
14 use Civi\Api4\ContributionRecur
;
15 use Civi\Api4\Participant
;
16 use Civi\Api4\PaymentProcessor
;
21 * @copyright CiviCRM LLC https://civicrm.org/licensing
23 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
26 * Static field for all the contribution information that we can potentially import
30 public static $_importableFields = NULL;
33 * Static field for all the contribution information that we can potentially export
37 public static $_exportableFields = NULL;
40 * Static field to hold financial trxn id's.
44 public static $_trxnIDs = NULL;
47 * Field for all the objects related to this contribution.
50 * 1) deprecated function transitionComponents
51 * 2) function to send contribution receipts _assignMessageVariablesToTemplate
52 * 3) some invoice code that is copied from 2
53 * 4) odds & sods that need to be investigated and fixed.
55 * However, it is no longer used by completeOrder.
57 * @var \CRM_Member_BAO_Membership|\CRM_Event_BAO_Participant[]
61 public $_relatedObjects = [];
64 * Field for the component - either 'event' (participant) or 'contribute'
65 * (any item related to a contribution page e.g. membership, pledge, contribution)
66 * This is used for composing messages because they have dependency on the
67 * contribution_page or event page - although over time we may eliminate that
70 * "contribution"\"event"
72 public $_component = NULL;
75 * Possibly obsolete variable.
77 * If you use it please explain why it is set in the create function here.
81 public $trxn_result_code;
86 public function __construct() {
87 parent
::__construct();
91 * Takes an associative array and creates a contribution object.
93 * the function extract all the params it needs to initialize the create a
94 * contribution object. the params array could contain additional unused name/value
97 * @param array $params
98 * (reference ) an assoc array of name/value pairs.
100 * @return \CRM_Contribute_BAO_Contribution
101 * @throws \CRM_Core_Exception
102 * @throws \CiviCRM_API3_Exception
104 public static function add(&$params) {
105 if (empty($params)) {
109 $contributionID = $params['id'] ??
NULL;
110 $action = $contributionID ?
'edit' : 'create';
112 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
113 $message = ts("Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: %1", [1 => implode(', ', $duplicates)]);
114 throw new CRM_Core_Exception($message);
117 //set defaults in create mode
118 if (!$contributionID) {
119 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
120 if (empty($params['invoice_number']) && CRM_Invoicing_Utils
::isInvoicingEnabled()) {
121 $nextContributionID = CRM_Core_DAO
::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
122 $params['invoice_number'] = self
::getInvoiceNumber($nextContributionID);
126 $contributionStatusID = $params['contribution_status_id'] ??
NULL;
127 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $contributionStatusID) === 'Partially paid' && empty($params['is_post_payment_create'])) {
128 CRM_Core_Error
::deprecatedFunctionWarning('Setting status to partially paid other than by using Payment.create is deprecated and unreliable');
130 if (!$contributionStatusID) {
131 // Since the fee amount is expecting this (later on) ensure it is always set.
132 // It would only not be set for an update where it is unchanged.
133 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', [
134 'id' => $contributionID,
135 'return' => 'contribution_status_id',
138 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['contribution_status_id']);
141 && !empty($params['membership_id'])
142 && Civi
::settings()->get('deferred_revenue_enabled')
144 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
145 if ($memberStartDate) {
146 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
149 self
::calculateMissingAmountParams($params, $contributionID);
151 if (!empty($params['payment_instrument_id'])) {
152 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
153 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
154 $params['check_number'] = 'null';
158 $setPrevContribution = TRUE;
159 if ($contributionID && $setPrevContribution) {
160 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
162 $previousContributionStatus = ($contributionID && !empty($params['prevContribution'])) ? CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['prevContribution']->contribution_status_id
) : NULL;
164 if ($contributionID && !empty($params['revenue_recognition_date'])
165 && !($previousContributionStatus === 'Pending')
166 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
168 unset($params['revenue_recognition_date']);
171 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
172 isset($params['financial_type_id']))) {
173 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
176 CRM_Utils_Hook
::pre($action, 'Contribution', $contributionID, $params);
178 $contribution = new CRM_Contribute_BAO_Contribution();
179 $contribution->copyValues($params);
181 $contribution->id
= $contributionID;
183 if (empty($contribution->id
)) {
184 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
185 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
186 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
190 $result = $contribution->save();
192 // Add financial_trxn details as part of fix for CRM-4724
193 $contribution->trxn_result_code
= $params['trxn_result_code'] ??
NULL;
194 $contribution->payment_processor
= $params['payment_processor'] ??
NULL;
196 //add Account details
197 $params['contribution'] = $contribution;
198 if (empty($params['is_post_payment_create'])) {
199 // If this is being called from the Payment.create api/ BAO then that Entity
200 // takes responsibility for the financial transactions. In fact calling Payment.create
201 // to add payments & having it call completetransaction and / or contribution.create
202 // to update related entities is the preferred flow.
203 // Note that leveraging this parameter for any other code flow is not supported and
204 // is likely to break in future and / or cause serious problems in your data.
205 // https://github.com/civicrm/civicrm-core/pull/14673
206 self
::recordFinancialAccounts($params);
209 if (self
::isUpdateToRecurringContribution($params)) {
210 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
211 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
213 $params['receive_date'] ??
NULL
217 $params['contribution_id'] = $contribution->id
;
219 if (!empty($params['custom']) &&
220 is_array($params['custom'])
222 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
, $action);
225 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
227 CRM_Utils_Hook
::post($action, 'Contribution', $contribution->id
, $contribution);
232 * Is this contribution updating an existing recurring contribution.
234 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
235 * pending payment is being confirmed (or failing).
237 * @param array $params
241 public static function isUpdateToRecurringContribution($params) {
242 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
245 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
248 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
251 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
252 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
259 * Get defaults for new entity.
263 public static function getDefaults() {
265 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
266 FALSE, FALSE, FALSE, 'AND is_default = 1')
268 'contribution_status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
269 'receive_date' => date('Y-m-d H:i:s'),
274 * Fetch the object and store the values in the values array.
276 * @param array $params
277 * Input parameters to find object.
278 * @param array $values
279 * Output values of the object.
281 * The array that holds all the db ids.
283 * @return CRM_Contribute_BAO_Contribution|null
284 * The found object or null
286 public static function getValues($params, &$values = [], &$ids = []) {
287 if (empty($params)) {
290 $contribution = new CRM_Contribute_BAO_Contribution();
292 $contribution->copyValues($params);
294 if ($contribution->find(TRUE)) {
295 $ids['contribution'] = $contribution->id
;
297 CRM_Core_DAO
::storeValues($contribution, $values);
299 return $contribution;
301 // return by reference
307 * Get the values and resolve the most common mappings.
309 * Since contribution status is resolved in almost every function that calls getValues it makes
310 * sense to have an extra function to resolve it rather than repeat the code.
312 * Think carefully before adding more mappings to be resolved as there could be performance implications
313 * if this function starts to be called from more iterative functions.
315 * @param array $params
316 * Input parameters to find object.
319 * Array of the found contribution.
320 * @throws CRM_Core_Exception
322 public static function getValuesWithMappings($params) {
324 $contribution = self
::getValues($params, $values, $ids);
325 if (is_null($contribution)) {
326 throw new CRM_Core_Exception('No contribution found');
328 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
333 * Calculate net_amount & fee_amount if they are not set.
335 * Net amount should be total - fee.
336 * This should only be called for new contributions.
338 * @param array $params
339 * Params for a new contribution before they are saved.
340 * @param int|null $contributionID
341 * Contribution ID if we are dealing with an update.
343 * @throws \CiviCRM_API3_Exception
345 public static function calculateMissingAmountParams(&$params, $contributionID) {
346 if (!$contributionID && !isset($params['fee_amount'])) {
347 if (isset($params['total_amount']) && isset($params['net_amount'])) {
348 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
351 $params['fee_amount'] = 0;
354 if (!isset($params['net_amount'])) {
355 if (!$contributionID) {
356 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
359 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
360 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
361 // net_amount may need adjusting.
362 $contribution = civicrm_api3('Contribution', 'getsingle', [
363 'id' => $contributionID,
364 'return' => ['total_amount', 'net_amount', 'fee_amount'],
366 $totalAmount = (isset($params['total_amount']) ?
(float) $params['total_amount'] : (float) CRM_Utils_Array
::value('total_amount', $contribution));
367 $feeAmount = (isset($params['fee_amount']) ?
(float) $params['fee_amount'] : (float) CRM_Utils_Array
::value('fee_amount', $contribution));
368 $params['net_amount'] = $totalAmount - $feeAmount;
376 * @param $billingLocationTypeID
380 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
381 $hasBillingField = FALSE;
390 //build address array
392 $addressParams['location_type_id'] = $billingLocationTypeID;
393 $addressParams['is_billing'] = 1;
395 $billingFirstName = $params['billing_first_name'] ??
NULL;
396 $billingMiddleName = $params['billing_middle_name'] ??
NULL;
397 $billingLastName = $params['billing_last_name'] ??
NULL;
398 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
400 foreach ($billingFields as $value) {
401 $addressParams[$value] = $params["billing_{$value}-{$billingLocationTypeID}"] ??
NULL;
402 if (!empty($addressParams[$value])) {
403 $hasBillingField = TRUE;
406 return [$hasBillingField, $addressParams];
410 * Get address params ready to be passed to the payment processor.
412 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
413 * To create an address we need state_province_id.
415 * @param array $params
416 * @param int $billingLocationTypeID
420 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
421 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
422 foreach ($addressParams as $name => $field) {
423 if (substr($name, 0, 8) == 'billing_') {
424 $addressParams[substr($name, 9)] = $addressParams[$field];
427 return [$hasBillingField, $addressParams];
431 * Get the number of terms for this contribution for a given membership type
432 * based on querying the line item table and relevant price field values
433 * Note that any one contribution should only be able to have one line item relating to a particular membership
436 * @param int $membershipTypeID
438 * @param int $contributionID
442 public static function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
443 $numTerms = CRM_Core_DAO
::singleValueQuery("
444 SELECT membership_num_terms FROM civicrm_line_item li
445 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
446 WHERE contribution_id = %1 AND membership_type_id = %2",
447 [1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']]
449 // default of 1 is precautionary
450 return empty($numTerms) ?
1 : $numTerms;
454 * Takes an associative array and creates a contribution object.
456 * @param array $params
457 * (reference ) an assoc array of name/value pairs.
459 * @return CRM_Contribute_BAO_Contribution
461 * @throws \API_Exception
462 * @throws \CRM_Core_Exception
463 * @throws \CiviCRM_API3_Exception
465 public static function create(&$params) {
467 $transaction = new CRM_Core_Transaction();
470 $contribution = self
::add($params);
472 catch (CRM_Core_Exception
$e) {
473 $transaction->rollback();
477 $params['contribution_id'] = $contribution->id
;
478 $session = CRM_Core_Session
::singleton();
480 if (!empty($params['note'])) {
482 'entity_table' => 'civicrm_contribution',
483 'note' => $params['note'],
484 'entity_id' => $contribution->id
,
485 'contact_id' => $session->get('userID'),
487 if (!$noteParams['contact_id']) {
488 $noteParams['contact_id'] = $params['contact_id'];
490 CRM_Core_BAO_Note
::add($noteParams);
493 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
495 $transaction->commit();
497 if (empty($contribution->contact_id
)) {
498 $contribution->find(TRUE);
501 $isCompleted = ('Completed' === CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
));
502 if (!empty($params['on_behalf'])
505 $existingActivity = Activity
::get(FALSE)->setWhere([
506 ['source_record_id', '=', $contribution->id
],
507 ['activity_type_id:name', '=', 'Contribution'],
508 ])->execute()->first();
510 $campaignParams = isset($params['campaign_id']) ?
['campaign_id' => ($params['campaign_id'] ??
NULL)] : [];
511 Activity
::save(FALSE)->addRecord(array_merge([
512 'activity_type_id:name' => 'Contribution',
513 'source_record_id' => $contribution->id
,
514 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ?
: $contribution->contact_id
,
515 'target_contact_id' => CRM_Core_Session
::getLoggedInContactID() ?
[$contribution->contact_id
] : [],
516 'activity_date_time' => $contribution->receive_date
,
517 'is_test' => (bool) $contribution->is_test
,
518 'status_id:name' => $isCompleted ?
'Completed' : 'Scheduled',
519 'skipRecentView' => TRUE,
520 'subject' => CRM_Activity_BAO_Activity
::getActivitySubject($contribution),
521 'id' => $existingActivity['id'] ??
NULL,
522 ], $campaignParams))->execute();
525 // do not add to recent items for import, CRM-4399
526 if (empty($params['skipRecentView'])) {
527 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
528 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
530 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
537 $retrieveRequired = 0;
538 foreach ($titleFields as $titleField) {
539 if (!isset($contribution->$titleField)) {
540 $retrieveRequired = 1;
544 if ($retrieveRequired == 1) {
545 $contribution->find(TRUE);
547 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
548 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
551 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
552 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
553 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
557 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
558 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
559 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
563 // add the recently created Contribution
564 CRM_Utils_Recent
::add($title,
568 $contribution->contact_id
,
574 return $contribution;
578 * Get the values for pseudoconstants for name->value and reverse.
580 * @param array $defaults
581 * (reference) the default values, some of which need to be resolved.
582 * @param bool $reverse
583 * True if we want to resolve the values in the reverse direction (value -> name).
585 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
586 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
587 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
588 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'), $reverse);
589 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
593 * Convert associative array names to values and vice-versa.
595 * This function is used by both the web form layer and the api. Note that
596 * the api needs the name => value conversion, also the view layer typically
597 * requires value => name conversion
599 * @param array $defaults
600 * @param string $property
601 * @param array $lookup
602 * @param bool $reverse
606 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
607 $id = $property . '_id';
609 $src = $reverse ?
$property : $id;
610 $dst = $reverse ?
$id : $property;
612 if (!array_key_exists($src, $defaults)) {
616 $look = $reverse ?
array_flip($lookup) : $lookup;
618 if (is_array($look)) {
619 if (!array_key_exists($defaults[$src], $look)) {
623 $defaults[$dst] = $look[$defaults[$src]];
628 * Retrieve DB object based on input parameters.
630 * It also stores all the retrieved values in the default array.
632 * @param array $params
633 * (reference ) an assoc array of name/value pairs.
634 * @param array $defaults
635 * (reference ) an assoc array to hold the name / value pairs.
636 * in a hierarchical manner
638 * (reference) the array that holds all the db ids.
640 * @return CRM_Contribute_BAO_Contribution
642 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
643 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
644 return $contribution;
648 * Combine all the importable fields from the lower levels object.
650 * The ordering is important, since currently we do not have a weight
651 * scheme. Adding weight is super important and should be done in the
652 * next week or so, before this can be called complete.
654 * @param string $contactType
655 * @param bool $status
658 * array of importable Fields
660 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
661 if (!self
::$_importableFields) {
662 if (!self
::$_importableFields) {
663 self
::$_importableFields = [];
667 $fields = ['' => ['title' => ts('- do not import -')]];
670 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
673 $note = CRM_Core_DAO_Note
::import();
674 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
675 unset($tmpFields['option_value']);
676 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
677 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
679 // Using new Dedupe rule.
681 'contact_type' => $contactType,
682 'used' => 'Unsupervised',
684 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
685 $tmpContactField = [];
686 if (is_array($fieldsArray)) {
687 foreach ($fieldsArray as $value) {
688 //skip if there is no dupe rule
689 if ($value == 'none') {
692 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
697 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
698 $tmpContactField[trim($value)] = $contactFields[trim($value)];
700 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
703 $title = $tmpContactField[trim($value)]['title'];
705 $tmpContactField[trim($value)]['title'] = $title;
709 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
710 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
711 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
712 $fields = array_merge($fields, $tmpContactField);
713 $fields = array_merge($fields, $tmpFields);
714 $fields = array_merge($fields, $note);
715 $fields = array_merge($fields, $optionFields);
716 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
717 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
718 self
::$_importableFields = $fields;
720 return self
::$_importableFields;
724 * Combine all the exportable fields from the lower level objects.
726 * @param bool $checkPermission
729 * array of exportable Fields
731 public static function &exportableFields($checkPermission = TRUE) {
732 if (!self
::$_exportableFields) {
733 if (!self
::$_exportableFields) {
734 self
::$_exportableFields = [];
737 $fields = CRM_Contribute_DAO_Contribution
::export();
738 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
739 $fields = array_merge(
741 CRM_Contribute_DAO_Product
::export(),
742 CRM_Contribute_DAO_ContributionProduct
::export(),
743 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
745 'contribution_product_id' => [
746 'title' => ts('Premium'),
747 'name' => 'contribution_product_id',
748 'where' => 'civicrm_product.id',
749 'data_type' => CRM_Utils_Type
::T_INT
,
755 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
757 $contributionPage = [
758 'contribution_page' => [
759 'title' => ts('Contribution Page'),
760 'name' => 'contribution_page',
761 'where' => 'civicrm_contribution_page.title',
762 'data_type' => CRM_Utils_Type
::T_STRING
,
766 $contributionNote = [
767 'contribution_note' => [
768 'title' => ts('Contribution Note'),
769 'name' => 'contribution_note',
770 'data_type' => CRM_Utils_Type
::T_TEXT
,
775 'contribution_batch' => [
776 'title' => ts('Batch Name'),
782 'contribution_campaign_title' => [
783 'title' => ts('Campaign Title'),
784 'name' => 'campaign_title',
785 'where' => 'civicrm_campaign.title',
786 'data_type' => CRM_Utils_Type
::T_STRING
,
789 $softCreditFields = [
790 'contribution_soft_credit_name' => [
791 'name' => 'contribution_soft_credit_name',
792 'title' => ts('Soft Credit For'),
793 'where' => 'civicrm_contact_d.display_name',
794 'data_type' => CRM_Utils_Type
::T_STRING
,
796 'contribution_soft_credit_amount' => [
797 'name' => 'contribution_soft_credit_amount',
798 'title' => ts('Soft Credit Amount'),
799 'where' => 'civicrm_contribution_soft.amount',
800 'data_type' => CRM_Utils_Type
::T_MONEY
,
802 'contribution_soft_credit_type' => [
803 'name' => 'contribution_soft_credit_type',
804 'title' => ts('Soft Credit Type'),
805 'where' => 'contribution_softcredit_type.label',
806 'data_type' => CRM_Utils_Type
::T_STRING
,
808 'contribution_soft_credit_contribution_id' => [
809 'name' => 'contribution_soft_credit_contribution_id',
810 'title' => ts('Soft Credit For Contribution ID'),
811 'where' => 'civicrm_contribution_soft.contribution_id',
812 'data_type' => CRM_Utils_Type
::T_INT
,
814 'contribution_soft_credit_contact_id' => [
815 'name' => 'contribution_soft_credit_contact_id',
816 'title' => ts('Soft Credit For Contact ID'),
817 'where' => 'civicrm_contact_d.id',
818 'data_type' => CRM_Utils_Type
::T_INT
,
822 $fields = array_merge($fields, $contributionPage,
823 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
824 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
827 self
::$_exportableFields = $fields;
830 return self
::$_exportableFields;
834 * Record an activity when a payment is received.
836 * @todo this is intended to be moved to payment BAO class as a protected function
837 * on that class. Currently being cleaned up. The addActivityForPayment doesn't really
838 * merit it's own function as it makes the code less rather than more readable.
840 * @param int $contributionId
841 * @param int $participantId
842 * @param string $totalAmount
843 * @param string $currency
844 * @param string $trxnDate
846 * @throws \CRM_Core_Exception
847 * @throws \CiviCRM_API3_Exception
849 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
850 $activityType = ($totalAmount < 0) ?
'Refund' : 'Payment';
852 if ($participantId) {
853 $inputParams['id'] = $participantId;
856 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
857 $entityObj = $entityObj[$participantId];
858 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
861 $entityObj = new CRM_Contribute_BAO_Contribution();
862 $entityObj->id
= $contributionId;
863 $entityObj->find(TRUE);
864 $title = ts('Contribution');
866 // @todo per block above this is not a logical splitting off of functionality.
867 self
::addActivityForPayment($entityObj->contact_id
, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
871 * Get the value for the To Financial Account.
873 * @param $contribution
878 public static function getToFinancialAccount($contribution, $params) {
879 if (!empty($params['payment_processor_id'])) {
880 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor_id'], NULL, 'civicrm_payment_processor');
882 if (!empty($params['payment_instrument_id'])) {
883 return CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
886 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
887 $queryParams = [1 => [$relationTypeId, 'Integer']];
888 return CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
893 * Get memberships related to the contribution.
895 * @param int $contributionID
899 protected static function getRelatedMemberships($contributionID) {
900 $membershipPayments = civicrm_api3('MembershipPayment', 'get', [
901 'return' => 'membership_id',
902 'contribution_id' => (int) $contributionID,
905 foreach ($membershipPayments as $membershipPayment) {
906 $membershipIDs[] = $membershipPayment['membership_id'];
908 if (empty($membershipIDs)) {
911 // We could combine this with the MembershipPayment.get - we'd
912 // need to re-wrangle the params (here or in the calling function)
913 // as they would then me membership.contact_id, membership.is_test etc
914 return civicrm_api3('Membership', 'get', [
915 'id' => ['IN' => $membershipIDs],
916 'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'],
921 * Cancel contribution.
923 * This function should only be called from transitioncomponents - it is an interim step in refactoring.
925 * @param $memberships
926 * @param $contributionId
927 * @param $membershipStatuses
928 * @param $participant
930 * @param $pledgePayment
932 * @param $pledgePaymentIDs
933 * @param $contributionStatusId
935 protected static function cancel($memberships, $contributionId, $membershipStatuses, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId) {
936 // @fixme https://lab.civicrm.org/dev/core/issues/927 Cancelling membership etc is not desirable for all use-cases and we should be able to disable it
937 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
938 if (is_array($memberships)) {
939 foreach ($memberships as $membership) {
941 //Update Membership status if there is no other completed contribution associated with the membership.
942 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
943 foreach ($relatedContributions as $contriId) {
944 if ($contriId == $contributionId) {
947 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
948 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
952 if ($membership && $update) {
953 $newStatus = array_search('Cancelled', $membershipStatuses);
956 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
958 'subject' => "Status changed from {$allStatus[$membership->status_id]} to {$allStatus[$newStatus]}",
959 'source_contact_id' => CRM_Core_Session
::singleton()->get('userID'),
960 'target_contact_id' => $membership->contact_id
,
961 'source_record_id' => $membership->id
,
962 'activity_type_id' => 'Change Membership Status',
963 'status_id' => 'Completed',
964 'priority_id' => 'Normal',
965 'activity_date_time' => 'now',
968 $membership->status_id
= $newStatus;
969 $membership->is_override
= TRUE;
970 $membership->status_override_end_date
= 'null';
972 civicrm_api3('activity', 'create', $activityParam);
978 $updatedStatusId = array_search('Cancelled', $participantStatuses);
979 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
982 if ($pledgePayment) {
983 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
988 * Do any accounting updates required as a result of a contribution status change.
990 * Currently we have a bit of a roundabout where adding a payment results in this being called &
991 * this may attempt to add a payment. We need to resolve that....
993 * The 'right' way to add payments or refunds is through the Payment.create api. That api
994 * then updates the contribution but this process should not also record another financial trxn.
995 * Currently we have weak detection fot that scenario & where it is detected the first returned
996 * value is FALSE - meaning 'do not continue'.
998 * We should also look at the fact that the calling function - updateFinancialAccounts
999 * bunches together some disparate processes rather than having separate appropriate
1002 * @param array $params
1005 * Return indicates whether the updateFinancialAccounts function should continue.
1007 private static function updateFinancialAccountsOnContributionStatusChange(&$params) {
1008 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
1009 $currentContributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
1011 if ((($previousContributionStatus == 'Partially paid' && $currentContributionStatus == 'Completed')
1012 ||
($previousContributionStatus == 'Pending refund' && $currentContributionStatus == 'Completed')
1013 // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
1014 // why it is here or where it is handled instead.
1015 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
1016 && $currentContributionStatus == 'Partially paid'))
1021 if (self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
)) {
1022 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1023 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1025 elseif (($previousContributionStatus == 'Pending'
1026 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
1028 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
1029 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
1031 if ($currentContributionStatus == 'Cancelled') {
1032 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1033 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
1034 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1037 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1038 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
1042 if (($previousContributionStatus == 'Pending'
1043 ||
$previousContributionStatus == 'In Progress')
1044 && ($currentContributionStatus == 'Completed')
1046 if (empty($params['line_item'])) {
1048 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
1049 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
1050 // & this can be removed
1053 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1054 // This is an update so original currency if none passed in.
1055 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
1057 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
1058 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
1059 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1060 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
1062 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
1065 'entity_table' => 'civicrm_financial_item',
1067 foreach ($params['line_item'] as $fieldId => $fields) {
1068 foreach ($fields as $fieldValueId => $lineItemDetails) {
1069 self
::updateFinancialItemForLineItemToPaid($lineItemDetails['id']);
1071 1 => [$lineItemDetails['id'], 'Integer'],
1073 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
1074 while ($financialItem->fetch()) {
1075 $entityParams['entity_id'] = $financialItem->id
;
1076 $entityParams['amount'] = $financialItem->amount
;
1077 foreach (self
::$_trxnIDs as $tID) {
1078 $entityParams['financial_trxn_id'] = $tID;
1079 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
1090 * It is possible to override the membership id that is updated from the payment processor.
1092 * Historically Paypal does this & it still does if it determines data is messed up - see
1093 * https://lab.civicrm.org/dev/membership/issues/13
1095 * Read the comment block on repeattransaction for more information
1096 * about how things should work.
1098 * @param int $contributionID
1099 * @param array $input
1101 * @throws \CiviCRM_API3_Exception
1103 protected static function handleMembershipIDOverride($contributionID, $input) {
1104 if (!empty($input['membership_id'])) {
1105 Civi
::log()->debug('The related membership id has been overridden - this may impact data - see https://github.com/civicrm/civicrm-core/pull/15053');
1106 civicrm_api3('MembershipPayment', 'create', ['contribution_id' => $contributionID, 'membership_id' => $input['membership_id']]);
1111 * Update all financial items related to the line item tto have a status of paid.
1113 * @param int $lineItemID
1115 private static function updateFinancialItemForLineItemToPaid($lineItemID) {
1118 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1121 2 => [$lineItemID, 'Integer'],
1123 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
1124 CRM_Core_DAO
::executeQuery($query, $fparams);
1128 * Create the financial items for the line.
1130 * @param array $params
1131 * @param string $context
1132 * @param array $fields
1133 * @param array $previousLineItems
1134 * @param array $inputParams
1135 * @param bool $isARefund
1136 * @param array $trxnIds
1137 * @param int $fieldId
1141 private static function createFinancialItemsForLine($params, $context, $fields, array $previousLineItems, array $inputParams, bool $isARefund, $trxnIds, $fieldId): array {
1142 foreach ($fields as $fieldValueId => $lineItemDetails) {
1143 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($lineItemDetails['id']);
1144 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
1145 if ($params['contribution']->receive_date
) {
1146 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
1149 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array
::value('financial_account_id', $prevFinancialItem));
1151 $currency = $params['prevContribution']->currency
;
1152 if ($params['contribution']->currency
) {
1153 $currency = $params['contribution']->currency
;
1155 $previousLineItemTotal = CRM_Utils_Array
::value('line_total', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1157 'transaction_date' => $receiveDate,
1158 'contact_id' => $params['prevContribution']->contact_id
,
1159 'currency' => $currency,
1160 'amount' => self
::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
1161 'description' => $prevFinancialItem['description'] ??
NULL,
1162 'status_id' => $prevFinancialItem['status_id'],
1163 'financial_account_id' => $financialAccount,
1164 'entity_table' => 'civicrm_line_item',
1165 'entity_id' => $lineItemDetails['id'],
1167 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1168 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
1169 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
1171 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') ||
($context == 'changeFinancialType')) {
1172 $taxAmount = (float) $lineItemDetails['tax_amount'];
1173 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
1174 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
1175 $taxAmount = CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1177 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
1178 $taxAmount -= CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1180 if ($taxAmount != 0) {
1181 $itemParams['amount'] = self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * $taxAmount;
1182 $itemParams['description'] = CRM_Invoicing_Utils
::getTaxTerm();
1183 if ($lineItemDetails['financial_type_id']) {
1184 $itemParams['financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getSalesTaxFinancialAccount($lineItemDetails['financial_type_id']);
1186 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1194 * Does this contributtion status update represent a refund.
1196 * @param int $previousContributionStatusID
1197 * @param int $currentContributionStatusID
1201 private static function isContributionUpdateARefund($previousContributionStatusID, $currentContributionStatusID): bool {
1202 if ('Completed' !== CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $previousContributionStatusID)) {
1205 return self
::isContributionStatusNegative($currentContributionStatusID);
1209 * Get transaction information about the contribution.
1211 * @param int $contributionId
1212 * @param int $financialTypeID
1216 protected static function getContributionTransactionInformation($contributionId, int $financialTypeID) {
1218 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Expense Account is');
1220 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
1222 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
1224 ft.payment_instrument_id,
1225 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
1227 FROM civicrm_contribution con
1228 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
1229 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
1230 AND ft.to_financial_account_id != %2
1231 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
1232 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
1233 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
1235 WHERE con.id = %1 AND ft.is_payment = 1
1238 1 => [$contributionId, 'Integer'],
1239 2 => [$feeFinancialAccount, 'Integer'],
1241 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
1242 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label');
1244 while ($resultDAO->fetch()) {
1245 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1246 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1247 if ($resultDAO->card_type_id
) {
1248 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
1249 $pantruncation = '';
1250 if ($resultDAO->pan_truncation
) {
1251 $pantruncation = ": {$resultDAO->pan_truncation}";
1253 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
1256 // show payment edit link only for payments done via backoffice form
1257 $paymentEditLink = '';
1258 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
1260 CRM_Core_Action
::UPDATE
=> [
1261 'name' => ts('Edit Payment'),
1262 'icon' => 'fa-pencil',
1263 'url' => 'civicrm/payment/edit',
1264 'class' => 'medium-popup',
1265 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
1266 'title' => ts('Edit Payment'),
1269 $paymentEditLink = CRM_Core_Action
::formLink(
1271 CRM_Core_Action
::mask([CRM_Core_Permission
::EDIT
]),
1273 'id' => $resultDAO->id
,
1274 'contribution_id' => $contributionId,
1278 'Payment.edit.action',
1286 'id' => $resultDAO->id
,
1287 'total_amount' => $resultDAO->total_amount
,
1288 'financial_type' => $resultDAO->financial_account
,
1289 'payment_instrument' => $paidByLabel,
1290 'receive_date' => $resultDAO->trxn_date
,
1291 'trxn_id' => $resultDAO->trxn_id
,
1292 'status' => $statuses[$resultDAO->status_id
],
1293 'currency' => $resultDAO->currency
,
1294 'action' => $paymentEditLink,
1296 if ($paidByName == 'Check') {
1297 $val['check_number'] = $resultDAO->check_number
;
1305 * Should an email receipt be sent for this contribution on completion.
1307 * @param array $input
1308 * @param int $contributionPageID
1309 * @param int $recurringContributionID
1312 * @throws \API_Exception
1313 * @throws \Civi\API\Exception\UnauthorizedException
1315 protected static function isEmailReceipt(array $input, $contributionPageID, $recurringContributionID): bool {
1316 if (isset($input['is_email_receipt'])) {
1317 return (bool) $input['is_email_receipt'];
1319 if ($recurringContributionID) {
1320 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
1321 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
1322 // 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
1323 // Instance that had the table added via an upgrade in 4.1
1324 // see also https://github.com/civicrm/civicrm-svn/commit/7f39befd60bc735408d7866b02b3ac7fff1d4eea#diff-9ad8e290180451a2d6eacbd3d1ca7966R354
1325 // https://lab.civicrm.org/dev/core/issues/1245
1326 return (bool) ContributionRecur
::get(FALSE)->addWhere('id', '=', $recurringContributionID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt'];
1328 if ($contributionPageID) {
1329 return (bool) ContributionPage
::get(FALSE)->addWhere('id', '=', $contributionPageID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt'];
1331 // This would be the case for backoffice (where is_email_receipt is not passed in) or events, where Event::sendMail will filter
1337 * Process failed contribution.
1339 * @param $memberships
1340 * @param $contributionId
1341 * @param array $membershipStatuses
1342 * @param $participant
1343 * @param $pledgePayment
1345 * @param array $pledgePaymentIDs
1346 * @param $contributionStatusId
1348 * @throws \CRM_Core_Exception
1350 protected static function processFail($memberships, $contributionId, array $membershipStatuses, array $participant, $pledgePayment, $pledgeID, array $pledgePaymentIDs, $contributionStatusId): void
{
1351 if (is_array($memberships)) {
1352 foreach ($memberships as $membership) {
1354 //Update Membership status if there is no other completed contribution associated with the membership.
1355 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1356 foreach ($relatedContributions as $contriId) {
1357 if ($contriId == $contributionId) {
1360 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1361 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1365 if ($membership && $update) {
1366 $membership->status_id
= array_search('Expired', $membershipStatuses);
1367 $membership->is_override
= TRUE;
1368 $membership->status_override_end_date
= 'null';
1369 $membership->save();
1374 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1378 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1379 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1380 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1383 if ($pledgePayment) {
1384 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1391 public function addSelectWhereClause() {
1392 $whereClauses = parent
::addSelectWhereClause();
1393 if ($whereClauses !== []) {
1394 // In this case permisssions have been applied & we assume the
1395 // financialaclreport is applying these
1396 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
1397 return $whereClauses;
1400 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1401 return $whereClauses;
1403 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
1404 if (empty($types)) {
1405 $whereClauses['financial_type_id'] = 'IN (0)';
1408 $whereClauses['financial_type_id'] = [
1409 'IN (' . implode(',', array_keys($types)) . ')',
1412 return $whereClauses;
1416 * @param null $status
1417 * @param null $startDate
1418 * @param null $endDate
1420 * @return array|null
1422 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1426 $where[] = 'contribution_status_id = 1';
1430 $where[] = 'contribution_status_id = 3';
1435 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
1438 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
1440 $financialTypeACLJoin = '';
1441 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1442 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1443 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
1444 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1445 if ($financialTypes) {
1446 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1447 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1450 $where[] = "c.financial_type_id IN (0)";
1454 $whereCond = implode(' AND ', $where);
1457 SELECT sum( total_amount ) as total_amount,
1458 count( c.id ) as total_count,
1460 FROM civicrm_contribution c
1461 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1462 $financialTypeACLJoin
1464 AND ( is_test = 0 OR is_test IS NULL )
1465 AND contact.is_deleted = 0
1469 $dao = CRM_Core_DAO
::executeQuery($query);
1472 while ($dao->fetch()) {
1473 $count +
= $dao->total_count
;
1474 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
1478 'amount' => implode(', ', $amount),
1486 * Delete the indirect records associated with this contribution first.
1490 * @return mixed|null
1491 * $results no of deleted Contribution on success, false otherwise
1493 public static function deleteContribution($id) {
1494 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
1496 $transaction = new CRM_Core_Transaction();
1499 //delete activity record
1501 'source_record_id' => $id,
1502 // activity type id for contribution
1503 'activity_type_id' => 6,
1506 CRM_Activity_BAO_Activity
::deleteActivity($params);
1508 //delete billing address if exists for this contribution.
1509 self
::deleteAddress($id);
1511 //update pledge and pledge payment, CRM-3961
1512 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1514 // remove entry from civicrm_price_set_entity, CRM-5095
1515 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1516 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1518 // cleanup line items.
1519 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1521 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1522 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1524 if ($participantId) {
1525 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1528 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1532 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1533 $noteId = key($note);
1535 CRM_Core_BAO_Note
::del($noteId, FALSE);
1538 $dao = new CRM_Contribute_DAO_Contribution();
1541 $results = $dao->delete();
1543 $transaction->commit();
1545 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1547 // delete the recently created Contribution
1548 $contributionRecent = [
1550 'type' => 'Contribution',
1552 CRM_Utils_Recent
::del($contributionRecent);
1558 * React to a financial transaction (payment) failure.
1560 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1561 * payments is important for forensic and outreach reasons.
1563 * @param int $contributionID
1564 * @param int $contactID
1565 * @param string $message
1567 * @throws \CiviCRM_API3_Exception
1569 public static function failPayment($contributionID, $contactID, $message) {
1570 civicrm_api3('activity', 'create', [
1571 'activity_type_id' => 'Failed Payment',
1572 'details' => $message,
1573 'subject' => ts('Payment failed at payment processor'),
1574 'source_record_id' => $contributionID,
1575 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() : $contactID,
1578 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1579 civicrm_api3('contribution', 'create', [
1580 'id' => $contributionID,
1581 'contribution_status_id' => 'Failed',
1586 * Check if there is a contribution with the same trxn_id or invoice_id.
1588 * @param array $input
1589 * An assoc array of name/value pairs.
1590 * @param array $duplicates
1591 * (reference) store ids of duplicate contribs.
1595 * true if duplicate, false otherwise
1597 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1599 $id = $input['id'] ??
NULL;
1601 $trxn_id = $input['trxn_id'] ??
NULL;
1602 $invoice_id = $input['invoice_id'] ??
NULL;
1608 $clause[] = "trxn_id = %1";
1609 $input[1] = [$trxn_id, 'String'];
1613 $clause[] = "invoice_id = %2";
1614 $input[2] = [$invoice_id, 'String'];
1617 if (empty($clause)) {
1621 $clause = implode(' OR ', $clause);
1623 $clause = "( $clause ) AND id != %3";
1624 $input[3] = [$id, 'Integer'];
1627 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1628 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1630 while ($dao->fetch()) {
1631 $duplicates[] = $dao->id
;
1638 * Takes an associative array and creates a contribution_product object.
1640 * the function extract all the params it needs to initialize the create a
1641 * contribution_product object. the params array could contain additional unused name/value
1644 * @param array $params
1645 * (reference) an assoc array of name/value pairs.
1647 * @return CRM_Contribute_DAO_ContributionProduct
1649 public static function addPremium(&$params) {
1650 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1651 $contributionProduct->copyValues($params);
1652 return $contributionProduct->save();
1656 * Get list of contribution fields for profile.
1657 * For now we only allow custom contribution fields to be in
1660 * @param bool $addExtraFields
1661 * True if special fields needs to be added.
1664 * the list of contribution fields
1666 public static function getContributionFields($addExtraFields = TRUE) {
1667 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1668 // @todo remove this - this line was added because payment_instrument_id was not
1669 // set to exportable - but now it is.
1670 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1672 if ($addExtraFields) {
1673 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1676 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1678 foreach ($contributionFields as $key => $var) {
1679 if ($key == 'contribution_contact_id') {
1682 elseif ($key == 'contribution_campaign_id') {
1683 $var['title'] = ts('Campaign');
1685 $fields[$key] = $var;
1688 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1693 * Add extra fields specific to contribution.
1695 public static function getSpecialContributionFields() {
1697 'contribution_soft_credit_name' => [
1698 'name' => 'contribution_soft_credit_name',
1699 'title' => ts('Soft Credit Name'),
1700 'headerPattern' => '/^soft_credit_name$/i',
1701 'where' => 'civicrm_contact_d.display_name',
1703 'contribution_soft_credit_email' => [
1704 'name' => 'contribution_soft_credit_email',
1705 'title' => ts('Soft Credit Email'),
1706 'headerPattern' => '/^soft_credit_email$/i',
1707 'where' => 'soft_email.email',
1709 'contribution_soft_credit_phone' => [
1710 'name' => 'contribution_soft_credit_phone',
1711 'title' => ts('Soft Credit Phone'),
1712 'headerPattern' => '/^soft_credit_phone$/i',
1713 'where' => 'soft_phone.phone',
1715 'contribution_soft_credit_contact_id' => [
1716 'name' => 'contribution_soft_credit_contact_id',
1717 'title' => ts('Soft Credit Contact ID'),
1718 'headerPattern' => '/^soft_credit_contact_id$/i',
1719 'where' => 'civicrm_contribution_soft.contact_id',
1721 'contribution_pcp_title' => [
1722 'name' => 'contribution_pcp_title',
1723 'title' => ts('Personal Campaign Page Title'),
1724 'headerPattern' => '/^contribution_pcp_title$/i',
1725 'where' => 'contribution_pcp.title',
1729 return $extraFields;
1733 * @param int $pageID
1737 public static function getCurrentandGoalAmount($pageID) {
1739 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1740 FROM civicrm_contribution_page p,
1741 civicrm_contribution c
1742 WHERE p.id = c.contribution_page_id
1744 AND c.cancel_date is null
1748 $config = CRM_Core_Config
::singleton();
1749 $params = [1 => [$pageID, 'Integer']];
1750 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1752 if ($dao->fetch()) {
1753 return [$dao->goal
, $dao->total
];
1756 return [NULL, NULL];
1761 * Get list of contributions which credit the passed in contact ID.
1763 * The returned array provides details about the original contribution & donor.
1765 * @param int $honorId
1766 * In Honor of Contact ID.
1769 * list of contribution fields
1770 * @todo - this is a confusing function called from one place. It has a test. It would be
1771 * nice to deprecate it.
1774 public static function getHonorContacts($honorId) {
1776 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1777 $honorDAO->contact_id
= $honorId;
1780 $type = CRM_Contribute_PseudoConstant
::financialType();
1782 while ($honorDAO->fetch()) {
1783 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1784 $contributionDAO->id
= $honorDAO->contribution_id
;
1786 if ($contributionDAO->find(TRUE)) {
1787 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1788 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1789 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1790 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1791 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1792 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1793 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1794 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1795 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
, 'label');
1803 * Get the sort name of a contact for a particular contribution.
1806 * Id of the contribution.
1808 * @return null|string
1809 * sort name of the contact if found
1811 public static function sortName($id) {
1812 $id = CRM_Utils_Type
::escape($id, 'Integer');
1815 SELECT civicrm_contact.sort_name
1816 FROM civicrm_contribution, civicrm_contact
1817 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1818 AND civicrm_contribution.id = {$id}
1820 return CRM_Core_DAO
::singleValueQuery($query);
1824 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1826 * @param int|array $contactIDs
1830 public static function annual($contactIDs) {
1831 if (!is_array($contactIDs)) {
1832 // In practice I can't fine any evidence that this function is ever called with
1833 // anything other than a single contact id, but left like this due to .... fear.
1834 $contactIDs = explode(',', $contactIDs);
1837 $query = self
::getAnnualQuery($contactIDs);
1838 $dao = CRM_Core_DAO
::executeQuery($query);
1840 $amount = $average = [];
1841 while ($dao->fetch()) {
1842 if ($dao->count
> 0 && $dao->amount
> 0) {
1843 $count +
= $dao->count
;
1844 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1845 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1851 implode(', ', $amount),
1852 implode(', ', $average),
1859 * Check if there is a contribution with the params passed in.
1861 * Used for trxn_id,invoice_id and contribution_id
1863 * @param array $params
1864 * An assoc array of name/value pairs.
1867 * contribution id if success else NULL
1869 public static function checkDuplicateIds($params) {
1870 $dao = new CRM_Contribute_DAO_Contribution();
1874 foreach ($params as $k => $v) {
1876 $clause[] = "$k = '$v'";
1879 $clause = implode(' AND ', $clause);
1880 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1881 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1883 while ($dao->fetch()) {
1891 * Get the contribution details for component export.
1893 * @param int $exportMode
1895 * @param array $componentIds
1901 public static function getContributionDetails($exportMode, $componentIds) {
1902 $paymentDetails = [];
1903 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1905 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1906 $componentSelect = " civicrm_participant_payment.participant_id id";
1907 $additionalClause = "
1908 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1909 AND civicrm_participant_payment.participant_id {$componentClause} )
1912 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1913 $componentSelect = " civicrm_membership_payment.membership_id id";
1914 $additionalClause = "
1915 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1916 AND civicrm_membership_payment.membership_id {$componentClause} )
1919 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1920 $componentSelect = " civicrm_pledge_payment.id id";
1921 $additionalClause = "
1922 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1923 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1927 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1928 trxn_id, {$componentSelect}
1929 FROM civicrm_contribution
1930 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1931 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1932 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1933 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1934 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1935 AND option_group_contribution_status.id = contribution_status.option_group_id )
1939 $dao = CRM_Core_DAO
::executeQuery($query);
1941 while ($dao->fetch()) {
1942 $paymentDetails[$dao->id
] = [
1943 'total_amount' => $dao->total_amount
,
1944 'contribution_status' => $dao->status
,
1945 'receive_date' => $dao->receive_date
,
1946 'pay_instru' => $dao->payment_instrument
,
1947 'trxn_id' => $dao->trxn_id
,
1951 return $paymentDetails;
1955 * Create address associated with contribution record.
1957 * As long as there is one or more billing field in the parameters we will create the address.
1959 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1962 * @param array $params
1963 * @param int $billingLocationTypeID
1968 public static function createAddress($params, $billingLocationTypeID) {
1969 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1970 if ($hasBillingField) {
1971 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1972 return $address->id
;
1979 * Delete billing address record related contribution.
1981 * @param int $contributionId
1982 * @param int $contactId
1984 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1986 $contactJoin = NULL;
1988 if ($contributionId) {
1989 $clauses[] = "cc.id = {$contributionId}";
1993 $clauses[] = "cco.id = {$contactId}";
1994 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1997 if (empty($clauses)) {
1998 throw new CRM_Core_Exception('No Where clauses defined when deleting address');
2001 $condition = implode(' OR ', $clauses);
2005 FROM civicrm_address ca
2006 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
2010 $dao = CRM_Core_DAO
::executeQuery($query);
2012 while ($dao->fetch()) {
2013 $params = ['id' => $dao->id
];
2014 CRM_Core_BAO_Block
::blockDelete('Address', $params);
2019 * This function check online pending contribution associated w/
2020 * Online Event Registration or Online Membership signup.
2022 * @param int $componentId
2023 * Participant/membership id.
2024 * @param string $componentName
2028 * pending contribution id.
2030 public static function checkOnlinePendingContribution($componentId, $componentName) {
2031 $contributionId = NULL;
2032 if (!$componentId ||
2033 !in_array($componentName, ['Event', 'Membership'])
2035 return $contributionId;
2038 if ($componentName == 'Event') {
2039 $idName = 'participant_id';
2040 $componentTable = 'civicrm_participant';
2041 $paymentTable = 'civicrm_participant_payment';
2042 $source = ts('Online Event Registration');
2045 if ($componentName == 'Membership') {
2046 $idName = 'membership_id';
2047 $componentTable = 'civicrm_membership';
2048 $paymentTable = 'civicrm_membership_payment';
2049 $source = ts('Online Contribution');
2052 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
2055 SELECT component.id as {$idName},
2056 componentPayment.contribution_id as contribution_id,
2057 contribution.source source,
2058 contribution.contribution_status_id as contribution_status_id,
2059 contribution.is_pay_later as is_pay_later
2060 FROM $componentTable component
2061 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
2062 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
2063 WHERE component.id = {$componentId}";
2065 $dao = CRM_Core_DAO
::executeQuery($query);
2067 while ($dao->fetch()) {
2068 if ($dao->contribution_id
&&
2069 $dao->is_pay_later
&&
2070 $dao->contribution_status_id
== $pendingStatusId &&
2071 strpos($dao->source
, $source) !== FALSE
2073 $contributionId = $dao->contribution_id
;
2077 return $contributionId;
2081 * Update contribution as well as related objects.
2083 * This function by-passes hooks - to address this - don't use this function.
2085 * @param array $params
2087 * @throws CRM_Core_Exception
2088 * @throws \CiviCRM_API3_Exception
2091 * Use api contribute.completetransaction
2092 * For failures use failPayment (preferably exposing by api in the process).
2095 public static function transitionComponents($params) {
2096 // get minimum required values.
2097 $contactId = $params['contact_id'] ??
NULL;
2098 $componentId = $params['component_id'] ??
NULL;
2099 $componentName = $params['componentName'] ??
NULL;
2100 $contributionId = $params['contribution_id'] ??
NULL;
2101 $contributionStatusId = $params['contribution_status_id'] ??
NULL;
2103 // if we already processed contribution object pass previous status id.
2104 $previousContriStatusId = $params['previous_contribution_status_id'] ??
NULL;
2106 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2108 // we process only ( Completed, Cancelled, or Failed ) contributions.
2109 if (!$contributionId ||
2110 !in_array($contributionStatusId, [
2111 array_search('Completed', $contributionStatuses),
2112 array_search('Cancelled', $contributionStatuses),
2113 array_search('Failed', $contributionStatuses),
2119 if (!$componentName ||
!$componentId) {
2120 // get the related component details.
2121 $componentDetails = self
::getComponentDetails($contributionId);
2124 $componentDetails['contact_id'] = $contactId;
2125 $componentDetails['component'] = $componentName;
2127 if ($componentName == 'event') {
2128 $componentDetails['participant'] = $componentId;
2131 $componentDetails['membership'] = $componentId;
2135 if (!empty($componentDetails['contact_id'])) {
2136 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2142 // do check for required ids.
2143 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
2149 $input['component'] = $componentDetails['component'] ??
NULL;
2150 $ids['contribution'] = $contributionId;
2151 $ids['contact'] = $componentDetails['contact_id'] ??
NULL;
2152 $ids['membership'] = $componentDetails['membership'] ??
NULL;
2153 $ids['participant'] = $componentDetails['participant'] ??
NULL;
2154 $ids['event'] = $componentDetails['event'] ??
NULL;
2155 $ids['pledge_payment'] = $componentDetails['pledge_payment'] ??
NULL;
2156 $ids['contributionRecur'] = NULL;
2157 $ids['contributionPage'] = NULL;
2159 $contribution = new CRM_Contribute_BAO_Contribution();
2160 $contribution->id
= $ids['contribution'];
2161 $contribution->find();
2163 $contribution->loadRelatedObjects($input, $ids);
2165 $memberships = $contribution->_relatedObjects
['membership'] ??
[];
2166 $participant = $contribution->_relatedObjects
['participant'] ??
[];
2167 $pledgePayment = $contribution->_relatedObjects
['pledge_payment'] ??
[];
2169 $pledgeID = $oldStatus = NULL;
2170 $pledgePaymentIDs = [];
2171 if ($pledgePayment) {
2172 foreach ($pledgePayment as $key => $object) {
2173 $pledgePaymentIDs[] = $object->id
;
2175 $pledgeID = $pledgePayment[0]->pledge_id
;
2178 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
2181 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
2182 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
2187 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
2188 // Call interim cancel function - with a goal to cleaning up the signature on it and switching to a tested api Contribution.cancel function.
2189 self
::cancel($memberships, $contributionId, $membershipStatuses, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
2191 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
2192 self
::processFail($memberships, $contributionId, $membershipStatuses, $participant, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
2194 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
2196 // only pending contribution related object processed.
2197 if ($previousContriStatusId &&
2198 !in_array($contributionStatuses[$previousContriStatusId], [
2203 // this is case when we already processed contribution object.
2206 elseif (!$previousContriStatusId &&
2207 !in_array($contributionStatuses[$contribution->contribution_status_id
], [
2212 // this is case when we are going to process contribution object later.
2216 if (is_array($memberships)) {
2217 foreach ($memberships as $membership) {
2222 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
2223 $membership->membership_type_id
,
2224 $membership->is_test
, $membership->id
2227 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2228 // this picks up membership type changes during renewals
2230 SELECT membership_type_id
2231 FROM civicrm_membership_log
2232 WHERE membership_id=$membership->id
2235 $dao = CRM_Core_DAO
::executeQuery($sql);
2236 if ($dao->fetch()) {
2237 if (!empty($dao->membership_type_id
)) {
2238 $membership->membership_type_id
= $dao->membership_type_id
;
2239 $membership->save();
2242 // else fall back to using current membership type
2243 // Figure out number of terms
2245 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
2246 foreach ($lineitems as $lineitem) {
2247 if ($membership->membership_type_id
== ($lineitem['membership_type_id'] ??
NULL)) {
2248 $numterms = $lineitem['membership_num_terms'] ??
NULL;
2250 // in case membership_num_terms comes through as null or zero
2251 $numterms = $numterms >= 1 ?
$numterms : 1;
2256 // CRM-15735-to update the membership status as per the contribution receive date
2258 $oldStatus = $membership->status_id
;
2259 if (!empty($params['receive_date'])) {
2260 $joinDate = $params['receive_date'];
2261 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
2262 $membership->end_date
,
2263 $membership->join_date
,
2264 $params['receive_date'],
2266 $membership->membership_type_id
,
2269 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
2270 $membership->save();
2273 if ($currentMembership) {
2274 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2275 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
2276 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2279 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
2282 //get the status for membership.
2283 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
2285 $dates['join_date'],
2288 $membership->membership_type_id
,
2292 $formattedParams = [
2293 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
2294 array_search('Current', $membershipStatuses)
2296 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
2297 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
2298 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
2301 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
2303 $membership->copyValues($formattedParams);
2304 $membership->save();
2306 //updating the membership log
2307 $membershipLog = [];
2308 $membershipLog = $formattedParams;
2309 $logStartDate = CRM_Utils_Date
::customFormat($dates['log_start_date'] ??
NULL, $format);
2310 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
2312 $membershipLog['start_date'] = $logStartDate;
2313 $membershipLog['membership_id'] = $membership->id
;
2314 $membershipLog['modified_id'] = $membership->contact_id
;
2315 $membershipLog['modified_date'] = date('Ymd');
2316 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
2318 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2320 //update related Memberships.
2321 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2323 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2324 $scheduledActivityID = CRM_Utils_Array
::value('id',
2325 civicrm_api3('Activity', 'Get',
2327 'source_record_id' => $membership->id
,
2328 'activity_type_id' => $activityType,
2329 'status_id' => 'Scheduled',
2332 'sort' => 'id DESC',
2337 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2338 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2339 if ($scheduledActivityID) {
2340 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, ['id' => $scheduledActivityID]);
2345 // track membership status change if any
2346 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
2347 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2348 CRM_Activity_BAO_Activity
::addActivity($membership,
2349 'Change Membership Status',
2352 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2353 'source_contact_id' => $membershipLog['modified_id'],
2354 'priority_id' => 'Normal',
2359 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2365 $updatedStatusId = array_search('Registered', $participantStatuses);
2366 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2369 if ($pledgePayment) {
2370 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2377 * Returns all contribution related object ids.
2379 * @param $contributionId
2383 public static function getComponentDetails($contributionId) {
2384 $componentDetails = $pledgePayment = [];
2385 if (!$contributionId) {
2386 return $componentDetails;
2390 SELECT c.id as contribution_id,
2391 c.contact_id as contact_id,
2392 c.contribution_recur_id,
2393 mp.membership_id as membership_id,
2394 m.membership_type_id as membership_type_id,
2395 pp.participant_id as participant_id,
2396 p.event_id as event_id,
2397 pgp.id as pledge_payment_id
2398 FROM civicrm_contribution c
2399 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2400 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2401 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2402 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2403 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2404 WHERE c.id = $contributionId";
2406 $dao = CRM_Core_DAO
::executeQuery($query);
2407 $componentDetails = [];
2409 while ($dao->fetch()) {
2410 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2411 $componentDetails['contact_id'] = $dao->contact_id
;
2412 if ($dao->event_id
) {
2413 $componentDetails['event'] = $dao->event_id
;
2415 if ($dao->participant_id
) {
2416 $componentDetails['participant'] = $dao->participant_id
;
2418 if ($dao->membership_id
) {
2419 if (!isset($componentDetails['membership'])) {
2420 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2422 $componentDetails['membership'][] = $dao->membership_id
;
2423 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2425 if ($dao->pledge_payment_id
) {
2426 $pledgePayment[] = $dao->pledge_payment_id
;
2428 if ($dao->contribution_recur_id
) {
2429 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2433 if ($pledgePayment) {
2434 $componentDetails['pledge_payment'] = $pledgePayment;
2437 return $componentDetails;
2441 * @param int $contactId
2442 * @param bool $includeSoftCredit
2444 * @return null|string
2446 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2450 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2451 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2452 $liWhere = " AND i.financial_type_id IN (0)";
2453 if (!empty($financialTypes)) {
2454 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2455 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2457 $contactContributionsSQL = "
2458 SELECT contribution.id AS id
2459 FROM civicrm_contribution contribution
2460 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2461 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2465 $contactSoftCreditContributionsSQL = "
2466 SELECT contribution.id
2467 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2468 ON ( contribution.id = softContribution.contribution_id )
2469 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2470 $query = "SELECT count( x.id ) count FROM ( ";
2471 $query .= $contactContributionsSQL;
2473 if ($includeSoftCredit) {
2474 $query .= " UNION ";
2475 $query .= $contactSoftCreditContributionsSQL;
2480 return CRM_Core_DAO
::singleValueQuery($query);
2484 * Repeat a transaction as part of a recurring series.
2487 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2488 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2489 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2490 * and associated entities.
2491 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2492 * which updates the various entities and sends appropriate emails.
2494 * Gaps in the above (@todo)
2495 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2496 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2497 * 3) Repeat transaction duplicates rather than calls Order.create
2498 * 4) Use of payment.create still limited - completetransaction is more common.
2499 * 5) the template transaction is tricky - historically we used the first contribution
2500 * linked to a recurring contribution. More recently that was changed to be the most recent.
2501 * Ideally it would be an actual template - not a contribution used as a template which
2502 * would give more appropriate flexibility. Note line_items have an entity so that table
2503 * could be used for the line item template - the difficulty is the custom fields...
2504 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2505 * to load the membership(s) referred to via line items in the template transactions. Any other
2506 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2507 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2508 * - membership_payment record
2509 * - civicrm_membership.contribution_recur_id
2511 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2512 * of historical processors since this has been handled 'forever' - specifically for paypal.
2513 * albeit by an even nastier mechanism than the current input override.
2514 * The count is out on how correct related entities wind up in this case.
2516 * @param CRM_Contribute_BAO_Contribution $contribution
2517 * @param array $input
2518 * @param array $contributionParams
2520 * @return bool|array
2521 * @throws CiviCRM_API3_Exception
2523 protected static function repeatTransaction(&$contribution, $input, $contributionParams) {
2524 if (!empty($contribution->id
)) {
2527 if (empty($contribution->id
)) {
2528 // Unclear why this would only be set for repeats.
2529 if (!empty($input['amount'])) {
2530 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2533 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2534 'id' => $contributionParams['contribution_recur_id'],
2536 if (!empty($recurringContribution['financial_type_id'])) {
2537 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2538 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2540 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2541 $contributionParams['contribution_recur_id'],
2542 array_intersect_key($contributionParams, [
2543 'total_amount' => TRUE,
2544 'financial_type_id' => TRUE,
2547 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2548 $contributionParams['status_id'] = 'Pending';
2550 if (isset($contributionParams['financial_type_id']) && count($input['line_item']) === 1) {
2551 // We permit the financial type to be overridden for single line items.
2552 // More comments on this are in getTemplateTransaction.
2553 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2556 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2558 foreach (['contact_id', 'currency', 'source', 'amount_level', 'address_id'] as $fieldName) {
2559 if (isset($templateContribution[$fieldName])) {
2560 $contributionParams[$fieldName] = $templateContribution[$fieldName];
2563 if (!empty($recurringContribution['campaign_id'])) {
2564 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2565 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2567 if (!isset($contributionParams['campaign_id']) && isset($templateContribution['campaign_id'])) {
2568 // Fall back on value from the previous contribution if not passed in as input
2569 // or loadable from the recurring contribution.
2570 $contributionParams['campaign_id'] = $templateContribution['campaign_id'];
2572 $contributionParams['source'] = $contributionParams['source'] ?
: ts('Recurring contribution');
2574 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2575 //do not create CC or BCC emails or profile notifications.
2576 //The if is just to be safe. Not sure if we can ever arrive with this unset
2577 // but per CRM-19478 it seems it can be 'null'
2578 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2579 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2581 if (!empty($contribution->tax_amount
)) {
2582 $contributionParams['tax_amount'] = $contribution->tax_amount
;
2585 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2586 $contribution->id
= $createContribution['id'];
2587 $contribution->copyCustomFields($templateContribution['id'], $contribution->id
);
2588 self
::handleMembershipIDOverride($contribution->id
, $input);
2589 // Add new soft credit against current $contribution.
2590 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($contributionParams['contribution_recur_id'], $createContribution['id']);
2591 return $createContribution;
2596 * Get individual id for onbehalf contribution.
2598 * @param int $contributionId
2600 * @param int $contributorId
2604 * containing organization id and individual id
2606 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2610 if (!$contributionId) {
2614 // fetch contributor id if null
2615 if (!$contributorId) {
2616 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2617 $contributionId, 'contact_id'
2621 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2622 $activityTypeId = array_search('Contribution', $activityTypeIds);
2624 if ($activityTypeId && $contributorId) {
2626 SELECT civicrm_activity_contact.contact_id
2627 FROM civicrm_activity_contact
2628 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2629 WHERE civicrm_activity.activity_type_id = %1
2630 AND civicrm_activity.source_record_id = %2
2631 AND civicrm_activity_contact.record_type_id = %3
2634 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2635 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2638 1 => [$activityTypeId, 'Integer'],
2639 2 => [$contributionId, 'Integer'],
2640 3 => [$sourceID, 'Integer'],
2643 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2645 // for on behalf contribution source is individual and contributor is organization
2646 if ($sourceContactId && $sourceContactId != $contributorId) {
2647 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2648 // get rel type id for employee of relation
2649 foreach ($relationshipTypeIds as $id => $typeVals) {
2650 if ($typeVals['name_a_b'] == 'Employee of') {
2651 $relationshipTypeId = $id;
2656 $rel = new CRM_Contact_DAO_Relationship();
2657 $rel->relationship_type_id
= $relationshipTypeId;
2658 $rel->contact_id_a
= $sourceContactId;
2659 $rel->contact_id_b
= $contributorId;
2660 if ($rel->find(TRUE)) {
2661 $ids['individual_id'] = $rel->contact_id_a
;
2662 $ids['organization_id'] = $rel->contact_id_b
;
2673 public static function getContributionDates() {
2674 $config = CRM_Core_Config
::singleton();
2675 $currentMonth = date('m');
2676 $currentDay = date('d');
2677 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2678 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2679 (int ) $config->fiscalYearStart
['d'] > $currentDay
2682 $year = date('Y') - 1;
2687 $year = ['Y' => $year];
2688 $yearDate = $config->fiscalYearStart
;
2689 $yearDate = array_merge($year, $yearDate);
2690 $yearDate = CRM_Utils_Date
::format($yearDate);
2692 $monthDate = date('Ym') . '01';
2698 'yearDate' => $yearDate,
2699 'monthDate' => $monthDate,
2704 * Load objects relations to contribution object.
2705 * Objects are stored in the $_relatedObjects property
2706 * In the first instance we are just moving functionality from BASEIpn -
2708 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2710 * Note that the unit test for the BaseIPN class tests this function
2712 * @param array $input
2713 * Input as delivered from Payment Processor.
2715 * Ids as Loaded by Payment Processor.
2716 * @param bool $loadAll
2717 * Load all related objects - even where id not passed in? (allows API to call this).
2720 * @throws CRM_Core_Exception
2722 public function loadRelatedObjects($input, &$ids, $loadAll = FALSE) {
2723 // @todo deprecate this function - the steps should be
2724 // 1) add additional functions like 'getRelatedMemberships'
2725 // 2) switch all calls that refer to ->_relatedObjects to
2726 // using the helper functions
2727 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2728 // 4) make ->_relatedObjects protected
2729 // 5) hone up the individual functions to not use rely on this having been called
2730 // 6) deprecate like mad
2732 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2733 if (empty($ids['contact']) && isset($this->contact_id
)) {
2734 $ids['contact'] = $this->contact_id
;
2737 if (empty($this->_component
)) {
2738 if (!empty($ids['event'])) {
2739 $this->_component
= 'event';
2742 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2746 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2747 // refactoring than anything else, and has unit test coverage.
2748 if (empty($this->financial_type_id
)) {
2752 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2757 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2758 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2759 $this->contribution_page_id
,
2762 if ($paymentProcessorID) {
2763 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2767 $ids['contributionType'] = $this->financial_type_id
;
2768 $ids['financialType'] = $this->financial_type_id
;
2769 if ($this->contribution_page_id
) {
2770 $ids['contributionPage'] = $this->contribution_page_id
;
2773 $this->loadRelatedEntitiesByID($ids);
2775 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2776 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2779 if (!empty($ids['pledge_payment'])) {
2780 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2781 if (empty($paymentID)) {
2784 $payment = new CRM_Pledge_BAO_PledgePayment();
2785 $payment->id
= $paymentID;
2786 if (!$payment->find(TRUE)) {
2787 throw new CRM_Core_Exception("Could not find pledge payment record: " . $paymentID);
2789 $this->_relatedObjects
['pledge_payment'][] = $payment;
2793 // These are probably no longer accessed from anywhere
2794 // @todo remove this line, after ensuring not used.
2795 $ids = $this->loadRelatedMembershipObjects($ids);
2797 if ($this->_component
!= 'contribute') {
2798 // we are in event mode
2799 // make sure event exists and is valid
2800 $event = new CRM_Event_BAO_Event();
2801 $event->id
= $ids['event'];
2802 if ($ids['event'] &&
2805 throw new CRM_Core_Exception("Could not find event: " . $ids['event']);
2808 $this->_relatedObjects
['event'] = &$event;
2810 $participant = new CRM_Event_BAO_Participant();
2811 $participant->id
= $ids['participant'];
2812 if ($ids['participant'] &&
2813 !$participant->find(TRUE)
2815 throw new CRM_Core_Exception("Could not find participant: " . $ids['participant']);
2817 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2819 $this->_relatedObjects
['participant'] = &$participant;
2821 // get the payment processor id from event - this is inaccurate see CRM-16923
2822 // in future we should look at throwing an exception here rather than an dubious guess.
2823 if (!$paymentProcessorID) {
2824 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2825 if ($paymentProcessorID) {
2826 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2831 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds($this->id
);
2832 if (!empty($relatedContact['individual_id'])) {
2833 $ids['related_contact'] = $relatedContact['individual_id'];
2836 if ($paymentProcessorID) {
2837 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2838 $this->is_test ?
'test' : 'live'
2840 $ids['paymentProcessor'] = $paymentProcessorID;
2841 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2844 // Add contribution id to $ids. CRM-20401
2845 $ids['contribution'] = $this->id
;
2850 * Create array of message information - ie. return html version, txt version, to field
2852 * @param array $input
2853 * Incoming information.
2854 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2855 * just check presence of recur object but maintaining legacy approach
2858 * IDs of related objects.
2859 * @param array $values
2860 * Any values that may have already been compiled by calling process.
2861 * This is augmented by values 'gathered' by gatherMessageValues
2862 * @param bool $returnMessageText
2863 * Distinguishes between whether to send message or return.
2864 * message text. We are working towards this function ALWAYS returning message text & calling
2865 * function doing emails / pdfs with it
2871 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2872 $this->loadRelatedObjects($input, $ids);
2874 if (empty($this->_component
)) {
2875 $this->_component
= $input['component'] ??
NULL;
2878 //not really sure what params might be passed in but lets merge em into values
2879 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2880 $values['is_email_receipt'] = !$returnMessageText;
2881 foreach (['receipt_date', 'cc_receipt', 'bcc_receipt', 'receipt_from_name', 'receipt_from_email', 'receipt_text'] as $fld) {
2882 if (!empty($input[$fld])) {
2883 $values[$fld] = $input[$fld];
2887 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2888 //what does recur 'mean here - to do with payment processor return functionality but
2889 // what is the importance
2890 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2891 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2893 $entityID = $entity = NULL;
2894 if (isset($ids['contribution'])) {
2895 $entity = 'contribution';
2896 $entityID = $ids['contribution'];
2898 if (!empty($ids['membership'])) {
2899 //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
2900 // 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
2901 // line having loaded an array
2902 $ids['membership'] = (array) $ids['membership'];
2903 $entity = 'membership';
2904 $entityID = $ids['membership'][0];
2907 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2908 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2909 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2911 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2912 //direct mode showing billing block, so use directIPN for temporary
2913 $template->assign('contributeMode', 'directIPN');
2916 // todo remove strtolower - check consistency
2917 if (strtolower($this->_component
) == 'event') {
2918 $eventParams = ['id' => $this->_relatedObjects
['participant']->event_id
];
2919 $values['event'] = [];
2921 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2923 //get location details
2925 'entity_id' => $this->_relatedObjects
['participant']->event_id
,
2926 'entity_table' => 'civicrm_event',
2928 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2931 'entity_table' => 'civicrm_event',
2932 'entity_id' => $ids['event'],
2933 'module' => 'CiviEvent',
2936 list($custom_pre_id,
2938 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2940 $values['custom_pre_id'] = $custom_pre_id;
2941 $values['custom_post_id'] = $custom_post_ids;
2942 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2943 //and cases involving status updation through ipn
2944 // whatever that means!
2945 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2946 // perhaps we should throw an e-notice if amount is set & force total_amount?
2947 if (!empty($input['amount'])) {
2948 $values['totalAmount'] = $input['amount'];
2950 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2951 if ($values['event']['is_email_confirm']) {
2952 $values['is_email_receipt'] = 1;
2955 if (!empty($ids['contribution'])) {
2956 $values['contributionId'] = $ids['contribution'];
2959 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2960 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2964 $values['contribution_id'] = $this->id
;
2965 if (!empty($ids['related_contact'])) {
2966 $values['related_contact'] = $ids['related_contact'];
2967 if (isset($ids['onbehalf_dupe_alert'])) {
2968 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2971 'contact_id' => $ids['contact'],
2972 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2973 'Home', 'id', 'name'
2976 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2977 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2980 if ($this->is_test
) {
2983 if (!empty($this->_relatedObjects
['membership'])) {
2984 foreach ($this->_relatedObjects
['membership'] as $membership) {
2985 if ($membership->id
) {
2986 $values['membership_id'] = $membership->id
;
2987 $values['isMembership'] = TRUE;
2988 $values['membership_assign'] = TRUE;
2990 // need to set the membership values here
2991 $template->assign('membership_name',
2992 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2994 $template->assign('mem_start_date', $membership->start_date
);
2995 $template->assign('mem_join_date', $membership->join_date
);
2996 $template->assign('mem_end_date', $membership->end_date
);
2997 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2998 $template->assign('mem_status', $membership_status);
2999 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
3000 $values['is_pay_later'] = 1;
3002 // Pass amount to floatval as string '0.00' is considered a
3003 // valid amount and includes Fee section in the mail.
3004 if (isset($values['amount'])) {
3005 $values['amount'] = floatval($values['amount']);
3008 if (!empty($this->contribution_recur_id
) && $paymentObject) {
3009 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
3010 $template->assign('cancelSubscriptionUrl', $url);
3011 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
3012 $template->assign('updateSubscriptionBillingUrl', $url);
3013 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
3014 $template->assign('updateSubscriptionUrl', $url);
3017 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3020 // otherwise if its about sending emails, continue sending without return, as we
3021 // don't want to exit the loop.
3026 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3032 * Gather values for contribution mail - this function has been created
3033 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
3034 * Values related to the contribution in question are gathered
3036 * @param array $input
3037 * Input into function (probably from payment processor).
3038 * @param array $values
3040 * The set of ids related to the input.
3043 * @throws \CRM_Core_Exception
3045 public function _gatherMessageValues($input, &$values, $ids = []) {
3046 // set display address of contributor
3047 $values['billingName'] = '';
3048 if ($this->address_id
) {
3049 $addressDetails = CRM_Core_BAO_Address
::getValues(['id' => $this->address_id
], FALSE, 'id');
3050 $addressDetails = reset($addressDetails);
3051 $values['billingName'] = $addressDetails['name'] ??
'';
3053 // Else we assign the billing address of the contribution contact.
3055 $addressDetails = (array) CRM_Core_BAO_Address
::getValues(['contact_id' => $this->contact_id
, 'is_billing' => 1]);
3056 $addressDetails = reset($addressDetails);
3058 $values['address'] = $addressDetails['display'] ??
'';
3060 if ($this->_component
=== 'contribute') {
3061 //get soft contributions
3062 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
3063 if (!empty($softContributions)) {
3064 // For pcp soft credit, there is no 'soft_credit' member it comes
3065 // back in different array members, but shortly after returning from
3066 // this function it calls _assignMessageVariablesToTemplate which does
3067 // its own lookup of any pcp soft credit, so we can skip it here.
3068 $values['softContributions'] = $softContributions['soft_credit'] ??
NULL;
3070 if (isset($this->contribution_page_id
)) {
3071 // This is a call we want to use less, in favour of loading related objects.
3072 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
3073 if ($this->contribution_page_id
) {
3074 // This is precautionary as there are some legacy flows, but it should really be
3076 if (!isset($this->_relatedObjects
['contributionPage'])) {
3077 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id
]);
3079 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($values);
3082 // no contribution page -probably back office
3084 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
3085 $values['title'] = 'Contribution';
3087 // set lineItem for contribution
3089 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
3090 if (!empty($lineItems)) {
3091 $firstLineItem = reset($lineItems);
3093 if (!empty($firstLineItem['price_set_id'])) {
3094 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
3095 'id' => $firstLineItem['price_set_id'],
3096 'return' => 'is_quick_config, id',
3098 $values['priceSetID'] = $priceSet['id'];
3100 foreach ($lineItems as &$eachItem) {
3101 if (isset($this->_relatedObjects
['membership'])
3102 && is_array($this->_relatedObjects
['membership'])
3103 && array_key_exists($eachItem['entity_id'] . '_' . $eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
3104 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->join_date
);
3105 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->start_date
);
3106 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->end_date
);
3108 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
3109 // However, that does create upgrade pain so would be better to be phased in.
3110 $values['useForMember'] = empty($priceSet['is_quick_config']);
3112 $values['lineItem'][0] = $lineItems;
3116 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
3120 // if this is onbehalf of contribution then set related contact
3121 if (!empty($relatedContact['individual_id'])) {
3122 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
3126 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects
['participant']->id
, $this->id
));
3129 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
3132 foreach ($groupTree as $key => $group) {
3133 if ($key === 'info') {
3137 foreach ($group['fields'] as $k => $customField) {
3138 $groupLabel = $group['title'];
3139 if (!empty($customField['customValue'])) {
3140 foreach ($customField['customValue'] as $customFieldValues) {
3141 $customGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
3146 $values['customGroup'] = $customGroup;
3148 $values['is_pay_later'] = $this->is_pay_later
;
3154 * Assign message variables to template but try to break the habit.
3156 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3157 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3158 * multiple recurring payments for processors like IATS that use tokens.
3160 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3161 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
3162 * Note we send directly from this function in some cases because it is only partly refactored.
3164 * Don't call this function directly as the signature will change.
3168 * @param bool $returnMessageText
3172 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
3173 // @todo - this should have a better separation of concerns - ie.
3174 // gatherMessageValues should build an array of values to be assigned to the template
3175 // and this function should assign them (assigning null if not set).
3176 // the way the pcpParams & honor Params section works is a baby-step towards this.
3177 $template = CRM_Core_Smarty
::singleton();
3178 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
3179 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
3180 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
3181 $template->assign('billingName', $values['billingName']);
3183 // For some unit tests contribution cannot contain paymentProcessor information
3184 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
3185 $template->assign('contributeMode', CRM_Core_SelectValues
::contributeMode()[$billingMode] ??
NULL);
3187 //assign honor information to receipt message
3188 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
3191 'soft_credit_type' => NULL,
3192 'honor_block_is_active' => NULL,
3194 if (isset($softRecord['soft_credit'])) {
3195 //if id of contribution page is present
3196 if (!empty($values['id'])) {
3197 $values['honor'] = [
3198 'honor_profile_values' => [],
3199 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3200 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
3203 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3204 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
3207 //offline contribution
3208 $softCreditTypes = $softCredits = [];
3209 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3210 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3211 $softCredits[$key] = [
3212 'Name' => $softCredit['contact_name'],
3213 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
3216 $template->assign('softCreditTypes', $softCreditTypes);
3217 $template->assign('softCredits', $softCredits);
3221 $dao = new CRM_Contribute_DAO_ContributionProduct();
3222 $dao->contribution_id
= $this->id
;
3223 if ($dao->find(TRUE)) {
3224 $premiumId = $dao->product_id
;
3225 $template->assign('option', $dao->product_option
);
3227 $productDAO = new CRM_Contribute_DAO_Product();
3228 $productDAO->id
= $premiumId;
3229 $productDAO->find(TRUE);
3230 $template->assign('selectPremium', TRUE);
3231 $template->assign('product_name', $productDAO->name
);
3232 $template->assign('price', $productDAO->price
);
3233 $template->assign('sku', $productDAO->sku
);
3235 $template->assign('title', $values['title'] ??
NULL);
3236 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
3237 if (!$values['amount'] && isset($this->total_amount
)) {
3238 $values['amount'] = $this->total_amount
;
3243 'pcp_display_in_roll' => NULL,
3244 'pcp_roll_nickname' => NULL,
3245 'pcp_personal_note' => NULL,
3249 if (strtolower($this->_component
) == 'contribute') {
3251 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3252 $softDAO->contribution_id
= $this->id
;
3253 if ($softDAO->find(TRUE)) {
3254 $pcpParams['pcpBlock'] = TRUE;
3255 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
3256 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
3257 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
3259 //assign the pcp page title for email subject
3260 $pcpDAO = new CRM_PCP_DAO_PCP();
3261 $pcpDAO->id
= $softDAO->pcp_id
;
3262 if ($pcpDAO->find(TRUE)) {
3263 $pcpParams['title'] = $pcpDAO->title
;
3267 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3268 $template->assign($templateKey, $templateValue);
3271 if ($this->financial_type_id
) {
3272 $values['financial_type_id'] = $this->financial_type_id
;
3275 $template->assign('trxn_id', $this->trxn_id
);
3276 $template->assign('receive_date',
3277 CRM_Utils_Date
::processDate($this->receive_date
)
3279 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
3280 $template->assign('action', $this->is_test ?
1024 : 1);
3281 $template->assign('receipt_text', $values['receipt_text'] ??
NULL);
3282 $template->assign('is_monetary', 1);
3283 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3284 $template->assign('currency', $this->currency
);
3285 $template->assign('address', CRM_Utils_Address
::format($input));
3286 if (!empty($values['customGroup'])) {
3287 $template->assign('customGroup', $values['customGroup']);
3289 if (!empty($values['softContributions'])) {
3290 $template->assign('softContributions', $values['softContributions']);
3292 if ($this->_component
== 'event') {
3293 $template->assign('title', $values['event']['title']);
3294 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3296 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3297 $viewRoles[] = $participantRoles[$v];
3299 $values['event']['participant_role'] = implode(', ', $viewRoles);
3300 $template->assign('event', $values['event']);
3301 $template->assign('participant', $values['participant']);
3302 $template->assign('location', $values['location']);
3303 $template->assign('customPre', $values['custom_pre_id']);
3304 $template->assign('customPost', $values['custom_post_id']);
3307 if ($this->_relatedObjects
['participant']->is_test
) {
3311 $values['params'] = [];
3312 //to get email of primary participant.
3313 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3314 $primaryAmount[] = [
3315 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3316 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3318 //build an array of cId/pId of participants
3319 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3320 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3321 //send receipt to additional participant if exists
3322 if (count($additionalIDs)) {
3323 $template->assign('isPrimary', 0);
3324 $template->assign('customProfile', NULL);
3325 //set additionalParticipant true
3326 $values['params']['additionalParticipant'] = TRUE;
3327 foreach ($additionalIDs as $pId => $cId) {
3329 //to change the status pending to completed
3330 $additional = new CRM_Event_DAO_Participant();
3331 $additional->id
= $pId;
3332 $additional->contact_id
= $cId;
3333 $additional->find(TRUE);
3334 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3335 $additional->status_id
= 1;
3336 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3337 //if additional participant dont have email
3339 if (!$additionalParticipantInfo) {
3340 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3343 'label' => $additional->fee_level
,
3344 'amount' => $additional->fee_amount
,
3346 $primaryAmount[] = [
3347 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3348 'amount' => $additional->fee_amount
,
3350 $additional->save();
3351 $template->assign('amount', $amount);
3352 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3356 //build an array of custom profile and assigning it to template
3357 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3359 if (count($customProfile)) {
3360 $template->assign('customProfile', $customProfile);
3363 // for primary contact
3364 $values['params']['additionalParticipant'] = FALSE;
3365 $template->assign('isPrimary', 1);
3366 $template->assign('amount', $primaryAmount);
3367 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3368 if ($this->payment_instrument_id
) {
3369 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3370 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3372 // carry paylater, since we did not created billing,
3373 // so need to pull email from primary location, CRM-4395
3374 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3380 * Check whether payment processor supports
3381 * cancellation of contribution subscription
3383 * @param int $contributionId
3386 * @param bool $isNotCancelled
3390 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3391 $cacheKeyString = "$contributionId";
3392 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3394 static $supportsCancel = [];
3396 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3397 $supportsCancel[$cacheKeyString] = FALSE;
3398 $isCancelled = FALSE;
3400 if ($isNotCancelled) {
3401 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3404 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3405 if (!empty($paymentObject)) {
3406 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3409 return $supportsCancel[$cacheKeyString];
3413 * Check whether subscription is already cancelled.
3415 * @param int $contributionId
3419 * contribution status
3421 public static function isSubscriptionCancelled($contributionId) {
3423 SELECT cr.contribution_status_id
3424 FROM civicrm_contribution_recur cr
3425 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3426 WHERE con.id = %1 LIMIT 1";
3427 $params = [1 => [$contributionId, 'Integer']];
3428 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3429 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
3430 if ($status == 'Cancelled') {
3437 * Create all financial accounts entry.
3439 * @param array $params
3440 * Contribution object, line item array and params for trxn.
3443 * @param array $financialTrxnValues
3445 * @return null|\CRM_Core_BAO_FinancialTrxn
3447 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3448 $skipRecords = $update = $return = $isRelatedId = FALSE;
3449 $isUpdate = !empty($params['prevContribution']);
3451 $additionalParticipantId = [];
3452 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3453 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3455 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3456 $entityId = $params['participant_id'];
3457 $entityTable = 'civicrm_participant';
3458 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3460 elseif (!empty($params['membership_id'])) {
3461 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3462 // are created off one contribution should be handled elsewhere
3463 $entityId = $params['membership_id'];
3464 $entityTable = 'civicrm_membership';
3467 $entityId = $params['contribution']->id
;
3468 $entityTable = 'civicrm_contribution';
3471 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3472 $isRelatedId = TRUE;
3475 $entityID[] = $entityId;
3476 if (!empty($additionalParticipantId)) {
3477 $entityID +
= $additionalParticipantId;
3479 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3480 if (empty($params['prevContribution'])) {
3484 $statusId = $params['contribution']->contribution_status_id
;
3486 // build line item array if its not set in $params
3487 if (empty($params['line_item']) ||
$additionalParticipantId) {
3488 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3491 if ($contributionStatus != 'Failed' &&
3492 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3494 $skipRecords = TRUE;
3499 if (in_array($contributionStatus, $pendingStatus)) {
3500 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3501 $params['financial_type_id'],
3502 'Accounts Receivable Account is'
3505 elseif (!empty($params['payment_processor'])) {
3506 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3507 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3508 'id' => $params['payment_processor'],
3509 'return' => 'payment_instrument_id',
3512 elseif (!empty($params['payment_instrument_id'])) {
3513 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3516 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3517 $queryParams = [1 => [$relationTypeId, 'Integer']];
3518 $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);
3521 $totalAmount = $params['total_amount'] ??
NULL;
3522 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3523 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3525 //build financial transaction params
3527 'contribution_id' => $params['contribution']->id
,
3528 'to_financial_account_id' => $params['to_financial_account_id'],
3529 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3530 'total_amount' => $totalAmount,
3531 'fee_amount' => $params['fee_amount'] ??
NULL,
3532 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3533 'currency' => $params['contribution']->currency
,
3534 'trxn_id' => $params['contribution']->trxn_id
,
3535 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3536 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3537 // this should really default to completed (after discussion).
3538 'status_id' => $statusId,
3539 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3540 'check_number' => $params['check_number'] ??
NULL,
3541 'pan_truncation' => $params['pan_truncation'] ??
NULL,
3542 'card_type_id' => $params['card_type_id'] ??
NULL,
3544 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3545 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3546 if (isset($params['refund_trxn_id'])) {
3547 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3548 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3551 //CRM-16259, set is_payment flag for non pending status
3552 if (!in_array($contributionStatus, $pendingStatus)) {
3553 $trxnParams['is_payment'] = 1;
3555 if (!empty($params['payment_processor'])) {
3556 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3559 if (isset($fromFinancialAccountId)) {
3560 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3563 // consider external values passed for recording transaction entry
3564 if (!empty($financialTrxnValues)) {
3565 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3567 if (empty($trxnParams['payment_processor_id'])) {
3568 unset($trxnParams['payment_processor_id']);
3571 $params['trxnParams'] = $trxnParams;
3575 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3576 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3577 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3578 if (!isset($params['trxnParams']['trxn_id'])) {
3579 // Actually I have no idea why we are overwriting any values from the previous contribution.
3580 // (filling makes sense to me). However, only protecting this value as I really really know we
3581 // don't want this one overwritten.
3583 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3585 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3587 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3588 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3589 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3591 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3592 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3595 //if financial type is changed
3596 if (!empty($params['financial_type_id']) &&
3597 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3599 $accountRelationship = 'Income Account is';
3600 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3601 $accountRelationship = 'Deferred Revenue Account is';
3603 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3604 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3605 if ($oldFinancialAccount != $newFinancialAccount) {
3606 $params['total_amount'] = 0;
3607 // If we have a fee amount set reverse this as well.
3608 if (isset($params['fee_amount'])) {
3609 $params['trxnParams']['fee_amount'] = 0 - $params['fee_amount'];
3611 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3612 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3613 $params['prevContribution']->financial_type_id
, $accountRelationship);
3616 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3617 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3618 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3621 self
::updateFinancialAccounts($params, 'changeFinancialType');
3622 $params['skipLineItem'] = FALSE;
3623 foreach ($params['line_item'] as &$lineItems) {
3624 foreach ($lineItems as &$line) {
3625 $line['financial_type_id'] = $params['financial_type_id'];
3628 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType');
3629 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3630 $params['financial_account_id'] = $newFinancialAccount;
3631 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3632 // Set the transaction fee amount back to the original value for creating the new positive financial trxn.
3633 if (isset($params['fee_amount'])) {
3634 $params['trxnParams']['fee_amount'] = $params['fee_amount'];
3636 self
::updateFinancialAccounts($params);
3637 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE);
3638 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3640 $params['deferred_financial_account_id'] = $newFinancialAccount;
3644 //Update contribution status
3645 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3646 if (!isset($params['refund_trxn_id'])) {
3647 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3648 // gets preference over another so I am only 'protecting' a very specific tested flow
3649 // and letting natural justice take care of the rest.
3650 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3652 if (!empty($params['contribution_status_id']) &&
3653 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3655 //Update Financial Records
3656 $callUpdateFinancialAccounts = self
::updateFinancialAccountsOnContributionStatusChange($params);
3657 if ($callUpdateFinancialAccounts) {
3658 self
::updateFinancialAccounts($params, 'changedStatus');
3659 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus');
3664 // change Payment Instrument for a Completed contribution
3665 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3666 // instrument is null and now new payment instrument is added along with the payment
3667 if (!$params['contribution']->payment_instrument_id
) {
3668 $params['contribution']->find(TRUE);
3670 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3671 $params['trxnParams']['check_number'] = $params['check_number'] ??
NULL;
3673 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3674 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3677 //if Change contribution amount
3678 $params['trxnParams']['fee_amount'] = $params['fee_amount'] ??
NULL;
3679 $params['trxnParams']['net_amount'] = $params['net_amount'] ??
NULL;
3680 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3681 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3682 if (isset($totalAmount) &&
3683 $totalAmount != $params['prevContribution']->total_amount
3685 //Update Financial Records
3686 $params['trxnParams']['from_financial_account_id'] = NULL;
3687 self
::updateFinancialAccounts($params, 'changedAmount');
3688 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount');
3693 // Looks like we might have a data correction update.
3694 // This would be a case where a transaction id has been entered but it is incorrect &
3695 // the person goes back in & fixes it, as opposed to a new transaction.
3696 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3697 // the data fix scenario.
3699 if (isset($params['refund_trxn_id'])) {
3700 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3701 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3702 civicrm_api3('FinancialTrxn', 'create', [
3703 'id' => $refundIDs['financialTrxnId'],
3704 'trxn_id' => $params['refund_trxn_id'],
3708 $cardType = $params['card_type_id'] ??
NULL;
3709 $panTruncation = $params['pan_truncation'] ??
NULL;
3710 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3715 // records finanical trxn and entity financial trxn
3716 // also make it available as return value
3717 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3718 $trxnParams['pan_truncation'] = $params['pan_truncation'] ??
NULL;
3719 $trxnParams['card_type_id'] = $params['card_type_id'] ??
NULL;
3720 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3721 $params['entity_id'] = $financialTxn->id
;
3722 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3723 self
::$_trxnIDs[] = $financialTxn->id
;
3727 // record line items and financial items
3728 if (empty($params['skipLineItem'])) {
3729 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $isUpdate);
3732 // create batch entry if batch_id is passed and
3733 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3734 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3736 'batch_id' => $params['batch_id'],
3737 'entity_table' => 'civicrm_financial_trxn',
3738 'entity_id' => $financialTxn->id
,
3740 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3743 // when a fee is charged
3744 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3745 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3748 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3749 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3751 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3752 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3753 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3755 unset($params['line_item']);
3756 self
::$_trxnIDs = NULL;
3761 * Update all financial accounts entry.
3763 * @param array $params
3764 * Contribution object, line item array and params for trxn.
3766 * @param string $context
3769 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3770 * adds unpredictability.
3773 public static function updateFinancialAccounts(&$params, $context = NULL) {
3775 $inputParams = $params;
3776 $isARefund = self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
);
3778 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3779 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3780 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3783 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3784 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3785 $params['entity_id'] = $trxn->id
;
3787 $itemParams['entity_table'] = 'civicrm_line_item';
3788 $trxnIds['id'] = $params['entity_id'];
3789 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution']->id
);
3790 foreach ($params['line_item'] as $fieldId => $fields) {
3791 $params = self
::createFinancialItemsForLine($params, $context, $fields, $previousLineItems, $inputParams, $isARefund, $trxnIds, $fieldId);
3796 * Is this contribution status a reversal.
3798 * If so we would expect to record a negative value in the financial_trxn table.
3800 * @param int $status_id
3804 public static function isContributionStatusNegative($status_id) {
3805 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3806 return in_array(CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE);
3810 * Check status validation on update of a contribution.
3812 * @param array $values
3813 * Previous form values before submit.
3815 * @param array $fields
3816 * The input form values.
3818 * @param array $errors
3823 public static function checkStatusValidation($values, &$fields, &$errors) {
3824 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3825 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3826 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3830 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3832 'Cancelled' => ['Completed', 'Refunded'],
3833 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3834 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3835 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3836 'Refunded' => ['Cancelled', 'Completed'],
3837 'Partially paid' => ['Completed'],
3838 'Pending refund' => ['Completed', 'Refunded'],
3839 'Failed' => ['Pending'],
3842 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3843 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3845 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3846 1 => $contributionStatuses[$values['contribution_status_id']],
3847 2 => $contributionStatuses[$fields['contribution_status_id']],
3853 * Delete contribution of contact.
3855 * @see https://issues.civicrm.org/jira/browse/CRM-12155
3857 * @param int $contactId
3861 public static function deleteContactContribution($contactId) {
3862 $contribution = new CRM_Contribute_DAO_Contribution();
3863 $contribution->contact_id
= $contactId;
3864 $contribution->find();
3865 while ($contribution->fetch()) {
3866 self
::deleteContribution($contribution->id
);
3871 * Get options for a given contribution field.
3873 * @param string $fieldName
3874 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3875 * @param array $props whatever is known about this dao object.
3877 * @return array|bool
3878 * @see CRM_Core_DAO::buildOptions
3881 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3882 $className = __CLASS__
;
3884 if (isset($props['orderColumn'])) {
3885 $params['orderColumn'] = $props['orderColumn'];
3887 switch ($fieldName) {
3888 // This field is not part of this object but the api supports it
3889 case 'payment_processor':
3890 $className = 'CRM_Contribute_BAO_ContributionPage';
3891 // Filter results by contribution page
3892 if (!empty($props['contribution_page_id'])) {
3893 $page = civicrm_api('contribution_page', 'getsingle', [
3895 'id' => ($props['contribution_page_id']),
3897 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3898 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3902 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3903 case 'honor_type_id':
3904 $className = 'CRM_Contribute_BAO_ContributionSoft';
3905 $fieldName = 'soft_credit_type_id';
3906 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3909 case 'contribution_status_id':
3910 if ($context !== 'validate') {
3911 $params['condition'] = "v.name <> 'Template'";
3914 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3918 * Validate financial type.
3920 * @see https://issues.civicrm.org/jira/browse/CRM-13231
3922 * @param int $financialTypeId
3923 * Financial Type id.
3925 * @param string $relationName
3927 * @return array|bool
3929 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3930 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3932 if (!$financialAccount) {
3933 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3939 * @param int $targetCid
3940 * @param $activityType
3941 * @param string $title
3942 * @param int $contributionId
3943 * @param string $totalAmount
3944 * @param string $currency
3945 * @param string $trxn_date
3947 * @throws \CRM_Core_Exception
3948 * @throws \CiviCRM_API3_Exception
3950 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
3951 $paymentAmount = CRM_Utils_Money
::format($totalAmount, $currency);
3952 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3953 $date = CRM_Utils_Date
::isoToMysql($trxn_date);
3954 // source record id would be the contribution id
3955 $srcRecId = $contributionId;
3959 'source_contact_id' => $targetCid,
3960 'source_record_id' => $srcRecId,
3961 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
3962 'subject' => $subject,
3963 'activity_date_time' => $date,
3964 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
3965 'skipRecentView' => TRUE,
3968 // create activity with target contacts
3969 $session = CRM_Core_Session
::singleton();
3970 $id = $session->get('userID');
3972 $activityParams['source_contact_id'] = $id;
3973 $activityParams['target_contact_id'][] = $targetCid;
3975 civicrm_api3('Activity', 'create', $activityParams);
3979 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3982 * @param string $component
3983 * @param bool $getTrxnInfo
3987 * @throws \CRM_Core_Exception
3988 * @throws \CiviCRM_API3_Exception
3990 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE) {
3991 // @todo deprecate passing in component - always call with contribution.
3992 if ($component == 'event') {
3993 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3995 if (!$contributionId) {
3996 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3997 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3998 $id = $primaryParticipantId;
4000 if (!$contributionId) {
4005 elseif ($component == 'membership') {
4006 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
4009 $contributionId = $id;
4012 // The balance used to be calculated this way - we really want to remove this 'oldCalculation'
4013 // but need to unpick the whole trxn_id it's returning first.
4014 $oldCalculation = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
4015 $baseTrxnId = !empty($oldCalculation['trxn_id']) ?
$oldCalculation['trxn_id'] : NULL;
4017 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
4018 $baseTrxnId = $baseTrxnId['financialTrxnId'];
4020 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4022 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
4024 $contribution = civicrm_api3('Contribution', 'getsingle', [
4025 'id' => $contributionId,
4029 'contribution_status_id',
4030 'financial_type_id',
4034 $info['payLater'] = $contribution['is_pay_later'];
4035 $info['contribution_status'] = $contribution['contribution_status'];
4036 $info['currency'] = $contribution['currency'];
4038 $info['total'] = $total;
4039 $info['paid'] = $total - $paymentBalance;
4040 $info['balance'] = $paymentBalance;
4042 $info['component'] = $component;
4043 if ($getTrxnInfo && $baseTrxnId) {
4044 $info['transaction'] = self
::getContributionTransactionInformation($contributionId, $contribution['financial_type_id']);
4047 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
4052 * Get the outstanding balance on a contribution.
4054 * @param int $contributionId
4055 * @param float $contributionTotal
4056 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
4060 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
4061 if ($contributionTotal === NULL) {
4062 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4065 return (float) CRM_Utils_Money
::subtractCurrencies(
4067 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE),
4068 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4073 * Get the tax amount (misnamed function).
4075 * @param array $params
4078 * @throws \CiviCRM_API3_Exception
4080 protected static function checkTaxAmount($params) {
4081 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4083 // Update contribution.
4084 if (!empty($params['id'])) {
4085 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4086 // there are no tax implications - early return.
4087 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4090 if (empty($params['prevContribution'])) {
4091 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4094 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
4095 if (!isset($params[$field])) {
4096 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4097 // Tax amount gets added back on later....
4098 $params['total_amount'] = $params['prevContribution']->total_amount
-
4099 $params['prevContribution']->tax_amount
;
4102 $params[$field] = $params['prevContribution']->$field;
4103 if ($params[$field] != $params['prevContribution']->$field) {
4109 self
::calculateMissingAmountParams($params, $params['id']);
4110 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4111 // Assign tax Amount on update of contribution
4112 if (!empty($params['prevContribution']->tax_amount
)) {
4113 $params['tax_amount'] = 'null';
4114 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4115 foreach ($params['line_item'] as $setID => $priceField) {
4116 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4117 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4124 // New Contribution and update of contribution with tax rate financial type
4125 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4126 empty($params['skipLineItem'])) {
4127 $taxRateParams = $taxRates[$params['financial_type_id']];
4128 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams);
4129 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4131 // Get Line Item on update of contribution
4132 if (isset($params['id'])) {
4133 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4136 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4138 foreach ($params['line_item'] as $setID => $priceField) {
4139 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4140 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4143 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4145 elseif (isset($params['api.line_item.create'])) {
4146 // Update total amount of contribution using lineItem
4147 $taxAmountArray = [];
4148 foreach ($params['api.line_item.create'] as $key => $value) {
4149 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4150 $taxRate = $taxRates[$value['financial_type_id']];
4151 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4152 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4155 $params['tax_amount'] = array_sum($taxAmountArray);
4156 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4163 * Check financial type validation on update of a contribution.
4165 * @param int $financialTypeId
4166 * Value of latest Financial Type.
4168 * @param int $contributionId
4171 * @param array $errors
4176 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4177 if (!empty($financialTypeId)) {
4178 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4179 if ($oldFinancialTypeId == $financialTypeId) {
4183 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4185 '1' => [$contributionId, 'Integer'],
4187 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4188 if ($result->N
> 1) {
4189 $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.');
4194 * Update related pledge payment payments.
4196 * This function has been refactored out of the back office contribution form and may
4197 * still overlap with other functions.
4199 * @param string $action
4200 * @param int $pledgePaymentID
4201 * @param int $contributionID
4202 * @param bool $adjustTotalAmount
4203 * @param float $total_amount
4204 * @param float $original_total_amount
4205 * @param int $contribution_status_id
4206 * @param int $original_contribution_status_id
4208 public static function updateRelatedPledge(
4214 $original_total_amount,
4215 $contribution_status_id,
4216 $original_contribution_status_id
4218 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4222 if ($pledgePaymentID) {
4223 //store contribution id in payment record.
4224 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4227 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4234 if (!$pledgePaymentID) {
4237 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4243 $updatePledgePaymentStatus = FALSE;
4245 // If either the status or the amount has changed we update the pledge status.
4246 if ($action & CRM_Core_Action
::ADD
) {
4247 $updatePledgePaymentStatus = TRUE;
4249 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4250 ($original_total_amount != $total_amount))
4252 $updatePledgePaymentStatus = TRUE;
4255 if ($updatePledgePaymentStatus) {
4256 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4258 $contribution_status_id,
4267 * Is there only one line item attached to the contribution.
4273 * @throws \CiviCRM_API3_Exception
4275 public static function isSingleLineItem($id) {
4276 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
4277 return ($lineItemCount == 1);
4281 * Complete an order.
4283 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4285 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4287 * Moving it out of the BaseIPN class is just the first step.
4289 * @param array $input
4291 * @param \CRM_Contribute_BAO_Contribution $contribution
4292 * @param bool $isPostPaymentCreate
4293 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
4294 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
4295 * transitioning related elements).
4298 * @throws \CRM_Core_Exception
4299 * @throws \CiviCRM_API3_Exception
4301 public static function completeOrder($input, $ids, $contribution, $isPostPaymentCreate = FALSE) {
4302 $transaction = new CRM_Core_Transaction();
4303 // @todo see if we even need this - it's used further down to create an activity
4304 // but the BAO layer should create that - we just need to add a test to cover it & can
4305 // maybe remove $ids altogether.
4306 $contributionContactID = $ids['related_contact'];
4307 $participantID = $ids['participant'];
4308 $recurringContributionID = $ids['contributionRecur'];
4310 // Unset ids just to make it clear it's not used again.
4312 // The previous details are used when calculating line items so keep it before any code that 'does something'
4313 if (!empty($contribution->id
)) {
4314 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(['id' => $contribution->id
]);
4316 $inputContributionWhiteList = [
4321 'payment_instrument_id',
4326 'contribution_status_id',
4329 'financial_type_id',
4332 $paymentProcessorId = $input['payment_processor_id'] ??
NULL;
4334 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4336 $contributionParams = array_merge([
4337 'contribution_status_id' => $completedContributionStatusID,
4338 'source' => self
::getRecurringContributionDescription($contribution, $participantID),
4339 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4342 $contributionParams['payment_processor'] = $paymentProcessorId;
4344 if (empty($contributionParams['payment_instrument_id']) && $paymentProcessorId) {
4345 $contributionParams['payment_instrument_id'] = PaymentProcessor
::get(FALSE)->addWhere('id', '=', $paymentProcessorId)->addSelect('payment_instrument_id')->execute()->first()['payment_instrument_id'];
4348 if ($recurringContributionID) {
4349 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4351 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4353 $contributionResult = self
::repeatTransaction($contribution, $input, $contributionParams);
4354 $contributionID = (int) $contribution->id
;
4356 if ($input['component'] == 'contribute') {
4357 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4358 self
::updateMembershipBasedOnCompletionOfContribution(
4365 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4366 $participantParams['id'] = $participantID;
4367 $participantParams['status_id'] = 'Registered';
4368 civicrm_api3('Participant', 'create', $participantParams);
4372 $contributionParams['id'] = $contributionID;
4373 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
4375 if (!$contributionResult) {
4376 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4379 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4381 CRM_Core_Error
::debug_log_message('Contribution record updated successfully');
4382 $transaction->commit();
4384 // @todo - check if Contribution::create does this, test, remove.
4385 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contributionID, $recurringContributionID,
4386 $contributionParams['contribution_status_id'], $input['amount']);
4388 // create an activity record
4389 // @todo - check if Contribution::create does this, test, remove.
4390 if ($input['component'] == 'contribute') {
4392 $targetContactID = NULL;
4393 if ($contributionContactID) {
4394 $targetContactID = $contribution->contact_id
;
4395 $contribution->contact_id
= $contributionContactID;
4397 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution', $targetContactID);
4400 if (self
::isEmailReceipt($input, $contribution->contribution_page_id
, $recurringContributionID)) {
4401 civicrm_api3('Contribution', 'sendconfirmation', [
4402 'id' => $contributionID,
4403 'payment_processor_id' => $paymentProcessorId,
4405 CRM_Core_Error
::debug_log_message("Receipt sent");
4408 CRM_Core_Error
::debug_log_message("Success: Database updated");
4409 return $contributionResult;
4413 * Send receipt from contribution.
4415 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4417 * Note that the compose message part has been moved to contribution
4418 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4420 * @param array $input
4421 * Incoming data from Payment processor.
4423 * Related object IDs.
4424 * @param int $contributionID
4425 * @param bool $returnMessageText
4426 * Should text be returned instead of sent. This.
4427 * is because the function is also used to generate pdfs
4430 * @throws \CRM_Core_Exception
4431 * @throws \CiviCRM_API3_Exception
4432 * @throws \Exception
4434 public static function sendMail($input, $ids, $contributionID, $returnMessageText = FALSE) {
4436 $contribution = new CRM_Contribute_BAO_Contribution();
4437 $contribution->id
= $contributionID;
4438 if (!$contribution->find(TRUE)) {
4439 throw new CRM_Core_Exception('Contribution does not exist');
4441 $contribution->loadRelatedObjects($input, $ids, TRUE);
4442 // set receipt from e-mail and name in value
4443 if (!$returnMessageText) {
4444 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4446 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4447 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4448 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4449 civicrm_api3('Contribution', 'create', [
4450 'receipt_date' => 'now',
4451 'id' => $contribution->id
,
4458 * Generate From email and from name in an array values
4460 * @param array $input
4461 * @param \CRM_Contribute_BAO_Contribution $contribution
4465 public static function generateFromEmailAndName($input, $contribution) {
4466 // Use input value if supplied.
4467 if (!empty($input['receipt_from_email'])) {
4469 CRM_Utils_Array
::value('receipt_from_name', $input, ''),
4470 $input['receipt_from_email'],
4473 // if we are still empty see if we can use anything from a contribution page.
4475 if (!empty($contribution->contribution_page_id
)) {
4476 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id
]);
4478 // if we are still empty see if we can use anything from a contribution page.
4479 if (!empty($pageValues['receipt_from_email'])) {
4481 CRM_Utils_Array
::value('receipt_from_name', $pageValues),
4482 $pageValues['receipt_from_email'],
4485 // If we are still empty fall back to the domain or logged in user information.
4486 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4490 * Load related memberships.
4494 * @return array $ids
4499 * Note that in theory it should be possible to retrieve these from the line_item table
4500 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4501 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4502 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4503 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4505 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4508 public function loadRelatedMembershipObjects($ids = []) {
4510 SELECT membership_id
4511 FROM civicrm_membership_payment
4512 WHERE contribution_id = %1 ";
4513 $params = [1 => [$this->id
, 'Integer']];
4514 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, []);
4516 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4517 while ($dao->fetch()) {
4518 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4519 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4523 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4524 foreach ($ids['membership'] as $id) {
4526 $membership = new CRM_Member_BAO_Membership();
4527 $membership->id
= $id;
4528 if (!$membership->find(TRUE)) {
4529 throw new Exception("Could not find membership record: $id");
4531 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4532 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4533 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4534 $this->_relatedObjects
['membership'][$membership->id
. '_' . $membership->membership_type_id
] = $membership;
4543 * Get the description (source field) for the recurring contribution.
4545 * @param CRM_Contribute_BAO_Contribution $contribution
4546 * @param int|null $participantID
4549 * @throws \CiviCRM_API3_Exception
4550 * @throws \API_Exception
4552 protected static function getRecurringContributionDescription($contribution, $participantID) {
4553 if (!empty($contribution->source
)) {
4554 return $contribution->source
;
4556 elseif (!empty($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
4557 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', [
4558 'id' => $contribution->contribution_page_id
,
4559 'return' => 'title',
4561 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4563 elseif ($participantID) {
4564 $eventTitle = Participant
::get(FALSE)
4565 ->addSelect('event.title')
4566 ->addWhere('id', '=', (int) $participantID)
4567 ->execute()->first()['event.title'];
4568 return ts('Online Event Registration') . ': ' . $eventTitle;
4570 elseif (!empty($contribution->contribution_recur_id
)) {
4571 return 'recurring contribution';
4577 * Function use to store line item proportionally in in entity financial trxn table
4579 * @param array $trxnParams
4581 * @param int $trxnId
4583 * @param float $contributionTotalAmount
4585 * @throws \CiviCRM_API3_Exception
4587 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4588 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4589 if (!empty($lineItems)) {
4590 // get financial item
4591 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4593 'contribution_total_amount' => $contributionTotalAmount,
4594 'trxn_total_amount' => $trxnParams['total_amount'],
4595 'trxn_id' => $trxnId,
4597 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4602 * Checks if line items total amounts
4603 * match the contribution total amount.
4605 * @param array $params
4606 * array of order params.
4608 * @throws \API_Exception
4610 public static function checkLineItems(&$params) {
4611 $totalAmount = $params['total_amount'] ??
NULL;
4612 $lineItemAmount = 0;
4614 foreach ($params['line_items'] as &$lineItems) {
4615 foreach ($lineItems['line_item'] as &$item) {
4616 if (empty($item['financial_type_id'])) {
4617 $item['financial_type_id'] = $params['financial_type_id'];
4619 $lineItemAmount +
= $item['line_total'] +
($item['tax_amount'] ??
0.00);
4623 if (!isset($totalAmount)) {
4624 $params['total_amount'] = $lineItemAmount;
4627 $currency = $params['currency'] ?? CRM_Core_Config
::singleton()->defaultCurrency
;
4629 if (!CRM_Utils_Money
::equals($totalAmount, $lineItemAmount, $currency)) {
4630 throw new CRM_Contribute_Exception_CheckLineItemsException();
4636 * Get the financial account for the item associated with the new transaction.
4638 * @param array $params
4639 * @param int $default
4643 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
4645 if (!empty($params['financial_account_id'])) {
4646 return $params['financial_account_id'];
4649 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4650 $preferredAccountsRelationships = [
4651 'Refunded' => 'Credit/Contra Revenue Account is',
4652 'Chargeback' => 'Chargeback Account is',
4655 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4656 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4657 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4659 $preferredAccountsRelationships[$contributionStatus]
4667 * ContributionPage values were being imposed onto values.
4669 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4670 * REALLY didn't want superimposed. The rest are left there in their overkill out
4673 * The rationale for making this explicit is that it was a case of carefully set values being
4674 * seemingly randonly overwritten without much care. In general I think array randomly setting
4675 * variables en mass is risky.
4677 * @param array $values
4681 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4682 $contributionPageValues = [];
4683 CRM_Contribute_BAO_ContributionPage
::setValues(
4684 $this->contribution_page_id
,
4685 $contributionPageValues
4688 // These are the values that I believe to be useful.
4691 'pay_later_receipt',
4693 'receipt_from_email',
4694 'receipt_from_name',
4698 'honoree_profile_id',
4699 'onbehalf_profile_id',
4700 'honor_block_is_active',
4701 // Kinda might be - but would be on the contribution...
4704 // Included for 'fear of regression' but can't justify any use for these....
4706 'payment_processor',
4707 'financial_type_id',
4708 'amount_block_is_active',
4713 'default_amount_id',
4717 'initial_amount_help_text',
4718 'initial_amount_label',
4720 'is_allow_other_amount',
4721 'is_billing_required',
4722 'is_confirm_enabled',
4723 'is_credit_card_only',
4725 'is_partial_payment',
4726 'is_recur_installments',
4727 'is_recur_interval',
4731 'min_initial_amount',
4732 'recur_frequency_unit',
4739 foreach ($valuesToCopy as $valueToCopy) {
4740 if (isset($contributionPageValues[$valueToCopy])) {
4741 if ($valueToCopy === 'title') {
4742 $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils
::getContributionPageTitle($this->contribution_page_id
);
4745 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
4753 * Get values of CiviContribute Settings
4754 * and check if its enabled or not.
4755 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
4756 * in serialized form. Usually this should be stored as flat settings for each form fields
4757 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
4758 * settings we will live with an inconsistency because it's too hard to change for now.
4759 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
4762 * @param string $name
4767 public static function checkContributeSettings($name) {
4768 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
4769 return $contributeSettings[$name] ??
NULL;
4773 * Get the contribution as it is in the database before being updated.
4775 * @param int $contributionID
4777 * @return \CRM_Contribute_BAO_Contribution|null
4779 private static function getOriginalContribution($contributionID) {
4780 return self
::getValues(['id' => $contributionID]);
4784 * Get the amount for the financial item row.
4786 * Helper function to start to break down recordFinancialTransactions for readability.
4788 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
4790 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
4791 * for historical reasons. Going forwards we can hope to add tests & improve readibility
4794 * @param array $params
4795 * Params as passed to contribution.create
4797 * @param string $context
4798 * changeFinancialType| changedAmount
4799 * @param array $lineItemDetails
4801 * @param bool $isARefund
4802 * Is this a refund / negative transaction.
4803 * @param int $previousLineItemTotal
4806 * @todo move recordFinancialAccounts & helper functions to their own class?
4809 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
4810 if ($context == 'changedAmount') {
4811 $lineTotal = $lineItemDetails['line_total'];
4812 if ($lineTotal != $previousLineItemTotal) {
4813 $lineTotal -= $previousLineItemTotal;
4817 elseif ($context == 'changeFinancialType') {
4818 return -$lineItemDetails['line_total'];
4820 elseif ($context == 'changedStatus') {
4821 $cancelledTaxAmount = 0;
4823 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
4825 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
4827 elseif ($context === NULL) {
4828 // erm, yes because? but, hey, it's tested.
4829 return $lineItemDetails['line_total'];
4831 elseif (empty($lineItemDetails['line_total'])) {
4832 // follow legacy code path
4834 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', ['civi.tag' => 'deprecated']);
4835 return $params['total_amount'];
4838 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
4843 * Get the multiplier for adjusting rows.
4845 * If we are dealing with a refund or cancellation then it will be a negative
4846 * amount to reflect the negative transaction.
4848 * If we are changing Financial Type it will be a negative amount to
4849 * adjust down the old type.
4851 * @param int $contribution_status_id
4852 * @param string $context
4856 protected static function getMultiplier($contribution_status_id, $context) {
4857 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
4864 * Does this transaction reflect a payment instrument change.
4866 * @param array $params
4867 * @param array $pendingStatuses
4871 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
4872 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
4874 if (array_key_exists('payment_instrument_id', $params)) {
4875 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
4876 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
4878 //check if status is changed from Pending to Completed
4879 // do not update payment instrument changes for Pending to Completed
4880 if (!($contributionStatus == 'Completed' &&
4881 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
4886 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
4887 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
4888 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
4892 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
4893 $params['contribution']->check_number
!= $params['prevContribution']->check_number
4895 // another special case when check number is changed, create new financial records
4896 // create financial trxn with negative amount
4904 * Update the memberships associated with a contribution if it has been completed.
4906 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
4907 * load them in this function. Code clean up would compensate for any minor performance implication.
4909 * @param int $contributionID
4910 * @param string $changeDate
4912 * @throws \CRM_Core_Exception
4913 * @throws \CiviCRM_API3_Exception
4915 public static function updateMembershipBasedOnCompletionOfContribution($contributionID, $changeDate) {
4916 $memberships = self
::getRelatedMemberships($contributionID);
4917 foreach ($memberships as $membership) {
4918 $membershipParams = [
4919 'id' => $membership['id'],
4920 'contact_id' => $membership['contact_id'],
4921 'is_test' => $membership['is_test'],
4922 'membership_type_id' => $membership['membership_type_id'],
4923 'membership_activity_status' => 'Completed',
4926 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4927 $membershipParams['membership_type_id'],
4928 $membershipParams['is_test'],
4929 $membershipParams['id']
4932 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4933 // this picks up membership type changes during renewals
4934 // @todo this is almost certainly an obsolete sql call, the pre-change
4935 // membership is accessible via $this->_relatedObjects
4937 SELECT membership_type_id
4938 FROM civicrm_membership_log
4939 WHERE membership_id={$membershipParams['id']}
4942 $dao = CRM_Core_DAO
::executeQuery($sql);
4943 if ($dao->fetch()) {
4944 if (!empty($dao->membership_type_id
)) {
4945 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4948 if (empty($membership['end_date']) ||
(int) $membership['status_id'] !== CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
4949 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
4950 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
4951 // 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.
4952 // ... except testCompleteTransactionMembershipPriceSetTwoTerms hits this line so the above is obviously not true....
4953 // @todo once apiv4 ships with core switch to that & find sanity.
4954 $membershipParams['num_terms'] = self
::getNumTermsByContributionAndMembershipType(
4955 $membershipParams['membership_type_id'],
4959 // @todo remove all this stuff in favour of letting the api call further down handle in
4960 // (it is a duplication of what the api does).
4961 $dates = array_fill_keys([
4966 if ($currentMembership) {
4968 * Fixed FOR CRM-4433
4969 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4970 * when Contribution mode is notify and membership is for renewal )
4972 // Test cover for this is in testRepeattransactionRenewMembershipOldMembership
4974 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4976 // @todo - we should pass membership_type_id instead of null here but not
4977 // adding as not sure of testing
4978 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4979 $changeDate, NULL, $membershipParams['num_terms']
4981 $dates['join_date'] = $currentMembership['join_date'];
4984 //get the status for membership.
4985 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4987 $dates['join_date'],
4990 $membershipParams['membership_type_id'],
4994 unset($dates['end_date']);
4995 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4996 //we might be renewing membership,
4997 //so make status override false.
4998 $membershipParams['is_override'] = FALSE;
4999 $membershipParams['status_override_end_date'] = 'null';
5000 civicrm_api3('Membership', 'create', $membershipParams);
5005 * Get payment links as they relate to a contribution.
5007 * If a payment can be made then include a payment link & if a refund is appropriate
5008 * then a refund link.
5011 * @param float $balance
5012 * @param string $contributionStatus
5015 * $actionLinks Links array containing:
5019 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
5020 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
5021 // In general the balance is the best way to determine if a payment can be added or not,
5022 // but not for Failed contributions, where we don't accept additional payments at the moment.
5023 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
5024 // do accept more payments agains them.
5029 'url' => CRM_Utils_System
::url('civicrm/payment', [
5035 'title' => ts('Record Payment'),
5038 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
5040 'url' => CRM_Utils_System
::url('civicrm/payment', [
5047 'title' => ts('Submit Credit Card payment'),
5051 'url' => CRM_Utils_System
::url('civicrm/payment', [
5057 'title' => ts('Record Refund'),
5059 return $actionLinks;
5063 * Get a query to determine the amount donated by the contact/s in the current financial year.
5065 * @param array $contactIDs
5069 public static function getAnnualQuery($contactIDs) {
5070 $contactIDs = implode(',', $contactIDs);
5071 $config = CRM_Core_Config
::singleton();
5072 $currentMonth = date('m');
5073 $currentDay = date('d');
5075 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
5077 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
5078 (int) $config->fiscalYearStart
['d'] > $currentDay
5081 $year = date('Y') - 1;
5086 $nextYear = $year +
1;
5088 if ($config->fiscalYearStart
) {
5089 $newFiscalYearStart = $config->fiscalYearStart
;
5090 if ($newFiscalYearStart['M'] < 10) {
5091 // This is just a clumsy way of adding padding.
5092 // @todo next round look for a nicer way.
5093 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
5095 if ($newFiscalYearStart['d'] < 10) {
5096 // This is just a clumsy way of adding padding.
5097 // @todo next round look for a nicer way.
5098 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
5100 $config->fiscalYearStart
= $newFiscalYearStart;
5101 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
5104 // First of January.
5107 $startDate = "$year$monthDay";
5108 $endDate = "$nextYear$monthDay";
5111 'contact_id' => 'IN (' . $contactIDs . ')',
5112 'is_test' => ' = 0',
5113 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
5115 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
5116 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
5119 foreach ($whereClauses as $key => $clause) {
5120 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
5122 $whereClauseString = implode(' AND ', $clauses);
5124 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5125 // this group by + having on contribution_status_id improves performance
5127 SELECT COUNT(*) as count,
5128 SUM(total_amount) as amount,
5129 AVG(total_amount) as average,
5131 FROM civicrm_contribution b
5132 WHERE " . $whereClauseString . "
5133 GROUP BY currency, contribution_status_id
5134 HAVING $havingClause
5140 * Assign Test Value.
5142 * @param string $fieldName
5143 * @param array $fieldDef
5144 * @param int $counter
5146 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5147 if ($fieldName == 'tax_amount') {
5148 $this->{$fieldName} = "0.00";
5150 elseif ($fieldName == 'net_amount') {
5151 $this->{$fieldName} = "2.00";
5153 elseif ($fieldName == 'total_amount') {
5154 $this->{$fieldName} = "3.00";
5156 elseif ($fieldName == 'fee_amount') {
5157 $this->{$fieldName} = "1.00";
5160 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5165 * Check if contribution has participant/membership payment.
5167 * @param int $contributionId
5172 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5173 // get line item for contribution
5174 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5175 // check if line item is for membership or participant
5176 foreach ($lineItems as $items) {
5177 if ($items['entity_table'] == 'civicrm_participant') {
5181 elseif ($items['entity_table'] == 'civicrm_membership') {
5193 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5195 * @param array $trxnParams
5196 * Financial trxn params
5197 * @param array $contributionParams
5198 * Contribution Params
5202 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5203 if (!Civi
::settings()->get('always_post_to_accounts_receivable')) {
5206 $statusId = $contributionParams['contribution']->contribution_status_id
;
5207 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5208 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5209 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5210 // Return if contribution status is not completed.
5211 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5212 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5213 && $contributionParams['prevContribution']->is_pay_later
== 0
5219 $params = $trxnParams;
5220 $financialTypeID = !empty($contributionParams['financial_type_id']) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5221 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5222 $params['to_financial_account_id'] = $arAccountId;
5223 $params['status_id'] = array_search('Pending', $contributionStatuses);
5224 $params['is_payment'] = FALSE;
5225 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5226 self
::$_trxnIDs[] = $trxn->id
;
5227 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5231 * Calculate financial item amount when contribution is updated.
5233 * @param array $params
5234 * contribution params
5235 * @param array $amountParams
5237 * @param string $context
5241 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5242 if (!empty($params['is_quick_config'])) {
5243 $amount = $amountParams['item_amount'];
5245 $amount = $params['total_amount'];
5246 if ($context === NULL) {
5247 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5252 $amount = $amountParams['line_total'];
5253 if ($context == 'changedAmount') {
5254 $amount -= $amountParams['previous_line_total'];
5256 $amount *= $amountParams['diff'];
5262 * Retrieve Sales Tax Financial Accounts.
5268 public static function getSalesTaxFinancialAccounts() {
5269 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5270 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5271 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5272 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5273 $queryParams = [1 => [$accountRel, 'Integer']];
5274 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5275 $financialAccount = [];
5276 while ($dao->fetch()) {
5277 $financialAccount[$dao->id
] = $dao->id
;
5279 return $financialAccount;
5283 * Create tax entry in civicrm_entity_financial_trxn table.
5285 * @param array $entityParams
5287 * @param array $eftParams
5289 * @throws \CiviCRM_API3_Exception
5291 public static function createProportionalEntry($entityParams, $eftParams) {
5293 if ($entityParams['contribution_total_amount'] != 0) {
5294 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5296 // Record Entity Financial Trxn; CRM-20145
5297 $eftParams['amount'] = $paid;
5298 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5302 * Create array of last financial item id's.
5304 * @param int $contributionId
5308 public static function getLastFinancialItemIds($contributionId) {
5309 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5310 FROM civicrm_financial_item fi
5311 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5312 WHERE li.contribution_id = %1";
5313 $dao = CRM_Core_DAO
::executeQuery($sql, [
5319 $ftIds = $taxItems = [];
5320 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5321 while ($dao->fetch()) {
5322 /* if sales tax item*/
5323 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5324 $taxItems[$dao->price_field_value_id
] = [
5325 'financial_item_id' => $dao->id
,
5326 'amount' => $dao->tax_amount
,
5330 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5333 return [$ftIds, $taxItems];
5337 * Create proportional entries in civicrm_entity_financial_trxn.
5339 * @param array $entityParams
5341 * @param array $lineItems
5343 * @param array $ftIds
5345 * @param array $taxItems
5347 * @throws \CiviCRM_API3_Exception
5349 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5351 'entity_table' => 'civicrm_financial_item',
5352 'financial_trxn_id' => $entityParams['trxn_id'],
5354 foreach ($lineItems as $key => $value) {
5355 if ($value['qty'] == 0) {
5358 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5359 $entityParams['line_item_amount'] = $value['line_total'];
5360 self
::createProportionalEntry($entityParams, $eftParams);
5361 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5362 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5363 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5364 self
::createProportionalEntry($entityParams, $eftParams);
5370 * Load entities related to the contribution into $this->_relatedObjects.
5374 * @throws \CRM_Core_Exception
5376 protected function loadRelatedEntitiesByID($ids) {
5378 'contact' => 'CRM_Contact_BAO_Contact',
5379 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5380 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5381 'financialType' => 'CRM_Financial_BAO_FinancialType',
5382 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5384 foreach ($entities as $entity => $bao) {
5385 if (!empty($ids[$entity])) {
5386 $this->_relatedObjects
[$entity] = new $bao();
5387 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5388 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5389 throw new CRM_Core_Exception($entity . ' could not be loaded');
5396 * Function to replace contribution tokens.
5398 * @param array $contributionIds
5400 * @param string $subject
5402 * @param array $subjectToken
5404 * @param string $text
5406 * @param string $html
5408 * @param array $messageToken
5410 * @param bool $escapeSmarty
5413 * @throws \CiviCRM_API3_Exception
5415 public static function replaceContributionTokens(
5424 if (empty($contributionIds)) {
5427 $contributionDetails = [];
5428 foreach ($contributionIds as $id) {
5429 $result = self
::getContributionTokenValues($id, $messageToken);
5430 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5431 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5432 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5434 return $contributionDetails;
5438 * Get the contribution fields for $id and display labels where
5439 * appropriate (if the token is present).
5442 * @param array $messageToken
5445 public static function getContributionTokenValues($id, $messageToken) {
5449 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5450 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5451 if (!empty($messageToken)) {
5452 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5453 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5454 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField
::displayValue($result['values'][$id][$fieldName], $fieldName);
5462 * Get invoice_number for contribution.
5464 * @param int $contributionID
5468 public static function getInvoiceNumber($contributionID) {
5469 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix')) {
5470 return $invoicePrefix . $contributionID;
5477 * Load the values needed for the event message.
5479 * @param int $eventID
5480 * @param int $participantID
5481 * @param int|null $contributionID
5484 * @throws \CRM_Core_Exception
5486 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5491 $values = ['event' => []];
5493 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
5494 // add custom fields for event
5495 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $eventID);
5497 $eventCustomGroup = [];
5498 foreach ($eventGroupTree as $key => $group) {
5499 if ($key === 'info') {
5503 foreach ($group['fields'] as $k => $customField) {
5504 $groupLabel = $group['title'];
5505 if (!empty($customField['customValue'])) {
5506 foreach ($customField['customValue'] as $customFieldValues) {
5507 $eventCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5512 $values['event']['customGroup'] = $eventCustomGroup;
5514 //get participant details
5515 $participantParams = [
5516 'id' => $participantID,
5519 $values['participant'] = [];
5521 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
5522 // add custom fields for event
5523 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $participantID);
5524 $participantCustomGroup = [];
5525 foreach ($participantGroupTree as $key => $group) {
5526 if ($key === 'info') {
5530 foreach ($group['fields'] as $k => $customField) {
5531 $groupLabel = $group['title'];
5532 if (!empty($customField['customValue'])) {
5533 foreach ($customField['customValue'] as $customFieldValues) {
5534 $participantCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5539 $values['participant']['customGroup'] = $participantCustomGroup;
5541 //get location details
5543 'entity_id' => $eventID,
5544 'entity_table' => 'civicrm_event',
5546 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
5549 'entity_table' => 'civicrm_event',
5550 'entity_id' => $eventID,
5551 'module' => 'CiviEvent',
5554 list($custom_pre_id,
5556 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
5558 $values['custom_pre_id'] = $custom_pre_id;
5559 $values['custom_post_id'] = $custom_post_ids;
5561 // set lineItem for event contribution
5562 if ($contributionID) {
5563 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($contributionID);
5564 if (!empty($participantIds)) {
5565 foreach ($participantIds as $pIDs) {
5566 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
5567 if (!CRM_Utils_System
::isNull($lineItem)) {
5568 $values['lineItem'][] = $lineItem;