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