3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
33 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
36 * Static field for all the contribution information that we can potentially import
40 public static $_importableFields = NULL;
43 * Static field for all the contribution information that we can potentially export
47 public static $_exportableFields = NULL;
50 * Static field to hold financial trxn id's.
54 public static $_trxnIDs = NULL;
57 * Field for all the objects related to this contribution
59 * @var \CRM_Member_BAO_Membership|\CRM_Event_BAO_Participant[]
61 public $_relatedObjects = [];
64 * Field for the component - either 'event' (participant) or 'contribute'
65 * (any item related to a contribution page e.g. membership, pledge, contribution)
66 * This is used for composing messages because they have dependency on the
67 * contribution_page or event page - although over time we may eliminate that
69 * @var "contribution"\"event"
71 public $_component = NULL;
74 * Possibly obsolete variable.
76 * If you use it please explain why it is set in the create function here.
80 public $trxn_result_code;
85 public function __construct() {
86 parent
::__construct();
90 * Takes an associative array and creates a contribution object.
92 * the function extract all the params it needs to initialize the create a
93 * contribution object. the params array could contain additional unused name/value
96 * @param array $params
97 * (reference ) an assoc array of name/value pairs.
99 * The array that holds all the db ids.
101 * @return \CRM_Contribute_BAO_Contribution
102 * @throws \CRM_Core_Exception
103 * @throws \CiviCRM_API3_Exception
105 public static function add(&$params, $ids = []) {
106 if (empty($params)) {
109 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
110 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
112 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
113 $message = ts("Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: %1", [1 => implode(', ', $duplicates)]);
114 throw new CRM_Core_Exception($message);
117 // first clean up all the money fields
122 'non_deductible_amount',
125 //if priceset is used, no need to cleanup money
126 if (!empty($params['skipCleanMoney'])) {
130 // @todo put a deprecated here - this should be done in the form layer.
131 $params['skipCleanMoney'] = FALSE;
132 Civi
::log()->warning('Deprecated code path. Money should always be clean before it hits the BAO.', array('civi.tag' => 'deprecated'));
135 foreach ($moneyFields as $field) {
136 if (isset($params[$field])) {
137 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
141 //set defaults in create mode
142 if (!$contributionID) {
143 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
145 if (empty($params['invoice_number'])) {
146 $nextContributionID = CRM_Core_DAO
::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
147 $params['invoice_number'] = self
::getInvoiceNumber($nextContributionID);
151 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
152 //if contribution is created with cancelled or refunded status, add credit note id
153 if (!empty($params['contribution_status_id'])) {
154 // @todo - should we include Chargeback? If so use self::isContributionStatusNegative($params['contribution_status_id'])
155 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
156 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
158 if (empty($params['creditnote_id'])) {
159 $params['creditnote_id'] = self
::createCreditNoteId();
164 // Since the fee amount is expecting this (later on) ensure it is always set.
165 // It would only not be set for an update where it is unchanged.
166 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', [
167 'id' => $contributionID,
168 'return' => 'contribution_status_id',
173 && CRM_Utils_Array
::value('membership_id', $params)
174 && Civi
::settings()->get('deferred_revenue_enabled')
176 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
177 if ($memberStartDate) {
178 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
181 self
::calculateMissingAmountParams($params, $contributionID);
183 if (!empty($params['payment_instrument_id'])) {
184 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
185 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
186 $params['check_number'] = 'null';
190 $setPrevContribution = TRUE;
191 // CRM-13964 partial payment
192 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])) {
193 $partialAmtTotal = $params['partial_payment_total'];
194 $partialAmtPay = $params['partial_amount_to_pay'];
195 $params['total_amount'] = $partialAmtTotal;
196 if ($partialAmtPay < $partialAmtTotal) {
197 $params['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Partially paid');
198 $params['is_pay_later'] = 0;
199 $setPrevContribution = FALSE;
202 if ($contributionID && $setPrevContribution) {
203 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
206 if ($contributionID && !empty($params['revenue_recognition_date']) && !empty($params['prevContribution'])
207 && !($contributionStatus[$params['prevContribution']->contribution_status_id
] == 'Pending')
208 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
210 unset($params['revenue_recognition_date']);
213 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
214 isset($params['financial_type_id']))) {
215 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
218 if ($contributionID) {
219 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
222 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
224 $contribution = new CRM_Contribute_BAO_Contribution();
225 $contribution->copyValues($params);
227 $contribution->id
= $contributionID;
229 if (empty($contribution->id
)) {
230 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
231 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
232 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
236 $result = $contribution->save();
238 // Add financial_trxn details as part of fix for CRM-4724
239 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
240 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
242 //add Account details
243 $params['contribution'] = $contribution;
244 if (empty($params['is_post_payment_create'])) {
245 // If this is being called from the Payment.create api/ BAO then that Entity
246 // takes responsibility for the financial transactions. In fact calling Payment.create
247 // to add payments & having it call completetransaction and / or contribution.create
248 // to update related entities is the preferred flow.
249 // Note that leveraging this parameter for any other code flow is not supported and
250 // is likely to break in future and / or cause serious problems in your data.
251 // https://github.com/civicrm/civicrm-core/pull/14673
252 self
::recordFinancialAccounts($params);
255 if (self
::isUpdateToRecurringContribution($params)) {
256 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
257 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
258 $contributionStatus[$params['contribution_status_id']],
259 CRM_Utils_Array
::value('receive_date', $params)
263 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
265 if ($contributionID) {
266 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
269 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
276 * Is this contribution updating an existing recurring contribution.
278 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
279 * pending payment is being confirmed (or failing).
281 * @param array $params
285 public static function isUpdateToRecurringContribution($params) {
286 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
289 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
292 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
295 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
296 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
303 * Get defaults for new entity.
307 public static function getDefaults() {
309 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
310 FALSE, FALSE, FALSE, 'AND is_default = 1')
312 'contribution_status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
313 'receive_date' => date('Y-m-d H:i:s'),
318 * Fetch the object and store the values in the values array.
320 * @param array $params
321 * Input parameters to find object.
322 * @param array $values
323 * Output values of the object.
325 * The array that holds all the db ids.
327 * @return CRM_Contribute_BAO_Contribution|null
328 * The found object or null
330 public static function getValues($params, &$values = [], &$ids = []) {
331 if (empty($params)) {
334 $contribution = new CRM_Contribute_BAO_Contribution();
336 $contribution->copyValues($params);
338 if ($contribution->find(TRUE)) {
339 $ids['contribution'] = $contribution->id
;
341 CRM_Core_DAO
::storeValues($contribution, $values);
343 return $contribution;
345 // return by reference
351 * Get the values and resolve the most common mappings.
353 * Since contribution status is resolved in almost every function that calls getValues it makes
354 * sense to have an extra function to resolve it rather than repeat the code.
356 * Think carefully before adding more mappings to be resolved as there could be performance implications
357 * if this function starts to be called from more iterative functions.
359 * @param array $params
360 * Input parameters to find object.
363 * Array of the found contribution.
364 * @throws CRM_Core_Exception
366 public static function getValuesWithMappings($params) {
368 $contribution = self
::getValues($params, $values, $ids);
369 if (is_null($contribution)) {
370 throw new CRM_Core_Exception('No contribution found');
372 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
377 * Calculate net_amount & fee_amount if they are not set.
379 * Net amount should be total - fee.
380 * This should only be called for new contributions.
382 * @param array $params
383 * Params for a new contribution before they are saved.
384 * @param int|null $contributionID
385 * Contribution ID if we are dealing with an update.
387 * @throws \CiviCRM_API3_Exception
389 public static function calculateMissingAmountParams(&$params, $contributionID) {
390 if (!$contributionID && !isset($params['fee_amount'])) {
391 if (isset($params['total_amount']) && isset($params['net_amount'])) {
392 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
395 $params['fee_amount'] = 0;
398 if (!isset($params['net_amount'])) {
399 if (!$contributionID) {
400 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
403 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
404 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
405 // net_amount may need adjusting.
406 $contribution = civicrm_api3('Contribution', 'getsingle', [
407 'id' => $contributionID,
408 'return' => ['total_amount', 'net_amount', 'fee_amount'],
410 $totalAmount = (isset($params['total_amount']) ?
(float) $params['total_amount'] : (float) CRM_Utils_Array
::value('total_amount', $contribution));
411 $feeAmount = (isset($params['fee_amount']) ?
(float) $params['fee_amount'] : (float) CRM_Utils_Array
::value('fee_amount', $contribution));
412 $params['net_amount'] = $totalAmount - $feeAmount;
420 * @param $billingLocationTypeID
424 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
425 $hasBillingField = FALSE;
434 //build address array
436 $addressParams['location_type_id'] = $billingLocationTypeID;
437 $addressParams['is_billing'] = 1;
439 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
440 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
441 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
442 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
444 foreach ($billingFields as $value) {
445 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
446 if (!empty($addressParams[$value])) {
447 $hasBillingField = TRUE;
450 return [$hasBillingField, $addressParams];
454 * Get address params ready to be passed to the payment processor.
456 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
457 * To create an address we need state_province_id.
459 * @param array $params
460 * @param int $billingLocationTypeID
464 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
465 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
466 foreach ($addressParams as $name => $field) {
467 if (substr($name, 0, 8) == 'billing_') {
468 $addressParams[substr($name, 9)] = $addressParams[$field];
471 return [$hasBillingField, $addressParams];
475 * Get the number of terms for this contribution for a given membership type
476 * based on querying the line item table and relevant price field values
477 * Note that any one contribution should only be able to have one line item relating to a particular membership
480 * @param int $membershipTypeID
482 * @param int $contributionID
486 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
487 $numTerms = CRM_Core_DAO
::singleValueQuery("
488 SELECT membership_num_terms FROM civicrm_line_item li
489 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
490 WHERE contribution_id = %1 AND membership_type_id = %2",
491 [1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']]
493 // default of 1 is precautionary
494 return empty($numTerms) ?
1 : $numTerms;
498 * Takes an associative array and creates a contribution object.
500 * @param array $params
501 * (reference ) an assoc array of name/value pairs.
503 * The array that holds all the db ids.
505 * @return CRM_Contribute_BAO_Contribution
507 public static function create(&$params, $ids = []) {
508 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
509 $action = $contributionID ?
'edit' : 'create';
516 'revenue_recognition_date',
518 foreach ($dateFields as $df) {
519 if (isset($params[$df])) {
520 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
524 $transaction = new CRM_Core_Transaction();
527 $contribution = self
::add($params, $ids);
529 catch (CRM_Core_Exception
$e) {
530 $transaction->rollback();
534 $params['contribution_id'] = $contribution->id
;
536 if (!empty($params['custom']) &&
537 is_array($params['custom'])
539 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
, $action);
542 $session = CRM_Core_Session
::singleton();
544 if (!empty($params['note'])) {
546 'entity_table' => 'civicrm_contribution',
547 'note' => $params['note'],
548 'entity_id' => $contribution->id
,
549 'contact_id' => $session->get('userID'),
550 'modified_date' => date('Ymd'),
552 if (!$noteParams['contact_id']) {
553 $noteParams['contact_id'] = $params['contact_id'];
555 CRM_Core_BAO_Note
::add($noteParams);
558 // make entry in batch entity batch table
559 if (!empty($params['batch_id'])) {
560 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
567 $retrieveRequired = 0;
568 foreach ($titleFields as $titleField) {
569 if (!isset($contribution->$titleField)) {
570 $retrieveRequired = 1;
574 if ($retrieveRequired == 1) {
575 $contribution->find(TRUE);
579 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
581 $transaction->commit();
583 $activity = civicrm_api3('Activity', 'get', [
584 'source_record_id' => $contribution->id
,
585 'options' => ['limit' => 1],
587 'activity_type_id' => 'Contribution',
588 'return' => ['id', 'campaign'],
591 //CRM-18406: Update activity when edit contribution.
592 if ($activity['count']) {
593 // CRM-13237 : if activity record found, update it with campaign id of contribution
594 // @todo compare campaign ids first.
595 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity['id'], 'campaign_id', $contribution->campaign_id
);
596 $contribution->activity_id
= $activity['id'];
599 if (empty($contribution->contact_id
)) {
600 $contribution->find(TRUE);
602 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution');
604 // do not add to recent items for import, CRM-4399
605 if (empty($params['skipRecentView'])) {
606 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
607 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
609 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
616 $retrieveRequired = 0;
617 foreach ($titleFields as $titleField) {
618 if (!isset($contribution->$titleField)) {
619 $retrieveRequired = 1;
623 if ($retrieveRequired == 1) {
624 $contribution->find(TRUE);
626 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
627 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
630 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
631 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
632 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
636 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
637 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
638 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
642 // add the recently created Contribution
643 CRM_Utils_Recent
::add($title,
647 $contribution->contact_id
,
653 return $contribution;
657 * Get the values for pseudoconstants for name->value and reverse.
659 * @param array $defaults
660 * (reference) the default values, some of which need to be resolved.
661 * @param bool $reverse
662 * True if we want to resolve the values in the reverse direction (value -> name).
664 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
665 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
666 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
667 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'), $reverse);
668 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
672 * Convert associative array names to values and vice-versa.
674 * This function is used by both the web form layer and the api. Note that
675 * the api needs the name => value conversion, also the view layer typically
676 * requires value => name conversion
678 * @param array $defaults
679 * @param string $property
680 * @param array $lookup
681 * @param bool $reverse
685 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
686 $id = $property . '_id';
688 $src = $reverse ?
$property : $id;
689 $dst = $reverse ?
$id : $property;
691 if (!array_key_exists($src, $defaults)) {
695 $look = $reverse ?
array_flip($lookup) : $lookup;
697 if (is_array($look)) {
698 if (!array_key_exists($defaults[$src], $look)) {
702 $defaults[$dst] = $look[$defaults[$src]];
707 * Retrieve DB object based on input parameters.
709 * It also stores all the retrieved values in the default array.
711 * @param array $params
712 * (reference ) an assoc array of name/value pairs.
713 * @param array $defaults
714 * (reference ) an assoc array to hold the name / value pairs.
715 * in a hierarchical manner
717 * (reference) the array that holds all the db ids.
719 * @return CRM_Contribute_BAO_Contribution
721 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
722 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
723 return $contribution;
727 * Combine all the importable fields from the lower levels object.
729 * The ordering is important, since currently we do not have a weight
730 * scheme. Adding weight is super important and should be done in the
731 * next week or so, before this can be called complete.
733 * @param string $contactType
734 * @param bool $status
737 * array of importable Fields
739 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
740 if (!self
::$_importableFields) {
741 if (!self
::$_importableFields) {
742 self
::$_importableFields = [];
746 $fields = ['' => ['title' => ts('- do not import -')]];
749 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
752 $note = CRM_Core_DAO_Note
::import();
753 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
754 unset($tmpFields['option_value']);
755 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
756 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
758 // Using new Dedupe rule.
760 'contact_type' => $contactType,
761 'used' => 'Unsupervised',
763 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
764 $tmpContactField = [];
765 if (is_array($fieldsArray)) {
766 foreach ($fieldsArray as $value) {
767 //skip if there is no dupe rule
768 if ($value == 'none') {
771 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
776 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
777 $tmpContactField[trim($value)] = $contactFields[trim($value)];
779 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
782 $title = $tmpContactField[trim($value)]['title'];
784 $tmpContactField[trim($value)]['title'] = $title;
788 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
789 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
790 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
791 $fields = array_merge($fields, $tmpContactField);
792 $fields = array_merge($fields, $tmpFields);
793 $fields = array_merge($fields, $note);
794 $fields = array_merge($fields, $optionFields);
795 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
796 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
797 self
::$_importableFields = $fields;
799 return self
::$_importableFields;
803 * Combine all the exportable fields from the lower level objects.
805 * @param bool $checkPermission
808 * array of exportable Fields
810 public static function &exportableFields($checkPermission = TRUE) {
811 if (!self
::$_exportableFields) {
812 if (!self
::$_exportableFields) {
813 self
::$_exportableFields = [];
816 $fields = CRM_Contribute_DAO_Contribution
::export();
817 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
818 $fields = array_merge(
820 CRM_Contribute_DAO_Product
::export(),
821 CRM_Contribute_DAO_ContributionProduct
::export(),
822 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
824 'contribution_product_id' => [
825 'title' => ts('Premium'),
826 'name' => 'contribution_product_id',
827 'where' => 'civicrm_product.id',
828 'data_type' => CRM_Utils_Type
::T_INT
,
834 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
836 $contributionPage = [
837 'contribution_page' => [
838 'title' => ts('Contribution Page'),
839 'name' => 'contribution_page',
840 'where' => 'civicrm_contribution_page.title',
841 'data_type' => CRM_Utils_Type
::T_STRING
,
845 $contributionNote = [
846 'contribution_note' => [
847 'title' => ts('Contribution Note'),
848 'name' => 'contribution_note',
849 'data_type' => CRM_Utils_Type
::T_TEXT
,
854 'contribution_batch' => [
855 'title' => ts('Batch Name'),
861 'contribution_campaign_title' => [
862 'title' => ts('Campaign Title'),
863 'name' => 'campaign_title',
864 'where' => 'civicrm_campaign.title',
865 'data_type' => CRM_Utils_Type
::T_STRING
,
868 $softCreditFields = [
869 'contribution_soft_credit_name' => [
870 'name' => 'contribution_soft_credit_name',
871 'title' => ts('Soft Credit For'),
872 'where' => 'civicrm_contact_d.display_name',
873 'data_type' => CRM_Utils_Type
::T_STRING
,
875 'contribution_soft_credit_amount' => [
876 'name' => 'contribution_soft_credit_amount',
877 'title' => ts('Soft Credit Amount'),
878 'where' => 'civicrm_contribution_soft.amount',
879 'data_type' => CRM_Utils_Type
::T_MONEY
,
881 'contribution_soft_credit_type' => [
882 'name' => 'contribution_soft_credit_type',
883 'title' => ts('Soft Credit Type'),
884 'where' => 'contribution_softcredit_type.label',
885 'data_type' => CRM_Utils_Type
::T_STRING
,
887 'contribution_soft_credit_contribution_id' => [
888 'name' => 'contribution_soft_credit_contribution_id',
889 'title' => ts('Soft Credit For Contribution ID'),
890 'where' => 'civicrm_contribution_soft.contribution_id',
891 'data_type' => CRM_Utils_Type
::T_INT
,
893 'contribution_soft_credit_contact_id' => [
894 'name' => 'contribution_soft_credit_contact_id',
895 'title' => ts('Soft Credit For Contact ID'),
896 'where' => 'civicrm_contact_d.id',
897 'data_type' => CRM_Utils_Type
::T_INT
,
901 $fields = array_merge($fields, $contributionPage,
902 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
903 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
906 self
::$_exportableFields = $fields;
909 return self
::$_exportableFields;
913 * Record an activity when a payment is received.
915 * @todo this is intended to be moved to payment BAO class as a protected function
916 * on that class. Currently being cleaned up. The addActivityForPayment doesn't really
917 * merit it's own function as it makes the code less rather than more readable.
919 * @param int $contributionId
920 * @param int $participantId
921 * @param string $totalAmount
922 * @param string $currency
923 * @param string $trxnDate
925 * @throws \CRM_Core_Exception
926 * @throws \CiviCRM_API3_Exception
928 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
929 $activityType = ($totalAmount < 0) ?
'Refund' : 'Payment';
931 if ($participantId) {
932 $inputParams['id'] = $participantId;
935 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
936 $entityObj = $entityObj[$participantId];
937 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
940 $entityObj = new CRM_Contribute_BAO_Contribution();
941 $entityObj->id
= $contributionId;
942 $entityObj->find(TRUE);
943 $title = ts('Contribution');
945 // @todo per block above this is not a logical splitting off of functionality.
946 self
::addActivityForPayment($entityObj->contact_id
, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
950 * Get the value for the To Financial Account.
952 * @param $contribution
957 public static function getToFinancialAccount($contribution, $params) {
958 if (!empty($params['payment_processor'])) {
959 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contribution['payment_processor'], NULL, 'civicrm_payment_processor');
961 if (!empty($params['payment_instrument_id'])) {
962 return CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
965 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
966 $queryParams = [1 => [$relationTypeId, 'Integer']];
967 return CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
972 * Get memberships realted to the contribution.
974 * @param int $contributionID
978 protected static function getRelatedMemberships($contributionID) {
979 $membershipPayments = civicrm_api3('MembershipPayment', 'get', [
980 'return' => 'membership_id',
981 'contribution_id' => (int) $contributionID,
984 foreach ($membershipPayments as $membershipPayment) {
985 $membershipIDs[] = $membershipPayment['membership_id'];
987 if (empty($membershipIDs)) {
990 // We could combine this with the MembershipPayment.get - we'd
991 // need to re-wrangle the params (here or in the calling function)
992 // as they would then me membership.contact_id, membership.is_test etc
993 return civicrm_api3('Membership', 'get', [
994 'id' => ['IN' => $membershipIDs],
995 'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'],
1000 * Cancel contribution.
1002 * This function should only be called from transitioncomponents - it is an interim step in refactoring.
1004 * @param $processContributionObject
1005 * @param $memberships
1006 * @param $contributionId
1007 * @param $membershipStatuses
1008 * @param $updateResult
1009 * @param $participant
1011 * @param $pledgePayment
1013 * @param $pledgePaymentIDs
1014 * @param $contributionStatusId
1018 protected static function cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId) {
1019 // @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
1020 $processContribution = FALSE;
1021 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1022 if (is_array($memberships)) {
1023 foreach ($memberships as $membership) {
1025 //Update Membership status if there is no other completed contribution associated with the membership.
1026 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1027 foreach ($relatedContributions as $contriId) {
1028 if ($contriId == $contributionId) {
1031 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1032 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1036 if ($membership && $update) {
1037 $newStatus = array_search('Cancelled', $membershipStatuses);
1040 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1042 'subject' => "Status changed from {$allStatus[$membership->status_id]} to {$allStatus[$newStatus]}",
1043 'source_contact_id' => CRM_Core_Session
::singleton()->get('userID'),
1044 'target_contact_id' => $membership->contact_id
,
1045 'source_record_id' => $membership->id
,
1046 'activity_type_id' => 'Change Membership Status',
1047 'status_id' => 'Completed',
1048 'priority_id' => 'Normal',
1049 'activity_date_time' => 'now',
1052 $membership->status_id
= $newStatus;
1053 $membership->is_override
= TRUE;
1054 $membership->status_override_end_date
= 'null';
1055 $membership->save();
1056 civicrm_api3('activity', 'create', $activityParam);
1058 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1059 if ($processContributionObject) {
1060 $processContribution = TRUE;
1067 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1068 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1070 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1071 if ($processContributionObject) {
1072 $processContribution = TRUE;
1076 if ($pledgePayment) {
1077 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1079 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1080 if ($processContributionObject) {
1081 $processContribution = TRUE;
1084 return [$updateResult, $processContribution];
1088 * Do any accounting updates required as a result of a contribution status change.
1090 * Currently we have a bit of a roundabout where adding a payment results in this being called &
1091 * this may attempt to add a payment. We need to resolve that....
1093 * The 'right' way to add payments or refunds is through the Payment.create api. That api
1094 * then updates the contribution but this process should not also record another financial trxn.
1095 * Currently we have weak detection fot that scenario & where it is detected the first returned
1096 * value is FALSE - meaning 'do not continue'.
1098 * We should also look at the fact that the calling function - updateFinancialAccounts
1099 * bunches together some disparate processes rather than having separate appropriate
1102 * @param array $params
1105 * Return indicates whether the updateFinancialAccounts function should continue & whether this is a refund.
1107 private static function updateFinancialAccountsOnContributionStatusChange(&$params) {
1108 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
1109 $currentContributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
1112 if ((($previousContributionStatus == 'Partially paid' && $currentContributionStatus == 'Completed')
1113 ||
($previousContributionStatus == 'Pending refund' && $currentContributionStatus == 'Completed')
1114 // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
1115 // why it is here or where it is handled instead.
1116 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
1117 && $currentContributionStatus == 'Partially paid'))
1119 return [FALSE, $isARefund];
1122 if ($previousContributionStatus == 'Completed'
1123 && (self
::isContributionStatusNegative($params['contribution']->contribution_status_id
))
1126 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1127 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1128 if (empty($params['contribution']->creditnote_id
)) {
1129 $creditNoteId = self
::createCreditNoteId();
1130 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
1133 elseif (($previousContributionStatus == 'Pending'
1134 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
1136 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
1137 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
1139 if ($currentContributionStatus == 'Cancelled') {
1140 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1141 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
1142 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1143 if (empty($params['contribution']->creditnote_id
)) {
1144 $creditNoteId = self
::createCreditNoteId();
1145 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
1149 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1150 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
1154 if (($previousContributionStatus == 'Pending'
1155 ||
$previousContributionStatus == 'In Progress')
1156 && ($currentContributionStatus == 'Completed')
1158 if (empty($params['line_item'])) {
1160 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
1161 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
1162 // & this can be removed
1163 return [FALSE, $isARefund];
1165 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1166 // This is an update so original currency if none passed in.
1167 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
1169 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
1170 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
1171 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1172 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
1173 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
1174 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
1177 'entity_table' => 'civicrm_financial_item',
1179 foreach ($params['line_item'] as $fieldId => $fields) {
1180 foreach ($fields as $fieldValueId => $lineItemDetails) {
1183 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1186 2 => [$lineItemDetails['id'], 'Integer'],
1188 CRM_Core_DAO
::executeQuery($query, $fparams);
1190 1 => [$lineItemDetails['id'], 'Integer'],
1192 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
1193 while ($financialItem->fetch()) {
1194 $entityParams['entity_id'] = $financialItem->id
;
1195 $entityParams['amount'] = $financialItem->amount
;
1196 foreach (self
::$_trxnIDs as $tID) {
1197 $entityParams['financial_trxn_id'] = $tID;
1198 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
1203 return [FALSE, $isARefund];
1205 return [TRUE, $isARefund];
1209 * It is possible to override the membership id that is updated from the payment processor.
1211 * Historically Paypal does this & it still does if it determines data is messed up - see
1212 * https://lab.civicrm.org/dev/membership/issues/13
1214 * Read the comment block on repeattransaction for more information
1215 * about how things should work.
1217 * @param int $contributionID
1218 * @param array $input
1220 * @throws \CiviCRM_API3_Exception
1222 protected static function handleMembershipIDOverride($contributionID, $input) {
1223 if (!empty($input['membership_id'])) {
1224 Civi
::log()->debug('The related membership id has been overridden - this may impact data - see https://github.com/civicrm/civicrm-core/pull/15053');
1225 civicrm_api3('MembershipPayment', 'create', ['contribution_id' => $contributionID, 'membership_id' => $input['membership_id']]);
1232 public function addSelectWhereClause() {
1233 $whereClauses = parent
::addSelectWhereClause();
1234 if ($whereClauses !== []) {
1235 // In this case permisssions have been applied & we assume the
1236 // financialaclreport is applying these
1237 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
1238 return $whereClauses;
1241 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1242 return $whereClauses;
1244 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
1245 if (empty($types)) {
1246 $whereClauses['financial_type_id'] = 'IN (0)';
1249 $whereClauses['financial_type_id'] = [
1250 'IN (' . implode(',', array_keys($types)) . ')',
1253 return $whereClauses;
1257 * @param null $status
1258 * @param null $startDate
1259 * @param null $endDate
1261 * @return array|null
1263 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1267 $where[] = 'contribution_status_id = 1';
1271 $where[] = 'contribution_status_id = 3';
1276 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
1279 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
1281 $financialTypeACLJoin = '';
1282 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1283 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1284 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
1285 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1286 if ($financialTypes) {
1287 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1288 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1291 $where[] = "c.financial_type_id IN (0)";
1295 $whereCond = implode(' AND ', $where);
1298 SELECT sum( total_amount ) as total_amount,
1299 count( c.id ) as total_count,
1301 FROM civicrm_contribution c
1302 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1303 $financialTypeACLJoin
1305 AND ( is_test = 0 OR is_test IS NULL )
1306 AND contact.is_deleted = 0
1310 $dao = CRM_Core_DAO
::executeQuery($query);
1313 while ($dao->fetch()) {
1314 $count +
= $dao->total_count
;
1315 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
1319 'amount' => implode(', ', $amount),
1327 * Delete the indirect records associated with this contribution first.
1331 * @return mixed|null
1332 * $results no of deleted Contribution on success, false otherwise
1334 public static function deleteContribution($id) {
1335 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
1337 $transaction = new CRM_Core_Transaction();
1340 //delete activity record
1342 'source_record_id' => $id,
1343 // activity type id for contribution
1344 'activity_type_id' => 6,
1347 CRM_Activity_BAO_Activity
::deleteActivity($params);
1349 //delete billing address if exists for this contribution.
1350 self
::deleteAddress($id);
1352 //update pledge and pledge payment, CRM-3961
1353 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1355 // remove entry from civicrm_price_set_entity, CRM-5095
1356 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1357 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1359 // cleanup line items.
1360 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1362 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1363 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1365 if ($participantId) {
1366 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1369 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1373 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1374 $noteId = key($note);
1376 CRM_Core_BAO_Note
::del($noteId, FALSE);
1379 $dao = new CRM_Contribute_DAO_Contribution();
1382 $results = $dao->delete();
1384 $transaction->commit();
1386 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1388 // delete the recently created Contribution
1389 $contributionRecent = [
1391 'type' => 'Contribution',
1393 CRM_Utils_Recent
::del($contributionRecent);
1399 * React to a financial transaction (payment) failure.
1401 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1402 * payments is important for forensic and outreach reasons.
1404 * @param int $contributionID
1405 * @param int $contactID
1406 * @param string $message
1408 * @throws \CiviCRM_API3_Exception
1410 public static function failPayment($contributionID, $contactID, $message) {
1411 civicrm_api3('activity', 'create', [
1412 'activity_type_id' => 'Failed Payment',
1413 'details' => $message,
1414 'subject' => ts('Payment failed at payment processor'),
1415 'source_record_id' => $contributionID,
1416 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() : $contactID,
1419 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1420 civicrm_api3('contribution', 'create', [
1421 'id' => $contributionID,
1422 'contribution_status_id' => 'Failed',
1427 * Check if there is a contribution with the same trxn_id or invoice_id.
1429 * @param array $input
1430 * An assoc array of name/value pairs.
1431 * @param array $duplicates
1432 * (reference) store ids of duplicate contribs.
1436 * true if duplicate, false otherwise
1438 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1440 $id = CRM_Utils_Array
::value('id', $input);
1442 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1443 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1449 $clause[] = "trxn_id = %1";
1450 $input[1] = [$trxn_id, 'String'];
1454 $clause[] = "invoice_id = %2";
1455 $input[2] = [$invoice_id, 'String'];
1458 if (empty($clause)) {
1462 $clause = implode(' OR ', $clause);
1464 $clause = "( $clause ) AND id != %3";
1465 $input[3] = [$id, 'Integer'];
1468 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1469 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1471 while ($dao->fetch()) {
1472 $duplicates[] = $dao->id
;
1479 * Takes an associative array and creates a contribution_product object.
1481 * the function extract all the params it needs to initialize the create a
1482 * contribution_product object. the params array could contain additional unused name/value
1485 * @param array $params
1486 * (reference) an assoc array of name/value pairs.
1488 * @return CRM_Contribute_DAO_ContributionProduct
1490 public static function addPremium(&$params) {
1491 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1492 $contributionProduct->copyValues($params);
1493 return $contributionProduct->save();
1497 * Get list of contribution fields for profile.
1498 * For now we only allow custom contribution fields to be in
1501 * @param bool $addExtraFields
1502 * True if special fields needs to be added.
1505 * the list of contribution fields
1507 public static function getContributionFields($addExtraFields = TRUE) {
1508 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1509 // @todo remove this - this line was added because payment_instrument_id was not
1510 // set to exportable - but now it is.
1511 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1513 if ($addExtraFields) {
1514 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1517 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1519 foreach ($contributionFields as $key => $var) {
1520 if ($key == 'contribution_contact_id') {
1523 elseif ($key == 'contribution_campaign_id') {
1524 $var['title'] = ts('Campaign');
1526 $fields[$key] = $var;
1529 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1534 * Add extra fields specific to contribution.
1536 public static function getSpecialContributionFields() {
1538 'contribution_soft_credit_name' => [
1539 'name' => 'contribution_soft_credit_name',
1540 'title' => ts('Soft Credit Name'),
1541 'headerPattern' => '/^soft_credit_name$/i',
1542 'where' => 'civicrm_contact_d.display_name',
1544 'contribution_soft_credit_email' => [
1545 'name' => 'contribution_soft_credit_email',
1546 'title' => ts('Soft Credit Email'),
1547 'headerPattern' => '/^soft_credit_email$/i',
1548 'where' => 'soft_email.email',
1550 'contribution_soft_credit_phone' => [
1551 'name' => 'contribution_soft_credit_phone',
1552 'title' => ts('Soft Credit Phone'),
1553 'headerPattern' => '/^soft_credit_phone$/i',
1554 'where' => 'soft_phone.phone',
1556 'contribution_soft_credit_contact_id' => [
1557 'name' => 'contribution_soft_credit_contact_id',
1558 'title' => ts('Soft Credit Contact ID'),
1559 'headerPattern' => '/^soft_credit_contact_id$/i',
1560 'where' => 'civicrm_contribution_soft.contact_id',
1562 'contribution_pcp_title' => [
1563 'name' => 'contribution_pcp_title',
1564 'title' => ts('Personal Campaign Page Title'),
1565 'headerPattern' => '/^contribution_pcp_title$/i',
1566 'where' => 'contribution_pcp.title',
1570 return $extraFields;
1574 * @param int $pageID
1578 public static function getCurrentandGoalAmount($pageID) {
1580 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1581 FROM civicrm_contribution_page p,
1582 civicrm_contribution c
1583 WHERE p.id = c.contribution_page_id
1585 AND c.cancel_date is null
1589 $config = CRM_Core_Config
::singleton();
1590 $params = [1 => [$pageID, 'Integer']];
1591 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1593 if ($dao->fetch()) {
1594 return [$dao->goal
, $dao->total
];
1597 return [NULL, NULL];
1602 * Get list of contributions which credit the passed in contact ID.
1604 * The returned array provides details about the original contribution & donor.
1606 * @param int $honorId
1607 * In Honor of Contact ID.
1610 * list of contribution fields
1611 * @todo - this is a confusing function called from one place. It has a test. It would be
1612 * nice to deprecate it.
1615 public static function getHonorContacts($honorId) {
1617 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1618 $honorDAO->contact_id
= $honorId;
1621 $type = CRM_Contribute_PseudoConstant
::financialType();
1623 while ($honorDAO->fetch()) {
1624 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1625 $contributionDAO->id
= $honorDAO->contribution_id
;
1627 if ($contributionDAO->find(TRUE)) {
1628 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1629 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1630 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1631 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1632 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1633 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1634 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1635 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1636 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
, 'label');
1644 * Get the sort name of a contact for a particular contribution.
1647 * Id of the contribution.
1649 * @return null|string
1650 * sort name of the contact if found
1652 public static function sortName($id) {
1653 $id = CRM_Utils_Type
::escape($id, 'Integer');
1656 SELECT civicrm_contact.sort_name
1657 FROM civicrm_contribution, civicrm_contact
1658 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1659 AND civicrm_contribution.id = {$id}
1661 return CRM_Core_DAO
::singleValueQuery($query);
1665 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1667 * @param int|array $contactIDs
1671 public static function annual($contactIDs) {
1672 if (!is_array($contactIDs)) {
1673 // In practice I can't fine any evidence that this function is ever called with
1674 // anything other than a single contact id, but left like this due to .... fear.
1675 $contactIDs = explode(',', $contactIDs);
1678 $query = self
::getAnnualQuery($contactIDs);
1679 $dao = CRM_Core_DAO
::executeQuery($query);
1681 $amount = $average = [];
1682 while ($dao->fetch()) {
1683 if ($dao->count
> 0 && $dao->amount
> 0) {
1684 $count +
= $dao->count
;
1685 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1686 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1692 implode(', ', $amount),
1693 implode(', ', $average),
1700 * Check if there is a contribution with the params passed in.
1702 * Used for trxn_id,invoice_id and contribution_id
1704 * @param array $params
1705 * An assoc array of name/value pairs.
1708 * contribution id if success else NULL
1710 public static function checkDuplicateIds($params) {
1711 $dao = new CRM_Contribute_DAO_Contribution();
1715 foreach ($params as $k => $v) {
1717 $clause[] = "$k = '$v'";
1720 $clause = implode(' AND ', $clause);
1721 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1722 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1724 while ($dao->fetch()) {
1732 * Get the contribution details for component export.
1734 * @param int $exportMode
1736 * @param array $componentIds
1742 public static function getContributionDetails($exportMode, $componentIds) {
1743 $paymentDetails = [];
1744 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1746 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1747 $componentSelect = " civicrm_participant_payment.participant_id id";
1748 $additionalClause = "
1749 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1750 AND civicrm_participant_payment.participant_id {$componentClause} )
1753 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1754 $componentSelect = " civicrm_membership_payment.membership_id id";
1755 $additionalClause = "
1756 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1757 AND civicrm_membership_payment.membership_id {$componentClause} )
1760 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1761 $componentSelect = " civicrm_pledge_payment.id id";
1762 $additionalClause = "
1763 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1764 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1768 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1769 trxn_id, {$componentSelect}
1770 FROM civicrm_contribution
1771 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1772 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1773 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1774 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1775 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1776 AND option_group_contribution_status.id = contribution_status.option_group_id )
1780 $dao = CRM_Core_DAO
::executeQuery($query);
1782 while ($dao->fetch()) {
1783 $paymentDetails[$dao->id
] = [
1784 'total_amount' => $dao->total_amount
,
1785 'contribution_status' => $dao->status
,
1786 'receive_date' => $dao->receive_date
,
1787 'pay_instru' => $dao->payment_instrument
,
1788 'trxn_id' => $dao->trxn_id
,
1792 return $paymentDetails;
1796 * Create address associated with contribution record.
1798 * As long as there is one or more billing field in the parameters we will create the address.
1800 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1803 * @param array $params
1804 * @param int $billingLocationTypeID
1809 public static function createAddress($params, $billingLocationTypeID) {
1810 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1811 if ($hasBillingField) {
1812 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1813 return $address->id
;
1820 * Delete billing address record related contribution.
1822 * @param int $contributionId
1823 * @param int $contactId
1825 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1827 $contactJoin = NULL;
1829 if ($contributionId) {
1830 $clauses[] = "cc.id = {$contributionId}";
1834 $clauses[] = "cco.id = {$contactId}";
1835 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1838 if (empty($clauses)) {
1839 CRM_Core_Error
::fatal();
1842 $condition = implode(' OR ', $clauses);
1846 FROM civicrm_address ca
1847 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1851 $dao = CRM_Core_DAO
::executeQuery($query);
1853 while ($dao->fetch()) {
1854 $params = ['id' => $dao->id
];
1855 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1860 * This function check online pending contribution associated w/
1861 * Online Event Registration or Online Membership signup.
1863 * @param int $componentId
1864 * Participant/membership id.
1865 * @param string $componentName
1869 * pending contribution id.
1871 public static function checkOnlinePendingContribution($componentId, $componentName) {
1872 $contributionId = NULL;
1873 if (!$componentId ||
1874 !in_array($componentName, ['Event', 'Membership'])
1876 return $contributionId;
1879 if ($componentName == 'Event') {
1880 $idName = 'participant_id';
1881 $componentTable = 'civicrm_participant';
1882 $paymentTable = 'civicrm_participant_payment';
1883 $source = ts('Online Event Registration');
1886 if ($componentName == 'Membership') {
1887 $idName = 'membership_id';
1888 $componentTable = 'civicrm_membership';
1889 $paymentTable = 'civicrm_membership_payment';
1890 $source = ts('Online Contribution');
1893 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1896 SELECT component.id as {$idName},
1897 componentPayment.contribution_id as contribution_id,
1898 contribution.source source,
1899 contribution.contribution_status_id as contribution_status_id,
1900 contribution.is_pay_later as is_pay_later
1901 FROM $componentTable component
1902 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1903 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1904 WHERE component.id = {$componentId}";
1906 $dao = CRM_Core_DAO
::executeQuery($query);
1908 while ($dao->fetch()) {
1909 if ($dao->contribution_id
&&
1910 $dao->is_pay_later
&&
1911 $dao->contribution_status_id
== $pendingStatusId &&
1912 strpos($dao->source
, $source) !== FALSE
1914 $contributionId = $dao->contribution_id
;
1918 return $contributionId;
1922 * Update contribution as well as related objects.
1924 * This function by-passes hooks - to address this - don't use this function.
1926 * @param array $params
1927 * @param bool $processContributionObject
1930 * @throws \Exception
1933 * Use api contribute.completetransaction
1934 * For failures use failPayment (preferably exposing by api in the process).
1937 public static function transitionComponents($params, $processContributionObject = FALSE) {
1938 // get minimum required values.
1939 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1940 $componentId = CRM_Utils_Array
::value('component_id', $params);
1941 $componentName = CRM_Utils_Array
::value('componentName', $params);
1942 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1943 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1945 // if we already processed contribution object pass previous status id.
1946 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1950 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1952 // we process only ( Completed, Cancelled, or Failed ) contributions.
1953 if (!$contributionId ||
1954 !in_array($contributionStatusId, [
1955 array_search('Completed', $contributionStatuses),
1956 array_search('Cancelled', $contributionStatuses),
1957 array_search('Failed', $contributionStatuses),
1960 return $updateResult;
1963 if (!$componentName ||
!$componentId) {
1964 // get the related component details.
1965 $componentDetails = self
::getComponentDetails($contributionId);
1968 $componentDetails['contact_id'] = $contactId;
1969 $componentDetails['component'] = $componentName;
1971 if ($componentName == 'event') {
1972 $componentDetails['participant'] = $componentId;
1975 $componentDetails['membership'] = $componentId;
1979 if (!empty($componentDetails['contact_id'])) {
1980 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1986 // do check for required ids.
1987 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1988 return $updateResult;
1991 //now we are ready w/ required ids, start processing.
1993 $baseIPN = new CRM_Core_Payment_BaseIPN();
1995 $input = $ids = $objects = [];
1997 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1998 $ids['contribution'] = $contributionId;
1999 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
2000 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
2001 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
2002 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
2003 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
2004 $ids['contributionRecur'] = NULL;
2005 $ids['contributionPage'] = NULL;
2007 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
2008 CRM_Core_Error
::fatal();
2011 $memberships = &$objects['membership'];
2012 $participant = &$objects['participant'];
2013 $pledgePayment = &$objects['pledge_payment'];
2014 $contribution = &$objects['contribution'];
2015 $pledgeID = $oldStatus = NULL;
2016 $pledgePaymentIDs = [];
2017 if ($pledgePayment) {
2018 foreach ($pledgePayment as $key => $object) {
2019 $pledgePaymentIDs[] = $object->id
;
2021 $pledgeID = $pledgePayment[0]->pledge_id
;
2024 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
2027 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
2028 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
2033 // we might want to process contribution object.
2034 $processContribution = FALSE;
2035 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
2036 // Call interim cancel function - with a goal to cleaning up the signature on it and switching to a tested api Contribution.cancel function.
2037 list($updateResult, $processContribution) = self
::cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
2039 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
2040 if (is_array($memberships)) {
2041 foreach ($memberships as $membership) {
2043 //Update Membership status if there is no other completed contribution associated with the membership.
2044 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
2045 foreach ($relatedContributions as $contriId) {
2046 if ($contriId == $contributionId) {
2049 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
2050 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
2054 if ($membership && $update) {
2055 $membership->status_id
= array_search('Expired', $membershipStatuses);
2056 $membership->is_override
= TRUE;
2057 $membership->status_override_end_date
= 'null';
2058 $membership->save();
2060 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2061 if ($processContributionObject) {
2062 $processContribution = TRUE;
2068 $updatedStatusId = array_search('Cancelled', $participantStatuses);
2069 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2071 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2072 if ($processContributionObject) {
2073 $processContribution = TRUE;
2077 if ($pledgePayment) {
2078 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2080 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2081 if ($processContributionObject) {
2082 $processContribution = TRUE;
2086 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
2088 // only pending contribution related object processed.
2089 if ($previousContriStatusId &&
2090 !in_array($contributionStatuses[$previousContriStatusId], [
2095 // this is case when we already processed contribution object.
2096 return $updateResult;
2098 elseif (!$previousContriStatusId &&
2099 !in_array($contributionStatuses[$contribution->contribution_status_id
], [
2104 // this is case when we are going to process contribution object later.
2105 return $updateResult;
2108 if (is_array($memberships)) {
2109 foreach ($memberships as $membership) {
2114 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
2115 $membership->membership_type_id
,
2116 $membership->is_test
, $membership->id
2119 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2120 // this picks up membership type changes during renewals
2122 SELECT membership_type_id
2123 FROM civicrm_membership_log
2124 WHERE membership_id=$membership->id
2127 $dao = new CRM_Core_DAO();
2129 if ($dao->fetch()) {
2130 if (!empty($dao->membership_type_id
)) {
2131 $membership->membership_type_id
= $dao->membership_type_id
;
2132 $membership->save();
2135 // else fall back to using current membership type
2136 // Figure out number of terms
2138 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
2139 foreach ($lineitems as $lineitem) {
2140 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
2141 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
2143 // in case membership_num_terms comes through as null or zero
2144 $numterms = $numterms >= 1 ?
$numterms : 1;
2149 // CRM-15735-to update the membership status as per the contribution receive date
2151 $oldStatus = $membership->status_id
;
2152 if (!empty($params['receive_date'])) {
2153 $joinDate = $params['receive_date'];
2154 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
2155 $membership->end_date
,
2156 $membership->join_date
,
2157 $params['receive_date'],
2159 $membership->membership_type_id
,
2162 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
2163 $membership->save();
2166 if ($currentMembership) {
2167 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2168 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
2169 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2172 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
2175 //get the status for membership.
2176 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
2178 $dates['join_date'],
2181 $membership->membership_type_id
,
2185 $formattedParams = [
2186 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
2187 array_search('Current', $membershipStatuses)
2189 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
2190 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
2191 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
2194 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
2196 $membership->copyValues($formattedParams);
2197 $membership->save();
2199 //updating the membership log
2200 $membershipLog = [];
2201 $membershipLog = $formattedParams;
2202 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
2203 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
2205 $membershipLog['start_date'] = $logStartDate;
2206 $membershipLog['membership_id'] = $membership->id
;
2207 $membershipLog['modified_id'] = $membership->contact_id
;
2208 $membershipLog['modified_date'] = date('Ymd');
2209 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
2211 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2213 //update related Memberships.
2214 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2216 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2217 $scheduledActivityID = CRM_Utils_Array
::value('id',
2218 civicrm_api3('Activity', 'Get',
2220 'source_record_id' => $membership->id
,
2221 'activity_type_id' => $activityType,
2222 'status_id' => 'Scheduled',
2225 'sort' => 'id DESC',
2230 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2231 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2232 if ($scheduledActivityID) {
2233 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, ['id' => $scheduledActivityID]);
2238 // track membership status change if any
2239 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
2240 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2241 CRM_Activity_BAO_Activity
::addActivity($membership,
2242 'Change Membership Status',
2245 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2246 'source_contact_id' => $membershipLog['modified_id'],
2247 'priority_id' => 'Normal',
2252 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2253 if ($processContributionObject) {
2254 $processContribution = TRUE;
2257 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2263 $updatedStatusId = array_search('Registered', $participantStatuses);
2264 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2266 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2267 if ($processContributionObject) {
2268 $processContribution = TRUE;
2272 if ($pledgePayment) {
2273 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2275 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2276 if ($processContributionObject) {
2277 $processContribution = TRUE;
2282 // process contribution object.
2283 if ($processContribution) {
2284 $contributionParams = [];
2291 'payment_instrument_id',
2294 'financial_type_id',
2295 'contribution_status_id',
2296 'non_deductible_amount',
2300 foreach ($fields as $field) {
2301 if (empty($params[$field])) {
2304 $contributionParams[$field] = $params[$field];
2307 $ids = ['contribution' => $contributionId];
2308 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2311 return $updateResult;
2315 * Returns all contribution related object ids.
2317 * @param $contributionId
2321 public static function getComponentDetails($contributionId) {
2322 $componentDetails = $pledgePayment = [];
2323 if (!$contributionId) {
2324 return $componentDetails;
2328 SELECT c.id as contribution_id,
2329 c.contact_id as contact_id,
2330 c.contribution_recur_id,
2331 mp.membership_id as membership_id,
2332 m.membership_type_id as membership_type_id,
2333 pp.participant_id as participant_id,
2334 p.event_id as event_id,
2335 pgp.id as pledge_payment_id
2336 FROM civicrm_contribution c
2337 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2338 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2339 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2340 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2341 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2342 WHERE c.id = $contributionId";
2344 $dao = CRM_Core_DAO
::executeQuery($query);
2345 $componentDetails = [];
2347 while ($dao->fetch()) {
2348 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2349 $componentDetails['contact_id'] = $dao->contact_id
;
2350 if ($dao->event_id
) {
2351 $componentDetails['event'] = $dao->event_id
;
2353 if ($dao->participant_id
) {
2354 $componentDetails['participant'] = $dao->participant_id
;
2356 if ($dao->membership_id
) {
2357 if (!isset($componentDetails['membership'])) {
2358 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2360 $componentDetails['membership'][] = $dao->membership_id
;
2361 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2363 if ($dao->pledge_payment_id
) {
2364 $pledgePayment[] = $dao->pledge_payment_id
;
2366 if ($dao->contribution_recur_id
) {
2367 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2371 if ($pledgePayment) {
2372 $componentDetails['pledge_payment'] = $pledgePayment;
2375 return $componentDetails;
2379 * @param int $contactId
2380 * @param bool $includeSoftCredit
2382 * @return null|string
2384 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2388 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2389 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2390 $liWhere = " AND i.financial_type_id IN (0)";
2391 if (!empty($financialTypes)) {
2392 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2393 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2395 $contactContributionsSQL = "
2396 SELECT contribution.id AS id
2397 FROM civicrm_contribution contribution
2398 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2399 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2403 $contactSoftCreditContributionsSQL = "
2404 SELECT contribution.id
2405 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2406 ON ( contribution.id = softContribution.contribution_id )
2407 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2408 $query = "SELECT count( x.id ) count FROM ( ";
2409 $query .= $contactContributionsSQL;
2411 if ($includeSoftCredit) {
2412 $query .= " UNION ";
2413 $query .= $contactSoftCreditContributionsSQL;
2418 return CRM_Core_DAO
::singleValueQuery($query);
2422 * Repeat a transaction as part of a recurring series.
2425 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2426 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2427 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2428 * and associated entities.
2429 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2430 * which updates the various entities and sends appropriate emails.
2432 * Gaps in the above (@todo)
2433 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2434 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2435 * 3) Repeat transaction duplicates rather than calls Order.create
2436 * 4) Use of payment.create still limited - completetransaction is more common.
2437 * 5) the template transaction is tricky - historically we used the first contribution
2438 * linked to a recurring contribution. More recently that was changed to be the most recent.
2439 * Ideally it would be an actual template - not a contribution used as a template which
2440 * would give more appropriate flexibility. Note line_items have an entity so that table
2441 * could be used for the line item template - the difficulty is the custom fields...
2442 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2443 * to load the membership(s) referred to via line items in the template transactions. Any other
2444 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2445 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2446 * - membership_payment record
2447 * - civicrm_membership.contribution_recur_id
2449 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2450 * of historical processors since this has been handled 'forever' - specifically for paypal.
2451 * albeit by an even nastier mechanism than the current input override.
2452 * The count is out on how correct related entities wind up in this case.
2454 * @param CRM_Contribute_BAO_Contribution $contribution
2455 * @param array $input
2456 * @param array $contributionParams
2457 * @param int $paymentProcessorID
2460 * @throws CiviCRM_API3_Exception
2462 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
2463 if (!empty($contribution->id
)) {
2466 if (empty($contribution->id
)) {
2467 // Unclear why this would only be set for repeats.
2468 if (!empty($input['amount'])) {
2469 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2472 if (!empty($contributionParams['contribution_recur_id'])) {
2473 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2474 'id' => $contributionParams['contribution_recur_id'],
2476 if (!empty($recurringContribution['campaign_id'])) {
2477 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2478 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2480 if (!empty($recurringContribution['financial_type_id'])) {
2481 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2482 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2485 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2486 $contributionParams['contribution_recur_id'],
2487 array_intersect_key($contributionParams, [
2488 'total_amount' => TRUE,
2489 'financial_type_id' => TRUE,
2492 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2494 $contributionParams['status_id'] = 'Pending';
2495 if (isset($contributionParams['financial_type_id'])) {
2496 // Give precedence to passed in type.
2497 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2500 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2502 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2503 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2505 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2506 //do not create CC or BCC emails or profile notifications.
2507 //The if is just to be safe. Not sure if we can ever arrive with this unset
2508 // but per CRM-19478 it seems it can be 'null'
2509 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2510 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2513 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2514 $contribution->id
= $createContribution['id'];
2515 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2516 self
::handleMembershipIDOverride($contribution->id
, $input);
2522 * Get individual id for onbehalf contribution.
2524 * @param int $contributionId
2526 * @param int $contributorId
2530 * containing organization id and individual id
2532 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2536 if (!$contributionId) {
2540 // fetch contributor id if null
2541 if (!$contributorId) {
2542 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2543 $contributionId, 'contact_id'
2547 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2548 $activityTypeId = array_search('Contribution', $activityTypeIds);
2550 if ($activityTypeId && $contributorId) {
2552 SELECT civicrm_activity_contact.contact_id
2553 FROM civicrm_activity_contact
2554 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2555 WHERE civicrm_activity.activity_type_id = %1
2556 AND civicrm_activity.source_record_id = %2
2557 AND civicrm_activity_contact.record_type_id = %3
2560 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2561 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2564 1 => [$activityTypeId, 'Integer'],
2565 2 => [$contributionId, 'Integer'],
2566 3 => [$sourceID, 'Integer'],
2569 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2571 // for on behalf contribution source is individual and contributor is organization
2572 if ($sourceContactId && $sourceContactId != $contributorId) {
2573 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2574 // get rel type id for employee of relation
2575 foreach ($relationshipTypeIds as $id => $typeVals) {
2576 if ($typeVals['name_a_b'] == 'Employee of') {
2577 $relationshipTypeId = $id;
2582 $rel = new CRM_Contact_DAO_Relationship();
2583 $rel->relationship_type_id
= $relationshipTypeId;
2584 $rel->contact_id_a
= $sourceContactId;
2585 $rel->contact_id_b
= $contributorId;
2586 if ($rel->find(TRUE)) {
2587 $ids['individual_id'] = $rel->contact_id_a
;
2588 $ids['organization_id'] = $rel->contact_id_b
;
2599 public static function getContributionDates() {
2600 $config = CRM_Core_Config
::singleton();
2601 $currentMonth = date('m');
2602 $currentDay = date('d');
2603 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2604 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2605 (int ) $config->fiscalYearStart
['d'] > $currentDay
2608 $year = date('Y') - 1;
2613 $year = ['Y' => $year];
2614 $yearDate = $config->fiscalYearStart
;
2615 $yearDate = array_merge($year, $yearDate);
2616 $yearDate = CRM_Utils_Date
::format($yearDate);
2618 $monthDate = date('Ym') . '01';
2624 'yearDate' => $yearDate,
2625 'monthDate' => $monthDate,
2630 * Load objects relations to contribution object.
2631 * Objects are stored in the $_relatedObjects property
2632 * In the first instance we are just moving functionality from BASEIpn -
2634 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2636 * Note that the unit test for the BaseIPN class tests this function
2638 * @param array $input
2639 * Input as delivered from Payment Processor.
2641 * Ids as Loaded by Payment Processor.
2642 * @param bool $loadAll
2643 * Load all related objects - even where id not passed in? (allows API to call this).
2648 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2649 // @todo deprecate this function - the steps should be
2650 // 1) add additional functions like 'getRelatedMemberships'
2651 // 2) switch all calls that refer to ->_relatedObjects to
2652 // using the helper functions
2653 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2654 // 4) make ->_relatedObjects protected
2655 // 5) hone up the individual functions to not use rely on this having been called
2656 // 6) deprecate like mad
2658 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2659 if (empty($ids['contact']) && isset($this->contact_id
)) {
2660 $ids['contact'] = $this->contact_id
;
2663 if (empty($this->_component
)) {
2664 if (!empty($ids['event'])) {
2665 $this->_component
= 'event';
2668 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2672 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2673 // refactoring than anything else, and has unit test coverage.
2674 if (empty($this->financial_type_id
)) {
2678 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2683 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2684 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2685 $this->contribution_page_id
,
2688 if ($paymentProcessorID) {
2689 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2693 $ids['contributionType'] = $this->financial_type_id
;
2694 $ids['financialType'] = $this->financial_type_id
;
2695 if ($this->contribution_page_id
) {
2696 $ids['contributionPage'] = $this->contribution_page_id
;
2699 $this->loadRelatedEntitiesByID($ids);
2701 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2702 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2705 if (!empty($ids['pledge_payment'])) {
2706 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2707 if (empty($paymentID)) {
2710 $payment = new CRM_Pledge_BAO_PledgePayment();
2711 $payment->id
= $paymentID;
2712 if (!$payment->find(TRUE)) {
2713 throw new Exception("Could not find pledge payment record: " . $paymentID);
2715 $this->_relatedObjects
['pledge_payment'][] = $payment;
2719 // These are probably no longer accessed from anywhere
2720 // @todo remove this line, after ensuring not used.
2721 $ids = $this->loadRelatedMembershipObjects($ids);
2723 if ($this->_component
!= 'contribute') {
2724 // we are in event mode
2725 // make sure event exists and is valid
2726 $event = new CRM_Event_BAO_Event();
2727 $event->id
= $ids['event'];
2728 if ($ids['event'] &&
2731 throw new Exception("Could not find event: " . $ids['event']);
2734 $this->_relatedObjects
['event'] = &$event;
2736 $participant = new CRM_Event_BAO_Participant();
2737 $participant->id
= $ids['participant'];
2738 if ($ids['participant'] &&
2739 !$participant->find(TRUE)
2741 throw new Exception("Could not find participant: " . $ids['participant']);
2743 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2745 $this->_relatedObjects
['participant'] = &$participant;
2747 // get the payment processor id from event - this is inaccurate see CRM-16923
2748 // in future we should look at throwing an exception here rather than an dubious guess.
2749 if (!$paymentProcessorID) {
2750 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2751 if ($paymentProcessorID) {
2752 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2757 if ($paymentProcessorID) {
2758 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2759 $this->is_test ?
'test' : 'live'
2761 $ids['paymentProcessor'] = $paymentProcessorID;
2762 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2765 // Add contribution id to $ids. CRM-20401
2766 $ids['contribution'] = $this->id
;
2771 * Create array of message information - ie. return html version, txt version, to field
2773 * @param array $input
2774 * Incoming information.
2775 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2776 * just check presence of recur object but maintaining legacy approach
2779 * IDs of related objects.
2780 * @param array $values
2781 * Any values that may have already been compiled by calling process.
2782 * This is augmented by values 'gathered' by gatherMessageValues
2783 * @param bool $returnMessageText
2784 * Distinguishes between whether to send message or return.
2785 * message text. We are working towards this function ALWAYS returning message text & calling
2786 * function doing emails / pdfs with it
2792 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2793 $this->loadRelatedObjects($input, $ids);
2795 if (empty($this->_component
)) {
2796 $this->_component
= CRM_Utils_Array
::value('component', $input);
2799 //not really sure what params might be passed in but lets merge em into values
2800 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2801 $values['is_email_receipt'] = $this->isEmailReceipt($input, $values);
2802 if (!empty($input['receipt_date'])) {
2803 $values['receipt_date'] = $input['receipt_date'];
2806 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2807 //what does recur 'mean here - to do with payment processor return functionality but
2808 // what is the importance
2809 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2810 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2812 $entityID = $entity = NULL;
2813 if (isset($ids['contribution'])) {
2814 $entity = 'contribution';
2815 $entityID = $ids['contribution'];
2817 if (!empty($ids['membership'])) {
2818 //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
2819 // 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
2820 // line having loaded an array
2821 $ids['membership'] = (array) $ids['membership'];
2822 $entity = 'membership';
2823 $entityID = $ids['membership'][0];
2826 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2827 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2828 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2830 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2831 //direct mode showing billing block, so use directIPN for temporary
2832 $template->assign('contributeMode', 'directIPN');
2835 // todo remove strtolower - check consistency
2836 if (strtolower($this->_component
) == 'event') {
2837 $eventParams = ['id' => $this->_relatedObjects
['participant']->event_id
];
2838 $values['event'] = [];
2840 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2842 //get location details
2844 'entity_id' => $this->_relatedObjects
['participant']->event_id
,
2845 'entity_table' => 'civicrm_event',
2847 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2850 'entity_table' => 'civicrm_event',
2851 'entity_id' => $ids['event'],
2852 'module' => 'CiviEvent',
2855 list($custom_pre_id,
2857 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2859 $values['custom_pre_id'] = $custom_pre_id;
2860 $values['custom_post_id'] = $custom_post_ids;
2861 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2862 //and cases involving status updation through ipn
2863 // whatever that means!
2864 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2865 // perhaps we should throw an e-notice if amount is set & force total_amount?
2866 if (!empty($input['amount'])) {
2867 $values['totalAmount'] = $input['amount'];
2869 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2870 if ($values['event']['is_email_confirm']) {
2871 $values['is_email_receipt'] = 1;
2874 if (!empty($ids['contribution'])) {
2875 $values['contributionId'] = $ids['contribution'];
2878 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2879 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2883 $values['contribution_id'] = $this->id
;
2884 if (!empty($ids['related_contact'])) {
2885 $values['related_contact'] = $ids['related_contact'];
2886 if (isset($ids['onbehalf_dupe_alert'])) {
2887 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2890 'contact_id' => $ids['contact'],
2891 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2892 'Home', 'id', 'name'
2895 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2896 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2899 if ($this->is_test
) {
2902 if (!empty($this->_relatedObjects
['membership'])) {
2903 foreach ($this->_relatedObjects
['membership'] as $membership) {
2904 if ($membership->id
) {
2905 $values['membership_id'] = $membership->id
;
2906 $values['isMembership'] = TRUE;
2907 $values['membership_assign'] = TRUE;
2909 // need to set the membership values here
2910 $template->assign('membership_name',
2911 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2913 $template->assign('mem_start_date', $membership->start_date
);
2914 $template->assign('mem_join_date', $membership->join_date
);
2915 $template->assign('mem_end_date', $membership->end_date
);
2916 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2917 $template->assign('mem_status', $membership_status);
2918 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2919 $values['is_pay_later'] = 1;
2921 // Pass amount to floatval as string '0.00' is considered a
2922 // valid amount and includes Fee section in the mail.
2923 if (isset($values['amount'])) {
2924 $values['amount'] = floatval($values['amount']);
2927 if (!empty($this->contribution_recur_id
) && $paymentObject) {
2928 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2929 $template->assign('cancelSubscriptionUrl', $url);
2930 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2931 $template->assign('updateSubscriptionBillingUrl', $url);
2932 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2933 $template->assign('updateSubscriptionUrl', $url);
2936 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2939 // otherwise if its about sending emails, continue sending without return, as we
2940 // don't want to exit the loop.
2945 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2951 * Gather values for contribution mail - this function has been created
2952 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2953 * Values related to the contribution in question are gathered
2955 * @param array $input
2956 * Input into function (probably from payment processor).
2957 * @param array $values
2959 * The set of ids related to the input.
2962 * @throws \CRM_Core_Exception
2964 public function _gatherMessageValues($input, &$values, $ids = []) {
2965 // set display address of contributor
2966 if ($this->address_id
) {
2967 $addressParams = ['id' => $this->address_id
];
2968 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2969 $addressDetails = array_values($addressDetails);
2971 // Else we assign the billing address of the contribution contact.
2973 $addressParams = ['contact_id' => $this->contact_id
, 'is_billing' => 1];
2974 $addressDetails = (array) CRM_Core_BAO_Address
::getValues($addressParams);
2975 $addressDetails = array_values($addressDetails);
2978 if (!empty($addressDetails[0]['display'])) {
2979 $values['address'] = $addressDetails[0]['display'];
2982 if ($this->_component
== 'contribute') {
2983 //get soft contributions
2984 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2985 if (!empty($softContributions)) {
2986 $values['softContributions'] = $softContributions['soft_credit'];
2988 if (isset($this->contribution_page_id
)) {
2989 // This is a call we want to use less, in favour of loading related objects.
2990 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
2991 if ($this->contribution_page_id
) {
2992 // This is precautionary as there are some legacy flows, but it should really be
2994 if (!isset($this->_relatedObjects
['contributionPage'])) {
2995 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id
]);
2997 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($values);
3000 // no contribution page -probably back office
3002 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
3003 $values['title'] = 'Contribution';
3005 // set lineItem for contribution
3007 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
3008 if (!empty($lineItems)) {
3009 $firstLineItem = reset($lineItems);
3011 if (!empty($firstLineItem['price_set_id'])) {
3012 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
3013 'id' => $firstLineItem['price_set_id'],
3014 'return' => 'is_quick_config, id',
3016 $values['priceSetID'] = $priceSet['id'];
3018 foreach ($lineItems as &$eachItem) {
3019 if (isset($this->_relatedObjects
['membership'])
3020 && is_array($this->_relatedObjects
['membership'])
3021 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
3022 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
3023 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
3024 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
3026 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
3027 // However, that does create upgrade pain so would be better to be phased in.
3028 $values['useForMember'] = empty($priceSet['is_quick_config']);
3030 $values['lineItem'][0] = $lineItems;
3034 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
3038 // if this is onbehalf of contribution then set related contact
3039 if (!empty($relatedContact['individual_id'])) {
3040 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
3044 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects
['participant']->id
, $this->id
));
3047 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
3050 foreach ($groupTree as $key => $group) {
3051 if ($key === 'info') {
3055 foreach ($group['fields'] as $k => $customField) {
3056 $groupLabel = $group['title'];
3057 if (!empty($customField['customValue'])) {
3058 foreach ($customField['customValue'] as $customFieldValues) {
3059 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
3064 $values['customGroup'] = $customGroup;
3066 $values['is_pay_later'] = $this->is_pay_later
;
3072 * Assign message variables to template but try to break the habit.
3074 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3075 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3076 * multiple recurring payments for processors like IATS that use tokens.
3078 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3079 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
3080 * Note we send directly from this function in some cases because it is only partly refactored.
3082 * Don't call this function directly as the signature will change.
3086 * @param bool $returnMessageText
3090 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
3091 // @todo - this should have a better separation of concerns - ie.
3092 // gatherMessageValues should build an array of values to be assigned to the template
3093 // and this function should assign them (assigning null if not set).
3094 // the way the pcpParams & honor Params section works is a baby-step towards this.
3095 $template = CRM_Core_Smarty
::singleton();
3096 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
3097 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
3098 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
3100 // For some unit tests contribution cannot contain paymentProcessor information
3101 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
3102 $template->assign('contributeMode', CRM_Utils_Array
::value($billingMode, CRM_Core_SelectValues
::contributeMode()));
3104 //assign honor information to receipt message
3105 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
3108 'soft_credit_type' => NULL,
3109 'honor_block_is_active' => NULL,
3111 if (isset($softRecord['soft_credit'])) {
3112 //if id of contribution page is present
3113 if (!empty($values['id'])) {
3114 $values['honor'] = [
3115 'honor_profile_values' => [],
3116 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3117 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
3120 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3121 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
3124 //offline contribution
3125 $softCreditTypes = $softCredits = [];
3126 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3127 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3128 $softCredits[$key] = [
3129 'Name' => $softCredit['contact_name'],
3130 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
3133 $template->assign('softCreditTypes', $softCreditTypes);
3134 $template->assign('softCredits', $softCredits);
3138 $dao = new CRM_Contribute_DAO_ContributionProduct();
3139 $dao->contribution_id
= $this->id
;
3140 if ($dao->find(TRUE)) {
3141 $premiumId = $dao->product_id
;
3142 $template->assign('option', $dao->product_option
);
3144 $productDAO = new CRM_Contribute_DAO_Product();
3145 $productDAO->id
= $premiumId;
3146 $productDAO->find(TRUE);
3147 $template->assign('selectPremium', TRUE);
3148 $template->assign('product_name', $productDAO->name
);
3149 $template->assign('price', $productDAO->price
);
3150 $template->assign('sku', $productDAO->sku
);
3152 $template->assign('title', CRM_Utils_Array
::value('title', $values));
3153 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
3154 if (!$values['amount'] && isset($this->total_amount
)) {
3155 $values['amount'] = $this->total_amount
;
3160 'pcp_display_in_roll' => NULL,
3161 'pcp_roll_nickname' => NULL,
3162 'pcp_personal_note' => NULL,
3166 if (strtolower($this->_component
) == 'contribute') {
3168 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3169 $softDAO->contribution_id
= $this->id
;
3170 if ($softDAO->find(TRUE)) {
3171 $pcpParams['pcpBlock'] = TRUE;
3172 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
3173 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
3174 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
3176 //assign the pcp page title for email subject
3177 $pcpDAO = new CRM_PCP_DAO_PCP();
3178 $pcpDAO->id
= $softDAO->pcp_id
;
3179 if ($pcpDAO->find(TRUE)) {
3180 $pcpParams['title'] = $pcpDAO->title
;
3184 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3185 $template->assign($templateKey, $templateValue);
3188 if ($this->financial_type_id
) {
3189 $values['financial_type_id'] = $this->financial_type_id
;
3192 $template->assign('trxn_id', $this->trxn_id
);
3193 $template->assign('receive_date',
3194 CRM_Utils_Date
::processDate($this->receive_date
)
3196 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
3197 $template->assign('action', $this->is_test ?
1024 : 1);
3198 $template->assign('receipt_text',
3199 CRM_Utils_Array
::value('receipt_text',
3203 $template->assign('is_monetary', 1);
3204 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3205 $template->assign('currency', $this->currency
);
3206 $template->assign('address', CRM_Utils_Address
::format($input));
3207 if (!empty($values['customGroup'])) {
3208 $template->assign('customGroup', $values['customGroup']);
3210 if (!empty($values['softContributions'])) {
3211 $template->assign('softContributions', $values['softContributions']);
3213 if ($this->_component
== 'event') {
3214 $template->assign('title', $values['event']['title']);
3215 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3217 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3218 $viewRoles[] = $participantRoles[$v];
3220 $values['event']['participant_role'] = implode(', ', $viewRoles);
3221 $template->assign('event', $values['event']);
3222 $template->assign('participant', $values['participant']);
3223 $template->assign('location', $values['location']);
3224 $template->assign('customPre', $values['custom_pre_id']);
3225 $template->assign('customPost', $values['custom_post_id']);
3228 if ($this->_relatedObjects
['participant']->is_test
) {
3232 $values['params'] = [];
3233 //to get email of primary participant.
3234 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3235 $primaryAmount[] = [
3236 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3237 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3239 //build an array of cId/pId of participants
3240 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3241 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3242 //send receipt to additional participant if exists
3243 if (count($additionalIDs)) {
3244 $template->assign('isPrimary', 0);
3245 $template->assign('customProfile', NULL);
3246 //set additionalParticipant true
3247 $values['params']['additionalParticipant'] = TRUE;
3248 foreach ($additionalIDs as $pId => $cId) {
3250 //to change the status pending to completed
3251 $additional = new CRM_Event_DAO_Participant();
3252 $additional->id
= $pId;
3253 $additional->contact_id
= $cId;
3254 $additional->find(TRUE);
3255 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3256 $additional->status_id
= 1;
3257 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3258 //if additional participant dont have email
3260 if (!$additionalParticipantInfo) {
3261 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3264 'label' => $additional->fee_level
,
3265 'amount' => $additional->fee_amount
,
3267 $primaryAmount[] = [
3268 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3269 'amount' => $additional->fee_amount
,
3271 $additional->save();
3272 $template->assign('amount', $amount);
3273 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3277 //build an array of custom profile and assigning it to template
3278 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3280 if (count($customProfile)) {
3281 $template->assign('customProfile', $customProfile);
3284 // for primary contact
3285 $values['params']['additionalParticipant'] = FALSE;
3286 $template->assign('isPrimary', 1);
3287 $template->assign('amount', $primaryAmount);
3288 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3289 if ($this->payment_instrument_id
) {
3290 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3291 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3293 // carry paylater, since we did not created billing,
3294 // so need to pull email from primary location, CRM-4395
3295 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3301 * Check whether payment processor supports
3302 * cancellation of contribution subscription
3304 * @param int $contributionId
3307 * @param bool $isNotCancelled
3311 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3312 $cacheKeyString = "$contributionId";
3313 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3315 static $supportsCancel = [];
3317 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3318 $supportsCancel[$cacheKeyString] = FALSE;
3319 $isCancelled = FALSE;
3321 if ($isNotCancelled) {
3322 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3325 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3326 if (!empty($paymentObject)) {
3327 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3330 return $supportsCancel[$cacheKeyString];
3334 * Check whether subscription is already cancelled.
3336 * @param int $contributionId
3340 * contribution status
3342 public static function isSubscriptionCancelled($contributionId) {
3344 SELECT cr.contribution_status_id
3345 FROM civicrm_contribution_recur cr
3346 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3347 WHERE con.id = %1 LIMIT 1";
3348 $params = [1 => [$contributionId, 'Integer']];
3349 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3350 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
3351 if ($status == 'Cancelled') {
3358 * Create all financial accounts entry.
3360 * @param array $params
3361 * Contribution object, line item array and params for trxn.
3364 * @param array $financialTrxnValues
3366 * @return null|\CRM_Core_BAO_FinancialTrxn
3368 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3369 $skipRecords = $update = $return = $isRelatedId = FALSE;
3371 $additionalParticipantId = [];
3372 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3373 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3375 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3376 $entityId = $params['participant_id'];
3377 $entityTable = 'civicrm_participant';
3378 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3380 elseif (!empty($params['membership_id'])) {
3381 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3382 // are created off one contribution should be handled elsewhere
3383 $entityId = $params['membership_id'];
3384 $entityTable = 'civicrm_membership';
3387 $entityId = $params['contribution']->id
;
3388 $entityTable = 'civicrm_contribution';
3391 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3392 $isRelatedId = TRUE;
3395 $entityID[] = $entityId;
3396 if (!empty($additionalParticipantId)) {
3397 $entityID +
= $additionalParticipantId;
3399 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3400 if (empty($params['prevContribution'])) {
3407 $statusId = $params['contribution']->contribution_status_id
;
3408 // CRM-13964 partial payment
3409 if ($contributionStatus == 'Partially paid'
3410 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])
3412 $partialAmtPay = CRM_Utils_Rule
::cleanMoney($params['partial_amount_to_pay']);
3413 $partialAmtTotal = CRM_Utils_Rule
::cleanMoney($params['partial_payment_total']);
3415 $fromFinancialAccountId = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3416 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
3417 $params['total_amount'] = $partialAmtPay;
3419 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3420 if (empty($balanceTrxnInfo['trxn_id'])) {
3421 // create new balance transaction record
3422 $toFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3424 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3425 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3426 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3427 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3428 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3429 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3430 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3431 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3432 $balanceTrxnParams['status_id'] = $statusId;
3433 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3434 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3435 $balanceTrxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3436 $balanceTrxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3437 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3438 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3440 $balanceTrxnParams['is_payment'] = 1;
3442 if (!empty($params['payment_processor'])) {
3443 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3445 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3449 // build line item array if its not set in $params
3450 if (empty($params['line_item']) ||
$additionalParticipantId) {
3451 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3454 if ($contributionStatus != 'Failed' &&
3455 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3457 $skipRecords = TRUE;
3462 if (in_array($contributionStatus, $pendingStatus)) {
3463 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3464 $params['financial_type_id'],
3465 'Accounts Receivable Account is'
3468 elseif (!empty($params['payment_processor'])) {
3469 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3470 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3471 'id' => $params['payment_processor'],
3472 'return' => 'payment_instrument_id',
3475 elseif (!empty($params['payment_instrument_id'])) {
3476 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3479 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3480 $queryParams = [1 => [$relationTypeId, 'Integer']];
3481 $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);
3484 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3485 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3486 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3488 //build financial transaction params
3490 'contribution_id' => $params['contribution']->id
,
3491 'to_financial_account_id' => $params['to_financial_account_id'],
3492 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3493 'total_amount' => $totalAmount,
3494 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3495 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3496 'currency' => $params['contribution']->currency
,
3497 'trxn_id' => $params['contribution']->trxn_id
,
3498 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3499 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3500 // this should really default to completed (after discussion).
3501 'status_id' => $statusId,
3502 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3503 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3504 'pan_truncation' => CRM_Utils_Array
::value('pan_truncation', $params),
3505 'card_type_id' => CRM_Utils_Array
::value('card_type_id', $params),
3507 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3508 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3509 if (isset($params['refund_trxn_id'])) {
3510 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3511 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3514 //CRM-16259, set is_payment flag for non pending status
3515 if (!in_array($contributionStatus, $pendingStatus)) {
3516 $trxnParams['is_payment'] = 1;
3518 if (!empty($params['payment_processor'])) {
3519 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3522 if (isset($fromFinancialAccountId)) {
3523 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3526 // consider external values passed for recording transaction entry
3527 if (!empty($financialTrxnValues)) {
3528 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3530 if (empty($trxnParams['payment_processor_id'])) {
3531 unset($trxnParams['payment_processor_id']);
3534 $params['trxnParams'] = $trxnParams;
3536 if (!empty($params['prevContribution'])) {
3538 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3539 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3540 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3541 if (!isset($params['trxnParams']['trxn_id'])) {
3542 // Actually I have no idea why we are overwriting any values from the previous contribution.
3543 // (filling makes sense to me). However, only protecting this value as I really really know we
3544 // don't want this one overwritten.
3546 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3548 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3550 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3551 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3552 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3554 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3555 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3558 //if financial type is changed
3559 if (!empty($params['financial_type_id']) &&
3560 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3562 $accountRelationship = 'Income Account is';
3563 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3564 $accountRelationship = 'Deferred Revenue Account is';
3566 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3567 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3568 if ($oldFinancialAccount != $newFinancialAccount) {
3569 $params['total_amount'] = 0;
3570 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3571 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3572 $params['prevContribution']->financial_type_id
, $accountRelationship);
3575 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3576 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3577 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3580 self
::updateFinancialAccounts($params, 'changeFinancialType');
3581 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3582 $params['financial_account_id'] = $newFinancialAccount;
3583 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3584 self
::updateFinancialAccounts($params);
3585 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3587 $params['deferred_financial_account_id'] = $newFinancialAccount;
3591 //Update contribution status
3592 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3593 if (!isset($params['refund_trxn_id'])) {
3594 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3595 // gets preference over another so I am only 'protecting' a very specific tested flow
3596 // and letting natural justice take care of the rest.
3597 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3599 if (!empty($params['contribution_status_id']) &&
3600 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3602 //Update Financial Records
3603 self
::updateFinancialAccounts($params, 'changedStatus');
3607 // change Payment Instrument for a Completed contribution
3608 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3609 // instrument is null and now new payment instrument is added along with the payment
3610 if (!$params['contribution']->payment_instrument_id
) {
3611 $params['contribution']->find(TRUE);
3613 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3614 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3616 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3617 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3620 //if Change contribution amount
3621 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3622 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3623 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3624 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3625 if (isset($totalAmount) &&
3626 $totalAmount != $params['prevContribution']->total_amount
3628 //Update Financial Records
3629 $params['trxnParams']['from_financial_account_id'] = NULL;
3630 self
::updateFinancialAccounts($params, 'changedAmount');
3635 // Looks like we might have a data correction update.
3636 // This would be a case where a transaction id has been entered but it is incorrect &
3637 // the person goes back in & fixes it, as opposed to a new transaction.
3638 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3639 // the data fix scenario.
3641 if (isset($params['refund_trxn_id'])) {
3642 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3643 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3644 civicrm_api3('FinancialTrxn', 'create', [
3645 'id' => $refundIDs['financialTrxnId'],
3646 'trxn_id' => $params['refund_trxn_id'],
3650 $cardType = CRM_Utils_Array
::value('card_type_id', $params);
3651 $panTruncation = CRM_Utils_Array
::value('pan_truncation', $params);
3652 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3657 // records finanical trxn and entity financial trxn
3658 // also make it available as return value
3659 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3660 $trxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3661 $trxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3662 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3663 $params['entity_id'] = $financialTxn->id
;
3664 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3665 self
::$_trxnIDs[] = $financialTxn->id
;
3669 // record line items and financial items
3670 if (empty($params['skipLineItem'])) {
3671 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3674 // create batch entry if batch_id is passed and
3675 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3676 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3678 'batch_id' => $params['batch_id'],
3679 'entity_table' => 'civicrm_financial_trxn',
3680 'entity_id' => $financialTxn->id
,
3682 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3685 // when a fee is charged
3686 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3687 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3690 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3691 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3693 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3694 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3695 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3697 unset($params['line_item']);
3698 self
::$_trxnIDs = NULL;
3703 * Update all financial accounts entry.
3705 * @param array $params
3706 * Contribution object, line item array and params for trxn.
3708 * @param string $context
3711 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3712 * adds unpredictability.
3715 public static function updateFinancialAccounts(&$params, $context = NULL) {
3717 $inputParams = $params;
3720 if ($context == 'changedStatus') {
3721 list($continue, $isARefund) = self
::updateFinancialAccountsOnContributionStatusChange($params);
3722 // @todo - it may be that this is always false & the parent function is just a confusing wrapper for the child fn.
3728 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3729 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3730 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3733 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3734 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3735 $params['entity_id'] = $trxn->id
;
3737 $itemParams['entity_table'] = 'civicrm_line_item';
3738 $trxnIds['id'] = $params['entity_id'];
3739 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution']->id
);
3740 foreach ($params['line_item'] as $fieldId => $fields) {
3741 foreach ($fields as $fieldValueId => $lineItemDetails) {
3742 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($lineItemDetails['id']);
3743 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3744 if ($params['contribution']->receive_date
) {
3745 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3748 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array
::value('financial_account_id', $prevFinancialItem));
3750 $currency = $params['prevContribution']->currency
;
3751 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3752 if ($params['contribution']->currency
) {
3753 $currency = $params['contribution']->currency
;
3755 $previousLineItemTotal = CRM_Utils_Array
::value('line_total', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
3757 'transaction_date' => $receiveDate,
3758 'contact_id' => $params['prevContribution']->contact_id
,
3759 'currency' => $currency,
3760 'amount' => self
::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
3761 'description' => CRM_Utils_Array
::value('description', $prevFinancialItem),
3762 'status_id' => $prevFinancialItem['status_id'],
3763 'financial_account_id' => $financialAccount,
3764 'entity_table' => 'civicrm_line_item',
3765 'entity_id' => $lineItemDetails['id'],
3767 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3768 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3769 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
3770 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
3772 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') ||
($context == 'changeFinancialType')) {
3773 $taxAmount = (float) $lineItemDetails['tax_amount'];
3774 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
3775 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
3776 $taxAmount = CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
3778 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
3779 $taxAmount -= CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
3781 if ($taxAmount != 0) {
3782 $itemParams['amount'] = self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * $taxAmount;
3783 $itemParams['description'] = CRM_Invoicing_Utils
::getTaxTerm();
3784 if ($lineItemDetails['financial_type_id']) {
3785 $itemParams['financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getSalesTaxFinancialAccount($lineItemDetails['financial_type_id']);
3787 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3793 if ($context == 'changeFinancialType') {
3794 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3795 $params['skipLineItem'] = FALSE;
3796 foreach ($params['line_item'] as &$lineItems) {
3797 foreach ($lineItems as &$line) {
3798 $line['financial_type_id'] = $params['financial_type_id'];
3803 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, $context);
3807 * Is this contribution status a reversal.
3809 * If so we would expect to record a negative value in the financial_trxn table.
3811 * @param int $status_id
3815 public static function isContributionStatusNegative($status_id) {
3816 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3817 return in_array(CRM_Contribute_PseudoConstant
::contributionStatus($status_id, 'name'), $reversalStatuses);
3821 * Check status validation on update of a contribution.
3823 * @param array $values
3824 * Previous form values before submit.
3826 * @param array $fields
3827 * The input form values.
3829 * @param array $errors
3834 public static function checkStatusValidation($values, &$fields, &$errors) {
3835 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3836 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3837 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3841 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3843 'Cancelled' => ['Completed', 'Refunded'],
3844 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3845 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3846 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3847 'Refunded' => ['Cancelled', 'Completed'],
3848 'Partially paid' => ['Completed'],
3849 'Pending refund' => ['Completed', 'Refunded'],
3852 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3853 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3855 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3856 1 => $contributionStatuses[$values['contribution_status_id']],
3857 2 => $contributionStatuses[$fields['contribution_status_id']],
3863 * Delete contribution of contact.
3867 * @param int $contactId
3871 public static function deleteContactContribution($contactId) {
3872 $contribution = new CRM_Contribute_DAO_Contribution();
3873 $contribution->contact_id
= $contactId;
3874 $contribution->find();
3875 while ($contribution->fetch()) {
3876 self
::deleteContribution($contribution->id
);
3881 * Get options for a given contribution field.
3883 * @param string $fieldName
3884 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3885 * @param array $props whatever is known about this dao object.
3887 * @return array|bool
3888 * @see CRM_Core_DAO::buildOptions
3891 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3892 $className = __CLASS__
;
3894 if (isset($props['orderColumn'])) {
3895 $params['orderColumn'] = $props['orderColumn'];
3897 switch ($fieldName) {
3898 // This field is not part of this object but the api supports it
3899 case 'payment_processor':
3900 $className = 'CRM_Contribute_BAO_ContributionPage';
3901 // Filter results by contribution page
3902 if (!empty($props['contribution_page_id'])) {
3903 $page = civicrm_api('contribution_page', 'getsingle', [
3905 'id' => ($props['contribution_page_id']),
3907 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3908 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3912 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3913 case 'honor_type_id':
3914 $className = 'CRM_Contribute_BAO_ContributionSoft';
3915 $fieldName = 'soft_credit_type_id';
3916 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3919 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3923 * Validate financial type.
3927 * @param int $financialTypeId
3928 * Financial Type id.
3930 * @param string $relationName
3932 * @return array|bool
3934 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3935 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3937 if (!$financialAccount) {
3938 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3944 * @param int $targetCid
3945 * @param $activityType
3946 * @param string $title
3947 * @param int $contributionId
3948 * @param string $totalAmount
3949 * @param string $currency
3950 * @param string $trxn_date
3952 * @throws \CRM_Core_Exception
3953 * @throws \CiviCRM_API3_Exception
3955 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
3956 $paymentAmount = CRM_Utils_Money
::format($totalAmount, $currency);
3957 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3958 $date = CRM_Utils_Date
::isoToMysql($trxn_date);
3959 // source record id would be the contribution id
3960 $srcRecId = $contributionId;
3964 'source_contact_id' => $targetCid,
3965 'source_record_id' => $srcRecId,
3966 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
3967 'subject' => $subject,
3968 'activity_date_time' => $date,
3969 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
3970 'skipRecentView' => TRUE,
3973 // create activity with target contacts
3974 $session = CRM_Core_Session
::singleton();
3975 $id = $session->get('userID');
3977 $activityParams['source_contact_id'] = $id;
3978 $activityParams['target_contact_id'][] = $targetCid;
3980 civicrm_api3('Activity', 'create', $activityParams);
3984 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3988 * @param bool $getTrxnInfo
3989 * @param bool $usingLineTotal
3993 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3994 // @todo deprecate passing in component - always call with contribution.
3995 if ($component == 'event') {
3996 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3998 if (!$contributionId) {
3999 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4000 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4001 $id = $primaryParticipantId;
4003 if (!$contributionId) {
4008 elseif ($component == 'membership') {
4009 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
4012 $contributionId = $id;
4015 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
4016 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
4018 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
4019 $baseTrxnId = $baseTrxnId['financialTrxnId'];
4021 if (empty($total['total_amount']) ||
$usingLineTotal) {
4022 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4025 $baseTrxnId = $total['trxn_id'];
4026 $total = $total['total_amount'];
4029 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
4031 $contribution = civicrm_api3('Contribution', 'getsingle', [
4032 'id' => $contributionId,
4036 'contribution_status_id',
4037 'financial_type_id',
4041 $info['payLater'] = $contribution['is_pay_later'];
4042 $info['contribution_status'] = $contribution['contribution_status'];
4043 $info['currency'] = $contribution['currency'];
4045 $financialTypeId = $contribution['financial_type_id'];
4046 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, 'Expense Account is');
4048 if ($paymentBalance == 0 && $info['payLater']) {
4049 // @todo - review - this looks very unlikely to be correct.
4050 // the balance should be correct based on payment transactions not
4052 $paymentBalance = $total;
4055 $info['total'] = $total;
4056 $info['paid'] = $total - $paymentBalance;
4057 $info['balance'] = $paymentBalance;
4059 $info['component'] = $component;
4061 if ($getTrxnInfo && $baseTrxnId) {
4062 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
4064 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
4066 ft.payment_instrument_id,
4067 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
4069 FROM civicrm_contribution con
4070 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4071 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4072 AND ft.to_financial_account_id != %2
4073 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
4074 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
4075 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
4077 WHERE con.id = %1 AND ft.is_payment = 1
4080 1 => [$contributionId, 'Integer'],
4081 2 => [$feeFinancialAccount, 'Integer'],
4083 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
4084 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label');
4086 while ($resultDAO->fetch()) {
4087 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4088 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4089 if ($resultDAO->card_type_id
) {
4090 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
4091 $pantruncation = '';
4092 if ($resultDAO->pan_truncation
) {
4093 $pantruncation = ": {$resultDAO->pan_truncation}";
4095 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
4098 // show payment edit link only for payments done via backoffice form
4099 $paymentEditLink = '';
4100 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
4102 CRM_Core_Action
::UPDATE
=> [
4103 'name' => "<i class='crm-i fa-pencil'></i>",
4104 'url' => 'civicrm/payment/edit',
4105 'class' => 'medium-popup',
4106 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
4107 'title' => ts('Edit Payment'),
4110 $paymentEditLink = CRM_Core_Action
::formLink(
4112 CRM_Core_Action
::mask([CRM_Core_Permission
::EDIT
]),
4114 'id' => $resultDAO->id
,
4115 'contribution_id' => $contributionId,
4121 'id' => $resultDAO->id
,
4122 'total_amount' => $resultDAO->total_amount
,
4123 'financial_type' => $resultDAO->financial_account
,
4124 'payment_instrument' => $paidByLabel,
4125 'receive_date' => $resultDAO->trxn_date
,
4126 'trxn_id' => $resultDAO->trxn_id
,
4127 'status' => $statuses[$resultDAO->status_id
],
4128 'currency' => $resultDAO->currency
,
4129 'action' => $paymentEditLink,
4131 if ($paidByName == 'Check') {
4132 $val['check_number'] = $resultDAO->check_number
;
4136 $info['transaction'] = $rows;
4139 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
4144 * Get the outstanding balance on a contribution.
4146 * @param int $contributionId
4147 * @param float $contributionTotal
4148 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
4152 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
4153 if ($contributionTotal === NULL) {
4154 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4157 return CRM_Utils_Money
::subtractCurrencies(
4159 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE) ?
: 0,
4160 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4165 * Get the tax amount (misnamed function).
4167 * @param array $params
4168 * @param bool $isLineItem
4172 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4173 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4175 // This function should be only called after standardisation (removal of
4176 // thousand separator & using a decimal point for cents separator.
4177 // However, we don't know if that is always true :-(
4178 // There is a deprecation notice tho :-)
4179 $unknownIfMoneyIsClean = empty($params['skipCleanMoney']) && !$isLineItem;
4180 // Update contribution.
4181 if (!empty($params['id'])) {
4182 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4183 // there are no tax implications - early return.
4184 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4187 if (empty($params['prevContribution'])) {
4188 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4191 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
4192 if (!isset($params[$field])) {
4193 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4194 // Tax amount gets added back on later....
4195 $params['total_amount'] = $params['prevContribution']->total_amount
-
4196 $params['prevContribution']->tax_amount
;
4199 $params[$field] = $params['prevContribution']->$field;
4200 if ($params[$field] != $params['prevContribution']->$field) {
4206 self
::calculateMissingAmountParams($params, $params['id']);
4207 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4208 // Assign tax Amount on update of contribution
4209 if (!empty($params['prevContribution']->tax_amount
)) {
4210 $params['tax_amount'] = 'null';
4211 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4212 foreach ($params['line_item'] as $setID => $priceField) {
4213 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4214 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4221 // New Contribution and update of contribution with tax rate financial type
4222 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4223 empty($params['skipLineItem']) && !$isLineItem
4225 $taxRateParams = $taxRates[$params['financial_type_id']];
4226 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams, $unknownIfMoneyIsClean);
4227 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4229 // Get Line Item on update of contribution
4230 if (isset($params['id'])) {
4231 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4234 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4236 foreach ($params['line_item'] as $setID => $priceField) {
4237 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4238 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4241 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4243 elseif (isset($params['api.line_item.create'])) {
4244 // Update total amount of contribution using lineItem
4245 $taxAmountArray = [];
4246 foreach ($params['api.line_item.create'] as $key => $value) {
4247 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4248 $taxRate = $taxRates[$value['financial_type_id']];
4249 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4250 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4253 $params['tax_amount'] = array_sum($taxAmountArray);
4254 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4257 // update line item of contrbution
4258 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4259 $taxRate = $taxRates[$params['financial_type_id']];
4260 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate, $unknownIfMoneyIsClean);
4261 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4268 * Check financial type validation on update of a contribution.
4270 * @param int $financialTypeId
4271 * Value of latest Financial Type.
4273 * @param int $contributionId
4276 * @param array $errors
4281 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4282 if (!empty($financialTypeId)) {
4283 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4284 if ($oldFinancialTypeId == $financialTypeId) {
4288 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4290 '1' => [$contributionId, 'Integer'],
4292 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4293 if ($result->N
> 1) {
4294 $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.');
4299 * Update related pledge payment payments.
4301 * This function has been refactored out of the back office contribution form and may
4302 * still overlap with other functions.
4304 * @param string $action
4305 * @param int $pledgePaymentID
4306 * @param int $contributionID
4307 * @param bool $adjustTotalAmount
4308 * @param float $total_amount
4309 * @param float $original_total_amount
4310 * @param int $contribution_status_id
4311 * @param int $original_contribution_status_id
4313 public static function updateRelatedPledge(
4319 $original_total_amount,
4320 $contribution_status_id,
4321 $original_contribution_status_id
4323 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4327 if ($pledgePaymentID) {
4328 //store contribution id in payment record.
4329 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4332 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4339 if (!$pledgePaymentID) {
4342 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4348 $updatePledgePaymentStatus = FALSE;
4350 // If either the status or the amount has changed we update the pledge status.
4351 if ($action & CRM_Core_Action
::ADD
) {
4352 $updatePledgePaymentStatus = TRUE;
4354 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4355 ($original_total_amount != $total_amount))
4357 $updatePledgePaymentStatus = TRUE;
4360 if ($updatePledgePaymentStatus) {
4361 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4363 $contribution_status_id,
4372 * Compute the stats values
4374 * @param string $stat either 'mode' or 'median'
4375 * @param string $sql
4376 * @param string $alias of civicrm_contribution
4378 * @return array|null
4382 public static function computeStats($stat, $sql, $alias = NULL) {
4383 CRM_Core_Error
::deprecatedFunctionWarning('computeStats is now deprecated');
4388 * Is there only one line item attached to the contribution.
4394 * @throws \CiviCRM_API3_Exception
4396 public static function isSingleLineItem($id) {
4397 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
4398 return ($lineItemCount == 1);
4402 * Complete an order.
4404 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4406 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4408 * Moving it out of the BaseIPN class is just the first step.
4410 * @param array $input
4412 * @param array $objects
4413 * @param CRM_Core_Transaction $transaction
4415 * @param CRM_Contribute_BAO_Contribution $contribution
4416 * @param bool $isPostPaymentCreate
4417 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
4418 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
4419 * transitioning related elements).
4422 * @throws \CRM_Core_Exception
4423 * @throws \CiviCRM_API3_Exception
4425 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isPostPaymentCreate = FALSE) {
4426 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4427 // The previous details are used when calculating line items so keep it before any code that 'does something'
4428 if (!empty($contribution->id
)) {
4429 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(['id' => $contribution->id
]);
4431 $inputContributionWhiteList = [
4436 'payment_instrument_id',
4441 'contribution_status_id',
4445 if (self
::isSingleLineItem($primaryContributionID)) {
4446 $inputContributionWhiteList[] = 'financial_type_id';
4449 $participant = CRM_Utils_Array
::value('participant', $objects);
4450 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4451 $recurringContributionID = (empty($recurContrib->id
)) ?
NULL : $recurContrib->id
;
4452 $event = CRM_Utils_Array
::value('event', $objects);
4454 $paymentProcessorId = '';
4455 if (isset($objects['paymentProcessor'])) {
4456 if (is_array($objects['paymentProcessor'])) {
4457 $paymentProcessorId = $objects['paymentProcessor']['id'];
4460 $paymentProcessorId = $objects['paymentProcessor']->id
;
4464 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4466 $contributionParams = array_merge([
4467 'contribution_status_id' => $completedContributionStatusID,
4468 'source' => self
::getRecurringContributionDescription($contribution, $event),
4469 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4472 // CRM-20678 Ensure that the currency is correct in subseqent transcations.
4473 if (empty($contributionParams['currency']) && isset($objects['first_contribution']->currency
)) {
4474 $contributionParams['currency'] = $objects['first_contribution']->currency
;
4477 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
4479 // If paymentProcessor is not set then the payment_instrument_id would not be correct.
4480 // not clear when or if this would occur if you encounter this please fix here & add a unit test.
4481 if (empty($contributionParams['payment_instrument_id']) && isset($contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'])) {
4482 $contributionParams['payment_instrument_id'] = $contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'];
4485 if ($recurringContributionID) {
4486 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4488 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4490 if (empty($contributionParams['receive_date']) && $changeDate) {
4491 $contributionParams['receive_date'] = $changeDate;
4494 self
::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
4495 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4498 if (isset($input['is_email_receipt'])) {
4499 $values['is_email_receipt'] = $input['is_email_receipt'];
4502 if ($input['component'] == 'contribute') {
4503 if ($contribution->contribution_page_id
) {
4504 // Figure out what we gain from this.
4505 // Note that we may have overwritten the is_email_receipt input, fix that below.
4506 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4508 elseif ($recurContrib && $recurringContributionID) {
4509 $values['amount'] = $recurContrib->amount
;
4510 $values['financial_type_id'] = $objects['contributionType']->id
;
4511 $values['title'] = $source = ts('Offline Recurring Contribution');
4514 if (isset($input['is_email_receipt'])) {
4515 // CRM-19601 - we may have overwritten this above.
4516 $values['is_email_receipt'] = $input['is_email_receipt'];
4518 elseif ($recurContrib && $recurringContributionID) {
4519 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4520 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4521 // 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
4522 // Instance that had the table added via an upgrade in 4.1
4523 // see also https://github.com/civicrm/civicrm-svn/commit/7f39befd60bc735408d7866b02b3ac7fff1d4eea#diff-9ad8e290180451a2d6eacbd3d1ca7966R354
4524 // https://lab.civicrm.org/dev/core/issues/1245
4525 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4528 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4529 self
::updateMembershipBasedOnCompletionOfContribution(
4531 $primaryContributionID,
4537 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4538 if ($event->is_email_confirm
) {
4539 // @todo this should be set by the function that sends the mail after sending.
4540 $contributionParams['receipt_date'] = $changeDate;
4542 $participantParams['id'] = $participant->id
;
4543 $participantParams['status_id'] = 'Registered';
4544 civicrm_api3('Participant', 'create', $participantParams);
4548 $contributionParams['id'] = $contribution->id
;
4549 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
4551 // CRM-19309 - if you update the contribution here with financial_type_id it can/will mess with $lineItem
4552 // unsetting it here does NOT cause any other contribution test to fail!
4553 unset($contributionParams['financial_type_id']);
4554 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4556 // Add new soft credit against current $contribution.
4557 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
4558 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4561 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
4562 'labelColumn' => 'name',
4565 if (isset($input['prevContribution']) && (!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4566 $input['payment_processor'] = $paymentProcessorId;
4569 if (!empty($contribution->_relatedObjects
['participant'])) {
4570 $input['contribution_mode'] = 'participant';
4571 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4573 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4574 // @todo - use getRelatedMemberships instead
4575 $input['contribution_mode'] = 'membership';
4576 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4577 $contribution->trxn_id
= CRM_Utils_Array
::value('trxn_id', $input);
4578 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4581 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4582 $transaction->commit();
4584 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution->id
, $recurringContributionID,
4585 $contributionParams['contribution_status_id'], $input['amount']);
4587 // create an activity record
4588 if ($input['component'] == 'contribute') {
4590 $targetContactID = NULL;
4591 if (!empty($ids['related_contact'])) {
4592 $targetContactID = $contribution->contact_id
;
4593 $contribution->contact_id
= $ids['related_contact'];
4595 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4598 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4599 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4600 if (!array_key_exists('is_email_receipt', $values) ||
4601 $values['is_email_receipt'] == 1
4603 civicrm_api3('Contribution', 'sendconfirmation', [
4604 'id' => $contribution->id
,
4605 'payment_processor_id' => $paymentProcessorId,
4607 CRM_Core_Error
::debug_log_message("Receipt sent");
4610 CRM_Core_Error
::debug_log_message("Success: Database updated");
4611 return $contributionResult;
4615 * Send receipt from contribution.
4617 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4619 * Note that the compose message part has been moved to contribution
4620 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4622 * @param array $input
4623 * Incoming data from Payment processor.
4625 * Related object IDs.
4626 * @param int $contributionID
4627 * @param array $values
4628 * Values related to objects that have already been loaded.
4629 * @param bool $returnMessageText
4630 * Should text be returned instead of sent. This.
4631 * is because the function is also used to generate pdfs
4634 * @throws \CRM_Core_Exception
4635 * @throws \CiviCRM_API3_Exception
4637 public static function sendMail(&$input, &$ids, $contributionID, &$values,
4638 $returnMessageText = FALSE) {
4640 $contribution = new CRM_Contribute_BAO_Contribution();
4641 $contribution->id
= $contributionID;
4642 if (!$contribution->find(TRUE)) {
4643 throw new CRM_Core_Exception('Contribution does not exist');
4645 $contribution->loadRelatedObjects($input, $ids, TRUE);
4646 // set receipt from e-mail and name in value
4647 if (!$returnMessageText) {
4648 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4650 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4651 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4652 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4653 civicrm_api3('Contribution', 'create', [
4654 'receipt_date' => 'now',
4655 'id' => $contribution->id
,
4662 * Generate From email and from name in an array values
4664 * @param array $input
4665 * @param \CRM_Contribute_BAO_Contribution $contribution
4669 public static function generateFromEmailAndName($input, $contribution) {
4670 // Use input value if supplied.
4671 if (!empty($input['receipt_from_email'])) {
4673 CRM_Utils_Array
::value('receipt_from_name', $input, ''),
4674 $input['receipt_from_email'],
4677 // if we are still empty see if we can use anything from a contribution page.
4679 if (!empty($contribution->contribution_page_id
)) {
4680 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id
]);
4682 // if we are still empty see if we can use anything from a contribution page.
4683 if (!empty($pageValues['receipt_from_email'])) {
4685 CRM_Utils_Array
::value('receipt_from_name', $pageValues),
4686 $pageValues['receipt_from_email'],
4689 // If we are still empty fall back to the domain or logged in user information.
4690 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4694 * Generate credit note id with next avaible number
4699 public static function createCreditNoteId() {
4700 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4702 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution WHERE creditnote_id IS NOT NULL");
4703 $creditNoteId = NULL;
4707 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4708 $result = civicrm_api3('Contribution', 'getcount', [
4710 'creditnote_id' => $creditNoteId,
4712 } while ($result > 0);
4714 return $creditNoteId;
4718 * Load related memberships.
4722 * @return array $ids
4727 * Note that in theory it should be possible to retrieve these from the line_item table
4728 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4729 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4730 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4731 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4733 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4736 public function loadRelatedMembershipObjects($ids = []) {
4738 SELECT membership_id
4739 FROM civicrm_membership_payment
4740 WHERE contribution_id = %1 ";
4741 $params = [1 => [$this->id
, 'Integer']];
4742 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, []);
4744 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4745 while ($dao->fetch()) {
4746 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4747 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4751 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4752 foreach ($ids['membership'] as $id) {
4754 $membership = new CRM_Member_BAO_Membership();
4755 $membership->id
= $id;
4756 if (!$membership->find(TRUE)) {
4757 throw new Exception("Could not find membership record: $id");
4759 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4760 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4761 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4762 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4770 * This function is used to record partial payments for contribution
4772 * @param array $contribution
4774 * @param array $params
4776 * @return CRM_Financial_DAO_FinancialTrxn
4778 public static function recordPartialPayment($contribution, $params) {
4779 CRM_Core_Error
::deprecatedFunctionWarning('use payment create api');
4780 $balanceTrxnParams['to_financial_account_id'] = self
::getToFinancialAccount($contribution, $params);
4781 $balanceTrxnParams['from_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($contribution['financial_type_id'], 'Accounts Receivable Account is');
4782 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4783 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4784 $balanceTrxnParams['trxn_date'] = CRM_Utils_Array
::value('trxn_date', $params, CRM_Utils_Array
::value('contribution_receive_date', $params, date('YmdHis')));
4785 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4786 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4787 $balanceTrxnParams['currency'] = $contribution['currency'];
4788 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4789 $balanceTrxnParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_FinancialTrxn', 'status_id', 'Completed');
4790 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4791 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4792 $balanceTrxnParams['is_payment'] = 1;
4794 if (!empty($params['payment_processor'])) {
4795 // I can't find evidence this is passed in - I was gonna just remove it but decided to deprecate as I see self::getToFinancialAccount
4796 // also anticipates it.
4797 CRM_Core_Error
::deprecatedFunctionWarning('passing payment_processor is deprecated - use payment_processor_id');
4798 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4800 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4804 * Get the description (source field) for the recurring contribution.
4806 * @param CRM_Contribute_BAO_Contribution $contribution
4807 * @param CRM_Event_DAO_Event|null $event
4810 * @throws \CiviCRM_API3_Exception
4812 protected static function getRecurringContributionDescription($contribution, $event) {
4813 if (!empty($contribution->source
)) {
4814 return $contribution->source
;
4816 elseif (!empty($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
4817 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', [
4818 'id' => $contribution->contribution_page_id
,
4819 'return' => 'title',
4821 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4824 return ts('Online Event Registration') . ': ' . $event->title
;
4826 elseif (!empty($contribution->contribution_recur_id
)) {
4827 return 'recurring contribution';
4833 * Function to add payments for contribution
4834 * for Partially Paid status
4836 * @param array $contributions
4837 * @param string $contributionStatusId
4840 public static function addPayments($contributions, $contributionStatusId = NULL) {
4841 // get financial trxn which is a payment
4842 $ftSql = "SELECT ft.id, ft.total_amount
4843 FROM civicrm_financial_trxn ft
4844 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
4845 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
4846 $contributionStatus = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
4847 'labelColumn' => 'name',
4849 foreach ($contributions as $contribution) {
4850 if (!($contributionStatus[$contribution->contribution_status_id
] == 'Partially paid'
4851 || CRM_Utils_Array
::value($contributionStatusId, $contributionStatus) == 'Partially paid')
4855 $ftDao = CRM_Core_DAO
::executeQuery($ftSql, [
4863 // store financial item Proportionaly.
4865 'total_amount' => $ftDao->total_amount
,
4866 'contribution_id' => $contribution->id
,
4868 self
::assignProportionalLineItems($trxnParams, $ftDao->id
, $contribution->total_amount
);
4873 * Function use to store line item proportionally in in entity financial trxn table
4875 * @param array $trxnParams
4877 * @param int $trxnId
4879 * @param float $contributionTotalAmount
4881 * @throws \CiviCRM_API3_Exception
4883 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4884 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4885 if (!empty($lineItems)) {
4886 // get financial item
4887 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4889 'contribution_total_amount' => $contributionTotalAmount,
4890 'trxn_total_amount' => $trxnParams['total_amount'],
4891 'trxn_id' => $trxnId,
4893 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4898 * Checks if line items total amounts
4899 * match the contribution total amount.
4901 * @param array $params
4902 * array of order params.
4904 * @throws \API_Exception
4906 public static function checkLineItems(&$params) {
4907 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
4908 $lineItemAmount = 0;
4910 foreach ($params['line_items'] as &$lineItems) {
4911 foreach ($lineItems['line_item'] as &$item) {
4912 if (empty($item['financial_type_id'])) {
4913 $item['financial_type_id'] = $params['financial_type_id'];
4915 $lineItemAmount +
= $item['line_total'] + CRM_Utils_Array
::value('tax_amount', $item, 0.00);
4919 if (!isset($totalAmount)) {
4920 $params['total_amount'] = $lineItemAmount;
4923 $currency = CRM_Utils_Array
::value('currency', $params, '');
4925 if (empty($currency)) {
4926 $currency = CRM_Core_Config
::singleton()->defaultCurrency
;
4929 if (!CRM_Utils_Money
::equals($totalAmount, $lineItemAmount, $currency)) {
4930 throw new CRM_Contribute_Exception_CheckLineItemsException();
4936 * Get the financial account for the item associated with the new transaction.
4938 * @param array $params
4939 * @param int $default
4943 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
4945 if (!empty($params['financial_account_id'])) {
4946 return $params['financial_account_id'];
4949 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4950 $preferredAccountsRelationships = [
4951 'Refunded' => 'Credit/Contra Revenue Account is',
4952 'Chargeback' => 'Chargeback Account is',
4955 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4956 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4957 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4959 $preferredAccountsRelationships[$contributionStatus]
4967 * ContributionPage values were being imposed onto values.
4969 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4970 * REALLY didn't want superimposed. The rest are left there in their overkill out
4973 * The rationale for making this explicit is that it was a case of carefully set values being
4974 * seemingly randonly overwritten without much care. In general I think array randomly setting
4975 * variables en mass is risky.
4977 * @param array $values
4981 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4982 $contributionPageValues = [];
4983 CRM_Contribute_BAO_ContributionPage
::setValues(
4984 $this->contribution_page_id
,
4985 $contributionPageValues
4988 // These are the values that I believe to be useful.
4991 'pay_later_receipt',
4993 'receipt_from_email',
4994 'receipt_from_name',
4998 'honoree_profile_id',
4999 'onbehalf_profile_id',
5000 'honor_block_is_active',
5001 // Kinda might be - but would be on the contribution...
5004 // Included for 'fear of regression' but can't justify any use for these....
5006 'payment_processor',
5007 'financial_type_id',
5008 'amount_block_is_active',
5013 'default_amount_id',
5017 'initial_amount_help_text',
5018 'initial_amount_label',
5020 'is_allow_other_amount',
5021 'is_billing_required',
5022 'is_confirm_enabled',
5023 'is_credit_card_only',
5025 'is_partial_payment',
5026 'is_recur_installments',
5027 'is_recur_interval',
5031 'min_initial_amount',
5032 'recur_frequency_unit',
5039 foreach ($valuesToCopy as $valueToCopy) {
5040 if (isset($contributionPageValues[$valueToCopy])) {
5041 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
5048 * Get values of CiviContribute Settings
5049 * and check if its enabled or not.
5050 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
5051 * in serialized form. Usually this should be stored as flat settings for each form fields
5052 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
5053 * settings we will live with an inconsistency because it's too hard to change for now.
5054 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
5057 * @param string $name
5058 * @param bool $checkInvoicing
5062 public static function checkContributeSettings($name = NULL, $checkInvoicing = FALSE) {
5063 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
5065 if ($checkInvoicing && empty($contributeSettings['invoicing'])) {
5070 return CRM_Utils_Array
::value($name, $contributeSettings);
5072 return $contributeSettings;
5076 * This function process contribution related objects.
5078 * @param int $contributionId
5079 * @param int $statusId
5080 * @param int|null $previousStatusId
5082 * @param string $receiveDate
5084 * @return null|string
5086 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
5088 if (!$contributionId ||
!$statusId) {
5093 'contribution_id' => $contributionId,
5094 'contribution_status_id' => $statusId,
5095 'previous_contribution_status_id' => $previousStatusId,
5096 'receive_date' => $receiveDate,
5099 $updateResult = CRM_Contribute_BAO_Contribution
::transitionComponents($params);
5101 if (!is_array($updateResult) ||
5102 !($updatedComponents = CRM_Utils_Array
::value('updatedComponents', $updateResult)) ||
5103 !is_array($updatedComponents) ||
5104 empty($updatedComponents)
5109 // get the user display name.
5111 SELECT display_name as displayName
5112 FROM civicrm_contact
5113 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
5114 WHERE civicrm_contribution.id = {$contributionId}";
5115 $userDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
5117 // get the status message for user.
5118 foreach ($updatedComponents as $componentName => $updatedStatusId) {
5120 if ($componentName == 'CiviMember') {
5121 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5122 CRM_Member_PseudoConstant
::membershipStatus()
5125 $statusNameMsgPart = 'updated';
5126 switch ($updatedStatusName) {
5129 $statusNameMsgPart = $updatedStatusName;
5133 $statusMsg .= "<br />" . ts("Membership for %1 has been %2.", [
5134 1 => $userDisplayName,
5135 2 => $statusNameMsgPart,
5139 if ($componentName == 'CiviEvent') {
5140 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5141 CRM_Event_PseudoConstant
::participantStatus()
5143 if ($updatedStatusName == 'Cancelled') {
5144 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", [1 => $userDisplayName]);
5146 elseif ($updatedStatusName == 'Registered') {
5147 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", [1 => $userDisplayName]);
5151 if ($componentName == 'CiviPledge') {
5152 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5153 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name')
5155 if ($updatedStatusName == 'Cancelled') {
5156 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", [1 => $userDisplayName]);
5158 elseif ($updatedStatusName == 'Failed') {
5159 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", [1 => $userDisplayName]);
5161 elseif ($updatedStatusName == 'Completed') {
5162 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", [1 => $userDisplayName]);
5171 * Get the contribution as it is in the database before being updated.
5173 * @param int $contributionID
5175 * @return \CRM_Contribute_BAO_Contribution|null
5177 private static function getOriginalContribution($contributionID) {
5178 return self
::getValues(['id' => $contributionID]);
5182 * Get the amount for the financial item row.
5184 * Helper function to start to break down recordFinancialTransactions for readability.
5186 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
5188 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
5189 * for historical reasons. Going forwards we can hope to add tests & improve readibility
5192 * @param array $params
5193 * Params as passed to contribution.create
5195 * @param string $context
5196 * changeFinancialType| changedAmount
5197 * @param array $lineItemDetails
5199 * @param bool $isARefund
5200 * Is this a refund / negative transaction.
5201 * @param int $previousLineItemTotal
5204 * @todo move recordFinancialAccounts & helper functions to their own class?
5207 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
5208 if ($context == 'changedAmount') {
5209 $lineTotal = $lineItemDetails['line_total'];
5210 if ($lineTotal != $previousLineItemTotal) {
5211 $lineTotal -= $previousLineItemTotal;
5215 elseif ($context == 'changeFinancialType') {
5216 return -$lineItemDetails['line_total'];
5218 elseif ($context == 'changedStatus') {
5219 $cancelledTaxAmount = 0;
5221 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
5223 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
5225 elseif ($context === NULL) {
5226 // erm, yes because? but, hey, it's tested.
5227 return $lineItemDetails['line_total'];
5229 elseif (empty($lineItemDetails['line_total'])) {
5230 // follow legacy code path
5232 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', ['civi.tag' => 'deprecated']);
5233 return $params['total_amount'];
5236 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
5241 * Get the multiplier for adjusting rows.
5243 * If we are dealing with a refund or cancellation then it will be a negative
5244 * amount to reflect the negative transaction.
5246 * If we are changing Financial Type it will be a negative amount to
5247 * adjust down the old type.
5249 * @param int $contribution_status_id
5250 * @param string $context
5254 protected static function getMultiplier($contribution_status_id, $context) {
5255 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
5262 * Does this transaction reflect a payment instrument change.
5264 * @param array $params
5265 * @param array $pendingStatuses
5269 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
5270 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
5272 if (array_key_exists('payment_instrument_id', $params)) {
5273 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
5274 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
5276 //check if status is changed from Pending to Completed
5277 // do not update payment instrument changes for Pending to Completed
5278 if (!($contributionStatus == 'Completed' &&
5279 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
5284 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
5285 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
5286 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
5290 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
5291 $params['contribution']->check_number
!= $params['prevContribution']->check_number
5293 // another special case when check number is changed, create new financial records
5294 // create financial trxn with negative amount
5302 * Update the memberships associated with a contribution if it has been completed.
5304 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
5305 * load them in this function. Code clean up would compensate for any minor performance implication.
5307 * @param \CRM_Contribute_BAO_Contribution $contribution
5308 * @param int $primaryContributionID
5309 * @param string $changeDate
5311 * @throws \CRM_Core_Exception
5312 * @throws \CiviCRM_API3_Exception
5314 public static function updateMembershipBasedOnCompletionOfContribution($contribution, $primaryContributionID, $changeDate) {
5315 $memberships = self
::getRelatedMemberships($contribution->id
);
5316 foreach ($memberships as $membership) {
5317 $membershipParams = [
5318 'id' => $membership['id'],
5319 'contact_id' => $membership['contact_id'],
5320 'is_test' => $membership['is_test'],
5321 'membership_type_id' => $membership['membership_type_id'],
5322 'membership_activity_status' => 'Completed',
5325 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
5326 $membershipParams['membership_type_id'],
5327 $membershipParams['is_test'],
5328 $membershipParams['id']
5331 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
5332 // this picks up membership type changes during renewals
5333 // @todo this is almost certainly an obsolete sql call, the pre-change
5334 // membership is accessible via $this->_relatedObjects
5336 SELECT membership_type_id
5337 FROM civicrm_membership_log
5338 WHERE membership_id={$membershipParams['id']}
5341 $dao = CRM_Core_DAO
::executeQuery($sql);
5342 if ($dao->fetch()) {
5343 if (!empty($dao->membership_type_id
)) {
5344 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
5347 if (empty($membership['end_date']) ||
(int) $membership['status_id'] !== CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
5348 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
5349 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
5350 // 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.
5351 // @todo once apiv4 ships with core switch to that & find sanity.
5352 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
5353 $membershipParams['membership_type_id'],
5354 $primaryContributionID
5357 // @todo remove all this stuff in favour of letting the api call further down handle in
5358 // (it is a duplication of what the api does).
5359 $dates = array_fill_keys([
5364 if ($currentMembership) {
5366 * Fixed FOR CRM-4433
5367 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
5368 * when Contribution mode is notify and membership is for renewal )
5370 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
5372 // @todo - we should pass membership_type_id instead of null here but not
5373 // adding as not sure of testing
5374 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
5375 $changeDate, NULL, $membershipParams['num_terms']
5377 $dates['join_date'] = $currentMembership['join_date'];
5380 //get the status for membership.
5381 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
5383 $dates['join_date'],
5386 $membershipParams['membership_type_id'],
5390 unset($dates['end_date']);
5391 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
5392 //we might be renewing membership,
5393 //so make status override false.
5394 $membershipParams['is_override'] = FALSE;
5395 $membershipParams['status_override_end_date'] = 'null';
5397 //CRM-17723 - reset static $relatedContactIds array()
5398 // @todo move it to Civi Statics.
5400 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
5401 civicrm_api3('Membership', 'create', $membershipParams);
5406 * Get payment links as they relate to a contribution.
5408 * If a payment can be made then include a payment link & if a refund is appropriate
5409 * then a refund link.
5412 * @param float $balance
5413 * @param string $contributionStatus
5416 * $actionLinks Links array containing:
5420 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
5421 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
5422 // In general the balance is the best way to determine if a payment can be added or not,
5423 // but not for Failed contributions, where we don't accept additional payments at the moment.
5424 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
5425 // do accept more payments agains them.
5429 if ((int) $balance > 0) {
5430 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
5432 'url' => CRM_Utils_System
::url('civicrm/payment', [
5438 'title' => ts('Submit Credit Card payment'),
5442 'url' => CRM_Utils_System
::url('civicrm/payment', [
5447 'title' => ts('Record Payment'),
5450 elseif ((int) $balance < 0) {
5452 'url' => CRM_Utils_System
::url('civicrm/payment', [
5457 'title' => ts('Record Refund'),
5460 return $actionLinks;
5464 * Get a query to determine the amount donated by the contact/s in the current financial year.
5466 * @param array $contactIDs
5470 public static function getAnnualQuery($contactIDs) {
5471 $contactIDs = implode(',', $contactIDs);
5472 $config = CRM_Core_Config
::singleton();
5473 $currentMonth = date('m');
5474 $currentDay = date('d');
5476 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
5478 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
5479 (int) $config->fiscalYearStart
['d'] > $currentDay
5482 $year = date('Y') - 1;
5487 $nextYear = $year +
1;
5489 if ($config->fiscalYearStart
) {
5490 $newFiscalYearStart = $config->fiscalYearStart
;
5491 if ($newFiscalYearStart['M'] < 10) {
5492 // This is just a clumsy way of adding padding.
5493 // @todo next round look for a nicer way.
5494 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
5496 if ($newFiscalYearStart['d'] < 10) {
5497 // This is just a clumsy way of adding padding.
5498 // @todo next round look for a nicer way.
5499 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
5501 $config->fiscalYearStart
= $newFiscalYearStart;
5502 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
5505 // First of January.
5508 $startDate = "$year$monthDay";
5509 $endDate = "$nextYear$monthDay";
5512 'contact_id' => 'IN (' . $contactIDs . ')',
5513 'is_test' => ' = 0',
5514 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
5516 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
5517 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
5520 foreach ($whereClauses as $key => $clause) {
5521 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
5523 $whereClauseString = implode(' AND ', $clauses);
5525 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5526 // this group by + having on contribution_status_id improves performance
5528 SELECT COUNT(*) as count,
5529 SUM(total_amount) as amount,
5530 AVG(total_amount) as average,
5532 FROM civicrm_contribution b
5533 WHERE " . $whereClauseString . "
5534 GROUP BY currency, contribution_status_id
5535 HAVING $havingClause
5541 * Assign Test Value.
5543 * @param string $fieldName
5544 * @param array $fieldDef
5545 * @param int $counter
5547 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5548 if ($fieldName == 'tax_amount') {
5549 $this->{$fieldName} = "0.00";
5551 elseif ($fieldName == 'net_amount') {
5552 $this->{$fieldName} = "2.00";
5554 elseif ($fieldName == 'total_amount') {
5555 $this->{$fieldName} = "3.00";
5557 elseif ($fieldName == 'fee_amount') {
5558 $this->{$fieldName} = "1.00";
5561 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5566 * Check if contribution has participant/membership payment.
5568 * @param int $contributionId
5573 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5574 // get line item for contribution
5575 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5576 // check if line item is for membership or participant
5577 foreach ($lineItems as $items) {
5578 if ($items['entity_table'] == 'civicrm_participant') {
5582 elseif ($items['entity_table'] == 'civicrm_membership') {
5594 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5596 * @param array $trxnParams
5597 * Financial trxn params
5598 * @param array $contributionParams
5599 * Contribution Params
5603 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5604 if (!Civi
::settings()->get('always_post_to_accounts_receivable')) {
5607 $statusId = $contributionParams['contribution']->contribution_status_id
;
5608 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5609 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5610 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5611 // Return if contribution status is not completed.
5612 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5613 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5614 && $contributionParams['prevContribution']->is_pay_later
== 0
5620 $params = $trxnParams;
5621 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $contributionParams) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5622 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5623 $params['to_financial_account_id'] = $arAccountId;
5624 $params['status_id'] = array_search('Pending', $contributionStatuses);
5625 $params['is_payment'] = FALSE;
5626 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5627 self
::$_trxnIDs[] = $trxn->id
;
5628 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5632 * Calculate financial item amount when contribution is updated.
5634 * @param array $params
5635 * contribution params
5636 * @param array $amountParams
5638 * @param string $context
5642 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5643 if (!empty($params['is_quick_config'])) {
5644 $amount = $amountParams['item_amount'];
5646 $amount = $params['total_amount'];
5647 if ($context === NULL) {
5648 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5653 $amount = $amountParams['line_total'];
5654 if ($context == 'changedAmount') {
5655 $amount -= $amountParams['previous_line_total'];
5657 $amount *= $amountParams['diff'];
5663 * Retrieve Sales Tax Financial Accounts.
5669 public static function getSalesTaxFinancialAccounts() {
5670 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5671 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5672 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5673 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5674 $queryParams = [1 => [$accountRel, 'Integer']];
5675 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5676 $financialAccount = [];
5677 while ($dao->fetch()) {
5678 $financialAccount[$dao->id
] = $dao->id
;
5680 return $financialAccount;
5684 * Create tax entry in civicrm_entity_financial_trxn table.
5686 * @param array $entityParams
5688 * @param array $eftParams
5690 * @throws \CiviCRM_API3_Exception
5692 public static function createProportionalEntry($entityParams, $eftParams) {
5694 if ($entityParams['contribution_total_amount'] != 0) {
5695 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5697 // Record Entity Financial Trxn; CRM-20145
5698 $eftParams['amount'] = CRM_Contribute_BAO_Contribution_Utils
::formatAmount($paid);
5699 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5703 * Create array of last financial item id's.
5705 * @param int $contributionId
5709 public static function getLastFinancialItemIds($contributionId) {
5710 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5711 FROM civicrm_financial_item fi
5712 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5713 WHERE li.contribution_id = %1";
5714 $dao = CRM_Core_DAO
::executeQuery($sql, [
5720 $ftIds = $taxItems = [];
5721 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5722 while ($dao->fetch()) {
5723 /* if sales tax item*/
5724 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5725 $taxItems[$dao->price_field_value_id
] = [
5726 'financial_item_id' => $dao->id
,
5727 'amount' => $dao->tax_amount
,
5731 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5734 return [$ftIds, $taxItems];
5738 * Create proportional entries in civicrm_entity_financial_trxn.
5740 * @param array $entityParams
5742 * @param array $lineItems
5744 * @param array $ftIds
5746 * @param array $taxItems
5748 * @throws \CiviCRM_API3_Exception
5750 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5752 'entity_table' => 'civicrm_financial_item',
5753 'financial_trxn_id' => $entityParams['trxn_id'],
5755 foreach ($lineItems as $key => $value) {
5756 if ($value['qty'] == 0) {
5759 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5760 $entityParams['line_item_amount'] = $value['line_total'];
5761 self
::createProportionalEntry($entityParams, $eftParams);
5762 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5763 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5764 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5765 self
::createProportionalEntry($entityParams, $eftParams);
5771 * Load entities related to the contribution into $this->_relatedObjects.
5775 * @throws \CRM_Core_Exception
5777 protected function loadRelatedEntitiesByID($ids) {
5779 'contact' => 'CRM_Contact_BAO_Contact',
5780 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5781 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5782 'financialType' => 'CRM_Financial_BAO_FinancialType',
5783 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5785 foreach ($entities as $entity => $bao) {
5786 if (!empty($ids[$entity])) {
5787 $this->_relatedObjects
[$entity] = new $bao();
5788 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5789 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5790 throw new CRM_Core_Exception($entity . ' could not be loaded');
5797 * Should an email receipt be sent for this contribution when complete.
5799 * @param array $input
5803 protected function isEmailReceipt($input) {
5804 if (isset($input['is_email_receipt'])) {
5805 return $input['is_email_receipt'];
5807 if (!empty($this->_relatedObjects
['contribution_page_id'])) {
5808 return $this->_relatedObjects
['contribution_page_id']->is_email_receipt
;
5814 * Function to replace contribution tokens.
5816 * @param array $contributionIds
5818 * @param string $subject
5820 * @param array $subjectToken
5822 * @param string $text
5824 * @param string $html
5826 * @param array $messageToken
5828 * @param bool $escapeSmarty
5831 * @throws \CiviCRM_API3_Exception
5833 public static function replaceContributionTokens(
5842 if (empty($contributionIds)) {
5845 $contributionDetails = [];
5846 foreach ($contributionIds as $id) {
5847 $result = self
::getContributionTokenValues($id, $messageToken);
5848 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5849 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5850 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5852 return $contributionDetails;
5856 * Get the contribution fields for $id and display labels where
5857 * appropriate (if the token is present).
5860 * @param array $messageToken
5863 public static function getContributionTokenValues($id, $messageToken) {
5867 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5868 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5869 if (!empty($messageToken)) {
5870 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5871 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5872 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField
::displayValue($result['values'][$id][$fieldName], $fieldName);
5880 * Get invoice_number for contribution.
5882 * @param int $contributionID
5886 public static function getInvoiceNumber($contributionID) {
5887 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix', TRUE)) {
5888 return $invoicePrefix . $contributionID;
5895 * Load the values needed for the event message.
5897 * @param int $eventID
5898 * @param int $participantID
5899 * @param int|null $contributionID
5902 * @throws \CRM_Core_Exception
5904 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5909 $values = ['event' => []];
5911 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
5912 // add custom fields for event
5913 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $eventID);
5915 $eventCustomGroup = [];
5916 foreach ($eventGroupTree as $key => $group) {
5917 if ($key === 'info') {
5921 foreach ($group['fields'] as $k => $customField) {
5922 $groupLabel = $group['title'];
5923 if (!empty($customField['customValue'])) {
5924 foreach ($customField['customValue'] as $customFieldValues) {
5925 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
5930 $values['event']['customGroup'] = $eventCustomGroup;
5932 //get participant details
5933 $participantParams = [
5934 'id' => $participantID,
5937 $values['participant'] = [];
5939 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
5940 // add custom fields for event
5941 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $participantID);
5942 $participantCustomGroup = [];
5943 foreach ($participantGroupTree as $key => $group) {
5944 if ($key === 'info') {
5948 foreach ($group['fields'] as $k => $customField) {
5949 $groupLabel = $group['title'];
5950 if (!empty($customField['customValue'])) {
5951 foreach ($customField['customValue'] as $customFieldValues) {
5952 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
5957 $values['participant']['customGroup'] = $participantCustomGroup;
5959 //get location details
5961 'entity_id' => $eventID,
5962 'entity_table' => 'civicrm_event',
5964 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
5967 'entity_table' => 'civicrm_event',
5968 'entity_id' => $eventID,
5969 'module' => 'CiviEvent',
5972 list($custom_pre_id,
5974 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
5976 $values['custom_pre_id'] = $custom_pre_id;
5977 $values['custom_post_id'] = $custom_post_ids;
5979 // set lineItem for event contribution
5980 if ($contributionID) {
5981 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($contributionID);
5982 if (!empty($participantIds)) {
5983 foreach ($participantIds as $pIDs) {
5984 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
5985 if (!CRM_Utils_System
::isNull($lineItem)) {
5986 $values['lineItem'][] = $lineItem;