CRM-15296
[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
334 $membershipResult[1] = $contribution;
335 }
336
337 if ($component == 'membership') {
338 return $membershipResult;
339 }
340
341 //Do not send an email if Recurring contribution is done via Direct Mode
342 //We will send email once the IPN is received.
343 if (!empty($paymentParams['is_recur']) && $form->_contributeMode == 'direct') {
344 return TRUE;
345 }
346
347 // get the price set values for receipt.
348 if ($form->_priceSetId && $form->_lineItem) {
349 $form->_values['lineItem'] = $form->_lineItem;
350 $form->_values['priceSetID'] = $form->_priceSetId;
351 }
352
353 // finally send an email receipt
354 if ($contribution) {
355 $form->_values['contribution_id'] = $contribution->id;
356 CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
357 $form->_values, $contribution->is_test,
358 FALSE, $fieldTypes
359 );
360 }
361 }
362
363 /**
364 * Function to get the contribution details by month
365 * of the year
366 *
367 * @param int $param year
368 *
369 * @return array associated array
370 *
371 * @static
372 * @access public
373 */
374 static function contributionChartMonthly($param) {
375 if ($param) {
376 $param = array(1 => array($param, 'Integer'));
377 }
378 else {
379 $param = date("Y");
380 $param = array(1 => array($param, 'Integer'));
381 }
382
383 $query = "
384 SELECT sum(contrib.total_amount) AS ctAmt,
385 MONTH( contrib.receive_date) AS contribMonth
386 FROM civicrm_contribution AS contrib
387 INNER JOIN civicrm_contact AS contact ON ( contact.id = contrib.contact_id )
388 WHERE contrib.contact_id = contact.id
389 AND ( contrib.is_test = 0 OR contrib.is_test IS NULL )
390 AND contrib.contribution_status_id = 1
391 AND date_format(contrib.receive_date,'%Y') = %1
392 AND contact.is_deleted = 0
393 GROUP BY contribMonth
394 ORDER BY month(contrib.receive_date)";
395
396 $dao = CRM_Core_DAO::executeQuery($query, $param);
397
398 $params = NULL;
399 while ($dao->fetch()) {
400 if ($dao->contribMonth) {
401 $params['By Month'][$dao->contribMonth] = $dao->ctAmt;
402 }
403 }
404 return $params;
405 }
406
407 /**
408 * Function to get the contribution details by year
409 *
410 * @return array associated array
411 *
412 * @static
413 * @access public
414 */
415 static function contributionChartYearly() {
416 $config = CRM_Core_Config::singleton();
417 $yearClause = "year(contrib.receive_date) as contribYear";
418 if (!empty($config->fiscalYearStart) && ($config->fiscalYearStart['M'] != 1 || $config->fiscalYearStart['d'] != 1)) {
419 $yearClause = "CASE
420 WHEN (MONTH(contrib.receive_date)>= " . $config->fiscalYearStart['M'] . "
421 && DAYOFMONTH(contrib.receive_date)>= " . $config->fiscalYearStart['d'] . " )
422 THEN
423 concat(YEAR(contrib.receive_date), '-',YEAR(contrib.receive_date)+1)
424 ELSE
425 concat(YEAR(contrib.receive_date)-1,'-', YEAR(contrib.receive_date))
426 END AS contribYear";
427 }
428
429 $query = "
430 SELECT sum(contrib.total_amount) AS ctAmt,
431 {$yearClause}
432 FROM civicrm_contribution AS contrib
433 INNER JOIN civicrm_contact contact ON ( contact.id = contrib.contact_id )
434 WHERE ( contrib.is_test = 0 OR contrib.is_test IS NULL )
435 AND contrib.contribution_status_id = 1
436 AND contact.is_deleted = 0
437 GROUP BY contribYear
438 ORDER BY contribYear";
439 $dao = CRM_Core_DAO::executeQuery($query);
440
441 $params = NULL;
442 while ($dao->fetch()) {
443 if (!empty($dao->contribYear)) {
444 $params['By Year'][$dao->contribYear] = $dao->ctAmt;
445 }
446 }
447 return $params;
448 }
449
450 /**
451 * @param $params
452 * @param $contactID
453 * @param $mail
454 */
455 static function createCMSUser(&$params, $contactID, $mail) {
456 // lets ensure we only create one CMS user
457 static $created = FALSE;
458
459 if ($created) {
460 return;
461 }
462 $created = TRUE;
463
464 if (!empty($params['cms_create_account'])) {
465 $params['contactID'] = $contactID;
466 if (!CRM_Core_BAO_CMSUser::create($params, $mail)) {
467 CRM_Core_Error::statusBounce(ts('Your profile is not saved and Account is not created.'));
468 }
469 }
470 }
471
472 /**
473 * @param $params
474 * @param string $type
475 *
476 * @return bool
477 */
478 static function _fillCommonParams(&$params, $type = 'paypal') {
479 if (array_key_exists('transaction', $params)) {
480 $transaction = &$params['transaction'];
481 }
482 else {
483 $transaction = &$params;
484 }
485
486 $params['contact_type'] = 'Individual';
487
488 $billingLocTypeId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', 'Billing', 'id', 'name');
489 if (!$billingLocTypeId) {
490 $billingLocTypeId = 1;
491 }
492 if (!CRM_Utils_System::isNull($params['address'])) {
493 $params['address'][1]['is_primary'] = 1;
494 $params['address'][1]['location_type_id'] = $billingLocTypeId;
495 }
496 if (!CRM_Utils_System::isNull($params['email'])) {
497 $params['email'] = array(
498 1 => array('email' => $params['email'],
499 'location_type_id' => $billingLocTypeId,
500 ));
501 }
502
503 if (isset($transaction['trxn_id'])) {
504 // set error message if transaction has already been processed.
505 $contribution = new CRM_Contribute_DAO_Contribution();
506 $contribution->trxn_id = $transaction['trxn_id'];
507 if ($contribution->find(TRUE)) {
508 $params['error'][] = ts('transaction already processed.');
509 }
510 }
511 else {
512 // generate a new transaction id, if not already exist
513 $transaction['trxn_id'] = md5(uniqid(rand(), TRUE));
514 }
515
516 if (!isset( $transaction['financial_type_id'])) {
517 $contributionTypes = array_keys(CRM_Contribute_PseudoConstant::financialType());
518 $transaction['financial_type_id'] = $contributionTypes[0];
519 }
520
521 if (($type == 'paypal') && (!isset($transaction['net_amount']))) {
522 $transaction['net_amount'] = $transaction['total_amount'] - CRM_Utils_Array::value('fee_amount', $transaction, 0);
523 }
524
525 if (!isset($transaction['invoice_id'])) {
526 $transaction['invoice_id'] = $transaction['trxn_id'];
527 }
528
529 $source = ts('ContributionProcessor: %1 API',
530 array(1 => ucfirst($type))
531 );
532 if (isset($transaction['source'])) {
533 $transaction['source'] = $source . ':: ' . $transaction['source'];
534 }
535 else {
536 $transaction['source'] = $source;
537 }
538
539 return TRUE;
540 }
541
542 /**
543 * @param $apiParams
544 * @param $mapper
545 * @param string $type
546 * @param bool $category
547 *
548 * @return array
549 */
550 static function formatAPIParams($apiParams, $mapper, $type = 'paypal', $category = TRUE) {
551 $type = strtolower($type);
552
553 if (!in_array($type, array(
554 'paypal', 'google', 'csv'))) {
555 // return the params as is
556 return $apiParams;
557 }
558 $params = $transaction = array();
559
560 if ($type == 'paypal') {
561 foreach ($apiParams as $detail => $val) {
562 if (isset($mapper['contact'][$detail])) {
563 $params[$mapper['contact'][$detail]] = $val;
564 }
565 elseif (isset($mapper['location'][$detail])) {
566 $params['address'][1][$mapper['location'][$detail]] = $val;
567 }
568 elseif (isset($mapper['transaction'][$detail])) {
569 switch ($detail) {
570 case 'l_period2':
571 // Sadly, PayPal seems to send two distinct data elements in a single field,
572 // so we break them out here. This is somewhat ugly and tragic.
573 $freqUnits = array(
574 'D' => 'day',
575 'W' => 'week',
576 'M' => 'month',
577 'Y' => 'year',
578 );
579 list($frequency_interval, $frequency_unit) = explode(' ', $val);
580 $transaction['frequency_interval'] = $frequency_interval;
581 $transaction['frequency_unit'] = $freqUnits[$frequency_unit];
582 break;
583
584 case 'subscriptiondate':
585 case 'timestamp':
586 // PayPal dates are in ISO-8601 format. We need a format that
587 // MySQL likes
588 $unix_timestamp = strtotime($val);
589 $transaction[$mapper['transaction'][$detail]] = date('YmdHis', $unix_timestamp);
590 break;
591
592 case 'note':
593 case 'custom':
594 case 'l_number0':
595 if ($val) {
596 $val = "[PayPal_field:{$detail}] {$val}";
597 $transaction[$mapper['transaction'][$detail]] = !empty($transaction[$mapper['transaction'][$detail]]) ? $transaction[$mapper['transaction'][$detail]] . " <br/> " . $val : $val;
598 }
599 break;
600
601 default:
602 $transaction[$mapper['transaction'][$detail]] = $val;
603 }
604 }
605 }
606
607 if (!empty($transaction) && $category) {
608 $params['transaction'] = $transaction;
609 }
610 else {
611 $params += $transaction;
612 }
613
614 self::_fillCommonParams($params, $type);
615
616 return $params;
617 }
618
619 if ($type == 'csv') {
620 $header = $apiParams['header'];
621 unset($apiParams['header']);
622 foreach ($apiParams as $key => $val) {
623 if (isset($mapper['contact'][$header[$key]])) {
624 $params[$mapper['contact'][$header[$key]]] = $val;
625 }
626 elseif (isset($mapper['location'][$header[$key]])) {
627 $params['address'][1][$mapper['location'][$header[$key]]] = $val;
628 }
629 elseif (isset($mapper['transaction'][$header[$key]])) {
630 $transaction[$mapper['transaction'][$header[$key]]] = $val;
631 }
632 else {
633 $params[$header[$key]] = $val;
634 }
635 }
636
637 if (!empty($transaction) && $category) {
638 $params['transaction'] = $transaction;
639 }
640 else {
641 $params += $transaction;
642 }
643
644 self::_fillCommonParams($params, $type);
645
646 return $params;
647 }
648
649 if ($type == 'google') {
650 // return if response smell invalid
651 if (!array_key_exists('risk-information-notification', $apiParams[1][$apiParams[0]]['notifications'])) {
652 return FALSE;
653 }
654 $riskInfo = &$apiParams[1][$apiParams[0]]['notifications']['risk-information-notification'];
655
656 if (array_key_exists('new-order-notification', $apiParams[1][$apiParams[0]]['notifications'])) {
657 $newOrder = &$apiParams[1][$apiParams[0]]['notifications']['new-order-notification'];
658 }
659
660 if ($riskInfo['google-order-number']['VALUE'] == $apiParams[2]['google-order-number']['VALUE']) {
661 foreach ($riskInfo['risk-information']['billing-address'] as $field => $info) {
662 if (!empty($mapper['location'][$field])) {
663 $params['address'][1][$mapper['location'][$field]] = $info['VALUE'];
664 }
665 elseif (!empty($mapper['contact'][$field])) {
666 if ($newOrder && !empty($newOrder['buyer-billing-address']['structured-name'])) {
667 foreach ($newOrder['buyer-billing-address']['structured-name'] as $namePart => $nameValue) {
668 $params[$mapper['contact'][$namePart]] = $nameValue['VALUE'];
669 }
670 }
671 else {
672 $params[$mapper['contact'][$field]] = $info['VALUE'];
673 }
674 }
675 elseif (!empty($mapper['transaction'][$field])) {
676 $transaction[$mapper['transaction'][$field]] = $info['VALUE'];
677 }
678 }
679
680 // Response is an huge array. Lets pickup only those which we ineterested in
681 // using a local mapper, rather than traversing the entire array.
682 $localMapper = array(
683 'google-order-number' => $riskInfo['google-order-number']['VALUE'],
684 'total-charge-amount' => $apiParams[2]['total-charge-amount']['VALUE'],
685 'currency' => $apiParams[2]['total-charge-amount']['currency'],
686 'item-name' => $newOrder['shopping-cart']['items']['item']['item-name']['VALUE'],
687 'timestamp' => $apiParams[2]['timestamp']['VALUE'],
688 );
689 if (array_key_exists('latest-charge-fee', $apiParams[2])) {
690 $localMapper['latest-charge-fee'] = $apiParams[2]['latest-charge-fee']['total']['VALUE'];
691 $localMapper['net-amount'] = $localMapper['total-charge-amount'] - $localMapper['latest-charge-fee'];
692 }
693
694 // This is a subscription (recurring) donation.
695 if (array_key_exists('subscription', $newOrder['shopping-cart']['items']['item'])) {
696 $subscription = $newOrder['shopping-cart']['items']['item']['subscription'];
697 $localMapper['amount'] = $newOrder['order-total']['VALUE'];
698 $localMapper['times'] = $subscription['payments']['subscription-payment']['times'];
699 // Convert Google's period to one compatible with the CiviCRM db field.
700 $freqUnits = array(
701 'DAILY' => 'day',
702 'WEEKLY' => 'week',
703 'MONHTLY' => 'month',
704 'YEARLY' => 'year',
705 );
706 $localMapper['period'] = $freqUnits[$subscription['period']];
707 // Unlike PayPal, Google has no concept of freq. interval, it is always 1.
708 $localMapper['frequency_interval'] = '1';
709 // Google Checkout dates are in ISO-8601 format. We need a format that
710 // MySQL likes
711 $unix_timestamp = strtotime($localMapper['timestamp']);
712 $mysql_date = date('YmdHis', $unix_timestamp);
713 $localMapper['modified_date'] = $mysql_date;
714 $localMapper['start_date'] = $mysql_date;
715 // This is PayPal's nomenclature, but just use it for Google as well since
716 // we act on the value of trxn_type in processAPIContribution().
717 $localMapper['trxn_type'] = 'subscrpayment';
718 }
719
720 foreach ($localMapper as $localKey => $localVal) {
721 if (!empty($mapper['transaction'][$localKey])) {
722 $transaction[$mapper['transaction'][$localKey]] = $localVal;
723 }
724 }
725
726 if (empty($params) && empty($transaction)) {
727 continue;
728 }
729
730 if (!empty($transaction) && $category) {
731 $params['transaction'] = $transaction;
732 }
733 else {
734 $params += $transaction;
735 }
736
737 self::_fillCommonParams($params, $type);
738 }
739 return $params;
740 }
741 }
742
743 /**
744 * @param $params
745 *
746 * @return bool
747 */
748 static function processAPIContribution($params) {
749 if (empty($params) || array_key_exists('error', $params)) {
750 return FALSE;
751 }
752
753 // add contact using dedupe rule
754 $dedupeParams = CRM_Dedupe_Finder::formatParams($params, 'Individual');
755 $dedupeParams['check_permission'] = FALSE;
756 $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
757 // if we find more than one contact, use the first one
758 if (!empty($dupeIds[0])) {
759 $params['contact_id'] = $dupeIds[0];
760 }
761 $contact = CRM_Contact_BAO_Contact::create($params);
762 if (!$contact->id) {
763 return FALSE;
764 }
765
766 // only pass transaction params to contribution::create, if available
767 if (array_key_exists('transaction', $params)) {
768 $params = $params['transaction'];
769 $params['contact_id'] = $contact->id;
770 }
771
772 // handle contribution custom data
773 $customFields = CRM_Core_BAO_CustomField::getFields('Contribution',
774 FALSE,
775 FALSE,
776 CRM_Utils_Array::value('financial_type_id',
777 $params
778 )
779 );
780 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
781 $customFields,
782 CRM_Utils_Array::value('id', $params, NULL),
783 'Contribution'
784 );
785 // create contribution
786
787 // if this is a recurring contribution then process it first
788 if ($params['trxn_type'] == 'subscrpayment') {
789 // see if a recurring record already exists
790 $recurring = new CRM_Contribute_BAO_ContributionRecur;
791 $recurring->processor_id = $params['processor_id'];
792 if (!$recurring->find(TRUE)) {
793 $recurring = new CRM_Contribute_BAO_ContributionRecur;
794 $recurring->invoice_id = $params['invoice_id'];
795 $recurring->find(TRUE);
796 }
797
798 // This is the same thing the CiviCRM IPN handler does to handle
799 // subsequent recurring payments to avoid duplicate contribution
800 // errors due to invoice ID. See:
801 // ./CRM/Core/Payment/PayPalIPN.php:200
802 if ($recurring->id) {
803 $params['invoice_id'] = md5(uniqid(rand(), TRUE));
804 }
805
806 $recurring->copyValues($params);
807 $recurring->save();
808 if (is_a($recurring, 'CRM_Core_Error')) {
809 return FALSE;
810 }
811 else {
812 $params['contribution_recur_id'] = $recurring->id;
813 }
814 }
815
816 $contribution = &CRM_Contribute_BAO_Contribution::create($params,
817 CRM_Core_DAO::$_nullArray
818 );
819 if (!$contribution->id) {
820 return FALSE;
821 }
822
823 return TRUE;
824 }
825
826 /**
827 * @param $contactID
828 *
829 * @return mixed
830 */
831 static function getFirstLastDetails($contactID) {
832 static $_cache;
833
834 if (!$_cache) {
835 $_cache = array();
836 }
837
838 if (!isset($_cache[$contactID])) {
839 $sql = "
840 SELECT total_amount, receive_date
841 FROM civicrm_contribution c
842 WHERE contact_id = %1
843 ORDER BY receive_date ASC
844 LIMIT 1
845 ";
846 $params = array(1 => array($contactID, 'Integer'));
847
848 $dao = CRM_Core_DAO::executeQuery($sql, $params);
849 $details = array(
850 'first' => NULL,
851 'last' => NULL,
852 );
853 if ($dao->fetch()) {
854 $details['first'] = array(
855 'total_amount' => $dao->total_amount,
856 'receive_date' => $dao->receive_date,
857 );
858 }
859
860 // flip asc and desc to get the last query
861 $sql = str_replace('ASC', 'DESC', $sql);
862 $dao = CRM_Core_DAO::executeQuery($sql, $params);
863 if ($dao->fetch()) {
864 $details['last'] = array(
865 'total_amount' => $dao->total_amount,
866 'receive_date' => $dao->receive_date,
867 );
868 }
869
870 $_cache[$contactID] = $details;
871 }
872 return $_cache[$contactID];
873 }
874 }
875