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