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