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 static $_importableFields = NULL;
43 * Static field for all the contribution information that we can potentially export
47 static $_exportableFields = NULL;
50 * Static field to hold financial trxn id's.
54 static $_trxnIDs = NULL;
57 * Field for all the objects related to this contribution
58 * @var array of objects (e.g membership object, participant object)
60 public $_relatedObjects = array();
63 * Field for the component - either 'event' (participant) or 'contribute'
64 * (any item related to a contribution page e.g. membership, pledge, contribution)
65 * This is used for composing messages because they have dependency on the
66 * contribution_page or event page - although over time we may eliminate that
68 * @var string component or event
70 public $_component = NULL;
73 * Possibly obsolete variable.
75 * If you use it please explain why it is set in the create function here.
79 public $trxn_result_code;
84 public function __construct() {
85 parent
::__construct();
89 * Takes an associative array and creates a contribution object.
91 * the function extract all the params it needs to initialize the create a
92 * contribution object. the params array could contain additional unused name/value
95 * @param array $params
96 * (reference ) an assoc array of name/value pairs.
98 * The array that holds all the db ids.
100 * @return \CRM_Contribute_BAO_Contribution
101 * @throws \CRM_Core_Exception
103 public static function add(&$params, $ids = array()) {
104 if (empty($params)) {
107 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
108 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
109 $duplicates = array();
110 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
111 $message = ts("Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: " . implode(', ', $duplicates));
112 throw new CRM_Core_Exception($message);
115 // first clean up all the money fields
116 $moneyFields = array(
120 'non_deductible_amount',
123 //if priceset is used, no need to cleanup money
124 if (!empty($params['skipCleanMoney'])) {
128 // @todo put a deprecated here - this should be done in the form layer.
129 $params['skipCleanMoney'] = FALSE;
130 Civi
::log()->warning('Deprecated code path. Money should always be clean before it hits the BAO.', array('civi.tag' => 'deprecated'));
133 foreach ($moneyFields as $field) {
134 if (isset($params[$field])) {
135 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
139 //set defaults in create mode
140 if (!$contributionID) {
141 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
143 if (empty($params['invoice_number'])) {
144 $nextContributionID = CRM_Core_DAO
::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
145 $params['invoice_number'] = self
::getInvoiceNumber($nextContributionID);
149 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
150 //if contribution is created with cancelled or refunded status, add credit note id
151 if (!empty($params['contribution_status_id'])) {
152 // @todo - should we include Chargeback? If so use self::isContributionStatusNegative($params['contribution_status_id'])
153 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
154 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
156 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
157 $params['creditnote_id'] = self
::createCreditNoteId();
162 // Since the fee amount is expecting this (later on) ensure it is always set.
163 // It would only not be set for an update where it is unchanged.
164 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', array('id' => $contributionID, 'return' => 'contribution_status_id'));
168 && CRM_Utils_Array
::value('membership_id', $params)
169 && self
::checkContributeSettings('deferred_revenue_enabled')
171 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
172 if ($memberStartDate) {
173 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
176 self
::calculateMissingAmountParams($params, $contributionID);
178 if (!empty($params['payment_instrument_id'])) {
179 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
180 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
181 $params['check_number'] = 'null';
185 $setPrevContribution = TRUE;
186 // CRM-13964 partial payment
187 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])) {
188 $partialAmtTotal = $params['partial_payment_total'];
189 $partialAmtPay = $params['partial_amount_to_pay'];
190 $params['total_amount'] = $partialAmtTotal;
191 if ($partialAmtPay < $partialAmtTotal) {
192 $params['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Partially paid');
193 $params['is_pay_later'] = 0;
194 $setPrevContribution = FALSE;
197 if ($contributionID && $setPrevContribution) {
198 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
201 if ($contributionID && !empty($params['revenue_recognition_date']) && !empty($params['prevContribution'])
202 && !($contributionStatus[$params['prevContribution']->contribution_status_id
] == 'Pending')
203 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
205 unset($params['revenue_recognition_date']);
208 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
209 isset($params['financial_type_id']))) {
210 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
213 if ($contributionID) {
214 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
217 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
219 $contribution = new CRM_Contribute_BAO_Contribution();
220 $contribution->copyValues($params);
222 $contribution->id
= $contributionID;
224 if (empty($contribution->id
)) {
225 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
226 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
227 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
231 $result = $contribution->save();
233 // Add financial_trxn details as part of fix for CRM-4724
234 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
235 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
237 //add Account details
238 $params['contribution'] = $contribution;
239 self
::recordFinancialAccounts($params);
241 if (self
::isUpdateToRecurringContribution($params)) {
242 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
243 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
244 $contributionStatus[$params['contribution_status_id']],
245 CRM_Utils_Array
::value('receive_date', $params)
249 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
251 if ($contributionID) {
252 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
255 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
262 * Is this contribution updating an existing recurring contribution.
264 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
265 * pending payment is being confirmed (or failing).
267 * @param array $params
271 public static function isUpdateToRecurringContribution($params) {
272 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
275 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
278 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
281 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
282 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
289 * Get defaults for new entity.
292 public static function getDefaults() {
294 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
295 FALSE, FALSE, FALSE, 'AND is_default = 1')
297 'contribution_status_id' => CRM_Core_Pseudoconstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
302 * Fetch the object and store the values in the values array.
304 * @param array $params
305 * Input parameters to find object.
306 * @param array $values
307 * Output values of the object.
309 * The array that holds all the db ids.
311 * @return CRM_Contribute_BAO_Contribution|null
312 * The found object or null
314 public static function getValues($params, &$values, &$ids) {
315 if (empty($params)) {
318 $contribution = new CRM_Contribute_BAO_Contribution();
320 $contribution->copyValues($params);
322 if ($contribution->find(TRUE)) {
323 $ids['contribution'] = $contribution->id
;
325 CRM_Core_DAO
::storeValues($contribution, $values);
327 return $contribution;
329 $null = NULL; // return by reference
334 * Get the values and resolve the most common mappings.
336 * Since contribution status is resolved in almost every function that calls getValues it makes
337 * sense to have an extra function to resolve it rather than repeat the code.
339 * Think carefully before adding more mappings to be resolved as there could be performance implications
340 * if this function starts to be called from more iterative functions.
342 * @param array $params
343 * Input parameters to find object.
346 * Array of the found contribution.
347 * @throws CRM_Core_Exception
349 public static function getValuesWithMappings($params) {
350 $values = $ids = array();
351 $contribution = self
::getValues($params, $values, $ids);
352 if (is_null($contribution)) {
353 throw new CRM_Core_Exception('No contribution found');
355 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
360 * Calculate net_amount & fee_amount if they are not set.
362 * Net amount should be total - fee.
363 * This should only be called for new contributions.
365 * @param array $params
366 * Params for a new contribution before they are saved.
367 * @param int|null $contributionID
368 * Contribution ID if we are dealing with an update.
370 * @throws \CiviCRM_API3_Exception
372 public static function calculateMissingAmountParams(&$params, $contributionID) {
373 if (!$contributionID && !isset($params['fee_amount'])) {
374 if (isset($params['total_amount']) && isset($params['net_amount'])) {
375 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
378 $params['fee_amount'] = 0;
381 if (!isset($params['net_amount'])) {
382 if (!$contributionID) {
383 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
386 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
387 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
388 // net_amount may need adjusting.
389 $contribution = civicrm_api3('Contribution', 'getsingle', array(
390 'id' => $contributionID,
391 'return' => array('total_amount', 'net_amount', 'fee_amount'),
393 $totalAmount = isset($params['total_amount']) ?
$params['total_amount'] : CRM_Utils_Array
::value('total_amount', $contribution);
394 $feeAmount = isset($params['fee_amount']) ?
$params['fee_amount'] : CRM_Utils_Array
::value('fee_amount', $contribution);
395 $params['net_amount'] = $totalAmount - $feeAmount;
403 * @param $billingLocationTypeID
407 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
408 $hasBillingField = FALSE;
409 $billingFields = array(
417 //build address array
418 $addressParams = array();
419 $addressParams['location_type_id'] = $billingLocationTypeID;
420 $addressParams['is_billing'] = 1;
422 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
423 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
424 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
425 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
427 foreach ($billingFields as $value) {
428 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
429 if (!empty($addressParams[$value])) {
430 $hasBillingField = TRUE;
433 return array($hasBillingField, $addressParams);
437 * Get address params ready to be passed to the payment processor.
439 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
440 * To create an address we need state_province_id.
442 * @param array $params
443 * @param int $billingLocationTypeID
447 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
448 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
449 foreach ($addressParams as $name => $field) {
450 if (substr($name, 0, 8) == 'billing_') {
451 $addressParams[substr($name, 9)] = $addressParams[$field];
454 return array($hasBillingField, $addressParams);
458 * Get the number of terms for this contribution for a given membership type
459 * based on querying the line item table and relevant price field values
460 * Note that any one contribution should only be able to have one line item relating to a particular membership
463 * @param int $membershipTypeID
465 * @param int $contributionID
469 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
470 $numTerms = CRM_Core_DAO
::singleValueQuery("
471 SELECT membership_num_terms FROM civicrm_line_item li
472 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
473 WHERE contribution_id = %1 AND membership_type_id = %2",
474 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
476 // default of 1 is precautionary
477 return empty($numTerms) ?
1 : $numTerms;
481 * Takes an associative array and creates a contribution object.
483 * @param array $params
484 * (reference ) an assoc array of name/value pairs.
486 * The array that holds all the db ids.
488 * @return CRM_Contribute_BAO_Contribution
490 public static function create(&$params, $ids = array()) {
491 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date', 'revenue_recognition_date');
492 foreach ($dateFields as $df) {
493 if (isset($params[$df])) {
494 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
498 $transaction = new CRM_Core_Transaction();
501 $contribution = self
::add($params, $ids);
503 catch (CRM_Core_Exception
$e) {
504 $transaction->rollback();
508 $params['contribution_id'] = $contribution->id
;
510 if (!empty($params['custom']) &&
511 is_array($params['custom'])
513 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
516 $session = CRM_Core_Session
::singleton();
518 if (!empty($params['note'])) {
520 'entity_table' => 'civicrm_contribution',
521 'note' => $params['note'],
522 'entity_id' => $contribution->id
,
523 'contact_id' => $session->get('userID'),
524 'modified_date' => date('Ymd'),
526 if (!$noteParams['contact_id']) {
527 $noteParams['contact_id'] = $params['contact_id'];
529 CRM_Core_BAO_Note
::add($noteParams);
532 // make entry in batch entity batch table
533 if (!empty($params['batch_id'])) {
534 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
535 $titleFields = array(
541 $retrieveRequired = 0;
542 foreach ($titleFields as $titleField) {
543 if (!isset($contribution->$titleField)) {
544 $retrieveRequired = 1;
548 if ($retrieveRequired == 1) {
549 $contribution->find(TRUE);
553 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
555 $transaction->commit();
557 $activity = civicrm_api3('Activity', 'get', array(
558 'source_record_id' => $contribution->id
,
559 'options' => array('limit' => 1),
561 'activity_type_id' => 'Contribution',
562 'return' => array('id', 'campaign'),
565 //CRM-18406: Update activity when edit contribution.
566 if ($activity['count']) {
567 // CRM-13237 : if activity record found, update it with campaign id of contribution
568 // @todo compare campaign ids first.
569 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity['id'], 'campaign_id', $contribution->campaign_id
);
570 $contribution->activity_id
= $activity['id'];
573 if (empty($contribution->contact_id
)) {
574 $contribution->find(TRUE);
576 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution');
578 // do not add to recent items for import, CRM-4399
579 if (empty($params['skipRecentView'])) {
580 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
581 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
583 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
584 $titleFields = array(
590 $retrieveRequired = 0;
591 foreach ($titleFields as $titleField) {
592 if (!isset($contribution->$titleField)) {
593 $retrieveRequired = 1;
597 if ($retrieveRequired == 1) {
598 $contribution->find(TRUE);
600 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
601 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
603 $recentOther = array();
604 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
605 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
606 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
610 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
611 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
612 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
616 // add the recently created Contribution
617 CRM_Utils_Recent
::add($title,
621 $contribution->contact_id
,
627 return $contribution;
631 * Get the values for pseudoconstants for name->value and reverse.
633 * @param array $defaults
634 * (reference) the default values, some of which need to be resolved.
635 * @param bool $reverse
636 * True if we want to resolve the values in the reverse direction (value -> name).
638 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
639 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
640 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
641 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
642 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
646 * Convert associative array names to values and vice-versa.
648 * This function is used by both the web form layer and the api. Note that
649 * the api needs the name => value conversion, also the view layer typically
650 * requires value => name conversion
652 * @param array $defaults
653 * @param string $property
654 * @param array $lookup
655 * @param bool $reverse
659 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
660 $id = $property . '_id';
662 $src = $reverse ?
$property : $id;
663 $dst = $reverse ?
$id : $property;
665 if (!array_key_exists($src, $defaults)) {
669 $look = $reverse ?
array_flip($lookup) : $lookup;
671 if (is_array($look)) {
672 if (!array_key_exists($defaults[$src], $look)) {
676 $defaults[$dst] = $look[$defaults[$src]];
681 * Retrieve DB object based on input parameters.
683 * It also stores all the retrieved values in the default array.
685 * @param array $params
686 * (reference ) an assoc array of name/value pairs.
687 * @param array $defaults
688 * (reference ) an assoc array to hold the name / value pairs.
689 * in a hierarchical manner
691 * (reference) the array that holds all the db ids.
693 * @return CRM_Contribute_BAO_Contribution
695 public static function retrieve(&$params, &$defaults, &$ids) {
696 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
697 return $contribution;
701 * Combine all the importable fields from the lower levels object.
703 * The ordering is important, since currently we do not have a weight
704 * scheme. Adding weight is super important and should be done in the
705 * next week or so, before this can be called complete.
707 * @param string $contactType
708 * @param bool $status
711 * array of importable Fields
713 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
714 if (!self
::$_importableFields) {
715 if (!self
::$_importableFields) {
716 self
::$_importableFields = array();
720 $fields = array('' => array('title' => ts('- do not import -')));
723 $fields = array('' => array('title' => ts('- Contribution Fields -')));
726 $note = CRM_Core_DAO_Note
::import();
727 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
728 unset($tmpFields['option_value']);
729 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
730 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
732 // Using new Dedupe rule.
734 'contact_type' => $contactType,
735 'used' => 'Unsupervised',
737 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
738 $tmpContactField = array();
739 if (is_array($fieldsArray)) {
740 foreach ($fieldsArray as $value) {
741 //skip if there is no dupe rule
742 if ($value == 'none') {
745 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
750 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
751 $tmpContactField[trim($value)] = $contactFields[trim($value)];
753 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
756 $title = $tmpContactField[trim($value)]['title'];
758 $tmpContactField[trim($value)]['title'] = $title;
762 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
763 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
764 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
765 $fields = array_merge($fields, $tmpContactField);
766 $fields = array_merge($fields, $tmpFields);
767 $fields = array_merge($fields, $note);
768 $fields = array_merge($fields, $optionFields);
769 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
770 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
771 self
::$_importableFields = $fields;
773 return self
::$_importableFields;
777 * Combine all the exportable fields from the lower level objects.
779 * @param bool $checkPermission
782 * array of exportable Fields
784 public static function &exportableFields($checkPermission = TRUE) {
785 if (!self
::$_exportableFields) {
786 if (!self
::$_exportableFields) {
787 self
::$_exportableFields = array();
790 $fields = CRM_Contribute_DAO_Contribution
::export();
791 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
792 $fields = array_merge(
794 CRM_Contribute_DAO_Product
::export(),
795 CRM_Contribute_DAO_ContributionProduct
::export(),
796 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
798 'contribution_product_id' => [
799 'title' => ts('Premium'),
800 'name' => 'contribution_product_id',
801 'where' => 'civicrm_product.id',
802 'data_type' => CRM_Utils_Type
::T_INT
,
808 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
810 $contributionPage = array(
811 'contribution_page' => array(
812 'title' => ts('Contribution Page'),
813 'name' => 'contribution_page',
814 'where' => 'civicrm_contribution_page.title',
815 'data_type' => CRM_Utils_Type
::T_STRING
,
819 $contributionNote = array(
820 'contribution_note' => array(
821 'title' => ts('Contribution Note'),
822 'name' => 'contribution_note',
823 'data_type' => CRM_Utils_Type
::T_TEXT
,
827 $extraFields = array(
828 'contribution_batch' => array(
829 'title' => ts('Batch Name'),
834 $campaignTitle = array(
835 'contribution_campaign_title' => array(
836 'title' => ts('Campaign Title'),
837 'name' => 'campaign_title',
838 'where' => 'civicrm_campaign.title',
839 'data_type' => CRM_Utils_Type
::T_STRING
,
842 $softCreditFields = array(
843 'contribution_soft_credit_name' => array(
844 'name' => 'contribution_soft_credit_name',
845 'title' => ts('Soft Credit For'),
846 'where' => 'civicrm_contact_d.display_name',
847 'data_type' => CRM_Utils_Type
::T_STRING
,
849 'contribution_soft_credit_amount' => array(
850 'name' => 'contribution_soft_credit_amount',
851 'title' => ts('Soft Credit Amount'),
852 'where' => 'civicrm_contribution_soft.amount',
853 'data_type' => CRM_Utils_Type
::T_MONEY
,
855 'contribution_soft_credit_type' => array(
856 'name' => 'contribution_soft_credit_type',
857 'title' => ts('Soft Credit Type'),
858 'where' => 'contribution_softcredit_type.label',
859 'data_type' => CRM_Utils_Type
::T_STRING
,
861 'contribution_soft_credit_contribution_id' => array(
862 'name' => 'contribution_soft_credit_contribution_id',
863 'title' => ts('Soft Credit For Contribution ID'),
864 'where' => 'civicrm_contribution_soft.contribution_id',
865 'data_type' => CRM_Utils_Type
::T_INT
,
867 'contribution_soft_credit_contact_id' => array(
868 'name' => 'contribution_soft_credit_contact_id',
869 'title' => ts('Soft Credit For Contact ID'),
870 'where' => 'civicrm_contact_d.id',
871 'data_type' => CRM_Utils_Type
::T_INT
,
875 $fields = array_merge($fields, $contributionPage,
876 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
877 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
880 self
::$_exportableFields = $fields;
883 return self
::$_exportableFields;
887 * @param $contributionId
888 * @param $participantId
889 * @param array $financialTrxn
891 * @param $financialTrxn
893 protected static function recordPaymentActivity($contributionId, $participantId, $financialTrxn) {
894 $activityType = ($financialTrxn->total_amount
< 0) ?
'Refund' : 'Payment';
895 if ($participantId) {
896 $inputParams['id'] = $participantId;
899 $component = 'event';
900 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
901 $entityObj = $entityObj[$participantId];
904 $entityObj = new CRM_Contribute_BAO_Contribution();
905 $entityObj->id
= $contributionId;
906 $entityObj->find(TRUE);
907 $component = 'contribution';
910 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
914 * Get the value for the To Financial Account.
916 * @param $contribution
921 protected static function getToFinancialAccount($contribution, $params) {
922 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
923 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
925 array_search('Pending', $contributionStatuses),
926 array_search('In Progress', $contributionStatuses),
928 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $contribution), $pendingStatus)) {
929 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contribution['financial_type_id'], 'Accounts Receivable Account is');
931 elseif (!empty($params['payment_processor'])) {
932 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contribution['payment_processor'], NULL, 'civicrm_payment_processor');
934 elseif (!empty($params['payment_instrument_id'])) {
935 return CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
938 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
939 $queryParams = [1 => [$relationTypeId, 'Integer']];
940 return CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
945 * Get memberships realted to the contribution.
947 * @param int $contributionID
951 protected static function getRelatedMemberships($contributionID) {
952 $contribution = new CRM_Contribute_BAO_Contribution();
953 $contribution->id
= $contributionID;
954 $contribution->fetch(TRUE);
955 $contribution->loadRelatedMembershipObjects();
956 $result = CRM_Utils_Array
::value('membership', $contribution->_relatedObjects
, []);
958 foreach ($result as $membership) {
959 if (empty($membership)) {
962 // @todo - remove this again & just call api in the first place.
963 _civicrm_api3_object_to_array($membership, $memberships[$membership->id
]);
971 public function addSelectWhereClause() {
972 $whereClauses = parent
::addSelectWhereClause();
973 if ($whereClauses !== []) {
974 // In this case permisssions have been applied & we assume the
975 // financialaclreport is applying these
976 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
977 return $whereClauses;
980 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
981 return $whereClauses;
983 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
985 $whereClauses['financial_type_id'] = 'IN (0)';
988 $whereClauses['financial_type_id'] = [
989 'IN (' . implode(',', array_keys($types)) . ')'
992 return $whereClauses;
996 * @param null $status
997 * @param null $startDate
998 * @param null $endDate
1000 * @return array|null
1002 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1006 $where[] = 'contribution_status_id = 1';
1010 $where[] = 'contribution_status_id = 3';
1015 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
1018 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
1020 $financialTypeACLJoin = '';
1021 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1022 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1023 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
1024 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1025 if ($financialTypes) {
1026 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1027 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1030 $where[] = "c.financial_type_id IN (0)";
1034 $whereCond = implode(' AND ', $where);
1037 SELECT sum( total_amount ) as total_amount,
1038 count( c.id ) as total_count,
1040 FROM civicrm_contribution c
1041 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1042 $financialTypeACLJoin
1044 AND ( is_test = 0 OR is_test IS NULL )
1045 AND contact.is_deleted = 0
1049 $dao = CRM_Core_DAO
::executeQuery($query);
1052 while ($dao->fetch()) {
1053 $count +
= $dao->total_count
;
1054 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
1058 'amount' => implode(', ', $amount),
1066 * Delete the indirect records associated with this contribution first.
1070 * @return mixed|null
1071 * $results no of deleted Contribution on success, false otherwise
1073 public static function deleteContribution($id) {
1074 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
1076 $transaction = new CRM_Core_Transaction();
1079 //delete activity record
1081 'source_record_id' => $id,
1082 // activity type id for contribution
1083 'activity_type_id' => 6,
1086 CRM_Activity_BAO_Activity
::deleteActivity($params);
1088 //delete billing address if exists for this contribution.
1089 self
::deleteAddress($id);
1091 //update pledge and pledge payment, CRM-3961
1092 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1094 // remove entry from civicrm_price_set_entity, CRM-5095
1095 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1096 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1098 // cleanup line items.
1099 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1101 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1102 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1104 if ($participantId) {
1105 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1108 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1112 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1113 $noteId = key($note);
1115 CRM_Core_BAO_Note
::del($noteId, FALSE);
1118 $dao = new CRM_Contribute_DAO_Contribution();
1121 $results = $dao->delete();
1123 $transaction->commit();
1125 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1127 // delete the recently created Contribution
1128 $contributionRecent = array(
1130 'type' => 'Contribution',
1132 CRM_Utils_Recent
::del($contributionRecent);
1138 * React to a financial transaction (payment) failure.
1140 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1141 * payments is important for forensic and outreach reasons.
1143 * @param int $contributionID
1144 * @param int $contactID
1145 * @param string $message
1147 * @throws \CiviCRM_API3_Exception
1149 public static function failPayment($contributionID, $contactID, $message) {
1150 civicrm_api3('activity', 'create', array(
1151 'activity_type_id' => 'Failed Payment',
1152 'details' => $message,
1153 'subject' => ts('Payment failed at payment processor'),
1154 'source_record_id' => $contributionID,
1155 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1159 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1160 civicrm_api3('contribution', 'create', array(
1161 'id' => $contributionID,
1162 'contribution_status_id' => 'Failed',
1167 * Check if there is a contribution with the same trxn_id or invoice_id.
1169 * @param array $input
1170 * An assoc array of name/value pairs.
1171 * @param array $duplicates
1172 * (reference) store ids of duplicate contribs.
1176 * true if duplicate, false otherwise
1178 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1180 $id = CRM_Utils_Array
::value('id', $input);
1182 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1183 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1189 $clause[] = "trxn_id = %1";
1190 $input[1] = array($trxn_id, 'String');
1194 $clause[] = "invoice_id = %2";
1195 $input[2] = array($invoice_id, 'String');
1198 if (empty($clause)) {
1202 $clause = implode(' OR ', $clause);
1204 $clause = "( $clause ) AND id != %3";
1205 $input[3] = array($id, 'Integer');
1208 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1209 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1211 while ($dao->fetch()) {
1212 $duplicates[] = $dao->id
;
1219 * Takes an associative array and creates a contribution_product object.
1221 * the function extract all the params it needs to initialize the create a
1222 * contribution_product object. the params array could contain additional unused name/value
1225 * @param array $params
1226 * (reference) an assoc array of name/value pairs.
1228 * @return CRM_Contribute_DAO_ContributionProduct
1230 public static function addPremium(&$params) {
1231 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1232 $contributionProduct->copyValues($params);
1233 return $contributionProduct->save();
1237 * Get list of contribution fields for profile.
1238 * For now we only allow custom contribution fields to be in
1241 * @param bool $addExtraFields
1242 * True if special fields needs to be added.
1245 * the list of contribution fields
1247 public static function getContributionFields($addExtraFields = TRUE) {
1248 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1249 // @todo remove this - this line was added because payment_instrument_id was not
1250 // set to exportable - but now it is.
1251 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1253 if ($addExtraFields) {
1254 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1257 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1259 foreach ($contributionFields as $key => $var) {
1260 if ($key == 'contribution_contact_id') {
1263 elseif ($key == 'contribution_campaign_id') {
1264 $var['title'] = ts('Campaign');
1266 $fields[$key] = $var;
1269 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1274 * Add extra fields specific to contribution.
1276 public static function getSpecialContributionFields() {
1277 $extraFields = array(
1278 'contribution_soft_credit_name' => array(
1279 'name' => 'contribution_soft_credit_name',
1280 'title' => ts('Soft Credit Name'),
1281 'headerPattern' => '/^soft_credit_name$/i',
1282 'where' => 'civicrm_contact_d.display_name',
1284 'contribution_soft_credit_email' => array(
1285 'name' => 'contribution_soft_credit_email',
1286 'title' => ts('Soft Credit Email'),
1287 'headerPattern' => '/^soft_credit_email$/i',
1288 'where' => 'soft_email.email',
1290 'contribution_soft_credit_phone' => array(
1291 'name' => 'contribution_soft_credit_phone',
1292 'title' => ts('Soft Credit Phone'),
1293 'headerPattern' => '/^soft_credit_phone$/i',
1294 'where' => 'soft_phone.phone',
1296 'contribution_soft_credit_contact_id' => array(
1297 'name' => 'contribution_soft_credit_contact_id',
1298 'title' => ts('Soft Credit Contact ID'),
1299 'headerPattern' => '/^soft_credit_contact_id$/i',
1300 'where' => 'civicrm_contribution_soft.contact_id',
1302 'contribution_pcp_title' => array(
1303 'name' => 'contribution_pcp_title',
1304 'title' => ts('Personal Campaign Page Title'),
1305 'headerPattern' => '/^contribution_pcp_title$/i',
1306 'where' => 'contribution_pcp.title',
1310 return $extraFields;
1314 * @param int $pageID
1318 public static function getCurrentandGoalAmount($pageID) {
1320 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1321 FROM civicrm_contribution_page p,
1322 civicrm_contribution c
1323 WHERE p.id = c.contribution_page_id
1325 AND c.cancel_date is null
1329 $config = CRM_Core_Config
::singleton();
1330 $params = array(1 => array($pageID, 'Integer'));
1331 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1333 if ($dao->fetch()) {
1334 return array($dao->goal
, $dao->total
);
1337 return array(NULL, NULL);
1342 * Get list of contributions which credit the passed in contact ID.
1344 * The returned array provides details about the original contribution & donor.
1346 * @todo - this is a confusing function called from one place. It has a test. It would be
1347 * nice to deprecate it.
1349 * @param int $honorId
1350 * In Honor of Contact ID.
1353 * list of contribution fields
1355 public static function getHonorContacts($honorId) {
1357 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1358 $honorDAO->contact_id
= $honorId;
1361 $type = CRM_Contribute_PseudoConstant
::financialType();
1363 while ($honorDAO->fetch()) {
1364 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1365 $contributionDAO->id
= $honorDAO->contribution_id
;
1367 if ($contributionDAO->find(TRUE)) {
1368 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1369 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1370 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1371 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1372 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1373 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1374 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1375 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1376 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1384 * Get the sort name of a contact for a particular contribution.
1387 * Id of the contribution.
1389 * @return null|string
1390 * sort name of the contact if found
1392 public static function sortName($id) {
1393 $id = CRM_Utils_Type
::escape($id, 'Integer');
1396 SELECT civicrm_contact.sort_name
1397 FROM civicrm_contribution, civicrm_contact
1398 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1399 AND civicrm_contribution.id = {$id}
1401 return CRM_Core_DAO
::singleValueQuery($query);
1405 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1407 * @param int|array $contactIDs
1411 public static function annual($contactIDs) {
1412 if (!is_array($contactIDs)) {
1413 // In practice I can't fine any evidence that this function is ever called with
1414 // anything other than a single contact id, but left like this due to .... fear.
1415 $contactIDs = explode(',', $contactIDs);
1418 $query = self
::getAnnualQuery($contactIDs);
1419 $dao = CRM_Core_DAO
::executeQuery($query);
1421 $amount = $average = array();
1422 while ($dao->fetch()) {
1423 if ($dao->count
> 0 && $dao->amount
> 0) {
1424 $count +
= $dao->count
;
1425 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1426 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1432 implode(', ', $amount),
1433 implode(', ', $average),
1436 return array(0, 0, 0);
1440 * Check if there is a contribution with the params passed in.
1442 * Used for trxn_id,invoice_id and contribution_id
1444 * @param array $params
1445 * An assoc array of name/value pairs.
1448 * contribution id if success else NULL
1450 public static function checkDuplicateIds($params) {
1451 $dao = new CRM_Contribute_DAO_Contribution();
1455 foreach ($params as $k => $v) {
1457 $clause[] = "$k = '$v'";
1460 $clause = implode(' AND ', $clause);
1461 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1462 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1464 while ($dao->fetch()) {
1472 * Get the contribution details for component export.
1474 * @param int $exportMode
1476 * @param array $componentIds
1482 public static function getContributionDetails($exportMode, $componentIds) {
1483 $paymentDetails = array();
1484 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1486 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1487 $componentSelect = " civicrm_participant_payment.participant_id id";
1488 $additionalClause = "
1489 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1490 AND civicrm_participant_payment.participant_id {$componentClause} )
1493 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1494 $componentSelect = " civicrm_membership_payment.membership_id id";
1495 $additionalClause = "
1496 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1497 AND civicrm_membership_payment.membership_id {$componentClause} )
1500 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1501 $componentSelect = " civicrm_pledge_payment.id id";
1502 $additionalClause = "
1503 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1504 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1508 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1509 trxn_id, {$componentSelect}
1510 FROM civicrm_contribution
1511 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1512 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1513 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1514 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1515 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1516 AND option_group_contribution_status.id = contribution_status.option_group_id )
1520 $dao = CRM_Core_DAO
::executeQuery($query);
1522 while ($dao->fetch()) {
1523 $paymentDetails[$dao->id
] = array(
1524 'total_amount' => $dao->total_amount
,
1525 'contribution_status' => $dao->status
,
1526 'receive_date' => $dao->receive_date
,
1527 'pay_instru' => $dao->payment_instrument
,
1528 'trxn_id' => $dao->trxn_id
,
1532 return $paymentDetails;
1536 * Create address associated with contribution record.
1538 * As long as there is one or more billing field in the parameters we will create the address.
1540 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1543 * @param array $params
1544 * @param int $billingLocationTypeID
1549 public static function createAddress($params, $billingLocationTypeID) {
1550 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1551 if ($hasBillingField) {
1552 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1553 return $address->id
;
1560 * Delete billing address record related contribution.
1562 * @param int $contributionId
1563 * @param int $contactId
1565 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1567 $contactJoin = NULL;
1569 if ($contributionId) {
1570 $clauses[] = "cc.id = {$contributionId}";
1574 $clauses[] = "cco.id = {$contactId}";
1575 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1578 if (empty($clauses)) {
1579 CRM_Core_Error
::fatal();
1582 $condition = implode(' OR ', $clauses);
1586 FROM civicrm_address ca
1587 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1591 $dao = CRM_Core_DAO
::executeQuery($query);
1593 while ($dao->fetch()) {
1594 $params = array('id' => $dao->id
);
1595 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1600 * This function check online pending contribution associated w/
1601 * Online Event Registration or Online Membership signup.
1603 * @param int $componentId
1604 * Participant/membership id.
1605 * @param string $componentName
1609 * pending contribution id.
1611 public static function checkOnlinePendingContribution($componentId, $componentName) {
1612 $contributionId = NULL;
1613 if (!$componentId ||
1614 !in_array($componentName, array('Event', 'Membership'))
1616 return $contributionId;
1619 if ($componentName == 'Event') {
1620 $idName = 'participant_id';
1621 $componentTable = 'civicrm_participant';
1622 $paymentTable = 'civicrm_participant_payment';
1623 $source = ts('Online Event Registration');
1626 if ($componentName == 'Membership') {
1627 $idName = 'membership_id';
1628 $componentTable = 'civicrm_membership';
1629 $paymentTable = 'civicrm_membership_payment';
1630 $source = ts('Online Contribution');
1633 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1636 SELECT component.id as {$idName},
1637 componentPayment.contribution_id as contribution_id,
1638 contribution.source source,
1639 contribution.contribution_status_id as contribution_status_id,
1640 contribution.is_pay_later as is_pay_later
1641 FROM $componentTable component
1642 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1643 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1644 WHERE component.id = {$componentId}";
1646 $dao = CRM_Core_DAO
::executeQuery($query);
1648 while ($dao->fetch()) {
1649 if ($dao->contribution_id
&&
1650 $dao->is_pay_later
&&
1651 $dao->contribution_status_id
== $pendingStatusId &&
1652 strpos($dao->source
, $source) !== FALSE
1654 $contributionId = $dao->contribution_id
;
1659 return $contributionId;
1663 * Update contribution as well as related objects.
1665 * This function by-passes hooks - to address this - don't use this function.
1669 * Use api contribute.completetransaction
1670 * For failures use failPayment (preferably exposing by api in the process).
1672 * @param array $params
1673 * @param bool $processContributionObject
1676 * @throws \Exception
1678 public static function transitionComponents($params, $processContributionObject = FALSE) {
1679 // get minimum required values.
1680 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1681 $componentId = CRM_Utils_Array
::value('component_id', $params);
1682 $componentName = CRM_Utils_Array
::value('componentName', $params);
1683 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1684 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1686 // if we already processed contribution object pass previous status id.
1687 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1689 $updateResult = array();
1691 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1693 // we process only ( Completed, Cancelled, or Failed ) contributions.
1694 if (!$contributionId ||
1695 !in_array($contributionStatusId, array(
1696 array_search('Completed', $contributionStatuses),
1697 array_search('Cancelled', $contributionStatuses),
1698 array_search('Failed', $contributionStatuses),
1701 return $updateResult;
1704 if (!$componentName ||
!$componentId) {
1705 // get the related component details.
1706 $componentDetails = self
::getComponentDetails($contributionId);
1709 $componentDetails['contact_id'] = $contactId;
1710 $componentDetails['component'] = $componentName;
1712 if ($componentName == 'event') {
1713 $componentDetails['participant'] = $componentId;
1716 $componentDetails['membership'] = $componentId;
1720 if (!empty($componentDetails['contact_id'])) {
1721 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1727 // do check for required ids.
1728 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1729 return $updateResult;
1732 //now we are ready w/ required ids, start processing.
1734 $baseIPN = new CRM_Core_Payment_BaseIPN();
1736 $input = $ids = $objects = array();
1738 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1739 $ids['contribution'] = $contributionId;
1740 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1741 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1742 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1743 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1744 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1745 $ids['contributionRecur'] = NULL;
1746 $ids['contributionPage'] = NULL;
1748 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1749 CRM_Core_Error
::fatal();
1752 $memberships = &$objects['membership'];
1753 $participant = &$objects['participant'];
1754 $pledgePayment = &$objects['pledge_payment'];
1755 $contribution = &$objects['contribution'];
1757 if ($pledgePayment) {
1758 $pledgePaymentIDs = array();
1759 foreach ($pledgePayment as $key => $object) {
1760 $pledgePaymentIDs[] = $object->id
;
1762 $pledgeID = $pledgePayment[0]->pledge_id
;
1765 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1768 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1769 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1774 // we might want to process contribution object.
1775 $processContribution = FALSE;
1776 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1777 if (is_array($memberships)) {
1778 foreach ($memberships as $membership) {
1780 //Update Membership status if there is no other completed contribution associated with the membership.
1781 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1782 foreach ($relatedContributions as $contriId) {
1783 if ($contriId == $contributionId) {
1786 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1787 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1791 if ($membership && $update) {
1792 $newStatus = array_search('Cancelled', $membershipStatuses);
1795 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1796 $activityParam = array(
1797 'subject' => "Status changed from {$allStatus[$membership->status_id]} to {$allStatus[$newStatus]}",
1798 'source_contact_id' => CRM_Core_Session
::singleton()->get('userID'),
1799 'target_contact_id' => $membership->contact_id
,
1800 'source_record_id' => $membership->id
,
1801 'activity_type_id' => 'Change Membership Status',
1802 'status_id' => 'Completed',
1803 'priority_id' => 'Normal',
1804 'activity_date_time' => 'now',
1807 $membership->status_id
= $newStatus;
1808 $membership->is_override
= TRUE;
1809 $membership->status_override_end_date
= 'null';
1810 $membership->save();
1811 civicrm_api3('activity', 'create', $activityParam);
1813 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1814 if ($processContributionObject) {
1815 $processContribution = TRUE;
1822 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1823 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1825 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1826 if ($processContributionObject) {
1827 $processContribution = TRUE;
1831 if ($pledgePayment) {
1832 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1834 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1835 if ($processContributionObject) {
1836 $processContribution = TRUE;
1840 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1841 if (is_array($memberships)) {
1842 foreach ($memberships as $membership) {
1844 //Update Membership status if there is no other completed contribution associated with the membership.
1845 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1846 foreach ($relatedContributions as $contriId) {
1847 if ($contriId == $contributionId) {
1850 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1851 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1855 if ($membership && $update) {
1856 $membership->status_id
= array_search('Expired', $membershipStatuses);
1857 $membership->is_override
= TRUE;
1858 $membership->status_override_end_date
= 'null';
1859 $membership->save();
1861 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1862 if ($processContributionObject) {
1863 $processContribution = TRUE;
1869 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1870 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1872 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1873 if ($processContributionObject) {
1874 $processContribution = TRUE;
1878 if ($pledgePayment) {
1879 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1881 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1882 if ($processContributionObject) {
1883 $processContribution = TRUE;
1887 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1889 // only pending contribution related object processed.
1890 if ($previousContriStatusId &&
1891 !in_array($contributionStatuses[$previousContriStatusId], array('Pending', 'Partially paid'))
1893 // this is case when we already processed contribution object.
1894 return $updateResult;
1896 elseif (!$previousContriStatusId &&
1897 !in_array($contributionStatuses[$contribution->contribution_status_id
], array('Pending', 'Partially paid'))
1899 // this is case when we are going to process contribution object later.
1900 return $updateResult;
1903 if (is_array($memberships)) {
1904 foreach ($memberships as $membership) {
1909 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1910 $membership->membership_type_id
,
1911 $membership->is_test
, $membership->id
1914 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1915 // this picks up membership type changes during renewals
1917 SELECT membership_type_id
1918 FROM civicrm_membership_log
1919 WHERE membership_id=$membership->id
1922 $dao = new CRM_Core_DAO();
1924 if ($dao->fetch()) {
1925 if (!empty($dao->membership_type_id
)) {
1926 $membership->membership_type_id
= $dao->membership_type_id
;
1927 $membership->save();
1930 // else fall back to using current membership type
1933 // Figure out number of terms
1935 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
1936 foreach ($lineitems as $lineitem) {
1937 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1938 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1940 // in case membership_num_terms comes through as null or zero
1941 $numterms = $numterms >= 1 ?
$numterms : 1;
1946 // CRM-15735-to update the membership status as per the contribution receive date
1948 $oldStatus = $membership->status_id
;
1949 if (!empty($params['receive_date'])) {
1950 $joinDate = $params['receive_date'];
1951 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1952 $membership->end_date
,
1953 $membership->join_date
,
1954 $params['receive_date'],
1956 $membership->membership_type_id
,
1959 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1960 $membership->save();
1963 if ($currentMembership) {
1964 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1965 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1966 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1969 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1972 //get the status for membership.
1973 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1975 $dates['join_date'],
1978 $membership->membership_type_id
,
1982 $formattedParams = array(
1983 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1984 array_search('Current', $membershipStatuses)
1986 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1987 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1988 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1991 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1993 $membership->copyValues($formattedParams);
1994 $membership->save();
1996 //updating the membership log
1997 $membershipLog = array();
1998 $membershipLog = $formattedParams;
1999 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
2000 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
2002 $membershipLog['start_date'] = $logStartDate;
2003 $membershipLog['membership_id'] = $membership->id
;
2004 $membershipLog['modified_id'] = $membership->contact_id
;
2005 $membershipLog['modified_date'] = date('Ymd');
2006 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
2008 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2010 //update related Memberships.
2011 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2013 foreach (array('Membership Signup', 'Membership Renewal') as $activityType) {
2014 $scheduledActivityID = CRM_Utils_Array
::value('id',
2015 civicrm_api3('Activity', 'Get',
2017 'source_record_id' => $membership->id
,
2018 'activity_type_id' => $activityType,
2019 'status_id' => 'Scheduled',
2022 'sort' => 'id DESC',
2027 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2028 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2029 if ($scheduledActivityID) {
2030 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, array('id' => $scheduledActivityID));
2035 // track membership status change if any
2036 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
2037 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2038 CRM_Activity_BAO_Activity
::addActivity($membership,
2039 'Change Membership Status',
2042 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2043 'source_contact_id' => $membershipLog['modified_id'],
2044 'priority_id' => 'Normal',
2049 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
2052 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2053 if ($processContributionObject) {
2054 $processContribution = TRUE;
2057 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2063 $updatedStatusId = array_search('Registered', $participantStatuses);
2064 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2066 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2067 if ($processContributionObject) {
2068 $processContribution = TRUE;
2072 if ($pledgePayment) {
2073 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2075 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2076 if ($processContributionObject) {
2077 $processContribution = TRUE;
2082 // process contribution object.
2083 if ($processContribution) {
2084 $contributionParams = array();
2091 'payment_instrument_id',
2094 'financial_type_id',
2095 'contribution_status_id',
2096 'non_deductible_amount',
2100 foreach ($fields as $field) {
2101 if (empty($params[$field])) {
2104 $contributionParams[$field] = $params[$field];
2107 $ids = array('contribution' => $contributionId);
2108 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2111 return $updateResult;
2115 * Returns all contribution related object ids.
2117 * @param $contributionId
2121 public static function getComponentDetails($contributionId) {
2122 $componentDetails = $pledgePayment = array();
2123 if (!$contributionId) {
2124 return $componentDetails;
2128 SELECT c.id as contribution_id,
2129 c.contact_id as contact_id,
2130 c.contribution_recur_id,
2131 mp.membership_id as membership_id,
2132 m.membership_type_id as membership_type_id,
2133 pp.participant_id as participant_id,
2134 p.event_id as event_id,
2135 pgp.id as pledge_payment_id
2136 FROM civicrm_contribution c
2137 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2138 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2139 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2140 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2141 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2142 WHERE c.id = $contributionId";
2144 $dao = CRM_Core_DAO
::executeQuery($query);
2145 $componentDetails = array();
2147 while ($dao->fetch()) {
2148 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2149 $componentDetails['contact_id'] = $dao->contact_id
;
2150 if ($dao->event_id
) {
2151 $componentDetails['event'] = $dao->event_id
;
2153 if ($dao->participant_id
) {
2154 $componentDetails['participant'] = $dao->participant_id
;
2156 if ($dao->membership_id
) {
2157 if (!isset($componentDetails['membership'])) {
2158 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
2160 $componentDetails['membership'][] = $dao->membership_id
;
2161 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2163 if ($dao->pledge_payment_id
) {
2164 $pledgePayment[] = $dao->pledge_payment_id
;
2166 if ($dao->contribution_recur_id
) {
2167 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2171 if ($pledgePayment) {
2172 $componentDetails['pledge_payment'] = $pledgePayment;
2175 return $componentDetails;
2179 * @param int $contactId
2180 * @param bool $includeSoftCredit
2182 * @return null|string
2184 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2188 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2189 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2190 $liWhere = " AND i.financial_type_id IN (0)";
2191 if (!empty($financialTypes)) {
2192 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2193 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2195 $contactContributionsSQL = "
2196 SELECT contribution.id AS id
2197 FROM civicrm_contribution contribution
2198 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2199 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2203 $contactSoftCreditContributionsSQL = "
2204 SELECT contribution.id
2205 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2206 ON ( contribution.id = softContribution.contribution_id )
2207 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2208 $query = "SELECT count( x.id ) count FROM ( ";
2209 $query .= $contactContributionsSQL;
2211 if ($includeSoftCredit) {
2212 $query .= " UNION ";
2213 $query .= $contactSoftCreditContributionsSQL;
2218 return CRM_Core_DAO
::singleValueQuery($query);
2222 * Repeat a transaction as part of a recurring series.
2224 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
2225 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
2226 * subsequent call to the contribution.completetransaction api.
2228 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
2230 * @param CRM_Contribute_BAO_Contribution $contribution
2231 * @param array $input
2232 * @param array $contributionParams
2233 * @param int $paymentProcessorID
2236 * @throws CiviCRM_API3_Exception
2238 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
2239 if (!empty($contribution->id
)) {
2242 if (empty($contribution->id
)) {
2243 // Unclear why this would only be set for repeats.
2244 if (!empty($input['amount'])) {
2245 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2248 if (!empty($contributionParams['contribution_recur_id'])) {
2249 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', array(
2250 'id' => $contributionParams['contribution_recur_id'],
2252 if (!empty($recurringContribution['campaign_id'])) {
2253 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2254 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2256 if (!empty($recurringContribution['financial_type_id'])) {
2257 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2258 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2261 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2262 $contributionParams['contribution_recur_id'],
2263 array_intersect_key($contributionParams, array('total_amount' => TRUE, 'financial_type_id' => TRUE))
2265 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2267 $contributionParams['status_id'] = 'Pending';
2268 if (isset($contributionParams['financial_type_id'])) {
2269 // Give precedence to passed in type.
2270 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2273 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2275 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2276 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2278 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2279 //do not create CC or BCC emails or profile notifications.
2280 //The if is just to be safe. Not sure if we can ever arrive with this unset
2281 // but per CRM-19478 it seems it can be 'null'
2282 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2283 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2286 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2287 $contribution->id
= $createContribution['id'];
2288 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2294 * Get individual id for onbehalf contribution.
2296 * @param int $contributionId
2298 * @param int $contributorId
2302 * containing organization id and individual id
2304 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2308 if (!$contributionId) {
2312 // fetch contributor id if null
2313 if (!$contributorId) {
2314 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2315 $contributionId, 'contact_id'
2319 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2320 $activityTypeId = array_search('Contribution', $activityTypeIds);
2322 if ($activityTypeId && $contributorId) {
2324 SELECT civicrm_activity_contact.contact_id
2325 FROM civicrm_activity_contact
2326 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2327 WHERE civicrm_activity.activity_type_id = %1
2328 AND civicrm_activity.source_record_id = %2
2329 AND civicrm_activity_contact.record_type_id = %3
2332 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2333 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2336 1 => array($activityTypeId, 'Integer'),
2337 2 => array($contributionId, 'Integer'),
2338 3 => array($sourceID, 'Integer'),
2341 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2343 // for on behalf contribution source is individual and contributor is organization
2344 if ($sourceContactId && $sourceContactId != $contributorId) {
2345 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2346 // get rel type id for employee of relation
2347 foreach ($relationshipTypeIds as $id => $typeVals) {
2348 if ($typeVals['name_a_b'] == 'Employee of') {
2349 $relationshipTypeId = $id;
2354 $rel = new CRM_Contact_DAO_Relationship();
2355 $rel->relationship_type_id
= $relationshipTypeId;
2356 $rel->contact_id_a
= $sourceContactId;
2357 $rel->contact_id_b
= $contributorId;
2358 if ($rel->find(TRUE)) {
2359 $ids['individual_id'] = $rel->contact_id_a
;
2360 $ids['organization_id'] = $rel->contact_id_b
;
2371 public static function getContributionDates() {
2372 $config = CRM_Core_Config
::singleton();
2373 $currentMonth = date('m');
2374 $currentDay = date('d');
2375 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2376 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2377 (int ) $config->fiscalYearStart
['d'] > $currentDay
2380 $year = date('Y') - 1;
2385 $year = array('Y' => $year);
2386 $yearDate = $config->fiscalYearStart
;
2387 $yearDate = array_merge($year, $yearDate);
2388 $yearDate = CRM_Utils_Date
::format($yearDate);
2390 $monthDate = date('Ym') . '01';
2396 'yearDate' => $yearDate,
2397 'monthDate' => $monthDate,
2402 * Load objects relations to contribution object.
2403 * Objects are stored in the $_relatedObjects property
2404 * In the first instance we are just moving functionality from BASEIpn -
2405 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2407 * Note that the unit test for the BaseIPN class tests this function
2409 * @param array $input
2410 * Input as delivered from Payment Processor.
2412 * Ids as Loaded by Payment Processor.
2413 * @param bool $loadAll
2414 * Load all related objects - even where id not passed in? (allows API to call this).
2419 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2421 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2422 if (empty($ids['contact']) && isset($this->contact_id
)) {
2423 $ids['contact'] = $this->contact_id
;
2426 if (empty($this->_component
)) {
2427 if (!empty($ids['event'])) {
2428 $this->_component
= 'event';
2431 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2435 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2436 // refactoring than anything else, and has unit test coverage.
2437 if (empty($this->financial_type_id
)) {
2441 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2446 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2447 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2448 $this->contribution_page_id
,
2451 if ($paymentProcessorID) {
2452 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2456 $ids['contributionType'] = $this->financial_type_id
;
2457 $ids['financialType'] = $this->financial_type_id
;
2458 if ($this->contribution_page_id
) {
2459 $ids['contributionPage'] = $this->contribution_page_id
;
2462 $this->loadRelatedEntitiesByID($ids);
2464 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2465 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2468 if (!empty($ids['pledge_payment'])) {
2469 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2470 if (empty($paymentID)) {
2473 $payment = new CRM_Pledge_BAO_PledgePayment();
2474 $payment->id
= $paymentID;
2475 if (!$payment->find(TRUE)) {
2476 throw new Exception("Could not find pledge payment record: " . $paymentID);
2478 $this->_relatedObjects
['pledge_payment'][] = $payment;
2482 $ids = $this->loadRelatedMembershipObjects($ids);
2484 if ($this->_component
!= 'contribute') {
2485 // we are in event mode
2486 // make sure event exists and is valid
2487 $event = new CRM_Event_BAO_Event();
2488 $event->id
= $ids['event'];
2489 if ($ids['event'] &&
2492 throw new Exception("Could not find event: " . $ids['event']);
2495 $this->_relatedObjects
['event'] = &$event;
2497 $participant = new CRM_Event_BAO_Participant();
2498 $participant->id
= $ids['participant'];
2499 if ($ids['participant'] &&
2500 !$participant->find(TRUE)
2502 throw new Exception("Could not find participant: " . $ids['participant']);
2504 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2506 $this->_relatedObjects
['participant'] = &$participant;
2508 // get the payment processor id from event - this is inaccurate see CRM-16923
2509 // in future we should look at throwing an exception here rather than an dubious guess.
2510 if (!$paymentProcessorID) {
2511 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2512 if ($paymentProcessorID) {
2513 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2518 if ($paymentProcessorID) {
2519 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2520 $this->is_test ?
'test' : 'live'
2522 $ids['paymentProcessor'] = $paymentProcessorID;
2523 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2526 // Add contribution id to $ids. CRM-20401
2527 $ids['contribution'] = $this->id
;
2532 * Create array of message information - ie. return html version, txt version, to field
2534 * @param array $input
2535 * Incoming information.
2536 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2537 * just check presence of recur object but maintaining legacy approach
2540 * IDs of related objects.
2541 * @param array $values
2542 * Any values that may have already been compiled by calling process.
2543 * This is augmented by values 'gathered' by gatherMessageValues
2544 * @param bool $returnMessageText
2545 * Distinguishes between whether to send message or return.
2546 * message text. We are working towards this function ALWAYS returning message text & calling
2547 * function doing emails / pdfs with it
2553 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2554 $this->loadRelatedObjects($input, $ids);
2556 if (empty($this->_component
)) {
2557 $this->_component
= CRM_Utils_Array
::value('component', $input);
2560 //not really sure what params might be passed in but lets merge em into values
2561 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2562 $values['is_email_receipt'] = $this->isEmailReceipt($input, $values);
2563 if (!empty($input['receipt_date'])) {
2564 $values['receipt_date'] = $input['receipt_date'];
2567 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2568 //what does recur 'mean here - to do with payment processor return functionality but
2569 // what is the importance
2570 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2571 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2573 $entityID = $entity = NULL;
2574 if (isset($ids['contribution'])) {
2575 $entity = 'contribution';
2576 $entityID = $ids['contribution'];
2578 if (!empty($ids['membership'])) {
2579 //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
2580 // 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
2581 // line having loaded an array
2582 $ids['membership'] = (array) $ids['membership'];
2583 $entity = 'membership';
2584 $entityID = $ids['membership'][0];
2587 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2588 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2589 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2591 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2592 //direct mode showing billing block, so use directIPN for temporary
2593 $template->assign('contributeMode', 'directIPN');
2596 // todo remove strtolower - check consistency
2597 if (strtolower($this->_component
) == 'event') {
2598 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2599 $values['event'] = array();
2601 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2603 //get location details
2604 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2605 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2607 $ufJoinParams = array(
2608 'entity_table' => 'civicrm_event',
2609 'entity_id' => $ids['event'],
2610 'module' => 'CiviEvent',
2613 list($custom_pre_id,
2615 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2617 $values['custom_pre_id'] = $custom_pre_id;
2618 $values['custom_post_id'] = $custom_post_ids;
2619 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2620 //and cases involving status updation through ipn
2621 // whatever that means!
2622 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2623 // perhaps we should throw an e-notice if amount is set & force total_amount?
2624 if (!empty($input['amount'])) {
2625 $values['totalAmount'] = $input['amount'];
2627 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2628 if ($values['event']['is_email_confirm']) {
2629 $values['is_email_receipt'] = 1;
2632 if (!empty($ids['contribution'])) {
2633 $values['contributionId'] = $ids['contribution'];
2636 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2637 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2641 $values['contribution_id'] = $this->id
;
2642 if (!empty($ids['related_contact'])) {
2643 $values['related_contact'] = $ids['related_contact'];
2644 if (isset($ids['onbehalf_dupe_alert'])) {
2645 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2647 $entityBlock = array(
2648 'contact_id' => $ids['contact'],
2649 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2650 'Home', 'id', 'name'
2653 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2654 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2657 if ($this->is_test
) {
2660 if (!empty($this->_relatedObjects
['membership'])) {
2661 foreach ($this->_relatedObjects
['membership'] as $membership) {
2662 if ($membership->id
) {
2663 $values['membership_id'] = $membership->id
;
2664 $values['isMembership'] = TRUE;
2665 $values['membership_assign'] = TRUE;
2667 // need to set the membership values here
2668 $template->assign('membership_name',
2669 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2671 $template->assign('mem_start_date', $membership->start_date
);
2672 $template->assign('mem_join_date', $membership->join_date
);
2673 $template->assign('mem_end_date', $membership->end_date
);
2674 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2675 $template->assign('mem_status', $membership_status);
2676 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2677 $values['is_pay_later'] = 1;
2679 // Pass amount to floatval as string '0.00' is considered a
2680 // valid amount and includes Fee section in the mail.
2681 if (isset($values['amount'])) {
2682 $values['amount'] = floatval($values['amount']);
2685 if (!empty($this->contribution_recur_id
) && $paymentObject) {
2686 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2687 $template->assign('cancelSubscriptionUrl', $url);
2688 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2689 $template->assign('updateSubscriptionBillingUrl', $url);
2690 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2691 $template->assign('updateSubscriptionUrl', $url);
2694 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2697 // otherwise if its about sending emails, continue sending without return, as we
2698 // don't want to exit the loop.
2703 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2709 * Gather values for contribution mail - this function has been created
2710 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2711 * Values related to the contribution in question are gathered
2713 * @param array $input
2714 * Input into function (probably from payment processor).
2715 * @param array $values
2717 * The set of ids related to the input.
2721 public function _gatherMessageValues($input, &$values, $ids = array()) {
2722 // set display address of contributor
2723 if ($this->address_id
) {
2724 $addressParams = array('id' => $this->address_id
);
2725 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2726 $addressDetails = array_values($addressDetails);
2728 // Else we assign the billing address of the contribution contact.
2730 $addressParams = array('contact_id' => $this->contact_id
, 'is_billing' => 1);
2731 $addressDetails = (array) CRM_Core_BAO_Address
::getValues($addressParams);
2732 $addressDetails = array_values($addressDetails);
2735 if (!empty($addressDetails[0]['display'])) {
2736 $values['address'] = $addressDetails[0]['display'];
2739 if ($this->_component
== 'contribute') {
2740 //get soft contributions
2741 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2742 if (!empty($softContributions)) {
2743 $values['softContributions'] = $softContributions['soft_credit'];
2745 if (isset($this->contribution_page_id
)) {
2746 // This is a call we want to use less, in favour of loading related objects.
2747 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
2748 if ($this->contribution_page_id
) {
2749 // This is precautionary as there are some legacy flows, but it should really be
2751 if (!isset($this->_relatedObjects
['contributionPage'])) {
2752 $this->loadRelatedEntitiesByID(array('contributionPage' => $this->contribution_page_id
));
2754 // CRM-8254 - override default currency if applicable
2755 $config = CRM_Core_Config
::singleton();
2756 $config->defaultCurrency
= CRM_Utils_Array
::value(
2759 $config->defaultCurrency
2763 // no contribution page -probably back office
2765 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2766 $values['title'] = 'Contribution';
2768 // set lineItem for contribution
2770 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
2771 if (!empty($lineItems)) {
2772 $firstLineItem = reset($lineItems);
2773 $priceSet = array();
2774 if (CRM_Utils_Array
::value('price_set_id', $firstLineItem)) {
2775 $priceSet = civicrm_api3('PriceSet', 'getsingle', array('id' => $firstLineItem['price_set_id'], 'return' => 'is_quick_config, id'));
2776 $values['priceSetID'] = $priceSet['id'];
2778 foreach ($lineItems as &$eachItem) {
2779 if (isset($this->_relatedObjects
['membership'])
2780 && is_array($this->_relatedObjects
['membership'])
2781 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2782 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2783 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2784 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2786 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
2787 // However, that does create upgrade pain so would be better to be phased in.
2788 $values['useForMember'] = empty($priceSet['is_quick_config']);
2790 $values['lineItem'][0] = $lineItems;
2794 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2798 // if this is onbehalf of contribution then set related contact
2799 if (!empty($relatedContact['individual_id'])) {
2800 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2805 $eventParams = array(
2806 'id' => $this->_relatedObjects
['event']->id
,
2808 $values['event'] = array();
2810 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2811 // add custom fields for event
2812 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $this->_relatedObjects
['event']->id
);
2814 $eventCustomGroup = array();
2815 foreach ($eventGroupTree as $key => $group) {
2816 if ($key === 'info') {
2820 foreach ($group['fields'] as $k => $customField) {
2821 $groupLabel = $group['title'];
2822 if (!empty($customField['customValue'])) {
2823 foreach ($customField['customValue'] as $customFieldValues) {
2824 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2829 $values['event']['customGroup'] = $eventCustomGroup;
2831 //get participant details
2832 $participantParams = array(
2833 'id' => $this->_relatedObjects
['participant']->id
,
2836 $values['participant'] = array();
2838 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2839 // add custom fields for event
2840 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $this->_relatedObjects
['participant']->id
);
2841 $participantCustomGroup = array();
2842 foreach ($participantGroupTree as $key => $group) {
2843 if ($key === 'info') {
2847 foreach ($group['fields'] as $k => $customField) {
2848 $groupLabel = $group['title'];
2849 if (!empty($customField['customValue'])) {
2850 foreach ($customField['customValue'] as $customFieldValues) {
2851 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2856 $values['participant']['customGroup'] = $participantCustomGroup;
2858 //get location details
2859 $locationParams = array(
2860 'entity_id' => $this->_relatedObjects
['event']->id
,
2861 'entity_table' => 'civicrm_event',
2863 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2865 $ufJoinParams = array(
2866 'entity_table' => 'civicrm_event',
2867 'entity_id' => $ids['event'],
2868 'module' => 'CiviEvent',
2871 list($custom_pre_id,
2873 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2875 $values['custom_pre_id'] = $custom_pre_id;
2876 $values['custom_post_id'] = $custom_post_ids;
2878 // set lineItem for event contribution
2880 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2881 if (!empty($participantIds)) {
2882 foreach ($participantIds as $pIDs) {
2883 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2884 if (!CRM_Utils_System
::isNull($lineItem)) {
2885 $values['lineItem'][] = $lineItem;
2892 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
2894 $customGroup = array();
2895 foreach ($groupTree as $key => $group) {
2896 if ($key === 'info') {
2900 foreach ($group['fields'] as $k => $customField) {
2901 $groupLabel = $group['title'];
2902 if (!empty($customField['customValue'])) {
2903 foreach ($customField['customValue'] as $customFieldValues) {
2904 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2909 $values['customGroup'] = $customGroup;
2911 $values['is_pay_later'] = $this->is_pay_later
;
2917 * Assign message variables to template but try to break the habit.
2919 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
2920 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
2921 * multiple recurring payments for processors like IATS that use tokens.
2923 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2924 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2925 * Note we send directly from this function in some cases because it is only partly refactored.
2927 * Don't call this function directly as the signature will change.
2931 * @param bool $returnMessageText
2935 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
2936 // @todo - this should have a better separation of concerns - ie.
2937 // gatherMessageValues should build an array of values to be assigned to the template
2938 // and this function should assign them (assigning null if not set).
2939 // the way the pcpParams & honor Params section works is a baby-step towards this.
2940 $template = CRM_Core_Smarty
::singleton();
2941 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2942 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2943 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2945 // For some unit tests contribution cannot contain paymentProcessor information
2946 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
2947 $template->assign('contributeMode', CRM_Utils_Array
::value($billingMode, CRM_Core_SelectValues
::contributeMode()));
2949 //assign honor information to receipt message
2950 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2952 $honorParams = ['soft_credit_type' => NULL, 'honor_block_is_active' => NULL];
2953 if (isset($softRecord['soft_credit'])) {
2954 //if id of contribution page is present
2955 if (!empty($values['id'])) {
2956 $values['honor'] = array(
2957 'honor_profile_values' => array(),
2958 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2959 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2962 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
2963 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
2966 //offline contribution
2967 $softCreditTypes = $softCredits = array();
2968 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2969 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2970 $softCredits[$key] = array(
2971 'Name' => $softCredit['contact_name'],
2972 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2975 $template->assign('softCreditTypes', $softCreditTypes);
2976 $template->assign('softCredits', $softCredits);
2980 $dao = new CRM_Contribute_DAO_ContributionProduct();
2981 $dao->contribution_id
= $this->id
;
2982 if ($dao->find(TRUE)) {
2983 $premiumId = $dao->product_id
;
2984 $template->assign('option', $dao->product_option
);
2986 $productDAO = new CRM_Contribute_DAO_Product();
2987 $productDAO->id
= $premiumId;
2988 $productDAO->find(TRUE);
2989 $template->assign('selectPremium', TRUE);
2990 $template->assign('product_name', $productDAO->name
);
2991 $template->assign('price', $productDAO->price
);
2992 $template->assign('sku', $productDAO->sku
);
2994 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2995 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2996 if (!$values['amount'] && isset($this->total_amount
)) {
2997 $values['amount'] = $this->total_amount
;
3000 $pcpParams = ['pcpBlock' => NULL, 'pcp_display_in_roll' => NULL, 'pcp_roll_nickname' => NULL, 'pcp_personal_note' => NULL, 'title' => NULL];
3002 if (strtolower($this->_component
) == 'contribute') {
3004 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3005 $softDAO->contribution_id
= $this->id
;
3006 if ($softDAO->find(TRUE)) {
3007 $pcpParams['pcpBlock'] = TRUE;
3008 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
3009 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
3010 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
3012 //assign the pcp page title for email subject
3013 $pcpDAO = new CRM_PCP_DAO_PCP();
3014 $pcpDAO->id
= $softDAO->pcp_id
;
3015 if ($pcpDAO->find(TRUE)) {
3016 $pcpParams['title'] = $pcpDAO->title
;
3020 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3021 $template->assign($templateKey, $templateValue);
3024 if ($this->financial_type_id
) {
3025 $values['financial_type_id'] = $this->financial_type_id
;
3028 $template->assign('trxn_id', $this->trxn_id
);
3029 $template->assign('receive_date',
3030 CRM_Utils_Date
::processDate($this->receive_date
)
3032 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
3033 $template->assign('action', $this->is_test ?
1024 : 1);
3034 $template->assign('receipt_text',
3035 CRM_Utils_Array
::value('receipt_text',
3039 $template->assign('is_monetary', 1);
3040 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3041 $template->assign('currency', $this->currency
);
3042 $template->assign('address', CRM_Utils_Address
::format($input));
3043 if (!empty($values['customGroup'])) {
3044 $template->assign('customGroup', $values['customGroup']);
3046 if (!empty($values['softContributions'])) {
3047 $template->assign('softContributions', $values['softContributions']);
3049 if ($this->_component
== 'event') {
3050 $template->assign('title', $values['event']['title']);
3051 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3052 $viewRoles = array();
3053 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3054 $viewRoles[] = $participantRoles[$v];
3056 $values['event']['participant_role'] = implode(', ', $viewRoles);
3057 $template->assign('event', $values['event']);
3058 $template->assign('participant', $values['participant']);
3059 $template->assign('location', $values['location']);
3060 $template->assign('customPre', $values['custom_pre_id']);
3061 $template->assign('customPost', $values['custom_post_id']);
3064 if ($this->_relatedObjects
['participant']->is_test
) {
3068 $values['params'] = array();
3069 //to get email of primary participant.
3070 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3071 $primaryAmount[] = array(
3072 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3073 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3075 //build an array of cId/pId of participants
3076 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3077 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3078 //send receipt to additional participant if exists
3079 if (count($additionalIDs)) {
3080 $template->assign('isPrimary', 0);
3081 $template->assign('customProfile', NULL);
3082 //set additionalParticipant true
3083 $values['params']['additionalParticipant'] = TRUE;
3084 foreach ($additionalIDs as $pId => $cId) {
3086 //to change the status pending to completed
3087 $additional = new CRM_Event_DAO_Participant();
3088 $additional->id
= $pId;
3089 $additional->contact_id
= $cId;
3090 $additional->find(TRUE);
3091 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3092 $additional->status_id
= 1;
3093 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3094 //if additional participant dont have email
3096 if (!$additionalParticipantInfo) {
3097 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3099 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
3100 $primaryAmount[] = array(
3101 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3102 'amount' => $additional->fee_amount
,
3104 $additional->save();
3105 $additional->free();
3106 $template->assign('amount', $amount);
3107 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3111 //build an array of custom profile and assigning it to template
3112 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3114 if (count($customProfile)) {
3115 $template->assign('customProfile', $customProfile);
3118 // for primary contact
3119 $values['params']['additionalParticipant'] = FALSE;
3120 $template->assign('isPrimary', 1);
3121 $template->assign('amount', $primaryAmount);
3122 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3123 if ($this->payment_instrument_id
) {
3124 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3125 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3127 // carry paylater, since we did not created billing,
3128 // so need to pull email from primary location, CRM-4395
3129 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3135 * Check whether payment processor supports
3136 * cancellation of contribution subscription
3138 * @param int $contributionId
3141 * @param bool $isNotCancelled
3145 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3146 $cacheKeyString = "$contributionId";
3147 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3149 static $supportsCancel = array();
3151 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3152 $supportsCancel[$cacheKeyString] = FALSE;
3153 $isCancelled = FALSE;
3155 if ($isNotCancelled) {
3156 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3159 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3160 if (!empty($paymentObject)) {
3161 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3164 return $supportsCancel[$cacheKeyString];
3168 * Check whether subscription is already cancelled.
3170 * @param int $contributionId
3174 * contribution status
3176 public static function isSubscriptionCancelled($contributionId) {
3178 SELECT cr.contribution_status_id
3179 FROM civicrm_contribution_recur cr
3180 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3181 WHERE con.id = %1 LIMIT 1";
3182 $params = array(1 => array($contributionId, 'Integer'));
3183 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3184 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
3185 if ($status == 'Cancelled') {
3192 * Create all financial accounts entry.
3194 * @param array $params
3195 * Contribution object, line item array and params for trxn.
3198 * @param array $financialTrxnValues
3200 * @return null|\CRM_Core_BAO_FinancialTrxn
3202 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3203 $skipRecords = $update = $return = $isRelatedId = FALSE;
3205 $additionalParticipantId = array();
3206 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3207 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3209 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3210 $entityId = $params['participant_id'];
3211 $entityTable = 'civicrm_participant';
3212 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3214 elseif (!empty($params['membership_id'])) {
3215 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3216 // are created off one contribution should be handled elsewhere
3217 $entityId = $params['membership_id'];
3218 $entityTable = 'civicrm_membership';
3221 $entityId = $params['contribution']->id
;
3222 $entityTable = 'civicrm_contribution';
3225 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3226 $isRelatedId = TRUE;
3229 $entityID[] = $entityId;
3230 if (!empty($additionalParticipantId)) {
3231 $entityID +
= $additionalParticipantId;
3233 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3234 if (empty($params['prevContribution'])) {
3241 $statusId = $params['contribution']->contribution_status_id
;
3242 // CRM-13964 partial payment
3243 if ($contributionStatus == 'Partially paid'
3244 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])
3246 $partialAmtPay = CRM_Utils_Rule
::cleanMoney($params['partial_amount_to_pay']);
3247 $partialAmtTotal = CRM_Utils_Rule
::cleanMoney($params['partial_payment_total']);
3249 $fromFinancialAccountId = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3250 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
3251 $params['total_amount'] = $partialAmtPay;
3253 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3254 if (empty($balanceTrxnInfo['trxn_id'])) {
3255 // create new balance transaction record
3256 $toFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3258 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3259 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3260 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3261 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3262 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3263 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3264 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3265 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3266 $balanceTrxnParams['status_id'] = $statusId;
3267 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3268 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3269 $balanceTrxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3270 $balanceTrxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3271 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3272 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3274 $balanceTrxnParams['is_payment'] = 1;
3276 if (!empty($params['payment_processor'])) {
3277 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3279 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3283 // build line item array if its not set in $params
3284 if (empty($params['line_item']) ||
$additionalParticipantId) {
3285 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3288 if ($contributionStatus != 'Failed' &&
3289 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3291 $skipRecords = TRUE;
3292 $pendingStatus = array(
3296 if (in_array($contributionStatus, $pendingStatus)) {
3297 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3298 $params['financial_type_id'],
3299 'Accounts Receivable Account is'
3302 elseif (!empty($params['payment_processor'])) {
3303 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3304 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', array(
3305 'id' => $params['payment_processor'],
3306 'return' => 'payment_instrument_id',
3309 elseif (!empty($params['payment_instrument_id'])) {
3310 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3313 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3314 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3315 $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);
3318 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3319 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3320 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3322 //build financial transaction params
3323 $trxnParams = array(
3324 'contribution_id' => $params['contribution']->id
,
3325 'to_financial_account_id' => $params['to_financial_account_id'],
3326 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3327 'total_amount' => $totalAmount,
3328 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3329 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3330 'currency' => $params['contribution']->currency
,
3331 'trxn_id' => $params['contribution']->trxn_id
,
3332 'status_id' => $statusId,
3333 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3334 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3335 'pan_truncation' => CRM_Utils_Array
::value('pan_truncation', $params),
3336 'card_type_id' => CRM_Utils_Array
::value('card_type_id', $params),
3338 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3339 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3340 if (isset($params['refund_trxn_id'])) {
3341 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3342 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3345 //CRM-16259, set is_payment flag for non pending status
3346 if (!in_array($contributionStatus, $pendingStatus)) {
3347 $trxnParams['is_payment'] = 1;
3349 if (!empty($params['payment_processor'])) {
3350 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3353 if (isset($fromFinancialAccountId)) {
3354 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3357 // consider external values passed for recording transaction entry
3358 if (!empty($financialTrxnValues)) {
3359 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3361 if (empty($trxnParams['payment_processor_id'])) {
3362 unset($trxnParams['payment_processor_id']);
3365 $params['trxnParams'] = $trxnParams;
3367 if (!empty($params['prevContribution'])) {
3369 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3370 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3371 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3372 if (!isset($params['trxnParams']['trxn_id'])) {
3373 // Actually I have no idea why we are overwriting any values from the previous contribution.
3374 // (filling makes sense to me). However, only protecting this value as I really really know we
3375 // don't want this one overwritten.
3377 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3379 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3381 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3382 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3383 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3385 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3386 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3389 //if financial type is changed
3390 if (!empty($params['financial_type_id']) &&
3391 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3393 $accountRelationship = 'Income Account is';
3394 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3395 $accountRelationship = 'Deferred Revenue Account is';
3397 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3398 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3399 if ($oldFinancialAccount != $newFinancialAccount) {
3400 $params['total_amount'] = 0;
3401 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3402 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3403 $params['prevContribution']->financial_type_id
, $accountRelationship);
3406 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3407 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3408 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3411 self
::updateFinancialAccounts($params, 'changeFinancialType');
3412 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3413 $params['financial_account_id'] = $newFinancialAccount;
3414 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3415 self
::updateFinancialAccounts($params);
3416 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3418 $params['deferred_financial_account_id'] = $newFinancialAccount;
3422 //Update contribution status
3423 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3424 if (!isset($params['refund_trxn_id'])) {
3425 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3426 // gets preference over another so I am only 'protecting' a very specific tested flow
3427 // and letting natural justice take care of the rest.
3428 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3430 if (!empty($params['contribution_status_id']) &&
3431 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3433 //Update Financial Records
3434 self
::updateFinancialAccounts($params, 'changedStatus');
3438 // change Payment Instrument for a Completed contribution
3439 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3440 // instrument is null and now new payment instrument is added along with the payment
3441 if (!$params['contribution']->payment_instrument_id
) {
3442 $params['contribution']->find(TRUE);
3444 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3445 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3447 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3448 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3451 //if Change contribution amount
3452 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3453 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3454 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3455 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3456 if (isset($totalAmount) &&
3457 $totalAmount != $params['prevContribution']->total_amount
3459 //Update Financial Records
3460 $params['trxnParams']['from_financial_account_id'] = NULL;
3461 self
::updateFinancialAccounts($params, 'changedAmount');
3466 // Looks like we might have a data correction update.
3467 // This would be a case where a transaction id has been entered but it is incorrect &
3468 // the person goes back in & fixes it, as opposed to a new transaction.
3469 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3470 // the data fix scenario.
3472 if (isset($params['refund_trxn_id'])) {
3473 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3474 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3475 civicrm_api3('FinancialTrxn', 'create', array('id' => $refundIDs['financialTrxnId'], 'trxn_id' => $params['refund_trxn_id']));
3478 $cardType = CRM_Utils_Array
::value('card_type_id', $params);
3479 $panTruncation = CRM_Utils_Array
::value('pan_truncation', $params);
3480 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3485 // records finanical trxn and entity financial trxn
3486 // also make it available as return value
3487 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3488 $trxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3489 $trxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3490 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3491 $params['entity_id'] = $financialTxn->id
;
3492 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3493 self
::$_trxnIDs[] = $financialTxn->id
;
3497 // record line items and financial items
3498 if (empty($params['skipLineItem'])) {
3499 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3502 // create batch entry if batch_id is passed and
3503 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3504 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3505 $entityParams = array(
3506 'batch_id' => $params['batch_id'],
3507 'entity_table' => 'civicrm_financial_trxn',
3508 'entity_id' => $financialTxn->id
,
3510 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3513 // when a fee is charged
3514 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3515 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3518 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3519 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3521 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3522 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3523 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3525 unset($params['line_item']);
3526 self
::$_trxnIDs = NULL;
3531 * Update all financial accounts entry.
3533 * @param array $params
3534 * Contribution object, line item array and params for trxn.
3536 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3537 * adds unpredictability.
3539 * @param string $context
3543 public static function updateFinancialAccounts(&$params, $context = NULL) {
3545 $inputParams = $params;
3547 $currentContributionStatus = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
3548 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
3550 if (($previousContributionStatus == 'Pending'
3551 ||
$previousContributionStatus == 'In Progress')
3552 && $currentContributionStatus == 'Completed'
3553 && $context == 'changePaymentInstrument'
3557 if ((($previousContributionStatus == 'Partially paid'
3558 && $currentContributionStatus == 'Completed')
3559 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
3560 && $currentContributionStatus == 'Partially paid'))
3561 && $context == 'changedStatus'
3565 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3566 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3567 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3569 if ($context == 'changedStatus') {
3570 if ($previousContributionStatus == 'Completed'
3571 && (self
::isContributionStatusNegative($params['contribution']->contribution_status_id
))
3574 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3575 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3576 if (empty($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3577 $creditNoteId = self
::createCreditNoteId();
3578 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3581 elseif (($previousContributionStatus == 'Pending'
3582 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
3584 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3585 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
3587 if ($currentContributionStatus == 'Cancelled') {
3588 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3589 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3590 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3591 if (is_null($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3592 $creditNoteId = self
::createCreditNoteId();
3593 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3597 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3598 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3603 if ($context == 'changedStatus') {
3604 if (($previousContributionStatus == 'Pending'
3605 ||
$previousContributionStatus == 'In Progress')
3606 && ($currentContributionStatus == 'Completed')
3608 if (empty($params['line_item'])) {
3610 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3611 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3612 // & this can be removed
3615 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3616 // This is an update so original currency if none passed in.
3617 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
3619 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
3620 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3621 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3622 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
3623 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3624 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3626 $entityParams = array(
3627 'entity_table' => 'civicrm_financial_item',
3629 foreach ($params['line_item'] as $fieldId => $fields) {
3630 foreach ($fields as $fieldValueId => $lineItemDetails) {
3632 1 => array(CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'), 'Integer'),
3633 2 => array($lineItemDetails['id'], 'Integer'),
3635 CRM_Core_DAO
::executeQuery($query, $fparams);
3637 1 => array($lineItemDetails['id'], 'Integer'),
3639 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3640 while ($financialItem->fetch()) {
3641 $entityParams['entity_id'] = $financialItem->id
;
3642 $entityParams['amount'] = $financialItem->amount
;
3643 foreach (self
::$_trxnIDs as $tID) {
3644 $entityParams['financial_trxn_id'] = $tID;
3645 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3654 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3655 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3656 $params['entity_id'] = $trxn->id
;
3657 if ($context != 'changePaymentInstrument') {
3658 $itemParams['entity_table'] = 'civicrm_line_item';
3659 $trxnIds['id'] = $params['entity_id'];
3660 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution']->id
);
3661 foreach ($params['line_item'] as $fieldId => $fields) {
3662 foreach ($fields as $fieldValueId => $lineItemDetails) {
3663 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($lineItemDetails['id']);
3664 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3665 if ($params['contribution']->receive_date
) {
3666 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3669 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array
::value('financial_account_id', $prevFinancialItem));
3671 $currency = $params['prevContribution']->currency
;
3672 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3673 if ($params['contribution']->currency
) {
3674 $currency = $params['contribution']->currency
;
3676 $previousLineItemTotal = CRM_Utils_Array
::value('line_total', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
3677 $itemParams = array(
3678 'transaction_date' => $receiveDate,
3679 'contact_id' => $params['prevContribution']->contact_id
,
3680 'currency' => $currency,
3681 'amount' => self
::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
3682 'description' => CRM_Utils_Array
::value('description', $prevFinancialItem),
3683 'status_id' => $prevFinancialItem['status_id'],
3684 'financial_account_id' => $financialAccount,
3685 'entity_table' => 'civicrm_line_item',
3686 'entity_id' => $lineItemDetails['id'],
3688 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3689 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3690 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
3691 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
3693 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') ||
($context == 'changeFinancialType')) {
3694 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
3695 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3696 $taxAmount = (float) $lineItemDetails['tax_amount'];
3697 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
3698 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
3699 $taxAmount = CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
3701 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
3702 $taxAmount -= CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
3704 $itemParams['amount'] = self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * $taxAmount;
3705 $itemParams['description'] = $taxTerm;
3706 if ($lineItemDetails['financial_type_id']) {
3707 $itemParams['financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount(
3708 $lineItemDetails['financial_type_id'],
3709 'Sales Tax Account is'
3712 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3717 if ($context == 'changeFinancialType') {
3718 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3719 $params['skipLineItem'] = FALSE;
3720 foreach ($params['line_item'] as &$lineItems) {
3721 foreach ($lineItems as &$line) {
3722 $line['financial_type_id'] = $params['financial_type_id'];
3727 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, $context);
3731 * Is this contribution status a reversal.
3733 * If so we would expect to record a negative value in the financial_trxn table.
3735 * @param int $status_id
3739 public static function isContributionStatusNegative($status_id) {
3740 $reversalStatuses = array('Cancelled', 'Chargeback', 'Refunded');
3741 return in_array(CRM_Contribute_PseudoConstant
::contributionStatus($status_id, 'name'), $reversalStatuses);
3745 * Check status validation on update of a contribution.
3747 * @param array $values
3748 * Previous form values before submit.
3750 * @param array $fields
3751 * The input form values.
3753 * @param array $errors
3758 public static function checkStatusValidation($values, &$fields, &$errors) {
3759 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3760 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3761 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3765 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3766 $checkStatus = array(
3767 'Cancelled' => array('Completed', 'Refunded'),
3768 'Completed' => array('Cancelled', 'Refunded', 'Chargeback'),
3769 'Pending' => array('Cancelled', 'Completed', 'Failed', 'Partially paid'),
3770 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3771 'Refunded' => array('Cancelled', 'Completed'),
3772 'Partially paid' => array('Completed'),
3775 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3776 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, array()))
3778 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3779 1 => $contributionStatuses[$values['contribution_status_id']],
3780 2 => $contributionStatuses[$fields['contribution_status_id']],
3786 * Delete contribution of contact.
3790 * @param int $contactId
3794 public static function deleteContactContribution($contactId) {
3795 $contribution = new CRM_Contribute_DAO_Contribution();
3796 $contribution->contact_id
= $contactId;
3797 $contribution->find();
3798 while ($contribution->fetch()) {
3799 self
::deleteContribution($contribution->id
);
3804 * Get options for a given contribution field.
3805 * @see CRM_Core_DAO::buildOptions
3807 * @param string $fieldName
3808 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3809 * @param array $props whatever is known about this dao object.
3811 * @return array|bool
3813 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3814 $className = __CLASS__
;
3816 if (isset($props['orderColumn'])) {
3817 $params['orderColumn'] = $props['orderColumn'];
3819 switch ($fieldName) {
3820 // This field is not part of this object but the api supports it
3821 case 'payment_processor':
3822 $className = 'CRM_Contribute_BAO_ContributionPage';
3823 // Filter results by contribution page
3824 if (!empty($props['contribution_page_id'])) {
3825 $page = civicrm_api('contribution_page', 'getsingle', array(
3827 'id' => ($props['contribution_page_id']),
3829 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3830 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3834 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3835 case 'honor_type_id':
3836 $className = 'CRM_Contribute_BAO_ContributionSoft';
3837 $fieldName = 'soft_credit_type_id';
3838 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3841 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3845 * Validate financial type.
3849 * @param int $financialTypeId
3850 * Financial Type id.
3852 * @param string $relationName
3854 * @return array|bool
3856 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3857 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3859 if (!$financialAccount) {
3860 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3867 * Function to record additional payment for partial and refund contributions.
3869 * @param int $contributionId
3870 * is the invoice contribution id (got created after processing participant payment).
3871 * @param array $trxnsData
3872 * to take user provided input of transaction details.
3873 * @param string $paymentType
3874 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3875 * @param int $participantId
3876 * @param bool $updateStatus
3878 * @return null|object
3880 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL, $updateStatus = TRUE) {
3882 if ($paymentType == 'owed') {
3883 $financialTrxn = CRM_Financial_BAO_Payment
::recordPayment($contributionId, $trxnsData, $participantId);
3885 elseif ($paymentType == 'refund') {
3886 $financialTrxn = CRM_Financial_BAO_Payment
::recordRefundPayment($contributionId, $trxnsData, $updateStatus);
3887 if ($participantId) {
3888 // update participant status
3889 // @todo this doesn't make sense...
3890 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3891 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3892 foreach ($ids as $val) {
3893 $participantUpdate['id'] = $val;
3894 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3895 CRM_Event_BAO_Participant
::add($participantUpdate);
3900 if (!empty($financialTrxn)) {
3901 self
::recordPaymentActivity($contributionId, $participantId, $financialTrxn);
3902 return $financialTrxn;
3910 * @param $activityType
3912 * @param int $contributionId
3914 * @throws CRM_Core_Exception
3916 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3917 if ($component == 'event') {
3918 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3921 $title = ts('Contribution');
3923 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3924 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3925 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3926 $targetCid = $entityObj->contact_id
;
3927 // source record id would be the contribution id
3928 $srcRecId = $contributionId;
3931 $activityParams = array(
3932 'source_contact_id' => $targetCid,
3933 'source_record_id' => $srcRecId,
3934 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
3935 'subject' => $subject,
3936 'activity_date_time' => $date,
3937 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
3938 'skipRecentView' => TRUE,
3941 // create activity with target contacts
3942 $session = CRM_Core_Session
::singleton();
3943 $id = $session->get('userID');
3945 $activityParams['source_contact_id'] = $id;
3946 $activityParams['target_contact_id'][] = $targetCid;
3949 CRM_Activity_BAO_Activity
::create($activityParams);
3953 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3957 * @param bool $getTrxnInfo
3958 * @param bool $usingLineTotal
3962 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3963 // @todo deprecate passing in component - always call with contribution.
3964 if ($component == 'event') {
3965 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3967 if (!$contributionId) {
3968 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3969 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3970 $id = $primaryParticipantId;
3972 if (!$contributionId) {
3977 elseif ($component == 'membership') {
3978 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
3981 $contributionId = $id;
3984 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3985 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3987 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3988 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3990 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3991 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
3994 $baseTrxnId = $total['trxn_id'];
3995 $total = $total['total_amount'];
3998 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
4000 $contribution = civicrm_api3('Contribution', 'getsingle', array('id' => $contributionId, 'return' => array('currency', 'is_pay_later', 'contribution_status_id', 'financial_type_id')));
4002 $info['payLater'] = $contribution['is_pay_later'];
4003 $info['contribution_status'] = $contribution['contribution_status'];
4004 $info['currency'] = $contribution['currency'];
4006 $financialTypeId = $contribution['financial_type_id'];
4007 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, 'Expense Account is');
4009 if ($paymentBalance == 0 && $info['payLater']) {
4010 // @todo - review - this looks very unlikely to be correct.
4011 // the balance should be correct based on payment transactions not
4013 $paymentBalance = $total;
4016 $info['total'] = $total;
4017 $info['paid'] = $total - $paymentBalance;
4018 $info['balance'] = $paymentBalance;
4020 $info['component'] = $component;
4022 if ($getTrxnInfo && $baseTrxnId) {
4023 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
4025 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
4027 ft.payment_instrument_id,
4028 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
4030 FROM civicrm_contribution con
4031 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4032 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4033 AND ft.to_financial_account_id != %2
4034 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
4035 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
4036 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
4038 WHERE con.id = %1 AND ft.is_payment = 1
4040 $queryParams = array(
4041 1 => array($contributionId, 'Integer'),
4042 2 => array($feeFinancialAccount, 'Integer'),
4044 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
4045 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
4047 while ($resultDAO->fetch()) {
4048 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4049 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4050 if ($resultDAO->card_type_id
) {
4051 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
4052 $pantruncation = '';
4053 if ($resultDAO->pan_truncation
) {
4054 $pantruncation = ": {$resultDAO->pan_truncation}";
4056 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
4059 // show payment edit link only for payments done via backoffice form
4060 $paymentEditLink = '';
4061 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
4063 CRM_Core_Action
::UPDATE
=> array(
4064 'name' => "<i class='crm-i fa-pencil'></i>",
4065 'url' => 'civicrm/payment/edit',
4066 'class' => 'medium-popup',
4067 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
4068 'title' => ts('Edit Payment'),
4071 $paymentEditLink = CRM_Core_Action
::formLink(
4073 CRM_Core_Action
::mask(array(CRM_Core_Permission
::EDIT
)),
4075 'id' => $resultDAO->id
,
4076 'contribution_id' => $contributionId,
4082 'id' => $resultDAO->id
,
4083 'total_amount' => $resultDAO->total_amount
,
4084 'financial_type' => $resultDAO->financial_account
,
4085 'payment_instrument' => $paidByLabel,
4086 'receive_date' => $resultDAO->trxn_date
,
4087 'trxn_id' => $resultDAO->trxn_id
,
4088 'status' => $statuses[$resultDAO->status_id
],
4089 'currency' => $resultDAO->currency
,
4090 'action' => $paymentEditLink,
4092 if ($paidByName == 'Check') {
4093 $val['check_number'] = $resultDAO->check_number
;
4097 $info['transaction'] = $rows;
4100 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
4105 * Get the outstanding balance on a contribution.
4107 * @param int $contributionId
4108 * @param float $contributionTotal
4109 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
4113 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
4114 if ($contributionTotal === NULL) {
4115 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4118 return CRM_Utils_Money
::subtractCurrencies(
4120 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE) ?
: 0,
4121 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4126 * Get the tax amount (misnamed function).
4128 * @param array $params
4129 * @param bool $isLineItem
4133 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4134 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4136 // This function should be only called after standardisation (removal of
4137 // thousand separator & using a decimal point for cents separator.
4138 // However, we don't know if that is always true :-(
4139 // There is a deprecation notice tho :-)
4140 $unknownIfMoneyIsClean = empty($params['skipCleanMoney']) && !$isLineItem;
4141 // Update contribution.
4142 if (!empty($params['id'])) {
4143 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4144 // there are no tax implications - early return.
4145 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4148 if (empty($params['prevContribution'])) {
4149 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4152 foreach (array('total_amount', 'financial_type_id', 'fee_amount') as $field) {
4153 if (!isset($params[$field])) {
4154 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4155 // Tax amount gets added back on later....
4156 $params['total_amount'] = $params['prevContribution']->total_amount
-
4157 $params['prevContribution']->tax_amount
;
4160 $params[$field] = $params['prevContribution']->$field;
4161 if ($params[$field] != $params['prevContribution']->$field) {
4167 self
::calculateMissingAmountParams($params, $params['id']);
4168 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4169 // Assign tax Amount on update of contribution
4170 if (!empty($params['prevContribution']->tax_amount
)) {
4171 $params['tax_amount'] = 'null';
4172 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4173 foreach ($params['line_item'] as $setID => $priceField) {
4174 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4175 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4182 // New Contribution and update of contribution with tax rate financial type
4183 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4184 empty($params['skipLineItem']) && !$isLineItem
4186 $taxRateParams = $taxRates[$params['financial_type_id']];
4187 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams, $unknownIfMoneyIsClean);
4188 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4190 // Get Line Item on update of contribution
4191 if (isset($params['id'])) {
4192 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4195 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4197 foreach ($params['line_item'] as $setID => $priceField) {
4198 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4199 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4202 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4204 elseif (isset($params['api.line_item.create'])) {
4205 // Update total amount of contribution using lineItem
4206 $taxAmountArray = array();
4207 foreach ($params['api.line_item.create'] as $key => $value) {
4208 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4209 $taxRate = $taxRates[$value['financial_type_id']];
4210 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4211 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4214 $params['tax_amount'] = array_sum($taxAmountArray);
4215 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4218 // update line item of contrbution
4219 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4220 $taxRate = $taxRates[$params['financial_type_id']];
4221 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate, $unknownIfMoneyIsClean);
4222 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4229 * Check financial type validation on update of a contribution.
4231 * @param Integer $financialTypeId
4232 * Value of latest Financial Type.
4234 * @param Integer $contributionId
4237 * @param array $errors
4242 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4243 if (!empty($financialTypeId)) {
4244 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4245 if ($oldFinancialTypeId == $financialTypeId) {
4249 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4251 '1' => array($contributionId, 'Integer'),
4253 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4254 if ($result->N
> 1) {
4255 $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.');
4260 * Update related pledge payment payments.
4262 * This function has been refactored out of the back office contribution form and may
4263 * still overlap with other functions.
4265 * @param string $action
4266 * @param int $pledgePaymentID
4267 * @param int $contributionID
4268 * @param bool $adjustTotalAmount
4269 * @param float $total_amount
4270 * @param float $original_total_amount
4271 * @param int $contribution_status_id
4272 * @param int $original_contribution_status_id
4274 public static function updateRelatedPledge(
4280 $original_total_amount,
4281 $contribution_status_id,
4282 $original_contribution_status_id
4284 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4288 if ($pledgePaymentID) {
4289 //store contribution id in payment record.
4290 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4293 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4300 if (!$pledgePaymentID) {
4303 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4309 $updatePledgePaymentStatus = FALSE;
4311 // If either the status or the amount has changed we update the pledge status.
4312 if ($action & CRM_Core_Action
::ADD
) {
4313 $updatePledgePaymentStatus = TRUE;
4315 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4316 ($original_total_amount != $total_amount))
4318 $updatePledgePaymentStatus = TRUE;
4321 if ($updatePledgePaymentStatus) {
4322 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4323 array($pledgePaymentID),
4324 $contribution_status_id,
4333 * Compute the stats values
4337 * @param string $stat either 'mode' or 'median'
4338 * @param string $sql
4339 * @param string $alias of civicrm_contribution
4341 * @return array|null
4343 public static function computeStats($stat, $sql, $alias = NULL) {
4344 CRM_Core_Error
::deprecatedFunctionWarning('computeStats is now deprecated');
4349 * Is there only one line item attached to the contribution.
4355 * @throws \CiviCRM_API3_Exception
4357 public static function isSingleLineItem($id) {
4358 $lineItemCount = civicrm_api3('LineItem', 'getcount', array('contribution_id' => $id));
4359 return ($lineItemCount == 1);
4363 * Complete an order.
4365 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4367 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4369 * Moving it out of the BaseIPN class is just the first step.
4371 * @param array $input
4373 * @param array $objects
4374 * @param CRM_Core_Transaction $transaction
4376 * @param CRM_Contribute_BAO_Contribution $contribution
4380 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution) {
4381 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4382 // The previous details are used when calculating line items so keep it before any code that 'does something'
4383 if (!empty($contribution->id
)) {
4384 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4385 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4387 $inputContributionWhiteList = array(
4392 'payment_instrument_id',
4397 'contribution_status_id',
4401 if (self
::isSingleLineItem($primaryContributionID)) {
4402 $inputContributionWhiteList[] = 'financial_type_id';
4405 $participant = CRM_Utils_Array
::value('participant', $objects);
4406 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4407 $recurringContributionID = (empty($recurContrib->id
)) ?
NULL : $recurContrib->id
;
4408 $event = CRM_Utils_Array
::value('event', $objects);
4410 $paymentProcessorId = '';
4411 if (isset($objects['paymentProcessor'])) {
4412 if (is_array($objects['paymentProcessor'])) {
4413 $paymentProcessorId = $objects['paymentProcessor']['id'];
4416 $paymentProcessorId = $objects['paymentProcessor']->id
;
4420 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4422 $contributionParams = array_merge(array(
4423 'contribution_status_id' => $completedContributionStatusID,
4424 'source' => self
::getRecurringContributionDescription($contribution, $event),
4425 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4428 // CRM-20678 Ensure that the currency is correct in subseqent transcations.
4429 if (empty($contributionParams['currency']) && isset($objects['first_contribution']->currency
)) {
4430 $contributionParams['currency'] = $objects['first_contribution']->currency
;
4433 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
4435 // If paymentProcessor is not set then the payment_instrument_id would not be correct.
4436 // not clear when or if this would occur if you encounter this please fix here & add a unit test.
4437 if (empty($contributionParams['payment_instrument_id']) && isset($contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'])) {
4438 $contributionParams['payment_instrument_id'] = $contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'];
4441 if ($recurringContributionID) {
4442 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4444 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4446 if (empty($contributionParams['receive_date']) && $changeDate) {
4447 $contributionParams['receive_date'] = $changeDate;
4450 self
::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
4451 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4454 if (isset($input['is_email_receipt'])) {
4455 $values['is_email_receipt'] = $input['is_email_receipt'];
4458 if ($input['component'] == 'contribute') {
4459 if ($contribution->contribution_page_id
) {
4460 // Figure out what we gain from this.
4461 // Note that we may have overwritten the is_email_receipt input, fix that below.
4462 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4464 elseif ($recurContrib && $recurringContributionID) {
4465 $values['amount'] = $recurContrib->amount
;
4466 $values['financial_type_id'] = $objects['contributionType']->id
;
4467 $values['title'] = $source = ts('Offline Recurring Contribution');
4470 if (isset($input['is_email_receipt'])) {
4471 // CRM-19601 - we may have overwritten this above.
4472 $values['is_email_receipt'] = $input['is_email_receipt'];
4474 elseif ($recurContrib && $recurringContributionID) {
4475 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4476 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4477 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4480 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4481 self
::updateMembershipBasedOnCompletionOfContribution(
4483 $primaryContributionID,
4489 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4490 if ($event->is_email_confirm
) {
4491 // @todo this should be set by the function that sends the mail after sending.
4492 $contributionParams['receipt_date'] = $changeDate;
4494 $participantParams['id'] = $participant->id
;
4495 $participantParams['status_id'] = 'Registered';
4496 civicrm_api3('Participant', 'create', $participantParams);
4500 $contributionParams['id'] = $contribution->id
;
4502 // CRM-19309 - if you update the contribution here with financial_type_id it can/will mess with $lineItem
4503 // unsetting it here does NOT cause any other contribution test to fail!
4504 unset($contributionParams['financial_type_id']);
4505 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4507 // Add new soft credit against current $contribution.
4508 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4509 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4512 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4513 'labelColumn' => 'name',
4516 if (isset($input['prevContribution']) && (!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4517 $input['payment_processor'] = $paymentProcessorId;
4520 if (!empty($contribution->_relatedObjects
['participant'])) {
4521 $input['contribution_mode'] = 'participant';
4522 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4524 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4525 $input['contribution_mode'] = 'membership';
4526 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4527 $contribution->trxn_id
= CRM_Utils_Array
::value('trxn_id', $input);
4528 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4531 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4532 $transaction->commit();
4534 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution->id
, $recurringContributionID,
4535 $contributionParams['contribution_status_id'], $input['amount']);
4537 // create an activity record
4538 if ($input['component'] == 'contribute') {
4540 $targetContactID = NULL;
4541 if (!empty($ids['related_contact'])) {
4542 $targetContactID = $contribution->contact_id
;
4543 $contribution->contact_id
= $ids['related_contact'];
4545 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4548 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4549 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4550 if (!array_key_exists('is_email_receipt', $values) ||
4551 $values['is_email_receipt'] == 1
4553 civicrm_api3('Contribution', 'sendconfirmation', array(
4554 'id' => $contribution->id
,
4555 'payment_processor_id' => $paymentProcessorId,
4557 CRM_Core_Error
::debug_log_message("Receipt sent");
4560 CRM_Core_Error
::debug_log_message("Success: Database updated");
4561 return $contributionResult;
4565 * Send receipt from contribution.
4567 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4569 * Note that the compose message part has been moved to contribution
4570 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4572 * @param array $input
4573 * Incoming data from Payment processor.
4575 * Related object IDs.
4576 * @param int $contributionID
4577 * @param array $values
4578 * Values related to objects that have already been loaded.
4579 * @param bool $returnMessageText
4580 * Should text be returned instead of sent. This.
4581 * is because the function is also used to generate pdfs
4584 * @throws \CRM_Core_Exception
4585 * @throws \CiviCRM_API3_Exception
4587 public static function sendMail(&$input, &$ids, $contributionID, &$values,
4588 $returnMessageText = FALSE) {
4590 $contribution = new CRM_Contribute_BAO_Contribution();
4591 $contribution->id
= $contributionID;
4592 if (!$contribution->find(TRUE)) {
4593 throw new CRM_Core_Exception('Contribution does not exist');
4595 $contribution->loadRelatedObjects($input, $ids, TRUE);
4596 // set receipt from e-mail and name in value
4597 if (!$returnMessageText) {
4598 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4600 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4601 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4602 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4603 civicrm_api3('Contribution', 'create', array('receipt_date' => 'now', 'id' => $contribution->id
));
4609 * Generate From email and from name in an array values
4610 * @param array $input
4611 * @param \CRM_Contribute_BAO_Contribution $contribution
4614 public static function generateFromEmailAndName($input, $contribution) {
4615 // Use input value if supplied.
4616 if (!empty($input['receipt_from_email'])) {
4617 return array(CRM_Utils_array
::value('receipt_from_name', $input, ''), $input['receipt_from_email']);
4619 // if we are still empty see if we can use anything from a contribution page.
4620 $pageValues = array();
4621 if (!empty($contribution->contribution_page_id
)) {
4622 $pageValues = civicrm_api3('ContributionPage', 'getsingle', array('id' => $contribution->contribution_page_id
));
4624 // if we are still empty see if we can use anything from a contribution page.
4625 if (!empty($pageValues['receipt_from_email'])) {
4626 return array($pageValues['receipt_from_name'], $pageValues['receipt_from_email']);
4628 // If we are still empty fall back to the domain or logged in user information.
4629 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4633 * Generate credit note id with next avaible number
4638 public static function createCreditNoteId() {
4639 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4641 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution WHERE creditnote_id IS NOT NULL");
4642 $creditNoteId = NULL;
4646 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4647 $result = civicrm_api3('Contribution', 'getcount', array(
4649 'creditnote_id' => $creditNoteId,
4651 } while ($result > 0);
4653 return $creditNoteId;
4657 * Load related memberships.
4659 * Note that in theory it should be possible to retrieve these from the line_item table
4660 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4661 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4662 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4663 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4665 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4669 * @return array $ids
4673 public function loadRelatedMembershipObjects($ids = []) {
4675 SELECT membership_id
4676 FROM civicrm_membership_payment
4677 WHERE contribution_id = %1 ";
4678 $params = array(1 => array($this->id
, 'Integer'));
4679 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, array());
4681 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4682 while ($dao->fetch()) {
4683 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4684 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4688 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4689 foreach ($ids['membership'] as $id) {
4691 $membership = new CRM_Member_BAO_Membership();
4692 $membership->id
= $id;
4693 if (!$membership->find(TRUE)) {
4694 throw new Exception("Could not find membership record: $id");
4696 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4697 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4698 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4699 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4700 $membership->free();
4708 * This function is used to record partial payments for contribution
4710 * @param array $contribution
4712 * @param array $params
4714 * @return CRM_Financial_DAO_FinancialTrxn
4716 public static function recordPartialPayment($contribution, $params) {
4718 $balanceTrxnParams['to_financial_account_id'] = self
::getToFinancialAccount($contribution, $params);
4719 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contribution['financial_type_id'], 'Accounts Receivable Account is');
4720 $balanceTrxnParams['from_financial_account_id'] = $fromFinancialAccountId;
4721 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4722 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4723 $balanceTrxnParams['trxn_date'] = CRM_Utils_Array
::value('trxn_date', $params, CRM_Utils_Array
::value('contribution_receive_date', $params, date('YmdHis')));
4724 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4725 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4726 $balanceTrxnParams['currency'] = $contribution['currency'];
4727 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4728 $balanceTrxnParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_FinancialTrxn', 'status_id', 'Completed');
4729 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4730 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4732 // @todo the logic of this section seems very wrong. This code is ONLY reached from the Payment.create
4733 // routine so is_payment should ALWAYS be true
4734 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
4735 $statusId = array_search('Completed', $contributionStatuses);
4736 if ($fromFinancialAccountId != NULL &&
4737 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
4739 $balanceTrxnParams['is_payment'] = 1;
4742 if (!empty($params['payment_processor'])) {
4743 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4745 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4749 * Get the description (source field) for the recurring contribution.
4751 * @param CRM_Contribute_BAO_Contribution $contribution
4752 * @param CRM_Event_DAO_Event|null $event
4755 * @throws \CiviCRM_API3_Exception
4757 protected static function getRecurringContributionDescription($contribution, $event) {
4758 if (!empty($contribution->source
)) {
4759 return $contribution->source
;
4761 elseif (!empty($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
4762 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', array(
4763 'id' => $contribution->contribution_page_id
,
4764 'return' => 'title',
4766 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4769 return ts('Online Event Registration') . ': ' . $event->title
;
4771 elseif (!empty($contribution->contribution_recur_id
)) {
4772 return 'recurring contribution';
4778 * Function to add payments for contribution
4779 * for Partially Paid status
4781 * @param array $contributions
4782 * @param string $contributionStatusId
4785 public static function addPayments($contributions, $contributionStatusId = NULL) {
4786 // get financial trxn which is a payment
4787 $ftSql = "SELECT ft.id, ft.total_amount
4788 FROM civicrm_financial_trxn ft
4789 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
4790 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
4791 $contributionStatus = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4792 'labelColumn' => 'name',
4794 foreach ($contributions as $contribution) {
4795 if (!($contributionStatus[$contribution->contribution_status_id
] == 'Partially paid'
4796 || CRM_Utils_Array
::value($contributionStatusId, $contributionStatus) == 'Partially paid')
4800 $ftDao = CRM_Core_DAO
::executeQuery($ftSql, array(1 => array($contribution->id
, 'Integer')));
4803 // store financial item Proportionaly.
4804 $trxnParams = array(
4805 'total_amount' => $ftDao->total_amount
,
4806 'contribution_id' => $contribution->id
,
4808 self
::assignProportionalLineItems($trxnParams, $ftDao->id
, $contribution->total_amount
);
4813 * Function use to store line item proportionaly in
4814 * in entity financial trxn table
4816 * @param array $trxnParams
4818 * @param Integer $trxnId
4820 * @param float $contributionTotalAmount
4823 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4824 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4825 if (!empty($lineItems)) {
4826 // get financial item
4827 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4828 $entityParams = array(
4829 'contribution_total_amount' => $contributionTotalAmount,
4830 'trxn_total_amount' => $trxnParams['total_amount'],
4831 'trxn_id' => $trxnId,
4833 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4838 * Checks if line items total amounts
4839 * match the contribution total amount.
4841 * @param array $params
4842 * array of order params.
4844 * @throws \API_Exception
4846 public static function checkLineItems(&$params) {
4847 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
4848 $lineItemAmount = 0;
4850 foreach ($params['line_items'] as &$lineItems) {
4851 foreach ($lineItems['line_item'] as &$item) {
4852 if (empty($item['financial_type_id'])) {
4853 $item['financial_type_id'] = $params['financial_type_id'];
4855 $lineItemAmount +
= $item['line_total'] + CRM_Utils_Array
::value('tax_amount', $item, 0.00);
4859 if (!isset($totalAmount)) {
4860 $params['total_amount'] = $lineItemAmount;
4863 $currency = CRM_Utils_Array
::value('currency', $params, '');
4865 if (empty($currency)) {
4866 $currency = CRM_Core_Config
::singleton()->defaultCurrency
;
4869 if (!CRM_Utils_Money
::equals($totalAmount, $lineItemAmount, $currency)) {
4870 throw new CRM_Contribute_Exception_CheckLineItemsException();
4876 * Get the financial account for the item associated with the new transaction.
4878 * @param array $params
4879 * @param int $default
4883 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
4885 if (!empty($params['financial_account_id'])) {
4886 return $params['financial_account_id'];
4889 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4890 $preferredAccountsRelationships = array(
4891 'Refunded' => 'Credit/Contra Revenue Account is',
4892 'Chargeback' => 'Chargeback Account is',
4895 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4896 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4897 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4899 $preferredAccountsRelationships[$contributionStatus]
4907 * ContributionPage values were being imposed onto values.
4909 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4910 * REALLY didn't want superimposed. The rest are left there in their overkill out
4913 * The rationale for making this explicit is that it was a case of carefully set values being
4914 * seemingly randonly overwritten without much care. In general I think array randomly setting
4915 * variables en mass is risky.
4917 * @param array $values
4921 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4922 $contributionPageValues = array();
4923 CRM_Contribute_BAO_ContributionPage
::setValues(
4924 $this->contribution_page_id
,
4925 $contributionPageValues
4927 $valuesToCopy = array(
4928 // These are the values that I believe to be useful.
4931 'pay_later_receipt',
4933 'receipt_from_email',
4934 'receipt_from_name',
4938 'honoree_profile_id',
4939 'onbehalf_profile_id',
4940 'honor_block_is_active',
4941 // Kinda might be - but would be on the contribution...
4944 // Included for 'fear of regression' but can't justify any use for these....
4946 'payment_processor',
4947 'financial_type_id',
4948 'amount_block_is_active',
4953 'default_amount_id',
4957 'initial_amount_help_text',
4958 'initial_amount_label',
4960 'is_allow_other_amount',
4961 'is_billing_required',
4962 'is_confirm_enabled',
4963 'is_credit_card_only',
4965 'is_partial_payment',
4966 'is_recur_installments',
4967 'is_recur_interval',
4971 'min_initial_amount',
4972 'recur_frequency_unit',
4979 foreach ($valuesToCopy as $valueToCopy) {
4980 if (isset($contributionPageValues[$valueToCopy])) {
4981 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
4988 * Get values of CiviContribute Settings
4989 * and check if its enabled or not.
4990 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
4991 * in serialized form. Usually this should be stored as flat settings for each form fields
4992 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
4993 * settings we will live with an inconsistency because it's too hard to change for now.
4994 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
4997 * @param string $name
4998 * @param bool $checkInvoicing
5002 public static function checkContributeSettings($name = NULL, $checkInvoicing = FALSE) {
5003 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
5005 if ($checkInvoicing && !CRM_Utils_Array
::value('invoicing', $contributeSettings)) {
5010 return CRM_Utils_Array
::value($name, $contributeSettings);
5012 return $contributeSettings;
5016 * This function process contribution related objects.
5018 * @param int $contributionId
5019 * @param int $statusId
5020 * @param int|null $previousStatusId
5022 * @param string $receiveDate
5024 * @return null|string
5026 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
5028 if (!$contributionId ||
!$statusId) {
5033 'contribution_id' => $contributionId,
5034 'contribution_status_id' => $statusId,
5035 'previous_contribution_status_id' => $previousStatusId,
5036 'receive_date' => $receiveDate,
5039 $updateResult = CRM_Contribute_BAO_Contribution
::transitionComponents($params);
5041 if (!is_array($updateResult) ||
5042 !($updatedComponents = CRM_Utils_Array
::value('updatedComponents', $updateResult)) ||
5043 !is_array($updatedComponents) ||
5044 empty($updatedComponents)
5049 // get the user display name.
5051 SELECT display_name as displayName
5052 FROM civicrm_contact
5053 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
5054 WHERE civicrm_contribution.id = {$contributionId}";
5055 $userDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
5057 // get the status message for user.
5058 foreach ($updatedComponents as $componentName => $updatedStatusId) {
5060 if ($componentName == 'CiviMember') {
5061 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5062 CRM_Member_PseudoConstant
::membershipStatus()
5064 if ($updatedStatusName == 'Cancelled') {
5065 $statusMsg .= "<br />" . ts("Membership for %1 has been Cancelled.", array(1 => $userDisplayName));
5067 elseif ($updatedStatusName == 'Expired') {
5068 $statusMsg .= "<br />" . ts("Membership for %1 has been Expired.", array(1 => $userDisplayName));
5071 $endDate = CRM_Utils_Array
::value('membership_end_date', $updateResult);
5073 $statusMsg .= "<br />" . ts("Membership for %1 has been updated. The membership End Date is %2.",
5075 1 => $userDisplayName,
5083 if ($componentName == 'CiviEvent') {
5084 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5085 CRM_Event_PseudoConstant
::participantStatus()
5087 if ($updatedStatusName == 'Cancelled') {
5088 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", array(1 => $userDisplayName));
5090 elseif ($updatedStatusName == 'Registered') {
5091 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", array(1 => $userDisplayName));
5095 if ($componentName == 'CiviPledge') {
5096 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5097 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name')
5099 if ($updatedStatusName == 'Cancelled') {
5100 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", array(1 => $userDisplayName));
5102 elseif ($updatedStatusName == 'Failed') {
5103 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", array(1 => $userDisplayName));
5105 elseif ($updatedStatusName == 'Completed') {
5106 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", array(1 => $userDisplayName));
5115 * Get the contribution as it is in the database before being updated.
5117 * @param int $contributionID
5119 * @return \CRM_Contribute_BAO_Contribution|null
5121 private static function getOriginalContribution($contributionID) {
5122 return self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
5126 * Get the amount for the financial item row.
5128 * Helper function to start to break down recordFinancialTransactions for readability.
5130 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
5132 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
5133 * for historical reasons. Going forwards we can hope to add tests & improve readibility
5136 * @todo move recordFinancialAccounts & helper functions to their own class?
5138 * @param array $params
5139 * Params as passed to contribution.create
5141 * @param string $context
5142 * changeFinancialType| changedAmount
5143 * @param array $lineItemDetails
5145 * @param bool $isARefund
5146 * Is this a refund / negative transaction.
5150 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
5151 if ($context == 'changedAmount') {
5152 $lineTotal = $lineItemDetails['line_total'];
5153 if ($lineTotal != $previousLineItemTotal) {
5154 $lineTotal -= $previousLineItemTotal;
5158 elseif ($context == 'changeFinancialType') {
5159 return -$lineItemDetails['line_total'];
5161 elseif ($context == 'changedStatus') {
5162 $cancelledTaxAmount = 0;
5164 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
5166 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
5168 elseif ($context === NULL) {
5169 // erm, yes because? but, hey, it's tested.
5170 return $lineItemDetails['line_total'];
5172 elseif (empty($lineItemDetails['line_total'])) {
5173 // follow legacy code path
5175 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', array('civi.tag' => 'deprecated'));
5176 return $params['total_amount'];
5179 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
5184 * Get the multiplier for adjusting rows.
5186 * If we are dealing with a refund or cancellation then it will be a negative
5187 * amount to reflect the negative transaction.
5189 * If we are changing Financial Type it will be a negative amount to
5190 * adjust down the old type.
5192 * @param int $contribution_status_id
5193 * @param string $context
5197 protected static function getMultiplier($contribution_status_id, $context) {
5198 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
5205 * Does this transaction reflect a payment instrument change.
5207 * @param array $params
5208 * @param array $pendingStatuses
5212 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
5213 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
5215 if (array_key_exists('payment_instrument_id', $params)) {
5216 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
5217 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
5219 //check if status is changed from Pending to Completed
5220 // do not update payment instrument changes for Pending to Completed
5221 if (!($contributionStatus == 'Completed' &&
5222 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
5227 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
5228 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
5229 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
5233 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
5234 $params['contribution']->check_number
!= $params['prevContribution']->check_number
5236 // another special case when check number is changed, create new financial records
5237 // create financial trxn with negative amount
5245 * Update the memberships associated with a contribution if it has been completed.
5247 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
5248 * load them in this function. Code clean up would compensate for any minor performance implication.
5250 * @param \CRM_Contribute_BAO_Contribution $contribution
5251 * @param int $primaryContributionID
5252 * @param string $changeDate
5254 * @throws \CRM_Core_Exception
5255 * @throws \CiviCRM_API3_Exception
5257 public static function updateMembershipBasedOnCompletionOfContribution($contribution, $primaryContributionID, $changeDate) {
5258 $memberships = self
::getRelatedMemberships($contribution->id
);
5259 foreach ($memberships as $membership) {
5260 $membershipParams = array(
5261 'id' => $membership['id'],
5262 'contact_id' => $membership['contact_id'],
5263 'is_test' => $membership['is_test'],
5264 'membership_type_id' => $membership['membership_type_id'],
5265 'membership_activity_status' => 'Completed',
5268 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
5269 $membershipParams['membership_type_id'],
5270 $membershipParams['is_test'],
5271 $membershipParams['id']
5274 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
5275 // this picks up membership type changes during renewals
5276 // @todo this is almost certainly an obsolete sql call, the pre-change
5277 // membership is accessible via $this->_relatedObjects
5279 SELECT membership_type_id
5280 FROM civicrm_membership_log
5281 WHERE membership_id={$membershipParams['id']}
5284 $dao = CRM_Core_DAO
::executeQuery($sql);
5285 if ($dao->fetch()) {
5286 if (!empty($dao->membership_type_id
)) {
5287 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
5292 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
5293 $membershipParams['membership_type_id'],
5294 $primaryContributionID
5296 // @todo remove all this stuff in favour of letting the api call further down handle in
5297 // (it is a duplication of what the api does).
5298 $dates = array_fill_keys(array(
5303 if ($currentMembership) {
5305 * Fixed FOR CRM-4433
5306 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
5307 * when Contribution mode is notify and membership is for renewal )
5309 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
5311 // @todo - we should pass membership_type_id instead of null here but not
5312 // adding as not sure of testing
5313 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
5314 $changeDate, NULL, $membershipParams['num_terms']
5316 $dates['join_date'] = $currentMembership['join_date'];
5319 //get the status for membership.
5320 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
5322 $dates['join_date'],
5325 $membershipParams['membership_type_id'],
5329 unset($dates['end_date']);
5330 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
5331 //we might be renewing membership,
5332 //so make status override false.
5333 $membershipParams['is_override'] = FALSE;
5334 $membershipParams['status_override_end_date'] = 'null';
5336 //CRM-17723 - reset static $relatedContactIds array()
5337 // @todo move it to Civi Statics.
5339 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
5340 civicrm_api3('Membership', 'create', $membershipParams);
5345 * Get payment links as they relate to a contribution.
5347 * If a payment can be made then include a payment link & if a refund is appropriate
5348 * then a refund link.
5351 * @param float $balance
5352 * @param string $contributionStatus
5354 * @return array $actionLinks Links array containing:
5358 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
5359 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
5360 // In general the balance is the best way to determine if a payment can be added or not,
5361 // but not for Failed contributions, where we don't accept additional payments at the moment.
5362 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
5363 // do accept more payments agains them.
5366 $actionLinks = array();
5367 if ((int) $balance > 0) {
5368 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
5369 $actionLinks[] = array(
5370 'url' => CRM_Utils_System
::url('civicrm/payment', array(
5376 'title' => ts('Submit Credit Card payment'),
5379 $actionLinks[] = array(
5380 'url' => CRM_Utils_System
::url('civicrm/payment', array(
5385 'title' => ts('Record Payment'),
5388 elseif ((int) $balance < 0) {
5389 $actionLinks[] = array(
5390 'url' => CRM_Utils_System
::url('civicrm/payment', array(
5395 'title' => ts('Record Refund'),
5398 return $actionLinks;
5402 * Get a query to determine the amount donated by the contact/s in the current financial year.
5404 * @param array $contactIDs
5408 public static function getAnnualQuery($contactIDs) {
5409 $contactIDs = implode(',', $contactIDs);
5410 $config = CRM_Core_Config
::singleton();
5411 $currentMonth = date('m');
5412 $currentDay = date('d');
5414 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
5416 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
5417 (int) $config->fiscalYearStart
['d'] > $currentDay
5420 $year = date('Y') - 1;
5425 $nextYear = $year +
1;
5427 if ($config->fiscalYearStart
) {
5428 $newFiscalYearStart = $config->fiscalYearStart
;
5429 if ($newFiscalYearStart['M'] < 10) {
5430 // This is just a clumsy way of adding padding.
5431 // @todo next round look for a nicer way.
5432 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
5434 if ($newFiscalYearStart['d'] < 10) {
5435 // This is just a clumsy way of adding padding.
5436 // @todo next round look for a nicer way.
5437 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
5439 $config->fiscalYearStart
= $newFiscalYearStart;
5440 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
5443 // First of January.
5446 $startDate = "$year$monthDay";
5447 $endDate = "$nextYear$monthDay";
5450 'contact_id' => 'IN (' . $contactIDs . ')',
5451 'is_test' => ' = 0',
5452 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
5454 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
5455 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
5458 foreach ($whereClauses as $key => $clause) {
5459 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
5461 $whereClauseString = implode(' AND ', $clauses);
5463 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5464 // this group by + having on contribution_status_id improves performance
5466 SELECT COUNT(*) as count,
5467 SUM(total_amount) as amount,
5468 AVG(total_amount) as average,
5470 FROM civicrm_contribution b
5471 WHERE " . $whereClauseString . "
5472 GROUP BY currency, contribution_status_id
5473 HAVING $havingClause
5479 * Assign Test Value.
5481 * @param string $fieldName
5482 * @param array $fieldDef
5483 * @param int $counter
5485 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5486 if ($fieldName == 'tax_amount') {
5487 $this->{$fieldName} = "0.00";
5489 elseif ($fieldName == 'net_amount') {
5490 $this->{$fieldName} = "2.00";
5492 elseif ($fieldName == 'total_amount') {
5493 $this->{$fieldName} = "3.00";
5495 elseif ($fieldName == 'fee_amount') {
5496 $this->{$fieldName} = "1.00";
5499 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5504 * Check if contribution has participant/membership payment.
5506 * @param int $contributionId
5511 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5512 // get line item for contribution
5513 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5514 // check if line item is for membership or participant
5515 foreach ($lineItems as $items) {
5516 if ($items['entity_table'] == 'civicrm_participant') {
5520 elseif ($items['entity_table'] == 'civicrm_membership') {
5532 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5534 * @param array $trxnParams
5535 * Financial trxn params
5536 * @param array $contributionParams
5537 * Contribution Params
5541 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5542 if (!self
::checkContributeSettings('always_post_to_accounts_receivable')) {
5545 $statusId = $contributionParams['contribution']->contribution_status_id
;
5546 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5547 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5548 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5549 // Return if contribution status is not completed.
5550 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5551 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5552 && $contributionParams['prevContribution']->is_pay_later
== 0
5558 $params = $trxnParams;
5559 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $contributionParams) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5560 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5561 $params['to_financial_account_id'] = $arAccountId;
5562 $params['status_id'] = array_search('Pending', $contributionStatuses);
5563 $params['is_payment'] = FALSE;
5564 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5565 self
::$_trxnIDs[] = $trxn->id
;
5566 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5570 * Calculate financial item amount when contribution is updated.
5572 * @param array $params
5573 * contribution params
5574 * @param array $amountParams
5576 * @param string $context
5580 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5581 if (!empty($params['is_quick_config'])) {
5582 $amount = $amountParams['item_amount'];
5584 $amount = $params['total_amount'];
5585 if ($context === NULL) {
5586 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5591 $amount = $amountParams['line_total'];
5592 if ($context == 'changedAmount') {
5593 $amount -= $amountParams['previous_line_total'];
5595 $amount *= $amountParams['diff'];
5601 * Retrieve Sales Tax Financial Accounts.
5607 public static function getSalesTaxFinancialAccounts() {
5608 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5609 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5610 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5611 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5612 $queryParams = array(1 => array($accountRel, 'Integer'));
5613 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5614 $financialAccount = array();
5615 while ($dao->fetch()) {
5616 $financialAccount[$dao->id
] = $dao->id
;
5618 return $financialAccount;
5622 * Create tax entry in civicrm_entity_financial_trxn table.
5624 * @param array $entityParams
5626 * @param array $eftParams
5629 public static function createProportionalEntry($entityParams, $eftParams) {
5631 if ($entityParams['contribution_total_amount'] != 0) {
5632 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5634 // Record Entity Financial Trxn; CRM-20145
5635 $eftParams['amount'] = CRM_Contribute_BAO_Contribution_Utils
::formatAmount($paid);
5636 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5640 * Create array of last financial item id's.
5642 * @param int $contributionId
5646 public static function getLastFinancialItemIds($contributionId) {
5647 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5648 FROM civicrm_financial_item fi
5649 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5650 WHERE li.contribution_id = %1";
5651 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($contributionId, 'Integer')));
5652 $ftIds = $taxItems = array();
5653 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5654 while ($dao->fetch()) {
5655 /* if sales tax item*/
5656 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5657 $taxItems[$dao->price_field_value_id
] = array(
5658 'financial_item_id' => $dao->id
,
5659 'amount' => $dao->tax_amount
,
5663 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5666 return array($ftIds, $taxItems);
5670 * Create proportional entries in civicrm_entity_financial_trxn.
5672 * @param array $entityParams
5674 * @param array $lineItems
5676 * @param array $ftIds
5678 * @param array $taxItems
5681 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5683 'entity_table' => 'civicrm_financial_item',
5684 'financial_trxn_id' => $entityParams['trxn_id'],
5686 foreach ($lineItems as $key => $value) {
5687 if ($value['qty'] == 0) {
5690 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5691 $entityParams['line_item_amount'] = $value['line_total'];
5692 self
::createProportionalEntry($entityParams, $eftParams);
5693 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5694 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5695 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5696 self
::createProportionalEntry($entityParams, $eftParams);
5702 * Load entities related to the contribution into $this->_relatedObjects.
5706 * @throws \CRM_Core_Exception
5708 protected function loadRelatedEntitiesByID($ids) {
5710 'contact' => 'CRM_Contact_BAO_Contact',
5711 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5712 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5713 'financialType' => 'CRM_Financial_BAO_FinancialType',
5714 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5716 foreach ($entities as $entity => $bao) {
5717 if (!empty($ids[$entity])) {
5718 $this->_relatedObjects
[$entity] = new $bao();
5719 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5720 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5721 throw new CRM_Core_Exception($entity . ' could not be loaded');
5728 * Should an email receipt be sent for this contribution when complete.
5730 * @param array $input
5734 protected function isEmailReceipt($input) {
5735 if (isset($input['is_email_receipt'])) {
5736 return $input['is_email_receipt'];
5738 if (!empty($this->_relatedObjects
['contribution_page_id'])) {
5739 return $this->_relatedObjects
['contribution_page_id']->is_email_receipt
;
5745 * Function to replace contribution tokens.
5747 * @param array $contributionIds
5749 * @param string $subject
5751 * @param array $subjectToken
5753 * @param string $text
5755 * @param string $html
5757 * @param array $messageToken
5759 * @param bool $escapeSmarty
5763 public static function replaceContributionTokens(
5772 if (empty($contributionIds)) {
5775 $contributionDetails = array();
5776 foreach ($contributionIds as $id) {
5777 $result = civicrm_api3('Contribution', 'get', array('id' => $id));
5778 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5779 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5780 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5782 return $contributionDetails;
5786 * Get invoice_number for contribution.
5788 * @param int $contributionID
5792 public static function getInvoiceNumber($contributionID) {
5793 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix', TRUE)) {
5794 return $invoicePrefix . $contributionID;