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