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