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