| 1 | <?php |
| 2 | /* |
| 3 | +--------------------------------------------------------------------+ |
| 4 | | Copyright CiviCRM LLC. All rights reserved. | |
| 5 | | | |
| 6 | | This work is published under the GNU AGPLv3 license with some | |
| 7 | | permitted exceptions and without any warranty. For full license | |
| 8 | | and copyright information, see https://civicrm.org/licensing | |
| 9 | +--------------------------------------------------------------------+ |
| 10 | */ |
| 11 | |
| 12 | /** |
| 13 | * |
| 14 | * @package CRM |
| 15 | * @copyright CiviCRM LLC https://civicrm.org/licensing |
| 16 | */ |
| 17 | class CiviContributeProcessor { |
| 18 | public static $_paypalParamsMapper = array( |
| 19 | //category => array(paypal_param => civicrm_field); |
| 20 | 'contact' => array( |
| 21 | 'salutation' => 'prefix_id', |
| 22 | 'firstname' => 'first_name', |
| 23 | 'lastname' => 'last_name', |
| 24 | 'middlename' => 'middle_name', |
| 25 | 'suffix' => 'suffix_id', |
| 26 | 'email' => 'email', |
| 27 | ), |
| 28 | 'location' => array( |
| 29 | 'shiptoname' => 'address_name', |
| 30 | 'shiptostreet' => 'street_address', |
| 31 | 'shiptostreet2' => 'supplemental_address_1', |
| 32 | 'shiptocity' => 'city', |
| 33 | 'shiptostate' => 'state_province', |
| 34 | 'shiptozip' => 'postal_code', |
| 35 | 'countrycode' => 'country', |
| 36 | ), |
| 37 | 'transaction' => array( |
| 38 | 'amt' => 'total_amount', |
| 39 | 'feeamt' => 'fee_amount', |
| 40 | 'transactionid' => 'trxn_id', |
| 41 | 'currencycode' => 'currency', |
| 42 | 'l_name0' => 'source', |
| 43 | 'ordertime' => 'receive_date', |
| 44 | 'note' => 'note', |
| 45 | 'custom' => 'note', |
| 46 | 'l_number0' => 'note', |
| 47 | 'is_test' => 'is_test', |
| 48 | 'transactiontype' => 'trxn_type', |
| 49 | 'recurrences' => 'installments', |
| 50 | 'l_amt2' => 'amount', |
| 51 | 'l_period2' => 'lol', |
| 52 | 'invnum' => 'invoice_id', |
| 53 | 'subscriptiondate' => 'start_date', |
| 54 | 'subscriptionid' => 'processor_id', |
| 55 | 'timestamp' => 'modified_date', |
| 56 | ), |
| 57 | ); |
| 58 | |
| 59 | /** |
| 60 | * Note: if csv header is not present in the mapper, header itself |
| 61 | * is considered as a civicrm field. |
| 62 | * category => array(csv_header => civicrm_field); |
| 63 | * @var array |
| 64 | */ |
| 65 | public static $_csvParamsMapper = array( |
| 66 | 'contact' => array( |
| 67 | 'first_name' => 'first_name', |
| 68 | 'last_name' => 'last_name', |
| 69 | 'middle_name' => 'middle_name', |
| 70 | 'email' => 'email', |
| 71 | ), |
| 72 | 'location' => array( |
| 73 | 'street_address' => 'street_address', |
| 74 | 'supplemental_address_1' => 'supplemental_address_1', |
| 75 | 'city' => 'city', |
| 76 | 'postal_code' => 'postal_code', |
| 77 | 'country' => 'country', |
| 78 | ), |
| 79 | 'transaction' => array( |
| 80 | 'total_amount' => 'total_amount', |
| 81 | 'trxn_id' => 'trxn_id', |
| 82 | 'currency' => 'currency', |
| 83 | 'source' => 'source', |
| 84 | 'receive_date' => 'receive_date', |
| 85 | 'note' => 'note', |
| 86 | 'is_test' => 'is_test', |
| 87 | ), |
| 88 | ); |
| 89 | |
| 90 | /** |
| 91 | * @param $paymentProcessor |
| 92 | * @param $paymentMode |
| 93 | * @param $start |
| 94 | * @param $end |
| 95 | */ |
| 96 | public static function paypal($paymentProcessor, $paymentMode, $start, $end) { |
| 97 | $url = "{$paymentProcessor['url_api']}nvp"; |
| 98 | |
| 99 | $keyArgs = array( |
| 100 | 'user' => $paymentProcessor['user_name'], |
| 101 | 'pwd' => $paymentProcessor['password'], |
| 102 | 'signature' => $paymentProcessor['signature'], |
| 103 | 'version' => 3.0, |
| 104 | ); |
| 105 | |
| 106 | $args = $keyArgs; |
| 107 | $args += array( |
| 108 | 'method' => 'TransactionSearch', |
| 109 | 'startdate' => $start, |
| 110 | 'enddate' => $end, |
| 111 | ); |
| 112 | |
| 113 | require_once 'CRM/Core/Payment/PayPalImpl.php'; |
| 114 | |
| 115 | // as invokeAPI fetch only last 100 transactions. |
| 116 | // we should require recursive calls to process more than 100. |
| 117 | // first fetch transactions w/ give date intervals. |
| 118 | // if we get error code w/ result, which means we do have more than 100 |
| 119 | // manipulate date interval accordingly and fetch again. |
| 120 | |
| 121 | do { |
| 122 | $result = CRM_Core_Payment_PayPalImpl::invokeAPI($args, $url); |
| 123 | require_once "CRM/Contribute/BAO/Contribution/Utils.php"; |
| 124 | |
| 125 | $keyArgs['method'] = 'GetTransactionDetails'; |
| 126 | foreach ($result as $name => $value) { |
| 127 | if (substr($name, 0, 15) == 'l_transactionid') { |
| 128 | |
| 129 | // We don't/can't process subscription notifications, which appear |
| 130 | // to be identified by transaction ids beginning with S- |
| 131 | if (substr($value, 0, 2) == 'S-') { |
| 132 | continue; |
| 133 | } |
| 134 | |
| 135 | // Before we bother making a remote API call to PayPal to lookup |
| 136 | // details about a transaction, let's make sure that it doesn't |
| 137 | // already exist in the database. |
| 138 | require_once 'CRM/Contribute/DAO/Contribution.php'; |
| 139 | $dao = new CRM_Contribute_DAO_Contribution(); |
| 140 | $dao->trxn_id = $value; |
| 141 | if ($dao->find(TRUE)) { |
| 142 | preg_match('/(\d+)$/', $name, $matches); |
| 143 | $seq = $matches[1]; |
| 144 | $email = $result["l_email{$seq}"]; |
| 145 | $amt = $result["l_amt{$seq}"]; |
| 146 | CRM_Core_Error::debug_log_message("Skipped (already recorded) - $email, $amt, $value ..<p>", TRUE); |
| 147 | continue; |
| 148 | } |
| 149 | |
| 150 | $keyArgs['transactionid'] = $value; |
| 151 | $trxnDetails = CRM_Core_Payment_PayPalImpl::invokeAPI($keyArgs, $url); |
| 152 | if (is_a($trxnDetails, 'CRM_Core_Error')) { |
| 153 | echo "PAYPAL ERROR: Skipping transaction id: $value<p>"; |
| 154 | continue; |
| 155 | } |
| 156 | |
| 157 | // only process completed payments |
| 158 | if (strtolower($trxnDetails['paymentstatus']) != 'completed') { |
| 159 | continue; |
| 160 | } |
| 161 | |
| 162 | // only process receipts, not payments |
| 163 | if (strtolower($trxnDetails['transactiontype']) == 'sendmoney') { |
| 164 | continue; |
| 165 | } |
| 166 | |
| 167 | $params = self::formatAPIParams($trxnDetails, |
| 168 | self::$_paypalParamsMapper, |
| 169 | 'paypal' |
| 170 | ); |
| 171 | if ($paymentMode == 'test') { |
| 172 | $params['transaction']['is_test'] = 1; |
| 173 | } |
| 174 | else { |
| 175 | $params['transaction']['is_test'] = 0; |
| 176 | } |
| 177 | |
| 178 | try { |
| 179 | if (self::processAPIContribution($params)) { |
| 180 | CRM_Core_Error::debug_log_message("Processed - {$trxnDetails['email']}, {$trxnDetails['amt']}, {$value} ..<p>", TRUE); |
| 181 | } |
| 182 | else { |
| 183 | CRM_Core_Error::debug_log_message("Skipped - {$trxnDetails['email']}, {$trxnDetails['amt']}, {$value} ..<p>", TRUE); |
| 184 | } |
| 185 | } |
| 186 | catch (CiviCRM_API3_Exception $e) { |
| 187 | CRM_Core_Error::debug_log_message("Skipped - {$trxnDetails['email']}, {$trxnDetails['amt']}, {$value} ..<p>", TRUE); |
| 188 | } |
| 189 | } |
| 190 | } |
| 191 | if ($result['l_errorcode0'] == '11002') { |
| 192 | $end = $result['l_timestamp99']; |
| 193 | $end_time = strtotime("{$end}", time()); |
| 194 | $end_date = date('Y-m-d\T00:00:00.00\Z', $end_time); |
| 195 | $args['enddate'] = $end_date; |
| 196 | } |
| 197 | } while ($result['l_errorcode0'] == '11002'); |
| 198 | } |
| 199 | |
| 200 | public static function csv() { |
| 201 | $csvFile = '/home/deepak/Desktop/crm-4247.csv'; |
| 202 | $delimiter = ";"; |
| 203 | $row = 1; |
| 204 | |
| 205 | $handle = fopen($csvFile, "r"); |
| 206 | if (!$handle) { |
| 207 | throw new CRM_Core_Exception("Can't locate csv file."); |
| 208 | } |
| 209 | |
| 210 | require_once "CRM/Contribute/BAO/Contribution/Utils.php"; |
| 211 | while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) { |
| 212 | if ($row !== 1) { |
| 213 | $data['header'] = $header; |
| 214 | $params = self::formatAPIParams($data, |
| 215 | self::$_csvParamsMapper, |
| 216 | 'csv' |
| 217 | ); |
| 218 | if (self::processAPIContribution($params)) { |
| 219 | CRM_Core_Error::debug_log_message("Processed - line $row of csv file .. {$params['email']}, {$params['transaction']['total_amount']}, {$params['transaction']['trxn_id']} ..<p>", TRUE); |
| 220 | } |
| 221 | else { |
| 222 | CRM_Core_Error::debug_log_message("Skipped - line $row of csv file .. {$params['email']}, {$params['transaction']['total_amount']}, {$params['transaction']['trxn_id']} ..<p>", TRUE); |
| 223 | } |
| 224 | |
| 225 | // clean up memory from dao's |
| 226 | CRM_Core_DAO::freeResult(); |
| 227 | } |
| 228 | else { |
| 229 | // we assuming - first row is always the header line |
| 230 | $header = $data; |
| 231 | CRM_Core_Error::debug_log_message("Considering first row ( line $row ) as HEADER ..<p>", TRUE); |
| 232 | |
| 233 | if (empty($header)) { |
| 234 | throw new CRM_Core_Exception("Header is empty."); |
| 235 | } |
| 236 | } |
| 237 | $row++; |
| 238 | } |
| 239 | fclose($handle); |
| 240 | } |
| 241 | |
| 242 | public static function process() { |
| 243 | require_once 'CRM/Utils/Request.php'; |
| 244 | |
| 245 | $type = CRM_Utils_Request::retrieve('type', 'String', CRM_Core_DAO::$_nullObject, FALSE, 'csv', 'REQUEST'); |
| 246 | $type = strtolower($type); |
| 247 | |
| 248 | switch ($type) { |
| 249 | case 'paypal': |
| 250 | $start = CRM_Utils_Request::retrieve('start', 'String', |
| 251 | CRM_Core_DAO::$_nullObject, FALSE, 31, 'REQUEST' |
| 252 | ); |
| 253 | $end = CRM_Utils_Request::retrieve('end', 'String', |
| 254 | CRM_Core_DAO::$_nullObject, FALSE, 0, 'REQUEST' |
| 255 | ); |
| 256 | if ($start < $end) { |
| 257 | throw new CRM_Core_Exception("Start offset can't be less than End offset."); |
| 258 | } |
| 259 | |
| 260 | $start = date('Y-m-d', time() - $start * 24 * 60 * 60) . 'T00:00:00.00Z'; |
| 261 | $end = date('Y-m-d', time() - $end * 24 * 60 * 60) . 'T23:59:00.00Z'; |
| 262 | |
| 263 | $ppID = CRM_Utils_Request::retrieve('ppID', 'Integer', |
| 264 | CRM_Core_DAO::$_nullObject, TRUE, NULL, 'REQUEST' |
| 265 | ); |
| 266 | $mode = CRM_Utils_Request::retrieve('ppMode', 'String', |
| 267 | CRM_Core_DAO::$_nullObject, FALSE, 'live', 'REQUEST' |
| 268 | ); |
| 269 | |
| 270 | $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($ppID, $mode); |
| 271 | |
| 272 | CRM_Core_Error::debug_log_message("Start Date=$start, End Date=$end, ppID=$ppID, mode=$mode <p>", TRUE); |
| 273 | |
| 274 | return self::$type($paymentProcessor, $mode, $start, $end); |
| 275 | |
| 276 | case 'csv': |
| 277 | return self::csv(); |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | /** |
| 282 | * @param array $apiParams |
| 283 | * @param $mapper |
| 284 | * @param string $type |
| 285 | * @param bool $category |
| 286 | * |
| 287 | * @return array |
| 288 | */ |
| 289 | public static function formatAPIParams($apiParams, $mapper, $type = 'paypal', $category = TRUE) { |
| 290 | $type = strtolower($type); |
| 291 | |
| 292 | if (!in_array($type, array( |
| 293 | 'paypal', |
| 294 | 'csv', |
| 295 | )) |
| 296 | ) { |
| 297 | // return the params as is |
| 298 | return $apiParams; |
| 299 | } |
| 300 | $params = $transaction = array(); |
| 301 | |
| 302 | if ($type == 'paypal') { |
| 303 | foreach ($apiParams as $detail => $val) { |
| 304 | if (isset($mapper['contact'][$detail])) { |
| 305 | $params[$mapper['contact'][$detail]] = $val; |
| 306 | } |
| 307 | elseif (isset($mapper['location'][$detail])) { |
| 308 | $params['address'][1][$mapper['location'][$detail]] = $val; |
| 309 | } |
| 310 | elseif (isset($mapper['transaction'][$detail])) { |
| 311 | switch ($detail) { |
| 312 | case 'l_period2': |
| 313 | // Sadly, PayPal seems to send two distinct data elements in a single field, |
| 314 | // so we break them out here. This is somewhat ugly and tragic. |
| 315 | $freqUnits = array( |
| 316 | 'D' => 'day', |
| 317 | 'W' => 'week', |
| 318 | 'M' => 'month', |
| 319 | 'Y' => 'year', |
| 320 | ); |
| 321 | list($frequency_interval, $frequency_unit) = explode(' ', $val); |
| 322 | $transaction['frequency_interval'] = $frequency_interval; |
| 323 | $transaction['frequency_unit'] = $freqUnits[$frequency_unit]; |
| 324 | break; |
| 325 | |
| 326 | case 'subscriptiondate': |
| 327 | case 'timestamp': |
| 328 | // PayPal dates are in ISO-8601 format. We need a format that |
| 329 | // MySQL likes |
| 330 | $unix_timestamp = strtotime($val); |
| 331 | $transaction[$mapper['transaction'][$detail]] = date('YmdHis', $unix_timestamp); |
| 332 | break; |
| 333 | |
| 334 | case 'note': |
| 335 | case 'custom': |
| 336 | case 'l_number0': |
| 337 | if ($val) { |
| 338 | $val = "[PayPal_field:{$detail}] {$val}"; |
| 339 | $transaction[$mapper['transaction'][$detail]] = !empty($transaction[$mapper['transaction'][$detail]]) ? $transaction[$mapper['transaction'][$detail]] . " <br/> " . $val : $val; |
| 340 | } |
| 341 | break; |
| 342 | |
| 343 | default: |
| 344 | $transaction[$mapper['transaction'][$detail]] = $val; |
| 345 | } |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | if (!empty($transaction) && $category) { |
| 350 | $params['transaction'] = $transaction; |
| 351 | } |
| 352 | else { |
| 353 | $params += $transaction; |
| 354 | } |
| 355 | |
| 356 | CRM_Contribute_BAO_Contribution_Utils::_fillCommonParams($params, $type); |
| 357 | |
| 358 | return $params; |
| 359 | } |
| 360 | |
| 361 | if ($type == 'csv') { |
| 362 | $header = $apiParams['header']; |
| 363 | unset($apiParams['header']); |
| 364 | foreach ($apiParams as $key => $val) { |
| 365 | if (isset($mapper['contact'][$header[$key]])) { |
| 366 | $params[$mapper['contact'][$header[$key]]] = $val; |
| 367 | } |
| 368 | elseif (isset($mapper['location'][$header[$key]])) { |
| 369 | $params['address'][1][$mapper['location'][$header[$key]]] = $val; |
| 370 | } |
| 371 | elseif (isset($mapper['transaction'][$header[$key]])) { |
| 372 | $transaction[$mapper['transaction'][$header[$key]]] = $val; |
| 373 | } |
| 374 | else { |
| 375 | $params[$header[$key]] = $val; |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | if (!empty($transaction) && $category) { |
| 380 | $params['transaction'] = $transaction; |
| 381 | } |
| 382 | else { |
| 383 | $params += $transaction; |
| 384 | } |
| 385 | |
| 386 | CRM_Contribute_BAO_Contribution_Utils::_fillCommonParams($params, $type); |
| 387 | |
| 388 | return $params; |
| 389 | } |
| 390 | |
| 391 | } |
| 392 | |
| 393 | /** |
| 394 | * @deprecated function. |
| 395 | * |
| 396 | * This function has probably been defunct for quite a long time. |
| 397 | * |
| 398 | * @param array $params |
| 399 | * |
| 400 | * @return bool |
| 401 | */ |
| 402 | public static function processAPIContribution($params) { |
| 403 | if (empty($params) || array_key_exists('error', $params)) { |
| 404 | return FALSE; |
| 405 | } |
| 406 | |
| 407 | $params['contact_id'] = CRM_Contact_BAO_Contact::getFirstDuplicateContact($params, 'Individual', 'Unsupervised', array(), FALSE); |
| 408 | |
| 409 | $contact = civicrm_api3('Contact', 'create', $params); |
| 410 | |
| 411 | // only pass transaction params to contribution::create, if available |
| 412 | if (array_key_exists('transaction', $params)) { |
| 413 | $params = $params['transaction']; |
| 414 | $params['contact_id'] = $contact['id']; |
| 415 | } |
| 416 | |
| 417 | $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, |
| 418 | CRM_Utils_Array::value('id', $params, NULL), |
| 419 | 'Contribution' |
| 420 | ); |
| 421 | // create contribution |
| 422 | |
| 423 | // if this is a recurring contribution then process it first |
| 424 | if ($params['trxn_type'] == 'subscrpayment') { |
| 425 | // see if a recurring record already exists |
| 426 | $recurring = new CRM_Contribute_BAO_ContributionRecur(); |
| 427 | $recurring->processor_id = $params['processor_id']; |
| 428 | if (!$recurring->find(TRUE)) { |
| 429 | $recurring = new CRM_Contribute_BAO_ContributionRecur(); |
| 430 | $recurring->invoice_id = $params['invoice_id']; |
| 431 | $recurring->find(TRUE); |
| 432 | } |
| 433 | |
| 434 | // This is the same thing the CiviCRM IPN handler does to handle |
| 435 | // subsequent recurring payments to avoid duplicate contribution |
| 436 | // errors due to invoice ID. See: |
| 437 | // ./CRM/Core/Payment/PayPalIPN.php:200 |
| 438 | if ($recurring->id) { |
| 439 | $params['invoice_id'] = md5(uniqid(rand(), TRUE)); |
| 440 | } |
| 441 | |
| 442 | $recurring->copyValues($params); |
| 443 | $recurring->save(); |
| 444 | if (is_a($recurring, 'CRM_Core_Error')) { |
| 445 | return FALSE; |
| 446 | } |
| 447 | else { |
| 448 | $params['contribution_recur_id'] = $recurring->id; |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | $contribution = CRM_Contribute_BAO_Contribution::create($params); |
| 453 | if (!$contribution->id) { |
| 454 | return FALSE; |
| 455 | } |
| 456 | |
| 457 | return TRUE; |
| 458 | } |
| 459 | |
| 460 | } |
| 461 | |
| 462 | // bootstrap the environment and run the processor |
| 463 | session_start(); |
| 464 | require_once '../civicrm.config.php'; |
| 465 | require_once 'CRM/Core/Config.php'; |
| 466 | CRM_Core_Config::singleton(); |
| 467 | |
| 468 | CRM_Utils_System::authenticateScript(TRUE); |
| 469 | |
| 470 | //log the execution of script |
| 471 | CRM_Core_Error::debug_log_message('ContributionProcessor.php'); |
| 472 | |
| 473 | $lock = Civi::lockManager()->acquire('worker.contribute.CiviContributeProcessor'); |
| 474 | |
| 475 | if ($lock->isAcquired()) { |
| 476 | // try to unset any time limits |
| 477 | if (!ini_get('safe_mode')) { |
| 478 | set_time_limit(0); |
| 479 | } |
| 480 | |
| 481 | CiviContributeProcessor::process(); |
| 482 | } |
| 483 | else { |
| 484 | throw new Exception('Could not acquire lock, another CiviContributeProcessor process is running'); |
| 485 | } |
| 486 | |
| 487 | $lock->release(); |
| 488 | |
| 489 | echo "Done processing<p>"; |