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