3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
35 class CRM_Contribute_BAO_Contribution_Utils
{
38 * Function to process payment after confirmation
40 * @param object $form form object
41 * @param array $paymentParams array with payment related key
43 * @param array $premiumParams array with premium related key
45 * @param int $contactID contact id
46 * @param int $contributionTypeId financial type id
47 * @param int $component component id
49 * @return array associated array
54 static function processConfirm(&$form,
59 $component = 'contribution',
62 CRM_Core_Payment_Form
::mapParams($form->_bltID
, $form->_params
, $paymentParams, TRUE);
64 $contributionType = new CRM_Financial_DAO_FinancialType();
65 if (isset($paymentParams['financial_type'])) {
66 $contributionType->id
= $paymentParams['financial_type'];
68 elseif (CRM_Utils_Array
::value('pledge_id', $form->_values
)) {
69 $contributionType->id
= CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge',
70 $form->_values
['pledge_id'],
75 $contributionType->id
= $contributionTypeId;
77 if (!$contributionType->find(TRUE)) {
78 CRM_Core_Error
::fatal('Could not find a system table');
81 // add some financial type details to the params list
82 // if folks need to use it
83 $paymentParams['contributionType_name'] = $form->_params
['contributionType_name'] = $contributionType->name
;
85 $paymentParams['contributionType_accounting_code'] = $form->_params
['contributionType_accounting_code'] = CRM_Financial_BAO_FinancialAccount
::getAccountingCode($contributionType->id
);
86 $paymentParams['contributionPageID'] = $form->_params
['contributionPageID'] = $form->_values
['id'];
90 $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.');
91 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0 && is_array($form->_paymentProcessor
)) {
92 $payment = CRM_Core_Payment
::singleton($form->_mode
, $form->_paymentProcessor
, $form);
96 $now = date('YmdHis');
99 if ($form->_contributeMode
== 'notify' ||
100 $form->_params
['is_pay_later']
102 // this is not going to come back, i.e. we fill in the other details
103 // when we get a callback from the payment processor
104 // also add the contact ID and contribution ID to the params list
105 $paymentParams['contactID'] = $form->_params
['contactID'] = $contactID;
106 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution(
116 $form->_params
['contributionID'] = $contribution->id
;
119 $form->_params
['contributionTypeID'] = $contributionType->id
;
120 $form->_params
['item_name'] = $form->_params
['description'];
121 $form->_params
['receive_date'] = $now;
123 if ($contribution && $form->_values
['is_recur'] &&
124 $contribution->contribution_recur_id
126 $form->_params
['contributionRecurID'] = $contribution->contribution_recur_id
;
129 $form->set('params', $form->_params
);
130 $form->postProcessPremium($premiumParams, $contribution);
132 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0) {
133 // add qfKey so we can send to paypal
134 $form->_params
['qfKey'] = $form->controller
->_key
;
135 if ($component == 'membership') {
136 $membershipResult = array(1 => $contribution);
137 return $membershipResult;
140 if (!$form->_params
['is_pay_later']) {
141 if (is_object($payment)) {
142 // call postprocess hook before leaving
143 $form->postProcessHook();
144 // this does not return
145 $result = &$payment->doTransferCheckout($form->_params
, 'contribute');
148 CRM_Core_Error
::fatal($paymentObjError);
152 // follow similar flow as IPN
153 // send the receipt mail
154 $form->set('params', $form->_params
);
155 if ($contributionType->is_deductible
) {
156 $form->assign('is_deductible', TRUE);
157 $form->set('is_deductible', TRUE);
159 if (isset($paymentParams['contribution_source'])) {
160 $form->_params
['source'] = $paymentParams['contribution_source'];
163 // get the price set values for receipt.
164 if ($form->_priceSetId
&& $form->_lineItem
) {
165 $form->_values
['lineItem'] = $form->_lineItem
;
166 $form->_values
['priceSetID'] = $form->_priceSetId
;
169 $form->_values
['contribution_id'] = $contribution->id
;
170 $form->_values
['contribution_page_id'] = $contribution->contribution_page_id
;
172 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
174 $contribution->is_test
181 elseif ($form->_contributeMode
== 'express') {
182 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0) {
183 // determine if express + recurring and direct accordingly
184 if ($paymentParams['is_recur'] == 1) {
185 if (is_object($payment)) {
186 $result = $payment->createRecurringPayments($paymentParams);
189 CRM_Core_Error
::fatal($paymentObjError);
193 if (is_object($payment)) {
194 $result = $payment->doExpressCheckout($paymentParams);
197 CRM_Core_Error
::fatal($paymentObjError);
202 elseif ($form->_values
['is_monetary'] && $form->_amount
> 0.0) {
203 if (CRM_Utils_Array
::value('is_recur', $paymentParams) &&
204 $form->_contributeMode
== 'direct'
207 // For recurring contribution, create Contribution Record first.
208 // Contribution ID, Recurring ID and Contact ID needed
209 // When we get a callback from the payment processor
211 $paymentParams['contactID'] = $contactID;
212 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution(
221 $paymentParams['contributionID'] = $contribution->id
;
222 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
223 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
225 if ($form->_values
['is_recur'] && $contribution->contribution_recur_id
) {
226 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
229 if (is_object($payment)) {
230 $result = $payment->doDirectPayment($paymentParams);
233 CRM_Core_Error
::fatal($paymentObjError);
237 if ($component == 'membership') {
238 $membershipResult = array();
241 if (is_a($result, 'CRM_Core_Error')) {
242 //make sure to cleanup db for recurring case.
243 if (CRM_Utils_Array
::value('contributionID', $paymentParams)) {
244 CRM_Contribute_BAO_Contribution
::deleteContribution($paymentParams['contributionID']);
246 if (CRM_Utils_Array
::value('contributionRecurID', $paymentParams)) {
247 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($paymentParams['contributionRecurID']);
250 if ($component !== 'membership') {
251 CRM_Core_Error
::displaySessionError($result);
252 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact',
253 "_qf_Main_display=true&qfKey={$form->_params['qfKey']}"
256 $membershipResult[1] = $result;
258 elseif ($result ||
($form->_amount
== 0.0 && !$form->_params
['is_pay_later'])) {
260 $form->_params
= array_merge($form->_params
, $result);
262 $form->_params
['receive_date'] = $now;
263 $form->set('params', $form->_params
);
264 $form->assign('trxn_id', CRM_Utils_Array
::value('trxn_id', $result));
265 $form->assign('receive_date',
266 CRM_Utils_Date
::mysqlToIso($form->_params
['receive_date'])
269 // result has all the stuff we need
270 // lets archive it to a financial transaction
271 if ($contributionType->is_deductible
) {
272 $form->assign('is_deductible', TRUE);
273 $form->set('is_deductible', TRUE);
276 if (isset($paymentParams['contribution_source'])) {
277 $form->_params
['source'] = $paymentParams['contribution_source'];
280 // check if pending was set to true by payment processor
282 if (CRM_Utils_Array
::value('contribution_status_pending',
287 if (!(!empty($paymentParams['is_recur']) && $form->_contributeMode
== 'direct')) {
288 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($form,
289 $form->_params
, $result,
290 $contactID, $contributionType,
294 $form->postProcessPremium($premiumParams, $contribution);
296 $membershipResult[1] = $contribution;
299 if ($component == 'membership') {
300 return $membershipResult;
303 //Do not send an email if Recurring contribution is done via Direct Mode
304 //We will send email once the IPN is received.
305 if (!empty($paymentParams['is_recur']) && $form->_contributeMode
== 'direct') {
309 // get the price set values for receipt.
310 if ($form->_priceSetId
&& $form->_lineItem
) {
311 $form->_values
['lineItem'] = $form->_lineItem
;
312 $form->_values
['priceSetID'] = $form->_priceSetId
;
315 // finally send an email receipt
317 $form->_values
['contribution_id'] = $contribution->id
;
318 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
319 $form->_values
, $contribution->is_test
,
326 * Function to get the contribution details by month
329 * @param int $param year
331 * @return array associated array
336 static function contributionChartMonthly($param) {
338 $param = array(1 => array($param, 'Integer'));
342 $param = array(1 => array($param, 'Integer'));
346 SELECT sum(contrib.total_amount) AS ctAmt,
347 MONTH( contrib.receive_date) AS contribMonth
348 FROM civicrm_contribution AS contrib
349 INNER JOIN civicrm_contact AS contact ON ( contact.id = contrib.contact_id )
350 WHERE contrib.contact_id = contact.id
351 AND ( contrib.is_test = 0 OR contrib.is_test IS NULL )
352 AND contrib.contribution_status_id = 1
353 AND date_format(contrib.receive_date,'%Y') = %1
354 AND contact.is_deleted = 0
355 GROUP BY contribMonth
356 ORDER BY month(contrib.receive_date)";
358 $dao = CRM_Core_DAO
::executeQuery($query, $param);
361 while ($dao->fetch()) {
362 if ($dao->contribMonth
) {
363 $params['By Month'][$dao->contribMonth
] = $dao->ctAmt
;
370 * Function to get the contribution details by year
372 * @return array associated array
377 static function contributionChartYearly() {
378 $config = CRM_Core_Config
::singleton();
379 $yearClause = "year(contrib.receive_date) as contribYear";
380 if (!empty($config->fiscalYearStart
) && ($config->fiscalYearStart
['M'] != 1 ||
$config->fiscalYearStart
['d'] != 1)) {
382 WHEN (MONTH(contrib.receive_date)>= " . $config->fiscalYearStart
['M'] . "
383 && DAYOFMONTH(contrib.receive_date)>= " . $config->fiscalYearStart
['d'] . " )
385 concat(YEAR(contrib.receive_date), '-',YEAR(contrib.receive_date)+1)
387 concat(YEAR(contrib.receive_date)-1,'-', YEAR(contrib.receive_date))
392 SELECT sum(contrib.total_amount) AS ctAmt,
394 FROM civicrm_contribution AS contrib
395 INNER JOIN civicrm_contact contact ON ( contact.id = contrib.contact_id )
396 WHERE ( contrib.is_test = 0 OR contrib.is_test IS NULL )
397 AND contrib.contribution_status_id = 1
398 AND contact.is_deleted = 0
400 ORDER BY contribYear";
401 $dao = CRM_Core_DAO
::executeQuery($query);
404 while ($dao->fetch()) {
405 if (!empty($dao->contribYear
)) {
406 $params['By Year'][$dao->contribYear
] = $dao->ctAmt
;
412 static function createCMSUser(&$params, $contactID, $mail) {
413 // lets ensure we only create one CMS user
414 static $created = FALSE;
421 if (CRM_Utils_Array
::value('cms_create_account', $params)) {
422 $params['contactID'] = $contactID;
423 if (!CRM_Core_BAO_CMSUser
::create($params, $mail)) {
424 CRM_Core_Error
::statusBounce(ts('Your profile is not saved and Account is not created.'));
429 static function _fillCommonParams(&$params, $type = 'paypal') {
430 if (array_key_exists('transaction', $params)) {
431 $transaction = &$params['transaction'];
434 $transaction = &$params;
437 $params['contact_type'] = 'Individual';
439 $billingLocTypeId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType', 'Billing', 'id', 'name');
440 if (!$billingLocTypeId) {
441 $billingLocTypeId = 1;
443 if (!CRM_Utils_System
::isNull($params['address'])) {
444 $params['address'][1]['is_primary'] = 1;
445 $params['address'][1]['location_type_id'] = $billingLocTypeId;
447 if (!CRM_Utils_System
::isNull($params['email'])) {
448 $params['email'] = array(
449 1 => array('email' => $params['email'],
450 'location_type_id' => $billingLocTypeId,
454 if (isset($transaction['trxn_id'])) {
455 // set error message if transaction has already been processed.
456 $contribution = new CRM_Contribute_DAO_Contribution();
457 $contribution->trxn_id
= $transaction['trxn_id'];
458 if ($contribution->find(TRUE)) {
459 $params['error'][] = ts('transaction already processed.');
463 // generate a new transaction id, if not already exist
464 $transaction['trxn_id'] = md5(uniqid(rand(), TRUE));
467 if (!isset( $transaction['financial_type_id'])) {
468 $contributionTypes = array_keys(CRM_Contribute_PseudoConstant
::financialType());
469 $transaction['financial_type_id'] = $contributionTypes[0];
472 if (($type == 'paypal') && (!isset($transaction['net_amount']))) {
473 $transaction['net_amount'] = $transaction['total_amount'] - CRM_Utils_Array
::value('fee_amount', $transaction, 0);
476 if (!isset($transaction['invoice_id'])) {
477 $transaction['invoice_id'] = $transaction['trxn_id'];
480 $source = ts('ContributionProcessor: %1 API',
481 array(1 => ucfirst($type))
483 if (isset($transaction['source'])) {
484 $transaction['source'] = $source . ':: ' . $transaction['source'];
487 $transaction['source'] = $source;
493 static function formatAPIParams($apiParams, $mapper, $type = 'paypal', $category = TRUE) {
494 $type = strtolower($type);
496 if (!in_array($type, array(
497 'paypal', 'google', 'csv'))) {
498 // return the params as is
501 $params = $transaction = array();
503 if ($type == 'paypal') {
504 foreach ($apiParams as $detail => $val) {
505 if (isset($mapper['contact'][$detail])) {
506 $params[$mapper['contact'][$detail]] = $val;
508 elseif (isset($mapper['location'][$detail])) {
509 $params['address'][1][$mapper['location'][$detail]] = $val;
511 elseif (isset($mapper['transaction'][$detail])) {
514 // Sadly, PayPal seems to send two distinct data elements in a single field,
515 // so we break them out here. This is somewhat ugly and tragic.
522 list($frequency_interval, $frequency_unit) = explode(' ', $val);
523 $transaction['frequency_interval'] = $frequency_interval;
524 $transaction['frequency_unit'] = $freqUnits[$frequency_unit];
527 case 'subscriptiondate':
529 // PayPal dates are in ISO-8601 format. We need a format that
531 $unix_timestamp = strtotime($val);
532 $transaction[$mapper['transaction'][$detail]] = date('YmdHis', $unix_timestamp);
539 $val = "[PayPal_field:{$detail}] {$val}";
540 $transaction[$mapper['transaction'][$detail]] = !empty($transaction[$mapper['transaction'][$detail]]) ?
$transaction[$mapper['transaction'][$detail]] . " <br/> " . $val : $val;
545 $transaction[$mapper['transaction'][$detail]] = $val;
550 if (!empty($transaction) && $category) {
551 $params['transaction'] = $transaction;
554 $params +
= $transaction;
557 self
::_fillCommonParams($params, $type);
562 if ($type == 'csv') {
563 $header = $apiParams['header'];
564 unset($apiParams['header']);
565 foreach ($apiParams as $key => $val) {
566 if (isset($mapper['contact'][$header[$key]])) {
567 $params[$mapper['contact'][$header[$key]]] = $val;
569 elseif (isset($mapper['location'][$header[$key]])) {
570 $params['address'][1][$mapper['location'][$header[$key]]] = $val;
572 elseif (isset($mapper['transaction'][$header[$key]])) {
573 $transaction[$mapper['transaction'][$header[$key]]] = $val;
576 $params[$header[$key]] = $val;
580 if (!empty($transaction) && $category) {
581 $params['transaction'] = $transaction;
584 $params +
= $transaction;
587 self
::_fillCommonParams($params, $type);
592 if ($type == 'google') {
593 // return if response smell invalid
594 if (!array_key_exists('risk-information-notification', $apiParams[1][$apiParams[0]]['notifications'])) {
597 $riskInfo = &$apiParams[1][$apiParams[0]]['notifications']['risk-information-notification'];
599 if (array_key_exists('new-order-notification', $apiParams[1][$apiParams[0]]['notifications'])) {
600 $newOrder = &$apiParams[1][$apiParams[0]]['notifications']['new-order-notification'];
603 if ($riskInfo['google-order-number']['VALUE'] == $apiParams[2]['google-order-number']['VALUE']) {
604 foreach ($riskInfo['risk-information']['billing-address'] as $field => $info) {
605 if (CRM_Utils_Array
::value($field, $mapper['location'])) {
606 $params['address'][1][$mapper['location'][$field]] = $info['VALUE'];
608 elseif (CRM_Utils_Array
::value($field, $mapper['contact'])) {
609 if ($newOrder && CRM_Utils_Array
::value('structured-name', $newOrder['buyer-billing-address'])) {
610 foreach ($newOrder['buyer-billing-address']['structured-name'] as $namePart => $nameValue) {
611 $params[$mapper['contact'][$namePart]] = $nameValue['VALUE'];
615 $params[$mapper['contact'][$field]] = $info['VALUE'];
618 elseif (CRM_Utils_Array
::value($field, $mapper['transaction'])) {
619 $transaction[$mapper['transaction'][$field]] = $info['VALUE'];
623 // Response is an huge array. Lets pickup only those which we ineterested in
624 // using a local mapper, rather than traversing the entire array.
625 $localMapper = array(
626 'google-order-number' => $riskInfo['google-order-number']['VALUE'],
627 'total-charge-amount' => $apiParams[2]['total-charge-amount']['VALUE'],
628 'currency' => $apiParams[2]['total-charge-amount']['currency'],
629 'item-name' => $newOrder['shopping-cart']['items']['item']['item-name']['VALUE'],
630 'timestamp' => $apiParams[2]['timestamp']['VALUE'],
632 if (array_key_exists('latest-charge-fee', $apiParams[2])) {
633 $localMapper['latest-charge-fee'] = $apiParams[2]['latest-charge-fee']['total']['VALUE'];
634 $localMapper['net-amount'] = $localMapper['total-charge-amount'] - $localMapper['latest-charge-fee'];
637 // This is a subscription (recurring) donation.
638 if (array_key_exists('subscription', $newOrder['shopping-cart']['items']['item'])) {
639 $subscription = $newOrder['shopping-cart']['items']['item']['subscription'];
640 $localMapper['amount'] = $newOrder['order-total']['VALUE'];
641 $localMapper['times'] = $subscription['payments']['subscription-payment']['times'];
642 // Convert Google's period to one compatible with the CiviCRM db field.
646 'MONHTLY' => 'month',
649 $localMapper['period'] = $freqUnits[$subscription['period']];
650 // Unlike PayPal, Google has no concept of freq. interval, it is always 1.
651 $localMapper['frequency_interval'] = '1';
652 // Google Checkout dates are in ISO-8601 format. We need a format that
654 $unix_timestamp = strtotime($localMapper['timestamp']);
655 $mysql_date = date('YmdHis', $unix_timestamp);
656 $localMapper['modified_date'] = $mysql_date;
657 $localMapper['start_date'] = $mysql_date;
658 // This is PayPal's nomenclature, but just use it for Google as well since
659 // we act on the value of trxn_type in processAPIContribution().
660 $localMapper['trxn_type'] = 'subscrpayment';
663 foreach ($localMapper as $localKey => $localVal) {
664 if (CRM_Utils_Array
::value($localKey, $mapper['transaction'])) {
665 $transaction[$mapper['transaction'][$localKey]] = $localVal;
669 if (empty($params) && empty($transaction)) {
673 if (!empty($transaction) && $category) {
674 $params['transaction'] = $transaction;
677 $params +
= $transaction;
680 self
::_fillCommonParams($params, $type);
686 static function processAPIContribution($params) {
687 if (empty($params) ||
array_key_exists('error', $params)) {
691 // add contact using dedupe rule
692 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params, 'Individual');
693 $dedupeParams['check_permission'] = FALSE;
694 $dupeIds = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Individual');
695 // if we find more than one contact, use the first one
696 if (CRM_Utils_Array
::value(0, $dupeIds)) {
697 $params['contact_id'] = $dupeIds[0];
699 $contact = CRM_Contact_BAO_Contact
::create($params);
704 // only pass transaction params to contribution::create, if available
705 if (array_key_exists('transaction', $params)) {
706 $params = $params['transaction'];
707 $params['contact_id'] = $contact->id
;
710 // handle contribution custom data
711 $customFields = CRM_Core_BAO_CustomField
::getFields('Contribution',
714 CRM_Utils_Array
::value('financial_type_id',
718 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
720 CRM_Utils_Array
::value('id', $params, NULL),
723 // create contribution
725 // if this is a recurring contribution then process it first
726 if ($params['trxn_type'] == 'subscrpayment') {
727 // see if a recurring record already exists
728 $recurring = new CRM_Contribute_BAO_ContributionRecur
;
729 $recurring->processor_id
= $params['processor_id'];
730 if (!$recurring->find(TRUE)) {
731 $recurring = new CRM_Contribute_BAO_ContributionRecur
;
732 $recurring->invoice_id
= $params['invoice_id'];
733 $recurring->find(TRUE);
736 // This is the same thing the CiviCRM IPN handler does to handle
737 // subsequent recurring payments to avoid duplicate contribution
738 // errors due to invoice ID. See:
739 // ./CRM/Core/Payment/PayPalIPN.php:200
740 if ($recurring->id
) {
741 $params['invoice_id'] = md5(uniqid(rand(), TRUE));
744 $recurring->copyValues($params);
746 if (is_a($recurring, 'CRM_Core_Error')) {
750 $params['contribution_recur_id'] = $recurring->id
;
754 $contribution = &CRM_Contribute_BAO_Contribution
::create($params,
755 CRM_Core_DAO
::$_nullArray
757 if (!$contribution->id
) {
764 static function getFirstLastDetails($contactID) {
771 if (!isset($_cache[$contactID])) {
773 SELECT total_amount, receive_date
774 FROM civicrm_contribution c
775 WHERE contact_id = %1
776 ORDER BY receive_date ASC
779 $params = array(1 => array($contactID, 'Integer'));
781 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
787 $details['first'] = array(
788 'total_amount' => $dao->total_amount
,
789 'receive_date' => $dao->receive_date
,
793 // flip asc and desc to get the last query
794 $sql = str_replace('ASC', 'DESC', $sql);
795 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
797 $details['last'] = array(
798 'total_amount' => $dao->total_amount
,
799 'receive_date' => $dao->receive_date
,
803 $_cache[$contactID] = $details;
805 return $_cache[$contactID];