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