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