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\ActivityContact
;
14 use Civi\Api4\Contribution
;
15 use Civi\Api4\ContributionRecur
;
16 use Civi\Api4\LineItem
;
17 use Civi\Api4\ContributionSoft
;
18 use Civi\Api4\PaymentProcessor
;
19 use Civi\Api4\PledgePayment
;
24 * @copyright CiviCRM LLC https://civicrm.org/licensing
26 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
29 * Static field for all the contribution information that we can potentially import
33 public static $_importableFields = NULL;
36 * Static field for all the contribution information that we can potentially export
40 public static $_exportableFields = NULL;
43 * Field for all the objects related to this contribution.
46 * 1) deprecated function transitionComponents
47 * 2) function to send contribution receipts _assignMessageVariablesToTemplate
48 * 3) some invoice code that is copied from 2
49 * 4) odds & sods that need to be investigated and fixed.
51 * However, it is no longer used by completeOrder.
53 * @var \CRM_Member_BAO_Membership|\CRM_Event_BAO_Participant[]
57 public $_relatedObjects = [];
60 * Field for the component - either 'event' (participant) or 'contribute'
61 * (any item related to a contribution page e.g. membership, pledge, contribution)
62 * This is used for composing messages because they have dependency on the
63 * contribution_page or event page - although over time we may eliminate that
66 * "contribution"\"event"
68 public $_component = NULL;
71 * Possibly obsolete variable.
73 * If you use it please explain why it is set in the create function here.
77 public $trxn_result_code;
82 public function __construct() {
83 parent
::__construct();
87 * Takes an associative array and creates a contribution object.
89 * the function extract all the params it needs to initialize the create a
90 * contribution object. the params array could contain additional unused name/value
93 * @param array $params
94 * (reference ) an assoc array of name/value pairs.
96 * @return \CRM_Contribute_BAO_Contribution
97 * @throws \CRM_Core_Exception
98 * @throws \CiviCRM_API3_Exception
100 public static function add(&$params) {
101 if (empty($params)) {
105 $contributionID = $params['id'] ??
NULL;
106 $action = $contributionID ?
'edit' : 'create';
108 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
109 $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)]);
110 throw new CRM_Core_Exception($message);
113 //set defaults in create mode
114 if (!$contributionID) {
115 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
116 if (empty($params['invoice_number']) && CRM_Invoicing_Utils
::isInvoicingEnabled()) {
117 $nextContributionID = CRM_Core_DAO
::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
118 $params['invoice_number'] = self
::getInvoiceNumber($nextContributionID);
122 $contributionStatusID = $params['contribution_status_id'] ??
NULL;
123 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $contributionStatusID) === 'Partially paid' && empty($params['is_post_payment_create'])) {
124 CRM_Core_Error
::deprecatedFunctionWarning('Setting status to partially paid other than by using Payment.create is deprecated and unreliable');
126 if (!$contributionStatusID) {
127 // Since the fee amount is expecting this (later on) ensure it is always set.
128 // It would only not be set for an update where it is unchanged.
129 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', [
130 'id' => $contributionID,
131 'return' => 'contribution_status_id',
134 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['contribution_status_id']);
137 && !empty($params['membership_id'])
138 && Civi
::settings()->get('deferred_revenue_enabled')
140 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
141 if ($memberStartDate) {
142 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
145 self
::calculateMissingAmountParams($params, $contributionID);
147 if (!empty($params['payment_instrument_id'])) {
148 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
149 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
150 $params['check_number'] = 'null';
154 $setPrevContribution = TRUE;
155 if ($contributionID && $setPrevContribution) {
156 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
158 $previousContributionStatus = ($contributionID && !empty($params['prevContribution'])) ? CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['prevContribution']->contribution_status_id
) : NULL;
160 if ($contributionID && !empty($params['revenue_recognition_date'])
161 && !($previousContributionStatus === 'Pending')
162 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
164 unset($params['revenue_recognition_date']);
167 // Get Line Items if we don't have them already.
168 if (empty($params['line_item'])) {
169 CRM_Price_BAO_LineItem
::getLineItemArray($params, $contributionID ?
[$contributionID] : NULL);
172 // We should really ALWAYS calculate tax amount off the line items.
173 // In order to be a bit cautious we are just messaging rather than
174 // overwriting in cases where we were not previously setting it here.
175 $taxAmount = $lineTotal = 0;
176 foreach ($params['line_item'] ??
[] as $lineItems) {
177 foreach ($lineItems as $lineItem) {
178 $taxAmount +
= (float) ($lineItem['tax_amount'] ??
0);
179 $lineTotal +
= (float) ($lineItem['line_total'] ??
0);
182 if (($params['tax_amount'] ??
'') === 'null') {
183 CRM_Core_Error
::deprecatedWarning('tax_amount should be not passed in (preferable) or a float');
185 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
186 isset($params['financial_type_id']))) {
187 $params['tax_amount'] = $taxAmount;
189 if (isset($params['tax_amount']) && empty($params['skipLineItem'])
190 && !CRM_Utils_Money
::equals($params['tax_amount'], $taxAmount, ($params['currency'] ?? Civi
::settings()->get('defaultCurrency')))
192 CRM_Core_Error
::deprecatedWarning('passing in incorrect tax amounts is deprecated');
195 CRM_Utils_Hook
::pre($action, 'Contribution', $contributionID, $params);
197 $contribution = new CRM_Contribute_BAO_Contribution();
198 $contribution->copyValues($params);
200 $contribution->id
= $contributionID;
202 if (empty($contribution->id
)) {
203 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
204 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
205 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
209 $result = $contribution->save();
211 // Add financial_trxn details as part of fix for CRM-4724
212 $contribution->trxn_result_code
= $params['trxn_result_code'] ??
NULL;
213 $contribution->payment_processor
= $params['payment_processor'] ??
NULL;
215 //add Account details
216 $params['contribution'] = $contribution;
217 if (empty($params['is_post_payment_create'])) {
218 // If this is being called from the Payment.create api/ BAO then that Entity
219 // takes responsibility for the financial transactions. In fact calling Payment.create
220 // to add payments & having it call completetransaction and / or contribution.create
221 // to update related entities is the preferred flow.
222 // Note that leveraging this parameter for any other code flow is not supported and
223 // is likely to break in future and / or cause serious problems in your data.
224 // https://github.com/civicrm/civicrm-core/pull/14673
225 self
::recordFinancialAccounts($params);
228 if (self
::isUpdateToRecurringContribution($params)) {
229 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
230 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
232 $params['receive_date'] ??
'now'
236 $params['contribution_id'] = $contribution->id
;
238 if (!empty($params['custom']) &&
239 is_array($params['custom'])
241 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
, $action);
244 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
246 CRM_Utils_Hook
::post($action, 'Contribution', $contribution->id
, $contribution);
251 * Is this contribution updating an existing recurring contribution.
253 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
254 * pending payment is being confirmed (or failing).
256 * @param array $params
260 public static function isUpdateToRecurringContribution($params) {
261 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
264 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
267 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
270 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
271 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
278 * Get defaults for new entity.
282 public static function getDefaults() {
284 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
285 FALSE, FALSE, FALSE, 'AND is_default = 1')
287 'contribution_status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
288 'receive_date' => date('Y-m-d H:i:s'),
293 * Fetch the object and store the values in the values array.
295 * @param array $params
296 * Input parameters to find object.
297 * @param array $values
298 * Output values of the object.
300 * The array that holds all the db ids.
302 * @return CRM_Contribute_BAO_Contribution|null
303 * The found object or null
305 public static function getValues($params, &$values = [], &$ids = []) {
306 if (empty($params)) {
309 $contribution = new CRM_Contribute_BAO_Contribution();
311 $contribution->copyValues($params);
313 if ($contribution->find(TRUE)) {
314 $ids['contribution'] = $contribution->id
;
316 CRM_Core_DAO
::storeValues($contribution, $values);
318 return $contribution;
320 // return by reference
326 * Get the values and resolve the most common mappings.
328 * Since contribution status is resolved in almost every function that calls getValues it makes
329 * sense to have an extra function to resolve it rather than repeat the code.
331 * Think carefully before adding more mappings to be resolved as there could be performance implications
332 * if this function starts to be called from more iterative functions.
334 * @param array $params
335 * Input parameters to find object.
338 * Array of the found contribution.
339 * @throws CRM_Core_Exception
341 public static function getValuesWithMappings($params) {
343 $contribution = self
::getValues($params, $values, $ids);
344 if (is_null($contribution)) {
345 throw new CRM_Core_Exception('No contribution found');
347 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
352 * Calculate net_amount & fee_amount if they are not set.
354 * Net amount should be total - fee.
355 * This should only be called for new contributions.
357 * @param array $params
358 * Params for a new contribution before they are saved.
359 * @param int|null $contributionID
360 * Contribution ID if we are dealing with an update.
362 * @throws \CiviCRM_API3_Exception
364 public static function calculateMissingAmountParams(&$params, $contributionID) {
365 if (!$contributionID && (!isset($params['fee_amount']) ||
$params['fee_amount'] === '')) {
366 if (isset($params['total_amount']) && isset($params['net_amount'])) {
367 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
370 $params['fee_amount'] = 0;
373 if (!isset($params['net_amount'])) {
374 if (!$contributionID) {
375 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
378 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
379 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
380 // net_amount may need adjusting.
381 $contribution = civicrm_api3('Contribution', 'getsingle', [
382 'id' => $contributionID,
383 'return' => ['total_amount', 'net_amount', 'fee_amount'],
385 $totalAmount = (isset($params['total_amount']) ?
(float) $params['total_amount'] : (float) CRM_Utils_Array
::value('total_amount', $contribution));
386 $feeAmount = (isset($params['fee_amount']) ?
(float) $params['fee_amount'] : (float) CRM_Utils_Array
::value('fee_amount', $contribution));
387 $params['net_amount'] = $totalAmount - $feeAmount;
395 * @param $billingLocationTypeID
399 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
400 $hasBillingField = FALSE;
409 //build address array
411 $addressParams['location_type_id'] = $billingLocationTypeID;
412 $addressParams['is_billing'] = 1;
414 $billingFirstName = $params['billing_first_name'] ??
NULL;
415 $billingMiddleName = $params['billing_middle_name'] ??
NULL;
416 $billingLastName = $params['billing_last_name'] ??
NULL;
417 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
419 foreach ($billingFields as $value) {
420 $addressParams[$value] = $params["billing_{$value}-{$billingLocationTypeID}"] ??
NULL;
421 if (!empty($addressParams[$value])) {
422 $hasBillingField = TRUE;
425 return [$hasBillingField, $addressParams];
429 * Get address params ready to be passed to the payment processor.
431 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
432 * To create an address we need state_province_id.
434 * @param array $params
435 * @param int $billingLocationTypeID
439 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
440 [$hasBillingField, $addressParams] = self
::getBillingAddressParams($params, $billingLocationTypeID);
441 foreach ($addressParams as $name => $field) {
442 if (substr($name, 0, 8) == 'billing_') {
443 $addressParams[substr($name, 9)] = $addressParams[$field];
446 return [$hasBillingField, $addressParams];
450 * Get the number of terms for this contribution for a given membership type
451 * based on querying the line item table and relevant price field values
452 * Note that any one contribution should only be able to have one line item relating to a particular membership
455 * @param int $membershipTypeID
457 * @param int $contributionID
461 public static function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
462 $numTerms = CRM_Core_DAO
::singleValueQuery("
463 SELECT v.membership_num_terms FROM civicrm_line_item li
464 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
465 WHERE contribution_id = %1 AND membership_type_id = %2",
466 [1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']]
468 // default of 1 is precautionary
469 return empty($numTerms) ?
1 : $numTerms;
473 * Takes an associative array and creates a contribution object.
475 * @param array $params
476 * (reference ) an assoc array of name/value pairs.
478 * @return CRM_Contribute_BAO_Contribution
480 * @throws \API_Exception
481 * @throws \CRM_Core_Exception
482 * @throws \CiviCRM_API3_Exception
484 public static function create(&$params) {
486 $transaction = new CRM_Core_Transaction();
489 $contribution = self
::add($params);
491 catch (CRM_Core_Exception
$e) {
492 $transaction->rollback();
496 $params['contribution_id'] = $contribution->id
;
497 $session = CRM_Core_Session
::singleton();
499 if (!empty($params['note'])) {
501 'entity_table' => 'civicrm_contribution',
502 'note' => $params['note'],
503 'entity_id' => $contribution->id
,
504 'contact_id' => $session->get('userID'),
506 if (!$noteParams['contact_id']) {
507 $noteParams['contact_id'] = $params['contact_id'];
509 CRM_Core_BAO_Note
::add($noteParams);
512 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
514 if (!empty($params['id']) && !empty($params['contribution_status_id'])
516 self
::disconnectPledgePaymentsIfCancelled((int) $params['id'], CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution_status_id']));
518 $transaction->commit();
520 if (empty($contribution->contact_id
)) {
521 $contribution->find(TRUE);
524 $isCompleted = ('Completed' === CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
));
525 if (!empty($params['on_behalf'])
528 $existingActivity = Activity
::get(FALSE)->setWhere([
529 ['source_record_id', '=', $contribution->id
],
530 ['activity_type_id:name', '=', 'Contribution'],
531 ])->execute()->first();
534 'activity_type_id:name' => 'Contribution',
535 'source_record_id' => $contribution->id
,
536 'activity_date_time' => $contribution->receive_date
,
537 'is_test' => (bool) $contribution->is_test
,
538 'status_id:name' => $isCompleted ?
'Completed' : 'Scheduled',
539 'skipRecentView' => TRUE,
540 'subject' => CRM_Activity_BAO_Activity
::getActivitySubject($contribution),
541 'campaign_id' => !is_numeric($contribution->campaign_id
) ?
NULL : $contribution->campaign_id
,
542 'id' => $existingActivity['id'] ??
NULL,
544 if (!$activityParams['id']) {
545 $activityParams['source_contact_id'] = (int) ($params['source_contact_id'] ??
(CRM_Core_Session
::getLoggedInContactID() ?
: $contribution->contact_id
));
546 $activityParams['target_contact_id'] = ($activityParams['source_contact_id'] === (int) $contribution->contact_id
) ?
[] : [$contribution->contact_id
];
549 [$sourceContactId, $targetContactId] = self
::getActivitySourceAndTarget($activityParams['id']);
551 if (empty($targetContactId) && $sourceContactId != $contribution->contact_id
) {
552 // If no target contact exists and the source contact is not equal to
553 // the contribution contact, update the source contact
554 $activityParams['source_contact_id'] = $contribution->contact_id
;
556 elseif (isset($targetContactId) && $targetContactId != $contribution->contact_id
) {
557 // If a target contact exists and it is not equal to the contribution
558 // contact, update the target contact
559 $activityParams['target_contact_id'] = [$contribution->contact_id
];
562 Activity
::save(FALSE)->addRecord($activityParams)->execute();
565 // do not add to recent items for import, CRM-4399
566 if (empty($params['skipRecentView'])) {
567 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
568 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
570 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
577 $retrieveRequired = 0;
578 foreach ($titleFields as $titleField) {
579 if (!isset($contribution->$titleField)) {
580 $retrieveRequired = 1;
584 if ($retrieveRequired == 1) {
585 $contribution->find(TRUE);
587 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
588 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
591 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
592 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
593 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
597 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
598 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
599 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
603 // add the recently created Contribution
604 CRM_Utils_Recent
::add($title,
608 $contribution->contact_id
,
614 return $contribution;
618 * Get the values for pseudoconstants for name->value and reverse.
620 * @param array $defaults
621 * (reference) the default values, some of which need to be resolved.
622 * @param bool $reverse
623 * True if we want to resolve the values in the reverse direction (value -> name).
625 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
626 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
627 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
628 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'), $reverse);
629 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
633 * Convert associative array names to values and vice-versa.
635 * This function is used by both the web form layer and the api. Note that
636 * the api needs the name => value conversion, also the view layer typically
637 * requires value => name conversion
639 * @param array $defaults
640 * @param string $property
641 * @param array $lookup
642 * @param bool $reverse
646 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
647 $id = $property . '_id';
649 $src = $reverse ?
$property : $id;
650 $dst = $reverse ?
$id : $property;
652 if (!array_key_exists($src, $defaults)) {
656 $look = $reverse ?
array_flip($lookup) : $lookup;
658 if (is_array($look)) {
659 if (!array_key_exists($defaults[$src], $look)) {
663 $defaults[$dst] = $look[$defaults[$src]];
668 * Retrieve DB object based on input parameters.
670 * It also stores all the retrieved values in the default array.
672 * @param array $params
673 * (reference ) an assoc array of name/value pairs.
674 * @param array $defaults
675 * (reference ) an assoc array to hold the name / value pairs.
676 * in a hierarchical manner
678 * (reference) the array that holds all the db ids.
680 * @return CRM_Contribute_BAO_Contribution
682 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
683 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
684 return $contribution;
688 * Combine all the importable fields from the lower levels object.
690 * The ordering is important, since currently we do not have a weight
691 * scheme. Adding weight is super important and should be done in the
692 * next week or so, before this can be called complete.
694 * @param string $contactType
695 * @param bool $status
698 * array of importable Fields
700 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
701 if (!self
::$_importableFields) {
702 if (!self
::$_importableFields) {
703 self
::$_importableFields = [];
707 $fields = ['' => ['title' => ts('- do not import -')]];
710 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
713 $note = CRM_Core_DAO_Note
::import();
714 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
715 unset($tmpFields['option_value']);
716 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
717 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
719 // Using new Dedupe rule.
721 'contact_type' => $contactType,
722 'used' => 'Unsupervised',
724 $fieldsArray = CRM_Dedupe_BAO_DedupeRule
::dedupeRuleFields($ruleParams);
725 $tmpContactField = [];
726 if (is_array($fieldsArray)) {
727 foreach ($fieldsArray as $value) {
728 //skip if there is no dupe rule
729 if ($value == 'none') {
732 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
737 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
738 $tmpContactField[trim($value)] = $contactFields[trim($value)];
740 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
743 $title = $tmpContactField[trim($value)]['title'];
745 $tmpContactField[trim($value)]['title'] = $title;
749 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
750 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
751 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
752 $fields = array_merge($fields, $tmpContactField);
753 $fields = array_merge($fields, $tmpFields);
754 $fields = array_merge($fields, $note);
755 $fields = array_merge($fields, $optionFields);
756 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
757 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
758 self
::$_importableFields = $fields;
760 return self
::$_importableFields;
764 * Combine all the exportable fields from the lower level objects.
766 * @param bool $checkPermission
769 * array of exportable Fields
771 public static function &exportableFields($checkPermission = TRUE) {
772 if (!self
::$_exportableFields) {
773 if (!self
::$_exportableFields) {
774 self
::$_exportableFields = [];
777 $fields = CRM_Contribute_DAO_Contribution
::export();
778 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
779 $fields = array_merge(
781 CRM_Contribute_DAO_Product
::export(),
782 CRM_Contribute_DAO_ContributionProduct
::export(),
783 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
785 'contribution_product_id' => [
786 'title' => ts('Premium'),
787 'name' => 'contribution_product_id',
788 'where' => 'civicrm_product.id',
789 'data_type' => CRM_Utils_Type
::T_INT
,
795 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
797 $contributionPage = [
798 'contribution_page' => [
799 'title' => ts('Contribution Page'),
800 'name' => 'contribution_page',
801 'where' => 'civicrm_contribution_page.title',
802 'data_type' => CRM_Utils_Type
::T_STRING
,
806 $contributionNote = [
807 'contribution_note' => [
808 'title' => ts('Contribution Note'),
809 'name' => 'contribution_note',
810 'data_type' => CRM_Utils_Type
::T_TEXT
,
815 'contribution_batch' => [
816 'title' => ts('Batch Name'),
822 'contribution_campaign_title' => [
823 'title' => ts('Campaign Title'),
824 'name' => 'campaign_title',
825 'where' => 'civicrm_campaign.title',
826 'data_type' => CRM_Utils_Type
::T_STRING
,
829 $softCreditFields = [
830 'contribution_soft_credit_name' => [
831 'name' => 'contribution_soft_credit_name',
832 'title' => ts('Soft Credit For'),
833 'where' => 'civicrm_contact_d.display_name',
834 'data_type' => CRM_Utils_Type
::T_STRING
,
836 'contribution_soft_credit_amount' => [
837 'name' => 'contribution_soft_credit_amount',
838 'title' => ts('Soft Credit Amount'),
839 'where' => 'civicrm_contribution_soft.amount',
840 'data_type' => CRM_Utils_Type
::T_MONEY
,
842 'contribution_soft_credit_type' => [
843 'name' => 'contribution_soft_credit_type',
844 'title' => ts('Soft Credit Type'),
845 'where' => 'contribution_softcredit_type.label',
846 'data_type' => CRM_Utils_Type
::T_STRING
,
848 'contribution_soft_credit_contribution_id' => [
849 'name' => 'contribution_soft_credit_contribution_id',
850 'title' => ts('Soft Credit For Contribution ID'),
851 'where' => 'civicrm_contribution_soft.contribution_id',
852 'data_type' => CRM_Utils_Type
::T_INT
,
854 'contribution_soft_credit_contact_id' => [
855 'name' => 'contribution_soft_credit_contact_id',
856 'title' => ts('Soft Credit For Contact ID'),
857 'where' => 'civicrm_contact_d.id',
858 'data_type' => CRM_Utils_Type
::T_INT
,
862 $fields = array_merge($fields, $contributionPage,
863 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
864 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
867 self
::$_exportableFields = $fields;
870 return self
::$_exportableFields;
874 * Record an activity when a payment is received.
876 * @todo this is intended to be moved to payment BAO class as a protected function
877 * on that class. Currently being cleaned up. The addActivityForPayment doesn't really
878 * merit it's own function as it makes the code less rather than more readable.
880 * @param int $contributionId
881 * @param int $participantId
882 * @param string $totalAmount
883 * @param string $currency
884 * @param string $trxnDate
886 * @throws \CRM_Core_Exception
887 * @throws \CiviCRM_API3_Exception
889 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
890 $activityType = ($totalAmount < 0) ?
'Refund' : 'Payment';
892 if ($participantId) {
893 $inputParams['id'] = $participantId;
896 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
897 $entityObj = $entityObj[$participantId];
898 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
901 $entityObj = new CRM_Contribute_BAO_Contribution();
902 $entityObj->id
= $contributionId;
903 $entityObj->find(TRUE);
904 $title = ts('Contribution');
906 // @todo per block above this is not a logical splitting off of functionality.
907 self
::addActivityForPayment($entityObj->contact_id
, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
911 * Get the value for the To Financial Account.
913 * @param $contribution
918 public static function getToFinancialAccount($contribution, $params) {
919 if (!empty($params['payment_processor_id'])) {
920 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor_id'], NULL, 'civicrm_payment_processor');
922 if (!empty($params['payment_instrument_id'])) {
923 return CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
926 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
927 $queryParams = [1 => [$relationTypeId, 'Integer']];
928 return CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
933 * Get memberships related to the contribution.
935 * @param int $contributionID
938 * @throws \API_Exception
940 protected static function getRelatedMemberships(int $contributionID): array {
941 $membershipIDs = array_keys((array) LineItem
::get(FALSE)
942 ->addWhere('contribution_id', '=', $contributionID)
943 ->addWhere('entity_table', '=', 'civicrm_membership')
944 ->addSelect('entity_id')
945 ->execute()->indexBy('entity_id'));
947 $doubleCheckParams = [
948 'return' => 'membership_id',
949 'contribution_id' => $contributionID,
951 if (!empty($membershipIDs)) {
952 $doubleCheckParams['membership_id'] = ['NOT IN' => $membershipIDs];
954 $membershipPayments = civicrm_api3('MembershipPayment', 'get', $doubleCheckParams)['values'];
955 if (!empty($membershipPayments)) {
957 CRM_Core_Error
::deprecatedWarning('Not having valid line items for membership payments is invalid.');
958 foreach ($membershipPayments as $membershipPayment) {
959 $membershipIDs[] = $membershipPayment['membership_id'];
962 if (empty($membershipIDs)) {
965 // We could combine this with the MembershipPayment.get - we'd
966 // need to re-wrangle the params (here or in the calling function)
967 // as they would then me membership.contact_id, membership.is_test etc
968 return civicrm_api3('Membership', 'get', [
969 'id' => ['IN' => $membershipIDs],
970 'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'],
975 * Do any accounting updates required as a result of a contribution status change.
977 * Currently we have a bit of a roundabout where adding a payment results in this being called &
978 * this may attempt to add a payment. We need to resolve that....
980 * The 'right' way to add payments or refunds is through the Payment.create api. That api
981 * then updates the contribution but this process should not also record another financial trxn.
982 * Currently we have weak detection fot that scenario & where it is detected the first returned
983 * value is FALSE - meaning 'do not continue'.
985 * We should also look at the fact that the calling function - updateFinancialAccounts
986 * bunches together some disparate processes rather than having separate appropriate
989 * @param array $params
992 * Return indicates whether the updateFinancialAccounts function should continue.
994 private static function updateFinancialAccountsOnContributionStatusChange(&$params) {
995 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
996 $currentContributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
998 if ((($previousContributionStatus === 'Partially paid' && $currentContributionStatus === 'Completed')
999 ||
($previousContributionStatus === 'Pending refund' && $currentContributionStatus === 'Completed')
1000 // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
1001 // why it is here or where it is handled instead.
1002 ||
($previousContributionStatus === 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
1003 && $currentContributionStatus === 'Partially paid'))
1008 if (CRM_Contribute_BAO_FinancialProcessor
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
)) {
1009 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1010 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1012 elseif (($previousContributionStatus === 'Pending'
1013 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus === 'In Progress'
1015 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
1016 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
1018 if ($currentContributionStatus === 'Cancelled') {
1019 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1020 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
1021 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1024 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1025 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
1029 if (($previousContributionStatus === 'Pending'
1030 ||
$previousContributionStatus === 'In Progress')
1031 && ($currentContributionStatus === 'Completed')
1033 if (empty($params['line_item'])) {
1035 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
1036 // when creating recurring membership payment - there are 2 lines to comment out in contributionPageTest if fixed
1037 // & this can be removed
1040 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1041 // This is an update so original currency if none passed in.
1042 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
1044 $transactionIDs[] = CRM_Contribute_BAO_FinancialProcessor
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
1045 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
1046 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1047 $params['entity_id'] = $transactionIDs[] = $trxn->id
;
1049 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
1052 'entity_table' => 'civicrm_financial_item',
1054 foreach ($params['line_item'] as $fieldId => $fields) {
1055 foreach ($fields as $fieldValueId => $lineItemDetails) {
1056 self
::updateFinancialItemForLineItemToPaid($lineItemDetails['id']);
1058 1 => [$lineItemDetails['id'], 'Integer'],
1060 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
1061 while ($financialItem->fetch()) {
1062 $entityParams['entity_id'] = $financialItem->id
;
1063 $entityParams['amount'] = $financialItem->amount
;
1064 foreach ($transactionIDs as $tID) {
1065 $entityParams['financial_trxn_id'] = $tID;
1066 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
1077 * It is possible to override the membership id that is updated from the payment processor.
1079 * Historically Paypal does this & it still does if it determines data is messed up - see
1080 * https://lab.civicrm.org/dev/membership/issues/13
1082 * Read the comment block on repeattransaction for more information
1083 * about how things should work.
1085 * @param int $contributionID
1086 * @param array $input
1088 * @throws \CiviCRM_API3_Exception
1090 protected static function handleMembershipIDOverride($contributionID, $input) {
1091 if (!empty($input['membership_id'])) {
1092 Civi
::log()->debug('The related membership id has been overridden - this may impact data - see https://github.com/civicrm/civicrm-core/pull/15053');
1093 civicrm_api3('MembershipPayment', 'create', ['contribution_id' => $contributionID, 'membership_id' => $input['membership_id']]);
1098 * Update all financial items related to the line item tto have a status of paid.
1100 * @param int $lineItemID
1102 private static function updateFinancialItemForLineItemToPaid($lineItemID) {
1105 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1108 2 => [$lineItemID, 'Integer'],
1110 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
1111 CRM_Core_DAO
::executeQuery($query, $fparams);
1115 * Get transaction information about the contribution.
1117 * @param int $contributionId
1118 * @param int $financialTypeID
1122 protected static function getContributionTransactionInformation($contributionId, int $financialTypeID) {
1124 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Expense Account is');
1126 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
1128 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
1130 ft.payment_instrument_id,
1131 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
1133 FROM civicrm_contribution con
1134 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
1135 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
1136 AND ft.to_financial_account_id != %2
1137 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
1138 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
1139 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
1141 WHERE con.id = %1 AND ft.is_payment = 1
1144 1 => [$contributionId, 'Integer'],
1145 2 => [$feeFinancialAccount, 'Integer'],
1147 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
1148 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label');
1150 while ($resultDAO->fetch()) {
1151 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1152 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1153 if ($resultDAO->card_type_id
) {
1154 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
1155 $pantruncation = '';
1156 if ($resultDAO->pan_truncation
) {
1157 $pantruncation = ": {$resultDAO->pan_truncation}";
1159 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
1162 // show payment edit link only for payments done via backoffice form
1163 $paymentEditLink = '';
1164 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
1166 CRM_Core_Action
::UPDATE
=> [
1167 'name' => ts('Edit Payment'),
1168 'icon' => 'fa-pencil',
1169 'url' => 'civicrm/payment/edit',
1170 'class' => 'medium-popup',
1171 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
1172 'title' => ts('Edit Payment'),
1175 $paymentEditLink = CRM_Core_Action
::formLink(
1177 CRM_Core_Action
::mask([CRM_Core_Permission
::EDIT
]),
1179 'id' => $resultDAO->id
,
1180 'contribution_id' => $contributionId,
1184 'Payment.edit.action',
1192 'id' => $resultDAO->id
,
1193 'total_amount' => $resultDAO->total_amount
,
1194 'financial_type' => $resultDAO->financial_account
,
1195 'payment_instrument' => $paidByLabel,
1196 'receive_date' => $resultDAO->trxn_date
,
1197 'trxn_id' => $resultDAO->trxn_id
,
1198 'status' => $statuses[$resultDAO->status_id
],
1199 'currency' => $resultDAO->currency
,
1200 'action' => $paymentEditLink,
1202 if ($paidByName === 'Check') {
1203 $val['check_number'] = $resultDAO->check_number
;
1211 * Should an email receipt be sent for this contribution on completion.
1213 * @param array $input
1214 * @param int $contributionID
1215 * @param int $recurringContributionID
1218 * @throws \API_Exception
1220 protected static function isEmailReceipt(array $input, int $contributionID, $recurringContributionID): bool {
1221 if (isset($input['is_email_receipt'])) {
1222 return (bool) $input['is_email_receipt'];
1224 if ($recurringContributionID) {
1225 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
1226 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
1227 // 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
1228 // Instance that had the table added via an upgrade in 4.1
1229 // see also https://github.com/civicrm/civicrm-svn/commit/7f39befd60bc735408d7866b02b3ac7fff1d4eea#diff-9ad8e290180451a2d6eacbd3d1ca7966R354
1230 // https://lab.civicrm.org/dev/core/issues/1245
1231 return (bool) ContributionRecur
::get(FALSE)->addWhere('id', '=', $recurringContributionID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt'];
1233 $contributionPage = Contribution
::get(FALSE)
1234 ->addSelect('contribution_page_id.is_email_receipt')
1235 ->addWhere('contribution_page_id', 'IS NOT NULL')
1236 ->addWhere('id', '=', $contributionID)
1237 ->execute()->first();
1239 if (!empty($contributionPage)) {
1240 return (bool) $contributionPage['contribution_page_id.is_email_receipt'];
1242 // This would be the case for backoffice (where is_email_receipt is not passed in) or events, where Event::sendMail will filter
1248 * Disconnect pledge payments from cancelled or failed contributions.
1250 * If the contribution has been cancelled or has failed check to
1251 * see if it is linked to a pledge and unlink it.
1253 * @param int $pledgePaymentID
1254 * @param string $contributionStatus
1256 * @throws \API_Exception
1257 * @throws \Civi\API\Exception\UnauthorizedException
1259 protected static function disconnectPledgePaymentsIfCancelled(int $pledgePaymentID, $contributionStatus): void
{
1260 if (!in_array($contributionStatus, ['Failed', 'Cancelled'], TRUE)) {
1263 // Check first since just doing an update could be locking under load.
1264 $pledgePayment = PledgePayment
::get(FALSE)
1265 ->addWhere('contribution_id', '=', $pledgePaymentID)
1266 ->setSelect(['id', 'pledge_id', 'scheduled_date', 'scheduled_amount'])
1269 if (!empty($pledgePayment)) {
1270 PledgePayment
::update(FALSE)->setValues([
1271 'contribution_id' => NULL,
1272 'actual_amount' => NULL,
1273 'status_id:name' => 'Pending',
1274 // We need to set these fields for now because the PledgePayment::create
1275 // function doesn't handled updates well at the moment. Test cover
1276 // in testCancelOrderWithPledge.
1277 'scheduled_date' => $pledgePayment['scheduled_date'],
1278 'installment_amount' => $pledgePayment['scheduled_amount'],
1279 'installments' => 1,
1280 'pledge_id' => $pledgePayment['pledge_id'],
1281 ])->addWhere('id', '=', $pledgePayment['id'])->execute();
1288 public function addSelectWhereClause() {
1289 $whereClauses = parent
::addSelectWhereClause();
1290 if ($whereClauses !== []) {
1291 // In this case permisssions have been applied & we assume the
1292 // financialaclreport is applying these
1293 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
1294 return $whereClauses;
1297 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1298 return $whereClauses;
1300 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
1301 if (empty($types)) {
1302 $whereClauses['financial_type_id'] = 'IN (0)';
1305 $whereClauses['financial_type_id'] = [
1306 'IN (' . implode(',', array_keys($types)) . ')',
1309 return $whereClauses;
1313 * @param null $status
1314 * @param null $startDate
1315 * @param null $endDate
1317 * @return array|null
1319 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1323 $where[] = 'contribution_status_id = 1';
1327 $where[] = 'contribution_status_id = 3';
1332 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
1335 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
1337 $financialTypeACLJoin = '';
1338 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1339 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1340 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
1341 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1342 if ($financialTypes) {
1343 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1344 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1347 $where[] = "c.financial_type_id IN (0)";
1351 $whereCond = implode(' AND ', $where);
1354 SELECT sum( total_amount ) as total_amount,
1355 count( c.id ) as total_count,
1357 FROM civicrm_contribution c
1358 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1359 $financialTypeACLJoin
1361 AND ( is_test = 0 OR is_test IS NULL )
1362 AND contact.is_deleted = 0
1366 $dao = CRM_Core_DAO
::executeQuery($query);
1369 while ($dao->fetch()) {
1370 $count +
= $dao->total_count
;
1371 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
1375 'amount' => implode(', ', $amount),
1383 * Delete the indirect records associated with this contribution first.
1387 * @return mixed|null
1388 * $results no of deleted Contribution on success, false otherwise
1390 public static function deleteContribution($id) {
1391 CRM_Utils_Hook
::pre('delete', 'Contribution', $id);
1393 $transaction = new CRM_Core_Transaction();
1396 //delete activity record
1398 'source_record_id' => $id,
1399 // activity type id for contribution
1400 'activity_type_id' => 6,
1403 CRM_Activity_BAO_Activity
::deleteActivity($params);
1405 //delete billing address if exists for this contribution.
1406 self
::deleteAddress($id);
1408 //update pledge and pledge payment, CRM-3961
1409 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1411 // remove entry from civicrm_price_set_entity, CRM-5095
1412 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1413 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1415 // cleanup line items.
1416 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1418 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1419 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1421 if ($participantId) {
1422 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1425 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1429 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1430 $noteId = key($note);
1432 CRM_Core_BAO_Note
::deleteRecord(['id' => $noteId]);
1435 $dao = new CRM_Contribute_DAO_Contribution();
1438 $results = $dao->delete();
1440 $transaction->commit();
1442 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1448 * React to a financial transaction (payment) failure.
1450 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1451 * payments is important for forensic and outreach reasons.
1453 * @param int $contributionID
1454 * @param int $contactID
1455 * @param string $message
1457 * @throws \CiviCRM_API3_Exception
1459 public static function failPayment($contributionID, $contactID, $message) {
1460 civicrm_api3('activity', 'create', [
1461 'activity_type_id' => 'Failed Payment',
1462 'details' => $message,
1463 'subject' => ts('Payment failed at payment processor'),
1464 'source_record_id' => $contributionID,
1465 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() : $contactID,
1468 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1469 civicrm_api3('contribution', 'create', [
1470 'id' => $contributionID,
1471 'contribution_status_id' => 'Failed',
1476 * Check if there is a contribution with the same trxn_id or invoice_id.
1478 * @param array $input
1479 * An assoc array of name/value pairs.
1480 * @param array $duplicates
1481 * (reference) store ids of duplicate contribs.
1485 * true if duplicate, false otherwise
1487 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1489 $id = $input['id'] ??
NULL;
1491 $trxn_id = $input['trxn_id'] ??
NULL;
1492 $invoice_id = $input['invoice_id'] ??
NULL;
1498 $clause[] = 'trxn_id = %1';
1499 $input[1] = [$trxn_id, 'String'];
1503 $clause[] = "invoice_id = %2";
1504 $input[2] = [$invoice_id, 'String'];
1507 if (empty($clause)) {
1511 $clause = implode(' OR ', $clause);
1513 $clause = "( $clause ) AND id != %3";
1514 $input[3] = [$id, 'Integer'];
1517 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1518 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1520 while ($dao->fetch()) {
1521 $duplicates[] = $dao->id
;
1528 * Takes an associative array and creates a contribution_product object.
1530 * the function extract all the params it needs to initialize the create a
1531 * contribution_product object. the params array could contain additional unused name/value
1534 * @param array $params
1535 * (reference) an assoc array of name/value pairs.
1537 * @return CRM_Contribute_DAO_ContributionProduct
1539 public static function addPremium(&$params) {
1540 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1541 $contributionProduct->copyValues($params);
1542 return $contributionProduct->save();
1546 * Get list of contribution fields for profile.
1547 * For now we only allow custom contribution fields to be in
1550 * @param bool $addExtraFields
1551 * True if special fields needs to be added.
1554 * the list of contribution fields
1556 public static function getContributionFields($addExtraFields = TRUE) {
1557 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1558 // @todo remove this - this line was added because payment_instrument_id was not
1559 // set to exportable - but now it is.
1560 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1562 if ($addExtraFields) {
1563 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1566 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1568 foreach ($contributionFields as $key => $var) {
1569 if ($key === 'contribution_contact_id') {
1572 elseif ($key === 'contribution_campaign_id') {
1573 $var['title'] = ts('Campaign');
1575 $fields[$key] = $var;
1578 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1583 * Add extra fields specific to contribution.
1585 public static function getSpecialContributionFields() {
1587 'contribution_soft_credit_name' => [
1588 'name' => 'contribution_soft_credit_name',
1589 'title' => ts('Soft Credit Name'),
1590 'headerPattern' => '/^soft_credit_name$/i',
1591 'where' => 'civicrm_contact_d.display_name',
1593 'contribution_soft_credit_email' => [
1594 'name' => 'contribution_soft_credit_email',
1595 'title' => ts('Soft Credit Email'),
1596 'headerPattern' => '/^soft_credit_email$/i',
1597 'where' => 'soft_email.email',
1599 'contribution_soft_credit_phone' => [
1600 'name' => 'contribution_soft_credit_phone',
1601 'title' => ts('Soft Credit Phone'),
1602 'headerPattern' => '/^soft_credit_phone$/i',
1603 'where' => 'soft_phone.phone',
1605 'contribution_soft_credit_contact_id' => [
1606 'name' => 'contribution_soft_credit_contact_id',
1607 'title' => ts('Soft Credit Contact ID'),
1608 'headerPattern' => '/^soft_credit_contact_id$/i',
1609 'where' => 'civicrm_contribution_soft.contact_id',
1611 'contribution_pcp_title' => [
1612 'name' => 'contribution_pcp_title',
1613 'title' => ts('Personal Campaign Page Title'),
1614 'headerPattern' => '/^contribution_pcp_title$/i',
1615 'where' => 'contribution_pcp.title',
1619 return $extraFields;
1623 * @param int $pageID
1627 public static function getCurrentandGoalAmount($pageID) {
1629 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1630 FROM civicrm_contribution_page p,
1631 civicrm_contribution c
1632 WHERE p.id = c.contribution_page_id
1634 AND c.cancel_date is null
1638 $config = CRM_Core_Config
::singleton();
1639 $params = [1 => [$pageID, 'Integer']];
1640 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1642 if ($dao->fetch()) {
1643 return [$dao->goal
, $dao->total
];
1646 return [NULL, NULL];
1651 * Get list of contributions which credit the passed in contact ID.
1653 * The returned array provides details about the original contribution & donor.
1655 * @param int $honorId
1656 * In Honor of Contact ID.
1659 * list of contribution fields
1660 * @todo - this is a confusing function called from one place. It has a test. It would be
1661 * nice to deprecate it.
1664 public static function getHonorContacts($honorId) {
1666 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1667 $honorDAO->contact_id
= $honorId;
1670 $type = CRM_Contribute_PseudoConstant
::financialType();
1672 while ($honorDAO->fetch()) {
1673 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1674 $contributionDAO->id
= $honorDAO->contribution_id
;
1676 if ($contributionDAO->find(TRUE)) {
1677 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1678 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1679 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1680 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1681 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1682 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1683 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1684 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1685 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
, 'label');
1693 * Get the sort name of a contact for a particular contribution.
1696 * Id of the contribution.
1698 * @return null|string
1699 * sort name of the contact if found
1701 public static function sortName($id) {
1702 $id = CRM_Utils_Type
::escape($id, 'Integer');
1705 SELECT civicrm_contact.sort_name
1706 FROM civicrm_contribution, civicrm_contact
1707 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1708 AND civicrm_contribution.id = {$id}
1710 return CRM_Core_DAO
::singleValueQuery($query);
1714 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1716 * @param int|array $contactIDs
1720 public static function annual($contactIDs) {
1721 if (!is_array($contactIDs)) {
1722 // In practice I can't fine any evidence that this function is ever called with
1723 // anything other than a single contact id, but left like this due to .... fear.
1724 $contactIDs = explode(',', $contactIDs);
1727 $query = self
::getAnnualQuery($contactIDs);
1728 $dao = CRM_Core_DAO
::executeQuery($query);
1730 $amount = $average = [];
1731 while ($dao->fetch()) {
1732 if ($dao->count
> 0 && $dao->amount
> 0) {
1733 $count +
= $dao->count
;
1734 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1735 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1741 implode(', ', $amount),
1742 implode(', ', $average),
1749 * Check if there is a contribution with the params passed in.
1751 * Used for trxn_id,invoice_id and contribution_id
1753 * @param array $params
1754 * An assoc array of name/value pairs.
1757 * contribution id if success else NULL
1759 public static function checkDuplicateIds($params) {
1760 $dao = new CRM_Contribute_DAO_Contribution();
1764 foreach ($params as $k => $v) {
1766 $clause[] = "$k = '$v'";
1769 $clause = implode(' AND ', $clause);
1770 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1771 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1773 while ($dao->fetch()) {
1781 * Get the contribution details for component export.
1783 * @param int $exportMode
1785 * @param array $componentIds
1791 public static function getContributionDetails($exportMode, $componentIds) {
1792 $paymentDetails = [];
1793 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1795 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1796 $componentSelect = " civicrm_participant_payment.participant_id id";
1797 $additionalClause = "
1798 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1799 AND civicrm_participant_payment.participant_id {$componentClause} )
1802 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1803 $componentSelect = " civicrm_membership_payment.membership_id id";
1804 $additionalClause = "
1805 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1806 AND civicrm_membership_payment.membership_id {$componentClause} )
1809 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1810 $componentSelect = " civicrm_pledge_payment.id id";
1811 $additionalClause = "
1812 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1813 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1817 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1818 trxn_id, {$componentSelect}
1819 FROM civicrm_contribution
1820 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1821 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1822 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1823 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1824 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1825 AND option_group_contribution_status.id = contribution_status.option_group_id )
1829 $dao = CRM_Core_DAO
::executeQuery($query);
1831 while ($dao->fetch()) {
1832 $paymentDetails[$dao->id
] = [
1833 'total_amount' => $dao->total_amount
,
1834 'contribution_status' => $dao->status
,
1835 'receive_date' => $dao->receive_date
,
1836 'pay_instru' => $dao->payment_instrument
,
1837 'trxn_id' => $dao->trxn_id
,
1841 return $paymentDetails;
1845 * Create address associated with contribution record.
1847 * As long as there is one or more billing field in the parameters we will create the address.
1849 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1852 * @param array $params
1853 * @param int $billingLocationTypeID
1858 public static function createAddress($params, $billingLocationTypeID) {
1859 [$hasBillingField, $addressParams] = self
::getBillingAddressParams($params, $billingLocationTypeID);
1860 if ($hasBillingField) {
1861 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1862 return $address->id
;
1869 * Delete billing address record related contribution.
1871 * @param int $contributionId
1872 * @param int $contactId
1874 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1876 $contactJoin = NULL;
1878 if ($contributionId) {
1879 $clauses[] = "cc.id = {$contributionId}";
1883 $clauses[] = "cco.id = {$contactId}";
1884 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1887 if (empty($clauses)) {
1888 throw new CRM_Core_Exception('No Where clauses defined when deleting address');
1891 $condition = implode(' OR ', $clauses);
1895 FROM civicrm_address ca
1896 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1900 $dao = CRM_Core_DAO
::executeQuery($query);
1902 while ($dao->fetch()) {
1903 $params = ['id' => $dao->id
];
1904 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1909 * This function check online pending contribution associated w/
1910 * Online Event Registration or Online Membership signup.
1912 * @param int $componentId
1913 * Participant/membership id.
1914 * @param string $componentName
1918 * pending contribution id.
1920 public static function checkOnlinePendingContribution($componentId, $componentName) {
1921 $contributionId = NULL;
1922 if (!$componentId ||
1923 !in_array($componentName, ['Event', 'Membership'])
1925 return $contributionId;
1928 if ($componentName === 'Event') {
1929 $idName = 'participant_id';
1930 $componentTable = 'civicrm_participant';
1931 $paymentTable = 'civicrm_participant_payment';
1932 $source = ts('Online Event Registration');
1935 if ($componentName === 'Membership') {
1936 $idName = 'membership_id';
1937 $componentTable = 'civicrm_membership';
1938 $paymentTable = 'civicrm_membership_payment';
1939 $source = ts('Online Contribution');
1942 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1945 SELECT component.id as {$idName},
1946 componentPayment.contribution_id as contribution_id,
1947 contribution.source source,
1948 contribution.contribution_status_id as contribution_status_id,
1949 contribution.is_pay_later as is_pay_later
1950 FROM $componentTable component
1951 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1952 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1953 WHERE component.id = {$componentId}";
1955 $dao = CRM_Core_DAO
::executeQuery($query);
1957 while ($dao->fetch()) {
1958 if ($dao->contribution_id
&&
1959 $dao->is_pay_later
&&
1960 $dao->contribution_status_id
== $pendingStatusId &&
1961 strpos($dao->source
, $source) !== FALSE
1963 $contributionId = $dao->contribution_id
;
1967 return $contributionId;
1971 * Update contribution as well as related objects.
1973 * This function by-passes hooks - to address this - don't use this function.
1975 * @param array $params
1977 * @throws CRM_Core_Exception
1978 * @throws \CiviCRM_API3_Exception
1981 * Use api contribute.completetransaction
1982 * For failures use failPayment (preferably exposing by api in the process).
1985 public static function transitionComponents($params) {
1986 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution_status_id']);
1987 $previousStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['previous_contribution_status_id']);
1988 // @todo fix the one place that calls this function to use Payment.create
1990 // get minimum required values.
1991 $contributionId = $params['contribution_id'];
1992 $contributionStatusId = $params['contribution_status_id'];
1994 // we process only ( Completed, Cancelled, or Failed ) contributions.
1995 if (!$contributionId ||
$contributionStatus !== 'Completed') {
1999 // get the related component details.
2000 $componentDetails = self
::getComponentDetails($contributionId);
2002 if (!empty($componentDetails['contact_id'])) {
2003 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2009 // do check for required ids.
2010 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
2016 $input['component'] = $componentDetails['component'] ??
NULL;
2017 $ids['contribution'] = $contributionId;
2018 $ids['contact'] = $componentDetails['contact_id'] ??
NULL;
2019 $ids['membership'] = $componentDetails['membership'] ??
NULL;
2020 $ids['participant'] = $componentDetails['participant'] ??
NULL;
2021 $ids['event'] = $componentDetails['event'] ??
NULL;
2022 $ids['pledge_payment'] = $componentDetails['pledge_payment'] ??
NULL;
2023 $ids['contributionRecur'] = NULL;
2024 $ids['contributionPage'] = NULL;
2026 $contribution = new CRM_Contribute_BAO_Contribution();
2027 $contribution->id
= $ids['contribution'];
2028 $contribution->find();
2030 $contribution->loadRelatedObjects($input, $ids);
2032 $memberships = $contribution->_relatedObjects
['membership'] ??
[];
2033 $participant = $contribution->_relatedObjects
['participant'] ??
[];
2034 $pledgePayment = $contribution->_relatedObjects
['pledge_payment'] ??
[];
2036 $pledgeID = $oldStatus = NULL;
2037 $pledgePaymentIDs = [];
2038 if ($pledgePayment) {
2039 foreach ($pledgePayment as $key => $object) {
2040 $pledgePaymentIDs[] = $object->id
;
2042 $pledgeID = $pledgePayment[0]->pledge_id
;
2045 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
2048 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
2049 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
2055 // only pending contribution related object processed.
2056 if (!in_array($previousStatus, ['Pending', 'Partially paid'])) {
2057 // this is case when we already processed contribution object.
2061 if (is_array($memberships)) {
2062 foreach ($memberships as $membership) {
2067 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
2068 $membership->membership_type_id
,
2069 $membership->is_test
, $membership->id
2072 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2073 // this picks up membership type changes during renewals
2075 SELECT membership_type_id
2076 FROM civicrm_membership_log
2077 WHERE membership_id=$membership->id
2080 $dao = CRM_Core_DAO
::executeQuery($sql);
2081 if ($dao->fetch()) {
2082 if (!empty($dao->membership_type_id
)) {
2083 $membership->membership_type_id
= $dao->membership_type_id
;
2084 $membership->save();
2087 // else fall back to using current membership type
2088 // Figure out number of terms
2090 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
2091 foreach ($lineitems as $lineitem) {
2092 if ($membership->membership_type_id
== ($lineitem['membership_type_id'] ??
NULL)) {
2093 $numterms = $lineitem['membership_num_terms'] ??
NULL;
2095 // in case membership_num_terms comes through as null or zero
2096 $numterms = $numterms >= 1 ?
$numterms : 1;
2101 // CRM-15735-to update the membership status as per the contribution receive date
2103 $oldStatus = $membership->status_id
;
2104 if (!empty($params['receive_date'])) {
2105 $joinDate = $params['receive_date'];
2106 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
2107 $membership->end_date
,
2108 $membership->join_date
,
2109 $params['receive_date'],
2111 $membership->membership_type_id
,
2114 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
2115 $membership->save();
2118 if ($currentMembership) {
2119 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2120 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
2121 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2124 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
2127 //get the status for membership.
2128 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
2130 $dates['join_date'],
2133 $membership->membership_type_id
,
2137 $formattedParams = [
2138 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
2139 array_search('Current', $membershipStatuses)
2141 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
2142 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
2143 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
2146 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
2148 $membership->copyValues($formattedParams);
2149 $membership->save();
2151 //updating the membership log
2152 $membershipLog = $formattedParams;
2153 $logStartDate = CRM_Utils_Date
::customFormat($dates['log_start_date'] ??
NULL, $format);
2154 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
2156 $membershipLog['start_date'] = $logStartDate;
2157 $membershipLog['membership_id'] = $membership->id
;
2158 $membershipLog['modified_id'] = $membership->contact_id
;
2159 $membershipLog['modified_date'] = date('Ymd');
2160 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
2162 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2164 //update related Memberships.
2165 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2167 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2168 $scheduledActivityID = CRM_Utils_Array
::value('id',
2169 civicrm_api3('Activity', 'Get',
2171 'source_record_id' => $membership->id
,
2172 'activity_type_id' => $activityType,
2173 'status_id' => 'Scheduled',
2176 'sort' => 'id DESC',
2181 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2182 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2183 if ($scheduledActivityID) {
2184 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, ['id' => $scheduledActivityID]);
2189 // track membership status change if any
2190 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
2191 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2192 CRM_Activity_BAO_Activity
::addActivity($membership,
2193 'Change Membership Status',
2196 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2197 'source_contact_id' => $membershipLog['modified_id'],
2198 'priority_id' => 'Normal',
2203 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2209 $updatedStatusId = array_search('Registered', $participantStatuses);
2210 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2213 if ($pledgePayment) {
2214 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2220 * Returns all contribution related object ids.
2222 * @param $contributionId
2226 public static function getComponentDetails($contributionId) {
2227 $componentDetails = $pledgePayment = [];
2228 if (!$contributionId) {
2229 return $componentDetails;
2233 SELECT c.id as contribution_id,
2234 c.contact_id as contact_id,
2235 c.contribution_recur_id,
2236 mp.membership_id as membership_id,
2237 m.membership_type_id as membership_type_id,
2238 pp.participant_id as participant_id,
2239 p.event_id as event_id,
2240 pgp.id as pledge_payment_id
2241 FROM civicrm_contribution c
2242 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2243 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2244 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2245 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2246 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2247 WHERE c.id = $contributionId";
2249 $dao = CRM_Core_DAO
::executeQuery($query);
2250 $componentDetails = [];
2252 while ($dao->fetch()) {
2253 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2254 $componentDetails['contact_id'] = $dao->contact_id
;
2255 if ($dao->event_id
) {
2256 $componentDetails['event'] = $dao->event_id
;
2258 if ($dao->participant_id
) {
2259 $componentDetails['participant'] = $dao->participant_id
;
2261 if ($dao->membership_id
) {
2262 if (!isset($componentDetails['membership'])) {
2263 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2265 $componentDetails['membership'][] = $dao->membership_id
;
2266 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2268 if ($dao->pledge_payment_id
) {
2269 $pledgePayment[] = $dao->pledge_payment_id
;
2271 if ($dao->contribution_recur_id
) {
2272 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2276 if ($pledgePayment) {
2277 $componentDetails['pledge_payment'] = $pledgePayment;
2280 return $componentDetails;
2284 * @param int $contactId
2285 * @param bool $includeSoftCredit
2287 * @return null|string
2289 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2293 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2294 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2295 $liWhere = " AND i.financial_type_id IN (0)";
2296 if (!empty($financialTypes)) {
2297 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2298 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2300 $contactContributionsSQL = "
2301 SELECT contribution.id AS id
2302 FROM civicrm_contribution contribution
2303 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2304 WHERE contribution.is_test = 0 AND contribution.is_template != '1' AND contribution.contact_id = {$contactId}
2308 $contactSoftCreditContributionsSQL = "
2309 SELECT contribution.id
2310 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2311 ON ( contribution.id = softContribution.contribution_id )
2312 WHERE contribution.is_test = 0 AND contribution.is_template != '1' AND softContribution.contact_id = {$contactId} ";
2313 $query = "SELECT count( x.id ) count FROM ( ";
2314 $query .= $contactContributionsSQL;
2316 if ($includeSoftCredit) {
2317 $query .= " UNION ";
2318 $query .= $contactSoftCreditContributionsSQL;
2323 return CRM_Core_DAO
::singleValueQuery($query);
2327 * Repeat a transaction as part of a recurring series.
2330 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2331 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2332 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2333 * and associated entities.
2334 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2335 * which updates the various entities and sends appropriate emails.
2337 * Gaps in the above (
2339 * @param array $input
2341 * @param array $contributionParams
2343 * @return bool|array
2344 * @throws \API_Exception
2345 * @throws \CiviCRM_API3_Exception
2346 * @throws \Civi\API\Exception\UnauthorizedException
2348 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2349 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2350 * 3) Repeat transaction duplicates rather than calls Order.create
2351 * 4) Use of payment.create still limited - completetransaction is more common.
2352 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2353 * to load the membership(s) referred to via line items in the template transactions. Any other
2354 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2355 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2356 * - membership_payment record
2357 * - civicrm_membership.contribution_recur_id
2359 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2360 * of historical processors since this has been handled 'forever' - specifically for paypal.
2361 * albeit by an even nastier mechanism than the current input override.
2362 * The count is out on how correct related entities wind up in this case.
2364 protected static function repeatTransaction(array $input, array $contributionParams) {
2365 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2366 (int) $contributionParams['contribution_recur_id'],
2368 'total_amount' => $input['total_amount'] ??
NULL,
2369 'financial_type_id' => $input['financial_type_id'] ??
NULL,
2370 'campaign_id' => $input['campaign_id'] ??
NULL,
2371 // array_filter with strlen filters out NULL, '' and FALSE but not 0.
2374 $contributionParams['line_item'] = $templateContribution['line_item'];
2375 $contributionParams['status_id'] = 'Pending';
2377 foreach (['contact_id', 'campaign_id', 'financial_type_id', 'currency', 'source', 'amount_level', 'address_id', 'on_behalf', 'source_contact_id', 'tax_amount', 'contribution_page_id', 'total_amount'] as $fieldName) {
2378 if (isset($templateContribution[$fieldName])) {
2379 $contributionParams[$fieldName] = $templateContribution[$fieldName];
2383 $contributionParams['source'] = $contributionParams['source'] ??
ts('Recurring contribution');
2385 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2386 $temporaryObject = new CRM_Contribute_BAO_Contribution();
2387 $temporaryObject->copyCustomFields($templateContribution['id'], $createContribution['id']);
2388 self
::handleMembershipIDOverride($createContribution['id'], $input);
2389 // Add new soft credit against current $contribution.
2390 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($contributionParams['contribution_recur_id'], $createContribution['id']);
2391 return $createContribution;
2395 * Get individual id for onbehalf contribution.
2397 * @param int $contributionId
2399 * @param int $contributorId
2403 * containing organization id and individual id
2405 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2409 if (!$contributionId) {
2413 // fetch contributor id if null
2414 if (!$contributorId) {
2415 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2416 $contributionId, 'contact_id'
2420 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2421 $activityTypeId = array_search('Contribution', $activityTypeIds);
2423 if ($activityTypeId && $contributorId) {
2425 SELECT civicrm_activity_contact.contact_id
2426 FROM civicrm_activity_contact
2427 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2428 WHERE civicrm_activity.activity_type_id = %1
2429 AND civicrm_activity.source_record_id = %2
2430 AND civicrm_activity_contact.record_type_id = %3
2433 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2434 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2437 1 => [$activityTypeId, 'Integer'],
2438 2 => [$contributionId, 'Integer'],
2439 3 => [$sourceID, 'Integer'],
2442 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2444 // for on behalf contribution source is individual and contributor is organization
2445 if ($sourceContactId && $sourceContactId != $contributorId) {
2446 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2447 // get rel type id for employee of relation
2448 foreach ($relationshipTypeIds as $id => $typeVals) {
2449 if ($typeVals['name_a_b'] == 'Employee of') {
2450 $relationshipTypeId = $id;
2455 $rel = new CRM_Contact_DAO_Relationship();
2456 $rel->relationship_type_id
= $relationshipTypeId;
2457 $rel->contact_id_a
= $sourceContactId;
2458 $rel->contact_id_b
= $contributorId;
2459 if ($rel->find(TRUE)) {
2460 $ids['individual_id'] = $rel->contact_id_a
;
2461 $ids['organization_id'] = $rel->contact_id_b
;
2472 public static function getContributionDates() {
2473 $config = CRM_Core_Config
::singleton();
2474 $currentMonth = date('m');
2475 $currentDay = date('d');
2476 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2477 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2478 (int ) $config->fiscalYearStart
['d'] > $currentDay
2481 $year = date('Y') - 1;
2486 $year = ['Y' => $year];
2487 $yearDate = $config->fiscalYearStart
;
2488 $yearDate = array_merge($year, $yearDate);
2489 $yearDate = CRM_Utils_Date
::format($yearDate);
2491 $monthDate = date('Ym') . '01';
2497 'yearDate' => $yearDate,
2498 'monthDate' => $monthDate,
2503 * Load objects relations to contribution object.
2504 * Objects are stored in the $_relatedObjects property
2505 * In the first instance we are just moving functionality from BASEIpn -
2507 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2509 * Note that the unit test for the BaseIPN class tests this function
2511 * @param array $input
2512 * Input as delivered from Payment Processor.
2514 * Ids as Loaded by Payment Processor.
2515 * @param bool $loadAll
2516 * Load all related objects - even where id not passed in? (allows API to call this).
2519 * @throws CRM_Core_Exception
2521 public function loadRelatedObjects($input, &$ids, $loadAll = FALSE) {
2522 // @todo deprecate this function - the steps should be
2523 // 1) add additional functions like 'getRelatedMemberships'
2524 // 2) switch all calls that refer to ->_relatedObjects to
2525 // using the helper functions
2526 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2527 // 4) make ->_relatedObjects protected
2528 // 5) hone up the individual functions to not use rely on this having been called
2529 // 6) deprecate like mad
2531 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2532 if (empty($ids['contact']) && isset($this->contact_id
)) {
2533 $ids['contact'] = $this->contact_id
;
2536 if (empty($this->_component
)) {
2537 if (!empty($ids['event'])) {
2538 $this->_component
= 'event';
2541 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2545 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2546 // refactoring than anything else, and has unit test coverage.
2547 if (empty($this->financial_type_id
)) {
2551 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2556 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2557 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2558 $this->contribution_page_id
,
2561 if ($paymentProcessorID) {
2562 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2566 $ids['contributionType'] = $this->financial_type_id
;
2567 $ids['financialType'] = $this->financial_type_id
;
2568 if ($this->contribution_page_id
) {
2569 $ids['contributionPage'] = $this->contribution_page_id
;
2572 $this->loadRelatedEntitiesByID($ids);
2574 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2575 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2578 if (!empty($ids['pledge_payment'])) {
2579 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2580 if (empty($paymentID)) {
2583 $payment = new CRM_Pledge_BAO_PledgePayment();
2584 $payment->id
= $paymentID;
2585 if (!$payment->find(TRUE)) {
2586 throw new CRM_Core_Exception("Could not find pledge payment record: " . $paymentID);
2588 $this->_relatedObjects
['pledge_payment'][] = $payment;
2592 // These are probably no longer accessed from anywhere
2593 // @todo remove this line, after ensuring not used.
2594 $ids = $this->loadRelatedMembershipObjects($ids);
2596 if ($this->_component
!= 'contribute') {
2597 // we are in event mode
2598 // make sure event exists and is valid
2599 $event = new CRM_Event_BAO_Event();
2600 $event->id
= $ids['event'];
2601 if ($ids['event'] &&
2604 throw new CRM_Core_Exception("Could not find event: " . $ids['event']);
2607 $this->_relatedObjects
['event'] = &$event;
2609 $participant = new CRM_Event_BAO_Participant();
2610 $participant->id
= $ids['participant'];
2611 if ($ids['participant'] &&
2612 !$participant->find(TRUE)
2614 throw new CRM_Core_Exception("Could not find participant: " . $ids['participant']);
2616 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2618 $this->_relatedObjects
['participant'] = &$participant;
2620 // get the payment processor id from event - this is inaccurate see CRM-16923
2621 // in future we should look at throwing an exception here rather than an dubious guess.
2622 if (!$paymentProcessorID) {
2623 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2624 if ($paymentProcessorID) {
2625 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2630 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds($this->id
);
2631 if (!empty($relatedContact['individual_id'])) {
2632 $ids['related_contact'] = $relatedContact['individual_id'];
2635 if ($paymentProcessorID) {
2636 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2637 $this->is_test ?
'test' : 'live'
2639 $ids['paymentProcessor'] = $paymentProcessorID;
2640 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2643 // Add contribution id to $ids. CRM-20401
2644 $ids['contribution'] = $this->id
;
2649 * Create array of message information - ie. return html version, txt version, to field
2651 * @param array $input
2652 * Incoming information.
2653 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2654 * just check presence of recur object but maintaining legacy approach
2657 * IDs of related objects.
2658 * @param array $values
2659 * Any values that may have already been compiled by calling process.
2660 * This is augmented by values 'gathered' by gatherMessageValues
2661 * @param bool $returnMessageText
2662 * Distinguishes between whether to send message or return.
2663 * message text. We are working towards this function ALWAYS returning message text & calling
2664 * function doing emails / pdfs with it
2670 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2671 $this->loadRelatedObjects($input, $ids, TRUE);
2673 if (empty($this->_component
)) {
2674 $this->_component
= $input['component'] ??
NULL;
2677 //not really sure what params might be passed in but lets merge em into values
2678 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2679 $values['is_email_receipt'] = !$returnMessageText;
2680 foreach (['receipt_date', 'cc_receipt', 'bcc_receipt', 'receipt_from_name', 'receipt_from_email', 'receipt_text', 'pay_later_receipt'] as $fld) {
2681 if (!empty($input[$fld])) {
2682 $values[$fld] = $input[$fld];
2686 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2687 //what does recur 'mean here - to do with payment processor return functionality but
2688 // what is the importance
2689 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2690 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2692 $entityID = $entity = NULL;
2693 if (isset($ids['contribution'])) {
2694 $entity = 'contribution';
2695 $entityID = $ids['contribution'];
2697 if (!empty($ids['membership'])) {
2698 //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
2699 // 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
2700 // line having loaded an array
2701 $ids['membership'] = (array) $ids['membership'];
2702 $entity = 'membership';
2703 $entityID = $ids['membership'][0];
2706 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2707 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2708 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2710 // todo remove strtolower - check consistency
2711 if (strtolower($this->_component
) === 'event') {
2712 $eventParams = ['id' => $this->_relatedObjects
['participant']->event_id
];
2713 $values['event'] = [];
2715 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2717 //get location details
2719 'entity_id' => $this->_relatedObjects
['participant']->event_id
,
2720 'entity_table' => 'civicrm_event',
2722 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2725 'entity_table' => 'civicrm_event',
2726 'entity_id' => $ids['event'],
2727 'module' => 'CiviEvent',
2730 [$custom_pre_id, $custom_post_ids] = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2732 $values['custom_pre_id'] = $custom_pre_id;
2733 $values['custom_post_id'] = $custom_post_ids;
2734 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2735 //and cases involving status updation through ipn
2736 // whatever that means!
2737 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2738 // perhaps we should throw an e-notice if amount is set & force total_amount?
2739 if (!empty($input['amount'])) {
2740 $values['totalAmount'] = $input['amount'];
2742 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2743 if ($values['event']['is_email_confirm']) {
2744 $values['is_email_receipt'] = 1;
2747 if (!empty($ids['contribution'])) {
2748 $values['contributionId'] = $ids['contribution'];
2751 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2752 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2756 $values['contribution_id'] = $this->id
;
2757 if (!empty($ids['related_contact'])) {
2758 $values['related_contact'] = $ids['related_contact'];
2759 if (isset($ids['onbehalf_dupe_alert'])) {
2760 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2763 'contact_id' => $ids['contact'],
2764 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2765 'Home', 'id', 'name'
2768 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2769 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display'] ??
NULL);
2772 if ($this->is_test
) {
2775 if (!empty($this->_relatedObjects
['membership'])) {
2776 foreach ($this->_relatedObjects
['membership'] as $membership) {
2777 if ($membership->id
) {
2778 $values['membership_id'] = $membership->id
;
2779 $values['isMembership'] = TRUE;
2780 $values['membership_assign'] = TRUE;
2782 // need to set the membership values here
2783 $template->assign('membership_name',
2784 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2786 $template->assign('mem_start_date', $membership->start_date
);
2787 $template->assign('mem_join_date', $membership->join_date
);
2788 $template->assign('mem_end_date', $membership->end_date
);
2789 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2790 $template->assign('mem_status', $membership_status);
2791 if ($membership_status === 'Pending' && $membership->is_pay_later
== 1) {
2792 $values['is_pay_later'] = 1;
2794 // Pass amount to floatval as string '0.00' is considered a
2795 // valid amount and includes Fee section in the mail.
2796 if (isset($values['amount'])) {
2797 $values['amount'] = floatval($values['amount']);
2800 if (!empty($this->contribution_recur_id
) && $paymentObject) {
2801 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2802 $template->assign('cancelSubscriptionUrl', $url);
2803 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2804 $template->assign('updateSubscriptionBillingUrl', $url);
2805 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2806 $template->assign('updateSubscriptionUrl', $url);
2809 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2812 // otherwise if its about sending emails, continue sending without return, as we
2813 // don't want to exit the loop.
2818 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2824 * Gather values for contribution mail - this function has been created
2825 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2826 * Values related to the contribution in question are gathered
2828 * @param array $input
2829 * Input into function (probably from payment processor).
2830 * @param array $values
2832 * The set of ids related to the input.
2835 * @throws \CRM_Core_Exception
2837 public function _gatherMessageValues($input, &$values, $ids = []) {
2838 // set display address of contributor
2839 $values['billingName'] = '';
2840 if ($this->address_id
) {
2841 $addressDetails = CRM_Core_BAO_Address
::getValues(['id' => $this->address_id
], FALSE, 'id');
2842 $addressDetails = reset($addressDetails);
2843 $values['billingName'] = $addressDetails['name'] ??
'';
2845 // Else we assign the billing address of the contribution contact.
2847 $addressDetails = (array) CRM_Core_BAO_Address
::getValues(['contact_id' => $this->contact_id
, 'is_billing' => 1]);
2848 $addressDetails = reset($addressDetails);
2850 $values['address'] = $addressDetails['display'] ??
'';
2852 if ($this->_component
=== 'contribute') {
2853 //get soft contributions
2854 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2855 if (!empty($softContributions)) {
2856 // For pcp soft credit, there is no 'soft_credit' member it comes
2857 // back in different array members, but shortly after returning from
2858 // this function it calls _assignMessageVariablesToTemplate which does
2859 // its own lookup of any pcp soft credit, so we can skip it here.
2860 $values['softContributions'] = $softContributions['soft_credit'] ??
NULL;
2862 if (isset($this->contribution_page_id
)) {
2863 // This is a call we want to use less, in favour of loading related objects.
2864 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
2865 if ($this->contribution_page_id
) {
2866 // This is precautionary as there are some legacy flows, but it should really be
2868 if (!isset($this->_relatedObjects
['contributionPage'])) {
2869 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id
]);
2871 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($values);
2874 // no contribution page -probably back office
2876 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2877 $values['title'] = 'Contribution';
2879 // set lineItem for contribution
2881 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
2882 if (!empty($lineItems)) {
2883 $firstLineItem = reset($lineItems);
2885 if (!empty($firstLineItem['price_set_id'])) {
2886 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
2887 'id' => $firstLineItem['price_set_id'],
2888 'return' => 'is_quick_config, id',
2890 $values['priceSetID'] = $priceSet['id'];
2892 foreach ($lineItems as &$eachItem) {
2893 if ($eachItem['entity_table'] === 'civicrm_membership') {
2894 $membership = reset(civicrm_api3('Membership', 'get', [
2895 'id' => $eachItem['entity_id'],
2896 'return' => ['join_date', 'start_date', 'end_date'],
2899 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($membership['join_date']);
2900 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($membership['start_date']);
2901 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($membership['end_date']);
2904 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
2905 // However, that does create upgrade pain so would be better to be phased in.
2906 $values['useForMember'] = empty($priceSet['is_quick_config']);
2908 $values['lineItem'][0] = $lineItems;
2912 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2916 // if this is onbehalf of contribution then set related contact
2917 if (!empty($relatedContact['individual_id'])) {
2918 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2922 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects
['participant']->id
, $this->id
));
2925 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
2928 foreach ($groupTree as $key => $group) {
2929 if ($key === 'info') {
2933 foreach ($group['fields'] as $k => $customField) {
2934 $groupLabel = $group['title'];
2935 if (!empty($customField['customValue'])) {
2936 foreach ($customField['customValue'] as $customFieldValues) {
2937 $customGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
2942 $values['customGroup'] = $customGroup;
2944 $values['is_pay_later'] = $this->is_pay_later
;
2950 * Assign message variables to template but try to break the habit.
2952 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
2953 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
2954 * multiple recurring payments for processors like IATS that use tokens.
2956 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2957 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2958 * Note we send directly from this function in some cases because it is only partly refactored.
2960 * Don't call this function directly as the signature will change.
2964 * @param bool $returnMessageText
2968 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
2969 // @todo - this should have a better separation of concerns - ie.
2970 // gatherMessageValues should build an array of values to be assigned to the template
2971 // and this function should assign them (assigning null if not set).
2972 // the way the pcpParams & honor Params section works is a baby-step towards this.
2973 $template = CRM_Core_Smarty
::singleton();
2974 $template->assign('billingName', $values['billingName']);
2976 //assign honor information to receipt message
2977 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2980 'soft_credit_type' => NULL,
2981 'honor_block_is_active' => NULL,
2983 if (isset($softRecord['soft_credit'])) {
2984 //if id of contribution page is present
2985 if (!empty($values['id'])) {
2986 $values['honor'] = [
2987 'honor_profile_values' => [],
2988 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2989 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2992 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
2993 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
2996 //offline contribution
2997 $softCreditTypes = $softCredits = [];
2998 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2999 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3000 $softCredits[$key] = [
3001 'Name' => $softCredit['contact_name'],
3002 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
3005 $template->assign('softCreditTypes', $softCreditTypes);
3006 $template->assign('softCredits', $softCredits);
3010 $dao = new CRM_Contribute_DAO_ContributionProduct();
3011 $dao->contribution_id
= $this->id
;
3012 if ($dao->find(TRUE)) {
3013 $premiumId = $dao->product_id
;
3014 $template->assign('option', $dao->product_option
);
3016 $productDAO = new CRM_Contribute_DAO_Product();
3017 $productDAO->id
= $premiumId;
3018 $productDAO->find(TRUE);
3019 $template->assign('selectPremium', TRUE);
3020 $template->assign('product_name', $productDAO->name
);
3021 $template->assign('price', $productDAO->price
);
3022 $template->assign('sku', $productDAO->sku
);
3024 $template->assign('title', $values['title'] ??
NULL);
3025 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
3026 if (!$values['amount'] && isset($this->total_amount
)) {
3027 $values['amount'] = $this->total_amount
;
3032 'pcp_display_in_roll' => NULL,
3033 'pcp_roll_nickname' => NULL,
3034 'pcp_personal_note' => NULL,
3038 if (strtolower($this->_component
) == 'contribute') {
3040 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3041 $softDAO->contribution_id
= $this->id
;
3042 if ($softDAO->find(TRUE)) {
3043 $pcpParams['pcpBlock'] = TRUE;
3044 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
3045 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
3046 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
3048 //assign the pcp page title for email subject
3049 $pcpDAO = new CRM_PCP_DAO_PCP();
3050 $pcpDAO->id
= $softDAO->pcp_id
;
3051 if ($pcpDAO->find(TRUE)) {
3052 $pcpParams['title'] = $pcpDAO->title
;
3056 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3057 $template->assign($templateKey, $templateValue);
3060 if ($this->financial_type_id
) {
3061 $values['financial_type_id'] = $this->financial_type_id
;
3064 $template->assign('trxn_id', $this->trxn_id
);
3065 $template->assign('receive_date',
3066 CRM_Utils_Date
::processDate($this->receive_date
)
3068 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
3069 $template->assign('action', $this->is_test ?
1024 : 1);
3070 $template->assign('receipt_text', $values['receipt_text'] ??
NULL);
3071 $template->assign('is_monetary', 1);
3072 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3073 $template->assign('currency', $this->currency
);
3074 $template->assign('address', CRM_Utils_Address
::format($input));
3075 if (!empty($values['customGroup'])) {
3076 $template->assign('customGroup', $values['customGroup']);
3078 if (!empty($values['softContributions'])) {
3079 $template->assign('softContributions', $values['softContributions']);
3081 if ($this->_component
== 'event') {
3082 $template->assign('title', $values['event']['title']);
3083 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3085 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3086 $viewRoles[] = $participantRoles[$v];
3088 $values['event']['participant_role'] = implode(', ', $viewRoles);
3089 $template->assign('event', $values['event']);
3090 $template->assign('participant', $values['participant']);
3091 $template->assign('location', $values['location']);
3092 $template->assign('customPre', $values['custom_pre_id']);
3093 $template->assign('customPost', $values['custom_post_id']);
3096 if ($this->_relatedObjects
['participant']->is_test
) {
3100 $values['params'] = [];
3101 //to get email of primary participant.
3102 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3103 $primaryAmount[] = [
3104 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3105 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3107 //build an array of cId/pId of participants
3108 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3109 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3110 //send receipt to additional participant if exists
3111 if (count($additionalIDs)) {
3112 $template->assign('isPrimary', 0);
3113 $template->assign('customProfile', NULL);
3114 //set additionalParticipant true
3115 $values['params']['additionalParticipant'] = TRUE;
3116 foreach ($additionalIDs as $pId => $cId) {
3118 //to change the status pending to completed
3119 $additional = new CRM_Event_DAO_Participant();
3120 $additional->id
= $pId;
3121 $additional->contact_id
= $cId;
3122 $additional->find(TRUE);
3123 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3124 $additional->status_id
= 1;
3125 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3126 //if additional participant dont have email
3128 if (!$additionalParticipantInfo) {
3129 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3132 'label' => $additional->fee_level
,
3133 'amount' => $additional->fee_amount
,
3135 $primaryAmount[] = [
3136 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3137 'amount' => $additional->fee_amount
,
3139 $additional->save();
3140 $template->assign('amount', $amount);
3141 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3145 //build an array of custom profile and assigning it to template
3146 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3148 if (count($customProfile)) {
3149 $template->assign('customProfile', $customProfile);
3152 // for primary contact
3153 $values['params']['additionalParticipant'] = FALSE;
3154 $template->assign('isPrimary', 1);
3155 $template->assign('amount', $primaryAmount);
3156 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3157 if ($this->payment_instrument_id
) {
3158 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3159 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3161 // carry paylater, since we did not created billing,
3162 // so need to pull email from primary location, CRM-4395
3163 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3169 * Check whether payment processor supports
3170 * cancellation of contribution subscription
3172 * @param int $contributionId
3175 * @param bool $isNotCancelled
3179 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3180 $cacheKeyString = "$contributionId";
3181 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3183 static $supportsCancel = [];
3185 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3186 $supportsCancel[$cacheKeyString] = FALSE;
3187 $isCancelled = FALSE;
3189 if ($isNotCancelled) {
3190 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3193 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3194 if (!empty($paymentObject)) {
3195 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3198 return $supportsCancel[$cacheKeyString];
3202 * Check whether subscription is already cancelled.
3204 * @param int $contributionId
3208 * contribution status
3210 public static function isSubscriptionCancelled($contributionId) {
3212 SELECT cr.contribution_status_id
3213 FROM civicrm_contribution_recur cr
3214 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3215 WHERE con.id = %1 LIMIT 1";
3216 $params = [1 => [$contributionId, 'Integer']];
3217 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3218 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
3219 if ($status == 'Cancelled') {
3226 * Create all financial accounts entry.
3228 * @param array $params
3229 * Contribution object, line item array and params for trxn.
3232 * @return null|\CRM_Core_BAO_FinancialTrxn
3234 public static function recordFinancialAccounts(&$params) {
3235 $skipRecords = $return = FALSE;
3236 $isUpdate = !empty($params['prevContribution']);
3238 $additionalParticipantId = [];
3239 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3240 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3242 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3243 $entityId = $params['participant_id'];
3244 $entityTable = 'civicrm_participant';
3245 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3247 elseif (!empty($params['membership_id'])) {
3248 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3249 // are created off one contribution should be handled elsewhere
3250 $entityId = $params['membership_id'];
3251 $entityTable = 'civicrm_membership';
3254 $entityId = $params['contribution']->id
;
3255 $entityTable = 'civicrm_contribution';
3258 $entityID[] = $entityId;
3259 if (!empty($additionalParticipantId)) {
3260 $entityID +
= $additionalParticipantId;
3261 // build line item array if necessary
3262 if ($additionalParticipantId) {
3263 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable));
3266 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3267 if (empty($params['prevContribution'])) {
3271 $statusId = $params['contribution']->contribution_status_id
;
3273 if ($contributionStatus != 'Failed' &&
3274 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3276 $skipRecords = TRUE;
3281 if (in_array($contributionStatus, $pendingStatus)) {
3282 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3283 $params['financial_type_id'],
3284 'Accounts Receivable Account is'
3287 elseif (!empty($params['payment_processor'])) {
3288 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3289 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3290 'id' => $params['payment_processor'],
3291 'return' => 'payment_instrument_id',
3294 elseif (!empty($params['payment_instrument_id'])) {
3295 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3297 // dev/financial#160 - If this is a contribution update, also check for an existing payment_instrument_id.
3298 elseif ($isUpdate && $params['prevContribution']->payment_instrument_id
) {
3299 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount((int) $params['prevContribution']->payment_instrument_id
);
3302 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3303 $queryParams = [1 => [$relationTypeId, 'Integer']];
3304 $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);
3307 $totalAmount = $params['total_amount'] ??
NULL;
3308 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3309 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3311 //build financial transaction params
3313 'contribution_id' => $params['contribution']->id
,
3314 'to_financial_account_id' => $params['to_financial_account_id'],
3315 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3316 'total_amount' => $totalAmount,
3317 'fee_amount' => $params['fee_amount'] ??
NULL,
3318 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3319 'currency' => $params['contribution']->currency
,
3320 'trxn_id' => $params['contribution']->trxn_id
,
3321 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3322 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3323 // this should really default to completed (after discussion).
3324 'status_id' => $statusId,
3325 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3326 'check_number' => $params['check_number'] ??
NULL,
3327 'pan_truncation' => $params['pan_truncation'] ??
NULL,
3328 'card_type_id' => $params['card_type_id'] ??
NULL,
3330 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3331 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3332 if (isset($params['refund_trxn_id'])) {
3333 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3334 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3337 //CRM-16259, set is_payment flag for non pending status
3338 if (!in_array($contributionStatus, $pendingStatus)) {
3339 $trxnParams['is_payment'] = 1;
3341 if (!empty($params['payment_processor'])) {
3342 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3345 if (empty($trxnParams['payment_processor_id'])) {
3346 unset($trxnParams['payment_processor_id']);
3349 $params['trxnParams'] = $trxnParams;
3353 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3354 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3355 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3356 if (!isset($params['trxnParams']['trxn_id'])) {
3357 // Actually I have no idea why we are overwriting any values from the previous contribution.
3358 // (filling makes sense to me). However, only protecting this value as I really really know we
3359 // don't want this one overwritten.
3361 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3363 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3365 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3366 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3367 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3369 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3370 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3373 //if financial type is changed
3374 if (!empty($params['financial_type_id']) &&
3375 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3377 $accountRelationship = 'Income Account is';
3378 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3379 $accountRelationship = 'Deferred Revenue Account is';
3381 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3382 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3383 if ($oldFinancialAccount != $newFinancialAccount) {
3384 $params['total_amount'] = 0;
3385 // If we have a fee amount set reverse this as well.
3386 if (isset($params['fee_amount'])) {
3387 $params['trxnParams']['fee_amount'] = 0 - $params['fee_amount'];
3389 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3390 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3391 $params['prevContribution']->financial_type_id
, $accountRelationship);
3394 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3395 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3396 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3399 CRM_Contribute_BAO_FinancialProcessor
::updateFinancialAccounts($params, 'changeFinancialType');
3400 $params['skipLineItem'] = FALSE;
3401 foreach ($params['line_item'] as &$lineItems) {
3402 foreach ($lineItems as &$line) {
3403 $line['financial_type_id'] = $params['financial_type_id'];
3406 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType');
3407 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3408 $params['financial_account_id'] = $newFinancialAccount;
3409 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3410 // Set the transaction fee amount back to the original value for creating the new positive financial trxn.
3411 if (isset($params['fee_amount'])) {
3412 $params['trxnParams']['fee_amount'] = $params['fee_amount'];
3414 CRM_Contribute_BAO_FinancialProcessor
::updateFinancialAccounts($params);
3415 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE);
3416 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3418 $params['deferred_financial_account_id'] = $newFinancialAccount;
3422 //Update contribution status
3423 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3424 if (!isset($params['refund_trxn_id'])) {
3425 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3426 // gets preference over another so I am only 'protecting' a very specific tested flow
3427 // and letting natural justice take care of the rest.
3428 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3430 if (!empty($params['contribution_status_id']) &&
3431 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3433 //Update Financial Records
3434 $callUpdateFinancialAccounts = self
::updateFinancialAccountsOnContributionStatusChange($params);
3435 if ($callUpdateFinancialAccounts) {
3436 CRM_Contribute_BAO_FinancialProcessor
::updateFinancialAccounts($params, 'changedStatus');
3437 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus');
3442 // change Payment Instrument for a Completed contribution
3443 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3444 // instrument is null and now new payment instrument is added along with the payment
3445 if (!$params['contribution']->payment_instrument_id
) {
3446 $params['contribution']->find(TRUE);
3448 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3449 $params['trxnParams']['check_number'] = $params['check_number'] ??
NULL;
3451 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3452 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3455 //if Change contribution amount
3456 $params['trxnParams']['fee_amount'] = $params['fee_amount'] ??
NULL;
3457 $params['trxnParams']['net_amount'] = $params['net_amount'] ??
NULL;
3458 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3459 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3460 if (isset($totalAmount) &&
3461 $totalAmount != $params['prevContribution']->total_amount
3463 //Update Financial Records
3464 $params['trxnParams']['from_financial_account_id'] = NULL;
3465 CRM_Contribute_BAO_FinancialProcessor
::updateFinancialAccounts($params, 'changedAmount');
3466 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount');
3471 // Looks like we might have a data correction update.
3472 // This would be a case where a transaction id has been entered but it is incorrect &
3473 // the person goes back in & fixes it, as opposed to a new transaction.
3474 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3475 // the data fix scenario.
3477 if (isset($params['refund_trxn_id'])) {
3478 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3479 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3480 civicrm_api3('FinancialTrxn', 'create', [
3481 'id' => $refundIDs['financialTrxnId'],
3482 'trxn_id' => $params['refund_trxn_id'],
3486 $cardType = $params['card_type_id'] ??
NULL;
3487 $panTruncation = $params['pan_truncation'] ??
NULL;
3488 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3493 // records finanical trxn and entity financial trxn
3494 // also make it available as return value
3495 CRM_Contribute_BAO_FinancialProcessor
::recordAlwaysAccountsReceivable($trxnParams, $params);
3496 $trxnParams['pan_truncation'] = $params['pan_truncation'] ??
NULL;
3497 $trxnParams['card_type_id'] = $params['card_type_id'] ??
NULL;
3498 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3499 $params['entity_id'] = $financialTxn->id
;
3502 // record line items and financial items
3503 if (empty($params['skipLineItem'])) {
3504 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $isUpdate);
3507 // create batch entry if batch_id is passed and
3508 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3509 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3511 'batch_id' => $params['batch_id'],
3512 'entity_table' => 'civicrm_financial_trxn',
3513 'entity_id' => $financialTxn->id
,
3515 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3518 // when a fee is charged
3519 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3520 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3523 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3524 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3526 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3527 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3528 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3530 unset($params['line_item']);
3535 * Is this contribution status a reversal.
3537 * If so we would expect to record a negative value in the financial_trxn table.
3539 * @param int $status_id
3543 public static function isContributionStatusNegative($status_id) {
3544 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3545 return in_array(CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE);
3549 * Check status validation on update of a contribution.
3551 * @param array $values
3552 * Previous form values before submit.
3554 * @param array $fields
3555 * The input form values.
3557 * @param array $errors
3562 public static function checkStatusValidation($values, &$fields, &$errors) {
3563 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3564 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3565 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3569 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3571 'Cancelled' => ['Completed', 'Refunded'],
3572 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3573 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3574 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3575 'Refunded' => ['Cancelled', 'Completed'],
3576 'Partially paid' => ['Completed'],
3577 'Pending refund' => ['Completed', 'Refunded'],
3578 'Failed' => ['Pending'],
3581 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3582 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3584 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3585 1 => $contributionStatuses[$values['contribution_status_id']],
3586 2 => $contributionStatuses[$fields['contribution_status_id']],
3592 * Delete contribution of contact.
3594 * @see https://issues.civicrm.org/jira/browse/CRM-12155
3596 * @param int $contactId
3600 public static function deleteContactContribution($contactId) {
3601 $contribution = new CRM_Contribute_DAO_Contribution();
3602 $contribution->contact_id
= $contactId;
3603 $contribution->find();
3604 while ($contribution->fetch()) {
3605 self
::deleteContribution($contribution->id
);
3610 * Get options for a given contribution field.
3612 * @param string $fieldName
3613 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3614 * @param array $props whatever is known about this dao object.
3616 * @return array|bool
3617 * @see CRM_Core_DAO::buildOptions
3620 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3621 $className = __CLASS__
;
3623 if (isset($props['orderColumn'])) {
3624 $params['orderColumn'] = $props['orderColumn'];
3626 switch ($fieldName) {
3627 // This field is not part of this object but the api supports it
3628 case 'payment_processor':
3629 $className = 'CRM_Contribute_BAO_ContributionPage';
3630 // Filter results by contribution page
3631 if (!empty($props['contribution_page_id'])) {
3632 $page = civicrm_api('contribution_page', 'getsingle', [
3634 'id' => ($props['contribution_page_id']),
3636 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3637 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3641 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3642 case 'honor_type_id':
3643 $className = 'CRM_Contribute_BAO_ContributionSoft';
3644 $fieldName = 'soft_credit_type_id';
3645 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3648 case 'contribution_status_id':
3649 if ($context !== 'validate') {
3650 $params['condition'] = "v.name <> 'Template'";
3653 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3657 * Validate financial type.
3659 * @see https://issues.civicrm.org/jira/browse/CRM-13231
3661 * @param int $financialTypeId
3662 * Financial Type id.
3664 * @param string $relationName
3666 * @return array|bool
3668 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3669 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3671 if (!$financialAccount) {
3672 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3678 * @param int $targetCid
3679 * @param $activityType
3680 * @param string $title
3681 * @param int $contributionId
3682 * @param string $totalAmount
3683 * @param string $currency
3684 * @param string $trxn_date
3686 * @throws \CRM_Core_Exception
3687 * @throws \CiviCRM_API3_Exception
3689 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
3690 $paymentAmount = CRM_Utils_Money
::format($totalAmount, $currency);
3691 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3692 $date = CRM_Utils_Date
::isoToMysql($trxn_date);
3693 // source record id would be the contribution id
3694 $srcRecId = $contributionId;
3698 'source_contact_id' => $targetCid,
3699 'source_record_id' => $srcRecId,
3700 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
3701 'subject' => $subject,
3702 'activity_date_time' => $date,
3703 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
3704 'skipRecentView' => TRUE,
3707 // create activity with target contacts
3708 $session = CRM_Core_Session
::singleton();
3709 $id = $session->get('userID');
3711 $activityParams['source_contact_id'] = $id;
3712 $activityParams['target_contact_id'][] = $targetCid;
3714 civicrm_api3('Activity', 'create', $activityParams);
3718 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3721 * @param string $component
3722 * @param bool $getTrxnInfo
3726 * @throws \CRM_Core_Exception
3727 * @throws \CiviCRM_API3_Exception
3729 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE) {
3730 // @todo deprecate passing in component - always call with contribution.
3731 if ($component == 'event') {
3732 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3734 if (!$contributionId) {
3735 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3736 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3737 $id = $primaryParticipantId;
3739 if (!$contributionId) {
3744 elseif ($component == 'membership') {
3745 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
3748 $contributionId = $id;
3751 // The balance used to be calculated this way - we really want to remove this 'oldCalculation'
3752 // but need to unpick the whole trxn_id it's returning first.
3753 $oldCalculation = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3754 $baseTrxnId = !empty($oldCalculation['trxn_id']) ?
$oldCalculation['trxn_id'] : NULL;
3756 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3757 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3759 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
3761 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
3763 $contribution = civicrm_api3('Contribution', 'getsingle', [
3764 'id' => $contributionId,
3768 'contribution_status_id',
3769 'financial_type_id',
3773 $info['payLater'] = $contribution['is_pay_later'];
3774 $info['contribution_status'] = $contribution['contribution_status'];
3775 $info['currency'] = $contribution['currency'];
3777 $info['total'] = $total;
3778 $info['paid'] = $total - $paymentBalance;
3779 $info['balance'] = $paymentBalance;
3781 $info['component'] = $component;
3782 if ($getTrxnInfo && $baseTrxnId) {
3783 $info['transaction'] = self
::getContributionTransactionInformation($contributionId, $contribution['financial_type_id']);
3786 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
3791 * Get the outstanding balance on a contribution.
3793 * @param int $contributionId
3794 * @param float $contributionTotal
3795 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
3798 * @throws \CRM_Core_Exception
3800 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
3801 if ($contributionTotal === NULL) {
3802 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
3805 return (float) CRM_Utils_Money
::subtractCurrencies(
3807 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE),
3808 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
3813 * Check financial type validation on update of a contribution.
3815 * @param int $financialTypeId
3816 * Value of latest Financial Type.
3818 * @param int $contributionId
3821 * @param array $errors
3826 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
3827 if (!empty($financialTypeId)) {
3828 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3829 if ($oldFinancialTypeId == $financialTypeId) {
3833 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
3835 '1' => [$contributionId, 'Integer'],
3837 $result = CRM_Core_DAO
::executeQuery($sql, $params);
3838 if ($result->N
> 1) {
3839 $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.');
3844 * Update related pledge payment payments.
3846 * This function has been refactored out of the back office contribution form and may
3847 * still overlap with other functions.
3849 * @param string $action
3850 * @param int $pledgePaymentID
3851 * @param int $contributionID
3852 * @param bool $adjustTotalAmount
3853 * @param float $total_amount
3854 * @param float $original_total_amount
3855 * @param int $contribution_status_id
3856 * @param int $original_contribution_status_id
3858 public static function updateRelatedPledge(
3864 $original_total_amount,
3865 $contribution_status_id,
3866 $original_contribution_status_id
3868 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
3872 if ($pledgePaymentID) {
3873 //store contribution id in payment record.
3874 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
3877 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
3884 if (!$pledgePaymentID) {
3887 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
3893 $updatePledgePaymentStatus = FALSE;
3895 // If either the status or the amount has changed we update the pledge status.
3896 if ($action & CRM_Core_Action
::ADD
) {
3897 $updatePledgePaymentStatus = TRUE;
3899 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
3900 ($original_total_amount != $total_amount))
3902 $updatePledgePaymentStatus = TRUE;
3905 if ($updatePledgePaymentStatus) {
3906 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
3908 $contribution_status_id,
3917 * Is there only one line item attached to the contribution.
3923 * @throws \CiviCRM_API3_Exception
3925 public static function isSingleLineItem($id) {
3926 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
3927 return ($lineItemCount == 1);
3931 * Complete an order.
3933 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
3935 * Currently overloaded to complete a transaction & repeat a transaction - fix!
3937 * Moving it out of the BaseIPN class is just the first step.
3939 * @param array $input
3940 * @param int $recurringContributionID
3941 * @param int|null $contributionID
3942 * @param bool $isPostPaymentCreate
3943 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
3944 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
3945 * transitioning related elements).
3948 * @throws \API_Exception
3949 * @throws \CRM_Core_Exception
3950 * @throws \CiviCRM_API3_Exception
3952 public static function completeOrder($input, $recurringContributionID, $contributionID, $isPostPaymentCreate = FALSE) {
3953 $transaction = new CRM_Core_Transaction();
3955 $inputContributionWhiteList = [
3960 'payment_instrument_id',
3965 'contribution_status_id',
3968 'financial_type_id',
3971 $paymentProcessorId = $input['payment_processor_id'] ??
NULL;
3973 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
3975 $contributionParams = array_merge([
3976 'contribution_status_id' => $completedContributionStatusID,
3977 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
3980 $contributionParams['payment_processor'] = $paymentProcessorId;
3982 if (empty($contributionParams['payment_instrument_id']) && $paymentProcessorId) {
3983 $contributionParams['payment_instrument_id'] = PaymentProcessor
::get(FALSE)->addWhere('id', '=', $paymentProcessorId)->addSelect('payment_instrument_id')->execute()->first()['payment_instrument_id'];
3986 if ($recurringContributionID) {
3987 $contributionParams['contribution_recur_id'] = $recurringContributionID;
3990 if (!$contributionID) {
3991 $contributionResult = self
::repeatTransaction($input, $contributionParams);
3992 $contributionID = $contributionResult['id'];
3995 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
3996 self
::updateMembershipBasedOnCompletionOfContribution(
3998 $input['trxn_date'] ??
date('YmdHis')
4002 $participantPayments = civicrm_api3('ParticipantPayment', 'get', ['contribution_id' => $contributionID, 'return' => 'participant_id', 'sequential' => 1])['values'];
4003 if (!empty($participantPayments) && empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4004 foreach ($participantPayments as $participantPayment) {
4005 $participantParams['id'] = $participantPayment['participant_id'];
4006 $participantParams['status_id'] = 'Registered';
4007 civicrm_api3('Participant', 'create', $participantParams);
4011 $contributionParams['id'] = $contributionID;
4012 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
4014 if (empty($contributionResult)) {
4015 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4018 $transaction->commit();
4019 \Civi
::log()->info("Contribution {$contributionParams['id']} updated successfully");
4021 $contributionSoft = ContributionSoft
::get(FALSE)
4022 ->addWhere('contribution_id', '=', $contributionID)
4023 ->addWhere('pcp_id', '>', 0)
4025 ->execute()->first();
4026 if (!empty($contributionSoft)) {
4027 CRM_Contribute_BAO_ContributionSoft
::pcpNotifyOwner($contributionID, $contributionSoft);
4029 // @todo - check if Contribution::create does this, test, remove.
4030 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contributionID, $recurringContributionID,
4031 $contributionParams['contribution_status_id'], $input['amount']);
4033 if (self
::isEmailReceipt($input, $contributionID, $recurringContributionID)) {
4034 civicrm_api3('Contribution', 'sendconfirmation', [
4035 'id' => $contributionID,
4036 'payment_processor_id' => $paymentProcessorId,
4038 \Civi
::log()->info("Contribution {$contributionParams['id']} Receipt sent");
4041 return $contributionResult;
4045 * Send receipt from contribution.
4047 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4049 * Note that the compose message part has been moved to contribution
4050 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4052 * @param array $input
4053 * Incoming data from Payment processor.
4055 * Related object IDs.
4056 * @param int $contributionID
4057 * @param bool $returnMessageText
4058 * Should text be returned instead of sent. This.
4059 * is because the function is also used to generate pdfs
4062 * @throws \CRM_Core_Exception
4063 * @throws \CiviCRM_API3_Exception
4064 * @throws \Exception
4066 public static function sendMail($input, $ids, $contributionID, $returnMessageText = FALSE) {
4068 $contribution = new CRM_Contribute_BAO_Contribution();
4069 $contribution->id
= $contributionID;
4070 if (!$contribution->find(TRUE)) {
4071 throw new CRM_Core_Exception('Contribution does not exist');
4073 // set receipt from e-mail and name in value
4074 if (!$returnMessageText) {
4075 [$values['receipt_from_name'], $values['receipt_from_email']] = self
::generateFromEmailAndName($input, $contribution);
4077 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4078 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4079 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4080 civicrm_api3('Contribution', 'create', [
4081 'receipt_date' => 'now',
4082 'id' => $contribution->id
,
4089 * Generate From email and from name in an array values
4091 * @param array $input
4092 * @param \CRM_Contribute_BAO_Contribution $contribution
4096 public static function generateFromEmailAndName($input, $contribution) {
4097 // Use input value if supplied.
4098 if (!empty($input['receipt_from_email'])) {
4100 CRM_Utils_Array
::value('receipt_from_name', $input, ''),
4101 $input['receipt_from_email'],
4104 // if we are still empty see if we can use anything from a contribution page.
4106 if (!empty($contribution->contribution_page_id
)) {
4107 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id
]);
4109 // if we are still empty see if we can use anything from a contribution page.
4110 if (!empty($pageValues['receipt_from_email'])) {
4112 CRM_Utils_Array
::value('receipt_from_name', $pageValues),
4113 $pageValues['receipt_from_email'],
4116 // If we are still empty fall back to the domain or logged in user information.
4117 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4121 * Load related memberships.
4125 * @return array $ids
4130 * Note that in theory it should be possible to retrieve these from the line_item table
4131 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4132 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4133 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4134 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4136 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4139 public function loadRelatedMembershipObjects($ids = []) {
4141 SELECT membership_id
4142 FROM civicrm_membership_payment
4143 WHERE contribution_id = %1 ";
4144 $params = [1 => [$this->id
, 'Integer']];
4145 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, []);
4147 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4148 while ($dao->fetch()) {
4149 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4150 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4154 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4155 foreach ($ids['membership'] as $id) {
4157 $membership = new CRM_Member_BAO_Membership();
4158 $membership->id
= $id;
4159 if (!$membership->find(TRUE)) {
4160 throw new Exception("Could not find membership record: $id");
4162 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4163 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4164 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4165 $this->_relatedObjects
['membership'][$membership->id
. '_' . $membership->membership_type_id
] = $membership;
4174 * Function use to store line item proportionally in in entity financial trxn table
4176 * @param array $trxnParams
4178 * @param int $trxnId
4180 * @param float $contributionTotalAmount
4182 * @throws \CiviCRM_API3_Exception
4184 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4185 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4186 if (!empty($lineItems)) {
4187 // get financial item
4188 [$ftIds, $taxItems] = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4190 'contribution_total_amount' => $contributionTotalAmount,
4191 'trxn_total_amount' => $trxnParams['total_amount'],
4192 'trxn_id' => $trxnId,
4194 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4199 * ContributionPage values were being imposed onto values.
4201 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4202 * REALLY didn't want superimposed. The rest are left there in their overkill out
4205 * The rationale for making this explicit is that it was a case of carefully set values being
4206 * seemingly randonly overwritten without much care. In general I think array randomly setting
4207 * variables en mass is risky.
4209 * @param array $values
4213 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4214 $contributionPageValues = [];
4215 CRM_Contribute_BAO_ContributionPage
::setValues(
4216 $this->contribution_page_id
,
4217 $contributionPageValues
4220 // These are the values that I believe to be useful.
4223 'pay_later_receipt',
4225 'receipt_from_email',
4226 'receipt_from_name',
4230 'honoree_profile_id',
4231 'onbehalf_profile_id',
4232 'honor_block_is_active',
4233 // Kinda might be - but would be on the contribution...
4236 // Included for 'fear of regression' but can't justify any use for these....
4238 'payment_processor',
4239 'financial_type_id',
4240 'amount_block_is_active',
4245 'default_amount_id',
4249 'initial_amount_help_text',
4250 'initial_amount_label',
4252 'is_allow_other_amount',
4253 'is_billing_required',
4254 'is_confirm_enabled',
4255 'is_credit_card_only',
4257 'is_partial_payment',
4258 'is_recur_installments',
4259 'is_recur_interval',
4263 'min_initial_amount',
4264 'recur_frequency_unit',
4271 foreach ($valuesToCopy as $valueToCopy) {
4272 if (isset($contributionPageValues[$valueToCopy])) {
4273 if ($valueToCopy === 'title') {
4274 $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils
::getContributionPageTitle($this->contribution_page_id
);
4277 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
4285 * Get values of CiviContribute Settings
4286 * and check if its enabled or not.
4287 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
4288 * in serialized form. Usually this should be stored as flat settings for each form fields
4289 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
4290 * settings we will live with an inconsistency because it's too hard to change for now.
4291 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
4294 * @param string $name
4299 public static function checkContributeSettings($name) {
4300 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
4301 return $contributeSettings[$name] ??
NULL;
4305 * Get the contribution as it is in the database before being updated.
4307 * @param int $contributionID
4309 * @return \CRM_Contribute_BAO_Contribution|null
4311 private static function getOriginalContribution($contributionID) {
4312 return self
::getValues(['id' => $contributionID]);
4316 * Does this transaction reflect a payment instrument change.
4318 * @param array $params
4319 * @param array $pendingStatuses
4323 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
4324 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
4326 if (array_key_exists('payment_instrument_id', $params)) {
4327 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
4328 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
4330 //check if status is changed from Pending to Completed
4331 // do not update payment instrument changes for Pending to Completed
4332 if (!($contributionStatus == 'Completed' &&
4333 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
4338 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
4339 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
4340 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
4344 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
4345 $params['contribution']->check_number
!= $params['prevContribution']->check_number
4347 // another special case when check number is changed, create new financial records
4348 // create financial trxn with negative amount
4356 * Update the memberships associated with a contribution if it has been completed.
4358 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
4359 * load them in this function. Code clean up would compensate for any minor performance implication.
4361 * @param int $contributionID
4362 * @param string $changeDate
4364 * @throws \CRM_Core_Exception
4365 * @throws \CiviCRM_API3_Exception
4367 public static function updateMembershipBasedOnCompletionOfContribution($contributionID, $changeDate) {
4368 $memberships = self
::getRelatedMemberships((int) $contributionID);
4369 foreach ($memberships as $membership) {
4370 $membershipParams = [
4371 'id' => $membership['id'],
4372 'contact_id' => $membership['contact_id'],
4373 'is_test' => $membership['is_test'],
4374 'membership_type_id' => $membership['membership_type_id'],
4375 'membership_activity_status' => 'Completed',
4378 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4379 $membershipParams['membership_type_id'],
4380 $membershipParams['is_test'],
4381 $membershipParams['id']
4384 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4385 // this picks up membership type changes during renewals
4386 // @todo this is almost certainly an obsolete sql call, the pre-change
4387 // membership is accessible via $this->_relatedObjects
4389 SELECT membership_type_id
4390 FROM civicrm_membership_log
4391 WHERE membership_id={$membershipParams['id']}
4394 $dao = CRM_Core_DAO
::executeQuery($sql);
4395 if ($dao->fetch()) {
4396 if (!empty($dao->membership_type_id
)) {
4397 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4400 if (empty($membership['end_date']) ||
(int) $membership['status_id'] !== CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
4401 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
4402 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
4403 // 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.
4404 // ... except testCompleteTransactionMembershipPriceSetTwoTerms hits this line so the above is obviously not true....
4405 // @todo once apiv4 ships with core switch to that & find sanity.
4406 $membershipParams['num_terms'] = self
::getNumTermsByContributionAndMembershipType(
4407 $membershipParams['membership_type_id'],
4411 // @todo remove all this stuff in favour of letting the api call further down handle in
4412 // (it is a duplication of what the api does).
4413 $dates = array_fill_keys([
4418 if ($currentMembership) {
4420 * Fixed FOR CRM-4433
4421 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4422 * when Contribution mode is notify and membership is for renewal )
4424 // Test cover for this is in testRepeattransactionRenewMembershipOldMembership
4426 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4428 // @todo - we should pass membership_type_id instead of null here but not
4429 // adding as not sure of testing
4430 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4431 $changeDate, NULL, $membershipParams['num_terms']
4433 $dates['join_date'] = $currentMembership['join_date'];
4435 if ('Pending' === CRM_Core_PseudoConstant
::getName('CRM_Member_BAO_Membership', 'status_id', $membership['status_id'])) {
4436 $membershipParams['skipStatusCal'] = '';
4439 //get the status for membership.
4440 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4442 $dates['join_date'],
4445 $membershipParams['membership_type_id'],
4449 unset($dates['end_date']);
4450 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4452 //we might be renewing membership,
4453 //so make status override false.
4454 $membershipParams['is_override'] = FALSE;
4455 $membershipParams['status_override_end_date'] = 'null';
4456 civicrm_api3('Membership', 'create', $membershipParams);
4461 * Get payment links as they relate to a contribution.
4463 * If a payment can be made then include a payment link & if a refund is appropriate
4464 * then a refund link.
4467 * @param float $balance
4468 * @param string $contributionStatus
4471 * $actionLinks Links array containing:
4475 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
4476 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
4477 // In general the balance is the best way to determine if a payment can be added or not,
4478 // but not for Failed contributions, where we don't accept additional payments at the moment.
4479 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
4480 // do accept more payments agains them.
4485 'url' => CRM_Utils_System
::url('civicrm/payment', [
4491 'title' => ts('Record Payment'),
4494 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
4496 'url' => CRM_Utils_System
::url('civicrm/payment', [
4503 'title' => ts('Submit Credit Card payment'),
4507 'url' => CRM_Utils_System
::url('civicrm/payment', [
4513 'title' => ts('Record Refund'),
4515 return $actionLinks;
4519 * Get a query to determine the amount donated by the contact/s in the current financial year.
4521 * @param array $contactIDs
4525 public static function getAnnualQuery($contactIDs) {
4526 $contactIDs = implode(',', $contactIDs);
4527 $config = CRM_Core_Config
::singleton();
4528 $currentMonth = date('m');
4529 $currentDay = date('d');
4531 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
4533 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
4534 (int) $config->fiscalYearStart
['d'] > $currentDay
4537 $year = date('Y') - 1;
4542 $nextYear = $year +
1;
4544 if ($config->fiscalYearStart
) {
4545 $newFiscalYearStart = $config->fiscalYearStart
;
4546 if ($newFiscalYearStart['M'] < 10) {
4547 // This is just a clumsy way of adding padding.
4548 // @todo next round look for a nicer way.
4549 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
4551 if ($newFiscalYearStart['d'] < 10) {
4552 // This is just a clumsy way of adding padding.
4553 // @todo next round look for a nicer way.
4554 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
4556 $config->fiscalYearStart
= $newFiscalYearStart;
4557 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
4560 // First of January.
4563 $startDate = "$year$monthDay";
4564 $endDate = "$nextYear$monthDay";
4567 'contact_id' => 'IN (' . $contactIDs . ')',
4568 'is_test' => ' = 0',
4569 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
4571 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4572 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
4575 foreach ($whereClauses as $key => $clause) {
4576 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
4578 $whereClauseString = implode(' AND ', $clauses);
4580 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
4581 // this group by + having on contribution_status_id improves performance
4583 SELECT COUNT(*) as count,
4584 SUM(total_amount) as amount,
4585 AVG(total_amount) as average,
4587 FROM civicrm_contribution b
4588 WHERE " . $whereClauseString . "
4589 GROUP BY currency, contribution_status_id
4590 HAVING $havingClause
4596 * Assign Test Value.
4598 * @param string $fieldName
4599 * @param array $fieldDef
4600 * @param int $counter
4602 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
4603 if ($fieldName === 'tax_amount') {
4604 $this->{$fieldName} = "0.00";
4606 elseif ($fieldName === 'net_amount') {
4607 $this->{$fieldName} = '2.00';
4609 elseif ($fieldName === 'total_amount') {
4610 $this->{$fieldName} = "3.00";
4612 elseif ($fieldName === 'fee_amount') {
4613 $this->{$fieldName} = '1.00';
4616 parent
::assignTestValues($fieldName, $fieldDef, $counter);
4621 * Check if contribution has participant/membership payment.
4623 * @param int $contributionId
4628 public static function allowUpdateRevenueRecognitionDate($contributionId) {
4629 // get line item for contribution
4630 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
4631 // check if line item is for membership or participant
4632 foreach ($lineItems as $items) {
4633 if ($items['entity_table'] == 'civicrm_participant') {
4637 elseif ($items['entity_table'] == 'civicrm_membership') {
4649 * Retrieve Sales Tax Financial Accounts.
4655 public static function getSalesTaxFinancialAccounts() {
4656 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
4657 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
4658 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
4659 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
4660 $queryParams = [1 => [$accountRel, 'Integer']];
4661 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
4662 $financialAccount = [];
4663 while ($dao->fetch()) {
4664 $financialAccount[(int) $dao->id
] = (int) $dao->id
;
4666 return $financialAccount;
4670 * Create tax entry in civicrm_entity_financial_trxn table.
4672 * @param array $entityParams
4674 * @param array $eftParams
4676 * @throws \CiviCRM_API3_Exception
4678 public static function createProportionalEntry($entityParams, $eftParams) {
4680 if ($entityParams['contribution_total_amount'] != 0) {
4681 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
4683 // Record Entity Financial Trxn; CRM-20145
4684 $eftParams['amount'] = $paid;
4685 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
4689 * Create array of last financial item id's.
4691 * @param int $contributionId
4695 public static function getLastFinancialItemIds($contributionId) {
4696 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
4697 FROM civicrm_financial_item fi
4698 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
4699 WHERE li.contribution_id = %1";
4700 $dao = CRM_Core_DAO
::executeQuery($sql, [
4706 $ftIds = $taxItems = [];
4707 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
4708 while ($dao->fetch()) {
4709 /* if sales tax item*/
4710 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
4711 $taxItems[$dao->price_field_value_id
] = [
4712 'financial_item_id' => $dao->id
,
4713 'amount' => $dao->tax_amount
,
4717 $ftIds[$dao->price_field_value_id
] = $dao->id
;
4720 return [$ftIds, $taxItems];
4724 * Create proportional entries in civicrm_entity_financial_trxn.
4726 * @param array $entityParams
4728 * @param array $lineItems
4730 * @param array $ftIds
4732 * @param array $taxItems
4734 * @throws \CiviCRM_API3_Exception
4736 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
4738 'entity_table' => 'civicrm_financial_item',
4739 'financial_trxn_id' => $entityParams['trxn_id'],
4741 foreach ($lineItems as $key => $value) {
4742 if ($value['qty'] == 0) {
4745 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
4746 $entityParams['line_item_amount'] = $value['line_total'];
4747 self
::createProportionalEntry($entityParams, $eftParams);
4748 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
4749 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
4750 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
4751 self
::createProportionalEntry($entityParams, $eftParams);
4757 * Load entities related to the contribution into $this->_relatedObjects.
4761 * @throws \CRM_Core_Exception
4763 protected function loadRelatedEntitiesByID($ids) {
4765 'contact' => 'CRM_Contact_BAO_Contact',
4766 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
4767 'contributionType' => 'CRM_Financial_BAO_FinancialType',
4768 'financialType' => 'CRM_Financial_BAO_FinancialType',
4769 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
4771 foreach ($entities as $entity => $bao) {
4772 if (!empty($ids[$entity])) {
4773 $this->_relatedObjects
[$entity] = new $bao();
4774 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
4775 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
4776 throw new CRM_Core_Exception($entity . ' could not be loaded');
4783 * Do not use - unused in core.
4785 * Function to replace contribution tokens.
4787 * @param array $contributionIds
4789 * @param string $subject
4791 * @param array $subjectToken
4793 * @param string $text
4795 * @param string $html
4797 * @param array $messageToken
4799 * @param bool $escapeSmarty
4804 * @throws \CiviCRM_API3_Exception
4806 public static function replaceContributionTokens(
4815 if (empty($contributionIds)) {
4818 $contributionDetails = [];
4819 foreach ($contributionIds as $id) {
4820 $result = self
::getContributionTokenValues($id, $messageToken);
4821 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
4822 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
4823 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
4825 return $contributionDetails;
4829 * Do not use - still called from CRM_Contribute_Form_Task_PDFLetter
4831 * This needs to be refactored out of use & deprecated out of existence.
4833 * Get the contribution fields for $id and display labels where
4834 * appropriate (if the token is present).
4839 * @param array $messageToken
4842 * @throws \CRM_Core_Exception
4844 public static function getContributionTokenValues($id, $messageToken) {
4848 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
4849 if (!empty($messageToken['contribution'])) {
4850 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
4851 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
4852 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
4853 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField
::displayValue($result['values'][$id][$fieldName], $fieldName);
4858 'financial_type_id:label',
4859 'financial_type_id:name',
4860 'contribution_page_id:label',
4861 'contribution_page_id:name',
4862 'payment_instrument_id:label',
4863 'payment_instrument_id:name',
4865 'is_pay_later:label',
4866 'contribution_status_id:label',
4867 'contribution_status_id:name',
4868 'is_template:label',
4869 'campaign_id:label',
4872 foreach ($pseudoFields as $pseudoField) {
4873 $split = explode(':', $pseudoField);
4874 $pseudoKey = $split[1];
4875 $realField = $split[0];
4876 $fieldValue = $result['values'][$id][$realField] ??
'';
4877 if ($pseudoKey === 'name') {
4878 $fieldValue = (string) CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', $realField, $fieldValue);
4880 if ($pseudoKey === 'label') {
4881 $fieldValue = (string) CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', $realField, $fieldValue);
4883 $result['values'][$id][$pseudoField] = $fieldValue;
4890 * Get invoice_number for contribution.
4892 * @param int $contributionID
4894 * @return string|null
4896 public static function getInvoiceNumber(int $contributionID): ?
string {
4897 $invoicePrefix = Civi
::settings()->get('invoice_prefix');
4898 return $invoicePrefix ?
$invoicePrefix . $contributionID : NULL;
4902 * Load the values needed for the event message.
4904 * @param int $eventID
4905 * @param int $participantID
4906 * @param int|null $contributionID
4909 * @throws \CRM_Core_Exception
4911 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
4916 $values = ['event' => []];
4918 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
4919 // add custom fields for event
4920 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $eventID);
4922 $eventCustomGroup = [];
4923 foreach ($eventGroupTree as $key => $group) {
4924 if ($key === 'info') {
4928 foreach ($group['fields'] as $k => $customField) {
4929 $groupLabel = $group['title'];
4930 if (!empty($customField['customValue'])) {
4931 foreach ($customField['customValue'] as $customFieldValues) {
4932 $eventCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
4937 $values['event']['customGroup'] = $eventCustomGroup;
4939 //get participant details
4940 $participantParams = [
4941 'id' => $participantID,
4944 $values['participant'] = [];
4946 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
4947 // add custom fields for event
4948 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $participantID);
4949 $participantCustomGroup = [];
4950 foreach ($participantGroupTree as $key => $group) {
4951 if ($key === 'info') {
4955 foreach ($group['fields'] as $k => $customField) {
4956 $groupLabel = $group['title'];
4957 if (!empty($customField['customValue'])) {
4958 foreach ($customField['customValue'] as $customFieldValues) {
4959 $participantCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
4964 $values['participant']['customGroup'] = $participantCustomGroup;
4966 //get location details
4968 'entity_id' => $eventID,
4969 'entity_table' => 'civicrm_event',
4971 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
4974 'entity_table' => 'civicrm_event',
4975 'entity_id' => $eventID,
4976 'module' => 'CiviEvent',
4979 [$custom_pre_id, $custom_post_ids] = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
4981 $values['custom_pre_id'] = $custom_pre_id;
4982 $values['custom_post_id'] = $custom_post_ids;
4984 // set lineItem for event contribution
4985 if ($contributionID) {
4986 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($contributionID);
4987 if (!empty($participantIds)) {
4988 foreach ($participantIds as $pIDs) {
4989 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
4990 if (!CRM_Utils_System
::isNull($lineItem)) {
4991 $values['lineItem'][] = $lineItem;
5000 * Get the activity source and target contacts linked to a contribution
5002 * @param $activityId
5006 private static function getActivitySourceAndTarget($activityId): array {
5007 $activityContactQuery = ActivityContact
::get(FALSE)->setWhere([
5008 ['activity_id', '=', $activityId],
5009 ['record_type_id:name', 'IN', ['Activity Source', 'Activity Targets']],
5012 $sourceContactKey = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
5013 $targetContactKey = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Targets');
5015 $sourceContactId = NULL;
5016 $targetContactId = NULL;
5018 for ($i = 0; $i < $activityContactQuery->count(); $i++
) {
5019 $record = $activityContactQuery->itemAt($i);
5021 if ($record['record_type_id'] === $sourceContactKey) {
5022 $sourceContactId = $record['contact_id'];
5025 if ($record['record_type_id'] === $targetContactKey) {
5026 $targetContactId = $record['contact_id'];
5030 return [$sourceContactId, $targetContactId];