Merge pull request #3223 from lcdservices/CRM-14672
[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, 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, 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 TRUE, $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 static function createCMSUser(&$params, $contactID, $mail) {
432 // lets ensure we only create one CMS user
433 static $created = FALSE;
434
435 if ($created) {
436 return;
437 }
438 $created = TRUE;
439
440 if (!empty($params['cms_create_account'])) {
441 $params['contactID'] = $contactID;
442 if (!CRM_Core_BAO_CMSUser::create($params, $mail)) {
443 CRM_Core_Error::statusBounce(ts('Your profile is not saved and Account is not created.'));
444 }
445 }
446 }
447
448 static function _fillCommonParams(&$params, $type = 'paypal') {
449 if (array_key_exists('transaction', $params)) {
450 $transaction = &$params['transaction'];
451 }
452 else {
453 $transaction = &$params;
454 }
455
456 $params['contact_type'] = 'Individual';
457
458 $billingLocTypeId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', 'Billing', 'id', 'name');
459 if (!$billingLocTypeId) {
460 $billingLocTypeId = 1;
461 }
462 if (!CRM_Utils_System::isNull($params['address'])) {
463 $params['address'][1]['is_primary'] = 1;
464 $params['address'][1]['location_type_id'] = $billingLocTypeId;
465 }
466 if (!CRM_Utils_System::isNull($params['email'])) {
467 $params['email'] = array(
468 1 => array('email' => $params['email'],
469 'location_type_id' => $billingLocTypeId,
470 ));
471 }
472
473 if (isset($transaction['trxn_id'])) {
474 // set error message if transaction has already been processed.
475 $contribution = new CRM_Contribute_DAO_Contribution();
476 $contribution->trxn_id = $transaction['trxn_id'];
477 if ($contribution->find(TRUE)) {
478 $params['error'][] = ts('transaction already processed.');
479 }
480 }
481 else {
482 // generate a new transaction id, if not already exist
483 $transaction['trxn_id'] = md5(uniqid(rand(), TRUE));
484 }
485
486 if (!isset( $transaction['financial_type_id'])) {
487 $contributionTypes = array_keys(CRM_Contribute_PseudoConstant::financialType());
488 $transaction['financial_type_id'] = $contributionTypes[0];
489 }
490
491 if (($type == 'paypal') && (!isset($transaction['net_amount']))) {
492 $transaction['net_amount'] = $transaction['total_amount'] - CRM_Utils_Array::value('fee_amount', $transaction, 0);
493 }
494
495 if (!isset($transaction['invoice_id'])) {
496 $transaction['invoice_id'] = $transaction['trxn_id'];
497 }
498
499 $source = ts('ContributionProcessor: %1 API',
500 array(1 => ucfirst($type))
501 );
502 if (isset($transaction['source'])) {
503 $transaction['source'] = $source . ':: ' . $transaction['source'];
504 }
505 else {
506 $transaction['source'] = $source;
507 }
508
509 return TRUE;
510 }
511
512 static function formatAPIParams($apiParams, $mapper, $type = 'paypal', $category = TRUE) {
513 $type = strtolower($type);
514
515 if (!in_array($type, array(
516 'paypal', 'google', 'csv'))) {
517 // return the params as is
518 return $apiParams;
519 }
520 $params = $transaction = array();
521
522 if ($type == 'paypal') {
523 foreach ($apiParams as $detail => $val) {
524 if (isset($mapper['contact'][$detail])) {
525 $params[$mapper['contact'][$detail]] = $val;
526 }
527 elseif (isset($mapper['location'][$detail])) {
528 $params['address'][1][$mapper['location'][$detail]] = $val;
529 }
530 elseif (isset($mapper['transaction'][$detail])) {
531 switch ($detail) {
532 case 'l_period2':
533 // Sadly, PayPal seems to send two distinct data elements in a single field,
534 // so we break them out here. This is somewhat ugly and tragic.
535 $freqUnits = array(
536 'D' => 'day',
537 'W' => 'week',
538 'M' => 'month',
539 'Y' => 'year',
540 );
541 list($frequency_interval, $frequency_unit) = explode(' ', $val);
542 $transaction['frequency_interval'] = $frequency_interval;
543 $transaction['frequency_unit'] = $freqUnits[$frequency_unit];
544 break;
545
546 case 'subscriptiondate':
547 case 'timestamp':
548 // PayPal dates are in ISO-8601 format. We need a format that
549 // MySQL likes
550 $unix_timestamp = strtotime($val);
551 $transaction[$mapper['transaction'][$detail]] = date('YmdHis', $unix_timestamp);
552 break;
553
554 case 'note':
555 case 'custom':
556 case 'l_number0':
557 if ($val) {
558 $val = "[PayPal_field:{$detail}] {$val}";
559 $transaction[$mapper['transaction'][$detail]] = !empty($transaction[$mapper['transaction'][$detail]]) ? $transaction[$mapper['transaction'][$detail]] . " <br/> " . $val : $val;
560 }
561 break;
562
563 default:
564 $transaction[$mapper['transaction'][$detail]] = $val;
565 }
566 }
567 }
568
569 if (!empty($transaction) && $category) {
570 $params['transaction'] = $transaction;
571 }
572 else {
573 $params += $transaction;
574 }
575
576 self::_fillCommonParams($params, $type);
577
578 return $params;
579 }
580
581 if ($type == 'csv') {
582 $header = $apiParams['header'];
583 unset($apiParams['header']);
584 foreach ($apiParams as $key => $val) {
585 if (isset($mapper['contact'][$header[$key]])) {
586 $params[$mapper['contact'][$header[$key]]] = $val;
587 }
588 elseif (isset($mapper['location'][$header[$key]])) {
589 $params['address'][1][$mapper['location'][$header[$key]]] = $val;
590 }
591 elseif (isset($mapper['transaction'][$header[$key]])) {
592 $transaction[$mapper['transaction'][$header[$key]]] = $val;
593 }
594 else {
595 $params[$header[$key]] = $val;
596 }
597 }
598
599 if (!empty($transaction) && $category) {
600 $params['transaction'] = $transaction;
601 }
602 else {
603 $params += $transaction;
604 }
605
606 self::_fillCommonParams($params, $type);
607
608 return $params;
609 }
610
611 if ($type == 'google') {
612 // return if response smell invalid
613 if (!array_key_exists('risk-information-notification', $apiParams[1][$apiParams[0]]['notifications'])) {
614 return FALSE;
615 }
616 $riskInfo = &$apiParams[1][$apiParams[0]]['notifications']['risk-information-notification'];
617
618 if (array_key_exists('new-order-notification', $apiParams[1][$apiParams[0]]['notifications'])) {
619 $newOrder = &$apiParams[1][$apiParams[0]]['notifications']['new-order-notification'];
620 }
621
622 if ($riskInfo['google-order-number']['VALUE'] == $apiParams[2]['google-order-number']['VALUE']) {
623 foreach ($riskInfo['risk-information']['billing-address'] as $field => $info) {
624 if (!empty($mapper['location'][$field])) {
625 $params['address'][1][$mapper['location'][$field]] = $info['VALUE'];
626 }
627 elseif (!empty($mapper['contact'][$field])) {
628 if ($newOrder && !empty($newOrder['buyer-billing-address']['structured-name'])) {
629 foreach ($newOrder['buyer-billing-address']['structured-name'] as $namePart => $nameValue) {
630 $params[$mapper['contact'][$namePart]] = $nameValue['VALUE'];
631 }
632 }
633 else {
634 $params[$mapper['contact'][$field]] = $info['VALUE'];
635 }
636 }
637 elseif (!empty($mapper['transaction'][$field])) {
638 $transaction[$mapper['transaction'][$field]] = $info['VALUE'];
639 }
640 }
641
642 // Response is an huge array. Lets pickup only those which we ineterested in
643 // using a local mapper, rather than traversing the entire array.
644 $localMapper = array(
645 'google-order-number' => $riskInfo['google-order-number']['VALUE'],
646 'total-charge-amount' => $apiParams[2]['total-charge-amount']['VALUE'],
647 'currency' => $apiParams[2]['total-charge-amount']['currency'],
648 'item-name' => $newOrder['shopping-cart']['items']['item']['item-name']['VALUE'],
649 'timestamp' => $apiParams[2]['timestamp']['VALUE'],
650 );
651 if (array_key_exists('latest-charge-fee', $apiParams[2])) {
652 $localMapper['latest-charge-fee'] = $apiParams[2]['latest-charge-fee']['total']['VALUE'];
653 $localMapper['net-amount'] = $localMapper['total-charge-amount'] - $localMapper['latest-charge-fee'];
654 }
655
656 // This is a subscription (recurring) donation.
657 if (array_key_exists('subscription', $newOrder['shopping-cart']['items']['item'])) {
658 $subscription = $newOrder['shopping-cart']['items']['item']['subscription'];
659 $localMapper['amount'] = $newOrder['order-total']['VALUE'];
660 $localMapper['times'] = $subscription['payments']['subscription-payment']['times'];
661 // Convert Google's period to one compatible with the CiviCRM db field.
662 $freqUnits = array(
663 'DAILY' => 'day',
664 'WEEKLY' => 'week',
665 'MONHTLY' => 'month',
666 'YEARLY' => 'year',
667 );
668 $localMapper['period'] = $freqUnits[$subscription['period']];
669 // Unlike PayPal, Google has no concept of freq. interval, it is always 1.
670 $localMapper['frequency_interval'] = '1';
671 // Google Checkout dates are in ISO-8601 format. We need a format that
672 // MySQL likes
673 $unix_timestamp = strtotime($localMapper['timestamp']);
674 $mysql_date = date('YmdHis', $unix_timestamp);
675 $localMapper['modified_date'] = $mysql_date;
676 $localMapper['start_date'] = $mysql_date;
677 // This is PayPal's nomenclature, but just use it for Google as well since
678 // we act on the value of trxn_type in processAPIContribution().
679 $localMapper['trxn_type'] = 'subscrpayment';
680 }
681
682 foreach ($localMapper as $localKey => $localVal) {
683 if (!empty($mapper['transaction'][$localKey])) {
684 $transaction[$mapper['transaction'][$localKey]] = $localVal;
685 }
686 }
687
688 if (empty($params) && empty($transaction)) {
689 continue;
690 }
691
692 if (!empty($transaction) && $category) {
693 $params['transaction'] = $transaction;
694 }
695 else {
696 $params += $transaction;
697 }
698
699 self::_fillCommonParams($params, $type);
700 }
701 return $params;
702 }
703 }
704
705 static function processAPIContribution($params) {
706 if (empty($params) || array_key_exists('error', $params)) {
707 return FALSE;
708 }
709
710 // add contact using dedupe rule
711 $dedupeParams = CRM_Dedupe_Finder::formatParams($params, 'Individual');
712 $dedupeParams['check_permission'] = FALSE;
713 $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
714 // if we find more than one contact, use the first one
715 if (!empty($dupeIds[0])) {
716 $params['contact_id'] = $dupeIds[0];
717 }
718 $contact = CRM_Contact_BAO_Contact::create($params);
719 if (!$contact->id) {
720 return FALSE;
721 }
722
723 // only pass transaction params to contribution::create, if available
724 if (array_key_exists('transaction', $params)) {
725 $params = $params['transaction'];
726 $params['contact_id'] = $contact->id;
727 }
728
729 // handle contribution custom data
730 $customFields = CRM_Core_BAO_CustomField::getFields('Contribution',
731 FALSE,
732 FALSE,
733 CRM_Utils_Array::value('financial_type_id',
734 $params
735 )
736 );
737 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
738 $customFields,
739 CRM_Utils_Array::value('id', $params, NULL),
740 'Contribution'
741 );
742 // create contribution
743
744 // if this is a recurring contribution then process it first
745 if ($params['trxn_type'] == 'subscrpayment') {
746 // see if a recurring record already exists
747 $recurring = new CRM_Contribute_BAO_ContributionRecur;
748 $recurring->processor_id = $params['processor_id'];
749 if (!$recurring->find(TRUE)) {
750 $recurring = new CRM_Contribute_BAO_ContributionRecur;
751 $recurring->invoice_id = $params['invoice_id'];
752 $recurring->find(TRUE);
753 }
754
755 // This is the same thing the CiviCRM IPN handler does to handle
756 // subsequent recurring payments to avoid duplicate contribution
757 // errors due to invoice ID. See:
758 // ./CRM/Core/Payment/PayPalIPN.php:200
759 if ($recurring->id) {
760 $params['invoice_id'] = md5(uniqid(rand(), TRUE));
761 }
762
763 $recurring->copyValues($params);
764 $recurring->save();
765 if (is_a($recurring, 'CRM_Core_Error')) {
766 return FALSE;
767 }
768 else {
769 $params['contribution_recur_id'] = $recurring->id;
770 }
771 }
772
773 $contribution = &CRM_Contribute_BAO_Contribution::create($params,
774 CRM_Core_DAO::$_nullArray
775 );
776 if (!$contribution->id) {
777 return FALSE;
778 }
779
780 return TRUE;
781 }
782
783 static function getFirstLastDetails($contactID) {
784 static $_cache;
785
786 if (!$_cache) {
787 $_cache = array();
788 }
789
790 if (!isset($_cache[$contactID])) {
791 $sql = "
792 SELECT total_amount, receive_date
793 FROM civicrm_contribution c
794 WHERE contact_id = %1
795 ORDER BY receive_date ASC
796 LIMIT 1
797 ";
798 $params = array(1 => array($contactID, 'Integer'));
799
800 $dao = CRM_Core_DAO::executeQuery($sql, $params);
801 $details = array(
802 'first' => NULL,
803 'last' => NULL,
804 );
805 if ($dao->fetch()) {
806 $details['first'] = array(
807 'total_amount' => $dao->total_amount,
808 'receive_date' => $dao->receive_date,
809 );
810 }
811
812 // flip asc and desc to get the last query
813 $sql = str_replace('ASC', 'DESC', $sql);
814 $dao = CRM_Core_DAO::executeQuery($sql, $params);
815 if ($dao->fetch()) {
816 $details['last'] = array(
817 'total_amount' => $dao->total_amount,
818 'receive_date' => $dao->receive_date,
819 );
820 }
821
822 $_cache[$contactID] = $details;
823 }
824 return $_cache[$contactID];
825 }
826 }
827