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