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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
20 * Static field for all the contribution information that we can potentially import
24 public static $_importableFields = NULL;
27 * Static field for all the contribution information that we can potentially export
31 public static $_exportableFields = NULL;
34 * Static field to hold financial trxn id's.
38 public static $_trxnIDs = NULL;
41 * Field for all the objects related to this contribution
43 * @var \CRM_Member_BAO_Membership|\CRM_Event_BAO_Participant[]
45 public $_relatedObjects = [];
48 * Field for the component - either 'event' (participant) or 'contribute'
49 * (any item related to a contribution page e.g. membership, pledge, contribution)
50 * This is used for composing messages because they have dependency on the
51 * contribution_page or event page - although over time we may eliminate that
54 * "contribution"\"event"
56 public $_component = NULL;
59 * Possibly obsolete variable.
61 * If you use it please explain why it is set in the create function here.
65 public $trxn_result_code;
70 public function __construct() {
71 parent
::__construct();
75 * Takes an associative array and creates a contribution object.
77 * the function extract all the params it needs to initialize the create a
78 * contribution object. the params array could contain additional unused name/value
81 * @param array $params
82 * (reference ) an assoc array of name/value pairs.
84 * The array that holds all the db ids.
86 * @return \CRM_Contribute_BAO_Contribution
87 * @throws \CRM_Core_Exception
88 * @throws \CiviCRM_API3_Exception
90 public static function add(&$params, $ids = []) {
95 CRM_Core_Error
::deprecatedFunctionWarning('ids should not be passed into Contribution.add');
97 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
98 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
99 $action = $contributionID ?
'edit' : 'create';
101 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
102 $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)]);
103 throw new CRM_Core_Exception($message);
106 // first clean up all the money fields
111 'non_deductible_amount',
114 //if priceset is used, no need to cleanup money
115 if (!empty($params['skipCleanMoney'])) {
119 // @todo put a deprecated here - this should be done in the form layer.
120 $params['skipCleanMoney'] = FALSE;
121 Civi
::log()->warning('Deprecated code path. Money should always be clean before it hits the BAO.', array('civi.tag' => 'deprecated'));
124 foreach ($moneyFields as $field) {
125 if (isset($params[$field])) {
126 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
130 //set defaults in create mode
131 if (!$contributionID) {
132 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
133 if (empty($params['invoice_number']) && CRM_Invoicing_Utils
::isInvoicingEnabled()) {
134 $nextContributionID = CRM_Core_DAO
::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
135 $params['invoice_number'] = self
::getInvoiceNumber($nextContributionID);
139 $contributionStatusID = $params['contribution_status_id'] ??
NULL;
140 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $contributionStatusID) === 'Partially paid' && empty($params['is_post_payment_create'])) {
141 CRM_Core_Error
::deprecatedFunctionWarning('Setting status to partially paid other than by using Payment.create is deprecated and unreliable');
143 if (!$contributionStatusID) {
144 // Since the fee amount is expecting this (later on) ensure it is always set.
145 // It would only not be set for an update where it is unchanged.
146 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', [
147 'id' => $contributionID,
148 'return' => 'contribution_status_id',
151 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['contribution_status_id']);
154 && CRM_Utils_Array
::value('membership_id', $params)
155 && Civi
::settings()->get('deferred_revenue_enabled')
157 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
158 if ($memberStartDate) {
159 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
162 self
::calculateMissingAmountParams($params, $contributionID);
164 if (!empty($params['payment_instrument_id'])) {
165 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
166 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
167 $params['check_number'] = 'null';
171 $setPrevContribution = TRUE;
172 // CRM-13964 partial payment
173 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])) {
174 CRM_Core_Error
::deprecatedFunctionWarning('partial_amount params are deprecated from Contribution.create - use Payment.create');
175 $partialAmtTotal = $params['partial_payment_total'];
176 $partialAmtPay = $params['partial_amount_to_pay'];
177 $params['total_amount'] = $partialAmtTotal;
178 if ($partialAmtPay < $partialAmtTotal) {
179 $params['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Partially paid');
180 $params['is_pay_later'] = 0;
181 $setPrevContribution = FALSE;
184 if ($contributionID && $setPrevContribution) {
185 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
187 $previousContributionStatus = ($contributionID && !empty($params['prevContribution'])) ? CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['prevContribution']->contribution_status_id
) : NULL;
189 if ($contributionID && !empty($params['revenue_recognition_date'])
190 && !($previousContributionStatus === 'Pending')
191 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
193 unset($params['revenue_recognition_date']);
196 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
197 isset($params['financial_type_id']))) {
198 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
201 CRM_Utils_Hook
::pre($action, 'Contribution', $contributionID, $params);
203 $contribution = new CRM_Contribute_BAO_Contribution();
204 $contribution->copyValues($params);
206 $contribution->id
= $contributionID;
208 if (empty($contribution->id
)) {
209 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
210 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
211 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
215 $result = $contribution->save();
217 // Add financial_trxn details as part of fix for CRM-4724
218 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
219 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
221 //add Account details
222 $params['contribution'] = $contribution;
223 if (empty($params['is_post_payment_create'])) {
224 // If this is being called from the Payment.create api/ BAO then that Entity
225 // takes responsibility for the financial transactions. In fact calling Payment.create
226 // to add payments & having it call completetransaction and / or contribution.create
227 // to update related entities is the preferred flow.
228 // Note that leveraging this parameter for any other code flow is not supported and
229 // is likely to break in future and / or cause serious problems in your data.
230 // https://github.com/civicrm/civicrm-core/pull/14673
231 self
::recordFinancialAccounts($params);
234 if (self
::isUpdateToRecurringContribution($params)) {
235 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
236 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
238 CRM_Utils_Array
::value('receive_date', $params)
242 $params['contribution_id'] = $contribution->id
;
244 if (!empty($params['custom']) &&
245 is_array($params['custom'])
247 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
, $action);
250 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
252 CRM_Utils_Hook
::post($action, 'Contribution', $contribution->id
, $contribution);
257 * Is this contribution updating an existing recurring contribution.
259 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
260 * pending payment is being confirmed (or failing).
262 * @param array $params
266 public static function isUpdateToRecurringContribution($params) {
267 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
270 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
273 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
276 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
277 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
284 * Get defaults for new entity.
288 public static function getDefaults() {
290 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
291 FALSE, FALSE, FALSE, 'AND is_default = 1')
293 'contribution_status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
294 'receive_date' => date('Y-m-d H:i:s'),
299 * Fetch the object and store the values in the values array.
301 * @param array $params
302 * Input parameters to find object.
303 * @param array $values
304 * Output values of the object.
306 * The array that holds all the db ids.
308 * @return CRM_Contribute_BAO_Contribution|null
309 * The found object or null
311 public static function getValues($params, &$values = [], &$ids = []) {
312 if (empty($params)) {
315 $contribution = new CRM_Contribute_BAO_Contribution();
317 $contribution->copyValues($params);
319 if ($contribution->find(TRUE)) {
320 $ids['contribution'] = $contribution->id
;
322 CRM_Core_DAO
::storeValues($contribution, $values);
324 return $contribution;
326 // return by reference
332 * Get the values and resolve the most common mappings.
334 * Since contribution status is resolved in almost every function that calls getValues it makes
335 * sense to have an extra function to resolve it rather than repeat the code.
337 * Think carefully before adding more mappings to be resolved as there could be performance implications
338 * if this function starts to be called from more iterative functions.
340 * @param array $params
341 * Input parameters to find object.
344 * Array of the found contribution.
345 * @throws CRM_Core_Exception
347 public static function getValuesWithMappings($params) {
349 $contribution = self
::getValues($params, $values, $ids);
350 if (is_null($contribution)) {
351 throw new CRM_Core_Exception('No contribution found');
353 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
358 * Calculate net_amount & fee_amount if they are not set.
360 * Net amount should be total - fee.
361 * This should only be called for new contributions.
363 * @param array $params
364 * Params for a new contribution before they are saved.
365 * @param int|null $contributionID
366 * Contribution ID if we are dealing with an update.
368 * @throws \CiviCRM_API3_Exception
370 public static function calculateMissingAmountParams(&$params, $contributionID) {
371 if (!$contributionID && !isset($params['fee_amount'])) {
372 if (isset($params['total_amount']) && isset($params['net_amount'])) {
373 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
376 $params['fee_amount'] = 0;
379 if (!isset($params['net_amount'])) {
380 if (!$contributionID) {
381 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
384 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
385 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
386 // net_amount may need adjusting.
387 $contribution = civicrm_api3('Contribution', 'getsingle', [
388 'id' => $contributionID,
389 'return' => ['total_amount', 'net_amount', 'fee_amount'],
391 $totalAmount = (isset($params['total_amount']) ?
(float) $params['total_amount'] : (float) CRM_Utils_Array
::value('total_amount', $contribution));
392 $feeAmount = (isset($params['fee_amount']) ?
(float) $params['fee_amount'] : (float) CRM_Utils_Array
::value('fee_amount', $contribution));
393 $params['net_amount'] = $totalAmount - $feeAmount;
401 * @param $billingLocationTypeID
405 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
406 $hasBillingField = FALSE;
415 //build address array
417 $addressParams['location_type_id'] = $billingLocationTypeID;
418 $addressParams['is_billing'] = 1;
420 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
421 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
422 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
423 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
425 foreach ($billingFields as $value) {
426 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
427 if (!empty($addressParams[$value])) {
428 $hasBillingField = TRUE;
431 return [$hasBillingField, $addressParams];
435 * Get address params ready to be passed to the payment processor.
437 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
438 * To create an address we need state_province_id.
440 * @param array $params
441 * @param int $billingLocationTypeID
445 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
446 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
447 foreach ($addressParams as $name => $field) {
448 if (substr($name, 0, 8) == 'billing_') {
449 $addressParams[substr($name, 9)] = $addressParams[$field];
452 return [$hasBillingField, $addressParams];
456 * Get the number of terms for this contribution for a given membership type
457 * based on querying the line item table and relevant price field values
458 * Note that any one contribution should only be able to have one line item relating to a particular membership
461 * @param int $membershipTypeID
463 * @param int $contributionID
467 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
468 $numTerms = CRM_Core_DAO
::singleValueQuery("
469 SELECT membership_num_terms FROM civicrm_line_item li
470 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
471 WHERE contribution_id = %1 AND membership_type_id = %2",
472 [1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']]
474 // default of 1 is precautionary
475 return empty($numTerms) ?
1 : $numTerms;
479 * Takes an associative array and creates a contribution object.
481 * @param array $params
482 * (reference ) an assoc array of name/value pairs.
484 * The array that holds all the db ids.
486 * @return CRM_Contribute_BAO_Contribution
488 * @throws \CRM_Core_Exception
489 * @throws \CiviCRM_API3_Exception
491 public static function create(&$params, $ids = []) {
497 'revenue_recognition_date',
499 foreach ($dateFields as $df) {
500 if (isset($params[$df])) {
501 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
505 $transaction = new CRM_Core_Transaction();
508 if (!isset($params['id']) && isset($ids['contribution'])) {
509 CRM_Core_Error
::deprecatedFunctionWarning('ids should not be used for contribution create');
510 $params['id'] = $ids['contribution'];
512 $contribution = self
::add($params);
514 catch (CRM_Core_Exception
$e) {
515 $transaction->rollback();
519 $params['contribution_id'] = $contribution->id
;
520 $session = CRM_Core_Session
::singleton();
522 if (!empty($params['note'])) {
524 'entity_table' => 'civicrm_contribution',
525 'note' => $params['note'],
526 'entity_id' => $contribution->id
,
527 'contact_id' => $session->get('userID'),
528 'modified_date' => date('Ymd'),
530 if (!$noteParams['contact_id']) {
531 $noteParams['contact_id'] = $params['contact_id'];
533 CRM_Core_BAO_Note
::add($noteParams);
536 // make entry in batch entity batch table
537 if (!empty($params['batch_id'])) {
538 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
545 $retrieveRequired = 0;
546 foreach ($titleFields as $titleField) {
547 if (!isset($contribution->$titleField)) {
548 $retrieveRequired = 1;
552 if ($retrieveRequired == 1) {
553 $contribution->find(TRUE);
557 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
559 $transaction->commit();
561 $activity = civicrm_api3('Activity', 'get', [
562 'source_record_id' => $contribution->id
,
563 'options' => ['limit' => 1],
565 'activity_type_id' => 'Contribution',
566 'return' => ['id', 'campaign'],
569 //CRM-18406: Update activity when edit contribution.
570 if ($activity['count']) {
571 // CRM-13237 : if activity record found, update it with campaign id of contribution
572 // @todo compare campaign ids first.
573 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity['id'], 'campaign_id', $contribution->campaign_id
);
574 $contribution->activity_id
= $activity['id'];
577 if (empty($contribution->contact_id
)) {
578 $contribution->find(TRUE);
580 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution');
582 // do not add to recent items for import, CRM-4399
583 if (empty($params['skipRecentView'])) {
584 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
585 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
587 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
594 $retrieveRequired = 0;
595 foreach ($titleFields as $titleField) {
596 if (!isset($contribution->$titleField)) {
597 $retrieveRequired = 1;
601 if ($retrieveRequired == 1) {
602 $contribution->find(TRUE);
604 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
605 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
608 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
609 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
610 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
614 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
615 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
616 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
620 // add the recently created Contribution
621 CRM_Utils_Recent
::add($title,
625 $contribution->contact_id
,
631 return $contribution;
635 * Get the values for pseudoconstants for name->value and reverse.
637 * @param array $defaults
638 * (reference) the default values, some of which need to be resolved.
639 * @param bool $reverse
640 * True if we want to resolve the values in the reverse direction (value -> name).
642 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
643 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
644 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
645 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'), $reverse);
646 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
650 * Convert associative array names to values and vice-versa.
652 * This function is used by both the web form layer and the api. Note that
653 * the api needs the name => value conversion, also the view layer typically
654 * requires value => name conversion
656 * @param array $defaults
657 * @param string $property
658 * @param array $lookup
659 * @param bool $reverse
663 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
664 $id = $property . '_id';
666 $src = $reverse ?
$property : $id;
667 $dst = $reverse ?
$id : $property;
669 if (!array_key_exists($src, $defaults)) {
673 $look = $reverse ?
array_flip($lookup) : $lookup;
675 if (is_array($look)) {
676 if (!array_key_exists($defaults[$src], $look)) {
680 $defaults[$dst] = $look[$defaults[$src]];
685 * Retrieve DB object based on input parameters.
687 * It also stores all the retrieved values in the default array.
689 * @param array $params
690 * (reference ) an assoc array of name/value pairs.
691 * @param array $defaults
692 * (reference ) an assoc array to hold the name / value pairs.
693 * in a hierarchical manner
695 * (reference) the array that holds all the db ids.
697 * @return CRM_Contribute_BAO_Contribution
699 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
700 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
701 return $contribution;
705 * Combine all the importable fields from the lower levels object.
707 * The ordering is important, since currently we do not have a weight
708 * scheme. Adding weight is super important and should be done in the
709 * next week or so, before this can be called complete.
711 * @param string $contactType
712 * @param bool $status
715 * array of importable Fields
717 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
718 if (!self
::$_importableFields) {
719 if (!self
::$_importableFields) {
720 self
::$_importableFields = [];
724 $fields = ['' => ['title' => ts('- do not import -')]];
727 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
730 $note = CRM_Core_DAO_Note
::import();
731 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
732 unset($tmpFields['option_value']);
733 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
734 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
736 // Using new Dedupe rule.
738 'contact_type' => $contactType,
739 'used' => 'Unsupervised',
741 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
742 $tmpContactField = [];
743 if (is_array($fieldsArray)) {
744 foreach ($fieldsArray as $value) {
745 //skip if there is no dupe rule
746 if ($value == 'none') {
749 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
754 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
755 $tmpContactField[trim($value)] = $contactFields[trim($value)];
757 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
760 $title = $tmpContactField[trim($value)]['title'];
762 $tmpContactField[trim($value)]['title'] = $title;
766 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
767 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
768 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
769 $fields = array_merge($fields, $tmpContactField);
770 $fields = array_merge($fields, $tmpFields);
771 $fields = array_merge($fields, $note);
772 $fields = array_merge($fields, $optionFields);
773 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
774 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
775 self
::$_importableFields = $fields;
777 return self
::$_importableFields;
781 * Combine all the exportable fields from the lower level objects.
783 * @param bool $checkPermission
786 * array of exportable Fields
788 public static function &exportableFields($checkPermission = TRUE) {
789 if (!self
::$_exportableFields) {
790 if (!self
::$_exportableFields) {
791 self
::$_exportableFields = [];
794 $fields = CRM_Contribute_DAO_Contribution
::export();
795 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
796 $fields = array_merge(
798 CRM_Contribute_DAO_Product
::export(),
799 CRM_Contribute_DAO_ContributionProduct
::export(),
800 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
802 'contribution_product_id' => [
803 'title' => ts('Premium'),
804 'name' => 'contribution_product_id',
805 'where' => 'civicrm_product.id',
806 'data_type' => CRM_Utils_Type
::T_INT
,
812 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
814 $contributionPage = [
815 'contribution_page' => [
816 'title' => ts('Contribution Page'),
817 'name' => 'contribution_page',
818 'where' => 'civicrm_contribution_page.title',
819 'data_type' => CRM_Utils_Type
::T_STRING
,
823 $contributionNote = [
824 'contribution_note' => [
825 'title' => ts('Contribution Note'),
826 'name' => 'contribution_note',
827 'data_type' => CRM_Utils_Type
::T_TEXT
,
832 'contribution_batch' => [
833 'title' => ts('Batch Name'),
839 'contribution_campaign_title' => [
840 'title' => ts('Campaign Title'),
841 'name' => 'campaign_title',
842 'where' => 'civicrm_campaign.title',
843 'data_type' => CRM_Utils_Type
::T_STRING
,
846 $softCreditFields = [
847 'contribution_soft_credit_name' => [
848 'name' => 'contribution_soft_credit_name',
849 'title' => ts('Soft Credit For'),
850 'where' => 'civicrm_contact_d.display_name',
851 'data_type' => CRM_Utils_Type
::T_STRING
,
853 'contribution_soft_credit_amount' => [
854 'name' => 'contribution_soft_credit_amount',
855 'title' => ts('Soft Credit Amount'),
856 'where' => 'civicrm_contribution_soft.amount',
857 'data_type' => CRM_Utils_Type
::T_MONEY
,
859 'contribution_soft_credit_type' => [
860 'name' => 'contribution_soft_credit_type',
861 'title' => ts('Soft Credit Type'),
862 'where' => 'contribution_softcredit_type.label',
863 'data_type' => CRM_Utils_Type
::T_STRING
,
865 'contribution_soft_credit_contribution_id' => [
866 'name' => 'contribution_soft_credit_contribution_id',
867 'title' => ts('Soft Credit For Contribution ID'),
868 'where' => 'civicrm_contribution_soft.contribution_id',
869 'data_type' => CRM_Utils_Type
::T_INT
,
871 'contribution_soft_credit_contact_id' => [
872 'name' => 'contribution_soft_credit_contact_id',
873 'title' => ts('Soft Credit For Contact ID'),
874 'where' => 'civicrm_contact_d.id',
875 'data_type' => CRM_Utils_Type
::T_INT
,
879 $fields = array_merge($fields, $contributionPage,
880 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
881 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
884 self
::$_exportableFields = $fields;
887 return self
::$_exportableFields;
891 * Record an activity when a payment is received.
893 * @todo this is intended to be moved to payment BAO class as a protected function
894 * on that class. Currently being cleaned up. The addActivityForPayment doesn't really
895 * merit it's own function as it makes the code less rather than more readable.
897 * @param int $contributionId
898 * @param int $participantId
899 * @param string $totalAmount
900 * @param string $currency
901 * @param string $trxnDate
903 * @throws \CRM_Core_Exception
904 * @throws \CiviCRM_API3_Exception
906 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
907 $activityType = ($totalAmount < 0) ?
'Refund' : 'Payment';
909 if ($participantId) {
910 $inputParams['id'] = $participantId;
913 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
914 $entityObj = $entityObj[$participantId];
915 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
918 $entityObj = new CRM_Contribute_BAO_Contribution();
919 $entityObj->id
= $contributionId;
920 $entityObj->find(TRUE);
921 $title = ts('Contribution');
923 // @todo per block above this is not a logical splitting off of functionality.
924 self
::addActivityForPayment($entityObj->contact_id
, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
928 * Get the value for the To Financial Account.
930 * @param $contribution
935 public static function getToFinancialAccount($contribution, $params) {
936 if (!empty($params['payment_processor_id'])) {
937 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor_id'], NULL, 'civicrm_payment_processor');
939 if (!empty($params['payment_instrument_id'])) {
940 return CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
943 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
944 $queryParams = [1 => [$relationTypeId, 'Integer']];
945 return CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
950 * Get memberships related to the contribution.
952 * @param int $contributionID
956 protected static function getRelatedMemberships($contributionID) {
957 $membershipPayments = civicrm_api3('MembershipPayment', 'get', [
958 'return' => 'membership_id',
959 'contribution_id' => (int) $contributionID,
962 foreach ($membershipPayments as $membershipPayment) {
963 $membershipIDs[] = $membershipPayment['membership_id'];
965 if (empty($membershipIDs)) {
968 // We could combine this with the MembershipPayment.get - we'd
969 // need to re-wrangle the params (here or in the calling function)
970 // as they would then me membership.contact_id, membership.is_test etc
971 return civicrm_api3('Membership', 'get', [
972 'id' => ['IN' => $membershipIDs],
973 'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'],
978 * Cancel contribution.
980 * This function should only be called from transitioncomponents - it is an interim step in refactoring.
982 * @param $processContributionObject
983 * @param $memberships
984 * @param $contributionId
985 * @param $membershipStatuses
986 * @param $updateResult
987 * @param $participant
989 * @param $pledgePayment
991 * @param $pledgePaymentIDs
992 * @param $contributionStatusId
996 protected static function cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId) {
997 // @fixme https://lab.civicrm.org/dev/core/issues/927 Cancelling membership etc is not desirable for all use-cases and we should be able to disable it
998 $processContribution = FALSE;
999 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1000 if (is_array($memberships)) {
1001 foreach ($memberships as $membership) {
1003 //Update Membership status if there is no other completed contribution associated with the membership.
1004 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1005 foreach ($relatedContributions as $contriId) {
1006 if ($contriId == $contributionId) {
1009 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1010 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1014 if ($membership && $update) {
1015 $newStatus = array_search('Cancelled', $membershipStatuses);
1018 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1020 'subject' => "Status changed from {$allStatus[$membership->status_id]} to {$allStatus[$newStatus]}",
1021 'source_contact_id' => CRM_Core_Session
::singleton()->get('userID'),
1022 'target_contact_id' => $membership->contact_id
,
1023 'source_record_id' => $membership->id
,
1024 'activity_type_id' => 'Change Membership Status',
1025 'status_id' => 'Completed',
1026 'priority_id' => 'Normal',
1027 'activity_date_time' => 'now',
1030 $membership->status_id
= $newStatus;
1031 $membership->is_override
= TRUE;
1032 $membership->status_override_end_date
= 'null';
1033 $membership->save();
1034 civicrm_api3('activity', 'create', $activityParam);
1036 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1037 if ($processContributionObject) {
1038 $processContribution = TRUE;
1045 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1046 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1048 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1049 if ($processContributionObject) {
1050 $processContribution = TRUE;
1054 if ($pledgePayment) {
1055 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1057 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1058 if ($processContributionObject) {
1059 $processContribution = TRUE;
1062 return [$updateResult, $processContribution];
1066 * Do any accounting updates required as a result of a contribution status change.
1068 * Currently we have a bit of a roundabout where adding a payment results in this being called &
1069 * this may attempt to add a payment. We need to resolve that....
1071 * The 'right' way to add payments or refunds is through the Payment.create api. That api
1072 * then updates the contribution but this process should not also record another financial trxn.
1073 * Currently we have weak detection fot that scenario & where it is detected the first returned
1074 * value is FALSE - meaning 'do not continue'.
1076 * We should also look at the fact that the calling function - updateFinancialAccounts
1077 * bunches together some disparate processes rather than having separate appropriate
1080 * @param array $params
1083 * Return indicates whether the updateFinancialAccounts function should continue.
1085 private static function updateFinancialAccountsOnContributionStatusChange(&$params) {
1086 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
1087 $currentContributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
1089 if ((($previousContributionStatus == 'Partially paid' && $currentContributionStatus == 'Completed')
1090 ||
($previousContributionStatus == 'Pending refund' && $currentContributionStatus == 'Completed')
1091 // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
1092 // why it is here or where it is handled instead.
1093 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
1094 && $currentContributionStatus == 'Partially paid'))
1099 if (self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
)) {
1100 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1101 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1103 elseif (($previousContributionStatus == 'Pending'
1104 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
1106 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
1107 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
1109 if ($currentContributionStatus == 'Cancelled') {
1110 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1111 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
1112 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1115 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1116 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
1120 if (($previousContributionStatus == 'Pending'
1121 ||
$previousContributionStatus == 'In Progress')
1122 && ($currentContributionStatus == 'Completed')
1124 if (empty($params['line_item'])) {
1126 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
1127 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
1128 // & this can be removed
1131 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1132 // This is an update so original currency if none passed in.
1133 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
1135 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
1136 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
1137 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1138 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
1140 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
1143 'entity_table' => 'civicrm_financial_item',
1145 foreach ($params['line_item'] as $fieldId => $fields) {
1146 foreach ($fields as $fieldValueId => $lineItemDetails) {
1147 self
::updateFinancialItemForLineItemToPaid($lineItemDetails['id']);
1149 1 => [$lineItemDetails['id'], 'Integer'],
1151 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
1152 while ($financialItem->fetch()) {
1153 $entityParams['entity_id'] = $financialItem->id
;
1154 $entityParams['amount'] = $financialItem->amount
;
1155 foreach (self
::$_trxnIDs as $tID) {
1156 $entityParams['financial_trxn_id'] = $tID;
1157 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
1168 * It is possible to override the membership id that is updated from the payment processor.
1170 * Historically Paypal does this & it still does if it determines data is messed up - see
1171 * https://lab.civicrm.org/dev/membership/issues/13
1173 * Read the comment block on repeattransaction for more information
1174 * about how things should work.
1176 * @param int $contributionID
1177 * @param array $input
1179 * @throws \CiviCRM_API3_Exception
1181 protected static function handleMembershipIDOverride($contributionID, $input) {
1182 if (!empty($input['membership_id'])) {
1183 Civi
::log()->debug('The related membership id has been overridden - this may impact data - see https://github.com/civicrm/civicrm-core/pull/15053');
1184 civicrm_api3('MembershipPayment', 'create', ['contribution_id' => $contributionID, 'membership_id' => $input['membership_id']]);
1189 * Update all financial items related to the line item tto have a status of paid.
1191 * @param int $lineItemID
1193 private static function updateFinancialItemForLineItemToPaid($lineItemID) {
1196 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1199 2 => [$lineItemID, 'Integer'],
1201 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
1202 CRM_Core_DAO
::executeQuery($query, $fparams);
1206 * Create the financial items for the line.
1208 * @param array $params
1209 * @param string $context
1210 * @param array $fields
1211 * @param array $previousLineItems
1212 * @param array $inputParams
1213 * @param bool $isARefund
1214 * @param array $trxnIds
1215 * @param int $fieldId
1219 private static function createFinancialItemsForLine($params, $context, $fields, array $previousLineItems, array $inputParams, bool $isARefund, $trxnIds, $fieldId): array {
1220 foreach ($fields as $fieldValueId => $lineItemDetails) {
1221 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($lineItemDetails['id']);
1222 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
1223 if ($params['contribution']->receive_date
) {
1224 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
1227 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array
::value('financial_account_id', $prevFinancialItem));
1229 $currency = $params['prevContribution']->currency
;
1230 if ($params['contribution']->currency
) {
1231 $currency = $params['contribution']->currency
;
1233 $previousLineItemTotal = CRM_Utils_Array
::value('line_total', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1235 'transaction_date' => $receiveDate,
1236 'contact_id' => $params['prevContribution']->contact_id
,
1237 'currency' => $currency,
1238 'amount' => self
::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
1239 'description' => CRM_Utils_Array
::value('description', $prevFinancialItem),
1240 'status_id' => $prevFinancialItem['status_id'],
1241 'financial_account_id' => $financialAccount,
1242 'entity_table' => 'civicrm_line_item',
1243 'entity_id' => $lineItemDetails['id'],
1245 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1246 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
1247 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
1249 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') ||
($context == 'changeFinancialType')) {
1250 $taxAmount = (float) $lineItemDetails['tax_amount'];
1251 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
1252 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
1253 $taxAmount = CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1255 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
1256 $taxAmount -= CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1258 if ($taxAmount != 0) {
1259 $itemParams['amount'] = self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * $taxAmount;
1260 $itemParams['description'] = CRM_Invoicing_Utils
::getTaxTerm();
1261 if ($lineItemDetails['financial_type_id']) {
1262 $itemParams['financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getSalesTaxFinancialAccount($lineItemDetails['financial_type_id']);
1264 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1272 * Does this contributtion status update represent a refund.
1274 * @param int $previousContributionStatusID
1275 * @param int $currentContributionStatusID
1279 private static function isContributionUpdateARefund($previousContributionStatusID, $currentContributionStatusID): bool {
1280 if ('Completed' !== CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $previousContributionStatusID)) {
1283 return self
::isContributionStatusNegative($currentContributionStatusID);
1289 public function addSelectWhereClause() {
1290 $whereClauses = parent
::addSelectWhereClause();
1291 if ($whereClauses !== []) {
1292 // In this case permisssions have been applied & we assume the
1293 // financialaclreport is applying these
1294 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
1295 return $whereClauses;
1298 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1299 return $whereClauses;
1301 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
1302 if (empty($types)) {
1303 $whereClauses['financial_type_id'] = 'IN (0)';
1306 $whereClauses['financial_type_id'] = [
1307 'IN (' . implode(',', array_keys($types)) . ')',
1310 return $whereClauses;
1314 * @param null $status
1315 * @param null $startDate
1316 * @param null $endDate
1318 * @return array|null
1320 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1324 $where[] = 'contribution_status_id = 1';
1328 $where[] = 'contribution_status_id = 3';
1333 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
1336 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
1338 $financialTypeACLJoin = '';
1339 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1340 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1341 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
1342 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1343 if ($financialTypes) {
1344 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1345 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1348 $where[] = "c.financial_type_id IN (0)";
1352 $whereCond = implode(' AND ', $where);
1355 SELECT sum( total_amount ) as total_amount,
1356 count( c.id ) as total_count,
1358 FROM civicrm_contribution c
1359 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1360 $financialTypeACLJoin
1362 AND ( is_test = 0 OR is_test IS NULL )
1363 AND contact.is_deleted = 0
1367 $dao = CRM_Core_DAO
::executeQuery($query);
1370 while ($dao->fetch()) {
1371 $count +
= $dao->total_count
;
1372 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
1376 'amount' => implode(', ', $amount),
1384 * Delete the indirect records associated with this contribution first.
1388 * @return mixed|null
1389 * $results no of deleted Contribution on success, false otherwise
1391 public static function deleteContribution($id) {
1392 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
1394 $transaction = new CRM_Core_Transaction();
1397 //delete activity record
1399 'source_record_id' => $id,
1400 // activity type id for contribution
1401 'activity_type_id' => 6,
1404 CRM_Activity_BAO_Activity
::deleteActivity($params);
1406 //delete billing address if exists for this contribution.
1407 self
::deleteAddress($id);
1409 //update pledge and pledge payment, CRM-3961
1410 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1412 // remove entry from civicrm_price_set_entity, CRM-5095
1413 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1414 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1416 // cleanup line items.
1417 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1419 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1420 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1422 if ($participantId) {
1423 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1426 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1430 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1431 $noteId = key($note);
1433 CRM_Core_BAO_Note
::del($noteId, FALSE);
1436 $dao = new CRM_Contribute_DAO_Contribution();
1439 $results = $dao->delete();
1441 $transaction->commit();
1443 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1445 // delete the recently created Contribution
1446 $contributionRecent = [
1448 'type' => 'Contribution',
1450 CRM_Utils_Recent
::del($contributionRecent);
1456 * React to a financial transaction (payment) failure.
1458 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1459 * payments is important for forensic and outreach reasons.
1461 * @param int $contributionID
1462 * @param int $contactID
1463 * @param string $message
1465 * @throws \CiviCRM_API3_Exception
1467 public static function failPayment($contributionID, $contactID, $message) {
1468 civicrm_api3('activity', 'create', [
1469 'activity_type_id' => 'Failed Payment',
1470 'details' => $message,
1471 'subject' => ts('Payment failed at payment processor'),
1472 'source_record_id' => $contributionID,
1473 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() : $contactID,
1476 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1477 civicrm_api3('contribution', 'create', [
1478 'id' => $contributionID,
1479 'contribution_status_id' => 'Failed',
1484 * Check if there is a contribution with the same trxn_id or invoice_id.
1486 * @param array $input
1487 * An assoc array of name/value pairs.
1488 * @param array $duplicates
1489 * (reference) store ids of duplicate contribs.
1493 * true if duplicate, false otherwise
1495 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1497 $id = CRM_Utils_Array
::value('id', $input);
1499 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1500 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1506 $clause[] = "trxn_id = %1";
1507 $input[1] = [$trxn_id, 'String'];
1511 $clause[] = "invoice_id = %2";
1512 $input[2] = [$invoice_id, 'String'];
1515 if (empty($clause)) {
1519 $clause = implode(' OR ', $clause);
1521 $clause = "( $clause ) AND id != %3";
1522 $input[3] = [$id, 'Integer'];
1525 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1526 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1528 while ($dao->fetch()) {
1529 $duplicates[] = $dao->id
;
1536 * Takes an associative array and creates a contribution_product object.
1538 * the function extract all the params it needs to initialize the create a
1539 * contribution_product object. the params array could contain additional unused name/value
1542 * @param array $params
1543 * (reference) an assoc array of name/value pairs.
1545 * @return CRM_Contribute_DAO_ContributionProduct
1547 public static function addPremium(&$params) {
1548 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1549 $contributionProduct->copyValues($params);
1550 return $contributionProduct->save();
1554 * Get list of contribution fields for profile.
1555 * For now we only allow custom contribution fields to be in
1558 * @param bool $addExtraFields
1559 * True if special fields needs to be added.
1562 * the list of contribution fields
1564 public static function getContributionFields($addExtraFields = TRUE) {
1565 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1566 // @todo remove this - this line was added because payment_instrument_id was not
1567 // set to exportable - but now it is.
1568 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1570 if ($addExtraFields) {
1571 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1574 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1576 foreach ($contributionFields as $key => $var) {
1577 if ($key == 'contribution_contact_id') {
1580 elseif ($key == 'contribution_campaign_id') {
1581 $var['title'] = ts('Campaign');
1583 $fields[$key] = $var;
1586 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1591 * Add extra fields specific to contribution.
1593 public static function getSpecialContributionFields() {
1595 'contribution_soft_credit_name' => [
1596 'name' => 'contribution_soft_credit_name',
1597 'title' => ts('Soft Credit Name'),
1598 'headerPattern' => '/^soft_credit_name$/i',
1599 'where' => 'civicrm_contact_d.display_name',
1601 'contribution_soft_credit_email' => [
1602 'name' => 'contribution_soft_credit_email',
1603 'title' => ts('Soft Credit Email'),
1604 'headerPattern' => '/^soft_credit_email$/i',
1605 'where' => 'soft_email.email',
1607 'contribution_soft_credit_phone' => [
1608 'name' => 'contribution_soft_credit_phone',
1609 'title' => ts('Soft Credit Phone'),
1610 'headerPattern' => '/^soft_credit_phone$/i',
1611 'where' => 'soft_phone.phone',
1613 'contribution_soft_credit_contact_id' => [
1614 'name' => 'contribution_soft_credit_contact_id',
1615 'title' => ts('Soft Credit Contact ID'),
1616 'headerPattern' => '/^soft_credit_contact_id$/i',
1617 'where' => 'civicrm_contribution_soft.contact_id',
1619 'contribution_pcp_title' => [
1620 'name' => 'contribution_pcp_title',
1621 'title' => ts('Personal Campaign Page Title'),
1622 'headerPattern' => '/^contribution_pcp_title$/i',
1623 'where' => 'contribution_pcp.title',
1627 return $extraFields;
1631 * @param int $pageID
1635 public static function getCurrentandGoalAmount($pageID) {
1637 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1638 FROM civicrm_contribution_page p,
1639 civicrm_contribution c
1640 WHERE p.id = c.contribution_page_id
1642 AND c.cancel_date is null
1646 $config = CRM_Core_Config
::singleton();
1647 $params = [1 => [$pageID, 'Integer']];
1648 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1650 if ($dao->fetch()) {
1651 return [$dao->goal
, $dao->total
];
1654 return [NULL, NULL];
1659 * Get list of contributions which credit the passed in contact ID.
1661 * The returned array provides details about the original contribution & donor.
1663 * @param int $honorId
1664 * In Honor of Contact ID.
1667 * list of contribution fields
1668 * @todo - this is a confusing function called from one place. It has a test. It would be
1669 * nice to deprecate it.
1672 public static function getHonorContacts($honorId) {
1674 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1675 $honorDAO->contact_id
= $honorId;
1678 $type = CRM_Contribute_PseudoConstant
::financialType();
1680 while ($honorDAO->fetch()) {
1681 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1682 $contributionDAO->id
= $honorDAO->contribution_id
;
1684 if ($contributionDAO->find(TRUE)) {
1685 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1686 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1687 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1688 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1689 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1690 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1691 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1692 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1693 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
, 'label');
1701 * Get the sort name of a contact for a particular contribution.
1704 * Id of the contribution.
1706 * @return null|string
1707 * sort name of the contact if found
1709 public static function sortName($id) {
1710 $id = CRM_Utils_Type
::escape($id, 'Integer');
1713 SELECT civicrm_contact.sort_name
1714 FROM civicrm_contribution, civicrm_contact
1715 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1716 AND civicrm_contribution.id = {$id}
1718 return CRM_Core_DAO
::singleValueQuery($query);
1722 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1724 * @param int|array $contactIDs
1728 public static function annual($contactIDs) {
1729 if (!is_array($contactIDs)) {
1730 // In practice I can't fine any evidence that this function is ever called with
1731 // anything other than a single contact id, but left like this due to .... fear.
1732 $contactIDs = explode(',', $contactIDs);
1735 $query = self
::getAnnualQuery($contactIDs);
1736 $dao = CRM_Core_DAO
::executeQuery($query);
1738 $amount = $average = [];
1739 while ($dao->fetch()) {
1740 if ($dao->count
> 0 && $dao->amount
> 0) {
1741 $count +
= $dao->count
;
1742 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1743 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1749 implode(', ', $amount),
1750 implode(', ', $average),
1757 * Check if there is a contribution with the params passed in.
1759 * Used for trxn_id,invoice_id and contribution_id
1761 * @param array $params
1762 * An assoc array of name/value pairs.
1765 * contribution id if success else NULL
1767 public static function checkDuplicateIds($params) {
1768 $dao = new CRM_Contribute_DAO_Contribution();
1772 foreach ($params as $k => $v) {
1774 $clause[] = "$k = '$v'";
1777 $clause = implode(' AND ', $clause);
1778 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1779 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1781 while ($dao->fetch()) {
1789 * Get the contribution details for component export.
1791 * @param int $exportMode
1793 * @param array $componentIds
1799 public static function getContributionDetails($exportMode, $componentIds) {
1800 $paymentDetails = [];
1801 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1803 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1804 $componentSelect = " civicrm_participant_payment.participant_id id";
1805 $additionalClause = "
1806 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1807 AND civicrm_participant_payment.participant_id {$componentClause} )
1810 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1811 $componentSelect = " civicrm_membership_payment.membership_id id";
1812 $additionalClause = "
1813 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1814 AND civicrm_membership_payment.membership_id {$componentClause} )
1817 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1818 $componentSelect = " civicrm_pledge_payment.id id";
1819 $additionalClause = "
1820 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1821 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1825 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1826 trxn_id, {$componentSelect}
1827 FROM civicrm_contribution
1828 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1829 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1830 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1831 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1832 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1833 AND option_group_contribution_status.id = contribution_status.option_group_id )
1837 $dao = CRM_Core_DAO
::executeQuery($query);
1839 while ($dao->fetch()) {
1840 $paymentDetails[$dao->id
] = [
1841 'total_amount' => $dao->total_amount
,
1842 'contribution_status' => $dao->status
,
1843 'receive_date' => $dao->receive_date
,
1844 'pay_instru' => $dao->payment_instrument
,
1845 'trxn_id' => $dao->trxn_id
,
1849 return $paymentDetails;
1853 * Create address associated with contribution record.
1855 * As long as there is one or more billing field in the parameters we will create the address.
1857 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1860 * @param array $params
1861 * @param int $billingLocationTypeID
1866 public static function createAddress($params, $billingLocationTypeID) {
1867 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1868 if ($hasBillingField) {
1869 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1870 return $address->id
;
1877 * Delete billing address record related contribution.
1879 * @param int $contributionId
1880 * @param int $contactId
1882 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1884 $contactJoin = NULL;
1886 if ($contributionId) {
1887 $clauses[] = "cc.id = {$contributionId}";
1891 $clauses[] = "cco.id = {$contactId}";
1892 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1895 if (empty($clauses)) {
1896 CRM_Core_Error
::fatal();
1899 $condition = implode(' OR ', $clauses);
1903 FROM civicrm_address ca
1904 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1908 $dao = CRM_Core_DAO
::executeQuery($query);
1910 while ($dao->fetch()) {
1911 $params = ['id' => $dao->id
];
1912 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1917 * This function check online pending contribution associated w/
1918 * Online Event Registration or Online Membership signup.
1920 * @param int $componentId
1921 * Participant/membership id.
1922 * @param string $componentName
1926 * pending contribution id.
1928 public static function checkOnlinePendingContribution($componentId, $componentName) {
1929 $contributionId = NULL;
1930 if (!$componentId ||
1931 !in_array($componentName, ['Event', 'Membership'])
1933 return $contributionId;
1936 if ($componentName == 'Event') {
1937 $idName = 'participant_id';
1938 $componentTable = 'civicrm_participant';
1939 $paymentTable = 'civicrm_participant_payment';
1940 $source = ts('Online Event Registration');
1943 if ($componentName == 'Membership') {
1944 $idName = 'membership_id';
1945 $componentTable = 'civicrm_membership';
1946 $paymentTable = 'civicrm_membership_payment';
1947 $source = ts('Online Contribution');
1950 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1953 SELECT component.id as {$idName},
1954 componentPayment.contribution_id as contribution_id,
1955 contribution.source source,
1956 contribution.contribution_status_id as contribution_status_id,
1957 contribution.is_pay_later as is_pay_later
1958 FROM $componentTable component
1959 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1960 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1961 WHERE component.id = {$componentId}";
1963 $dao = CRM_Core_DAO
::executeQuery($query);
1965 while ($dao->fetch()) {
1966 if ($dao->contribution_id
&&
1967 $dao->is_pay_later
&&
1968 $dao->contribution_status_id
== $pendingStatusId &&
1969 strpos($dao->source
, $source) !== FALSE
1971 $contributionId = $dao->contribution_id
;
1975 return $contributionId;
1979 * Update contribution as well as related objects.
1981 * This function by-passes hooks - to address this - don't use this function.
1983 * @param array $params
1984 * @param bool $processContributionObject
1988 * @throws CRM_Core_Exception
1989 * @throws \CiviCRM_API3_Exception
1992 * Use api contribute.completetransaction
1993 * For failures use failPayment (preferably exposing by api in the process).
1996 public static function transitionComponents($params, $processContributionObject = FALSE) {
1997 // get minimum required values.
1998 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1999 $componentId = CRM_Utils_Array
::value('component_id', $params);
2000 $componentName = CRM_Utils_Array
::value('componentName', $params);
2001 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
2002 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
2004 // if we already processed contribution object pass previous status id.
2005 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
2009 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2011 // we process only ( Completed, Cancelled, or Failed ) contributions.
2012 if (!$contributionId ||
2013 !in_array($contributionStatusId, [
2014 array_search('Completed', $contributionStatuses),
2015 array_search('Cancelled', $contributionStatuses),
2016 array_search('Failed', $contributionStatuses),
2019 return $updateResult;
2022 if (!$componentName ||
!$componentId) {
2023 // get the related component details.
2024 $componentDetails = self
::getComponentDetails($contributionId);
2027 $componentDetails['contact_id'] = $contactId;
2028 $componentDetails['component'] = $componentName;
2030 if ($componentName == 'event') {
2031 $componentDetails['participant'] = $componentId;
2034 $componentDetails['membership'] = $componentId;
2038 if (!empty($componentDetails['contact_id'])) {
2039 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2045 // do check for required ids.
2046 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
2047 return $updateResult;
2050 //now we are ready w/ required ids, start processing.
2052 $baseIPN = new CRM_Core_Payment_BaseIPN();
2054 $input = $ids = $objects = [];
2056 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
2057 $ids['contribution'] = $contributionId;
2058 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
2059 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
2060 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
2061 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
2062 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
2063 $ids['contributionRecur'] = NULL;
2064 $ids['contributionPage'] = NULL;
2066 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
2067 CRM_Core_Error
::fatal();
2070 $memberships = &$objects['membership'];
2071 $participant = &$objects['participant'];
2072 $pledgePayment = &$objects['pledge_payment'];
2073 $contribution = &$objects['contribution'];
2074 $pledgeID = $oldStatus = NULL;
2075 $pledgePaymentIDs = [];
2076 if ($pledgePayment) {
2077 foreach ($pledgePayment as $key => $object) {
2078 $pledgePaymentIDs[] = $object->id
;
2080 $pledgeID = $pledgePayment[0]->pledge_id
;
2083 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
2086 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
2087 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
2092 // we might want to process contribution object.
2093 $processContribution = FALSE;
2094 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
2095 // Call interim cancel function - with a goal to cleaning up the signature on it and switching to a tested api Contribution.cancel function.
2096 list($updateResult, $processContribution) = self
::cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
2098 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
2099 if (is_array($memberships)) {
2100 foreach ($memberships as $membership) {
2102 //Update Membership status if there is no other completed contribution associated with the membership.
2103 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
2104 foreach ($relatedContributions as $contriId) {
2105 if ($contriId == $contributionId) {
2108 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
2109 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
2113 if ($membership && $update) {
2114 $membership->status_id
= array_search('Expired', $membershipStatuses);
2115 $membership->is_override
= TRUE;
2116 $membership->status_override_end_date
= 'null';
2117 $membership->save();
2119 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2120 if ($processContributionObject) {
2121 $processContribution = TRUE;
2127 $updatedStatusId = array_search('Cancelled', $participantStatuses);
2128 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2130 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2131 if ($processContributionObject) {
2132 $processContribution = TRUE;
2136 if ($pledgePayment) {
2137 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2139 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2140 if ($processContributionObject) {
2141 $processContribution = TRUE;
2145 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
2147 // only pending contribution related object processed.
2148 if ($previousContriStatusId &&
2149 !in_array($contributionStatuses[$previousContriStatusId], [
2154 // this is case when we already processed contribution object.
2155 return $updateResult;
2157 elseif (!$previousContriStatusId &&
2158 !in_array($contributionStatuses[$contribution->contribution_status_id
], [
2163 // this is case when we are going to process contribution object later.
2164 return $updateResult;
2167 if (is_array($memberships)) {
2168 foreach ($memberships as $membership) {
2173 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
2174 $membership->membership_type_id
,
2175 $membership->is_test
, $membership->id
2178 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2179 // this picks up membership type changes during renewals
2181 SELECT membership_type_id
2182 FROM civicrm_membership_log
2183 WHERE membership_id=$membership->id
2186 $dao = new CRM_Core_DAO();
2188 if ($dao->fetch()) {
2189 if (!empty($dao->membership_type_id
)) {
2190 $membership->membership_type_id
= $dao->membership_type_id
;
2191 $membership->save();
2194 // else fall back to using current membership type
2195 // Figure out number of terms
2197 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
2198 foreach ($lineitems as $lineitem) {
2199 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
2200 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
2202 // in case membership_num_terms comes through as null or zero
2203 $numterms = $numterms >= 1 ?
$numterms : 1;
2208 // CRM-15735-to update the membership status as per the contribution receive date
2210 $oldStatus = $membership->status_id
;
2211 if (!empty($params['receive_date'])) {
2212 $joinDate = $params['receive_date'];
2213 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
2214 $membership->end_date
,
2215 $membership->join_date
,
2216 $params['receive_date'],
2218 $membership->membership_type_id
,
2221 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
2222 $membership->save();
2225 if ($currentMembership) {
2226 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2227 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
2228 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2231 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
2234 //get the status for membership.
2235 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
2237 $dates['join_date'],
2240 $membership->membership_type_id
,
2244 $formattedParams = [
2245 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
2246 array_search('Current', $membershipStatuses)
2248 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
2249 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
2250 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
2253 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
2255 $membership->copyValues($formattedParams);
2256 $membership->save();
2258 //updating the membership log
2259 $membershipLog = [];
2260 $membershipLog = $formattedParams;
2261 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
2262 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
2264 $membershipLog['start_date'] = $logStartDate;
2265 $membershipLog['membership_id'] = $membership->id
;
2266 $membershipLog['modified_id'] = $membership->contact_id
;
2267 $membershipLog['modified_date'] = date('Ymd');
2268 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
2270 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2272 //update related Memberships.
2273 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2275 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2276 $scheduledActivityID = CRM_Utils_Array
::value('id',
2277 civicrm_api3('Activity', 'Get',
2279 'source_record_id' => $membership->id
,
2280 'activity_type_id' => $activityType,
2281 'status_id' => 'Scheduled',
2284 'sort' => 'id DESC',
2289 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2290 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2291 if ($scheduledActivityID) {
2292 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, ['id' => $scheduledActivityID]);
2297 // track membership status change if any
2298 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
2299 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2300 CRM_Activity_BAO_Activity
::addActivity($membership,
2301 'Change Membership Status',
2304 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2305 'source_contact_id' => $membershipLog['modified_id'],
2306 'priority_id' => 'Normal',
2311 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2312 if ($processContributionObject) {
2313 $processContribution = TRUE;
2316 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2322 $updatedStatusId = array_search('Registered', $participantStatuses);
2323 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2325 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2326 if ($processContributionObject) {
2327 $processContribution = TRUE;
2331 if ($pledgePayment) {
2332 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2334 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2335 if ($processContributionObject) {
2336 $processContribution = TRUE;
2341 // process contribution object.
2342 if ($processContribution) {
2343 $contributionParams = [];
2350 'payment_instrument_id',
2353 'financial_type_id',
2354 'contribution_status_id',
2355 'non_deductible_amount',
2359 foreach ($fields as $field) {
2360 if (empty($params[$field])) {
2363 $contributionParams[$field] = $params[$field];
2366 $contributionParams['id'] = $contributionId;
2367 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams);
2370 return $updateResult;
2374 * Returns all contribution related object ids.
2376 * @param $contributionId
2380 public static function getComponentDetails($contributionId) {
2381 $componentDetails = $pledgePayment = [];
2382 if (!$contributionId) {
2383 return $componentDetails;
2387 SELECT c.id as contribution_id,
2388 c.contact_id as contact_id,
2389 c.contribution_recur_id,
2390 mp.membership_id as membership_id,
2391 m.membership_type_id as membership_type_id,
2392 pp.participant_id as participant_id,
2393 p.event_id as event_id,
2394 pgp.id as pledge_payment_id
2395 FROM civicrm_contribution c
2396 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2397 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2398 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2399 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2400 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2401 WHERE c.id = $contributionId";
2403 $dao = CRM_Core_DAO
::executeQuery($query);
2404 $componentDetails = [];
2406 while ($dao->fetch()) {
2407 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2408 $componentDetails['contact_id'] = $dao->contact_id
;
2409 if ($dao->event_id
) {
2410 $componentDetails['event'] = $dao->event_id
;
2412 if ($dao->participant_id
) {
2413 $componentDetails['participant'] = $dao->participant_id
;
2415 if ($dao->membership_id
) {
2416 if (!isset($componentDetails['membership'])) {
2417 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2419 $componentDetails['membership'][] = $dao->membership_id
;
2420 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2422 if ($dao->pledge_payment_id
) {
2423 $pledgePayment[] = $dao->pledge_payment_id
;
2425 if ($dao->contribution_recur_id
) {
2426 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2430 if ($pledgePayment) {
2431 $componentDetails['pledge_payment'] = $pledgePayment;
2434 return $componentDetails;
2438 * @param int $contactId
2439 * @param bool $includeSoftCredit
2441 * @return null|string
2443 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2447 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2448 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2449 $liWhere = " AND i.financial_type_id IN (0)";
2450 if (!empty($financialTypes)) {
2451 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2452 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2454 $contactContributionsSQL = "
2455 SELECT contribution.id AS id
2456 FROM civicrm_contribution contribution
2457 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2458 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2462 $contactSoftCreditContributionsSQL = "
2463 SELECT contribution.id
2464 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2465 ON ( contribution.id = softContribution.contribution_id )
2466 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2467 $query = "SELECT count( x.id ) count FROM ( ";
2468 $query .= $contactContributionsSQL;
2470 if ($includeSoftCredit) {
2471 $query .= " UNION ";
2472 $query .= $contactSoftCreditContributionsSQL;
2477 return CRM_Core_DAO
::singleValueQuery($query);
2481 * Repeat a transaction as part of a recurring series.
2484 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2485 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2486 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2487 * and associated entities.
2488 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2489 * which updates the various entities and sends appropriate emails.
2491 * Gaps in the above (@todo)
2492 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2493 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2494 * 3) Repeat transaction duplicates rather than calls Order.create
2495 * 4) Use of payment.create still limited - completetransaction is more common.
2496 * 5) the template transaction is tricky - historically we used the first contribution
2497 * linked to a recurring contribution. More recently that was changed to be the most recent.
2498 * Ideally it would be an actual template - not a contribution used as a template which
2499 * would give more appropriate flexibility. Note line_items have an entity so that table
2500 * could be used for the line item template - the difficulty is the custom fields...
2501 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2502 * to load the membership(s) referred to via line items in the template transactions. Any other
2503 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2504 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2505 * - membership_payment record
2506 * - civicrm_membership.contribution_recur_id
2508 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2509 * of historical processors since this has been handled 'forever' - specifically for paypal.
2510 * albeit by an even nastier mechanism than the current input override.
2511 * The count is out on how correct related entities wind up in this case.
2513 * @param CRM_Contribute_BAO_Contribution $contribution
2514 * @param array $input
2515 * @param array $contributionParams
2516 * @param int $paymentProcessorID
2519 * @throws CiviCRM_API3_Exception
2521 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
2522 if (!empty($contribution->id
)) {
2525 if (empty($contribution->id
)) {
2526 // Unclear why this would only be set for repeats.
2527 if (!empty($input['amount'])) {
2528 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2531 if (!empty($contributionParams['contribution_recur_id'])) {
2532 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2533 'id' => $contributionParams['contribution_recur_id'],
2535 if (!empty($recurringContribution['campaign_id'])) {
2536 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2537 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2539 if (!empty($recurringContribution['financial_type_id'])) {
2540 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2541 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2544 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2545 $contributionParams['contribution_recur_id'],
2546 array_intersect_key($contributionParams, [
2547 'total_amount' => TRUE,
2548 'financial_type_id' => TRUE,
2551 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2553 $contributionParams['status_id'] = 'Pending';
2554 if (isset($contributionParams['financial_type_id'])) {
2555 // Give precedence to passed in type.
2556 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2559 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2561 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2562 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2564 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2565 //do not create CC or BCC emails or profile notifications.
2566 //The if is just to be safe. Not sure if we can ever arrive with this unset
2567 // but per CRM-19478 it seems it can be 'null'
2568 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2569 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2571 if (!empty($contribution->tax_amount
)) {
2572 $contributionParams['tax_amount'] = $contribution->tax_amount
;
2575 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2576 $contribution->id
= $createContribution['id'];
2577 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2578 self
::handleMembershipIDOverride($contribution->id
, $input);
2584 * Get individual id for onbehalf contribution.
2586 * @param int $contributionId
2588 * @param int $contributorId
2592 * containing organization id and individual id
2594 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2598 if (!$contributionId) {
2602 // fetch contributor id if null
2603 if (!$contributorId) {
2604 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2605 $contributionId, 'contact_id'
2609 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2610 $activityTypeId = array_search('Contribution', $activityTypeIds);
2612 if ($activityTypeId && $contributorId) {
2614 SELECT civicrm_activity_contact.contact_id
2615 FROM civicrm_activity_contact
2616 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2617 WHERE civicrm_activity.activity_type_id = %1
2618 AND civicrm_activity.source_record_id = %2
2619 AND civicrm_activity_contact.record_type_id = %3
2622 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2623 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2626 1 => [$activityTypeId, 'Integer'],
2627 2 => [$contributionId, 'Integer'],
2628 3 => [$sourceID, 'Integer'],
2631 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2633 // for on behalf contribution source is individual and contributor is organization
2634 if ($sourceContactId && $sourceContactId != $contributorId) {
2635 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2636 // get rel type id for employee of relation
2637 foreach ($relationshipTypeIds as $id => $typeVals) {
2638 if ($typeVals['name_a_b'] == 'Employee of') {
2639 $relationshipTypeId = $id;
2644 $rel = new CRM_Contact_DAO_Relationship();
2645 $rel->relationship_type_id
= $relationshipTypeId;
2646 $rel->contact_id_a
= $sourceContactId;
2647 $rel->contact_id_b
= $contributorId;
2648 if ($rel->find(TRUE)) {
2649 $ids['individual_id'] = $rel->contact_id_a
;
2650 $ids['organization_id'] = $rel->contact_id_b
;
2661 public static function getContributionDates() {
2662 $config = CRM_Core_Config
::singleton();
2663 $currentMonth = date('m');
2664 $currentDay = date('d');
2665 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2666 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2667 (int ) $config->fiscalYearStart
['d'] > $currentDay
2670 $year = date('Y') - 1;
2675 $year = ['Y' => $year];
2676 $yearDate = $config->fiscalYearStart
;
2677 $yearDate = array_merge($year, $yearDate);
2678 $yearDate = CRM_Utils_Date
::format($yearDate);
2680 $monthDate = date('Ym') . '01';
2686 'yearDate' => $yearDate,
2687 'monthDate' => $monthDate,
2692 * Load objects relations to contribution object.
2693 * Objects are stored in the $_relatedObjects property
2694 * In the first instance we are just moving functionality from BASEIpn -
2696 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2698 * Note that the unit test for the BaseIPN class tests this function
2700 * @param array $input
2701 * Input as delivered from Payment Processor.
2703 * Ids as Loaded by Payment Processor.
2704 * @param bool $loadAll
2705 * Load all related objects - even where id not passed in? (allows API to call this).
2710 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2711 // @todo deprecate this function - the steps should be
2712 // 1) add additional functions like 'getRelatedMemberships'
2713 // 2) switch all calls that refer to ->_relatedObjects to
2714 // using the helper functions
2715 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2716 // 4) make ->_relatedObjects protected
2717 // 5) hone up the individual functions to not use rely on this having been called
2718 // 6) deprecate like mad
2720 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2721 if (empty($ids['contact']) && isset($this->contact_id
)) {
2722 $ids['contact'] = $this->contact_id
;
2725 if (empty($this->_component
)) {
2726 if (!empty($ids['event'])) {
2727 $this->_component
= 'event';
2730 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2734 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2735 // refactoring than anything else, and has unit test coverage.
2736 if (empty($this->financial_type_id
)) {
2740 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2745 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2746 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2747 $this->contribution_page_id
,
2750 if ($paymentProcessorID) {
2751 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2755 $ids['contributionType'] = $this->financial_type_id
;
2756 $ids['financialType'] = $this->financial_type_id
;
2757 if ($this->contribution_page_id
) {
2758 $ids['contributionPage'] = $this->contribution_page_id
;
2761 $this->loadRelatedEntitiesByID($ids);
2763 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2764 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2767 if (!empty($ids['pledge_payment'])) {
2768 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2769 if (empty($paymentID)) {
2772 $payment = new CRM_Pledge_BAO_PledgePayment();
2773 $payment->id
= $paymentID;
2774 if (!$payment->find(TRUE)) {
2775 throw new Exception("Could not find pledge payment record: " . $paymentID);
2777 $this->_relatedObjects
['pledge_payment'][] = $payment;
2781 // These are probably no longer accessed from anywhere
2782 // @todo remove this line, after ensuring not used.
2783 $ids = $this->loadRelatedMembershipObjects($ids);
2785 if ($this->_component
!= 'contribute') {
2786 // we are in event mode
2787 // make sure event exists and is valid
2788 $event = new CRM_Event_BAO_Event();
2789 $event->id
= $ids['event'];
2790 if ($ids['event'] &&
2793 throw new Exception("Could not find event: " . $ids['event']);
2796 $this->_relatedObjects
['event'] = &$event;
2798 $participant = new CRM_Event_BAO_Participant();
2799 $participant->id
= $ids['participant'];
2800 if ($ids['participant'] &&
2801 !$participant->find(TRUE)
2803 throw new Exception("Could not find participant: " . $ids['participant']);
2805 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2807 $this->_relatedObjects
['participant'] = &$participant;
2809 // get the payment processor id from event - this is inaccurate see CRM-16923
2810 // in future we should look at throwing an exception here rather than an dubious guess.
2811 if (!$paymentProcessorID) {
2812 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2813 if ($paymentProcessorID) {
2814 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2819 if ($paymentProcessorID) {
2820 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2821 $this->is_test ?
'test' : 'live'
2823 $ids['paymentProcessor'] = $paymentProcessorID;
2824 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2827 // Add contribution id to $ids. CRM-20401
2828 $ids['contribution'] = $this->id
;
2833 * Create array of message information - ie. return html version, txt version, to field
2835 * @param array $input
2836 * Incoming information.
2837 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2838 * just check presence of recur object but maintaining legacy approach
2841 * IDs of related objects.
2842 * @param array $values
2843 * Any values that may have already been compiled by calling process.
2844 * This is augmented by values 'gathered' by gatherMessageValues
2845 * @param bool $returnMessageText
2846 * Distinguishes between whether to send message or return.
2847 * message text. We are working towards this function ALWAYS returning message text & calling
2848 * function doing emails / pdfs with it
2854 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2855 $this->loadRelatedObjects($input, $ids);
2857 if (empty($this->_component
)) {
2858 $this->_component
= CRM_Utils_Array
::value('component', $input);
2861 //not really sure what params might be passed in but lets merge em into values
2862 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2863 $values['is_email_receipt'] = $this->isEmailReceipt($input, $values);
2864 if (!empty($input['receipt_date'])) {
2865 $values['receipt_date'] = $input['receipt_date'];
2868 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2869 //what does recur 'mean here - to do with payment processor return functionality but
2870 // what is the importance
2871 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2872 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2874 $entityID = $entity = NULL;
2875 if (isset($ids['contribution'])) {
2876 $entity = 'contribution';
2877 $entityID = $ids['contribution'];
2879 if (!empty($ids['membership'])) {
2880 //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
2881 // 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
2882 // line having loaded an array
2883 $ids['membership'] = (array) $ids['membership'];
2884 $entity = 'membership';
2885 $entityID = $ids['membership'][0];
2888 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2889 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2890 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2892 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2893 //direct mode showing billing block, so use directIPN for temporary
2894 $template->assign('contributeMode', 'directIPN');
2897 // todo remove strtolower - check consistency
2898 if (strtolower($this->_component
) == 'event') {
2899 $eventParams = ['id' => $this->_relatedObjects
['participant']->event_id
];
2900 $values['event'] = [];
2902 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2904 //get location details
2906 'entity_id' => $this->_relatedObjects
['participant']->event_id
,
2907 'entity_table' => 'civicrm_event',
2909 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2912 'entity_table' => 'civicrm_event',
2913 'entity_id' => $ids['event'],
2914 'module' => 'CiviEvent',
2917 list($custom_pre_id,
2919 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2921 $values['custom_pre_id'] = $custom_pre_id;
2922 $values['custom_post_id'] = $custom_post_ids;
2923 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2924 //and cases involving status updation through ipn
2925 // whatever that means!
2926 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2927 // perhaps we should throw an e-notice if amount is set & force total_amount?
2928 if (!empty($input['amount'])) {
2929 $values['totalAmount'] = $input['amount'];
2931 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2932 if ($values['event']['is_email_confirm']) {
2933 $values['is_email_receipt'] = 1;
2936 if (!empty($ids['contribution'])) {
2937 $values['contributionId'] = $ids['contribution'];
2940 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2941 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2945 $values['contribution_id'] = $this->id
;
2946 if (!empty($ids['related_contact'])) {
2947 $values['related_contact'] = $ids['related_contact'];
2948 if (isset($ids['onbehalf_dupe_alert'])) {
2949 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2952 'contact_id' => $ids['contact'],
2953 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2954 'Home', 'id', 'name'
2957 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2958 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2961 if ($this->is_test
) {
2964 if (!empty($this->_relatedObjects
['membership'])) {
2965 foreach ($this->_relatedObjects
['membership'] as $membership) {
2966 if ($membership->id
) {
2967 $values['membership_id'] = $membership->id
;
2968 $values['isMembership'] = TRUE;
2969 $values['membership_assign'] = TRUE;
2971 // need to set the membership values here
2972 $template->assign('membership_name',
2973 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2975 $template->assign('mem_start_date', $membership->start_date
);
2976 $template->assign('mem_join_date', $membership->join_date
);
2977 $template->assign('mem_end_date', $membership->end_date
);
2978 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2979 $template->assign('mem_status', $membership_status);
2980 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2981 $values['is_pay_later'] = 1;
2983 // Pass amount to floatval as string '0.00' is considered a
2984 // valid amount and includes Fee section in the mail.
2985 if (isset($values['amount'])) {
2986 $values['amount'] = floatval($values['amount']);
2989 if (!empty($this->contribution_recur_id
) && $paymentObject) {
2990 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2991 $template->assign('cancelSubscriptionUrl', $url);
2992 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2993 $template->assign('updateSubscriptionBillingUrl', $url);
2994 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2995 $template->assign('updateSubscriptionUrl', $url);
2998 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3001 // otherwise if its about sending emails, continue sending without return, as we
3002 // don't want to exit the loop.
3007 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3013 * Gather values for contribution mail - this function has been created
3014 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
3015 * Values related to the contribution in question are gathered
3017 * @param array $input
3018 * Input into function (probably from payment processor).
3019 * @param array $values
3021 * The set of ids related to the input.
3024 * @throws \CRM_Core_Exception
3026 public function _gatherMessageValues($input, &$values, $ids = []) {
3027 // set display address of contributor
3028 $values['billingName'] = '';
3029 if ($this->address_id
) {
3030 $addressDetails = CRM_Core_BAO_Address
::getValues(['id' => $this->address_id
], FALSE, 'id');
3031 $addressDetails = reset($addressDetails);
3032 $values['billingName'] = $addressDetails['name'] ??
'';
3034 // Else we assign the billing address of the contribution contact.
3036 $addressDetails = (array) CRM_Core_BAO_Address
::getValues(['contact_id' => $this->contact_id
, 'is_billing' => 1]);
3037 $addressDetails = reset($addressDetails);
3039 $values['address'] = $addressDetails['display'] ??
'';
3041 if ($this->_component
=== 'contribute') {
3042 //get soft contributions
3043 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
3044 if (!empty($softContributions)) {
3045 $values['softContributions'] = $softContributions['soft_credit'];
3047 if (isset($this->contribution_page_id
)) {
3048 // This is a call we want to use less, in favour of loading related objects.
3049 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
3050 if ($this->contribution_page_id
) {
3051 // This is precautionary as there are some legacy flows, but it should really be
3053 if (!isset($this->_relatedObjects
['contributionPage'])) {
3054 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id
]);
3056 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($values);
3059 // no contribution page -probably back office
3061 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
3062 $values['title'] = 'Contribution';
3064 // set lineItem for contribution
3066 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
3067 if (!empty($lineItems)) {
3068 $firstLineItem = reset($lineItems);
3070 if (!empty($firstLineItem['price_set_id'])) {
3071 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
3072 'id' => $firstLineItem['price_set_id'],
3073 'return' => 'is_quick_config, id',
3075 $values['priceSetID'] = $priceSet['id'];
3077 foreach ($lineItems as &$eachItem) {
3078 if (isset($this->_relatedObjects
['membership'])
3079 && is_array($this->_relatedObjects
['membership'])
3080 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
3081 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
3082 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
3083 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
3085 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
3086 // However, that does create upgrade pain so would be better to be phased in.
3087 $values['useForMember'] = empty($priceSet['is_quick_config']);
3089 $values['lineItem'][0] = $lineItems;
3093 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
3097 // if this is onbehalf of contribution then set related contact
3098 if (!empty($relatedContact['individual_id'])) {
3099 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
3103 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects
['participant']->id
, $this->id
));
3106 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
3109 foreach ($groupTree as $key => $group) {
3110 if ($key === 'info') {
3114 foreach ($group['fields'] as $k => $customField) {
3115 $groupLabel = $group['title'];
3116 if (!empty($customField['customValue'])) {
3117 foreach ($customField['customValue'] as $customFieldValues) {
3118 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
3123 $values['customGroup'] = $customGroup;
3125 $values['is_pay_later'] = $this->is_pay_later
;
3131 * Assign message variables to template but try to break the habit.
3133 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3134 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3135 * multiple recurring payments for processors like IATS that use tokens.
3137 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3138 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
3139 * Note we send directly from this function in some cases because it is only partly refactored.
3141 * Don't call this function directly as the signature will change.
3145 * @param bool $returnMessageText
3149 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
3150 // @todo - this should have a better separation of concerns - ie.
3151 // gatherMessageValues should build an array of values to be assigned to the template
3152 // and this function should assign them (assigning null if not set).
3153 // the way the pcpParams & honor Params section works is a baby-step towards this.
3154 $template = CRM_Core_Smarty
::singleton();
3155 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
3156 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
3157 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
3158 $template->assign('billingName', $values['billingName']);
3160 // For some unit tests contribution cannot contain paymentProcessor information
3161 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
3162 $template->assign('contributeMode', CRM_Utils_Array
::value($billingMode, CRM_Core_SelectValues
::contributeMode()));
3164 //assign honor information to receipt message
3165 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
3168 'soft_credit_type' => NULL,
3169 'honor_block_is_active' => NULL,
3171 if (isset($softRecord['soft_credit'])) {
3172 //if id of contribution page is present
3173 if (!empty($values['id'])) {
3174 $values['honor'] = [
3175 'honor_profile_values' => [],
3176 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3177 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
3180 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3181 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
3184 //offline contribution
3185 $softCreditTypes = $softCredits = [];
3186 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3187 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3188 $softCredits[$key] = [
3189 'Name' => $softCredit['contact_name'],
3190 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
3193 $template->assign('softCreditTypes', $softCreditTypes);
3194 $template->assign('softCredits', $softCredits);
3198 $dao = new CRM_Contribute_DAO_ContributionProduct();
3199 $dao->contribution_id
= $this->id
;
3200 if ($dao->find(TRUE)) {
3201 $premiumId = $dao->product_id
;
3202 $template->assign('option', $dao->product_option
);
3204 $productDAO = new CRM_Contribute_DAO_Product();
3205 $productDAO->id
= $premiumId;
3206 $productDAO->find(TRUE);
3207 $template->assign('selectPremium', TRUE);
3208 $template->assign('product_name', $productDAO->name
);
3209 $template->assign('price', $productDAO->price
);
3210 $template->assign('sku', $productDAO->sku
);
3212 $template->assign('title', CRM_Utils_Array
::value('title', $values));
3213 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
3214 if (!$values['amount'] && isset($this->total_amount
)) {
3215 $values['amount'] = $this->total_amount
;
3220 'pcp_display_in_roll' => NULL,
3221 'pcp_roll_nickname' => NULL,
3222 'pcp_personal_note' => NULL,
3226 if (strtolower($this->_component
) == 'contribute') {
3228 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3229 $softDAO->contribution_id
= $this->id
;
3230 if ($softDAO->find(TRUE)) {
3231 $pcpParams['pcpBlock'] = TRUE;
3232 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
3233 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
3234 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
3236 //assign the pcp page title for email subject
3237 $pcpDAO = new CRM_PCP_DAO_PCP();
3238 $pcpDAO->id
= $softDAO->pcp_id
;
3239 if ($pcpDAO->find(TRUE)) {
3240 $pcpParams['title'] = $pcpDAO->title
;
3244 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3245 $template->assign($templateKey, $templateValue);
3248 if ($this->financial_type_id
) {
3249 $values['financial_type_id'] = $this->financial_type_id
;
3252 $template->assign('trxn_id', $this->trxn_id
);
3253 $template->assign('receive_date',
3254 CRM_Utils_Date
::processDate($this->receive_date
)
3256 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
3257 $template->assign('action', $this->is_test ?
1024 : 1);
3258 $template->assign('receipt_text',
3259 CRM_Utils_Array
::value('receipt_text',
3263 $template->assign('is_monetary', 1);
3264 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3265 $template->assign('currency', $this->currency
);
3266 $template->assign('address', CRM_Utils_Address
::format($input));
3267 if (!empty($values['customGroup'])) {
3268 $template->assign('customGroup', $values['customGroup']);
3270 if (!empty($values['softContributions'])) {
3271 $template->assign('softContributions', $values['softContributions']);
3273 if ($this->_component
== 'event') {
3274 $template->assign('title', $values['event']['title']);
3275 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3277 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3278 $viewRoles[] = $participantRoles[$v];
3280 $values['event']['participant_role'] = implode(', ', $viewRoles);
3281 $template->assign('event', $values['event']);
3282 $template->assign('participant', $values['participant']);
3283 $template->assign('location', $values['location']);
3284 $template->assign('customPre', $values['custom_pre_id']);
3285 $template->assign('customPost', $values['custom_post_id']);
3288 if ($this->_relatedObjects
['participant']->is_test
) {
3292 $values['params'] = [];
3293 //to get email of primary participant.
3294 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3295 $primaryAmount[] = [
3296 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3297 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3299 //build an array of cId/pId of participants
3300 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3301 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3302 //send receipt to additional participant if exists
3303 if (count($additionalIDs)) {
3304 $template->assign('isPrimary', 0);
3305 $template->assign('customProfile', NULL);
3306 //set additionalParticipant true
3307 $values['params']['additionalParticipant'] = TRUE;
3308 foreach ($additionalIDs as $pId => $cId) {
3310 //to change the status pending to completed
3311 $additional = new CRM_Event_DAO_Participant();
3312 $additional->id
= $pId;
3313 $additional->contact_id
= $cId;
3314 $additional->find(TRUE);
3315 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3316 $additional->status_id
= 1;
3317 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3318 //if additional participant dont have email
3320 if (!$additionalParticipantInfo) {
3321 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3324 'label' => $additional->fee_level
,
3325 'amount' => $additional->fee_amount
,
3327 $primaryAmount[] = [
3328 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3329 'amount' => $additional->fee_amount
,
3331 $additional->save();
3332 $template->assign('amount', $amount);
3333 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3337 //build an array of custom profile and assigning it to template
3338 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3340 if (count($customProfile)) {
3341 $template->assign('customProfile', $customProfile);
3344 // for primary contact
3345 $values['params']['additionalParticipant'] = FALSE;
3346 $template->assign('isPrimary', 1);
3347 $template->assign('amount', $primaryAmount);
3348 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3349 if ($this->payment_instrument_id
) {
3350 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3351 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3353 // carry paylater, since we did not created billing,
3354 // so need to pull email from primary location, CRM-4395
3355 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3361 * Check whether payment processor supports
3362 * cancellation of contribution subscription
3364 * @param int $contributionId
3367 * @param bool $isNotCancelled
3371 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3372 $cacheKeyString = "$contributionId";
3373 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3375 static $supportsCancel = [];
3377 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3378 $supportsCancel[$cacheKeyString] = FALSE;
3379 $isCancelled = FALSE;
3381 if ($isNotCancelled) {
3382 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3385 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3386 if (!empty($paymentObject)) {
3387 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3390 return $supportsCancel[$cacheKeyString];
3394 * Check whether subscription is already cancelled.
3396 * @param int $contributionId
3400 * contribution status
3402 public static function isSubscriptionCancelled($contributionId) {
3404 SELECT cr.contribution_status_id
3405 FROM civicrm_contribution_recur cr
3406 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3407 WHERE con.id = %1 LIMIT 1";
3408 $params = [1 => [$contributionId, 'Integer']];
3409 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3410 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
3411 if ($status == 'Cancelled') {
3418 * Create all financial accounts entry.
3420 * @param array $params
3421 * Contribution object, line item array and params for trxn.
3424 * @param array $financialTrxnValues
3426 * @return null|\CRM_Core_BAO_FinancialTrxn
3428 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3429 $skipRecords = $update = $return = $isRelatedId = FALSE;
3431 $additionalParticipantId = [];
3432 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3433 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3435 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3436 $entityId = $params['participant_id'];
3437 $entityTable = 'civicrm_participant';
3438 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3440 elseif (!empty($params['membership_id'])) {
3441 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3442 // are created off one contribution should be handled elsewhere
3443 $entityId = $params['membership_id'];
3444 $entityTable = 'civicrm_membership';
3447 $entityId = $params['contribution']->id
;
3448 $entityTable = 'civicrm_contribution';
3451 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3452 $isRelatedId = TRUE;
3455 $entityID[] = $entityId;
3456 if (!empty($additionalParticipantId)) {
3457 $entityID +
= $additionalParticipantId;
3459 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3460 if (empty($params['prevContribution'])) {
3467 $statusId = $params['contribution']->contribution_status_id
;
3468 // CRM-13964 partial payment
3469 if ($contributionStatus == 'Partially paid'
3470 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])
3472 CRM_Core_Error
::deprecatedFunctionWarning('partial_amount params are deprecated from Contribution.create - use Payment.create');
3473 $partialAmtPay = CRM_Utils_Rule
::cleanMoney($params['partial_amount_to_pay']);
3474 $partialAmtTotal = CRM_Utils_Rule
::cleanMoney($params['partial_payment_total']);
3476 $fromFinancialAccountId = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3477 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
3478 $params['total_amount'] = $partialAmtPay;
3480 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3481 if (empty($balanceTrxnInfo['trxn_id'])) {
3482 // create new balance transaction record
3483 $toFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3485 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3486 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3487 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3488 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3489 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3490 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3491 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3492 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3493 $balanceTrxnParams['status_id'] = $statusId;
3494 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3495 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3496 $balanceTrxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3497 $balanceTrxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3498 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3499 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3501 $balanceTrxnParams['is_payment'] = 1;
3503 if (!empty($params['payment_processor'])) {
3504 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3506 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3510 // build line item array if its not set in $params
3511 if (empty($params['line_item']) ||
$additionalParticipantId) {
3512 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3515 if ($contributionStatus != 'Failed' &&
3516 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3518 $skipRecords = TRUE;
3523 if (in_array($contributionStatus, $pendingStatus)) {
3524 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3525 $params['financial_type_id'],
3526 'Accounts Receivable Account is'
3529 elseif (!empty($params['payment_processor'])) {
3530 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3531 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3532 'id' => $params['payment_processor'],
3533 'return' => 'payment_instrument_id',
3536 elseif (!empty($params['payment_instrument_id'])) {
3537 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3540 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3541 $queryParams = [1 => [$relationTypeId, 'Integer']];
3542 $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);
3545 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3546 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3547 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3549 //build financial transaction params
3551 'contribution_id' => $params['contribution']->id
,
3552 'to_financial_account_id' => $params['to_financial_account_id'],
3553 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3554 'total_amount' => $totalAmount,
3555 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3556 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3557 'currency' => $params['contribution']->currency
,
3558 'trxn_id' => $params['contribution']->trxn_id
,
3559 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3560 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3561 // this should really default to completed (after discussion).
3562 'status_id' => $statusId,
3563 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3564 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3565 'pan_truncation' => CRM_Utils_Array
::value('pan_truncation', $params),
3566 'card_type_id' => CRM_Utils_Array
::value('card_type_id', $params),
3568 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3569 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3570 if (isset($params['refund_trxn_id'])) {
3571 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3572 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3575 //CRM-16259, set is_payment flag for non pending status
3576 if (!in_array($contributionStatus, $pendingStatus)) {
3577 $trxnParams['is_payment'] = 1;
3579 if (!empty($params['payment_processor'])) {
3580 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3583 if (isset($fromFinancialAccountId)) {
3584 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3587 // consider external values passed for recording transaction entry
3588 if (!empty($financialTrxnValues)) {
3589 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3591 if (empty($trxnParams['payment_processor_id'])) {
3592 unset($trxnParams['payment_processor_id']);
3595 $params['trxnParams'] = $trxnParams;
3597 if (!empty($params['prevContribution'])) {
3599 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3600 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3601 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3602 if (!isset($params['trxnParams']['trxn_id'])) {
3603 // Actually I have no idea why we are overwriting any values from the previous contribution.
3604 // (filling makes sense to me). However, only protecting this value as I really really know we
3605 // don't want this one overwritten.
3607 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3609 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3611 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3612 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3613 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3615 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3616 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3619 //if financial type is changed
3620 if (!empty($params['financial_type_id']) &&
3621 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3623 $accountRelationship = 'Income Account is';
3624 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3625 $accountRelationship = 'Deferred Revenue Account is';
3627 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3628 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3629 if ($oldFinancialAccount != $newFinancialAccount) {
3630 $params['total_amount'] = 0;
3631 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3632 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3633 $params['prevContribution']->financial_type_id
, $accountRelationship);
3636 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3637 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3638 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3641 self
::updateFinancialAccounts($params, 'changeFinancialType');
3642 $params['skipLineItem'] = FALSE;
3643 foreach ($params['line_item'] as &$lineItems) {
3644 foreach ($lineItems as &$line) {
3645 $line['financial_type_id'] = $params['financial_type_id'];
3648 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType');
3649 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3650 $params['financial_account_id'] = $newFinancialAccount;
3651 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3652 self
::updateFinancialAccounts($params);
3653 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE);
3654 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3656 $params['deferred_financial_account_id'] = $newFinancialAccount;
3660 //Update contribution status
3661 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3662 if (!isset($params['refund_trxn_id'])) {
3663 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3664 // gets preference over another so I am only 'protecting' a very specific tested flow
3665 // and letting natural justice take care of the rest.
3666 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3668 if (!empty($params['contribution_status_id']) &&
3669 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3671 //Update Financial Records
3672 $callUpdateFinancialAccounts = self
::updateFinancialAccountsOnContributionStatusChange($params);
3673 if ($callUpdateFinancialAccounts) {
3674 self
::updateFinancialAccounts($params, 'changedStatus');
3675 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus');
3680 // change Payment Instrument for a Completed contribution
3681 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3682 // instrument is null and now new payment instrument is added along with the payment
3683 if (!$params['contribution']->payment_instrument_id
) {
3684 $params['contribution']->find(TRUE);
3686 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3687 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3689 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3690 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3693 //if Change contribution amount
3694 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3695 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3696 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3697 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3698 if (isset($totalAmount) &&
3699 $totalAmount != $params['prevContribution']->total_amount
3701 //Update Financial Records
3702 $params['trxnParams']['from_financial_account_id'] = NULL;
3703 self
::updateFinancialAccounts($params, 'changedAmount');
3704 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount');
3709 // Looks like we might have a data correction update.
3710 // This would be a case where a transaction id has been entered but it is incorrect &
3711 // the person goes back in & fixes it, as opposed to a new transaction.
3712 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3713 // the data fix scenario.
3715 if (isset($params['refund_trxn_id'])) {
3716 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3717 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3718 civicrm_api3('FinancialTrxn', 'create', [
3719 'id' => $refundIDs['financialTrxnId'],
3720 'trxn_id' => $params['refund_trxn_id'],
3724 $cardType = CRM_Utils_Array
::value('card_type_id', $params);
3725 $panTruncation = CRM_Utils_Array
::value('pan_truncation', $params);
3726 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3731 // records finanical trxn and entity financial trxn
3732 // also make it available as return value
3733 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3734 $trxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3735 $trxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3736 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3737 $params['entity_id'] = $financialTxn->id
;
3738 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3739 self
::$_trxnIDs[] = $financialTxn->id
;
3743 // record line items and financial items
3744 if (empty($params['skipLineItem'])) {
3745 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3748 // create batch entry if batch_id is passed and
3749 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3750 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3752 'batch_id' => $params['batch_id'],
3753 'entity_table' => 'civicrm_financial_trxn',
3754 'entity_id' => $financialTxn->id
,
3756 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3759 // when a fee is charged
3760 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3761 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3764 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3765 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3767 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3768 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3769 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3771 unset($params['line_item']);
3772 self
::$_trxnIDs = NULL;
3777 * Update all financial accounts entry.
3779 * @param array $params
3780 * Contribution object, line item array and params for trxn.
3782 * @param string $context
3785 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3786 * adds unpredictability.
3789 public static function updateFinancialAccounts(&$params, $context = NULL) {
3791 $inputParams = $params;
3792 $isARefund = self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
);
3794 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3795 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3796 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3799 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3800 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3801 $params['entity_id'] = $trxn->id
;
3803 $itemParams['entity_table'] = 'civicrm_line_item';
3804 $trxnIds['id'] = $params['entity_id'];
3805 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution']->id
);
3806 foreach ($params['line_item'] as $fieldId => $fields) {
3807 $params = self
::createFinancialItemsForLine($params, $context, $fields, $previousLineItems, $inputParams, $isARefund, $trxnIds, $fieldId);
3812 * Is this contribution status a reversal.
3814 * If so we would expect to record a negative value in the financial_trxn table.
3816 * @param int $status_id
3820 public static function isContributionStatusNegative($status_id) {
3821 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3822 return in_array(CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE);
3826 * Check status validation on update of a contribution.
3828 * @param array $values
3829 * Previous form values before submit.
3831 * @param array $fields
3832 * The input form values.
3834 * @param array $errors
3839 public static function checkStatusValidation($values, &$fields, &$errors) {
3840 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3841 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3842 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3846 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3848 'Cancelled' => ['Completed', 'Refunded'],
3849 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3850 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3851 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3852 'Refunded' => ['Cancelled', 'Completed'],
3853 'Partially paid' => ['Completed'],
3854 'Pending refund' => ['Completed', 'Refunded'],
3857 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3858 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3860 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3861 1 => $contributionStatuses[$values['contribution_status_id']],
3862 2 => $contributionStatuses[$fields['contribution_status_id']],
3868 * Delete contribution of contact.
3872 * @param int $contactId
3876 public static function deleteContactContribution($contactId) {
3877 $contribution = new CRM_Contribute_DAO_Contribution();
3878 $contribution->contact_id
= $contactId;
3879 $contribution->find();
3880 while ($contribution->fetch()) {
3881 self
::deleteContribution($contribution->id
);
3886 * Get options for a given contribution field.
3888 * @param string $fieldName
3889 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3890 * @param array $props whatever is known about this dao object.
3892 * @return array|bool
3893 * @see CRM_Core_DAO::buildOptions
3896 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3897 $className = __CLASS__
;
3899 if (isset($props['orderColumn'])) {
3900 $params['orderColumn'] = $props['orderColumn'];
3902 switch ($fieldName) {
3903 // This field is not part of this object but the api supports it
3904 case 'payment_processor':
3905 $className = 'CRM_Contribute_BAO_ContributionPage';
3906 // Filter results by contribution page
3907 if (!empty($props['contribution_page_id'])) {
3908 $page = civicrm_api('contribution_page', 'getsingle', [
3910 'id' => ($props['contribution_page_id']),
3912 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3913 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3917 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3918 case 'honor_type_id':
3919 $className = 'CRM_Contribute_BAO_ContributionSoft';
3920 $fieldName = 'soft_credit_type_id';
3921 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3924 case 'contribution_status_id':
3925 if ($context !== 'validate') {
3926 $params['condition'] = "v.name <> 'Template'";
3929 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3933 * Validate financial type.
3937 * @param int $financialTypeId
3938 * Financial Type id.
3940 * @param string $relationName
3942 * @return array|bool
3944 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3945 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3947 if (!$financialAccount) {
3948 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3954 * @param int $targetCid
3955 * @param $activityType
3956 * @param string $title
3957 * @param int $contributionId
3958 * @param string $totalAmount
3959 * @param string $currency
3960 * @param string $trxn_date
3962 * @throws \CRM_Core_Exception
3963 * @throws \CiviCRM_API3_Exception
3965 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
3966 $paymentAmount = CRM_Utils_Money
::format($totalAmount, $currency);
3967 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3968 $date = CRM_Utils_Date
::isoToMysql($trxn_date);
3969 // source record id would be the contribution id
3970 $srcRecId = $contributionId;
3974 'source_contact_id' => $targetCid,
3975 'source_record_id' => $srcRecId,
3976 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
3977 'subject' => $subject,
3978 'activity_date_time' => $date,
3979 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
3980 'skipRecentView' => TRUE,
3983 // create activity with target contacts
3984 $session = CRM_Core_Session
::singleton();
3985 $id = $session->get('userID');
3987 $activityParams['source_contact_id'] = $id;
3988 $activityParams['target_contact_id'][] = $targetCid;
3990 civicrm_api3('Activity', 'create', $activityParams);
3994 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3998 * @param bool $getTrxnInfo
3999 * @param bool $usingLineTotal
4003 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
4004 // @todo deprecate passing in component - always call with contribution.
4005 if ($component == 'event') {
4006 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
4008 if (!$contributionId) {
4009 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4010 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4011 $id = $primaryParticipantId;
4013 if (!$contributionId) {
4018 elseif ($component == 'membership') {
4019 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
4022 $contributionId = $id;
4025 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
4026 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
4028 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
4029 $baseTrxnId = $baseTrxnId['financialTrxnId'];
4031 if (empty($total['total_amount']) ||
$usingLineTotal) {
4032 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4035 $baseTrxnId = $total['trxn_id'];
4036 $total = $total['total_amount'];
4039 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
4041 $contribution = civicrm_api3('Contribution', 'getsingle', [
4042 'id' => $contributionId,
4046 'contribution_status_id',
4047 'financial_type_id',
4051 $info['payLater'] = $contribution['is_pay_later'];
4052 $info['contribution_status'] = $contribution['contribution_status'];
4053 $info['currency'] = $contribution['currency'];
4055 $financialTypeId = $contribution['financial_type_id'];
4056 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, 'Expense Account is');
4058 $info['total'] = $total;
4059 $info['paid'] = $total - $paymentBalance;
4060 $info['balance'] = $paymentBalance;
4062 $info['component'] = $component;
4064 if ($getTrxnInfo && $baseTrxnId) {
4065 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
4067 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
4069 ft.payment_instrument_id,
4070 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
4072 FROM civicrm_contribution con
4073 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4074 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4075 AND ft.to_financial_account_id != %2
4076 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
4077 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
4078 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
4080 WHERE con.id = %1 AND ft.is_payment = 1
4083 1 => [$contributionId, 'Integer'],
4084 2 => [$feeFinancialAccount, 'Integer'],
4086 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
4087 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label');
4089 while ($resultDAO->fetch()) {
4090 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4091 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4092 if ($resultDAO->card_type_id
) {
4093 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
4094 $pantruncation = '';
4095 if ($resultDAO->pan_truncation
) {
4096 $pantruncation = ": {$resultDAO->pan_truncation}";
4098 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
4101 // show payment edit link only for payments done via backoffice form
4102 $paymentEditLink = '';
4103 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
4105 CRM_Core_Action
::UPDATE
=> [
4106 'name' => "<i class='crm-i fa-pencil'></i>",
4107 'url' => 'civicrm/payment/edit',
4108 'class' => 'medium-popup',
4109 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
4110 'title' => ts('Edit Payment'),
4113 $paymentEditLink = CRM_Core_Action
::formLink(
4115 CRM_Core_Action
::mask([CRM_Core_Permission
::EDIT
]),
4117 'id' => $resultDAO->id
,
4118 'contribution_id' => $contributionId,
4122 'Payment.edit.action',
4129 'id' => $resultDAO->id
,
4130 'total_amount' => $resultDAO->total_amount
,
4131 'financial_type' => $resultDAO->financial_account
,
4132 'payment_instrument' => $paidByLabel,
4133 'receive_date' => $resultDAO->trxn_date
,
4134 'trxn_id' => $resultDAO->trxn_id
,
4135 'status' => $statuses[$resultDAO->status_id
],
4136 'currency' => $resultDAO->currency
,
4137 'action' => $paymentEditLink,
4139 if ($paidByName == 'Check') {
4140 $val['check_number'] = $resultDAO->check_number
;
4144 $info['transaction'] = $rows;
4147 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
4152 * Get the outstanding balance on a contribution.
4154 * @param int $contributionId
4155 * @param float $contributionTotal
4156 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
4160 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
4161 if ($contributionTotal === NULL) {
4162 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4165 return (float) CRM_Utils_Money
::subtractCurrencies(
4167 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE),
4168 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4173 * Get the tax amount (misnamed function).
4175 * @param array $params
4176 * @param bool $isLineItem
4180 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4181 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4183 // This function should be only called after standardisation (removal of
4184 // thousand separator & using a decimal point for cents separator.
4185 // However, we don't know if that is always true :-(
4186 // There is a deprecation notice tho :-)
4187 $unknownIfMoneyIsClean = empty($params['skipCleanMoney']) && !$isLineItem;
4188 // Update contribution.
4189 if (!empty($params['id'])) {
4190 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4191 // there are no tax implications - early return.
4192 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4195 if (empty($params['prevContribution'])) {
4196 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4199 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
4200 if (!isset($params[$field])) {
4201 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4202 // Tax amount gets added back on later....
4203 $params['total_amount'] = $params['prevContribution']->total_amount
-
4204 $params['prevContribution']->tax_amount
;
4207 $params[$field] = $params['prevContribution']->$field;
4208 if ($params[$field] != $params['prevContribution']->$field) {
4214 self
::calculateMissingAmountParams($params, $params['id']);
4215 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4216 // Assign tax Amount on update of contribution
4217 if (!empty($params['prevContribution']->tax_amount
)) {
4218 $params['tax_amount'] = 'null';
4219 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4220 foreach ($params['line_item'] as $setID => $priceField) {
4221 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4222 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4229 // New Contribution and update of contribution with tax rate financial type
4230 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4231 empty($params['skipLineItem']) && !$isLineItem
4233 $taxRateParams = $taxRates[$params['financial_type_id']];
4234 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams, $unknownIfMoneyIsClean);
4235 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4237 // Get Line Item on update of contribution
4238 if (isset($params['id'])) {
4239 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4242 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4244 foreach ($params['line_item'] as $setID => $priceField) {
4245 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4246 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4249 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4251 elseif (isset($params['api.line_item.create'])) {
4252 // Update total amount of contribution using lineItem
4253 $taxAmountArray = [];
4254 foreach ($params['api.line_item.create'] as $key => $value) {
4255 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4256 $taxRate = $taxRates[$value['financial_type_id']];
4257 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4258 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4261 $params['tax_amount'] = array_sum($taxAmountArray);
4262 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4265 // update line item of contrbution
4266 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4267 $taxRate = $taxRates[$params['financial_type_id']];
4268 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate, $unknownIfMoneyIsClean);
4269 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4276 * Check financial type validation on update of a contribution.
4278 * @param int $financialTypeId
4279 * Value of latest Financial Type.
4281 * @param int $contributionId
4284 * @param array $errors
4289 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4290 if (!empty($financialTypeId)) {
4291 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4292 if ($oldFinancialTypeId == $financialTypeId) {
4296 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4298 '1' => [$contributionId, 'Integer'],
4300 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4301 if ($result->N
> 1) {
4302 $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.');
4307 * Update related pledge payment payments.
4309 * This function has been refactored out of the back office contribution form and may
4310 * still overlap with other functions.
4312 * @param string $action
4313 * @param int $pledgePaymentID
4314 * @param int $contributionID
4315 * @param bool $adjustTotalAmount
4316 * @param float $total_amount
4317 * @param float $original_total_amount
4318 * @param int $contribution_status_id
4319 * @param int $original_contribution_status_id
4321 public static function updateRelatedPledge(
4327 $original_total_amount,
4328 $contribution_status_id,
4329 $original_contribution_status_id
4331 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4335 if ($pledgePaymentID) {
4336 //store contribution id in payment record.
4337 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4340 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4347 if (!$pledgePaymentID) {
4350 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4356 $updatePledgePaymentStatus = FALSE;
4358 // If either the status or the amount has changed we update the pledge status.
4359 if ($action & CRM_Core_Action
::ADD
) {
4360 $updatePledgePaymentStatus = TRUE;
4362 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4363 ($original_total_amount != $total_amount))
4365 $updatePledgePaymentStatus = TRUE;
4368 if ($updatePledgePaymentStatus) {
4369 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4371 $contribution_status_id,
4380 * Compute the stats values
4382 * @param string $stat either 'mode' or 'median'
4383 * @param string $sql
4384 * @param string $alias of civicrm_contribution
4386 * @return array|null
4390 public static function computeStats($stat, $sql, $alias = NULL) {
4391 CRM_Core_Error
::deprecatedFunctionWarning('computeStats is now deprecated');
4396 * Is there only one line item attached to the contribution.
4402 * @throws \CiviCRM_API3_Exception
4404 public static function isSingleLineItem($id) {
4405 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
4406 return ($lineItemCount == 1);
4410 * Complete an order.
4412 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4414 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4416 * Moving it out of the BaseIPN class is just the first step.
4418 * @param array $input
4420 * @param array $objects
4421 * @param CRM_Core_Transaction $transaction
4422 * @param CRM_Contribute_BAO_Contribution $contribution
4423 * @param bool $isPostPaymentCreate
4424 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
4425 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
4426 * transitioning related elements).
4429 * @throws \CRM_Core_Exception
4430 * @throws \CiviCRM_API3_Exception
4432 public static function completeOrder($input, &$ids, $objects, $transaction, $contribution, $isPostPaymentCreate = FALSE) {
4433 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4434 // The previous details are used when calculating line items so keep it before any code that 'does something'
4435 if (!empty($contribution->id
)) {
4436 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(['id' => $contribution->id
]);
4438 $inputContributionWhiteList = [
4443 'payment_instrument_id',
4448 'contribution_status_id',
4452 if (self
::isSingleLineItem($primaryContributionID)) {
4453 $inputContributionWhiteList[] = 'financial_type_id';
4456 $participant = CRM_Utils_Array
::value('participant', $objects);
4457 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4458 $recurringContributionID = (empty($recurContrib->id
)) ?
NULL : $recurContrib->id
;
4459 $event = CRM_Utils_Array
::value('event', $objects);
4461 $paymentProcessorId = '';
4462 if (isset($objects['paymentProcessor'])) {
4463 if (is_array($objects['paymentProcessor'])) {
4464 $paymentProcessorId = $objects['paymentProcessor']['id'];
4467 $paymentProcessorId = $objects['paymentProcessor']->id
;
4471 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4473 $contributionParams = array_merge([
4474 'contribution_status_id' => $completedContributionStatusID,
4475 'source' => self
::getRecurringContributionDescription($contribution, $event),
4476 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4479 // CRM-20678 Ensure that the currency is correct in subseqent transcations.
4480 if (empty($contributionParams['currency']) && isset($objects['first_contribution']->currency
)) {
4481 $contributionParams['currency'] = $objects['first_contribution']->currency
;
4484 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
4486 // If paymentProcessor is not set then the payment_instrument_id would not be correct.
4487 // not clear when or if this would occur if you encounter this please fix here & add a unit test.
4488 if (empty($contributionParams['payment_instrument_id']) && isset($contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'])) {
4489 $contributionParams['payment_instrument_id'] = $contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'];
4492 if ($recurringContributionID) {
4493 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4495 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4497 if (empty($contributionParams['receive_date']) && $changeDate) {
4498 $contributionParams['receive_date'] = $changeDate;
4501 self
::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
4502 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4505 if (isset($input['is_email_receipt'])) {
4506 $values['is_email_receipt'] = $input['is_email_receipt'];
4509 if ($input['component'] == 'contribute') {
4510 if ($contribution->contribution_page_id
) {
4511 // Figure out what we gain from this.
4512 // Note that we may have overwritten the is_email_receipt input, fix that below.
4513 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4515 elseif ($recurContrib && $recurringContributionID) {
4516 $values['amount'] = $recurContrib->amount
;
4517 $values['financial_type_id'] = $objects['contributionType']->id
;
4518 $values['title'] = $source = ts('Offline Recurring Contribution');
4521 if (isset($input['is_email_receipt'])) {
4522 // CRM-19601 - we may have overwritten this above.
4523 $values['is_email_receipt'] = $input['is_email_receipt'];
4525 elseif ($recurContrib && $recurringContributionID) {
4526 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4527 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4528 // 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
4529 // Instance that had the table added via an upgrade in 4.1
4530 // see also https://github.com/civicrm/civicrm-svn/commit/7f39befd60bc735408d7866b02b3ac7fff1d4eea#diff-9ad8e290180451a2d6eacbd3d1ca7966R354
4531 // https://lab.civicrm.org/dev/core/issues/1245
4532 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4535 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4536 self
::updateMembershipBasedOnCompletionOfContribution(
4538 $primaryContributionID,
4544 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4545 if ($event->is_email_confirm
) {
4546 // @todo this should be set by the function that sends the mail after sending.
4547 $contributionParams['receipt_date'] = $changeDate;
4549 $participantParams['id'] = $participant->id
;
4550 $participantParams['status_id'] = 'Registered';
4551 civicrm_api3('Participant', 'create', $participantParams);
4555 $contributionParams['id'] = $contribution->id
;
4556 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
4558 // CRM-19309 - if you update the contribution here with financial_type_id it can/will mess with $lineItem
4559 // unsetting it here does NOT cause any other contribution test to fail!
4560 unset($contributionParams['financial_type_id']);
4561 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4563 // Add new soft credit against current $contribution.
4564 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
4565 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4568 if (empty($contribution->_relatedObjects
['participant']) && !empty($contribution->_relatedObjects
['membership'])) {
4569 // @fixme Can we remove this if altogether? - we removed the participant if / else and left relatedObjects['participant'] to ensure behaviour didn't change but it is probably not required.
4570 // @todo - use getRelatedMemberships instead
4571 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4572 $contribution->trxn_id
= CRM_Utils_Array
::value('trxn_id', $input);
4573 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4576 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4577 $transaction->commit();
4579 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution->id
, $recurringContributionID,
4580 $contributionParams['contribution_status_id'], $input['amount']);
4582 // create an activity record
4583 if ($input['component'] == 'contribute') {
4585 $targetContactID = NULL;
4586 if (!empty($ids['related_contact'])) {
4587 $targetContactID = $contribution->contact_id
;
4588 $contribution->contact_id
= $ids['related_contact'];
4590 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4593 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4594 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4595 if (!array_key_exists('is_email_receipt', $values) ||
4596 $values['is_email_receipt'] == 1
4598 civicrm_api3('Contribution', 'sendconfirmation', [
4599 'id' => $contribution->id
,
4600 'payment_processor_id' => $paymentProcessorId,
4602 CRM_Core_Error
::debug_log_message("Receipt sent");
4605 CRM_Core_Error
::debug_log_message("Success: Database updated");
4606 return $contributionResult;
4610 * Send receipt from contribution.
4612 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4614 * Note that the compose message part has been moved to contribution
4615 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4617 * @param array $input
4618 * Incoming data from Payment processor.
4620 * Related object IDs.
4621 * @param int $contributionID
4622 * @param array $values
4623 * Values related to objects that have already been loaded.
4624 * @param bool $returnMessageText
4625 * Should text be returned instead of sent. This.
4626 * is because the function is also used to generate pdfs
4629 * @throws \CRM_Core_Exception
4630 * @throws \CiviCRM_API3_Exception
4631 * @throws \Exception
4633 public static function sendMail(&$input, &$ids, $contributionID, &$values,
4634 $returnMessageText = FALSE) {
4636 $contribution = new CRM_Contribute_BAO_Contribution();
4637 $contribution->id
= $contributionID;
4638 if (!$contribution->find(TRUE)) {
4639 throw new CRM_Core_Exception('Contribution does not exist');
4641 $contribution->loadRelatedObjects($input, $ids, TRUE);
4642 // set receipt from e-mail and name in value
4643 if (!$returnMessageText) {
4644 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4646 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4647 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4648 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4649 civicrm_api3('Contribution', 'create', [
4650 'receipt_date' => 'now',
4651 'id' => $contribution->id
,
4658 * Generate From email and from name in an array values
4660 * @param array $input
4661 * @param \CRM_Contribute_BAO_Contribution $contribution
4665 public static function generateFromEmailAndName($input, $contribution) {
4666 // Use input value if supplied.
4667 if (!empty($input['receipt_from_email'])) {
4669 CRM_Utils_Array
::value('receipt_from_name', $input, ''),
4670 $input['receipt_from_email'],
4673 // if we are still empty see if we can use anything from a contribution page.
4675 if (!empty($contribution->contribution_page_id
)) {
4676 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id
]);
4678 // if we are still empty see if we can use anything from a contribution page.
4679 if (!empty($pageValues['receipt_from_email'])) {
4681 CRM_Utils_Array
::value('receipt_from_name', $pageValues),
4682 $pageValues['receipt_from_email'],
4685 // If we are still empty fall back to the domain or logged in user information.
4686 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4690 * Load related memberships.
4694 * @return array $ids
4699 * Note that in theory it should be possible to retrieve these from the line_item table
4700 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4701 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4702 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4703 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4705 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4708 public function loadRelatedMembershipObjects($ids = []) {
4710 SELECT membership_id
4711 FROM civicrm_membership_payment
4712 WHERE contribution_id = %1 ";
4713 $params = [1 => [$this->id
, 'Integer']];
4714 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, []);
4716 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4717 while ($dao->fetch()) {
4718 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4719 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4723 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4724 foreach ($ids['membership'] as $id) {
4726 $membership = new CRM_Member_BAO_Membership();
4727 $membership->id
= $id;
4728 if (!$membership->find(TRUE)) {
4729 throw new Exception("Could not find membership record: $id");
4731 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4732 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4733 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4734 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4742 * This function is used to record partial payments for contribution
4744 * @param array $contribution
4746 * @param array $params
4748 * @return CRM_Financial_DAO_FinancialTrxn
4750 public static function recordPartialPayment($contribution, $params) {
4751 CRM_Core_Error
::deprecatedFunctionWarning('use payment create api');
4752 $balanceTrxnParams['to_financial_account_id'] = self
::getToFinancialAccount($contribution, $params);
4753 $balanceTrxnParams['from_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($contribution['financial_type_id'], 'Accounts Receivable Account is');
4754 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4755 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4756 $balanceTrxnParams['trxn_date'] = CRM_Utils_Array
::value('trxn_date', $params, CRM_Utils_Array
::value('contribution_receive_date', $params, date('YmdHis')));
4757 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4758 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4759 $balanceTrxnParams['currency'] = $contribution['currency'];
4760 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4761 $balanceTrxnParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_FinancialTrxn', 'status_id', 'Completed');
4762 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4763 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4764 $balanceTrxnParams['is_payment'] = 1;
4766 if (!empty($params['payment_processor'])) {
4767 // I can't find evidence this is passed in - I was gonna just remove it but decided to deprecate as I see self::getToFinancialAccount
4768 // also anticipates it.
4769 CRM_Core_Error
::deprecatedFunctionWarning('passing payment_processor is deprecated - use payment_processor_id');
4770 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4772 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4776 * Get the description (source field) for the recurring contribution.
4778 * @param CRM_Contribute_BAO_Contribution $contribution
4779 * @param CRM_Event_DAO_Event|null $event
4782 * @throws \CiviCRM_API3_Exception
4784 protected static function getRecurringContributionDescription($contribution, $event) {
4785 if (!empty($contribution->source
)) {
4786 return $contribution->source
;
4788 elseif (!empty($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
4789 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', [
4790 'id' => $contribution->contribution_page_id
,
4791 'return' => 'title',
4793 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4796 return ts('Online Event Registration') . ': ' . $event->title
;
4798 elseif (!empty($contribution->contribution_recur_id
)) {
4799 return 'recurring contribution';
4805 * Function use to store line item proportionally in in entity financial trxn table
4807 * @param array $trxnParams
4809 * @param int $trxnId
4811 * @param float $contributionTotalAmount
4813 * @throws \CiviCRM_API3_Exception
4815 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4816 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4817 if (!empty($lineItems)) {
4818 // get financial item
4819 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4821 'contribution_total_amount' => $contributionTotalAmount,
4822 'trxn_total_amount' => $trxnParams['total_amount'],
4823 'trxn_id' => $trxnId,
4825 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4830 * Checks if line items total amounts
4831 * match the contribution total amount.
4833 * @param array $params
4834 * array of order params.
4836 * @throws \API_Exception
4838 public static function checkLineItems(&$params) {
4839 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
4840 $lineItemAmount = 0;
4842 foreach ($params['line_items'] as &$lineItems) {
4843 foreach ($lineItems['line_item'] as &$item) {
4844 if (empty($item['financial_type_id'])) {
4845 $item['financial_type_id'] = $params['financial_type_id'];
4847 $lineItemAmount +
= $item['line_total'] + CRM_Utils_Array
::value('tax_amount', $item, 0.00);
4851 if (!isset($totalAmount)) {
4852 $params['total_amount'] = $lineItemAmount;
4855 $currency = CRM_Utils_Array
::value('currency', $params, '');
4857 if (empty($currency)) {
4858 $currency = CRM_Core_Config
::singleton()->defaultCurrency
;
4861 if (!CRM_Utils_Money
::equals($totalAmount, $lineItemAmount, $currency)) {
4862 throw new CRM_Contribute_Exception_CheckLineItemsException();
4868 * Get the financial account for the item associated with the new transaction.
4870 * @param array $params
4871 * @param int $default
4875 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
4877 if (!empty($params['financial_account_id'])) {
4878 return $params['financial_account_id'];
4881 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4882 $preferredAccountsRelationships = [
4883 'Refunded' => 'Credit/Contra Revenue Account is',
4884 'Chargeback' => 'Chargeback Account is',
4887 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4888 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4889 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4891 $preferredAccountsRelationships[$contributionStatus]
4899 * ContributionPage values were being imposed onto values.
4901 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4902 * REALLY didn't want superimposed. The rest are left there in their overkill out
4905 * The rationale for making this explicit is that it was a case of carefully set values being
4906 * seemingly randonly overwritten without much care. In general I think array randomly setting
4907 * variables en mass is risky.
4909 * @param array $values
4913 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4914 $contributionPageValues = [];
4915 CRM_Contribute_BAO_ContributionPage
::setValues(
4916 $this->contribution_page_id
,
4917 $contributionPageValues
4920 // These are the values that I believe to be useful.
4923 'pay_later_receipt',
4925 'receipt_from_email',
4926 'receipt_from_name',
4930 'honoree_profile_id',
4931 'onbehalf_profile_id',
4932 'honor_block_is_active',
4933 // Kinda might be - but would be on the contribution...
4936 // Included for 'fear of regression' but can't justify any use for these....
4938 'payment_processor',
4939 'financial_type_id',
4940 'amount_block_is_active',
4945 'default_amount_id',
4949 'initial_amount_help_text',
4950 'initial_amount_label',
4952 'is_allow_other_amount',
4953 'is_billing_required',
4954 'is_confirm_enabled',
4955 'is_credit_card_only',
4957 'is_partial_payment',
4958 'is_recur_installments',
4959 'is_recur_interval',
4963 'min_initial_amount',
4964 'recur_frequency_unit',
4971 foreach ($valuesToCopy as $valueToCopy) {
4972 if (isset($contributionPageValues[$valueToCopy])) {
4973 if ($valueToCopy === 'title') {
4974 $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils
::getContributionPageTitle($this->contribution_page_id
);
4977 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
4985 * Get values of CiviContribute Settings
4986 * and check if its enabled or not.
4987 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
4988 * in serialized form. Usually this should be stored as flat settings for each form fields
4989 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
4990 * settings we will live with an inconsistency because it's too hard to change for now.
4991 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
4994 * @param string $name
4999 public static function checkContributeSettings($name) {
5000 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
5001 return CRM_Utils_Array
::value($name, $contributeSettings);
5005 * This function process contribution related objects.
5007 * @param int $contributionId
5008 * @param int $statusId
5009 * @param int|null $previousStatusId
5011 * @param string $receiveDate
5013 * @return null|string
5015 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
5017 if (!$contributionId ||
!$statusId) {
5022 'contribution_id' => $contributionId,
5023 'contribution_status_id' => $statusId,
5024 'previous_contribution_status_id' => $previousStatusId,
5025 'receive_date' => $receiveDate,
5028 $updateResult = CRM_Contribute_BAO_Contribution
::transitionComponents($params);
5030 if (!is_array($updateResult) ||
5031 !($updatedComponents = CRM_Utils_Array
::value('updatedComponents', $updateResult)) ||
5032 !is_array($updatedComponents) ||
5033 empty($updatedComponents)
5038 // get the user display name.
5040 SELECT display_name as displayName
5041 FROM civicrm_contact
5042 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
5043 WHERE civicrm_contribution.id = {$contributionId}";
5044 $userDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
5046 // get the status message for user.
5047 foreach ($updatedComponents as $componentName => $updatedStatusId) {
5049 if ($componentName == 'CiviMember') {
5050 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5051 CRM_Member_PseudoConstant
::membershipStatus()
5054 $statusNameMsgPart = 'updated';
5055 switch ($updatedStatusName) {
5058 $statusNameMsgPart = $updatedStatusName;
5062 $statusMsg .= "<br />" . ts("Membership for %1 has been %2.", [
5063 1 => $userDisplayName,
5064 2 => $statusNameMsgPart,
5068 if ($componentName == 'CiviEvent') {
5069 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5070 CRM_Event_PseudoConstant
::participantStatus()
5072 if ($updatedStatusName == 'Cancelled') {
5073 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", [1 => $userDisplayName]);
5075 elseif ($updatedStatusName == 'Registered') {
5076 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", [1 => $userDisplayName]);
5080 if ($componentName == 'CiviPledge') {
5081 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5082 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name')
5084 if ($updatedStatusName == 'Cancelled') {
5085 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", [1 => $userDisplayName]);
5087 elseif ($updatedStatusName == 'Failed') {
5088 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", [1 => $userDisplayName]);
5090 elseif ($updatedStatusName == 'Completed') {
5091 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", [1 => $userDisplayName]);
5100 * Get the contribution as it is in the database before being updated.
5102 * @param int $contributionID
5104 * @return \CRM_Contribute_BAO_Contribution|null
5106 private static function getOriginalContribution($contributionID) {
5107 return self
::getValues(['id' => $contributionID]);
5111 * Get the amount for the financial item row.
5113 * Helper function to start to break down recordFinancialTransactions for readability.
5115 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
5117 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
5118 * for historical reasons. Going forwards we can hope to add tests & improve readibility
5121 * @param array $params
5122 * Params as passed to contribution.create
5124 * @param string $context
5125 * changeFinancialType| changedAmount
5126 * @param array $lineItemDetails
5128 * @param bool $isARefund
5129 * Is this a refund / negative transaction.
5130 * @param int $previousLineItemTotal
5133 * @todo move recordFinancialAccounts & helper functions to their own class?
5136 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
5137 if ($context == 'changedAmount') {
5138 $lineTotal = $lineItemDetails['line_total'];
5139 if ($lineTotal != $previousLineItemTotal) {
5140 $lineTotal -= $previousLineItemTotal;
5144 elseif ($context == 'changeFinancialType') {
5145 return -$lineItemDetails['line_total'];
5147 elseif ($context == 'changedStatus') {
5148 $cancelledTaxAmount = 0;
5150 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
5152 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
5154 elseif ($context === NULL) {
5155 // erm, yes because? but, hey, it's tested.
5156 return $lineItemDetails['line_total'];
5158 elseif (empty($lineItemDetails['line_total'])) {
5159 // follow legacy code path
5161 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', ['civi.tag' => 'deprecated']);
5162 return $params['total_amount'];
5165 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
5170 * Get the multiplier for adjusting rows.
5172 * If we are dealing with a refund or cancellation then it will be a negative
5173 * amount to reflect the negative transaction.
5175 * If we are changing Financial Type it will be a negative amount to
5176 * adjust down the old type.
5178 * @param int $contribution_status_id
5179 * @param string $context
5183 protected static function getMultiplier($contribution_status_id, $context) {
5184 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
5191 * Does this transaction reflect a payment instrument change.
5193 * @param array $params
5194 * @param array $pendingStatuses
5198 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
5199 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
5201 if (array_key_exists('payment_instrument_id', $params)) {
5202 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
5203 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
5205 //check if status is changed from Pending to Completed
5206 // do not update payment instrument changes for Pending to Completed
5207 if (!($contributionStatus == 'Completed' &&
5208 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
5213 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
5214 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
5215 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
5219 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
5220 $params['contribution']->check_number
!= $params['prevContribution']->check_number
5222 // another special case when check number is changed, create new financial records
5223 // create financial trxn with negative amount
5231 * Update the memberships associated with a contribution if it has been completed.
5233 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
5234 * load them in this function. Code clean up would compensate for any minor performance implication.
5236 * @param \CRM_Contribute_BAO_Contribution $contribution
5237 * @param int $primaryContributionID
5238 * @param string $changeDate
5240 * @throws \CRM_Core_Exception
5241 * @throws \CiviCRM_API3_Exception
5243 public static function updateMembershipBasedOnCompletionOfContribution($contribution, $primaryContributionID, $changeDate) {
5244 $memberships = self
::getRelatedMemberships($contribution->id
);
5245 foreach ($memberships as $membership) {
5246 $membershipParams = [
5247 'id' => $membership['id'],
5248 'contact_id' => $membership['contact_id'],
5249 'is_test' => $membership['is_test'],
5250 'membership_type_id' => $membership['membership_type_id'],
5251 'membership_activity_status' => 'Completed',
5254 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
5255 $membershipParams['membership_type_id'],
5256 $membershipParams['is_test'],
5257 $membershipParams['id']
5260 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
5261 // this picks up membership type changes during renewals
5262 // @todo this is almost certainly an obsolete sql call, the pre-change
5263 // membership is accessible via $this->_relatedObjects
5265 SELECT membership_type_id
5266 FROM civicrm_membership_log
5267 WHERE membership_id={$membershipParams['id']}
5270 $dao = CRM_Core_DAO
::executeQuery($sql);
5271 if ($dao->fetch()) {
5272 if (!empty($dao->membership_type_id
)) {
5273 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
5276 if (empty($membership['end_date']) ||
(int) $membership['status_id'] !== CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
5277 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
5278 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
5279 // 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.
5280 // @todo once apiv4 ships with core switch to that & find sanity.
5281 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
5282 $membershipParams['membership_type_id'],
5283 $primaryContributionID
5286 // @todo remove all this stuff in favour of letting the api call further down handle in
5287 // (it is a duplication of what the api does).
5288 $dates = array_fill_keys([
5293 if ($currentMembership) {
5295 * Fixed FOR CRM-4433
5296 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
5297 * when Contribution mode is notify and membership is for renewal )
5299 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
5301 // @todo - we should pass membership_type_id instead of null here but not
5302 // adding as not sure of testing
5303 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
5304 $changeDate, NULL, $membershipParams['num_terms']
5306 $dates['join_date'] = $currentMembership['join_date'];
5309 //get the status for membership.
5310 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
5312 $dates['join_date'],
5315 $membershipParams['membership_type_id'],
5319 unset($dates['end_date']);
5320 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
5321 //we might be renewing membership,
5322 //so make status override false.
5323 $membershipParams['is_override'] = FALSE;
5324 $membershipParams['status_override_end_date'] = 'null';
5326 //CRM-17723 - reset static $relatedContactIds array()
5327 // @todo move it to Civi Statics.
5329 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
5330 civicrm_api3('Membership', 'create', $membershipParams);
5335 * Get payment links as they relate to a contribution.
5337 * If a payment can be made then include a payment link & if a refund is appropriate
5338 * then a refund link.
5341 * @param float $balance
5342 * @param string $contributionStatus
5345 * $actionLinks Links array containing:
5349 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
5350 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
5351 // In general the balance is the best way to determine if a payment can be added or not,
5352 // but not for Failed contributions, where we don't accept additional payments at the moment.
5353 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
5354 // do accept more payments agains them.
5358 if ((int) $balance > 0) {
5359 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
5361 'url' => CRM_Utils_System
::url('civicrm/payment', [
5367 'title' => ts('Submit Credit Card payment'),
5371 'url' => CRM_Utils_System
::url('civicrm/payment', [
5376 'title' => ts('Record Payment'),
5379 elseif ((int) $balance < 0) {
5381 'url' => CRM_Utils_System
::url('civicrm/payment', [
5386 'title' => ts('Record Refund'),
5389 return $actionLinks;
5393 * Get a query to determine the amount donated by the contact/s in the current financial year.
5395 * @param array $contactIDs
5399 public static function getAnnualQuery($contactIDs) {
5400 $contactIDs = implode(',', $contactIDs);
5401 $config = CRM_Core_Config
::singleton();
5402 $currentMonth = date('m');
5403 $currentDay = date('d');
5405 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
5407 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
5408 (int) $config->fiscalYearStart
['d'] > $currentDay
5411 $year = date('Y') - 1;
5416 $nextYear = $year +
1;
5418 if ($config->fiscalYearStart
) {
5419 $newFiscalYearStart = $config->fiscalYearStart
;
5420 if ($newFiscalYearStart['M'] < 10) {
5421 // This is just a clumsy way of adding padding.
5422 // @todo next round look for a nicer way.
5423 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
5425 if ($newFiscalYearStart['d'] < 10) {
5426 // This is just a clumsy way of adding padding.
5427 // @todo next round look for a nicer way.
5428 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
5430 $config->fiscalYearStart
= $newFiscalYearStart;
5431 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
5434 // First of January.
5437 $startDate = "$year$monthDay";
5438 $endDate = "$nextYear$monthDay";
5441 'contact_id' => 'IN (' . $contactIDs . ')',
5442 'is_test' => ' = 0',
5443 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
5445 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
5446 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
5449 foreach ($whereClauses as $key => $clause) {
5450 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
5452 $whereClauseString = implode(' AND ', $clauses);
5454 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5455 // this group by + having on contribution_status_id improves performance
5457 SELECT COUNT(*) as count,
5458 SUM(total_amount) as amount,
5459 AVG(total_amount) as average,
5461 FROM civicrm_contribution b
5462 WHERE " . $whereClauseString . "
5463 GROUP BY currency, contribution_status_id
5464 HAVING $havingClause
5470 * Assign Test Value.
5472 * @param string $fieldName
5473 * @param array $fieldDef
5474 * @param int $counter
5476 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5477 if ($fieldName == 'tax_amount') {
5478 $this->{$fieldName} = "0.00";
5480 elseif ($fieldName == 'net_amount') {
5481 $this->{$fieldName} = "2.00";
5483 elseif ($fieldName == 'total_amount') {
5484 $this->{$fieldName} = "3.00";
5486 elseif ($fieldName == 'fee_amount') {
5487 $this->{$fieldName} = "1.00";
5490 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5495 * Check if contribution has participant/membership payment.
5497 * @param int $contributionId
5502 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5503 // get line item for contribution
5504 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5505 // check if line item is for membership or participant
5506 foreach ($lineItems as $items) {
5507 if ($items['entity_table'] == 'civicrm_participant') {
5511 elseif ($items['entity_table'] == 'civicrm_membership') {
5523 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5525 * @param array $trxnParams
5526 * Financial trxn params
5527 * @param array $contributionParams
5528 * Contribution Params
5532 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5533 if (!Civi
::settings()->get('always_post_to_accounts_receivable')) {
5536 $statusId = $contributionParams['contribution']->contribution_status_id
;
5537 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5538 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5539 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5540 // Return if contribution status is not completed.
5541 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5542 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5543 && $contributionParams['prevContribution']->is_pay_later
== 0
5549 $params = $trxnParams;
5550 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $contributionParams) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5551 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5552 $params['to_financial_account_id'] = $arAccountId;
5553 $params['status_id'] = array_search('Pending', $contributionStatuses);
5554 $params['is_payment'] = FALSE;
5555 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5556 self
::$_trxnIDs[] = $trxn->id
;
5557 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5561 * Calculate financial item amount when contribution is updated.
5563 * @param array $params
5564 * contribution params
5565 * @param array $amountParams
5567 * @param string $context
5571 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5572 if (!empty($params['is_quick_config'])) {
5573 $amount = $amountParams['item_amount'];
5575 $amount = $params['total_amount'];
5576 if ($context === NULL) {
5577 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5582 $amount = $amountParams['line_total'];
5583 if ($context == 'changedAmount') {
5584 $amount -= $amountParams['previous_line_total'];
5586 $amount *= $amountParams['diff'];
5592 * Retrieve Sales Tax Financial Accounts.
5598 public static function getSalesTaxFinancialAccounts() {
5599 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5600 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5601 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5602 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5603 $queryParams = [1 => [$accountRel, 'Integer']];
5604 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5605 $financialAccount = [];
5606 while ($dao->fetch()) {
5607 $financialAccount[$dao->id
] = $dao->id
;
5609 return $financialAccount;
5613 * Create tax entry in civicrm_entity_financial_trxn table.
5615 * @param array $entityParams
5617 * @param array $eftParams
5619 * @throws \CiviCRM_API3_Exception
5621 public static function createProportionalEntry($entityParams, $eftParams) {
5623 if ($entityParams['contribution_total_amount'] != 0) {
5624 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5626 // Record Entity Financial Trxn; CRM-20145
5627 $eftParams['amount'] = CRM_Contribute_BAO_Contribution_Utils
::formatAmount($paid);
5628 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5632 * Create array of last financial item id's.
5634 * @param int $contributionId
5638 public static function getLastFinancialItemIds($contributionId) {
5639 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5640 FROM civicrm_financial_item fi
5641 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5642 WHERE li.contribution_id = %1";
5643 $dao = CRM_Core_DAO
::executeQuery($sql, [
5649 $ftIds = $taxItems = [];
5650 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5651 while ($dao->fetch()) {
5652 /* if sales tax item*/
5653 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5654 $taxItems[$dao->price_field_value_id
] = [
5655 'financial_item_id' => $dao->id
,
5656 'amount' => $dao->tax_amount
,
5660 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5663 return [$ftIds, $taxItems];
5667 * Create proportional entries in civicrm_entity_financial_trxn.
5669 * @param array $entityParams
5671 * @param array $lineItems
5673 * @param array $ftIds
5675 * @param array $taxItems
5677 * @throws \CiviCRM_API3_Exception
5679 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5681 'entity_table' => 'civicrm_financial_item',
5682 'financial_trxn_id' => $entityParams['trxn_id'],
5684 foreach ($lineItems as $key => $value) {
5685 if ($value['qty'] == 0) {
5688 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5689 $entityParams['line_item_amount'] = $value['line_total'];
5690 self
::createProportionalEntry($entityParams, $eftParams);
5691 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5692 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5693 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5694 self
::createProportionalEntry($entityParams, $eftParams);
5700 * Load entities related to the contribution into $this->_relatedObjects.
5704 * @throws \CRM_Core_Exception
5706 protected function loadRelatedEntitiesByID($ids) {
5708 'contact' => 'CRM_Contact_BAO_Contact',
5709 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5710 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5711 'financialType' => 'CRM_Financial_BAO_FinancialType',
5712 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5714 foreach ($entities as $entity => $bao) {
5715 if (!empty($ids[$entity])) {
5716 $this->_relatedObjects
[$entity] = new $bao();
5717 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5718 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5719 throw new CRM_Core_Exception($entity . ' could not be loaded');
5726 * Should an email receipt be sent for this contribution when complete.
5728 * @param array $input
5732 protected function isEmailReceipt($input) {
5733 if (isset($input['is_email_receipt'])) {
5734 return $input['is_email_receipt'];
5736 if (!empty($this->_relatedObjects
['contribution_page_id'])) {
5737 return $this->_relatedObjects
['contribution_page_id']->is_email_receipt
;
5743 * Function to replace contribution tokens.
5745 * @param array $contributionIds
5747 * @param string $subject
5749 * @param array $subjectToken
5751 * @param string $text
5753 * @param string $html
5755 * @param array $messageToken
5757 * @param bool $escapeSmarty
5760 * @throws \CiviCRM_API3_Exception
5762 public static function replaceContributionTokens(
5771 if (empty($contributionIds)) {
5774 $contributionDetails = [];
5775 foreach ($contributionIds as $id) {
5776 $result = self
::getContributionTokenValues($id, $messageToken);
5777 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5778 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5779 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5781 return $contributionDetails;
5785 * Get the contribution fields for $id and display labels where
5786 * appropriate (if the token is present).
5789 * @param array $messageToken
5792 public static function getContributionTokenValues($id, $messageToken) {
5796 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5797 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5798 if (!empty($messageToken)) {
5799 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5800 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5801 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField
::displayValue($result['values'][$id][$fieldName], $fieldName);
5809 * Get invoice_number for contribution.
5811 * @param int $contributionID
5815 public static function getInvoiceNumber($contributionID) {
5816 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix')) {
5817 return $invoicePrefix . $contributionID;
5824 * Load the values needed for the event message.
5826 * @param int $eventID
5827 * @param int $participantID
5828 * @param int|null $contributionID
5831 * @throws \CRM_Core_Exception
5833 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5838 $values = ['event' => []];
5840 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
5841 // add custom fields for event
5842 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $eventID);
5844 $eventCustomGroup = [];
5845 foreach ($eventGroupTree as $key => $group) {
5846 if ($key === 'info') {
5850 foreach ($group['fields'] as $k => $customField) {
5851 $groupLabel = $group['title'];
5852 if (!empty($customField['customValue'])) {
5853 foreach ($customField['customValue'] as $customFieldValues) {
5854 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
5859 $values['event']['customGroup'] = $eventCustomGroup;
5861 //get participant details
5862 $participantParams = [
5863 'id' => $participantID,
5866 $values['participant'] = [];
5868 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
5869 // add custom fields for event
5870 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $participantID);
5871 $participantCustomGroup = [];
5872 foreach ($participantGroupTree as $key => $group) {
5873 if ($key === 'info') {
5877 foreach ($group['fields'] as $k => $customField) {
5878 $groupLabel = $group['title'];
5879 if (!empty($customField['customValue'])) {
5880 foreach ($customField['customValue'] as $customFieldValues) {
5881 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
5886 $values['participant']['customGroup'] = $participantCustomGroup;
5888 //get location details
5890 'entity_id' => $eventID,
5891 'entity_table' => 'civicrm_event',
5893 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
5896 'entity_table' => 'civicrm_event',
5897 'entity_id' => $eventID,
5898 'module' => 'CiviEvent',
5901 list($custom_pre_id,
5903 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
5905 $values['custom_pre_id'] = $custom_pre_id;
5906 $values['custom_post_id'] = $custom_post_ids;
5908 // set lineItem for event contribution
5909 if ($contributionID) {
5910 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($contributionID);
5911 if (!empty($participantIds)) {
5912 foreach ($participantIds as $pIDs) {
5913 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
5914 if (!CRM_Utils_System
::isNull($lineItem)) {
5915 $values['lineItem'][] = $lineItem;