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