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