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