CRM-16407 use new factory class fo instantiating payment processors
[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 95
2f5f6887
EM
96 if ($isPaymentTransaction && !empty($form->_paymentProcessor)) {
97 // @todo - remove this line once we are sure we can just use $form->_paymentProcessor['object'] consistently.
98 $payment = Civi\Payment\System::singleton()->getByProcessor($form->_paymentProcessor);
6a488035
TO
99 }
100
f1fc3638 101 //fix for CRM-16317
35cd38f5 102 $form->_params['receive_date'] = date('YmdHis');
f1fc3638 103 $form->assign('receive_date',
104 CRM_Utils_Date::mysqlToIso($form->_params['receive_date'])
105 );
6a488035
TO
106 $result = NULL;
107 if ($form->_contributeMode == 'notify' ||
cc789d46 108 $isPayLater
6a488035
TO
109 ) {
110 // this is not going to come back, i.e. we fill in the other details
111 // when we get a callback from the payment processor
112 // also add the contact ID and contribution ID to the params list
113 $paymentParams['contactID'] = $form->_params['contactID'] = $contactID;
ba013eea 114 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution(
6a488035
TO
115 $form,
116 $paymentParams,
117 NULL,
118 $contactID,
119 $contributionType,
4bd318e0
EM
120 TRUE, TRUE,
121 $isTest,
9fc4e1d9
EM
122 $lineItems,
123 $form->_bltID
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
ba013eea 241 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution(
6a488035
TO
242 $form,
243 $paymentParams,
244 NULL,
245 $contactID,
246 $contributionType,
a00ce7b3 247 $pending, TRUE,
4bd318e0 248 $isTest,
9fc4e1d9
EM
249 $lineItems,
250 $form->_bltID
6a488035
TO
251 );
252
cd125a40 253 // restore cached values (part of fix for CRM-14354)
919e8652 254 if (!empty($cachedFormValue)) {
d8a20b17
FG
255 $form->_values['is_recur'] = $cachedFormValue;
256 $paymentParams['is_recur'] = $cachedParamValue;
257 }
cd125a40 258
6a488035 259 $paymentParams['contributionID'] = $contribution->id;
d9659858
EM
260 //CRM-15297 deprecate contributionTypeID
261 $paymentParams['financialTypeID'] = $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
6a488035
TO
262 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
263
264 if ($form->_values['is_recur'] && $contribution->contribution_recur_id) {
265 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
266 }
267 }
06d062ce
EM
268 try {
269 $result = $payment->doPayment($paymentParams);
6a488035 270 }
06d062ce
EM
271 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
272 // Clean up DB as appropriate.
273 if (!empty($paymentParams['contributionID'])) {
274 CRM_Contribute_BAO_Contribution::failPayment($paymentParams['contributionID'],
275 $paymentParams['contactID'], $e->getMessage());
276 }
277 if (!empty($paymentParams['contributionRecurID'])) {
278 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
279 }
280
281 if ($component !== 'membership') {
282 // This is only called from contribution form.
283 // Not sure if there is any reason not to just throw an exception up to it.
284 $result['is_payment_failure'] = TRUE;
285 return $result;
286 }
287 $membershipResult[1] = $result;
6a488035
TO
288 }
289 }
290
291 if ($component == 'membership') {
292 $membershipResult = array();
293 }
294
06d062ce 295 if ($result || ($form->_amount == 0.0 && !$form->_params['is_pay_later'])) {
6a488035
TO
296 if ($result) {
297 $form->_params = array_merge($form->_params, $result);
298 }
6a488035
TO
299 $form->set('params', $form->_params);
300 $form->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
6a488035
TO
301
302 // result has all the stuff we need
303 // lets archive it to a financial transaction
d9659858
EM
304 //@todo - this is done in 2 places - can't we just do it once straight after retrieving contribution type -
305 // when would this be a bad thing?
6a488035
TO
306 if ($contributionType->is_deductible) {
307 $form->assign('is_deductible', TRUE);
308 $form->set('is_deductible', TRUE);
309 }
310
311 if (isset($paymentParams['contribution_source'])) {
312 $form->_params['source'] = $paymentParams['contribution_source'];
313 }
314
315 // check if pending was set to true by payment processor
316 $pending = FALSE;
8c096555 317 if (!empty($form->_params['contribution_status_pending'])) {
6a488035
TO
318 $pending = TRUE;
319 }
320 if (!(!empty($paymentParams['is_recur']) && $form->_contributeMode == 'direct')) {
ba013eea 321 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($form,
6a488035
TO
322 $form->_params, $result,
323 $contactID, $contributionType,
4bd318e0
EM
324 $pending, TRUE,
325 $isTest,
9fc4e1d9
EM
326 $lineItems,
327 $form->_bltID
6a488035
TO
328 );
329 }
330 $form->postProcessPremium($premiumParams, $contribution);
a7a33651
EM
331 if (is_array($result) && !empty($result['trxn_id'])) {
332 $contribution->trxn_id = $result['trxn_id'];
333 }
6a488035
TO
334 $membershipResult[1] = $contribution;
335 }
336
337 if ($component == 'membership') {
338 return $membershipResult;
339 }
340
341 //Do not send an email if Recurring contribution is done via Direct Mode
342 //We will send email once the IPN is received.
343 if (!empty($paymentParams['is_recur']) && $form->_contributeMode == 'direct') {
344 return TRUE;
345 }
346
347 // get the price set values for receipt.
348 if ($form->_priceSetId && $form->_lineItem) {
349 $form->_values['lineItem'] = $form->_lineItem;
350 $form->_values['priceSetID'] = $form->_priceSetId;
351 }
352
353 // finally send an email receipt
354 if ($contribution) {
874c9be7 355 $form->_values['contribution_id'] = $contribution->id;
6a488035
TO
356 CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
357 $form->_values, $contribution->is_test,
353ffa53 358 FALSE, $fieldTypes
874c9be7
TO
359 );
360 }
6a488035
TO
361 }
362
cc789d46
EM
363 /**
364 * Is a payment being made.
365 * Note that setting is_monetary on the form is somewhat legacy and the behaviour around this setting is confusing. It would be preferable
366 * to look for the amount only (assuming this cannot refer to payment in goats or other non-monetary currency
c490a46a 367 * @param CRM_Core_Form $form
cc789d46
EM
368 *
369 * @return bool
370 */
371 static protected function isPaymentTransaction($form) {
22e263ad 372 if (!empty($form->_values['is_monetary']) && $form->_amount >= 0.0) {
cc789d46
EM
373 return TRUE;
374 }
375 return FALSE;
376
377 }
353ffa53 378
6a488035 379 /**
100fef9d 380 * Get the contribution details by month
6a488035
TO
381 * of the year
382 *
014c4014
TO
383 * @param int $param
384 * Year.
6a488035 385 *
a6c01b45
CW
386 * @return array
387 * associated array
6a488035 388 *
6a488035 389 */
00be9182 390 public static function contributionChartMonthly($param) {
6a488035
TO
391 if ($param) {
392 $param = array(1 => array($param, 'Integer'));
393 }
394 else {
395 $param = date("Y");
396 $param = array(1 => array($param, 'Integer'));
397 }
398
399 $query = "
400 SELECT sum(contrib.total_amount) AS ctAmt,
401 MONTH( contrib.receive_date) AS contribMonth
402 FROM civicrm_contribution AS contrib
403INNER JOIN civicrm_contact AS contact ON ( contact.id = contrib.contact_id )
404 WHERE contrib.contact_id = contact.id
405 AND ( contrib.is_test = 0 OR contrib.is_test IS NULL )
406 AND contrib.contribution_status_id = 1
407 AND date_format(contrib.receive_date,'%Y') = %1
408 AND contact.is_deleted = 0
409 GROUP BY contribMonth
410 ORDER BY month(contrib.receive_date)";
411
412 $dao = CRM_Core_DAO::executeQuery($query, $param);
413
414 $params = NULL;
415 while ($dao->fetch()) {
416 if ($dao->contribMonth) {
417 $params['By Month'][$dao->contribMonth] = $dao->ctAmt;
418 }
419 }
420 return $params;
421 }
422
423 /**
fe482240 424 * Get the contribution details by year.
6a488035 425 *
a6c01b45
CW
426 * @return array
427 * associated array
6a488035 428 *
6a488035 429 */
00be9182 430 public static function contributionChartYearly() {
6a488035
TO
431 $config = CRM_Core_Config::singleton();
432 $yearClause = "year(contrib.receive_date) as contribYear";
433 if (!empty($config->fiscalYearStart) && ($config->fiscalYearStart['M'] != 1 || $config->fiscalYearStart['d'] != 1)) {
a48278eb
KJ
434 $yearClause = "CASE
435 WHEN (MONTH(contrib.receive_date)>= " . $config->fiscalYearStart['M'] . "
f813f78e 436 && DAYOFMONTH(contrib.receive_date)>= " . $config->fiscalYearStart['d'] . " )
a48278eb
KJ
437 THEN
438 concat(YEAR(contrib.receive_date), '-',YEAR(contrib.receive_date)+1)
439 ELSE
440 concat(YEAR(contrib.receive_date)-1,'-', YEAR(contrib.receive_date))
441 END AS contribYear";
6a488035
TO
442 }
443
444 $query = "
445 SELECT sum(contrib.total_amount) AS ctAmt,
446 {$yearClause}
447 FROM civicrm_contribution AS contrib
448INNER JOIN civicrm_contact contact ON ( contact.id = contrib.contact_id )
449 WHERE ( contrib.is_test = 0 OR contrib.is_test IS NULL )
450 AND contrib.contribution_status_id = 1
451 AND contact.is_deleted = 0
452 GROUP BY contribYear
453 ORDER BY contribYear";
454 $dao = CRM_Core_DAO::executeQuery($query);
455
456 $params = NULL;
457 while ($dao->fetch()) {
458 if (!empty($dao->contribYear)) {
459 $params['By Year'][$dao->contribYear] = $dao->ctAmt;
460 }
461 }
462 return $params;
463 }
464
186c9c17 465 /**
c490a46a 466 * @param array $params
100fef9d 467 * @param int $contactID
186c9c17
EM
468 * @param $mail
469 */
00be9182 470 public static function createCMSUser(&$params, $contactID, $mail) {
6a488035
TO
471 // lets ensure we only create one CMS user
472 static $created = FALSE;
473
474 if ($created) {
475 return;
476 }
477 $created = TRUE;
478
a7488080 479 if (!empty($params['cms_create_account'])) {
6a488035
TO
480 $params['contactID'] = $contactID;
481 if (!CRM_Core_BAO_CMSUser::create($params, $mail)) {
482 CRM_Core_Error::statusBounce(ts('Your profile is not saved and Account is not created.'));
483 }
484 }
485 }
486
186c9c17 487 /**
c490a46a 488 * @param array $params
186c9c17
EM
489 * @param string $type
490 *
491 * @return bool
492 */
00be9182 493 public static function _fillCommonParams(&$params, $type = 'paypal') {
6a488035
TO
494 if (array_key_exists('transaction', $params)) {
495 $transaction = &$params['transaction'];
496 }
497 else {
498 $transaction = &$params;
499 }
500
501 $params['contact_type'] = 'Individual';
502
503 $billingLocTypeId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', 'Billing', 'id', 'name');
504 if (!$billingLocTypeId) {
505 $billingLocTypeId = 1;
506 }
507 if (!CRM_Utils_System::isNull($params['address'])) {
508 $params['address'][1]['is_primary'] = 1;
509 $params['address'][1]['location_type_id'] = $billingLocTypeId;
510 }
511 if (!CRM_Utils_System::isNull($params['email'])) {
512 $params['email'] = array(
874c9be7 513 1 => array(
353ffa53 514 'email' => $params['email'],
6a488035 515 'location_type_id' => $billingLocTypeId,
ae5ffbb7 516 ),
353ffa53 517 );
6a488035
TO
518 }
519
520 if (isset($transaction['trxn_id'])) {
521 // set error message if transaction has already been processed.
522 $contribution = new CRM_Contribute_DAO_Contribution();
523 $contribution->trxn_id = $transaction['trxn_id'];
524 if ($contribution->find(TRUE)) {
525 $params['error'][] = ts('transaction already processed.');
526 }
527 }
528 else {
529 // generate a new transaction id, if not already exist
530 $transaction['trxn_id'] = md5(uniqid(rand(), TRUE));
531 }
532
481a74f4 533 if (!isset($transaction['financial_type_id'])) {
6a488035
TO
534 $contributionTypes = array_keys(CRM_Contribute_PseudoConstant::financialType());
535 $transaction['financial_type_id'] = $contributionTypes[0];
536 }
537
538 if (($type == 'paypal') && (!isset($transaction['net_amount']))) {
539 $transaction['net_amount'] = $transaction['total_amount'] - CRM_Utils_Array::value('fee_amount', $transaction, 0);
540 }
541
542 if (!isset($transaction['invoice_id'])) {
543 $transaction['invoice_id'] = $transaction['trxn_id'];
544 }
545
546 $source = ts('ContributionProcessor: %1 API',
547 array(1 => ucfirst($type))
548 );
549 if (isset($transaction['source'])) {
550 $transaction['source'] = $source . ':: ' . $transaction['source'];
551 }
552 else {
553 $transaction['source'] = $source;
554 }
555
556 return TRUE;
557 }
558
186c9c17 559 /**
100fef9d 560 * @param array $apiParams
186c9c17
EM
561 * @param $mapper
562 * @param string $type
563 * @param bool $category
564 *
565 * @return array
566 */
00be9182 567 public static function formatAPIParams($apiParams, $mapper, $type = 'paypal', $category = TRUE) {
6a488035
TO
568 $type = strtolower($type);
569
570 if (!in_array($type, array(
353ffa53
TO
571 'paypal',
572 'google',
ae5ffbb7 573 'csv',
353ffa53
TO
574 ))
575 ) {
6a488035
TO
576 // return the params as is
577 return $apiParams;
578 }
579 $params = $transaction = array();
580
581 if ($type == 'paypal') {
582 foreach ($apiParams as $detail => $val) {
583 if (isset($mapper['contact'][$detail])) {
584 $params[$mapper['contact'][$detail]] = $val;
585 }
586 elseif (isset($mapper['location'][$detail])) {
587 $params['address'][1][$mapper['location'][$detail]] = $val;
588 }
589 elseif (isset($mapper['transaction'][$detail])) {
590 switch ($detail) {
591 case 'l_period2':
592 // Sadly, PayPal seems to send two distinct data elements in a single field,
593 // so we break them out here. This is somewhat ugly and tragic.
594 $freqUnits = array(
595 'D' => 'day',
596 'W' => 'week',
597 'M' => 'month',
598 'Y' => 'year',
599 );
600 list($frequency_interval, $frequency_unit) = explode(' ', $val);
601 $transaction['frequency_interval'] = $frequency_interval;
602 $transaction['frequency_unit'] = $freqUnits[$frequency_unit];
603 break;
604
605 case 'subscriptiondate':
606 case 'timestamp':
607 // PayPal dates are in ISO-8601 format. We need a format that
608 // MySQL likes
609 $unix_timestamp = strtotime($val);
610 $transaction[$mapper['transaction'][$detail]] = date('YmdHis', $unix_timestamp);
611 break;
612
613 case 'note':
614 case 'custom':
615 case 'l_number0':
616 if ($val) {
617 $val = "[PayPal_field:{$detail}] {$val}";
618 $transaction[$mapper['transaction'][$detail]] = !empty($transaction[$mapper['transaction'][$detail]]) ? $transaction[$mapper['transaction'][$detail]] . " <br/> " . $val : $val;
619 }
620 break;
621
622 default:
623 $transaction[$mapper['transaction'][$detail]] = $val;
624 }
625 }
626 }
627
628 if (!empty($transaction) && $category) {
629 $params['transaction'] = $transaction;
630 }
631 else {
632 $params += $transaction;
633 }
634
635 self::_fillCommonParams($params, $type);
636
637 return $params;
638 }
639
640 if ($type == 'csv') {
641 $header = $apiParams['header'];
642 unset($apiParams['header']);
643 foreach ($apiParams as $key => $val) {
644 if (isset($mapper['contact'][$header[$key]])) {
645 $params[$mapper['contact'][$header[$key]]] = $val;
646 }
647 elseif (isset($mapper['location'][$header[$key]])) {
648 $params['address'][1][$mapper['location'][$header[$key]]] = $val;
649 }
650 elseif (isset($mapper['transaction'][$header[$key]])) {
651 $transaction[$mapper['transaction'][$header[$key]]] = $val;
652 }
653 else {
654 $params[$header[$key]] = $val;
655 }
656 }
657
658 if (!empty($transaction) && $category) {
659 $params['transaction'] = $transaction;
660 }
661 else {
662 $params += $transaction;
663 }
664
665 self::_fillCommonParams($params, $type);
666
667 return $params;
668 }
669
670 if ($type == 'google') {
671 // return if response smell invalid
672 if (!array_key_exists('risk-information-notification', $apiParams[1][$apiParams[0]]['notifications'])) {
673 return FALSE;
674 }
675 $riskInfo = &$apiParams[1][$apiParams[0]]['notifications']['risk-information-notification'];
676
677 if (array_key_exists('new-order-notification', $apiParams[1][$apiParams[0]]['notifications'])) {
678 $newOrder = &$apiParams[1][$apiParams[0]]['notifications']['new-order-notification'];
679 }
680
681 if ($riskInfo['google-order-number']['VALUE'] == $apiParams[2]['google-order-number']['VALUE']) {
682 foreach ($riskInfo['risk-information']['billing-address'] as $field => $info) {
a7488080 683 if (!empty($mapper['location'][$field])) {
6a488035
TO
684 $params['address'][1][$mapper['location'][$field]] = $info['VALUE'];
685 }
a7488080 686 elseif (!empty($mapper['contact'][$field])) {
8cc574cf 687 if ($newOrder && !empty($newOrder['buyer-billing-address']['structured-name'])) {
6a488035
TO
688 foreach ($newOrder['buyer-billing-address']['structured-name'] as $namePart => $nameValue) {
689 $params[$mapper['contact'][$namePart]] = $nameValue['VALUE'];
690 }
691 }
692 else {
693 $params[$mapper['contact'][$field]] = $info['VALUE'];
694 }
695 }
a7488080 696 elseif (!empty($mapper['transaction'][$field])) {
6a488035
TO
697 $transaction[$mapper['transaction'][$field]] = $info['VALUE'];
698 }
699 }
700
701 // Response is an huge array. Lets pickup only those which we ineterested in
702 // using a local mapper, rather than traversing the entire array.
703 $localMapper = array(
704 'google-order-number' => $riskInfo['google-order-number']['VALUE'],
705 'total-charge-amount' => $apiParams[2]['total-charge-amount']['VALUE'],
706 'currency' => $apiParams[2]['total-charge-amount']['currency'],
707 'item-name' => $newOrder['shopping-cart']['items']['item']['item-name']['VALUE'],
708 'timestamp' => $apiParams[2]['timestamp']['VALUE'],
709 );
710 if (array_key_exists('latest-charge-fee', $apiParams[2])) {
711 $localMapper['latest-charge-fee'] = $apiParams[2]['latest-charge-fee']['total']['VALUE'];
712 $localMapper['net-amount'] = $localMapper['total-charge-amount'] - $localMapper['latest-charge-fee'];
713 }
714
715 // This is a subscription (recurring) donation.
716 if (array_key_exists('subscription', $newOrder['shopping-cart']['items']['item'])) {
717 $subscription = $newOrder['shopping-cart']['items']['item']['subscription'];
718 $localMapper['amount'] = $newOrder['order-total']['VALUE'];
719 $localMapper['times'] = $subscription['payments']['subscription-payment']['times'];
720 // Convert Google's period to one compatible with the CiviCRM db field.
721 $freqUnits = array(
722 'DAILY' => 'day',
723 'WEEKLY' => 'week',
724 'MONHTLY' => 'month',
725 'YEARLY' => 'year',
726 );
727 $localMapper['period'] = $freqUnits[$subscription['period']];
728 // Unlike PayPal, Google has no concept of freq. interval, it is always 1.
729 $localMapper['frequency_interval'] = '1';
730 // Google Checkout dates are in ISO-8601 format. We need a format that
731 // MySQL likes
732 $unix_timestamp = strtotime($localMapper['timestamp']);
733 $mysql_date = date('YmdHis', $unix_timestamp);
734 $localMapper['modified_date'] = $mysql_date;
735 $localMapper['start_date'] = $mysql_date;
736 // This is PayPal's nomenclature, but just use it for Google as well since
737 // we act on the value of trxn_type in processAPIContribution().
738 $localMapper['trxn_type'] = 'subscrpayment';
739 }
740
741 foreach ($localMapper as $localKey => $localVal) {
a7488080 742 if (!empty($mapper['transaction'][$localKey])) {
6a488035
TO
743 $transaction[$mapper['transaction'][$localKey]] = $localVal;
744 }
745 }
746
747 if (empty($params) && empty($transaction)) {
748 continue;
749 }
750
751 if (!empty($transaction) && $category) {
752 $params['transaction'] = $transaction;
753 }
754 else {
755 $params += $transaction;
756 }
757
758 self::_fillCommonParams($params, $type);
759 }
760 return $params;
761 }
762 }
763
186c9c17 764 /**
c490a46a 765 * @param array $params
186c9c17
EM
766 *
767 * @return bool
768 */
00be9182 769 public static function processAPIContribution($params) {
6a488035
TO
770 if (empty($params) || array_key_exists('error', $params)) {
771 return FALSE;
772 }
773
774 // add contact using dedupe rule
775 $dedupeParams = CRM_Dedupe_Finder::formatParams($params, 'Individual');
776 $dedupeParams['check_permission'] = FALSE;
777 $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
778 // if we find more than one contact, use the first one
a7488080 779 if (!empty($dupeIds[0])) {
6a488035
TO
780 $params['contact_id'] = $dupeIds[0];
781 }
782 $contact = CRM_Contact_BAO_Contact::create($params);
783 if (!$contact->id) {
784 return FALSE;
785 }
786
787 // only pass transaction params to contribution::create, if available
788 if (array_key_exists('transaction', $params)) {
789 $params = $params['transaction'];
790 $params['contact_id'] = $contact->id;
791 }
792
793 // handle contribution custom data
794 $customFields = CRM_Core_BAO_CustomField::getFields('Contribution',
795 FALSE,
796 FALSE,
797 CRM_Utils_Array::value('financial_type_id',
798 $params
799 )
800 );
801 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
6a488035
TO
802 CRM_Utils_Array::value('id', $params, NULL),
803 'Contribution'
804 );
805 // create contribution
806
807 // if this is a recurring contribution then process it first
808 if ($params['trxn_type'] == 'subscrpayment') {
809 // see if a recurring record already exists
ae5ffbb7 810 $recurring = new CRM_Contribute_BAO_ContributionRecur();
6a488035
TO
811 $recurring->processor_id = $params['processor_id'];
812 if (!$recurring->find(TRUE)) {
ae5ffbb7 813 $recurring = new CRM_Contribute_BAO_ContributionRecur();
6a488035
TO
814 $recurring->invoice_id = $params['invoice_id'];
815 $recurring->find(TRUE);
816 }
817
818 // This is the same thing the CiviCRM IPN handler does to handle
819 // subsequent recurring payments to avoid duplicate contribution
820 // errors due to invoice ID. See:
821 // ./CRM/Core/Payment/PayPalIPN.php:200
822 if ($recurring->id) {
823 $params['invoice_id'] = md5(uniqid(rand(), TRUE));
824 }
825
826 $recurring->copyValues($params);
827 $recurring->save();
828 if (is_a($recurring, 'CRM_Core_Error')) {
829 return FALSE;
830 }
831 else {
832 $params['contribution_recur_id'] = $recurring->id;
833 }
834 }
835
836 $contribution = &CRM_Contribute_BAO_Contribution::create($params,
837 CRM_Core_DAO::$_nullArray
838 );
839 if (!$contribution->id) {
840 return FALSE;
841 }
842
843 return TRUE;
844 }
845
186c9c17 846 /**
100fef9d 847 * @param int $contactID
186c9c17
EM
848 *
849 * @return mixed
850 */
00be9182 851 public static function getFirstLastDetails($contactID) {
6a488035
TO
852 static $_cache;
853
854 if (!$_cache) {
855 $_cache = array();
856 }
857
858 if (!isset($_cache[$contactID])) {
859 $sql = "
860SELECT total_amount, receive_date
861FROM civicrm_contribution c
862WHERE contact_id = %1
863ORDER BY receive_date ASC
864LIMIT 1
865";
866 $params = array(1 => array($contactID, 'Integer'));
867
868 $dao = CRM_Core_DAO::executeQuery($sql, $params);
869 $details = array(
870 'first' => NULL,
871 'last' => NULL,
872 );
873 if ($dao->fetch()) {
874 $details['first'] = array(
875 'total_amount' => $dao->total_amount,
876 'receive_date' => $dao->receive_date,
877 );
878 }
879
880 // flip asc and desc to get the last query
881 $sql = str_replace('ASC', 'DESC', $sql);
882 $dao = CRM_Core_DAO::executeQuery($sql, $params);
883 if ($dao->fetch()) {
884 $details['last'] = array(
885 'total_amount' => $dao->total_amount,
886 'receive_date' => $dao->receive_date,
887 );
888 }
889
890 $_cache[$contactID] = $details;
891 }
892 return $_cache[$contactID];
893 }
9d1c9154 894
895 /**
896 * Calculate the tax amount based on given tax rate.
897 *
014c4014
TO
898 * @param float $amount
899 * Amount of field.
900 * @param float $taxRate
901 * Tax rate of selected financial account for field.
9d1c9154 902 *
a6c01b45
CW
903 * @return array
904 * array of tax amount
9d1c9154 905 *
9d1c9154 906 */
907 public static function calculateTaxAmount($amount, $taxRate) {
908 $taxAmount = array();
874c9be7 909 $taxAmount['tax_amount'] = ($taxRate / 100) * CRM_Utils_Rule::cleanMoney($amount);
9d1c9154 910
911 return $taxAmount;
912 }
96025800 913
6a488035 914}