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