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