province abbreviation patch - issue 724
[civicrm-core.git] / bin / ContributionProcessor.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
6b7eb9df 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
6b7eb9df
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17class CiviContributeProcessor {
683bf891 18 public static $_paypalParamsMapper = array(
6a488035
TO
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
683bf891
SL
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(
6a488035
TO
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
4e87860d
EM
90 /**
91 * @param $paymentProcessor
92 * @param $paymentMode
93 * @param $start
94 * @param $end
95 */
3bdca100 96 public static function paypal($paymentProcessor, $paymentMode, $start, $end) {
6a488035
TO
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';
3bdca100 139 $dao = new CRM_Contribute_DAO_Contribution();
6a488035
TO
140 $dao->trxn_id = $value;
141 if ($dao->find(TRUE)) {
142 preg_match('/(\d+)$/', $name, $matches);
56fdfc52 143 $seq = $matches[1];
6a488035 144 $email = $result["l_email{$seq}"];
56fdfc52 145 $amt = $result["l_amt{$seq}"];
6a488035
TO
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
3c536a11 167 $params = self::formatAPIParams($trxnDetails,
6a488035
TO
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
fedc3428 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 }
6a488035 185 }
fedc3428 186 catch (CiviCRM_API3_Exception $e) {
6a488035
TO
187 CRM_Core_Error::debug_log_message("Skipped - {$trxnDetails['email']}, {$trxnDetails['amt']}, {$value} ..<p>", TRUE);
188 }
189 }
190 }
191 if ($result['l_errorcode0'] == '11002') {
56fdfc52
TO
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);
6a488035
TO
195 $args['enddate'] = $end_date;
196 }
197 } while ($result['l_errorcode0'] == '11002');
198 }
199
3bdca100 200 public static function csv() {
56fdfc52 201 $csvFile = '/home/deepak/Desktop/crm-4247.csv';
6a488035 202 $delimiter = ";";
56fdfc52 203 $row = 1;
6a488035
TO
204
205 $handle = fopen($csvFile, "r");
206 if (!$handle) {
ee3db087 207 throw new CRM_Core_Exception("Can't locate csv file.");
6a488035
TO
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;
3c536a11 214 $params = self::formatAPIParams($data,
6a488035
TO
215 self::$_csvParamsMapper,
216 'csv'
217 );
3c536a11 218 if (self::processAPIContribution($params)) {
6a488035
TO
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)) {
ee3db087 234 throw new CRM_Core_Exception("Header is empty.");
6a488035
TO
235 }
236 }
237 $row++;
238 }
239 fclose($handle);
240 }
241
3bdca100 242 public static function process() {
6a488035
TO
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':
6a488035
TO
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) {
ee3db087 257 throw new CRM_Core_Exception("Start offset can't be less than End offset.");
6a488035
TO
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
6a488035
TO
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 }
96025800 280
3c536a11
EM
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',
3c536a11
EM
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
9e60c4e1 356 self::_fillCommonParams($params, $type);
3c536a11
EM
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
9e60c4e1 386 self::_fillCommonParams($params, $type);
3c536a11
EM
387
388 return $params;
389 }
390
3c536a11
EM
391 }
392
393 /**
fedc3428 394 * @deprecated function.
395 *
396 * This function has probably been defunct for quite a long time.
397 *
3c536a11
EM
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
fedc3428 407 $params['contact_id'] = CRM_Contact_BAO_Contact::getFirstDuplicateContact($params, 'Individual', 'Unsupervised', array(), FALSE);
408
409 $contact = civicrm_api3('Contact', 'create', $params);
3c536a11
EM
410
411 // only pass transaction params to contribution::create, if available
412 if (array_key_exists('transaction', $params)) {
413 $params = $params['transaction'];
fedc3428 414 $params['contact_id'] = $contact['id'];
3c536a11
EM
415 }
416
3c536a11
EM
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
33621c4f 452 $contribution = CRM_Contribute_BAO_Contribution::create($params);
3c536a11
EM
453 if (!$contribution->id) {
454 return FALSE;
455 }
456
457 return TRUE;
458 }
459
9e60c4e1 460 /**
461 * @param array $params
462 * @param string $type
463 *
464 * @return bool
465 */
466 public static function _fillCommonParams(&$params, $type = 'paypal') {
467 if (array_key_exists('transaction', $params)) {
468 $transaction = &$params['transaction'];
469 }
470 else {
471 $transaction = &$params;
472 }
473
474 $params['contact_type'] = 'Individual';
475
476 $billingLocTypeId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', 'Billing', 'id', 'name');
477 if (!$billingLocTypeId) {
478 $billingLocTypeId = 1;
479 }
480 if (!CRM_Utils_System::isNull($params['address'])) {
481 $params['address'][1]['is_primary'] = 1;
482 $params['address'][1]['location_type_id'] = $billingLocTypeId;
483 }
484 if (!CRM_Utils_System::isNull($params['email'])) {
485 $params['email'] = [
486 1 => [
487 'email' => $params['email'],
488 'location_type_id' => $billingLocTypeId,
489 ],
490 ];
491 }
492
493 if (isset($transaction['trxn_id'])) {
494 // set error message if transaction has already been processed.
495 $contribution = new CRM_Contribute_DAO_Contribution();
496 $contribution->trxn_id = $transaction['trxn_id'];
497 if ($contribution->find(TRUE)) {
498 $params['error'][] = ts('transaction already processed.');
499 }
500 }
501 else {
502 // generate a new transaction id, if not already exist
503 $transaction['trxn_id'] = md5(uniqid(rand(), TRUE));
504 }
505
506 if (!isset($transaction['financial_type_id'])) {
507 $contributionTypes = array_keys(CRM_Contribute_PseudoConstant::financialType());
508 $transaction['financial_type_id'] = $contributionTypes[0];
509 }
510
511 if (($type == 'paypal') && (!isset($transaction['net_amount']))) {
512 $transaction['net_amount'] = $transaction['total_amount'] - CRM_Utils_Array::value('fee_amount', $transaction, 0);
513 }
514
515 if (!isset($transaction['invoice_id'])) {
516 $transaction['invoice_id'] = $transaction['trxn_id'];
517 }
518
519 $source = ts('ContributionProcessor: %1 API',
520 [1 => ucfirst($type)]
521 );
522 if (isset($transaction['source'])) {
523 $transaction['source'] = $source . ':: ' . $transaction['source'];
524 }
525 else {
526 $transaction['source'] = $source;
527 }
528
529 return TRUE;
530 }
531
6a488035
TO
532}
533
534// bootstrap the environment and run the processor
535session_start();
536require_once '../civicrm.config.php';
537require_once 'CRM/Core/Config.php';
d523d24a 538CRM_Core_Config::singleton();
6a488035
TO
539
540CRM_Utils_System::authenticateScript(TRUE);
541
542//log the execution of script
543CRM_Core_Error::debug_log_message('ContributionProcessor.php');
544
83617886 545$lock = Civi::lockManager()->acquire('worker.contribute.CiviContributeProcessor');
6a488035
TO
546
547if ($lock->isAcquired()) {
4d03ddb9 548 set_time_limit(0);
6a488035
TO
549
550 CiviContributeProcessor::process();
551}
552else {
33c5988b 553 throw new Exception('Could not acquire lock, another CiviContributeProcessor process is running');
6a488035
TO
554}
555
556$lock->release();
557
558echo "Done processing<p>";