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