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_Utils
{
36 * Process payment after confirmation.
38 * @param CRM_Core_Form $form
40 * @param array $paymentParams
41 * Array with payment related key.
43 * @param int $contactID
45 * @param int $financialTypeID
48 * @param bool $isRecur
50 * @throws CRM_Core_Exception
56 public static function processConfirm(
64 CRM_Core_Payment_Form
::mapParams($form->_bltID
, $form->_params
, $paymentParams, TRUE);
65 $isPaymentTransaction = self
::isPaymentTransaction($form);
67 $financialType = new CRM_Financial_DAO_FinancialType();
68 $financialType->id
= $financialTypeID;
69 $financialType->find(TRUE);
70 if ($financialType->is_deductible
) {
71 $form->assign('is_deductible', TRUE);
72 $form->set('is_deductible', TRUE);
75 // add some financial type details to the params list
76 // if folks need to use it
77 //CRM-15297 deprecate contributionTypeID
78 $paymentParams['financial_type_id'] = $paymentParams['financialTypeID'] = $paymentParams['contributionTypeID'] = $financialType->id
;
79 //CRM-15297 - contributionType is obsolete - pass financial type as well so people can deprecate it
80 $paymentParams['financialType_name'] = $paymentParams['contributionType_name'] = $form->_params
['contributionType_name'] = $financialType->name
;
82 $paymentParams['financialType_accounting_code'] = $paymentParams['contributionType_accounting_code'] = $form->_params
['contributionType_accounting_code'] = CRM_Financial_BAO_FinancialAccount
::getAccountingCode($financialTypeID);
83 $paymentParams['contributionPageID'] = $form->_params
['contributionPageID'] = $form->_values
['id'];
84 $paymentParams['contactID'] = $form->_params
['contactID'] = $contactID;
87 if (empty($form->_params
['receive_date'])) {
88 $form->_params
['receive_date'] = date('YmdHis');
90 if (!empty($form->_params
['start_date'])) {
91 $form->_params
['start_date'] = date('YmdHis');
93 $form->assign('receive_date',
94 CRM_Utils_Date
::mysqlToIso($form->_params
['receive_date'])
97 if (empty($form->_values
['amount'])) {
98 // If the amount is not in _values[], set it
99 $form->_values
['amount'] = $form->_params
['amount'];
102 if ($isPaymentTransaction) {
103 $contributionParams = [
104 'id' => CRM_Utils_Array
::value('contribution_id', $paymentParams),
105 'contact_id' => $contactID,
106 'is_test' => $isTest,
107 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
110 // CRM-21200: Don't overwrite contribution details during 'Pay now' payment
111 if (empty($form->_params
['contribution_id'])) {
112 $contributionParams['contribution_page_id'] = $form->_id
;
113 $contributionParams['campaign_id'] = CRM_Utils_Array
::value('campaign_id', $paymentParams, CRM_Utils_Array
::value('campaign_id', $form->_values
));
115 // In case of 'Pay now' payment, append the contribution source with new text 'Paid later via page ID: N.'
117 // contribution.source only allows 255 characters so we are using ellipsify(...) to ensure it.
118 $contributionParams['source'] = CRM_Utils_String
::ellipsify(
119 ts('Paid later via page ID: %1. %2', [
121 2 => $contributionParams['source'],
123 // eventually activity.description append price information to source text so keep it 220 to ensure string length doesn't exceed 255 characters.
128 if (isset($paymentParams['line_item'])) {
129 // @todo make sure this is consisently set at this point.
130 $contributionParams['line_item'] = $paymentParams['line_item'];
132 if (!empty($form->_paymentProcessor
)) {
133 $contributionParams['payment_instrument_id'] = $paymentParams['payment_instrument_id'] = $form->_paymentProcessor
['payment_instrument_id'];
136 // @todo this is the wrong place for this - it should be done as close to form submission
138 $paymentParams['amount'] = CRM_Utils_Rule
::cleanMoney($paymentParams['amount']);
139 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution(
150 $paymentParams['item_name'] = $form->_params
['description'];
152 $paymentParams['qfKey'] = empty($paymentParams['qfKey']) ?
$form->controller
->_key
: $paymentParams['qfKey'];
153 if ($paymentParams['skipLineItem']) {
154 // We are not processing the line item here because we are processing a membership.
155 // Do not continue with contribution processing in this function.
156 return ['contribution' => $contribution];
159 $paymentParams['contributionID'] = $contribution->id
;
160 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
161 if (isset($paymentParams['contribution_source'])) {
162 $paymentParams['source'] = $paymentParams['contribution_source'];
165 if (CRM_Utils_Array
::value('is_recur', $form->_params
) && $contribution->contribution_recur_id
) {
166 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
168 if (isset($paymentParams['contribution_source'])) {
169 $form->_params
['source'] = $paymentParams['contribution_source'];
172 // get the price set values for receipt.
173 if ($form->_priceSetId
&& $form->_lineItem
) {
174 $form->_values
['lineItem'] = $form->_lineItem
;
175 $form->_values
['priceSetID'] = $form->_priceSetId
;
178 $form->_values
['contribution_id'] = $contribution->id
;
179 $form->_values
['contribution_page_id'] = $contribution->contribution_page_id
;
181 if (!empty($form->_paymentProcessor
)) {
183 $payment = Civi\Payment\System
::singleton()->getByProcessor($form->_paymentProcessor
);
184 if ($form->_contributeMode
== 'notify') {
185 // We want to get rid of this & make it generic - eg. by making payment processing the last thing
186 // and always calling it first.
187 $form->postProcessHook();
189 $result = $payment->doPayment($paymentParams);
190 $form->_params
= array_merge($form->_params
, $result);
191 $form->assign('trxn_id', CRM_Utils_Array
::value('trxn_id', $result));
192 if (!empty($result['trxn_id'])) {
193 $contribution->trxn_id
= $result['trxn_id'];
195 if (!empty($result['payment_status_id'])) {
196 $contribution->payment_status_id
= $result['payment_status_id'];
198 $result['contribution'] = $contribution;
199 if ($result['payment_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution',
200 'status_id', 'Pending') && $payment->isSendReceiptForPending()) {
201 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
203 $contribution->is_test
208 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
209 // Clean up DB as appropriate.
210 if (!empty($paymentParams['contributionID'])) {
211 CRM_Contribute_BAO_Contribution
::failPayment($paymentParams['contributionID'],
212 $paymentParams['contactID'], $e->getMessage());
214 if (!empty($paymentParams['contributionRecurID'])) {
215 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($paymentParams['contributionRecurID']);
218 $result['is_payment_failure'] = TRUE;
219 $result['error'] = $e;
225 // Only pay later or unpaid should reach this point, although pay later likely does not & is handled via the
226 // manual processor, so it's unclear what this set is for and whether the following send ever fires.
227 $form->set('params', $form->_params
);
229 if ($form->_params
['amount'] == 0) {
230 // This is kind of a back-up for pay-later $0 transactions.
231 // In other flows they pick up the manual processor & get dealt with above (I
232 // think that might be better...).
234 'payment_status_id' => 1,
235 'contribution' => $contribution,
236 'payment_processor_id' => 0,
240 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
242 $contribution->is_test
247 * Is a payment being made.
249 * Note that setting is_monetary on the form is somewhat legacy and the behaviour around this setting is confusing. It would be preferable
250 * to look for the amount only (assuming this cannot refer to payment in goats or other non-monetary currency
251 * @param CRM_Core_Form $form
255 protected static function isPaymentTransaction($form) {
256 return ($form->_amount
>= 0.0) ?
TRUE : FALSE;
260 * Get the contribution details by month of the year.
268 public static function contributionChartMonthly($param) {
270 $param = [1 => [$param, 'Integer']];
274 $param = [1 => [$param, 'Integer']];
278 SELECT sum(contrib.total_amount) AS ctAmt,
279 MONTH( contrib.receive_date) AS contribMonth
280 FROM civicrm_contribution AS contrib
281 INNER JOIN civicrm_contact AS contact ON ( contact.id = contrib.contact_id )
282 WHERE contrib.contact_id = contact.id
283 AND ( contrib.is_test = 0 OR contrib.is_test IS NULL )
284 AND contrib.contribution_status_id = 1
285 AND date_format(contrib.receive_date,'%Y') = %1
286 AND contact.is_deleted = 0
287 GROUP BY contribMonth
288 ORDER BY month(contrib.receive_date)";
290 $dao = CRM_Core_DAO
::executeQuery($query, $param);
293 while ($dao->fetch()) {
294 if ($dao->contribMonth
) {
295 $params['By Month'][$dao->contribMonth
] = $dao->ctAmt
;
302 * Get the contribution details by year.
307 public static function contributionChartYearly() {
308 $config = CRM_Core_Config
::singleton();
309 $yearClause = "year(contrib.receive_date) as contribYear";
310 if (!empty($config->fiscalYearStart
) && ($config->fiscalYearStart
['M'] != 1 ||
$config->fiscalYearStart
['d'] != 1)) {
312 WHEN (MONTH(contrib.receive_date)>= " . $config->fiscalYearStart
['M'] . "
313 && DAYOFMONTH(contrib.receive_date)>= " . $config->fiscalYearStart
['d'] . " )
315 concat(YEAR(contrib.receive_date), '-',YEAR(contrib.receive_date)+1)
317 concat(YEAR(contrib.receive_date)-1,'-', YEAR(contrib.receive_date))
322 SELECT sum(contrib.total_amount) AS ctAmt,
324 FROM civicrm_contribution AS contrib
325 INNER JOIN civicrm_contact contact ON ( contact.id = contrib.contact_id )
326 WHERE ( contrib.is_test = 0 OR contrib.is_test IS NULL )
327 AND contrib.contribution_status_id = 1
328 AND contact.is_deleted = 0
330 ORDER BY contribYear";
331 $dao = CRM_Core_DAO
::executeQuery($query);
334 while ($dao->fetch()) {
335 if (!empty($dao->contribYear
)) {
336 $params['By Year'][$dao->contribYear
] = $dao->ctAmt
;
343 * @param array $params
344 * @param int $contactID
347 public static function createCMSUser(&$params, $contactID, $mail) {
348 // lets ensure we only create one CMS user
349 static $created = FALSE;
356 if (!empty($params['cms_create_account'])) {
357 $params['contactID'] = !empty($params['onbehalf_contact_id']) ?
$params['onbehalf_contact_id'] : $contactID;
358 if (!CRM_Core_BAO_CMSUser
::create($params, $mail)) {
359 CRM_Core_Error
::statusBounce(ts('Your profile is not saved and Account is not created.'));
365 * @param array $params
366 * @param string $type
370 public static function _fillCommonParams(&$params, $type = 'paypal') {
371 if (array_key_exists('transaction', $params)) {
372 $transaction = &$params['transaction'];
375 $transaction = &$params;
378 $params['contact_type'] = 'Individual';
380 $billingLocTypeId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType', 'Billing', 'id', 'name');
381 if (!$billingLocTypeId) {
382 $billingLocTypeId = 1;
384 if (!CRM_Utils_System
::isNull($params['address'])) {
385 $params['address'][1]['is_primary'] = 1;
386 $params['address'][1]['location_type_id'] = $billingLocTypeId;
388 if (!CRM_Utils_System
::isNull($params['email'])) {
391 'email' => $params['email'],
392 'location_type_id' => $billingLocTypeId,
397 if (isset($transaction['trxn_id'])) {
398 // set error message if transaction has already been processed.
399 $contribution = new CRM_Contribute_DAO_Contribution();
400 $contribution->trxn_id
= $transaction['trxn_id'];
401 if ($contribution->find(TRUE)) {
402 $params['error'][] = ts('transaction already processed.');
406 // generate a new transaction id, if not already exist
407 $transaction['trxn_id'] = md5(uniqid(rand(), TRUE));
410 if (!isset($transaction['financial_type_id'])) {
411 $contributionTypes = array_keys(CRM_Contribute_PseudoConstant
::financialType());
412 $transaction['financial_type_id'] = $contributionTypes[0];
415 if (($type == 'paypal') && (!isset($transaction['net_amount']))) {
416 $transaction['net_amount'] = $transaction['total_amount'] - CRM_Utils_Array
::value('fee_amount', $transaction, 0);
419 if (!isset($transaction['invoice_id'])) {
420 $transaction['invoice_id'] = $transaction['trxn_id'];
423 $source = ts('ContributionProcessor: %1 API',
424 [1 => ucfirst($type)]
426 if (isset($transaction['source'])) {
427 $transaction['source'] = $source . ':: ' . $transaction['source'];
430 $transaction['source'] = $source;
437 * @param int $contactID
441 public static function getFirstLastDetails($contactID) {
448 if (!isset($_cache[$contactID])) {
450 SELECT total_amount, receive_date
451 FROM civicrm_contribution c
452 WHERE contact_id = %1
453 ORDER BY receive_date ASC
456 $params = [1 => [$contactID, 'Integer']];
458 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
464 $details['first'] = [
465 'total_amount' => $dao->total_amount
,
466 'receive_date' => $dao->receive_date
,
470 // flip asc and desc to get the last query
471 $sql = str_replace('ASC', 'DESC', $sql);
472 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
475 'total_amount' => $dao->total_amount
,
476 'receive_date' => $dao->receive_date
,
480 $_cache[$contactID] = $details;
482 return $_cache[$contactID];
486 * Calculate the tax amount based on given tax rate.
488 * @param float $amount
490 * @param float $taxRate
491 * Tax rate of selected financial account for field.
492 * @param bool $ugWeDoNotKnowIfItNeedsCleaning_Help
493 * This should ALWAYS BE FALSE and then be removed. A 'clean' money string uses a standardised format
494 * such as '1000.99' for one thousand $/Euro/CUR and ninety nine cents/units.
495 * However, we are in the habit of not necessarily doing that so need to grandfather in
496 * the new expectation.
499 * array of tax amount
502 public static function calculateTaxAmount($amount, $taxRate, $ugWeDoNotKnowIfItNeedsCleaning_Help = FALSE) {
504 if ($ugWeDoNotKnowIfItNeedsCleaning_Help) {
505 Civi
::log()->warning('Deprecated function, make sure money is in usable format before calling this.', ['civi.tag' => 'deprecated']);
506 $amount = CRM_Utils_Rule
::cleanMoney($amount);
508 // There can not be any rounding at this stage - as this is prior to quantity multiplication
509 $taxAmount['tax_amount'] = ($taxRate / 100) * $amount;
515 * Format monetary amount: round and return to desired decimal place
518 * @param float $amount
520 * @param int $decimals
521 * How many decimal places to round to and return
524 * Amount rounded and returned with the desired decimal places
526 public static function formatAmount($amount, $decimals = 2) {
527 return number_format((float) round($amount, (int) $decimals), (int) $decimals, '.', '');
531 * Get contribution statuses by entity e.g. contribution, membership or 'participant'
533 * @param string $usedFor
538 * Array of contribution statuses in array('status id' => 'label') format
540 public static function getContributionStatuses($usedFor = 'contribution', $id = NULL) {
541 if ($usedFor == 'pledge') {
542 $statusNames = CRM_Pledge_BAO_Pledge
::buildOptions('status_id', 'validate');
545 $statusNames = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate');
548 $statusNamesToUnset = [];
549 // on create fetch statuses on basis of component
551 $statusNamesToUnset = [
557 // Event registration and New Membership backoffice form support partially paid payment,
558 // so exclude this status only for 'New Contribution' form
559 if ($usedFor == 'contribution') {
560 $statusNamesToUnset = array_merge($statusNamesToUnset, [
566 elseif ($usedFor == 'participant') {
567 $statusNamesToUnset = array_merge($statusNamesToUnset, [
572 elseif ($usedFor == 'membership') {
573 $statusNamesToUnset = array_merge($statusNamesToUnset, [
580 $contributionStatus = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $id, 'contribution_status_id');
581 $name = CRM_Utils_Array
::value($contributionStatus, $statusNames);
584 // [CRM-17498] Removing unsupported status change options.
585 $statusNamesToUnset = array_merge($statusNamesToUnset, [
596 $statusNamesToUnset = array_merge($statusNamesToUnset, [
604 $statusNamesToUnset = array_merge($statusNamesToUnset, [
611 $statusNamesToUnset = array_merge($statusNamesToUnset, [
623 foreach ($statusNamesToUnset as $name) {
624 unset($statusNames[CRM_Utils_Array
::key($name, $statusNames)]);
627 // based on filtered statuse names fetch the final list of statuses in array('id' => 'label') format
628 if ($usedFor == 'pledge') {
629 $statuses = CRM_Pledge_BAO_Pledge
::buildOptions('status_id');
632 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
634 foreach ($statuses as $statusID => $label) {
635 if (!array_key_exists($statusID, $statusNames)) {
636 unset($statuses[$statusID]);
644 * CRM-8254 / CRM-6907 - override default currency if applicable
645 * these lines exist to support a non-default currency on the form but are probably
646 * obsolete & meddling wth the defaultCurrency is not the right approach....
648 * @param array $params
650 public static function overrideDefaultCurrency($params) {
651 $config = CRM_Core_Config
::singleton();
652 $config->defaultCurrency
= CRM_Utils_Array
::value('currency', $params, $config->defaultCurrency
);