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\Contribution
;
14 use Civi\Api4\ContributionRecur
;
15 use Civi\Api4\PaymentProcessor
;
16 use Civi\Api4\PledgePayment
;
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 // Get Line Items if we don't have them already.
172 if (empty($params['line_item'])) {
173 if (isset($params['id'])) {
174 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
177 CRM_Price_BAO_LineItem
::getLineItemArray($params);
181 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
182 isset($params['financial_type_id']))) {
183 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
186 CRM_Utils_Hook
::pre($action, 'Contribution', $contributionID, $params);
188 $contribution = new CRM_Contribute_BAO_Contribution();
189 $contribution->copyValues($params);
191 $contribution->id
= $contributionID;
193 if (empty($contribution->id
)) {
194 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
195 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
196 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
200 $result = $contribution->save();
202 // Add financial_trxn details as part of fix for CRM-4724
203 $contribution->trxn_result_code
= $params['trxn_result_code'] ??
NULL;
204 $contribution->payment_processor
= $params['payment_processor'] ??
NULL;
206 //add Account details
207 $params['contribution'] = $contribution;
208 if (empty($params['is_post_payment_create'])) {
209 // If this is being called from the Payment.create api/ BAO then that Entity
210 // takes responsibility for the financial transactions. In fact calling Payment.create
211 // to add payments & having it call completetransaction and / or contribution.create
212 // to update related entities is the preferred flow.
213 // Note that leveraging this parameter for any other code flow is not supported and
214 // is likely to break in future and / or cause serious problems in your data.
215 // https://github.com/civicrm/civicrm-core/pull/14673
216 self
::recordFinancialAccounts($params);
219 if (self
::isUpdateToRecurringContribution($params)) {
220 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
221 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
223 $params['receive_date'] ??
'now'
227 $params['contribution_id'] = $contribution->id
;
229 if (!empty($params['custom']) &&
230 is_array($params['custom'])
232 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
, $action);
235 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
237 CRM_Utils_Hook
::post($action, 'Contribution', $contribution->id
, $contribution);
242 * Is this contribution updating an existing recurring contribution.
244 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
245 * pending payment is being confirmed (or failing).
247 * @param array $params
251 public static function isUpdateToRecurringContribution($params) {
252 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
255 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
258 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
261 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
262 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
269 * Get defaults for new entity.
273 public static function getDefaults() {
275 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
276 FALSE, FALSE, FALSE, 'AND is_default = 1')
278 'contribution_status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
279 'receive_date' => date('Y-m-d H:i:s'),
284 * Fetch the object and store the values in the values array.
286 * @param array $params
287 * Input parameters to find object.
288 * @param array $values
289 * Output values of the object.
291 * The array that holds all the db ids.
293 * @return CRM_Contribute_BAO_Contribution|null
294 * The found object or null
296 public static function getValues($params, &$values = [], &$ids = []) {
297 if (empty($params)) {
300 $contribution = new CRM_Contribute_BAO_Contribution();
302 $contribution->copyValues($params);
304 if ($contribution->find(TRUE)) {
305 $ids['contribution'] = $contribution->id
;
307 CRM_Core_DAO
::storeValues($contribution, $values);
309 return $contribution;
311 // return by reference
317 * Get the values and resolve the most common mappings.
319 * Since contribution status is resolved in almost every function that calls getValues it makes
320 * sense to have an extra function to resolve it rather than repeat the code.
322 * Think carefully before adding more mappings to be resolved as there could be performance implications
323 * if this function starts to be called from more iterative functions.
325 * @param array $params
326 * Input parameters to find object.
329 * Array of the found contribution.
330 * @throws CRM_Core_Exception
332 public static function getValuesWithMappings($params) {
334 $contribution = self
::getValues($params, $values, $ids);
335 if (is_null($contribution)) {
336 throw new CRM_Core_Exception('No contribution found');
338 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
343 * Calculate net_amount & fee_amount if they are not set.
345 * Net amount should be total - fee.
346 * This should only be called for new contributions.
348 * @param array $params
349 * Params for a new contribution before they are saved.
350 * @param int|null $contributionID
351 * Contribution ID if we are dealing with an update.
353 * @throws \CiviCRM_API3_Exception
355 public static function calculateMissingAmountParams(&$params, $contributionID) {
356 if (!$contributionID && (!isset($params['fee_amount']) ||
$params['fee_amount'] === '')) {
357 if (isset($params['total_amount']) && isset($params['net_amount'])) {
358 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
361 $params['fee_amount'] = 0;
364 if (!isset($params['net_amount'])) {
365 if (!$contributionID) {
366 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
369 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
370 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
371 // net_amount may need adjusting.
372 $contribution = civicrm_api3('Contribution', 'getsingle', [
373 'id' => $contributionID,
374 'return' => ['total_amount', 'net_amount', 'fee_amount'],
376 $totalAmount = (isset($params['total_amount']) ?
(float) $params['total_amount'] : (float) CRM_Utils_Array
::value('total_amount', $contribution));
377 $feeAmount = (isset($params['fee_amount']) ?
(float) $params['fee_amount'] : (float) CRM_Utils_Array
::value('fee_amount', $contribution));
378 $params['net_amount'] = $totalAmount - $feeAmount;
386 * @param $billingLocationTypeID
390 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
391 $hasBillingField = FALSE;
400 //build address array
402 $addressParams['location_type_id'] = $billingLocationTypeID;
403 $addressParams['is_billing'] = 1;
405 $billingFirstName = $params['billing_first_name'] ??
NULL;
406 $billingMiddleName = $params['billing_middle_name'] ??
NULL;
407 $billingLastName = $params['billing_last_name'] ??
NULL;
408 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
410 foreach ($billingFields as $value) {
411 $addressParams[$value] = $params["billing_{$value}-{$billingLocationTypeID}"] ??
NULL;
412 if (!empty($addressParams[$value])) {
413 $hasBillingField = TRUE;
416 return [$hasBillingField, $addressParams];
420 * Get address params ready to be passed to the payment processor.
422 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
423 * To create an address we need state_province_id.
425 * @param array $params
426 * @param int $billingLocationTypeID
430 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
431 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
432 foreach ($addressParams as $name => $field) {
433 if (substr($name, 0, 8) == 'billing_') {
434 $addressParams[substr($name, 9)] = $addressParams[$field];
437 return [$hasBillingField, $addressParams];
441 * Get the number of terms for this contribution for a given membership type
442 * based on querying the line item table and relevant price field values
443 * Note that any one contribution should only be able to have one line item relating to a particular membership
446 * @param int $membershipTypeID
448 * @param int $contributionID
452 public static function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
453 $numTerms = CRM_Core_DAO
::singleValueQuery("
454 SELECT membership_num_terms FROM civicrm_line_item li
455 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
456 WHERE contribution_id = %1 AND membership_type_id = %2",
457 [1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']]
459 // default of 1 is precautionary
460 return empty($numTerms) ?
1 : $numTerms;
464 * Takes an associative array and creates a contribution object.
466 * @param array $params
467 * (reference ) an assoc array of name/value pairs.
469 * @return CRM_Contribute_BAO_Contribution
471 * @throws \API_Exception
472 * @throws \CRM_Core_Exception
473 * @throws \CiviCRM_API3_Exception
475 public static function create(&$params) {
477 $transaction = new CRM_Core_Transaction();
480 $contribution = self
::add($params);
482 catch (CRM_Core_Exception
$e) {
483 $transaction->rollback();
487 $params['contribution_id'] = $contribution->id
;
488 $session = CRM_Core_Session
::singleton();
490 if (!empty($params['note'])) {
492 'entity_table' => 'civicrm_contribution',
493 'note' => $params['note'],
494 'entity_id' => $contribution->id
,
495 'contact_id' => $session->get('userID'),
497 if (!$noteParams['contact_id']) {
498 $noteParams['contact_id'] = $params['contact_id'];
500 CRM_Core_BAO_Note
::add($noteParams);
503 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
505 if (!empty($params['id']) && !empty($params['contribution_status_id'])
507 self
::disconnectPledgePaymentsIfCancelled((int) $params['id'], CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution_status_id']));
509 $transaction->commit();
511 if (empty($contribution->contact_id
)) {
512 $contribution->find(TRUE);
515 $isCompleted = ('Completed' === CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
));
516 if (!empty($params['on_behalf'])
519 $existingActivity = Activity
::get(FALSE)->setWhere([
520 ['source_record_id', '=', $contribution->id
],
521 ['activity_type_id:name', '=', 'Contribution'],
522 ])->execute()->first();
524 $campaignParams = isset($params['campaign_id']) ?
['campaign_id' => ($params['campaign_id'] ??
NULL)] : [];
525 $activityParams = array_merge([
526 'activity_type_id:name' => 'Contribution',
527 'source_record_id' => $contribution->id
,
528 'activity_date_time' => $contribution->receive_date
,
529 'is_test' => (bool) $contribution->is_test
,
530 'status_id:name' => $isCompleted ?
'Completed' : 'Scheduled',
531 'skipRecentView' => TRUE,
532 'subject' => CRM_Activity_BAO_Activity
::getActivitySubject($contribution),
533 'id' => $existingActivity['id'] ??
NULL,
535 if (!$activityParams['id']) {
536 // Don't set target contacts on update as these will have been
537 // correctly created and we risk overwriting them with
538 // 'best guess' params.
539 $activityParams['source_contact_id'] = (int) ($params['source_contact_id'] ??
(CRM_Core_Session
::getLoggedInContactID() ?
: $contribution->contact_id
));
540 $activityParams['target_contact_id'] = ($activityParams['source_contact_id'] === (int) $contribution->contact_id
) ?
[] : [$contribution->contact_id
];
542 Activity
::save(FALSE)->addRecord($activityParams)->execute();
545 // do not add to recent items for import, CRM-4399
546 if (empty($params['skipRecentView'])) {
547 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
548 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
550 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
557 $retrieveRequired = 0;
558 foreach ($titleFields as $titleField) {
559 if (!isset($contribution->$titleField)) {
560 $retrieveRequired = 1;
564 if ($retrieveRequired == 1) {
565 $contribution->find(TRUE);
567 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
568 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
571 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
572 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
573 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
577 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
578 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
579 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
583 // add the recently created Contribution
584 CRM_Utils_Recent
::add($title,
588 $contribution->contact_id
,
594 return $contribution;
598 * Get the values for pseudoconstants for name->value and reverse.
600 * @param array $defaults
601 * (reference) the default values, some of which need to be resolved.
602 * @param bool $reverse
603 * True if we want to resolve the values in the reverse direction (value -> name).
605 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
606 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
607 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
608 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'), $reverse);
609 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
613 * Convert associative array names to values and vice-versa.
615 * This function is used by both the web form layer and the api. Note that
616 * the api needs the name => value conversion, also the view layer typically
617 * requires value => name conversion
619 * @param array $defaults
620 * @param string $property
621 * @param array $lookup
622 * @param bool $reverse
626 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
627 $id = $property . '_id';
629 $src = $reverse ?
$property : $id;
630 $dst = $reverse ?
$id : $property;
632 if (!array_key_exists($src, $defaults)) {
636 $look = $reverse ?
array_flip($lookup) : $lookup;
638 if (is_array($look)) {
639 if (!array_key_exists($defaults[$src], $look)) {
643 $defaults[$dst] = $look[$defaults[$src]];
648 * Retrieve DB object based on input parameters.
650 * It also stores all the retrieved values in the default array.
652 * @param array $params
653 * (reference ) an assoc array of name/value pairs.
654 * @param array $defaults
655 * (reference ) an assoc array to hold the name / value pairs.
656 * in a hierarchical manner
658 * (reference) the array that holds all the db ids.
660 * @return CRM_Contribute_BAO_Contribution
662 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
663 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
664 return $contribution;
668 * Combine all the importable fields from the lower levels object.
670 * The ordering is important, since currently we do not have a weight
671 * scheme. Adding weight is super important and should be done in the
672 * next week or so, before this can be called complete.
674 * @param string $contactType
675 * @param bool $status
678 * array of importable Fields
680 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
681 if (!self
::$_importableFields) {
682 if (!self
::$_importableFields) {
683 self
::$_importableFields = [];
687 $fields = ['' => ['title' => ts('- do not import -')]];
690 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
693 $note = CRM_Core_DAO_Note
::import();
694 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
695 unset($tmpFields['option_value']);
696 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
697 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
699 // Using new Dedupe rule.
701 'contact_type' => $contactType,
702 'used' => 'Unsupervised',
704 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
705 $tmpContactField = [];
706 if (is_array($fieldsArray)) {
707 foreach ($fieldsArray as $value) {
708 //skip if there is no dupe rule
709 if ($value == 'none') {
712 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
717 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
718 $tmpContactField[trim($value)] = $contactFields[trim($value)];
720 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
723 $title = $tmpContactField[trim($value)]['title'];
725 $tmpContactField[trim($value)]['title'] = $title;
729 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
730 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
731 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
732 $fields = array_merge($fields, $tmpContactField);
733 $fields = array_merge($fields, $tmpFields);
734 $fields = array_merge($fields, $note);
735 $fields = array_merge($fields, $optionFields);
736 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
737 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
738 self
::$_importableFields = $fields;
740 return self
::$_importableFields;
744 * Combine all the exportable fields from the lower level objects.
746 * @param bool $checkPermission
749 * array of exportable Fields
751 public static function &exportableFields($checkPermission = TRUE) {
752 if (!self
::$_exportableFields) {
753 if (!self
::$_exportableFields) {
754 self
::$_exportableFields = [];
757 $fields = CRM_Contribute_DAO_Contribution
::export();
758 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
759 $fields = array_merge(
761 CRM_Contribute_DAO_Product
::export(),
762 CRM_Contribute_DAO_ContributionProduct
::export(),
763 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
765 'contribution_product_id' => [
766 'title' => ts('Premium'),
767 'name' => 'contribution_product_id',
768 'where' => 'civicrm_product.id',
769 'data_type' => CRM_Utils_Type
::T_INT
,
775 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
777 $contributionPage = [
778 'contribution_page' => [
779 'title' => ts('Contribution Page'),
780 'name' => 'contribution_page',
781 'where' => 'civicrm_contribution_page.title',
782 'data_type' => CRM_Utils_Type
::T_STRING
,
786 $contributionNote = [
787 'contribution_note' => [
788 'title' => ts('Contribution Note'),
789 'name' => 'contribution_note',
790 'data_type' => CRM_Utils_Type
::T_TEXT
,
795 'contribution_batch' => [
796 'title' => ts('Batch Name'),
802 'contribution_campaign_title' => [
803 'title' => ts('Campaign Title'),
804 'name' => 'campaign_title',
805 'where' => 'civicrm_campaign.title',
806 'data_type' => CRM_Utils_Type
::T_STRING
,
809 $softCreditFields = [
810 'contribution_soft_credit_name' => [
811 'name' => 'contribution_soft_credit_name',
812 'title' => ts('Soft Credit For'),
813 'where' => 'civicrm_contact_d.display_name',
814 'data_type' => CRM_Utils_Type
::T_STRING
,
816 'contribution_soft_credit_amount' => [
817 'name' => 'contribution_soft_credit_amount',
818 'title' => ts('Soft Credit Amount'),
819 'where' => 'civicrm_contribution_soft.amount',
820 'data_type' => CRM_Utils_Type
::T_MONEY
,
822 'contribution_soft_credit_type' => [
823 'name' => 'contribution_soft_credit_type',
824 'title' => ts('Soft Credit Type'),
825 'where' => 'contribution_softcredit_type.label',
826 'data_type' => CRM_Utils_Type
::T_STRING
,
828 'contribution_soft_credit_contribution_id' => [
829 'name' => 'contribution_soft_credit_contribution_id',
830 'title' => ts('Soft Credit For Contribution ID'),
831 'where' => 'civicrm_contribution_soft.contribution_id',
832 'data_type' => CRM_Utils_Type
::T_INT
,
834 'contribution_soft_credit_contact_id' => [
835 'name' => 'contribution_soft_credit_contact_id',
836 'title' => ts('Soft Credit For Contact ID'),
837 'where' => 'civicrm_contact_d.id',
838 'data_type' => CRM_Utils_Type
::T_INT
,
842 $fields = array_merge($fields, $contributionPage,
843 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
844 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
847 self
::$_exportableFields = $fields;
850 return self
::$_exportableFields;
854 * Record an activity when a payment is received.
856 * @todo this is intended to be moved to payment BAO class as a protected function
857 * on that class. Currently being cleaned up. The addActivityForPayment doesn't really
858 * merit it's own function as it makes the code less rather than more readable.
860 * @param int $contributionId
861 * @param int $participantId
862 * @param string $totalAmount
863 * @param string $currency
864 * @param string $trxnDate
866 * @throws \CRM_Core_Exception
867 * @throws \CiviCRM_API3_Exception
869 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
870 $activityType = ($totalAmount < 0) ?
'Refund' : 'Payment';
872 if ($participantId) {
873 $inputParams['id'] = $participantId;
876 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
877 $entityObj = $entityObj[$participantId];
878 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
881 $entityObj = new CRM_Contribute_BAO_Contribution();
882 $entityObj->id
= $contributionId;
883 $entityObj->find(TRUE);
884 $title = ts('Contribution');
886 // @todo per block above this is not a logical splitting off of functionality.
887 self
::addActivityForPayment($entityObj->contact_id
, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
891 * Get the value for the To Financial Account.
893 * @param $contribution
898 public static function getToFinancialAccount($contribution, $params) {
899 if (!empty($params['payment_processor_id'])) {
900 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor_id'], NULL, 'civicrm_payment_processor');
902 if (!empty($params['payment_instrument_id'])) {
903 return CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
906 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
907 $queryParams = [1 => [$relationTypeId, 'Integer']];
908 return CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
913 * Get memberships related to the contribution.
915 * @param int $contributionID
919 protected static function getRelatedMemberships($contributionID) {
920 $membershipPayments = civicrm_api3('MembershipPayment', 'get', [
921 'return' => 'membership_id',
922 'contribution_id' => (int) $contributionID,
925 foreach ($membershipPayments as $membershipPayment) {
926 $membershipIDs[] = $membershipPayment['membership_id'];
928 if (empty($membershipIDs)) {
931 // We could combine this with the MembershipPayment.get - we'd
932 // need to re-wrangle the params (here or in the calling function)
933 // as they would then me membership.contact_id, membership.is_test etc
934 return civicrm_api3('Membership', 'get', [
935 'id' => ['IN' => $membershipIDs],
936 'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'],
941 * Do any accounting updates required as a result of a contribution status change.
943 * Currently we have a bit of a roundabout where adding a payment results in this being called &
944 * this may attempt to add a payment. We need to resolve that....
946 * The 'right' way to add payments or refunds is through the Payment.create api. That api
947 * then updates the contribution but this process should not also record another financial trxn.
948 * Currently we have weak detection fot that scenario & where it is detected the first returned
949 * value is FALSE - meaning 'do not continue'.
951 * We should also look at the fact that the calling function - updateFinancialAccounts
952 * bunches together some disparate processes rather than having separate appropriate
955 * @param array $params
958 * Return indicates whether the updateFinancialAccounts function should continue.
960 private static function updateFinancialAccountsOnContributionStatusChange(&$params) {
961 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
962 $currentContributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
964 if ((($previousContributionStatus == 'Partially paid' && $currentContributionStatus == 'Completed')
965 ||
($previousContributionStatus == 'Pending refund' && $currentContributionStatus == 'Completed')
966 // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
967 // why it is here or where it is handled instead.
968 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
969 && $currentContributionStatus == 'Partially paid'))
974 if (self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
)) {
975 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
976 $params['trxnParams']['total_amount'] = -$params['total_amount'];
978 elseif (($previousContributionStatus == 'Pending'
979 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
981 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
982 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
984 if ($currentContributionStatus == 'Cancelled') {
985 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
986 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
987 $params['trxnParams']['total_amount'] = -$params['total_amount'];
990 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
991 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
995 if (($previousContributionStatus == 'Pending'
996 ||
$previousContributionStatus == 'In Progress')
997 && ($currentContributionStatus == 'Completed')
999 if (empty($params['line_item'])) {
1001 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
1002 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
1003 // & this can be removed
1006 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1007 // This is an update so original currency if none passed in.
1008 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
1010 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
1011 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
1012 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1013 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
1015 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
1018 'entity_table' => 'civicrm_financial_item',
1020 foreach ($params['line_item'] as $fieldId => $fields) {
1021 foreach ($fields as $fieldValueId => $lineItemDetails) {
1022 self
::updateFinancialItemForLineItemToPaid($lineItemDetails['id']);
1024 1 => [$lineItemDetails['id'], 'Integer'],
1026 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
1027 while ($financialItem->fetch()) {
1028 $entityParams['entity_id'] = $financialItem->id
;
1029 $entityParams['amount'] = $financialItem->amount
;
1030 foreach (self
::$_trxnIDs as $tID) {
1031 $entityParams['financial_trxn_id'] = $tID;
1032 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
1043 * It is possible to override the membership id that is updated from the payment processor.
1045 * Historically Paypal does this & it still does if it determines data is messed up - see
1046 * https://lab.civicrm.org/dev/membership/issues/13
1048 * Read the comment block on repeattransaction for more information
1049 * about how things should work.
1051 * @param int $contributionID
1052 * @param array $input
1054 * @throws \CiviCRM_API3_Exception
1056 protected static function handleMembershipIDOverride($contributionID, $input) {
1057 if (!empty($input['membership_id'])) {
1058 Civi
::log()->debug('The related membership id has been overridden - this may impact data - see https://github.com/civicrm/civicrm-core/pull/15053');
1059 civicrm_api3('MembershipPayment', 'create', ['contribution_id' => $contributionID, 'membership_id' => $input['membership_id']]);
1064 * Update all financial items related to the line item tto have a status of paid.
1066 * @param int $lineItemID
1068 private static function updateFinancialItemForLineItemToPaid($lineItemID) {
1071 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1074 2 => [$lineItemID, 'Integer'],
1076 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
1077 CRM_Core_DAO
::executeQuery($query, $fparams);
1081 * Create the financial items for the line.
1083 * @param array $params
1084 * @param string $context
1085 * @param array $fields
1086 * @param array $previousLineItems
1087 * @param array $inputParams
1088 * @param bool $isARefund
1089 * @param array $trxnIds
1090 * @param int $fieldId
1094 private static function createFinancialItemsForLine($params, $context, $fields, array $previousLineItems, array $inputParams, bool $isARefund, $trxnIds, $fieldId): array {
1095 foreach ($fields as $fieldValueId => $lineItemDetails) {
1096 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($lineItemDetails['id']);
1097 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
1098 if ($params['contribution']->receive_date
) {
1099 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
1102 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array
::value('financial_account_id', $prevFinancialItem));
1104 $currency = $params['prevContribution']->currency
;
1105 if ($params['contribution']->currency
) {
1106 $currency = $params['contribution']->currency
;
1108 $previousLineItemTotal = CRM_Utils_Array
::value('line_total', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1110 'transaction_date' => $receiveDate,
1111 'contact_id' => $params['prevContribution']->contact_id
,
1112 'currency' => $currency,
1113 'amount' => self
::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
1114 'description' => $prevFinancialItem['description'] ??
NULL,
1115 'status_id' => $prevFinancialItem['status_id'],
1116 'financial_account_id' => $financialAccount,
1117 'entity_table' => 'civicrm_line_item',
1118 'entity_id' => $lineItemDetails['id'],
1120 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1121 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
1122 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
1124 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') ||
($context == 'changeFinancialType')) {
1125 $taxAmount = (float) $lineItemDetails['tax_amount'];
1126 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
1127 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
1128 $taxAmount = CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1130 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
1131 $taxAmount -= CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1133 if ($taxAmount != 0) {
1134 $itemParams['amount'] = self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * $taxAmount;
1135 $itemParams['description'] = CRM_Invoicing_Utils
::getTaxTerm();
1136 if ($lineItemDetails['financial_type_id']) {
1137 $itemParams['financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getSalesTaxFinancialAccount($lineItemDetails['financial_type_id']);
1139 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1147 * Does this contributtion status update represent a refund.
1149 * @param int $previousContributionStatusID
1150 * @param int $currentContributionStatusID
1154 private static function isContributionUpdateARefund($previousContributionStatusID, $currentContributionStatusID): bool {
1155 if ('Completed' !== CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $previousContributionStatusID)) {
1158 return self
::isContributionStatusNegative($currentContributionStatusID);
1162 * Get transaction information about the contribution.
1164 * @param int $contributionId
1165 * @param int $financialTypeID
1169 protected static function getContributionTransactionInformation($contributionId, int $financialTypeID) {
1171 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Expense Account is');
1173 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
1175 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
1177 ft.payment_instrument_id,
1178 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
1180 FROM civicrm_contribution con
1181 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
1182 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
1183 AND ft.to_financial_account_id != %2
1184 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
1185 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
1186 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
1188 WHERE con.id = %1 AND ft.is_payment = 1
1191 1 => [$contributionId, 'Integer'],
1192 2 => [$feeFinancialAccount, 'Integer'],
1194 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
1195 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label');
1197 while ($resultDAO->fetch()) {
1198 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1199 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1200 if ($resultDAO->card_type_id
) {
1201 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
1202 $pantruncation = '';
1203 if ($resultDAO->pan_truncation
) {
1204 $pantruncation = ": {$resultDAO->pan_truncation}";
1206 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
1209 // show payment edit link only for payments done via backoffice form
1210 $paymentEditLink = '';
1211 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
1213 CRM_Core_Action
::UPDATE
=> [
1214 'name' => ts('Edit Payment'),
1215 'icon' => 'fa-pencil',
1216 'url' => 'civicrm/payment/edit',
1217 'class' => 'medium-popup',
1218 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
1219 'title' => ts('Edit Payment'),
1222 $paymentEditLink = CRM_Core_Action
::formLink(
1224 CRM_Core_Action
::mask([CRM_Core_Permission
::EDIT
]),
1226 'id' => $resultDAO->id
,
1227 'contribution_id' => $contributionId,
1231 'Payment.edit.action',
1239 'id' => $resultDAO->id
,
1240 'total_amount' => $resultDAO->total_amount
,
1241 'financial_type' => $resultDAO->financial_account
,
1242 'payment_instrument' => $paidByLabel,
1243 'receive_date' => $resultDAO->trxn_date
,
1244 'trxn_id' => $resultDAO->trxn_id
,
1245 'status' => $statuses[$resultDAO->status_id
],
1246 'currency' => $resultDAO->currency
,
1247 'action' => $paymentEditLink,
1249 if ($paidByName == 'Check') {
1250 $val['check_number'] = $resultDAO->check_number
;
1258 * Should an email receipt be sent for this contribution on completion.
1260 * @param array $input
1261 * @param int $contributionID
1262 * @param int $recurringContributionID
1265 * @throws \API_Exception
1267 protected static function isEmailReceipt(array $input, int $contributionID, $recurringContributionID): bool {
1268 if (isset($input['is_email_receipt'])) {
1269 return (bool) $input['is_email_receipt'];
1271 if ($recurringContributionID) {
1272 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
1273 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
1274 // 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
1275 // Instance that had the table added via an upgrade in 4.1
1276 // see also https://github.com/civicrm/civicrm-svn/commit/7f39befd60bc735408d7866b02b3ac7fff1d4eea#diff-9ad8e290180451a2d6eacbd3d1ca7966R354
1277 // https://lab.civicrm.org/dev/core/issues/1245
1278 return (bool) ContributionRecur
::get(FALSE)->addWhere('id', '=', $recurringContributionID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt'];
1280 $contributionPage = Contribution
::get(FALSE)
1281 ->addSelect('contribution_page.is_email_receipt')
1282 ->addWhere('contribution_page_id', 'IS NOT NULL')
1283 ->addWhere('id', '=', $contributionID)
1284 ->execute()->first();
1286 if (!empty($contributionPage)) {
1287 return (bool) $contributionPage['contribution_page.is_email_receipt'];
1289 // This would be the case for backoffice (where is_email_receipt is not passed in) or events, where Event::sendMail will filter
1295 * Disconnect pledge payments from cancelled or failed contributions.
1297 * If the contribution has been cancelled or has failed check to
1298 * see if it is linked to a pledge and unlink it.
1300 * @param int $pledgePaymentID
1301 * @param string $contributionStatus
1303 * @throws \API_Exception
1304 * @throws \Civi\API\Exception\UnauthorizedException
1306 protected static function disconnectPledgePaymentsIfCancelled(int $pledgePaymentID, $contributionStatus): void
{
1307 if (!in_array($contributionStatus, ['Failed', 'Cancelled'], TRUE)) {
1310 // Check first since just doing an update could be locking under load.
1311 $pledgePayment = PledgePayment
::get(FALSE)
1312 ->addWhere('contribution_id', '=', $pledgePaymentID)
1313 ->setSelect(['id', 'pledge_id', 'scheduled_date', 'scheduled_amount'])
1316 if (!empty($pledgePayment)) {
1317 PledgePayment
::update(FALSE)->setValues([
1318 'contribution_id' => NULL,
1319 'actual_amount' => NULL,
1320 'status_id:name' => 'Pending',
1321 // We need to set these fields for now because the PledgePayment::create
1322 // function doesn't handled updates well at the moment. Test cover
1323 // in testCancelOrderWithPledge.
1324 'scheduled_date' => $pledgePayment['scheduled_date'],
1325 'installment_amount' => $pledgePayment['scheduled_amount'],
1326 'installments' => 1,
1327 'pledge_id' => $pledgePayment['pledge_id'],
1328 ])->addWhere('id', '=', $pledgePayment['id'])->execute();
1335 public function addSelectWhereClause() {
1336 $whereClauses = parent
::addSelectWhereClause();
1337 if ($whereClauses !== []) {
1338 // In this case permisssions have been applied & we assume the
1339 // financialaclreport is applying these
1340 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
1341 return $whereClauses;
1344 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1345 return $whereClauses;
1347 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
1348 if (empty($types)) {
1349 $whereClauses['financial_type_id'] = 'IN (0)';
1352 $whereClauses['financial_type_id'] = [
1353 'IN (' . implode(',', array_keys($types)) . ')',
1356 return $whereClauses;
1360 * @param null $status
1361 * @param null $startDate
1362 * @param null $endDate
1364 * @return array|null
1366 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1370 $where[] = 'contribution_status_id = 1';
1374 $where[] = 'contribution_status_id = 3';
1379 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
1382 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
1384 $financialTypeACLJoin = '';
1385 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1386 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1387 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
1388 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1389 if ($financialTypes) {
1390 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1391 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1394 $where[] = "c.financial_type_id IN (0)";
1398 $whereCond = implode(' AND ', $where);
1401 SELECT sum( total_amount ) as total_amount,
1402 count( c.id ) as total_count,
1404 FROM civicrm_contribution c
1405 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1406 $financialTypeACLJoin
1408 AND ( is_test = 0 OR is_test IS NULL )
1409 AND contact.is_deleted = 0
1413 $dao = CRM_Core_DAO
::executeQuery($query);
1416 while ($dao->fetch()) {
1417 $count +
= $dao->total_count
;
1418 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
1422 'amount' => implode(', ', $amount),
1430 * Delete the indirect records associated with this contribution first.
1434 * @return mixed|null
1435 * $results no of deleted Contribution on success, false otherwise
1437 public static function deleteContribution($id) {
1438 CRM_Utils_Hook
::pre('delete', 'Contribution', $id);
1440 $transaction = new CRM_Core_Transaction();
1443 //delete activity record
1445 'source_record_id' => $id,
1446 // activity type id for contribution
1447 'activity_type_id' => 6,
1450 CRM_Activity_BAO_Activity
::deleteActivity($params);
1452 //delete billing address if exists for this contribution.
1453 self
::deleteAddress($id);
1455 //update pledge and pledge payment, CRM-3961
1456 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1458 // remove entry from civicrm_price_set_entity, CRM-5095
1459 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1460 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1462 // cleanup line items.
1463 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1465 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1466 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1468 if ($participantId) {
1469 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1472 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1476 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1477 $noteId = key($note);
1479 CRM_Core_BAO_Note
::del($noteId, FALSE);
1482 $dao = new CRM_Contribute_DAO_Contribution();
1485 $results = $dao->delete();
1487 $transaction->commit();
1489 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1491 // delete the recently created Contribution
1492 $contributionRecent = [
1494 'type' => 'Contribution',
1496 CRM_Utils_Recent
::del($contributionRecent);
1502 * React to a financial transaction (payment) failure.
1504 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1505 * payments is important for forensic and outreach reasons.
1507 * @param int $contributionID
1508 * @param int $contactID
1509 * @param string $message
1511 * @throws \CiviCRM_API3_Exception
1513 public static function failPayment($contributionID, $contactID, $message) {
1514 civicrm_api3('activity', 'create', [
1515 'activity_type_id' => 'Failed Payment',
1516 'details' => $message,
1517 'subject' => ts('Payment failed at payment processor'),
1518 'source_record_id' => $contributionID,
1519 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() : $contactID,
1522 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1523 civicrm_api3('contribution', 'create', [
1524 'id' => $contributionID,
1525 'contribution_status_id' => 'Failed',
1530 * Check if there is a contribution with the same trxn_id or invoice_id.
1532 * @param array $input
1533 * An assoc array of name/value pairs.
1534 * @param array $duplicates
1535 * (reference) store ids of duplicate contribs.
1539 * true if duplicate, false otherwise
1541 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1543 $id = $input['id'] ??
NULL;
1545 $trxn_id = $input['trxn_id'] ??
NULL;
1546 $invoice_id = $input['invoice_id'] ??
NULL;
1552 $clause[] = "trxn_id = %1";
1553 $input[1] = [$trxn_id, 'String'];
1557 $clause[] = "invoice_id = %2";
1558 $input[2] = [$invoice_id, 'String'];
1561 if (empty($clause)) {
1565 $clause = implode(' OR ', $clause);
1567 $clause = "( $clause ) AND id != %3";
1568 $input[3] = [$id, 'Integer'];
1571 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1572 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1574 while ($dao->fetch()) {
1575 $duplicates[] = $dao->id
;
1582 * Takes an associative array and creates a contribution_product object.
1584 * the function extract all the params it needs to initialize the create a
1585 * contribution_product object. the params array could contain additional unused name/value
1588 * @param array $params
1589 * (reference) an assoc array of name/value pairs.
1591 * @return CRM_Contribute_DAO_ContributionProduct
1593 public static function addPremium(&$params) {
1594 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1595 $contributionProduct->copyValues($params);
1596 return $contributionProduct->save();
1600 * Get list of contribution fields for profile.
1601 * For now we only allow custom contribution fields to be in
1604 * @param bool $addExtraFields
1605 * True if special fields needs to be added.
1608 * the list of contribution fields
1610 public static function getContributionFields($addExtraFields = TRUE) {
1611 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1612 // @todo remove this - this line was added because payment_instrument_id was not
1613 // set to exportable - but now it is.
1614 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1616 if ($addExtraFields) {
1617 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1620 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1622 foreach ($contributionFields as $key => $var) {
1623 if ($key == 'contribution_contact_id') {
1626 elseif ($key == 'contribution_campaign_id') {
1627 $var['title'] = ts('Campaign');
1629 $fields[$key] = $var;
1632 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1637 * Add extra fields specific to contribution.
1639 public static function getSpecialContributionFields() {
1641 'contribution_soft_credit_name' => [
1642 'name' => 'contribution_soft_credit_name',
1643 'title' => ts('Soft Credit Name'),
1644 'headerPattern' => '/^soft_credit_name$/i',
1645 'where' => 'civicrm_contact_d.display_name',
1647 'contribution_soft_credit_email' => [
1648 'name' => 'contribution_soft_credit_email',
1649 'title' => ts('Soft Credit Email'),
1650 'headerPattern' => '/^soft_credit_email$/i',
1651 'where' => 'soft_email.email',
1653 'contribution_soft_credit_phone' => [
1654 'name' => 'contribution_soft_credit_phone',
1655 'title' => ts('Soft Credit Phone'),
1656 'headerPattern' => '/^soft_credit_phone$/i',
1657 'where' => 'soft_phone.phone',
1659 'contribution_soft_credit_contact_id' => [
1660 'name' => 'contribution_soft_credit_contact_id',
1661 'title' => ts('Soft Credit Contact ID'),
1662 'headerPattern' => '/^soft_credit_contact_id$/i',
1663 'where' => 'civicrm_contribution_soft.contact_id',
1665 'contribution_pcp_title' => [
1666 'name' => 'contribution_pcp_title',
1667 'title' => ts('Personal Campaign Page Title'),
1668 'headerPattern' => '/^contribution_pcp_title$/i',
1669 'where' => 'contribution_pcp.title',
1673 return $extraFields;
1677 * @param int $pageID
1681 public static function getCurrentandGoalAmount($pageID) {
1683 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1684 FROM civicrm_contribution_page p,
1685 civicrm_contribution c
1686 WHERE p.id = c.contribution_page_id
1688 AND c.cancel_date is null
1692 $config = CRM_Core_Config
::singleton();
1693 $params = [1 => [$pageID, 'Integer']];
1694 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1696 if ($dao->fetch()) {
1697 return [$dao->goal
, $dao->total
];
1700 return [NULL, NULL];
1705 * Get list of contributions which credit the passed in contact ID.
1707 * The returned array provides details about the original contribution & donor.
1709 * @param int $honorId
1710 * In Honor of Contact ID.
1713 * list of contribution fields
1714 * @todo - this is a confusing function called from one place. It has a test. It would be
1715 * nice to deprecate it.
1718 public static function getHonorContacts($honorId) {
1720 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1721 $honorDAO->contact_id
= $honorId;
1724 $type = CRM_Contribute_PseudoConstant
::financialType();
1726 while ($honorDAO->fetch()) {
1727 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1728 $contributionDAO->id
= $honorDAO->contribution_id
;
1730 if ($contributionDAO->find(TRUE)) {
1731 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1732 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1733 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1734 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1735 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1736 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1737 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1738 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1739 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
, 'label');
1747 * Get the sort name of a contact for a particular contribution.
1750 * Id of the contribution.
1752 * @return null|string
1753 * sort name of the contact if found
1755 public static function sortName($id) {
1756 $id = CRM_Utils_Type
::escape($id, 'Integer');
1759 SELECT civicrm_contact.sort_name
1760 FROM civicrm_contribution, civicrm_contact
1761 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1762 AND civicrm_contribution.id = {$id}
1764 return CRM_Core_DAO
::singleValueQuery($query);
1768 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1770 * @param int|array $contactIDs
1774 public static function annual($contactIDs) {
1775 if (!is_array($contactIDs)) {
1776 // In practice I can't fine any evidence that this function is ever called with
1777 // anything other than a single contact id, but left like this due to .... fear.
1778 $contactIDs = explode(',', $contactIDs);
1781 $query = self
::getAnnualQuery($contactIDs);
1782 $dao = CRM_Core_DAO
::executeQuery($query);
1784 $amount = $average = [];
1785 while ($dao->fetch()) {
1786 if ($dao->count
> 0 && $dao->amount
> 0) {
1787 $count +
= $dao->count
;
1788 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1789 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1795 implode(', ', $amount),
1796 implode(', ', $average),
1803 * Check if there is a contribution with the params passed in.
1805 * Used for trxn_id,invoice_id and contribution_id
1807 * @param array $params
1808 * An assoc array of name/value pairs.
1811 * contribution id if success else NULL
1813 public static function checkDuplicateIds($params) {
1814 $dao = new CRM_Contribute_DAO_Contribution();
1818 foreach ($params as $k => $v) {
1820 $clause[] = "$k = '$v'";
1823 $clause = implode(' AND ', $clause);
1824 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1825 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1827 while ($dao->fetch()) {
1835 * Get the contribution details for component export.
1837 * @param int $exportMode
1839 * @param array $componentIds
1845 public static function getContributionDetails($exportMode, $componentIds) {
1846 $paymentDetails = [];
1847 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1849 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1850 $componentSelect = " civicrm_participant_payment.participant_id id";
1851 $additionalClause = "
1852 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1853 AND civicrm_participant_payment.participant_id {$componentClause} )
1856 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1857 $componentSelect = " civicrm_membership_payment.membership_id id";
1858 $additionalClause = "
1859 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1860 AND civicrm_membership_payment.membership_id {$componentClause} )
1863 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1864 $componentSelect = " civicrm_pledge_payment.id id";
1865 $additionalClause = "
1866 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1867 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1871 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1872 trxn_id, {$componentSelect}
1873 FROM civicrm_contribution
1874 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1875 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1876 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1877 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1878 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1879 AND option_group_contribution_status.id = contribution_status.option_group_id )
1883 $dao = CRM_Core_DAO
::executeQuery($query);
1885 while ($dao->fetch()) {
1886 $paymentDetails[$dao->id
] = [
1887 'total_amount' => $dao->total_amount
,
1888 'contribution_status' => $dao->status
,
1889 'receive_date' => $dao->receive_date
,
1890 'pay_instru' => $dao->payment_instrument
,
1891 'trxn_id' => $dao->trxn_id
,
1895 return $paymentDetails;
1899 * Create address associated with contribution record.
1901 * As long as there is one or more billing field in the parameters we will create the address.
1903 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1906 * @param array $params
1907 * @param int $billingLocationTypeID
1912 public static function createAddress($params, $billingLocationTypeID) {
1913 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1914 if ($hasBillingField) {
1915 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1916 return $address->id
;
1923 * Delete billing address record related contribution.
1925 * @param int $contributionId
1926 * @param int $contactId
1928 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1930 $contactJoin = NULL;
1932 if ($contributionId) {
1933 $clauses[] = "cc.id = {$contributionId}";
1937 $clauses[] = "cco.id = {$contactId}";
1938 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1941 if (empty($clauses)) {
1942 throw new CRM_Core_Exception('No Where clauses defined when deleting address');
1945 $condition = implode(' OR ', $clauses);
1949 FROM civicrm_address ca
1950 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1954 $dao = CRM_Core_DAO
::executeQuery($query);
1956 while ($dao->fetch()) {
1957 $params = ['id' => $dao->id
];
1958 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1963 * This function check online pending contribution associated w/
1964 * Online Event Registration or Online Membership signup.
1966 * @param int $componentId
1967 * Participant/membership id.
1968 * @param string $componentName
1972 * pending contribution id.
1974 public static function checkOnlinePendingContribution($componentId, $componentName) {
1975 $contributionId = NULL;
1976 if (!$componentId ||
1977 !in_array($componentName, ['Event', 'Membership'])
1979 return $contributionId;
1982 if ($componentName == 'Event') {
1983 $idName = 'participant_id';
1984 $componentTable = 'civicrm_participant';
1985 $paymentTable = 'civicrm_participant_payment';
1986 $source = ts('Online Event Registration');
1989 if ($componentName == 'Membership') {
1990 $idName = 'membership_id';
1991 $componentTable = 'civicrm_membership';
1992 $paymentTable = 'civicrm_membership_payment';
1993 $source = ts('Online Contribution');
1996 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1999 SELECT component.id as {$idName},
2000 componentPayment.contribution_id as contribution_id,
2001 contribution.source source,
2002 contribution.contribution_status_id as contribution_status_id,
2003 contribution.is_pay_later as is_pay_later
2004 FROM $componentTable component
2005 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
2006 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
2007 WHERE component.id = {$componentId}";
2009 $dao = CRM_Core_DAO
::executeQuery($query);
2011 while ($dao->fetch()) {
2012 if ($dao->contribution_id
&&
2013 $dao->is_pay_later
&&
2014 $dao->contribution_status_id
== $pendingStatusId &&
2015 strpos($dao->source
, $source) !== FALSE
2017 $contributionId = $dao->contribution_id
;
2021 return $contributionId;
2025 * Update contribution as well as related objects.
2027 * This function by-passes hooks - to address this - don't use this function.
2029 * @param array $params
2031 * @throws CRM_Core_Exception
2032 * @throws \CiviCRM_API3_Exception
2035 * Use api contribute.completetransaction
2036 * For failures use failPayment (preferably exposing by api in the process).
2039 public static function transitionComponents($params) {
2040 // @todo fix the one place that calls this function to use Payment.create
2042 // get minimum required values.
2043 $contactId = $params['contact_id'] ??
NULL;
2044 $componentId = $params['component_id'] ??
NULL;
2045 $componentName = $params['componentName'] ??
NULL;
2046 $contributionId = $params['contribution_id'] ??
NULL;
2047 $contributionStatusId = $params['contribution_status_id'] ??
NULL;
2049 // if we already processed contribution object pass previous status id.
2050 $previousContriStatusId = $params['previous_contribution_status_id'] ??
NULL;
2052 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2054 // we process only ( Completed, Cancelled, or Failed ) contributions.
2055 if (!$contributionId ||
2056 !in_array($contributionStatusId, [
2057 array_search('Completed', $contributionStatuses),
2063 if (!$componentName ||
!$componentId) {
2064 // get the related component details.
2065 $componentDetails = self
::getComponentDetails($contributionId);
2068 $componentDetails['contact_id'] = $contactId;
2069 $componentDetails['component'] = $componentName;
2071 if ($componentName == 'event') {
2072 $componentDetails['participant'] = $componentId;
2075 $componentDetails['membership'] = $componentId;
2079 if (!empty($componentDetails['contact_id'])) {
2080 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2086 // do check for required ids.
2087 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
2093 $input['component'] = $componentDetails['component'] ??
NULL;
2094 $ids['contribution'] = $contributionId;
2095 $ids['contact'] = $componentDetails['contact_id'] ??
NULL;
2096 $ids['membership'] = $componentDetails['membership'] ??
NULL;
2097 $ids['participant'] = $componentDetails['participant'] ??
NULL;
2098 $ids['event'] = $componentDetails['event'] ??
NULL;
2099 $ids['pledge_payment'] = $componentDetails['pledge_payment'] ??
NULL;
2100 $ids['contributionRecur'] = NULL;
2101 $ids['contributionPage'] = NULL;
2103 $contribution = new CRM_Contribute_BAO_Contribution();
2104 $contribution->id
= $ids['contribution'];
2105 $contribution->find();
2107 $contribution->loadRelatedObjects($input, $ids);
2109 $memberships = $contribution->_relatedObjects
['membership'] ??
[];
2110 $participant = $contribution->_relatedObjects
['participant'] ??
[];
2111 $pledgePayment = $contribution->_relatedObjects
['pledge_payment'] ??
[];
2113 $pledgeID = $oldStatus = NULL;
2114 $pledgePaymentIDs = [];
2115 if ($pledgePayment) {
2116 foreach ($pledgePayment as $key => $object) {
2117 $pledgePaymentIDs[] = $object->id
;
2119 $pledgeID = $pledgePayment[0]->pledge_id
;
2122 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
2125 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
2126 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
2131 if ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
2133 // only pending contribution related object processed.
2134 if ($previousContriStatusId &&
2135 !in_array($contributionStatuses[$previousContriStatusId], [
2140 // this is case when we already processed contribution object.
2143 elseif (!$previousContriStatusId &&
2144 !in_array($contributionStatuses[$contribution->contribution_status_id
], [
2149 // this is case when we are going to process contribution object later.
2153 if (is_array($memberships)) {
2154 foreach ($memberships as $membership) {
2159 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
2160 $membership->membership_type_id
,
2161 $membership->is_test
, $membership->id
2164 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2165 // this picks up membership type changes during renewals
2167 SELECT membership_type_id
2168 FROM civicrm_membership_log
2169 WHERE membership_id=$membership->id
2172 $dao = CRM_Core_DAO
::executeQuery($sql);
2173 if ($dao->fetch()) {
2174 if (!empty($dao->membership_type_id
)) {
2175 $membership->membership_type_id
= $dao->membership_type_id
;
2176 $membership->save();
2179 // else fall back to using current membership type
2180 // Figure out number of terms
2182 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
2183 foreach ($lineitems as $lineitem) {
2184 if ($membership->membership_type_id
== ($lineitem['membership_type_id'] ??
NULL)) {
2185 $numterms = $lineitem['membership_num_terms'] ??
NULL;
2187 // in case membership_num_terms comes through as null or zero
2188 $numterms = $numterms >= 1 ?
$numterms : 1;
2193 // CRM-15735-to update the membership status as per the contribution receive date
2195 $oldStatus = $membership->status_id
;
2196 if (!empty($params['receive_date'])) {
2197 $joinDate = $params['receive_date'];
2198 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
2199 $membership->end_date
,
2200 $membership->join_date
,
2201 $params['receive_date'],
2203 $membership->membership_type_id
,
2206 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
2207 $membership->save();
2210 if ($currentMembership) {
2211 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2212 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
2213 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2216 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
2219 //get the status for membership.
2220 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
2222 $dates['join_date'],
2225 $membership->membership_type_id
,
2229 $formattedParams = [
2230 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
2231 array_search('Current', $membershipStatuses)
2233 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
2234 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
2235 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
2238 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
2240 $membership->copyValues($formattedParams);
2241 $membership->save();
2243 //updating the membership log
2244 $membershipLog = [];
2245 $membershipLog = $formattedParams;
2246 $logStartDate = CRM_Utils_Date
::customFormat($dates['log_start_date'] ??
NULL, $format);
2247 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
2249 $membershipLog['start_date'] = $logStartDate;
2250 $membershipLog['membership_id'] = $membership->id
;
2251 $membershipLog['modified_id'] = $membership->contact_id
;
2252 $membershipLog['modified_date'] = date('Ymd');
2253 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
2255 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2257 //update related Memberships.
2258 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2260 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2261 $scheduledActivityID = CRM_Utils_Array
::value('id',
2262 civicrm_api3('Activity', 'Get',
2264 'source_record_id' => $membership->id
,
2265 'activity_type_id' => $activityType,
2266 'status_id' => 'Scheduled',
2269 'sort' => 'id DESC',
2274 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2275 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2276 if ($scheduledActivityID) {
2277 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, ['id' => $scheduledActivityID]);
2282 // track membership status change if any
2283 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
2284 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2285 CRM_Activity_BAO_Activity
::addActivity($membership,
2286 'Change Membership Status',
2289 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2290 'source_contact_id' => $membershipLog['modified_id'],
2291 'priority_id' => 'Normal',
2296 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2302 $updatedStatusId = array_search('Registered', $participantStatuses);
2303 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2306 if ($pledgePayment) {
2307 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2314 * Returns all contribution related object ids.
2316 * @param $contributionId
2320 public static function getComponentDetails($contributionId) {
2321 $componentDetails = $pledgePayment = [];
2322 if (!$contributionId) {
2323 return $componentDetails;
2327 SELECT c.id as contribution_id,
2328 c.contact_id as contact_id,
2329 c.contribution_recur_id,
2330 mp.membership_id as membership_id,
2331 m.membership_type_id as membership_type_id,
2332 pp.participant_id as participant_id,
2333 p.event_id as event_id,
2334 pgp.id as pledge_payment_id
2335 FROM civicrm_contribution c
2336 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2337 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2338 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2339 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2340 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2341 WHERE c.id = $contributionId";
2343 $dao = CRM_Core_DAO
::executeQuery($query);
2344 $componentDetails = [];
2346 while ($dao->fetch()) {
2347 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2348 $componentDetails['contact_id'] = $dao->contact_id
;
2349 if ($dao->event_id
) {
2350 $componentDetails['event'] = $dao->event_id
;
2352 if ($dao->participant_id
) {
2353 $componentDetails['participant'] = $dao->participant_id
;
2355 if ($dao->membership_id
) {
2356 if (!isset($componentDetails['membership'])) {
2357 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2359 $componentDetails['membership'][] = $dao->membership_id
;
2360 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2362 if ($dao->pledge_payment_id
) {
2363 $pledgePayment[] = $dao->pledge_payment_id
;
2365 if ($dao->contribution_recur_id
) {
2366 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2370 if ($pledgePayment) {
2371 $componentDetails['pledge_payment'] = $pledgePayment;
2374 return $componentDetails;
2378 * @param int $contactId
2379 * @param bool $includeSoftCredit
2381 * @return null|string
2383 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2387 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2388 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2389 $liWhere = " AND i.financial_type_id IN (0)";
2390 if (!empty($financialTypes)) {
2391 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2392 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2394 $contactContributionsSQL = "
2395 SELECT contribution.id AS id
2396 FROM civicrm_contribution contribution
2397 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2398 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2402 $contactSoftCreditContributionsSQL = "
2403 SELECT contribution.id
2404 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2405 ON ( contribution.id = softContribution.contribution_id )
2406 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2407 $query = "SELECT count( x.id ) count FROM ( ";
2408 $query .= $contactContributionsSQL;
2410 if ($includeSoftCredit) {
2411 $query .= " UNION ";
2412 $query .= $contactSoftCreditContributionsSQL;
2417 return CRM_Core_DAO
::singleValueQuery($query);
2421 * Repeat a transaction as part of a recurring series.
2424 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2425 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2426 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2427 * and associated entities.
2428 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2429 * which updates the various entities and sends appropriate emails.
2431 * Gaps in the above (@todo)
2432 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2433 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2434 * 3) Repeat transaction duplicates rather than calls Order.create
2435 * 4) Use of payment.create still limited - completetransaction is more common.
2436 * 5) the template transaction is tricky - historically we used the first contribution
2437 * linked to a recurring contribution. More recently that was changed to be the most recent.
2438 * Ideally it would be an actual template - not a contribution used as a template which
2439 * would give more appropriate flexibility. Note line_items have an entity so that table
2440 * could be used for the line item template - the difficulty is the custom fields...
2441 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2442 * to load the membership(s) referred to via line items in the template transactions. Any other
2443 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2444 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2445 * - membership_payment record
2446 * - civicrm_membership.contribution_recur_id
2448 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2449 * of historical processors since this has been handled 'forever' - specifically for paypal.
2450 * albeit by an even nastier mechanism than the current input override.
2451 * The count is out on how correct related entities wind up in this case.
2453 * @param CRM_Contribute_BAO_Contribution $contribution
2454 * @param array $input
2455 * @param array $contributionParams
2457 * @return bool|array
2458 * @throws CiviCRM_API3_Exception
2460 protected static function repeatTransaction(&$contribution, $input, $contributionParams) {
2461 if (!empty($contribution->id
)) {
2465 // Unclear why this would only be set for repeats.
2466 if (!empty($input['amount'])) {
2467 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2470 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2471 'id' => $contributionParams['contribution_recur_id'],
2473 if (!empty($recurringContribution['financial_type_id'])) {
2474 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2475 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2477 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2478 $contributionParams['contribution_recur_id'],
2479 array_intersect_key($contributionParams, [
2480 'total_amount' => TRUE,
2481 'financial_type_id' => TRUE,
2484 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2485 $contributionParams['status_id'] = 'Pending';
2487 if (isset($contributionParams['financial_type_id']) && count($input['line_item']) === 1) {
2488 // We permit the financial type to be overridden for single line items.
2489 // More comments on this are in getTemplateTransaction.
2490 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2493 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2495 foreach (['contact_id', 'currency', 'source', 'amount_level', 'address_id', 'on_behalf', 'source_contact_id', 'tax_amount', 'contribution_page_id'] as $fieldName) {
2496 if (isset($templateContribution[$fieldName])) {
2497 $contributionParams[$fieldName] = $templateContribution[$fieldName];
2500 if (!empty($recurringContribution['campaign_id'])) {
2501 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2502 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2504 if (!isset($contributionParams['campaign_id']) && isset($templateContribution['campaign_id'])) {
2505 // Fall back on value from the previous contribution if not passed in as input
2506 // or loadable from the recurring contribution.
2507 $contributionParams['campaign_id'] = $templateContribution['campaign_id'];
2509 $contributionParams['source'] = $contributionParams['source'] ??
ts('Recurring contribution');
2511 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2512 //do not create CC or BCC emails or profile notifications.
2513 //The if is just to be safe. Not sure if we can ever arrive with this unset
2514 // but per CRM-19478 it seems it can be 'null'
2515 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2516 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2519 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2520 $contribution->id
= $createContribution['id'];
2521 $contribution->copyCustomFields($templateContribution['id'], $contribution->id
);
2522 self
::handleMembershipIDOverride($contribution->id
, $input);
2523 // Add new soft credit against current $contribution.
2524 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($contributionParams['contribution_recur_id'], $createContribution['id']);
2525 return $createContribution;
2529 * Get individual id for onbehalf contribution.
2531 * @param int $contributionId
2533 * @param int $contributorId
2537 * containing organization id and individual id
2539 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2543 if (!$contributionId) {
2547 // fetch contributor id if null
2548 if (!$contributorId) {
2549 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2550 $contributionId, 'contact_id'
2554 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2555 $activityTypeId = array_search('Contribution', $activityTypeIds);
2557 if ($activityTypeId && $contributorId) {
2559 SELECT civicrm_activity_contact.contact_id
2560 FROM civicrm_activity_contact
2561 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2562 WHERE civicrm_activity.activity_type_id = %1
2563 AND civicrm_activity.source_record_id = %2
2564 AND civicrm_activity_contact.record_type_id = %3
2567 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2568 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2571 1 => [$activityTypeId, 'Integer'],
2572 2 => [$contributionId, 'Integer'],
2573 3 => [$sourceID, 'Integer'],
2576 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2578 // for on behalf contribution source is individual and contributor is organization
2579 if ($sourceContactId && $sourceContactId != $contributorId) {
2580 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2581 // get rel type id for employee of relation
2582 foreach ($relationshipTypeIds as $id => $typeVals) {
2583 if ($typeVals['name_a_b'] == 'Employee of') {
2584 $relationshipTypeId = $id;
2589 $rel = new CRM_Contact_DAO_Relationship();
2590 $rel->relationship_type_id
= $relationshipTypeId;
2591 $rel->contact_id_a
= $sourceContactId;
2592 $rel->contact_id_b
= $contributorId;
2593 if ($rel->find(TRUE)) {
2594 $ids['individual_id'] = $rel->contact_id_a
;
2595 $ids['organization_id'] = $rel->contact_id_b
;
2606 public static function getContributionDates() {
2607 $config = CRM_Core_Config
::singleton();
2608 $currentMonth = date('m');
2609 $currentDay = date('d');
2610 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2611 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2612 (int ) $config->fiscalYearStart
['d'] > $currentDay
2615 $year = date('Y') - 1;
2620 $year = ['Y' => $year];
2621 $yearDate = $config->fiscalYearStart
;
2622 $yearDate = array_merge($year, $yearDate);
2623 $yearDate = CRM_Utils_Date
::format($yearDate);
2625 $monthDate = date('Ym') . '01';
2631 'yearDate' => $yearDate,
2632 'monthDate' => $monthDate,
2637 * Load objects relations to contribution object.
2638 * Objects are stored in the $_relatedObjects property
2639 * In the first instance we are just moving functionality from BASEIpn -
2641 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2643 * Note that the unit test for the BaseIPN class tests this function
2645 * @param array $input
2646 * Input as delivered from Payment Processor.
2648 * Ids as Loaded by Payment Processor.
2649 * @param bool $loadAll
2650 * Load all related objects - even where id not passed in? (allows API to call this).
2653 * @throws CRM_Core_Exception
2655 public function loadRelatedObjects($input, &$ids, $loadAll = FALSE) {
2656 // @todo deprecate this function - the steps should be
2657 // 1) add additional functions like 'getRelatedMemberships'
2658 // 2) switch all calls that refer to ->_relatedObjects to
2659 // using the helper functions
2660 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2661 // 4) make ->_relatedObjects protected
2662 // 5) hone up the individual functions to not use rely on this having been called
2663 // 6) deprecate like mad
2665 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2666 if (empty($ids['contact']) && isset($this->contact_id
)) {
2667 $ids['contact'] = $this->contact_id
;
2670 if (empty($this->_component
)) {
2671 if (!empty($ids['event'])) {
2672 $this->_component
= 'event';
2675 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2679 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2680 // refactoring than anything else, and has unit test coverage.
2681 if (empty($this->financial_type_id
)) {
2685 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2690 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2691 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2692 $this->contribution_page_id
,
2695 if ($paymentProcessorID) {
2696 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2700 $ids['contributionType'] = $this->financial_type_id
;
2701 $ids['financialType'] = $this->financial_type_id
;
2702 if ($this->contribution_page_id
) {
2703 $ids['contributionPage'] = $this->contribution_page_id
;
2706 $this->loadRelatedEntitiesByID($ids);
2708 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2709 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2712 if (!empty($ids['pledge_payment'])) {
2713 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2714 if (empty($paymentID)) {
2717 $payment = new CRM_Pledge_BAO_PledgePayment();
2718 $payment->id
= $paymentID;
2719 if (!$payment->find(TRUE)) {
2720 throw new CRM_Core_Exception("Could not find pledge payment record: " . $paymentID);
2722 $this->_relatedObjects
['pledge_payment'][] = $payment;
2726 // These are probably no longer accessed from anywhere
2727 // @todo remove this line, after ensuring not used.
2728 $ids = $this->loadRelatedMembershipObjects($ids);
2730 if ($this->_component
!= 'contribute') {
2731 // we are in event mode
2732 // make sure event exists and is valid
2733 $event = new CRM_Event_BAO_Event();
2734 $event->id
= $ids['event'];
2735 if ($ids['event'] &&
2738 throw new CRM_Core_Exception("Could not find event: " . $ids['event']);
2741 $this->_relatedObjects
['event'] = &$event;
2743 $participant = new CRM_Event_BAO_Participant();
2744 $participant->id
= $ids['participant'];
2745 if ($ids['participant'] &&
2746 !$participant->find(TRUE)
2748 throw new CRM_Core_Exception("Could not find participant: " . $ids['participant']);
2750 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2752 $this->_relatedObjects
['participant'] = &$participant;
2754 // get the payment processor id from event - this is inaccurate see CRM-16923
2755 // in future we should look at throwing an exception here rather than an dubious guess.
2756 if (!$paymentProcessorID) {
2757 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2758 if ($paymentProcessorID) {
2759 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2764 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds($this->id
);
2765 if (!empty($relatedContact['individual_id'])) {
2766 $ids['related_contact'] = $relatedContact['individual_id'];
2769 if ($paymentProcessorID) {
2770 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2771 $this->is_test ?
'test' : 'live'
2773 $ids['paymentProcessor'] = $paymentProcessorID;
2774 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2777 // Add contribution id to $ids. CRM-20401
2778 $ids['contribution'] = $this->id
;
2783 * Create array of message information - ie. return html version, txt version, to field
2785 * @param array $input
2786 * Incoming information.
2787 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2788 * just check presence of recur object but maintaining legacy approach
2791 * IDs of related objects.
2792 * @param array $values
2793 * Any values that may have already been compiled by calling process.
2794 * This is augmented by values 'gathered' by gatherMessageValues
2795 * @param bool $returnMessageText
2796 * Distinguishes between whether to send message or return.
2797 * message text. We are working towards this function ALWAYS returning message text & calling
2798 * function doing emails / pdfs with it
2804 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2805 $this->loadRelatedObjects($input, $ids, TRUE);
2807 if (empty($this->_component
)) {
2808 $this->_component
= $input['component'] ??
NULL;
2811 //not really sure what params might be passed in but lets merge em into values
2812 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2813 $values['is_email_receipt'] = !$returnMessageText;
2814 foreach (['receipt_date', 'cc_receipt', 'bcc_receipt', 'receipt_from_name', 'receipt_from_email', 'receipt_text', 'pay_later_receipt'] as $fld) {
2815 if (!empty($input[$fld])) {
2816 $values[$fld] = $input[$fld];
2820 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2821 //what does recur 'mean here - to do with payment processor return functionality but
2822 // what is the importance
2823 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2824 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2826 $entityID = $entity = NULL;
2827 if (isset($ids['contribution'])) {
2828 $entity = 'contribution';
2829 $entityID = $ids['contribution'];
2831 if (!empty($ids['membership'])) {
2832 //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
2833 // 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
2834 // line having loaded an array
2835 $ids['membership'] = (array) $ids['membership'];
2836 $entity = 'membership';
2837 $entityID = $ids['membership'][0];
2840 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2841 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2842 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2844 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2845 //direct mode showing billing block, so use directIPN for temporary
2846 $template->assign('contributeMode', 'directIPN');
2849 // todo remove strtolower - check consistency
2850 if (strtolower($this->_component
) == 'event') {
2851 $eventParams = ['id' => $this->_relatedObjects
['participant']->event_id
];
2852 $values['event'] = [];
2854 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2856 //get location details
2858 'entity_id' => $this->_relatedObjects
['participant']->event_id
,
2859 'entity_table' => 'civicrm_event',
2861 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2864 'entity_table' => 'civicrm_event',
2865 'entity_id' => $ids['event'],
2866 'module' => 'CiviEvent',
2869 list($custom_pre_id,
2871 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2873 $values['custom_pre_id'] = $custom_pre_id;
2874 $values['custom_post_id'] = $custom_post_ids;
2875 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2876 //and cases involving status updation through ipn
2877 // whatever that means!
2878 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2879 // perhaps we should throw an e-notice if amount is set & force total_amount?
2880 if (!empty($input['amount'])) {
2881 $values['totalAmount'] = $input['amount'];
2883 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2884 if ($values['event']['is_email_confirm']) {
2885 $values['is_email_receipt'] = 1;
2888 if (!empty($ids['contribution'])) {
2889 $values['contributionId'] = $ids['contribution'];
2892 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2893 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2897 $values['contribution_id'] = $this->id
;
2898 if (!empty($ids['related_contact'])) {
2899 $values['related_contact'] = $ids['related_contact'];
2900 if (isset($ids['onbehalf_dupe_alert'])) {
2901 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2904 'contact_id' => $ids['contact'],
2905 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2906 'Home', 'id', 'name'
2909 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2910 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display'] ??
NULL);
2913 if ($this->is_test
) {
2916 if (!empty($this->_relatedObjects
['membership'])) {
2917 foreach ($this->_relatedObjects
['membership'] as $membership) {
2918 if ($membership->id
) {
2919 $values['membership_id'] = $membership->id
;
2920 $values['isMembership'] = TRUE;
2921 $values['membership_assign'] = TRUE;
2923 // need to set the membership values here
2924 $template->assign('membership_name',
2925 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2927 $template->assign('mem_start_date', $membership->start_date
);
2928 $template->assign('mem_join_date', $membership->join_date
);
2929 $template->assign('mem_end_date', $membership->end_date
);
2930 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2931 $template->assign('mem_status', $membership_status);
2932 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2933 $values['is_pay_later'] = 1;
2935 // Pass amount to floatval as string '0.00' is considered a
2936 // valid amount and includes Fee section in the mail.
2937 if (isset($values['amount'])) {
2938 $values['amount'] = floatval($values['amount']);
2941 if (!empty($this->contribution_recur_id
) && $paymentObject) {
2942 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2943 $template->assign('cancelSubscriptionUrl', $url);
2944 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2945 $template->assign('updateSubscriptionBillingUrl', $url);
2946 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2947 $template->assign('updateSubscriptionUrl', $url);
2950 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2953 // otherwise if its about sending emails, continue sending without return, as we
2954 // don't want to exit the loop.
2959 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2965 * Gather values for contribution mail - this function has been created
2966 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2967 * Values related to the contribution in question are gathered
2969 * @param array $input
2970 * Input into function (probably from payment processor).
2971 * @param array $values
2973 * The set of ids related to the input.
2976 * @throws \CRM_Core_Exception
2978 public function _gatherMessageValues($input, &$values, $ids = []) {
2979 // set display address of contributor
2980 $values['billingName'] = '';
2981 if ($this->address_id
) {
2982 $addressDetails = CRM_Core_BAO_Address
::getValues(['id' => $this->address_id
], FALSE, 'id');
2983 $addressDetails = reset($addressDetails);
2984 $values['billingName'] = $addressDetails['name'] ??
'';
2986 // Else we assign the billing address of the contribution contact.
2988 $addressDetails = (array) CRM_Core_BAO_Address
::getValues(['contact_id' => $this->contact_id
, 'is_billing' => 1]);
2989 $addressDetails = reset($addressDetails);
2991 $values['address'] = $addressDetails['display'] ??
'';
2993 if ($this->_component
=== 'contribute') {
2994 //get soft contributions
2995 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2996 if (!empty($softContributions)) {
2997 // For pcp soft credit, there is no 'soft_credit' member it comes
2998 // back in different array members, but shortly after returning from
2999 // this function it calls _assignMessageVariablesToTemplate which does
3000 // its own lookup of any pcp soft credit, so we can skip it here.
3001 $values['softContributions'] = $softContributions['soft_credit'] ??
NULL;
3003 if (isset($this->contribution_page_id
)) {
3004 // This is a call we want to use less, in favour of loading related objects.
3005 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
3006 if ($this->contribution_page_id
) {
3007 // This is precautionary as there are some legacy flows, but it should really be
3009 if (!isset($this->_relatedObjects
['contributionPage'])) {
3010 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id
]);
3012 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($values);
3015 // no contribution page -probably back office
3017 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
3018 $values['title'] = 'Contribution';
3020 // set lineItem for contribution
3022 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
3023 if (!empty($lineItems)) {
3024 $firstLineItem = reset($lineItems);
3026 if (!empty($firstLineItem['price_set_id'])) {
3027 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
3028 'id' => $firstLineItem['price_set_id'],
3029 'return' => 'is_quick_config, id',
3031 $values['priceSetID'] = $priceSet['id'];
3033 foreach ($lineItems as &$eachItem) {
3034 if (isset($this->_relatedObjects
['membership'])
3035 && is_array($this->_relatedObjects
['membership'])
3036 && array_key_exists($eachItem['entity_id'] . '_' . $eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
3037 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->join_date
);
3038 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->start_date
);
3039 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->end_date
);
3041 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
3042 // However, that does create upgrade pain so would be better to be phased in.
3043 $values['useForMember'] = empty($priceSet['is_quick_config']);
3045 $values['lineItem'][0] = $lineItems;
3049 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
3053 // if this is onbehalf of contribution then set related contact
3054 if (!empty($relatedContact['individual_id'])) {
3055 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
3059 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects
['participant']->id
, $this->id
));
3062 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
3065 foreach ($groupTree as $key => $group) {
3066 if ($key === 'info') {
3070 foreach ($group['fields'] as $k => $customField) {
3071 $groupLabel = $group['title'];
3072 if (!empty($customField['customValue'])) {
3073 foreach ($customField['customValue'] as $customFieldValues) {
3074 $customGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
3079 $values['customGroup'] = $customGroup;
3081 $values['is_pay_later'] = $this->is_pay_later
;
3087 * Assign message variables to template but try to break the habit.
3089 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3090 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3091 * multiple recurring payments for processors like IATS that use tokens.
3093 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3094 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
3095 * Note we send directly from this function in some cases because it is only partly refactored.
3097 * Don't call this function directly as the signature will change.
3101 * @param bool $returnMessageText
3105 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
3106 // @todo - this should have a better separation of concerns - ie.
3107 // gatherMessageValues should build an array of values to be assigned to the template
3108 // and this function should assign them (assigning null if not set).
3109 // the way the pcpParams & honor Params section works is a baby-step towards this.
3110 $template = CRM_Core_Smarty
::singleton();
3111 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
3112 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
3113 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
3114 $template->assign('billingName', $values['billingName']);
3116 // For some unit tests contribution cannot contain paymentProcessor information
3117 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
3118 $template->assign('contributeMode', CRM_Core_SelectValues
::contributeMode()[$billingMode] ??
NULL);
3120 //assign honor information to receipt message
3121 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
3124 'soft_credit_type' => NULL,
3125 'honor_block_is_active' => NULL,
3127 if (isset($softRecord['soft_credit'])) {
3128 //if id of contribution page is present
3129 if (!empty($values['id'])) {
3130 $values['honor'] = [
3131 'honor_profile_values' => [],
3132 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3133 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
3136 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3137 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
3140 //offline contribution
3141 $softCreditTypes = $softCredits = [];
3142 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3143 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3144 $softCredits[$key] = [
3145 'Name' => $softCredit['contact_name'],
3146 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
3149 $template->assign('softCreditTypes', $softCreditTypes);
3150 $template->assign('softCredits', $softCredits);
3154 $dao = new CRM_Contribute_DAO_ContributionProduct();
3155 $dao->contribution_id
= $this->id
;
3156 if ($dao->find(TRUE)) {
3157 $premiumId = $dao->product_id
;
3158 $template->assign('option', $dao->product_option
);
3160 $productDAO = new CRM_Contribute_DAO_Product();
3161 $productDAO->id
= $premiumId;
3162 $productDAO->find(TRUE);
3163 $template->assign('selectPremium', TRUE);
3164 $template->assign('product_name', $productDAO->name
);
3165 $template->assign('price', $productDAO->price
);
3166 $template->assign('sku', $productDAO->sku
);
3168 $template->assign('title', $values['title'] ??
NULL);
3169 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
3170 if (!$values['amount'] && isset($this->total_amount
)) {
3171 $values['amount'] = $this->total_amount
;
3176 'pcp_display_in_roll' => NULL,
3177 'pcp_roll_nickname' => NULL,
3178 'pcp_personal_note' => NULL,
3182 if (strtolower($this->_component
) == 'contribute') {
3184 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3185 $softDAO->contribution_id
= $this->id
;
3186 if ($softDAO->find(TRUE)) {
3187 $pcpParams['pcpBlock'] = TRUE;
3188 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
3189 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
3190 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
3192 //assign the pcp page title for email subject
3193 $pcpDAO = new CRM_PCP_DAO_PCP();
3194 $pcpDAO->id
= $softDAO->pcp_id
;
3195 if ($pcpDAO->find(TRUE)) {
3196 $pcpParams['title'] = $pcpDAO->title
;
3200 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3201 $template->assign($templateKey, $templateValue);
3204 if ($this->financial_type_id
) {
3205 $values['financial_type_id'] = $this->financial_type_id
;
3208 $template->assign('trxn_id', $this->trxn_id
);
3209 $template->assign('receive_date',
3210 CRM_Utils_Date
::processDate($this->receive_date
)
3212 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
3213 $template->assign('action', $this->is_test ?
1024 : 1);
3214 $template->assign('receipt_text', $values['receipt_text'] ??
NULL);
3215 $template->assign('is_monetary', 1);
3216 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3217 $template->assign('currency', $this->currency
);
3218 $template->assign('address', CRM_Utils_Address
::format($input));
3219 if (!empty($values['customGroup'])) {
3220 $template->assign('customGroup', $values['customGroup']);
3222 if (!empty($values['softContributions'])) {
3223 $template->assign('softContributions', $values['softContributions']);
3225 if ($this->_component
== 'event') {
3226 $template->assign('title', $values['event']['title']);
3227 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3229 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3230 $viewRoles[] = $participantRoles[$v];
3232 $values['event']['participant_role'] = implode(', ', $viewRoles);
3233 $template->assign('event', $values['event']);
3234 $template->assign('participant', $values['participant']);
3235 $template->assign('location', $values['location']);
3236 $template->assign('customPre', $values['custom_pre_id']);
3237 $template->assign('customPost', $values['custom_post_id']);
3240 if ($this->_relatedObjects
['participant']->is_test
) {
3244 $values['params'] = [];
3245 //to get email of primary participant.
3246 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3247 $primaryAmount[] = [
3248 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3249 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3251 //build an array of cId/pId of participants
3252 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3253 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3254 //send receipt to additional participant if exists
3255 if (count($additionalIDs)) {
3256 $template->assign('isPrimary', 0);
3257 $template->assign('customProfile', NULL);
3258 //set additionalParticipant true
3259 $values['params']['additionalParticipant'] = TRUE;
3260 foreach ($additionalIDs as $pId => $cId) {
3262 //to change the status pending to completed
3263 $additional = new CRM_Event_DAO_Participant();
3264 $additional->id
= $pId;
3265 $additional->contact_id
= $cId;
3266 $additional->find(TRUE);
3267 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3268 $additional->status_id
= 1;
3269 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3270 //if additional participant dont have email
3272 if (!$additionalParticipantInfo) {
3273 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3276 'label' => $additional->fee_level
,
3277 'amount' => $additional->fee_amount
,
3279 $primaryAmount[] = [
3280 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3281 'amount' => $additional->fee_amount
,
3283 $additional->save();
3284 $template->assign('amount', $amount);
3285 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3289 //build an array of custom profile and assigning it to template
3290 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3292 if (count($customProfile)) {
3293 $template->assign('customProfile', $customProfile);
3296 // for primary contact
3297 $values['params']['additionalParticipant'] = FALSE;
3298 $template->assign('isPrimary', 1);
3299 $template->assign('amount', $primaryAmount);
3300 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3301 if ($this->payment_instrument_id
) {
3302 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3303 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3305 // carry paylater, since we did not created billing,
3306 // so need to pull email from primary location, CRM-4395
3307 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3313 * Check whether payment processor supports
3314 * cancellation of contribution subscription
3316 * @param int $contributionId
3319 * @param bool $isNotCancelled
3323 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3324 $cacheKeyString = "$contributionId";
3325 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3327 static $supportsCancel = [];
3329 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3330 $supportsCancel[$cacheKeyString] = FALSE;
3331 $isCancelled = FALSE;
3333 if ($isNotCancelled) {
3334 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3337 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3338 if (!empty($paymentObject)) {
3339 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3342 return $supportsCancel[$cacheKeyString];
3346 * Check whether subscription is already cancelled.
3348 * @param int $contributionId
3352 * contribution status
3354 public static function isSubscriptionCancelled($contributionId) {
3356 SELECT cr.contribution_status_id
3357 FROM civicrm_contribution_recur cr
3358 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3359 WHERE con.id = %1 LIMIT 1";
3360 $params = [1 => [$contributionId, 'Integer']];
3361 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3362 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
3363 if ($status == 'Cancelled') {
3370 * Create all financial accounts entry.
3372 * @param array $params
3373 * Contribution object, line item array and params for trxn.
3376 * @param array $financialTrxnValues
3378 * @return null|\CRM_Core_BAO_FinancialTrxn
3380 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3381 $skipRecords = $update = $return = $isRelatedId = FALSE;
3382 $isUpdate = !empty($params['prevContribution']);
3384 $additionalParticipantId = [];
3385 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3386 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3388 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3389 $entityId = $params['participant_id'];
3390 $entityTable = 'civicrm_participant';
3391 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3393 elseif (!empty($params['membership_id'])) {
3394 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3395 // are created off one contribution should be handled elsewhere
3396 $entityId = $params['membership_id'];
3397 $entityTable = 'civicrm_membership';
3400 $entityId = $params['contribution']->id
;
3401 $entityTable = 'civicrm_contribution';
3404 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3405 $isRelatedId = TRUE;
3408 $entityID[] = $entityId;
3409 if (!empty($additionalParticipantId)) {
3410 $entityID +
= $additionalParticipantId;
3412 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3413 if (empty($params['prevContribution'])) {
3417 $statusId = $params['contribution']->contribution_status_id
;
3419 // build line item array if its not set in $params
3420 if (empty($params['line_item']) ||
$additionalParticipantId) {
3421 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3424 if ($contributionStatus != 'Failed' &&
3425 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3427 $skipRecords = TRUE;
3432 if (in_array($contributionStatus, $pendingStatus)) {
3433 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3434 $params['financial_type_id'],
3435 'Accounts Receivable Account is'
3438 elseif (!empty($params['payment_processor'])) {
3439 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3440 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3441 'id' => $params['payment_processor'],
3442 'return' => 'payment_instrument_id',
3445 elseif (!empty($params['payment_instrument_id'])) {
3446 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3448 // dev/financial#160 - If this is a contribution update, also check for an existing payment_instrument_id.
3449 elseif ($isUpdate && $params['prevContribution']->payment_instrument_id
) {
3450 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount((int) $params['prevContribution']->payment_instrument_id
);
3453 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3454 $queryParams = [1 => [$relationTypeId, 'Integer']];
3455 $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);
3458 $totalAmount = $params['total_amount'] ??
NULL;
3459 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3460 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3462 //build financial transaction params
3464 'contribution_id' => $params['contribution']->id
,
3465 'to_financial_account_id' => $params['to_financial_account_id'],
3466 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3467 'total_amount' => $totalAmount,
3468 'fee_amount' => $params['fee_amount'] ??
NULL,
3469 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3470 'currency' => $params['contribution']->currency
,
3471 'trxn_id' => $params['contribution']->trxn_id
,
3472 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3473 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3474 // this should really default to completed (after discussion).
3475 'status_id' => $statusId,
3476 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3477 'check_number' => $params['check_number'] ??
NULL,
3478 'pan_truncation' => $params['pan_truncation'] ??
NULL,
3479 'card_type_id' => $params['card_type_id'] ??
NULL,
3481 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3482 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3483 if (isset($params['refund_trxn_id'])) {
3484 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3485 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3488 //CRM-16259, set is_payment flag for non pending status
3489 if (!in_array($contributionStatus, $pendingStatus)) {
3490 $trxnParams['is_payment'] = 1;
3492 if (!empty($params['payment_processor'])) {
3493 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3496 if (isset($fromFinancialAccountId)) {
3497 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3500 // consider external values passed for recording transaction entry
3501 if (!empty($financialTrxnValues)) {
3502 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3504 if (empty($trxnParams['payment_processor_id'])) {
3505 unset($trxnParams['payment_processor_id']);
3508 $params['trxnParams'] = $trxnParams;
3512 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3513 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3514 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3515 if (!isset($params['trxnParams']['trxn_id'])) {
3516 // Actually I have no idea why we are overwriting any values from the previous contribution.
3517 // (filling makes sense to me). However, only protecting this value as I really really know we
3518 // don't want this one overwritten.
3520 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3522 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3524 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3525 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3526 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3528 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3529 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3532 //if financial type is changed
3533 if (!empty($params['financial_type_id']) &&
3534 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3536 $accountRelationship = 'Income Account is';
3537 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3538 $accountRelationship = 'Deferred Revenue Account is';
3540 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3541 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3542 if ($oldFinancialAccount != $newFinancialAccount) {
3543 $params['total_amount'] = 0;
3544 // If we have a fee amount set reverse this as well.
3545 if (isset($params['fee_amount'])) {
3546 $params['trxnParams']['fee_amount'] = 0 - $params['fee_amount'];
3548 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3549 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3550 $params['prevContribution']->financial_type_id
, $accountRelationship);
3553 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3554 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3555 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3558 self
::updateFinancialAccounts($params, 'changeFinancialType');
3559 $params['skipLineItem'] = FALSE;
3560 foreach ($params['line_item'] as &$lineItems) {
3561 foreach ($lineItems as &$line) {
3562 $line['financial_type_id'] = $params['financial_type_id'];
3565 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType');
3566 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3567 $params['financial_account_id'] = $newFinancialAccount;
3568 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3569 // Set the transaction fee amount back to the original value for creating the new positive financial trxn.
3570 if (isset($params['fee_amount'])) {
3571 $params['trxnParams']['fee_amount'] = $params['fee_amount'];
3573 self
::updateFinancialAccounts($params);
3574 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE);
3575 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3577 $params['deferred_financial_account_id'] = $newFinancialAccount;
3581 //Update contribution status
3582 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3583 if (!isset($params['refund_trxn_id'])) {
3584 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3585 // gets preference over another so I am only 'protecting' a very specific tested flow
3586 // and letting natural justice take care of the rest.
3587 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3589 if (!empty($params['contribution_status_id']) &&
3590 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3592 //Update Financial Records
3593 $callUpdateFinancialAccounts = self
::updateFinancialAccountsOnContributionStatusChange($params);
3594 if ($callUpdateFinancialAccounts) {
3595 self
::updateFinancialAccounts($params, 'changedStatus');
3596 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus');
3601 // change Payment Instrument for a Completed contribution
3602 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3603 // instrument is null and now new payment instrument is added along with the payment
3604 if (!$params['contribution']->payment_instrument_id
) {
3605 $params['contribution']->find(TRUE);
3607 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3608 $params['trxnParams']['check_number'] = $params['check_number'] ??
NULL;
3610 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3611 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3614 //if Change contribution amount
3615 $params['trxnParams']['fee_amount'] = $params['fee_amount'] ??
NULL;
3616 $params['trxnParams']['net_amount'] = $params['net_amount'] ??
NULL;
3617 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3618 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3619 if (isset($totalAmount) &&
3620 $totalAmount != $params['prevContribution']->total_amount
3622 //Update Financial Records
3623 $params['trxnParams']['from_financial_account_id'] = NULL;
3624 self
::updateFinancialAccounts($params, 'changedAmount');
3625 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount');
3630 // Looks like we might have a data correction update.
3631 // This would be a case where a transaction id has been entered but it is incorrect &
3632 // the person goes back in & fixes it, as opposed to a new transaction.
3633 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3634 // the data fix scenario.
3636 if (isset($params['refund_trxn_id'])) {
3637 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3638 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3639 civicrm_api3('FinancialTrxn', 'create', [
3640 'id' => $refundIDs['financialTrxnId'],
3641 'trxn_id' => $params['refund_trxn_id'],
3645 $cardType = $params['card_type_id'] ??
NULL;
3646 $panTruncation = $params['pan_truncation'] ??
NULL;
3647 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3652 // records finanical trxn and entity financial trxn
3653 // also make it available as return value
3654 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3655 $trxnParams['pan_truncation'] = $params['pan_truncation'] ??
NULL;
3656 $trxnParams['card_type_id'] = $params['card_type_id'] ??
NULL;
3657 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3658 $params['entity_id'] = $financialTxn->id
;
3659 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3660 self
::$_trxnIDs[] = $financialTxn->id
;
3664 // record line items and financial items
3665 if (empty($params['skipLineItem'])) {
3666 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $isUpdate);
3669 // create batch entry if batch_id is passed and
3670 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3671 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3673 'batch_id' => $params['batch_id'],
3674 'entity_table' => 'civicrm_financial_trxn',
3675 'entity_id' => $financialTxn->id
,
3677 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3680 // when a fee is charged
3681 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3682 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3685 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3686 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3688 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3689 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3690 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3692 unset($params['line_item']);
3693 self
::$_trxnIDs = NULL;
3698 * Update all financial accounts entry.
3700 * @param array $params
3701 * Contribution object, line item array and params for trxn.
3703 * @param string $context
3706 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3707 * adds unpredictability.
3710 public static function updateFinancialAccounts(&$params, $context = NULL) {
3712 $inputParams = $params;
3713 $isARefund = self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
);
3715 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3716 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3717 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3720 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3721 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3722 $params['entity_id'] = $trxn->id
;
3724 $itemParams['entity_table'] = 'civicrm_line_item';
3725 $trxnIds['id'] = $params['entity_id'];
3726 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution']->id
);
3727 foreach ($params['line_item'] as $fieldId => $fields) {
3728 $params = self
::createFinancialItemsForLine($params, $context, $fields, $previousLineItems, $inputParams, $isARefund, $trxnIds, $fieldId);
3733 * Is this contribution status a reversal.
3735 * If so we would expect to record a negative value in the financial_trxn table.
3737 * @param int $status_id
3741 public static function isContributionStatusNegative($status_id) {
3742 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3743 return in_array(CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE);
3747 * Check status validation on update of a contribution.
3749 * @param array $values
3750 * Previous form values before submit.
3752 * @param array $fields
3753 * The input form values.
3755 * @param array $errors
3760 public static function checkStatusValidation($values, &$fields, &$errors) {
3761 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3762 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3763 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3767 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3769 'Cancelled' => ['Completed', 'Refunded'],
3770 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3771 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3772 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3773 'Refunded' => ['Cancelled', 'Completed'],
3774 'Partially paid' => ['Completed'],
3775 'Pending refund' => ['Completed', 'Refunded'],
3776 'Failed' => ['Pending'],
3779 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3780 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3782 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3783 1 => $contributionStatuses[$values['contribution_status_id']],
3784 2 => $contributionStatuses[$fields['contribution_status_id']],
3790 * Delete contribution of contact.
3792 * @see https://issues.civicrm.org/jira/browse/CRM-12155
3794 * @param int $contactId
3798 public static function deleteContactContribution($contactId) {
3799 $contribution = new CRM_Contribute_DAO_Contribution();
3800 $contribution->contact_id
= $contactId;
3801 $contribution->find();
3802 while ($contribution->fetch()) {
3803 self
::deleteContribution($contribution->id
);
3808 * Get options for a given contribution field.
3810 * @param string $fieldName
3811 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3812 * @param array $props whatever is known about this dao object.
3814 * @return array|bool
3815 * @see CRM_Core_DAO::buildOptions
3818 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3819 $className = __CLASS__
;
3821 if (isset($props['orderColumn'])) {
3822 $params['orderColumn'] = $props['orderColumn'];
3824 switch ($fieldName) {
3825 // This field is not part of this object but the api supports it
3826 case 'payment_processor':
3827 $className = 'CRM_Contribute_BAO_ContributionPage';
3828 // Filter results by contribution page
3829 if (!empty($props['contribution_page_id'])) {
3830 $page = civicrm_api('contribution_page', 'getsingle', [
3832 'id' => ($props['contribution_page_id']),
3834 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3835 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3839 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3840 case 'honor_type_id':
3841 $className = 'CRM_Contribute_BAO_ContributionSoft';
3842 $fieldName = 'soft_credit_type_id';
3843 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3846 case 'contribution_status_id':
3847 if ($context !== 'validate') {
3848 $params['condition'] = "v.name <> 'Template'";
3851 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3855 * Validate financial type.
3857 * @see https://issues.civicrm.org/jira/browse/CRM-13231
3859 * @param int $financialTypeId
3860 * Financial Type id.
3862 * @param string $relationName
3864 * @return array|bool
3866 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3867 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3869 if (!$financialAccount) {
3870 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3876 * @param int $targetCid
3877 * @param $activityType
3878 * @param string $title
3879 * @param int $contributionId
3880 * @param string $totalAmount
3881 * @param string $currency
3882 * @param string $trxn_date
3884 * @throws \CRM_Core_Exception
3885 * @throws \CiviCRM_API3_Exception
3887 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
3888 $paymentAmount = CRM_Utils_Money
::format($totalAmount, $currency);
3889 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3890 $date = CRM_Utils_Date
::isoToMysql($trxn_date);
3891 // source record id would be the contribution id
3892 $srcRecId = $contributionId;
3896 'source_contact_id' => $targetCid,
3897 'source_record_id' => $srcRecId,
3898 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
3899 'subject' => $subject,
3900 'activity_date_time' => $date,
3901 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
3902 'skipRecentView' => TRUE,
3905 // create activity with target contacts
3906 $session = CRM_Core_Session
::singleton();
3907 $id = $session->get('userID');
3909 $activityParams['source_contact_id'] = $id;
3910 $activityParams['target_contact_id'][] = $targetCid;
3912 civicrm_api3('Activity', 'create', $activityParams);
3916 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3919 * @param string $component
3920 * @param bool $getTrxnInfo
3924 * @throws \CRM_Core_Exception
3925 * @throws \CiviCRM_API3_Exception
3927 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE) {
3928 // @todo deprecate passing in component - always call with contribution.
3929 if ($component == 'event') {
3930 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3932 if (!$contributionId) {
3933 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3934 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3935 $id = $primaryParticipantId;
3937 if (!$contributionId) {
3942 elseif ($component == 'membership') {
3943 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
3946 $contributionId = $id;
3949 // The balance used to be calculated this way - we really want to remove this 'oldCalculation'
3950 // but need to unpick the whole trxn_id it's returning first.
3951 $oldCalculation = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3952 $baseTrxnId = !empty($oldCalculation['trxn_id']) ?
$oldCalculation['trxn_id'] : NULL;
3954 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3955 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3957 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
3959 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
3961 $contribution = civicrm_api3('Contribution', 'getsingle', [
3962 'id' => $contributionId,
3966 'contribution_status_id',
3967 'financial_type_id',
3971 $info['payLater'] = $contribution['is_pay_later'];
3972 $info['contribution_status'] = $contribution['contribution_status'];
3973 $info['currency'] = $contribution['currency'];
3975 $info['total'] = $total;
3976 $info['paid'] = $total - $paymentBalance;
3977 $info['balance'] = $paymentBalance;
3979 $info['component'] = $component;
3980 if ($getTrxnInfo && $baseTrxnId) {
3981 $info['transaction'] = self
::getContributionTransactionInformation($contributionId, $contribution['financial_type_id']);
3984 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
3989 * Get the outstanding balance on a contribution.
3991 * @param int $contributionId
3992 * @param float $contributionTotal
3993 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
3997 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
3998 if ($contributionTotal === NULL) {
3999 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4002 return (float) CRM_Utils_Money
::subtractCurrencies(
4004 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE),
4005 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4010 * Get the tax amount (misnamed function).
4012 * @param array $params
4015 * @throws \CiviCRM_API3_Exception
4017 protected static function checkTaxAmount($params) {
4018 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4020 // Update contribution.
4021 if (!empty($params['id'])) {
4022 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4023 // there are no tax implications - early return.
4024 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4027 if (empty($params['prevContribution'])) {
4028 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4031 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
4032 if (!isset($params[$field])) {
4033 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4034 // Tax amount gets added back on later....
4035 $params['total_amount'] = $params['prevContribution']->total_amount
-
4036 $params['prevContribution']->tax_amount
;
4039 $params[$field] = $params['prevContribution']->$field;
4040 if ($params[$field] != $params['prevContribution']->$field) {
4046 self
::calculateMissingAmountParams($params, $params['id']);
4047 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4048 // Assign tax Amount on update of contribution
4049 if (!empty($params['prevContribution']->tax_amount
)) {
4050 $params['tax_amount'] = 'null';
4051 foreach ($params['line_item'] as $setID => $priceField) {
4052 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4053 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4060 // New Contribution and update of contribution with tax rate financial type
4061 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4062 empty($params['skipLineItem'])) {
4063 $taxRateParams = $taxRates[$params['financial_type_id']];
4064 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams);
4065 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4067 foreach ($params['line_item'] as $setID => $priceField) {
4068 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4069 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4072 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4074 elseif (isset($params['api.line_item.create'])) {
4075 // Update total amount of contribution using lineItem
4076 $taxAmountArray = [];
4077 foreach ($params['api.line_item.create'] as $key => $value) {
4078 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4079 $taxRate = $taxRates[$value['financial_type_id']];
4080 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4081 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4084 $params['tax_amount'] = array_sum($taxAmountArray);
4085 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4092 * Check financial type validation on update of a contribution.
4094 * @param int $financialTypeId
4095 * Value of latest Financial Type.
4097 * @param int $contributionId
4100 * @param array $errors
4105 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4106 if (!empty($financialTypeId)) {
4107 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4108 if ($oldFinancialTypeId == $financialTypeId) {
4112 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4114 '1' => [$contributionId, 'Integer'],
4116 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4117 if ($result->N
> 1) {
4118 $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.');
4123 * Update related pledge payment payments.
4125 * This function has been refactored out of the back office contribution form and may
4126 * still overlap with other functions.
4128 * @param string $action
4129 * @param int $pledgePaymentID
4130 * @param int $contributionID
4131 * @param bool $adjustTotalAmount
4132 * @param float $total_amount
4133 * @param float $original_total_amount
4134 * @param int $contribution_status_id
4135 * @param int $original_contribution_status_id
4137 public static function updateRelatedPledge(
4143 $original_total_amount,
4144 $contribution_status_id,
4145 $original_contribution_status_id
4147 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4151 if ($pledgePaymentID) {
4152 //store contribution id in payment record.
4153 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4156 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4163 if (!$pledgePaymentID) {
4166 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4172 $updatePledgePaymentStatus = FALSE;
4174 // If either the status or the amount has changed we update the pledge status.
4175 if ($action & CRM_Core_Action
::ADD
) {
4176 $updatePledgePaymentStatus = TRUE;
4178 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4179 ($original_total_amount != $total_amount))
4181 $updatePledgePaymentStatus = TRUE;
4184 if ($updatePledgePaymentStatus) {
4185 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4187 $contribution_status_id,
4196 * Is there only one line item attached to the contribution.
4202 * @throws \CiviCRM_API3_Exception
4204 public static function isSingleLineItem($id) {
4205 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
4206 return ($lineItemCount == 1);
4210 * Complete an order.
4212 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4214 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4216 * Moving it out of the BaseIPN class is just the first step.
4218 * @param array $input
4220 * @param \CRM_Contribute_BAO_Contribution $contribution
4221 * @param bool $isPostPaymentCreate
4222 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
4223 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
4224 * transitioning related elements).
4227 * @throws \CRM_Core_Exception
4228 * @throws \CiviCRM_API3_Exception
4230 public static function completeOrder($input, $ids, $contribution, $isPostPaymentCreate = FALSE) {
4231 $transaction = new CRM_Core_Transaction();
4232 // @todo see if we even need this - it's used further down to create an activity
4233 // but the BAO layer should create that - we just need to add a test to cover it & can
4234 // maybe remove $ids altogether.
4235 $participantID = $ids['participant'];
4236 $recurringContributionID = $ids['contributionRecur'];
4238 // Unset ids just to make it clear it's not used again.
4240 // The previous details are used when calculating line items so keep it before any code that 'does something'
4241 if (!empty($contribution->id
)) {
4242 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(['id' => $contribution->id
]);
4244 $inputContributionWhiteList = [
4249 'payment_instrument_id',
4254 'contribution_status_id',
4257 'financial_type_id',
4260 $paymentProcessorId = $input['payment_processor_id'] ??
NULL;
4262 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4264 $contributionParams = array_merge([
4265 'contribution_status_id' => $completedContributionStatusID,
4266 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4269 $contributionParams['payment_processor'] = $paymentProcessorId;
4271 if (empty($contributionParams['payment_instrument_id']) && $paymentProcessorId) {
4272 $contributionParams['payment_instrument_id'] = PaymentProcessor
::get(FALSE)->addWhere('id', '=', $paymentProcessorId)->addSelect('payment_instrument_id')->execute()->first()['payment_instrument_id'];
4275 if ($recurringContributionID) {
4276 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4278 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4280 $contributionResult = self
::repeatTransaction($contribution, $input, $contributionParams);
4281 $contributionID = (int) $contribution->id
;
4283 if ($input['component'] == 'contribute') {
4284 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4285 self
::updateMembershipBasedOnCompletionOfContribution(
4292 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4293 $participantParams['id'] = $participantID;
4294 $participantParams['status_id'] = 'Registered';
4295 civicrm_api3('Participant', 'create', $participantParams);
4299 $contributionParams['id'] = $contributionID;
4300 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
4302 if (!$contributionResult) {
4303 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4306 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4308 $transaction->commit();
4309 \Civi
::log()->info("Contribution {$contributionParams['id']} updated successfully");
4311 // @todo - check if Contribution::create does this, test, remove.
4312 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contributionID, $recurringContributionID,
4313 $contributionParams['contribution_status_id'], $input['amount']);
4315 if (self
::isEmailReceipt($input, $contributionID, $recurringContributionID)) {
4316 civicrm_api3('Contribution', 'sendconfirmation', [
4317 'id' => $contributionID,
4318 'payment_processor_id' => $paymentProcessorId,
4320 \Civi
::log()->info("Contribution {$contributionParams['id']} Receipt sent");
4323 return $contributionResult;
4327 * Send receipt from contribution.
4329 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4331 * Note that the compose message part has been moved to contribution
4332 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4334 * @param array $input
4335 * Incoming data from Payment processor.
4337 * Related object IDs.
4338 * @param int $contributionID
4339 * @param bool $returnMessageText
4340 * Should text be returned instead of sent. This.
4341 * is because the function is also used to generate pdfs
4344 * @throws \CRM_Core_Exception
4345 * @throws \CiviCRM_API3_Exception
4346 * @throws \Exception
4348 public static function sendMail($input, $ids, $contributionID, $returnMessageText = FALSE) {
4350 $contribution = new CRM_Contribute_BAO_Contribution();
4351 $contribution->id
= $contributionID;
4352 if (!$contribution->find(TRUE)) {
4353 throw new CRM_Core_Exception('Contribution does not exist');
4355 // set receipt from e-mail and name in value
4356 if (!$returnMessageText) {
4357 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4359 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4360 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4361 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4362 civicrm_api3('Contribution', 'create', [
4363 'receipt_date' => 'now',
4364 'id' => $contribution->id
,
4371 * Generate From email and from name in an array values
4373 * @param array $input
4374 * @param \CRM_Contribute_BAO_Contribution $contribution
4378 public static function generateFromEmailAndName($input, $contribution) {
4379 // Use input value if supplied.
4380 if (!empty($input['receipt_from_email'])) {
4382 CRM_Utils_Array
::value('receipt_from_name', $input, ''),
4383 $input['receipt_from_email'],
4386 // if we are still empty see if we can use anything from a contribution page.
4388 if (!empty($contribution->contribution_page_id
)) {
4389 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id
]);
4391 // if we are still empty see if we can use anything from a contribution page.
4392 if (!empty($pageValues['receipt_from_email'])) {
4394 CRM_Utils_Array
::value('receipt_from_name', $pageValues),
4395 $pageValues['receipt_from_email'],
4398 // If we are still empty fall back to the domain or logged in user information.
4399 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4403 * Load related memberships.
4407 * @return array $ids
4412 * Note that in theory it should be possible to retrieve these from the line_item table
4413 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4414 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4415 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4416 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4418 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4421 public function loadRelatedMembershipObjects($ids = []) {
4423 SELECT membership_id
4424 FROM civicrm_membership_payment
4425 WHERE contribution_id = %1 ";
4426 $params = [1 => [$this->id
, 'Integer']];
4427 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, []);
4429 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4430 while ($dao->fetch()) {
4431 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4432 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4436 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4437 foreach ($ids['membership'] as $id) {
4439 $membership = new CRM_Member_BAO_Membership();
4440 $membership->id
= $id;
4441 if (!$membership->find(TRUE)) {
4442 throw new Exception("Could not find membership record: $id");
4444 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4445 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4446 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4447 $this->_relatedObjects
['membership'][$membership->id
. '_' . $membership->membership_type_id
] = $membership;
4456 * Function use to store line item proportionally in in entity financial trxn table
4458 * @param array $trxnParams
4460 * @param int $trxnId
4462 * @param float $contributionTotalAmount
4464 * @throws \CiviCRM_API3_Exception
4466 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4467 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4468 if (!empty($lineItems)) {
4469 // get financial item
4470 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4472 'contribution_total_amount' => $contributionTotalAmount,
4473 'trxn_total_amount' => $trxnParams['total_amount'],
4474 'trxn_id' => $trxnId,
4476 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4481 * Checks if line items total amounts
4482 * match the contribution total amount.
4484 * @param array $params
4485 * array of order params.
4487 * @throws \API_Exception
4489 public static function checkLineItems(&$params) {
4490 $totalAmount = $params['total_amount'] ??
NULL;
4491 $lineItemAmount = 0;
4493 foreach ($params['line_items'] as &$lineItems) {
4494 foreach ($lineItems['line_item'] as &$item) {
4495 if (empty($item['financial_type_id'])) {
4496 $item['financial_type_id'] = $params['financial_type_id'];
4498 $lineItemAmount +
= $item['line_total'] +
($item['tax_amount'] ??
0.00);
4502 if (!isset($totalAmount)) {
4503 $params['total_amount'] = $lineItemAmount;
4506 $currency = $params['currency'] ?? CRM_Core_Config
::singleton()->defaultCurrency
;
4508 if (!CRM_Utils_Money
::equals($totalAmount, $lineItemAmount, $currency)) {
4509 throw new CRM_Contribute_Exception_CheckLineItemsException();
4515 * Get the financial account for the item associated with the new transaction.
4517 * @param array $params
4518 * @param int $default
4522 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
4524 if (!empty($params['financial_account_id'])) {
4525 return $params['financial_account_id'];
4528 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4529 $preferredAccountsRelationships = [
4530 'Refunded' => 'Credit/Contra Revenue Account is',
4531 'Chargeback' => 'Chargeback Account is',
4534 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4535 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4536 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4538 $preferredAccountsRelationships[$contributionStatus]
4546 * ContributionPage values were being imposed onto values.
4548 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4549 * REALLY didn't want superimposed. The rest are left there in their overkill out
4552 * The rationale for making this explicit is that it was a case of carefully set values being
4553 * seemingly randonly overwritten without much care. In general I think array randomly setting
4554 * variables en mass is risky.
4556 * @param array $values
4560 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4561 $contributionPageValues = [];
4562 CRM_Contribute_BAO_ContributionPage
::setValues(
4563 $this->contribution_page_id
,
4564 $contributionPageValues
4567 // These are the values that I believe to be useful.
4570 'pay_later_receipt',
4572 'receipt_from_email',
4573 'receipt_from_name',
4577 'honoree_profile_id',
4578 'onbehalf_profile_id',
4579 'honor_block_is_active',
4580 // Kinda might be - but would be on the contribution...
4583 // Included for 'fear of regression' but can't justify any use for these....
4585 'payment_processor',
4586 'financial_type_id',
4587 'amount_block_is_active',
4592 'default_amount_id',
4596 'initial_amount_help_text',
4597 'initial_amount_label',
4599 'is_allow_other_amount',
4600 'is_billing_required',
4601 'is_confirm_enabled',
4602 'is_credit_card_only',
4604 'is_partial_payment',
4605 'is_recur_installments',
4606 'is_recur_interval',
4610 'min_initial_amount',
4611 'recur_frequency_unit',
4618 foreach ($valuesToCopy as $valueToCopy) {
4619 if (isset($contributionPageValues[$valueToCopy])) {
4620 if ($valueToCopy === 'title') {
4621 $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils
::getContributionPageTitle($this->contribution_page_id
);
4624 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
4632 * Get values of CiviContribute Settings
4633 * and check if its enabled or not.
4634 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
4635 * in serialized form. Usually this should be stored as flat settings for each form fields
4636 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
4637 * settings we will live with an inconsistency because it's too hard to change for now.
4638 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
4641 * @param string $name
4646 public static function checkContributeSettings($name) {
4647 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
4648 return $contributeSettings[$name] ??
NULL;
4652 * Get the contribution as it is in the database before being updated.
4654 * @param int $contributionID
4656 * @return \CRM_Contribute_BAO_Contribution|null
4658 private static function getOriginalContribution($contributionID) {
4659 return self
::getValues(['id' => $contributionID]);
4663 * Get the amount for the financial item row.
4665 * Helper function to start to break down recordFinancialTransactions for readability.
4667 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
4669 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
4670 * for historical reasons. Going forwards we can hope to add tests & improve readibility
4673 * @param array $params
4674 * Params as passed to contribution.create
4676 * @param string $context
4677 * changeFinancialType| changedAmount
4678 * @param array $lineItemDetails
4680 * @param bool $isARefund
4681 * Is this a refund / negative transaction.
4682 * @param int $previousLineItemTotal
4685 * @todo move recordFinancialAccounts & helper functions to their own class?
4688 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
4689 if ($context == 'changedAmount') {
4690 $lineTotal = $lineItemDetails['line_total'];
4691 if ($lineTotal != $previousLineItemTotal) {
4692 $lineTotal -= $previousLineItemTotal;
4696 elseif ($context == 'changeFinancialType') {
4697 return -$lineItemDetails['line_total'];
4699 elseif ($context == 'changedStatus') {
4700 $cancelledTaxAmount = 0;
4702 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
4704 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
4706 elseif ($context === NULL) {
4707 // erm, yes because? but, hey, it's tested.
4708 return $lineItemDetails['line_total'];
4710 elseif (empty($lineItemDetails['line_total'])) {
4711 // follow legacy code path
4712 CRM_Core_Error
::deprecatedWarning('Deprecated bit of code, please log a ticket explaining how you got here!');
4713 return $params['total_amount'];
4716 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
4721 * Get the multiplier for adjusting rows.
4723 * If we are dealing with a refund or cancellation then it will be a negative
4724 * amount to reflect the negative transaction.
4726 * If we are changing Financial Type it will be a negative amount to
4727 * adjust down the old type.
4729 * @param int $contribution_status_id
4730 * @param string $context
4734 protected static function getMultiplier($contribution_status_id, $context) {
4735 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
4742 * Does this transaction reflect a payment instrument change.
4744 * @param array $params
4745 * @param array $pendingStatuses
4749 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
4750 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
4752 if (array_key_exists('payment_instrument_id', $params)) {
4753 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
4754 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
4756 //check if status is changed from Pending to Completed
4757 // do not update payment instrument changes for Pending to Completed
4758 if (!($contributionStatus == 'Completed' &&
4759 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
4764 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
4765 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
4766 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
4770 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
4771 $params['contribution']->check_number
!= $params['prevContribution']->check_number
4773 // another special case when check number is changed, create new financial records
4774 // create financial trxn with negative amount
4782 * Update the memberships associated with a contribution if it has been completed.
4784 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
4785 * load them in this function. Code clean up would compensate for any minor performance implication.
4787 * @param int $contributionID
4788 * @param string $changeDate
4790 * @throws \CRM_Core_Exception
4791 * @throws \CiviCRM_API3_Exception
4793 public static function updateMembershipBasedOnCompletionOfContribution($contributionID, $changeDate) {
4794 $memberships = self
::getRelatedMemberships($contributionID);
4795 foreach ($memberships as $membership) {
4796 $membershipParams = [
4797 'id' => $membership['id'],
4798 'contact_id' => $membership['contact_id'],
4799 'is_test' => $membership['is_test'],
4800 'membership_type_id' => $membership['membership_type_id'],
4801 'membership_activity_status' => 'Completed',
4804 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4805 $membershipParams['membership_type_id'],
4806 $membershipParams['is_test'],
4807 $membershipParams['id']
4810 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4811 // this picks up membership type changes during renewals
4812 // @todo this is almost certainly an obsolete sql call, the pre-change
4813 // membership is accessible via $this->_relatedObjects
4815 SELECT membership_type_id
4816 FROM civicrm_membership_log
4817 WHERE membership_id={$membershipParams['id']}
4820 $dao = CRM_Core_DAO
::executeQuery($sql);
4821 if ($dao->fetch()) {
4822 if (!empty($dao->membership_type_id
)) {
4823 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4826 if (empty($membership['end_date']) ||
(int) $membership['status_id'] !== CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
4827 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
4828 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
4829 // 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.
4830 // ... except testCompleteTransactionMembershipPriceSetTwoTerms hits this line so the above is obviously not true....
4831 // @todo once apiv4 ships with core switch to that & find sanity.
4832 $membershipParams['num_terms'] = self
::getNumTermsByContributionAndMembershipType(
4833 $membershipParams['membership_type_id'],
4837 // @todo remove all this stuff in favour of letting the api call further down handle in
4838 // (it is a duplication of what the api does).
4839 $dates = array_fill_keys([
4844 if ($currentMembership) {
4846 * Fixed FOR CRM-4433
4847 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4848 * when Contribution mode is notify and membership is for renewal )
4850 // Test cover for this is in testRepeattransactionRenewMembershipOldMembership
4852 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4854 // @todo - we should pass membership_type_id instead of null here but not
4855 // adding as not sure of testing
4856 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4857 $changeDate, NULL, $membershipParams['num_terms']
4859 $dates['join_date'] = $currentMembership['join_date'];
4862 //get the status for membership.
4863 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4865 $dates['join_date'],
4868 $membershipParams['membership_type_id'],
4872 unset($dates['end_date']);
4873 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4874 //we might be renewing membership,
4875 //so make status override false.
4876 $membershipParams['is_override'] = FALSE;
4877 $membershipParams['status_override_end_date'] = 'null';
4878 civicrm_api3('Membership', 'create', $membershipParams);
4883 * Get payment links as they relate to a contribution.
4885 * If a payment can be made then include a payment link & if a refund is appropriate
4886 * then a refund link.
4889 * @param float $balance
4890 * @param string $contributionStatus
4893 * $actionLinks Links array containing:
4897 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
4898 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
4899 // In general the balance is the best way to determine if a payment can be added or not,
4900 // but not for Failed contributions, where we don't accept additional payments at the moment.
4901 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
4902 // do accept more payments agains them.
4907 'url' => CRM_Utils_System
::url('civicrm/payment', [
4913 'title' => ts('Record Payment'),
4916 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
4918 'url' => CRM_Utils_System
::url('civicrm/payment', [
4925 'title' => ts('Submit Credit Card payment'),
4929 'url' => CRM_Utils_System
::url('civicrm/payment', [
4935 'title' => ts('Record Refund'),
4937 return $actionLinks;
4941 * Get a query to determine the amount donated by the contact/s in the current financial year.
4943 * @param array $contactIDs
4947 public static function getAnnualQuery($contactIDs) {
4948 $contactIDs = implode(',', $contactIDs);
4949 $config = CRM_Core_Config
::singleton();
4950 $currentMonth = date('m');
4951 $currentDay = date('d');
4953 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
4955 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
4956 (int) $config->fiscalYearStart
['d'] > $currentDay
4959 $year = date('Y') - 1;
4964 $nextYear = $year +
1;
4966 if ($config->fiscalYearStart
) {
4967 $newFiscalYearStart = $config->fiscalYearStart
;
4968 if ($newFiscalYearStart['M'] < 10) {
4969 // This is just a clumsy way of adding padding.
4970 // @todo next round look for a nicer way.
4971 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
4973 if ($newFiscalYearStart['d'] < 10) {
4974 // This is just a clumsy way of adding padding.
4975 // @todo next round look for a nicer way.
4976 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
4978 $config->fiscalYearStart
= $newFiscalYearStart;
4979 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
4982 // First of January.
4985 $startDate = "$year$monthDay";
4986 $endDate = "$nextYear$monthDay";
4989 'contact_id' => 'IN (' . $contactIDs . ')',
4990 'is_test' => ' = 0',
4991 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
4993 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4994 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
4997 foreach ($whereClauses as $key => $clause) {
4998 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
5000 $whereClauseString = implode(' AND ', $clauses);
5002 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5003 // this group by + having on contribution_status_id improves performance
5005 SELECT COUNT(*) as count,
5006 SUM(total_amount) as amount,
5007 AVG(total_amount) as average,
5009 FROM civicrm_contribution b
5010 WHERE " . $whereClauseString . "
5011 GROUP BY currency, contribution_status_id
5012 HAVING $havingClause
5018 * Assign Test Value.
5020 * @param string $fieldName
5021 * @param array $fieldDef
5022 * @param int $counter
5024 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5025 if ($fieldName == 'tax_amount') {
5026 $this->{$fieldName} = "0.00";
5028 elseif ($fieldName == 'net_amount') {
5029 $this->{$fieldName} = "2.00";
5031 elseif ($fieldName == 'total_amount') {
5032 $this->{$fieldName} = "3.00";
5034 elseif ($fieldName == 'fee_amount') {
5035 $this->{$fieldName} = "1.00";
5038 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5043 * Check if contribution has participant/membership payment.
5045 * @param int $contributionId
5050 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5051 // get line item for contribution
5052 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5053 // check if line item is for membership or participant
5054 foreach ($lineItems as $items) {
5055 if ($items['entity_table'] == 'civicrm_participant') {
5059 elseif ($items['entity_table'] == 'civicrm_membership') {
5071 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5073 * @param array $trxnParams
5074 * Financial trxn params
5075 * @param array $contributionParams
5076 * Contribution Params
5080 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5081 if (!Civi
::settings()->get('always_post_to_accounts_receivable')) {
5084 $statusId = $contributionParams['contribution']->contribution_status_id
;
5085 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5086 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5087 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5088 // Return if contribution status is not completed.
5089 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5090 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5091 && $contributionParams['prevContribution']->is_pay_later
== 0
5097 $params = $trxnParams;
5098 $financialTypeID = !empty($contributionParams['financial_type_id']) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5099 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5100 $params['to_financial_account_id'] = $arAccountId;
5101 $params['status_id'] = array_search('Pending', $contributionStatuses);
5102 $params['is_payment'] = FALSE;
5103 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5104 self
::$_trxnIDs[] = $trxn->id
;
5105 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5109 * Calculate financial item amount when contribution is updated.
5111 * @param array $params
5112 * contribution params
5113 * @param array $amountParams
5115 * @param string $context
5119 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5120 if (!empty($params['is_quick_config'])) {
5121 $amount = $amountParams['item_amount'];
5123 $amount = $params['total_amount'];
5124 if ($context === NULL) {
5125 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5130 $amount = $amountParams['line_total'];
5131 if ($context == 'changedAmount') {
5132 $amount -= $amountParams['previous_line_total'];
5134 $amount *= $amountParams['diff'];
5140 * Retrieve Sales Tax Financial Accounts.
5146 public static function getSalesTaxFinancialAccounts() {
5147 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5148 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5149 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5150 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5151 $queryParams = [1 => [$accountRel, 'Integer']];
5152 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5153 $financialAccount = [];
5154 while ($dao->fetch()) {
5155 $financialAccount[$dao->id
] = $dao->id
;
5157 return $financialAccount;
5161 * Create tax entry in civicrm_entity_financial_trxn table.
5163 * @param array $entityParams
5165 * @param array $eftParams
5167 * @throws \CiviCRM_API3_Exception
5169 public static function createProportionalEntry($entityParams, $eftParams) {
5171 if ($entityParams['contribution_total_amount'] != 0) {
5172 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5174 // Record Entity Financial Trxn; CRM-20145
5175 $eftParams['amount'] = $paid;
5176 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5180 * Create array of last financial item id's.
5182 * @param int $contributionId
5186 public static function getLastFinancialItemIds($contributionId) {
5187 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5188 FROM civicrm_financial_item fi
5189 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5190 WHERE li.contribution_id = %1";
5191 $dao = CRM_Core_DAO
::executeQuery($sql, [
5197 $ftIds = $taxItems = [];
5198 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5199 while ($dao->fetch()) {
5200 /* if sales tax item*/
5201 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5202 $taxItems[$dao->price_field_value_id
] = [
5203 'financial_item_id' => $dao->id
,
5204 'amount' => $dao->tax_amount
,
5208 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5211 return [$ftIds, $taxItems];
5215 * Create proportional entries in civicrm_entity_financial_trxn.
5217 * @param array $entityParams
5219 * @param array $lineItems
5221 * @param array $ftIds
5223 * @param array $taxItems
5225 * @throws \CiviCRM_API3_Exception
5227 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5229 'entity_table' => 'civicrm_financial_item',
5230 'financial_trxn_id' => $entityParams['trxn_id'],
5232 foreach ($lineItems as $key => $value) {
5233 if ($value['qty'] == 0) {
5236 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5237 $entityParams['line_item_amount'] = $value['line_total'];
5238 self
::createProportionalEntry($entityParams, $eftParams);
5239 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5240 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5241 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5242 self
::createProportionalEntry($entityParams, $eftParams);
5248 * Load entities related to the contribution into $this->_relatedObjects.
5252 * @throws \CRM_Core_Exception
5254 protected function loadRelatedEntitiesByID($ids) {
5256 'contact' => 'CRM_Contact_BAO_Contact',
5257 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5258 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5259 'financialType' => 'CRM_Financial_BAO_FinancialType',
5260 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5262 foreach ($entities as $entity => $bao) {
5263 if (!empty($ids[$entity])) {
5264 $this->_relatedObjects
[$entity] = new $bao();
5265 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5266 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5267 throw new CRM_Core_Exception($entity . ' could not be loaded');
5274 * Function to replace contribution tokens.
5276 * @param array $contributionIds
5278 * @param string $subject
5280 * @param array $subjectToken
5282 * @param string $text
5284 * @param string $html
5286 * @param array $messageToken
5288 * @param bool $escapeSmarty
5291 * @throws \CiviCRM_API3_Exception
5293 public static function replaceContributionTokens(
5302 if (empty($contributionIds)) {
5305 $contributionDetails = [];
5306 foreach ($contributionIds as $id) {
5307 $result = self
::getContributionTokenValues($id, $messageToken);
5308 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5309 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5310 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5312 return $contributionDetails;
5316 * Get the contribution fields for $id and display labels where
5317 * appropriate (if the token is present).
5320 * @param array $messageToken
5323 public static function getContributionTokenValues($id, $messageToken) {
5327 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5328 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5329 if (!empty($messageToken)) {
5330 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5331 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5332 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField
::displayValue($result['values'][$id][$fieldName], $fieldName);
5340 * Get invoice_number for contribution.
5342 * @param int $contributionID
5346 public static function getInvoiceNumber($contributionID) {
5347 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix')) {
5348 return $invoicePrefix . $contributionID;
5355 * Load the values needed for the event message.
5357 * @param int $eventID
5358 * @param int $participantID
5359 * @param int|null $contributionID
5362 * @throws \CRM_Core_Exception
5364 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5369 $values = ['event' => []];
5371 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
5372 // add custom fields for event
5373 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $eventID);
5375 $eventCustomGroup = [];
5376 foreach ($eventGroupTree as $key => $group) {
5377 if ($key === 'info') {
5381 foreach ($group['fields'] as $k => $customField) {
5382 $groupLabel = $group['title'];
5383 if (!empty($customField['customValue'])) {
5384 foreach ($customField['customValue'] as $customFieldValues) {
5385 $eventCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5390 $values['event']['customGroup'] = $eventCustomGroup;
5392 //get participant details
5393 $participantParams = [
5394 'id' => $participantID,
5397 $values['participant'] = [];
5399 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
5400 // add custom fields for event
5401 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $participantID);
5402 $participantCustomGroup = [];
5403 foreach ($participantGroupTree as $key => $group) {
5404 if ($key === 'info') {
5408 foreach ($group['fields'] as $k => $customField) {
5409 $groupLabel = $group['title'];
5410 if (!empty($customField['customValue'])) {
5411 foreach ($customField['customValue'] as $customFieldValues) {
5412 $participantCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5417 $values['participant']['customGroup'] = $participantCustomGroup;
5419 //get location details
5421 'entity_id' => $eventID,
5422 'entity_table' => 'civicrm_event',
5424 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
5427 'entity_table' => 'civicrm_event',
5428 'entity_id' => $eventID,
5429 'module' => 'CiviEvent',
5432 list($custom_pre_id,
5434 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
5436 $values['custom_pre_id'] = $custom_pre_id;
5437 $values['custom_post_id'] = $custom_post_ids;
5439 // set lineItem for event contribution
5440 if ($contributionID) {
5441 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($contributionID);
5442 if (!empty($participantIds)) {
5443 foreach ($participantIds as $pIDs) {
5444 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
5445 if (!CRM_Utils_System
::isNull($lineItem)) {
5446 $values['lineItem'][] = $lineItem;