Merge branch '4.6' of https://github.com/civicrm/civicrm-core
[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)) {
288 if (!empty($result['trxn_id'])) {
289 $contribution->trxn_id = $result['trxn_id'];
290 }
291 if (!empty($result['payment_status_id'])) {
292 $contribution->payment_status_id = $result['payment_status_id'];
293 }
294 }
295 $result['contribution'] = $contribution;
296 }
297 //Do not send an email if Recurring contribution is done via Direct Mode
298 //We will send email once the IPN is received.
299 if ($form->_contributeMode == 'direct') {
300 return $result;
301 }
302
303 // get the price set values for receipt.
304 if ($form->_priceSetId && $form->_lineItem) {
305 $form->_values['lineItem'] = $form->_lineItem;
306 $form->_values['priceSetID'] = $form->_priceSetId;
307 }
308
309 // finally send an email receipt
310 if ($contribution) {
311 $form->_values['contribution_id'] = $contribution->id;
312 CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
313 $form->_values, $contribution->is_test,
314 FALSE, $fieldTypes
315 );
316 }
317 }
318
319 /**
320 * Is a payment being made.
321 * Note that setting is_monetary on the form is somewhat legacy and the behaviour around this setting is confusing. It would be preferable
322 * to look for the amount only (assuming this cannot refer to payment in goats or other non-monetary currency
323 * @param CRM_Core_Form $form
324 *
325 * @return bool
326 */
327 static protected function isPaymentTransaction($form) {
328 if (!empty($form->_values['is_monetary']) && $form->_amount >= 0.0) {
329 return TRUE;
330 }
331 return FALSE;
332
333 }
334
335 /**
336 * Get the contribution details by month of the year.
337 *
338 * @param int $param
339 * Year.
340 *
341 * @return array
342 * associated array
343 */
344 public static function contributionChartMonthly($param) {
345 if ($param) {
346 $param = array(1 => array($param, 'Integer'));
347 }
348 else {
349 $param = date("Y");
350 $param = array(1 => array($param, 'Integer'));
351 }
352
353 $query = "
354 SELECT sum(contrib.total_amount) AS ctAmt,
355 MONTH( contrib.receive_date) AS contribMonth
356 FROM civicrm_contribution AS contrib
357 INNER JOIN civicrm_contact AS contact ON ( contact.id = contrib.contact_id )
358 WHERE contrib.contact_id = contact.id
359 AND ( contrib.is_test = 0 OR contrib.is_test IS NULL )
360 AND contrib.contribution_status_id = 1
361 AND date_format(contrib.receive_date,'%Y') = %1
362 AND contact.is_deleted = 0
363 GROUP BY contribMonth
364 ORDER BY month(contrib.receive_date)";
365
366 $dao = CRM_Core_DAO::executeQuery($query, $param);
367
368 $params = NULL;
369 while ($dao->fetch()) {
370 if ($dao->contribMonth) {
371 $params['By Month'][$dao->contribMonth] = $dao->ctAmt;
372 }
373 }
374 return $params;
375 }
376
377 /**
378 * Get the contribution details by year.
379 *
380 * @return array
381 * associated array
382 */
383 public static function contributionChartYearly() {
384 $config = CRM_Core_Config::singleton();
385 $yearClause = "year(contrib.receive_date) as contribYear";
386 if (!empty($config->fiscalYearStart) && ($config->fiscalYearStart['M'] != 1 || $config->fiscalYearStart['d'] != 1)) {
387 $yearClause = "CASE
388 WHEN (MONTH(contrib.receive_date)>= " . $config->fiscalYearStart['M'] . "
389 && DAYOFMONTH(contrib.receive_date)>= " . $config->fiscalYearStart['d'] . " )
390 THEN
391 concat(YEAR(contrib.receive_date), '-',YEAR(contrib.receive_date)+1)
392 ELSE
393 concat(YEAR(contrib.receive_date)-1,'-', YEAR(contrib.receive_date))
394 END AS contribYear";
395 }
396
397 $query = "
398 SELECT sum(contrib.total_amount) AS ctAmt,
399 {$yearClause}
400 FROM civicrm_contribution AS contrib
401 INNER JOIN civicrm_contact contact ON ( contact.id = contrib.contact_id )
402 WHERE ( contrib.is_test = 0 OR contrib.is_test IS NULL )
403 AND contrib.contribution_status_id = 1
404 AND contact.is_deleted = 0
405 GROUP BY contribYear
406 ORDER BY contribYear";
407 $dao = CRM_Core_DAO::executeQuery($query);
408
409 $params = NULL;
410 while ($dao->fetch()) {
411 if (!empty($dao->contribYear)) {
412 $params['By Year'][$dao->contribYear] = $dao->ctAmt;
413 }
414 }
415 return $params;
416 }
417
418 /**
419 * @param array $params
420 * @param int $contactID
421 * @param $mail
422 */
423 public static function createCMSUser(&$params, $contactID, $mail) {
424 // lets ensure we only create one CMS user
425 static $created = FALSE;
426
427 if ($created) {
428 return;
429 }
430 $created = TRUE;
431
432 if (!empty($params['cms_create_account'])) {
433 $params['contactID'] = $contactID;
434 if (!CRM_Core_BAO_CMSUser::create($params, $mail)) {
435 CRM_Core_Error::statusBounce(ts('Your profile is not saved and Account is not created.'));
436 }
437 }
438 }
439
440 /**
441 * @param array $params
442 * @param string $type
443 *
444 * @return bool
445 */
446 public static function _fillCommonParams(&$params, $type = 'paypal') {
447 if (array_key_exists('transaction', $params)) {
448 $transaction = &$params['transaction'];
449 }
450 else {
451 $transaction = &$params;
452 }
453
454 $params['contact_type'] = 'Individual';
455
456 $billingLocTypeId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', 'Billing', 'id', 'name');
457 if (!$billingLocTypeId) {
458 $billingLocTypeId = 1;
459 }
460 if (!CRM_Utils_System::isNull($params['address'])) {
461 $params['address'][1]['is_primary'] = 1;
462 $params['address'][1]['location_type_id'] = $billingLocTypeId;
463 }
464 if (!CRM_Utils_System::isNull($params['email'])) {
465 $params['email'] = array(
466 1 => array(
467 'email' => $params['email'],
468 'location_type_id' => $billingLocTypeId,
469 ),
470 );
471 }
472
473 if (isset($transaction['trxn_id'])) {
474 // set error message if transaction has already been processed.
475 $contribution = new CRM_Contribute_DAO_Contribution();
476 $contribution->trxn_id = $transaction['trxn_id'];
477 if ($contribution->find(TRUE)) {
478 $params['error'][] = ts('transaction already processed.');
479 }
480 }
481 else {
482 // generate a new transaction id, if not already exist
483 $transaction['trxn_id'] = md5(uniqid(rand(), TRUE));
484 }
485
486 if (!isset($transaction['financial_type_id'])) {
487 $contributionTypes = array_keys(CRM_Contribute_PseudoConstant::financialType());
488 $transaction['financial_type_id'] = $contributionTypes[0];
489 }
490
491 if (($type == 'paypal') && (!isset($transaction['net_amount']))) {
492 $transaction['net_amount'] = $transaction['total_amount'] - CRM_Utils_Array::value('fee_amount', $transaction, 0);
493 }
494
495 if (!isset($transaction['invoice_id'])) {
496 $transaction['invoice_id'] = $transaction['trxn_id'];
497 }
498
499 $source = ts('ContributionProcessor: %1 API',
500 array(1 => ucfirst($type))
501 );
502 if (isset($transaction['source'])) {
503 $transaction['source'] = $source . ':: ' . $transaction['source'];
504 }
505 else {
506 $transaction['source'] = $source;
507 }
508
509 return TRUE;
510 }
511
512 /**
513 * @param int $contactID
514 *
515 * @return mixed
516 */
517 public static function getFirstLastDetails($contactID) {
518 static $_cache;
519
520 if (!$_cache) {
521 $_cache = array();
522 }
523
524 if (!isset($_cache[$contactID])) {
525 $sql = "
526 SELECT total_amount, receive_date
527 FROM civicrm_contribution c
528 WHERE contact_id = %1
529 ORDER BY receive_date ASC
530 LIMIT 1
531 ";
532 $params = array(1 => array($contactID, 'Integer'));
533
534 $dao = CRM_Core_DAO::executeQuery($sql, $params);
535 $details = array(
536 'first' => NULL,
537 'last' => NULL,
538 );
539 if ($dao->fetch()) {
540 $details['first'] = array(
541 'total_amount' => $dao->total_amount,
542 'receive_date' => $dao->receive_date,
543 );
544 }
545
546 // flip asc and desc to get the last query
547 $sql = str_replace('ASC', 'DESC', $sql);
548 $dao = CRM_Core_DAO::executeQuery($sql, $params);
549 if ($dao->fetch()) {
550 $details['last'] = array(
551 'total_amount' => $dao->total_amount,
552 'receive_date' => $dao->receive_date,
553 );
554 }
555
556 $_cache[$contactID] = $details;
557 }
558 return $_cache[$contactID];
559 }
560
561 /**
562 * Calculate the tax amount based on given tax rate.
563 *
564 * @param float $amount
565 * Amount of field.
566 * @param float $taxRate
567 * Tax rate of selected financial account for field.
568 *
569 * @return array
570 * array of tax amount
571 *
572 */
573 public static function calculateTaxAmount($amount, $taxRate) {
574 $taxAmount = array();
575 $taxAmount['tax_amount'] = ($taxRate / 100) * CRM_Utils_Rule::cleanMoney($amount);
576
577 return $taxAmount;
578 }
579
580 }