5f8a9e2ef125597d96ffdf333dd9a7bd0ff2d917
[civicrm-core.git] / CRM / Contribute / BAO / Contribution / Utils.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 * $Id$
33 */
34 class CRM_Contribute_BAO_Contribution_Utils {
35
36 /**
37 * Process payment after confirmation.
38 *
39 * @param CRM_Core_Form $form
40 * Form object.
41 * @param array $paymentParams
42 * Array with payment related key.
43 * value pairs
44 * @param array $premiumParams
45 * Array with premium related key.
46 * value pairs
47 * @param int $contactID
48 * Contact id.
49 * @param int $contributionTypeId
50 * Financial type id.
51 * @param int|string $component component id
52 * @param array $fieldTypes
53 * Presumably relates to custom field types - used when building data for sendMail.
54 * @param $isTest
55 * @param $isPayLater
56 *
57 * @throws CRM_Core_Exception
58 * @throws Exception
59 * @return array
60 * associated array
61 *
62 */
63 public static function processConfirm(
64 &$form,
65 &$paymentParams,
66 &$premiumParams,
67 $contactID,
68 $contributionTypeId,
69 $component = 'contribution',
70 $fieldTypes = NULL,
71 $isTest,
72 $isPayLater
73 ) {
74 CRM_Core_Payment_Form::mapParams($form->_bltID, $form->_params, $paymentParams, TRUE);
75 $lineItems = $form->_lineItem;
76 $isPaymentTransaction = self::isPaymentTransaction($form);
77
78 $financialType = new CRM_Financial_DAO_FinancialType();
79 $financialType->id = $contributionTypeId;
80 $financialType->find(TRUE);
81 if ($financialType->is_deductible) {
82 $form->assign('is_deductible', TRUE);
83 $form->set('is_deductible', TRUE);
84 }
85
86 // add some financial type details to the params list
87 // if folks need to use it
88 //CRM-15297 - contributionType is obsolete - pass financial type as well so people can deprecate it
89 $paymentParams['financialType_name'] = $paymentParams['contributionType_name'] = $form->_params['contributionType_name'] = $financialType->name;
90 //CRM-11456
91 $paymentParams['financialType_accounting_code'] = $paymentParams['contributionType_accounting_code'] = $form->_params['contributionType_accounting_code'] = CRM_Financial_BAO_FinancialAccount::getAccountingCode($contributionTypeId);
92 $paymentParams['contributionPageID'] = $form->_params['contributionPageID'] = $form->_values['id'];
93
94 $payment = NULL;
95 $paymentObjError = ts('The system did not record payment details for this payment and so could not process the transaction. Please report this error to the site administrator.');
96
97 if ($isPaymentTransaction && !empty($form->_paymentProcessor)) {
98 // @todo - remove this line once we are sure we can just use $form->_paymentProcessor['object'] consistently.
99 $payment = Civi\Payment\System::singleton()->getByProcessor($form->_paymentProcessor);
100 }
101
102 //fix for CRM-16317
103 $form->_params['receive_date'] = date('YmdHis');
104 $form->assign('receive_date',
105 CRM_Utils_Date::mysqlToIso($form->_params['receive_date'])
106 );
107 $result = NULL;
108 if ($form->_contributeMode == 'notify' ||
109 $isPayLater
110 ) {
111 // this is not going to come back, i.e. we fill in the other details
112 // when we get a callback from the payment processor
113 // also add the contact ID and contribution ID to the params list
114 $paymentParams['contactID'] = $form->_params['contactID'] = $contactID;
115 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution(
116 $form,
117 $paymentParams,
118 NULL,
119 $contactID,
120 $financialType,
121 TRUE, TRUE,
122 $isTest,
123 $lineItems,
124 $form->_bltID
125 );
126
127 if ($contribution) {
128 $form->_params['contributionID'] = $contribution->id;
129 }
130
131 $form->_params['contributionTypeID'] = $contributionTypeId;
132 $form->_params['item_name'] = $form->_params['description'];
133
134 if ($contribution && $form->_values['is_recur'] &&
135 $contribution->contribution_recur_id
136 ) {
137 $form->_params['contributionRecurID'] = $contribution->contribution_recur_id;
138 }
139
140 $form->set('params', $form->_params);
141 $form->postProcessPremium($premiumParams, $contribution);
142
143 if ($isPaymentTransaction) {
144 // add qfKey so we can send to paypal
145 $form->_params['qfKey'] = $form->controller->_key;
146 if ($component == 'membership') {
147 return array('contribution' => $contribution);
148 }
149 else {
150 if (!$isPayLater) {
151 if (is_object($payment)) {
152 // call postProcess hook before leaving
153 $form->postProcessHook();
154 // this does not return
155 $result = $payment->doTransferCheckout($form->_params, 'contribute');
156 }
157 else {
158 CRM_Core_Error::fatal($paymentObjError);
159 }
160 }
161 else {
162 // follow similar flow as IPN
163 // send the receipt mail
164 $form->set('params', $form->_params);
165 if (isset($paymentParams['contribution_source'])) {
166 $form->_params['source'] = $paymentParams['contribution_source'];
167 }
168
169 // get the price set values for receipt.
170 if ($form->_priceSetId && $form->_lineItem) {
171 $form->_values['lineItem'] = $form->_lineItem;
172 $form->_values['priceSetID'] = $form->_priceSetId;
173 }
174
175 $form->_values['contribution_id'] = $contribution->id;
176 $form->_values['contribution_page_id'] = $contribution->contribution_page_id;
177
178 CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
179 $form->_values,
180 $contribution->is_test
181 );
182 return;
183 }
184 }
185 }
186 }
187 elseif ($form->_contributeMode == 'express') {
188 if ($form->_values['is_monetary'] && $form->_amount > 0.0) {
189 // determine if express + recurring and direct accordingly
190 if (!empty($paymentParams['is_recur']) && $paymentParams['is_recur'] == 1) {
191 if (is_object($payment)) {
192 $result = $payment->createRecurringPayments($paymentParams);
193 }
194 else {
195 CRM_Core_Error::fatal($paymentObjError);
196 }
197 }
198 else {
199 if (is_object($payment)) {
200 $result = $payment->doExpressCheckout($paymentParams);
201 }
202 else {
203 CRM_Core_Error::fatal($paymentObjError);
204 }
205 }
206 }
207 }
208 elseif ($isPaymentTransaction) {
209 if ($form->_contributeMode == 'direct') {
210 $paymentParams['contactID'] = $contactID;
211
212 // Fix for CRM-14354. If the membership is recurring, don't create a
213 // civicrm_contribution_recur record for the additional contribution
214 // (i.e., the amount NOT associated with the membership). Temporarily
215 // cache the is_recur values so we can process the additional gift as a
216 // one-off payment.
217 if (!empty($form->_values['is_recur'])) {
218 if ($form->_membershipBlock['is_separate_payment'] && !empty($form->_params['auto_renew'])) {
219 $cachedFormValue = CRM_Utils_Array::value('is_recur', $form->_values);
220 $cachedParamValue = CRM_Utils_Array::value('is_recur', $paymentParams);
221 unset($form->_values['is_recur']);
222 unset($paymentParams['is_recur']);
223 }
224 }
225
226 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution(
227 $form,
228 $paymentParams,
229 NULL,
230 $contactID,
231 $financialType,
232 TRUE,
233 TRUE,
234 $isTest,
235 $lineItems,
236 $form->_bltID
237 );
238
239 // restore cached values (part of fix for CRM-14354)
240 if (!empty($cachedFormValue)) {
241 $form->_values['is_recur'] = $cachedFormValue;
242 $paymentParams['is_recur'] = $cachedParamValue;
243 }
244
245 $paymentParams['contributionID'] = $contribution->id;
246 //CRM-15297 deprecate contributionTypeID
247 $paymentParams['financialTypeID'] = $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
248 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
249
250 if ($form->_values['is_recur'] && $contribution->contribution_recur_id) {
251 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
252 }
253 }
254 try {
255 $result = $payment->doPayment($paymentParams);
256 }
257 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
258 // Clean up DB as appropriate.
259 if (!empty($paymentParams['contributionID'])) {
260 CRM_Contribute_BAO_Contribution::failPayment($paymentParams['contributionID'],
261 $paymentParams['contactID'], $e->getMessage());
262 }
263 if (!empty($paymentParams['contributionRecurID'])) {
264 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
265 }
266
267 $result['is_payment_failure'] = TRUE;
268 $result['error'] = $e;
269 }
270 }
271
272 if ($result || ($form->_amount == 0.0 && !$form->_params['is_pay_later'])) {
273 if ($result) {
274 $form->_params = array_merge($form->_params, $result);
275 }
276 $form->set('params', $form->_params);
277 $form->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
278
279 // result has all the stuff we need
280 // lets archive it to a financial transaction
281
282 if (isset($paymentParams['contribution_source'])) {
283 $form->_params['source'] = $paymentParams['contribution_source'];
284 }
285
286 $form->postProcessPremium($premiumParams, $contribution);
287 if (is_array($result) && !empty($result['trxn_id'])) {
288 $contribution->trxn_id = $result['trxn_id'];
289 }
290 $result['contribution'] = $contribution;
291 }
292 //Do not send an email if Recurring contribution is done via Direct Mode
293 //We will send email once the IPN is received.
294 if ($form->_contributeMode == 'direct') {
295 return $result;
296 }
297
298 // get the price set values for receipt.
299 if ($form->_priceSetId && $form->_lineItem) {
300 $form->_values['lineItem'] = $form->_lineItem;
301 $form->_values['priceSetID'] = $form->_priceSetId;
302 }
303
304 // finally send an email receipt
305 if ($contribution) {
306 $form->_values['contribution_id'] = $contribution->id;
307 CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
308 $form->_values, $contribution->is_test,
309 FALSE, $fieldTypes
310 );
311 }
312 }
313
314 /**
315 * Is a payment being made.
316 * Note that setting is_monetary on the form is somewhat legacy and the behaviour around this setting is confusing. It would be preferable
317 * to look for the amount only (assuming this cannot refer to payment in goats or other non-monetary currency
318 * @param CRM_Core_Form $form
319 *
320 * @return bool
321 */
322 static protected function isPaymentTransaction($form) {
323 if (!empty($form->_values['is_monetary']) && $form->_amount >= 0.0) {
324 return TRUE;
325 }
326 return FALSE;
327
328 }
329
330 /**
331 * Get the contribution details by month of the year.
332 *
333 * @param int $param
334 * Year.
335 *
336 * @return array
337 * associated array
338 */
339 public static function contributionChartMonthly($param) {
340 if ($param) {
341 $param = array(1 => array($param, 'Integer'));
342 }
343 else {
344 $param = date("Y");
345 $param = array(1 => array($param, 'Integer'));
346 }
347
348 $query = "
349 SELECT sum(contrib.total_amount) AS ctAmt,
350 MONTH( contrib.receive_date) AS contribMonth
351 FROM civicrm_contribution AS contrib
352 INNER JOIN civicrm_contact AS contact ON ( contact.id = contrib.contact_id )
353 WHERE contrib.contact_id = contact.id
354 AND ( contrib.is_test = 0 OR contrib.is_test IS NULL )
355 AND contrib.contribution_status_id = 1
356 AND date_format(contrib.receive_date,'%Y') = %1
357 AND contact.is_deleted = 0
358 GROUP BY contribMonth
359 ORDER BY month(contrib.receive_date)";
360
361 $dao = CRM_Core_DAO::executeQuery($query, $param);
362
363 $params = NULL;
364 while ($dao->fetch()) {
365 if ($dao->contribMonth) {
366 $params['By Month'][$dao->contribMonth] = $dao->ctAmt;
367 }
368 }
369 return $params;
370 }
371
372 /**
373 * Get the contribution details by year.
374 *
375 * @return array
376 * associated array
377 */
378 public static function contributionChartYearly() {
379 $config = CRM_Core_Config::singleton();
380 $yearClause = "year(contrib.receive_date) as contribYear";
381 if (!empty($config->fiscalYearStart) && ($config->fiscalYearStart['M'] != 1 || $config->fiscalYearStart['d'] != 1)) {
382 $yearClause = "CASE
383 WHEN (MONTH(contrib.receive_date)>= " . $config->fiscalYearStart['M'] . "
384 && DAYOFMONTH(contrib.receive_date)>= " . $config->fiscalYearStart['d'] . " )
385 THEN
386 concat(YEAR(contrib.receive_date), '-',YEAR(contrib.receive_date)+1)
387 ELSE
388 concat(YEAR(contrib.receive_date)-1,'-', YEAR(contrib.receive_date))
389 END AS contribYear";
390 }
391
392 $query = "
393 SELECT sum(contrib.total_amount) AS ctAmt,
394 {$yearClause}
395 FROM civicrm_contribution AS contrib
396 INNER JOIN civicrm_contact contact ON ( contact.id = contrib.contact_id )
397 WHERE ( contrib.is_test = 0 OR contrib.is_test IS NULL )
398 AND contrib.contribution_status_id = 1
399 AND contact.is_deleted = 0
400 GROUP BY contribYear
401 ORDER BY contribYear";
402 $dao = CRM_Core_DAO::executeQuery($query);
403
404 $params = NULL;
405 while ($dao->fetch()) {
406 if (!empty($dao->contribYear)) {
407 $params['By Year'][$dao->contribYear] = $dao->ctAmt;
408 }
409 }
410 return $params;
411 }
412
413 /**
414 * @param array $params
415 * @param int $contactID
416 * @param $mail
417 */
418 public static function createCMSUser(&$params, $contactID, $mail) {
419 // lets ensure we only create one CMS user
420 static $created = FALSE;
421
422 if ($created) {
423 return;
424 }
425 $created = TRUE;
426
427 if (!empty($params['cms_create_account'])) {
428 $params['contactID'] = $contactID;
429 if (!CRM_Core_BAO_CMSUser::create($params, $mail)) {
430 CRM_Core_Error::statusBounce(ts('Your profile is not saved and Account is not created.'));
431 }
432 }
433 }
434
435 /**
436 * @param array $params
437 * @param string $type
438 *
439 * @return bool
440 */
441 public static function _fillCommonParams(&$params, $type = 'paypal') {
442 if (array_key_exists('transaction', $params)) {
443 $transaction = &$params['transaction'];
444 }
445 else {
446 $transaction = &$params;
447 }
448
449 $params['contact_type'] = 'Individual';
450
451 $billingLocTypeId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', 'Billing', 'id', 'name');
452 if (!$billingLocTypeId) {
453 $billingLocTypeId = 1;
454 }
455 if (!CRM_Utils_System::isNull($params['address'])) {
456 $params['address'][1]['is_primary'] = 1;
457 $params['address'][1]['location_type_id'] = $billingLocTypeId;
458 }
459 if (!CRM_Utils_System::isNull($params['email'])) {
460 $params['email'] = array(
461 1 => array(
462 'email' => $params['email'],
463 'location_type_id' => $billingLocTypeId,
464 ),
465 );
466 }
467
468 if (isset($transaction['trxn_id'])) {
469 // set error message if transaction has already been processed.
470 $contribution = new CRM_Contribute_DAO_Contribution();
471 $contribution->trxn_id = $transaction['trxn_id'];
472 if ($contribution->find(TRUE)) {
473 $params['error'][] = ts('transaction already processed.');
474 }
475 }
476 else {
477 // generate a new transaction id, if not already exist
478 $transaction['trxn_id'] = md5(uniqid(rand(), TRUE));
479 }
480
481 if (!isset($transaction['financial_type_id'])) {
482 $contributionTypes = array_keys(CRM_Contribute_PseudoConstant::financialType());
483 $transaction['financial_type_id'] = $contributionTypes[0];
484 }
485
486 if (($type == 'paypal') && (!isset($transaction['net_amount']))) {
487 $transaction['net_amount'] = $transaction['total_amount'] - CRM_Utils_Array::value('fee_amount', $transaction, 0);
488 }
489
490 if (!isset($transaction['invoice_id'])) {
491 $transaction['invoice_id'] = $transaction['trxn_id'];
492 }
493
494 $source = ts('ContributionProcessor: %1 API',
495 array(1 => ucfirst($type))
496 );
497 if (isset($transaction['source'])) {
498 $transaction['source'] = $source . ':: ' . $transaction['source'];
499 }
500 else {
501 $transaction['source'] = $source;
502 }
503
504 return TRUE;
505 }
506
507 /**
508 * @param int $contactID
509 *
510 * @return mixed
511 */
512 public static function getFirstLastDetails($contactID) {
513 static $_cache;
514
515 if (!$_cache) {
516 $_cache = array();
517 }
518
519 if (!isset($_cache[$contactID])) {
520 $sql = "
521 SELECT total_amount, receive_date
522 FROM civicrm_contribution c
523 WHERE contact_id = %1
524 ORDER BY receive_date ASC
525 LIMIT 1
526 ";
527 $params = array(1 => array($contactID, 'Integer'));
528
529 $dao = CRM_Core_DAO::executeQuery($sql, $params);
530 $details = array(
531 'first' => NULL,
532 'last' => NULL,
533 );
534 if ($dao->fetch()) {
535 $details['first'] = array(
536 'total_amount' => $dao->total_amount,
537 'receive_date' => $dao->receive_date,
538 );
539 }
540
541 // flip asc and desc to get the last query
542 $sql = str_replace('ASC', 'DESC', $sql);
543 $dao = CRM_Core_DAO::executeQuery($sql, $params);
544 if ($dao->fetch()) {
545 $details['last'] = array(
546 'total_amount' => $dao->total_amount,
547 'receive_date' => $dao->receive_date,
548 );
549 }
550
551 $_cache[$contactID] = $details;
552 }
553 return $_cache[$contactID];
554 }
555
556 /**
557 * Calculate the tax amount based on given tax rate.
558 *
559 * @param float $amount
560 * Amount of field.
561 * @param float $taxRate
562 * Tax rate of selected financial account for field.
563 *
564 * @return array
565 * array of tax amount
566 *
567 */
568 public static function calculateTaxAmount($amount, $taxRate) {
569 $taxAmount = array();
570 $taxAmount['tax_amount'] = ($taxRate / 100) * CRM_Utils_Rule::cleanMoney($amount);
571
572 return $taxAmount;
573 }
574
575 }