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