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