Merge pull request #4981 from totten/master-cbf2
[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-2014 |
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-2014
32 * $Id$
33 *
34 */
35 class CRM_Contribute_BAO_Contribution_Utils {
36
37 /**
38 * Process payment after confirmation
39 *
40 * @param CRM_Core_Form $form
41 * Form object.
42 * @param array $paymentParams
43 * Array with payment related key.
44 * value pairs
45 * @param array $premiumParams
46 * Array with premium related key.
47 * value pairs
48 * @param int $contactID
49 * Contact id.
50 * @param int $contributionTypeId
51 * Financial type id.
52 * @param int|string $component component id
53 * @param array $fieldTypes
54 * Presumably relates to custom field types - used when building data for sendMail.
55 * @param $isTest
56 * @param $isPayLater
57 *
58 * @throws CRM_Core_Exception
59 * @throws Exception
60 * @return array
61 * associated array
62 *
63 */
64 public static function processConfirm(
65 &$form,
66 &$paymentParams,
67 &$premiumParams,
68 $contactID,
69 $contributionTypeId,
70 $component = 'contribution',
71 $fieldTypes = NULL,
72 $isTest,
73 $isPayLater
74 ) {
75 CRM_Core_Payment_Form::mapParams($form->_bltID, $form->_params, $paymentParams, TRUE);
76 $lineItems = $form->_lineItem;
77 $isPaymentTransaction = self::isPaymentTransaction($form);
78
79 $contributionType = new CRM_Financial_DAO_FinancialType();
80 $contributionType->id = $contributionTypeId;
81 if (!$contributionType->find(TRUE)) {
82 //@todo - surely this check was part of the 4.3 upgrade & can go now?
83 CRM_Core_Error::fatal('Could not find a system table');
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'] = $contributionType->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) {
98 $payment = CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form);
99 }
100
101 //fix for CRM-2062
102 $now = date('YmdHis');
103
104 $result = NULL;
105 if ($form->_contributeMode == 'notify' ||
106 $isPayLater
107 ) {
108 // this is not going to come back, i.e. we fill in the other details
109 // when we get a callback from the payment processor
110 // also add the contact ID and contribution ID to the params list
111 $paymentParams['contactID'] = $form->_params['contactID'] = $contactID;
112 $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution(
113 $form,
114 $paymentParams,
115 NULL,
116 $contactID,
117 $contributionType,
118 TRUE, TRUE,
119 $isTest,
120 $lineItems
121 );
122
123 if ($contribution) {
124 $form->_params['contributionID'] = $contribution->id;
125 }
126
127 $form->_params['contributionTypeID'] = $contributionTypeId;
128 $form->_params['item_name'] = $form->_params['description'];
129 $form->_params['receive_date'] = $now;
130
131 if ($contribution && $form->_values['is_recur'] &&
132 $contribution->contribution_recur_id
133 ) {
134 $form->_params['contributionRecurID'] = $contribution->contribution_recur_id;
135 }
136
137 $form->set('params', $form->_params);
138 $form->postProcessPremium($premiumParams, $contribution);
139
140 if ($isPaymentTransaction) {
141 // add qfKey so we can send to paypal
142 $form->_params['qfKey'] = $form->controller->_key;
143 if ($component == 'membership') {
144 $membershipResult = array(1 => $contribution);
145 return $membershipResult;
146 }
147 else {
148 if (!$isPayLater) {
149 if (is_object($payment)) {
150 // call postProcess hook before leaving
151 $form->postProcessHook();
152 // this does not return
153 $result = $payment->doTransferCheckout($form->_params, 'contribute');
154 }
155 else {
156 CRM_Core_Error::fatal($paymentObjError);
157 }
158 }
159 else {
160 // follow similar flow as IPN
161 // send the receipt mail
162 $form->set('params', $form->_params);
163 if ($contributionType->is_deductible) {
164 $form->assign('is_deductible', TRUE);
165 $form->set('is_deductible', TRUE);
166 }
167 if (isset($paymentParams['contribution_source'])) {
168 $form->_params['source'] = $paymentParams['contribution_source'];
169 }
170
171 // get the price set values for receipt.
172 if ($form->_priceSetId && $form->_lineItem) {
173 $form->_values['lineItem'] = $form->_lineItem;
174 $form->_values['priceSetID'] = $form->_priceSetId;
175 }
176
177 $form->_values['contribution_id'] = $contribution->id;
178 $form->_values['contribution_page_id'] = $contribution->contribution_page_id;
179
180 CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
181 $form->_values,
182 $contribution->is_test
183 );
184 return;
185 }
186 }
187 }
188 }
189 elseif ($form->_contributeMode == 'express') {
190 if ($form->_values['is_monetary'] && $form->_amount > 0.0) {
191 // determine if express + recurring and direct accordingly
192 if (isset($paymentParams['is_recur']) && $paymentParams['is_recur'] == 1) {
193 if (is_object($payment)) {
194 $result = $payment->createRecurringPayments($paymentParams);
195 }
196 else {
197 CRM_Core_Error::fatal($paymentObjError);
198 }
199 }
200 else {
201 if (is_object($payment)) {
202 $result = $payment->doExpressCheckout($paymentParams);
203 }
204 else {
205 CRM_Core_Error::fatal($paymentObjError);
206 }
207 }
208 }
209 }
210 elseif ($isPaymentTransaction) {
211 if (!empty($paymentParams['is_recur']) &&
212 $form->_contributeMode == 'direct'
213 ) {
214
215 // For recurring contribution, create Contribution Record first.
216 // Contribution ID, Recurring ID and Contact ID needed
217 // When we get a callback from the payment processor
218
219 $paymentParams['contactID'] = $contactID;
220
221 // Fix for CRM-14354. If the membership is recurring, don't create a
222 // civicrm_contribution_recur record for the additional contribution
223 // (i.e., the amount NOT associated with the membership). Temporarily
224 // cache the is_recur values so we can process the additional gift as a
225 // one-off payment.
226 if ($form->_membershipBlock['is_separate_payment']) {
227 $cachedFormValue = CRM_Utils_Array::value('is_recur', $form->_values);
228 unset($form->_values['is_recur']);
229 $cachedParamValue = CRM_Utils_Array::value('is_recur', $paymentParams);
230 unset($paymentParams['is_recur']);
231 }
232
233 $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution(
234 $form,
235 $paymentParams,
236 NULL,
237 $contactID,
238 $contributionType,
239 TRUE, TRUE,
240 $isTest,
241 $lineItems
242 );
243
244 // restore cached values (part of fix for CRM-14354)
245 if ($form->_membershipBlock['is_separate_payment']) {
246 $form->_values['is_recur'] = $cachedFormValue;
247 $paymentParams['is_recur'] = $cachedParamValue;
248 }
249
250 $paymentParams['contributionID'] = $contribution->id;
251 //CRM-15297 deprecate contributionTypeID
252 $paymentParams['financialTypeID'] = $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
253 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
254
255 if ($form->_values['is_recur'] && $contribution->contribution_recur_id) {
256 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
257 }
258 }
259 if (is_object($payment)) {
260 $result = $payment->doDirectPayment($paymentParams);
261 }
262 else {
263 CRM_Core_Error::fatal($paymentObjError);
264 }
265 }
266
267 if ($component == 'membership') {
268 $membershipResult = array();
269 }
270
271 if (is_a($result, 'CRM_Core_Error')) {
272 //make sure to cleanup db for recurring case.
273 //@todo this clean up has always been controversial as many orgs prefer to see failed transactions.
274 // most recent discussion has been that they should be retained and this could be altered
275 if (!empty($paymentParams['contributionID'])) {
276 CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']);
277 }
278 if (!empty($paymentParams['contributionRecurID'])) {
279 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
280 }
281
282 if ($component !== 'membership') {
283 CRM_Core_Error::displaySessionError($result);
284 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact',
285 "_qf_Main_display=true&qfKey={$form->_params['qfKey']}"
286 ));
287 }
288 $membershipResult[1] = $result;
289 }
290 elseif ($result || ($form->_amount == 0.0 && !$form->_params['is_pay_later'])) {
291 if ($result) {
292 $form->_params = array_merge($form->_params, $result);
293 }
294 $form->_params['receive_date'] = $now;
295 $form->set('params', $form->_params);
296 $form->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
297 $form->assign('receive_date',
298 CRM_Utils_Date::mysqlToIso($form->_params['receive_date'])
299 );
300
301 // result has all the stuff we need
302 // lets archive it to a financial transaction
303 //@todo - this is done in 2 places - can't we just do it once straight after retrieving contribution type -
304 // when would this be a bad thing?
305 if ($contributionType->is_deductible) {
306 $form->assign('is_deductible', TRUE);
307 $form->set('is_deductible', TRUE);
308 }
309
310 if (isset($paymentParams['contribution_source'])) {
311 $form->_params['source'] = $paymentParams['contribution_source'];
312 }
313
314 // check if pending was set to true by payment processor
315 $pending = FALSE;
316 if (!empty($form->_params['contribution_status_pending'])) {
317 $pending = TRUE;
318 }
319 if (!(!empty($paymentParams['is_recur']) && $form->_contributeMode == 'direct')) {
320 $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($form,
321 $form->_params, $result,
322 $contactID, $contributionType,
323 $pending, TRUE,
324 $isTest,
325 $lineItems
326 );
327 }
328 $form->postProcessPremium($premiumParams, $contribution);
329 if (is_array($result) && !empty($result['trxn_id'])) {
330 $contribution->trxn_id = $result['trxn_id'];
331 }
332 $membershipResult[1] = $contribution;
333 }
334
335 if ($component == 'membership') {
336 return $membershipResult;
337 }
338
339 //Do not send an email if Recurring contribution is done via Direct Mode
340 //We will send email once the IPN is received.
341 if (!empty($paymentParams['is_recur']) && $form->_contributeMode == 'direct') {
342 return TRUE;
343 }
344
345 // get the price set values for receipt.
346 if ($form->_priceSetId && $form->_lineItem) {
347 $form->_values['lineItem'] = $form->_lineItem;
348 $form->_values['priceSetID'] = $form->_priceSetId;
349 }
350
351 // finally send an email receipt
352 if ($contribution) {
353 $form->_values['contribution_id'] = $contribution->id;
354 CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
355 $form->_values, $contribution->is_test,
356 FALSE, $fieldTypes
357 );
358 }
359 }
360
361 /**
362 * Is a payment being made.
363 * Note that setting is_monetary on the form is somewhat legacy and the behaviour around this setting is confusing. It would be preferable
364 * to look for the amount only (assuming this cannot refer to payment in goats or other non-monetary currency
365 * @param CRM_Core_Form $form
366 *
367 * @return bool
368 */
369 static protected function isPaymentTransaction($form) {
370 if (!empty($form->_values['is_monetary']) && $form->_amount >= 0.0) {
371 return TRUE;
372 }
373 return FALSE;
374
375 }
376
377 /**
378 * Get the contribution details by month
379 * of the year
380 *
381 * @param int $param
382 * Year.
383 *
384 * @return array
385 * associated array
386 *
387 */
388 public static function contributionChartMonthly($param) {
389 if ($param) {
390 $param = array(1 => array($param, 'Integer'));
391 }
392 else {
393 $param = date("Y");
394 $param = array(1 => array($param, 'Integer'));
395 }
396
397 $query = "
398 SELECT sum(contrib.total_amount) AS ctAmt,
399 MONTH( contrib.receive_date) AS contribMonth
400 FROM civicrm_contribution AS contrib
401 INNER JOIN civicrm_contact AS contact ON ( contact.id = contrib.contact_id )
402 WHERE contrib.contact_id = contact.id
403 AND ( contrib.is_test = 0 OR contrib.is_test IS NULL )
404 AND contrib.contribution_status_id = 1
405 AND date_format(contrib.receive_date,'%Y') = %1
406 AND contact.is_deleted = 0
407 GROUP BY contribMonth
408 ORDER BY month(contrib.receive_date)";
409
410 $dao = CRM_Core_DAO::executeQuery($query, $param);
411
412 $params = NULL;
413 while ($dao->fetch()) {
414 if ($dao->contribMonth) {
415 $params['By Month'][$dao->contribMonth] = $dao->ctAmt;
416 }
417 }
418 return $params;
419 }
420
421 /**
422 * Get the contribution details by year
423 *
424 * @return array
425 * associated array
426 *
427 */
428 public static function contributionChartYearly() {
429 $config = CRM_Core_Config::singleton();
430 $yearClause = "year(contrib.receive_date) as contribYear";
431 if (!empty($config->fiscalYearStart) && ($config->fiscalYearStart['M'] != 1 || $config->fiscalYearStart['d'] != 1)) {
432 $yearClause = "CASE
433 WHEN (MONTH(contrib.receive_date)>= " . $config->fiscalYearStart['M'] . "
434 && DAYOFMONTH(contrib.receive_date)>= " . $config->fiscalYearStart['d'] . " )
435 THEN
436 concat(YEAR(contrib.receive_date), '-',YEAR(contrib.receive_date)+1)
437 ELSE
438 concat(YEAR(contrib.receive_date)-1,'-', YEAR(contrib.receive_date))
439 END AS contribYear";
440 }
441
442 $query = "
443 SELECT sum(contrib.total_amount) AS ctAmt,
444 {$yearClause}
445 FROM civicrm_contribution AS contrib
446 INNER JOIN civicrm_contact contact ON ( contact.id = contrib.contact_id )
447 WHERE ( contrib.is_test = 0 OR contrib.is_test IS NULL )
448 AND contrib.contribution_status_id = 1
449 AND contact.is_deleted = 0
450 GROUP BY contribYear
451 ORDER BY contribYear";
452 $dao = CRM_Core_DAO::executeQuery($query);
453
454 $params = NULL;
455 while ($dao->fetch()) {
456 if (!empty($dao->contribYear)) {
457 $params['By Year'][$dao->contribYear] = $dao->ctAmt;
458 }
459 }
460 return $params;
461 }
462
463 /**
464 * @param array $params
465 * @param int $contactID
466 * @param $mail
467 */
468 public static function createCMSUser(&$params, $contactID, $mail) {
469 // lets ensure we only create one CMS user
470 static $created = FALSE;
471
472 if ($created) {
473 return;
474 }
475 $created = TRUE;
476
477 if (!empty($params['cms_create_account'])) {
478 $params['contactID'] = $contactID;
479 if (!CRM_Core_BAO_CMSUser::create($params, $mail)) {
480 CRM_Core_Error::statusBounce(ts('Your profile is not saved and Account is not created.'));
481 }
482 }
483 }
484
485 /**
486 * @param array $params
487 * @param string $type
488 *
489 * @return bool
490 */
491 public static function _fillCommonParams(&$params, $type = 'paypal') {
492 if (array_key_exists('transaction', $params)) {
493 $transaction = &$params['transaction'];
494 }
495 else {
496 $transaction = &$params;
497 }
498
499 $params['contact_type'] = 'Individual';
500
501 $billingLocTypeId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', 'Billing', 'id', 'name');
502 if (!$billingLocTypeId) {
503 $billingLocTypeId = 1;
504 }
505 if (!CRM_Utils_System::isNull($params['address'])) {
506 $params['address'][1]['is_primary'] = 1;
507 $params['address'][1]['location_type_id'] = $billingLocTypeId;
508 }
509 if (!CRM_Utils_System::isNull($params['email'])) {
510 $params['email'] = array(
511 1 => array(
512 'email' => $params['email'],
513 'location_type_id' => $billingLocTypeId,
514 ),
515 );
516 }
517
518 if (isset($transaction['trxn_id'])) {
519 // set error message if transaction has already been processed.
520 $contribution = new CRM_Contribute_DAO_Contribution();
521 $contribution->trxn_id = $transaction['trxn_id'];
522 if ($contribution->find(TRUE)) {
523 $params['error'][] = ts('transaction already processed.');
524 }
525 }
526 else {
527 // generate a new transaction id, if not already exist
528 $transaction['trxn_id'] = md5(uniqid(rand(), TRUE));
529 }
530
531 if (!isset($transaction['financial_type_id'])) {
532 $contributionTypes = array_keys(CRM_Contribute_PseudoConstant::financialType());
533 $transaction['financial_type_id'] = $contributionTypes[0];
534 }
535
536 if (($type == 'paypal') && (!isset($transaction['net_amount']))) {
537 $transaction['net_amount'] = $transaction['total_amount'] - CRM_Utils_Array::value('fee_amount', $transaction, 0);
538 }
539
540 if (!isset($transaction['invoice_id'])) {
541 $transaction['invoice_id'] = $transaction['trxn_id'];
542 }
543
544 $source = ts('ContributionProcessor: %1 API',
545 array(1 => ucfirst($type))
546 );
547 if (isset($transaction['source'])) {
548 $transaction['source'] = $source . ':: ' . $transaction['source'];
549 }
550 else {
551 $transaction['source'] = $source;
552 }
553
554 return TRUE;
555 }
556
557 /**
558 * @param array $apiParams
559 * @param $mapper
560 * @param string $type
561 * @param bool $category
562 *
563 * @return array
564 */
565 public static function formatAPIParams($apiParams, $mapper, $type = 'paypal', $category = TRUE) {
566 $type = strtolower($type);
567
568 if (!in_array($type, array(
569 'paypal',
570 'google',
571 'csv',
572 ))
573 ) {
574 // return the params as is
575 return $apiParams;
576 }
577 $params = $transaction = array();
578
579 if ($type == 'paypal') {
580 foreach ($apiParams as $detail => $val) {
581 if (isset($mapper['contact'][$detail])) {
582 $params[$mapper['contact'][$detail]] = $val;
583 }
584 elseif (isset($mapper['location'][$detail])) {
585 $params['address'][1][$mapper['location'][$detail]] = $val;
586 }
587 elseif (isset($mapper['transaction'][$detail])) {
588 switch ($detail) {
589 case 'l_period2':
590 // Sadly, PayPal seems to send two distinct data elements in a single field,
591 // so we break them out here. This is somewhat ugly and tragic.
592 $freqUnits = array(
593 'D' => 'day',
594 'W' => 'week',
595 'M' => 'month',
596 'Y' => 'year',
597 );
598 list($frequency_interval, $frequency_unit) = explode(' ', $val);
599 $transaction['frequency_interval'] = $frequency_interval;
600 $transaction['frequency_unit'] = $freqUnits[$frequency_unit];
601 break;
602
603 case 'subscriptiondate':
604 case 'timestamp':
605 // PayPal dates are in ISO-8601 format. We need a format that
606 // MySQL likes
607 $unix_timestamp = strtotime($val);
608 $transaction[$mapper['transaction'][$detail]] = date('YmdHis', $unix_timestamp);
609 break;
610
611 case 'note':
612 case 'custom':
613 case 'l_number0':
614 if ($val) {
615 $val = "[PayPal_field:{$detail}] {$val}";
616 $transaction[$mapper['transaction'][$detail]] = !empty($transaction[$mapper['transaction'][$detail]]) ? $transaction[$mapper['transaction'][$detail]] . " <br/> " . $val : $val;
617 }
618 break;
619
620 default:
621 $transaction[$mapper['transaction'][$detail]] = $val;
622 }
623 }
624 }
625
626 if (!empty($transaction) && $category) {
627 $params['transaction'] = $transaction;
628 }
629 else {
630 $params += $transaction;
631 }
632
633 self::_fillCommonParams($params, $type);
634
635 return $params;
636 }
637
638 if ($type == 'csv') {
639 $header = $apiParams['header'];
640 unset($apiParams['header']);
641 foreach ($apiParams as $key => $val) {
642 if (isset($mapper['contact'][$header[$key]])) {
643 $params[$mapper['contact'][$header[$key]]] = $val;
644 }
645 elseif (isset($mapper['location'][$header[$key]])) {
646 $params['address'][1][$mapper['location'][$header[$key]]] = $val;
647 }
648 elseif (isset($mapper['transaction'][$header[$key]])) {
649 $transaction[$mapper['transaction'][$header[$key]]] = $val;
650 }
651 else {
652 $params[$header[$key]] = $val;
653 }
654 }
655
656 if (!empty($transaction) && $category) {
657 $params['transaction'] = $transaction;
658 }
659 else {
660 $params += $transaction;
661 }
662
663 self::_fillCommonParams($params, $type);
664
665 return $params;
666 }
667
668 if ($type == 'google') {
669 // return if response smell invalid
670 if (!array_key_exists('risk-information-notification', $apiParams[1][$apiParams[0]]['notifications'])) {
671 return FALSE;
672 }
673 $riskInfo = &$apiParams[1][$apiParams[0]]['notifications']['risk-information-notification'];
674
675 if (array_key_exists('new-order-notification', $apiParams[1][$apiParams[0]]['notifications'])) {
676 $newOrder = &$apiParams[1][$apiParams[0]]['notifications']['new-order-notification'];
677 }
678
679 if ($riskInfo['google-order-number']['VALUE'] == $apiParams[2]['google-order-number']['VALUE']) {
680 foreach ($riskInfo['risk-information']['billing-address'] as $field => $info) {
681 if (!empty($mapper['location'][$field])) {
682 $params['address'][1][$mapper['location'][$field]] = $info['VALUE'];
683 }
684 elseif (!empty($mapper['contact'][$field])) {
685 if ($newOrder && !empty($newOrder['buyer-billing-address']['structured-name'])) {
686 foreach ($newOrder['buyer-billing-address']['structured-name'] as $namePart => $nameValue) {
687 $params[$mapper['contact'][$namePart]] = $nameValue['VALUE'];
688 }
689 }
690 else {
691 $params[$mapper['contact'][$field]] = $info['VALUE'];
692 }
693 }
694 elseif (!empty($mapper['transaction'][$field])) {
695 $transaction[$mapper['transaction'][$field]] = $info['VALUE'];
696 }
697 }
698
699 // Response is an huge array. Lets pickup only those which we ineterested in
700 // using a local mapper, rather than traversing the entire array.
701 $localMapper = array(
702 'google-order-number' => $riskInfo['google-order-number']['VALUE'],
703 'total-charge-amount' => $apiParams[2]['total-charge-amount']['VALUE'],
704 'currency' => $apiParams[2]['total-charge-amount']['currency'],
705 'item-name' => $newOrder['shopping-cart']['items']['item']['item-name']['VALUE'],
706 'timestamp' => $apiParams[2]['timestamp']['VALUE'],
707 );
708 if (array_key_exists('latest-charge-fee', $apiParams[2])) {
709 $localMapper['latest-charge-fee'] = $apiParams[2]['latest-charge-fee']['total']['VALUE'];
710 $localMapper['net-amount'] = $localMapper['total-charge-amount'] - $localMapper['latest-charge-fee'];
711 }
712
713 // This is a subscription (recurring) donation.
714 if (array_key_exists('subscription', $newOrder['shopping-cart']['items']['item'])) {
715 $subscription = $newOrder['shopping-cart']['items']['item']['subscription'];
716 $localMapper['amount'] = $newOrder['order-total']['VALUE'];
717 $localMapper['times'] = $subscription['payments']['subscription-payment']['times'];
718 // Convert Google's period to one compatible with the CiviCRM db field.
719 $freqUnits = array(
720 'DAILY' => 'day',
721 'WEEKLY' => 'week',
722 'MONHTLY' => 'month',
723 'YEARLY' => 'year',
724 );
725 $localMapper['period'] = $freqUnits[$subscription['period']];
726 // Unlike PayPal, Google has no concept of freq. interval, it is always 1.
727 $localMapper['frequency_interval'] = '1';
728 // Google Checkout dates are in ISO-8601 format. We need a format that
729 // MySQL likes
730 $unix_timestamp = strtotime($localMapper['timestamp']);
731 $mysql_date = date('YmdHis', $unix_timestamp);
732 $localMapper['modified_date'] = $mysql_date;
733 $localMapper['start_date'] = $mysql_date;
734 // This is PayPal's nomenclature, but just use it for Google as well since
735 // we act on the value of trxn_type in processAPIContribution().
736 $localMapper['trxn_type'] = 'subscrpayment';
737 }
738
739 foreach ($localMapper as $localKey => $localVal) {
740 if (!empty($mapper['transaction'][$localKey])) {
741 $transaction[$mapper['transaction'][$localKey]] = $localVal;
742 }
743 }
744
745 if (empty($params) && empty($transaction)) {
746 continue;
747 }
748
749 if (!empty($transaction) && $category) {
750 $params['transaction'] = $transaction;
751 }
752 else {
753 $params += $transaction;
754 }
755
756 self::_fillCommonParams($params, $type);
757 }
758 return $params;
759 }
760 }
761
762 /**
763 * @param array $params
764 *
765 * @return bool
766 */
767 public static function processAPIContribution($params) {
768 if (empty($params) || array_key_exists('error', $params)) {
769 return FALSE;
770 }
771
772 // add contact using dedupe rule
773 $dedupeParams = CRM_Dedupe_Finder::formatParams($params, 'Individual');
774 $dedupeParams['check_permission'] = FALSE;
775 $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
776 // if we find more than one contact, use the first one
777 if (!empty($dupeIds[0])) {
778 $params['contact_id'] = $dupeIds[0];
779 }
780 $contact = CRM_Contact_BAO_Contact::create($params);
781 if (!$contact->id) {
782 return FALSE;
783 }
784
785 // only pass transaction params to contribution::create, if available
786 if (array_key_exists('transaction', $params)) {
787 $params = $params['transaction'];
788 $params['contact_id'] = $contact->id;
789 }
790
791 // handle contribution custom data
792 $customFields = CRM_Core_BAO_CustomField::getFields('Contribution',
793 FALSE,
794 FALSE,
795 CRM_Utils_Array::value('financial_type_id',
796 $params
797 )
798 );
799 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
800 $customFields,
801 CRM_Utils_Array::value('id', $params, NULL),
802 'Contribution'
803 );
804 // create contribution
805
806 // if this is a recurring contribution then process it first
807 if ($params['trxn_type'] == 'subscrpayment') {
808 // see if a recurring record already exists
809 $recurring = new CRM_Contribute_BAO_ContributionRecur();
810 $recurring->processor_id = $params['processor_id'];
811 if (!$recurring->find(TRUE)) {
812 $recurring = new CRM_Contribute_BAO_ContributionRecur();
813 $recurring->invoice_id = $params['invoice_id'];
814 $recurring->find(TRUE);
815 }
816
817 // This is the same thing the CiviCRM IPN handler does to handle
818 // subsequent recurring payments to avoid duplicate contribution
819 // errors due to invoice ID. See:
820 // ./CRM/Core/Payment/PayPalIPN.php:200
821 if ($recurring->id) {
822 $params['invoice_id'] = md5(uniqid(rand(), TRUE));
823 }
824
825 $recurring->copyValues($params);
826 $recurring->save();
827 if (is_a($recurring, 'CRM_Core_Error')) {
828 return FALSE;
829 }
830 else {
831 $params['contribution_recur_id'] = $recurring->id;
832 }
833 }
834
835 $contribution = &CRM_Contribute_BAO_Contribution::create($params,
836 CRM_Core_DAO::$_nullArray
837 );
838 if (!$contribution->id) {
839 return FALSE;
840 }
841
842 return TRUE;
843 }
844
845 /**
846 * @param int $contactID
847 *
848 * @return mixed
849 */
850 public static function getFirstLastDetails($contactID) {
851 static $_cache;
852
853 if (!$_cache) {
854 $_cache = array();
855 }
856
857 if (!isset($_cache[$contactID])) {
858 $sql = "
859 SELECT total_amount, receive_date
860 FROM civicrm_contribution c
861 WHERE contact_id = %1
862 ORDER BY receive_date ASC
863 LIMIT 1
864 ";
865 $params = array(1 => array($contactID, 'Integer'));
866
867 $dao = CRM_Core_DAO::executeQuery($sql, $params);
868 $details = array(
869 'first' => NULL,
870 'last' => NULL,
871 );
872 if ($dao->fetch()) {
873 $details['first'] = array(
874 'total_amount' => $dao->total_amount,
875 'receive_date' => $dao->receive_date,
876 );
877 }
878
879 // flip asc and desc to get the last query
880 $sql = str_replace('ASC', 'DESC', $sql);
881 $dao = CRM_Core_DAO::executeQuery($sql, $params);
882 if ($dao->fetch()) {
883 $details['last'] = array(
884 'total_amount' => $dao->total_amount,
885 'receive_date' => $dao->receive_date,
886 );
887 }
888
889 $_cache[$contactID] = $details;
890 }
891 return $_cache[$contactID];
892 }
893
894 /**
895 * Calculate the tax amount based on given tax rate.
896 *
897 * @param float $amount
898 * Amount of field.
899 * @param float $taxRate
900 * Tax rate of selected financial account for field.
901 *
902 * @return array
903 * array of tax amount
904 *
905 */
906 public static function calculateTaxAmount($amount, $taxRate) {
907 $taxAmount = array();
908 $taxAmount['tax_amount'] = ($taxRate / 100) * CRM_Utils_Rule::cleanMoney($amount);
909
910 return $taxAmount;
911 }
912
913 }