CRM_Core_Error - Don't display HTML crash when running tests
[civicrm-core.git] / bin / ContributionProcessor.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
81621fee 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
e7112fa7 31 * @copyright CiviCRM LLC (c) 2004-2015
6a488035
TO
32 */
33class CiviContributeProcessor {
34 static $_paypalParamsMapper = array(
35 //category => array(paypal_param => civicrm_field);
36 'contact' => array(
37 'salutation' => 'prefix_id',
38 'firstname' => 'first_name',
39 'lastname' => 'last_name',
40 'middlename' => 'middle_name',
41 'suffix' => 'suffix_id',
42 'email' => 'email',
43 ),
44 'location' => array(
45 'shiptoname' => 'address_name',
46 'shiptostreet' => 'street_address',
47 'shiptostreet2' => 'supplemental_address_1',
48 'shiptocity' => 'city',
49 'shiptostate' => 'state_province',
50 'shiptozip' => 'postal_code',
51 'countrycode' => 'country',
52 ),
53 'transaction' => array(
54 'amt' => 'total_amount',
55 'feeamt' => 'fee_amount',
56 'transactionid' => 'trxn_id',
57 'currencycode' => 'currency',
58 'l_name0' => 'source',
59 'ordertime' => 'receive_date',
60 'note' => 'note',
61 'custom' => 'note',
62 'l_number0' => 'note',
63 'is_test' => 'is_test',
64 'transactiontype' => 'trxn_type',
65 'recurrences' => 'installments',
66 'l_amt2' => 'amount',
67 'l_period2' => 'lol',
68 'invnum' => 'invoice_id',
69 'subscriptiondate' => 'start_date',
70 'subscriptionid' => 'processor_id',
71 'timestamp' => 'modified_date',
72 ),
73 );
74
75 static $_googleParamsMapper = array(
76 //category => array(google_param => civicrm_field);
77 'contact' => array(
78 'first-name' => 'first_name',
79 'last-name' => 'last_name',
80 'contact-name' => 'display_name',
81 'email' => 'email',
82 ),
83 'location' => array(
84 'address1' => 'street_address',
85 'address2' => 'supplemental_address_1',
86 'city' => 'city',
87 'postal-code' => 'postal_code',
88 'country-code' => 'country',
89 ),
90 'transaction' => array(
91 'total-charge-amount' => 'total_amount',
92 'google-order-number' => 'trxn_id',
93 'currency' => 'currency',
94 'item-name' => 'source',
95 'item-description' => 'note',
96 'timestamp' => 'receive_date',
97 'latest-charge-fee' => 'fee_amount',
98 'net-amount' => 'net_amount',
99 'times' => 'installments',
100 'period' => 'frequency_unit',
101 'frequency_interval' => 'frequency_interval',
102 'start_date' => 'start_date',
103 'modified_date' => 'modified_date',
104 'trxn_type' => 'trxn_type',
105 'amount' => 'amount',
106 ),
107 );
108
109 static $_csvParamsMapper = array(
110 // Note: if csv header is not present in the mapper, header itself
111 // is considered as a civicrm field.
112 //category => array(csv_header => civicrm_field);
113 'contact' => array(
114 'first_name' => 'first_name',
115 'last_name' => 'last_name',
116 'middle_name' => 'middle_name',
117 'email' => 'email',
118 ),
119 'location' => array(
120 'street_address' => 'street_address',
121 'supplemental_address_1' => 'supplemental_address_1',
122 'city' => 'city',
123 'postal_code' => 'postal_code',
124 'country' => 'country',
125 ),
126 'transaction' => array(
127 'total_amount' => 'total_amount',
128 'trxn_id' => 'trxn_id',
129 'currency' => 'currency',
130 'source' => 'source',
131 'receive_date' => 'receive_date',
132 'note' => 'note',
133 'is_test' => 'is_test',
134 ),
135 );
136
4e87860d
EM
137 /**
138 * @param $paymentProcessor
139 * @param $paymentMode
140 * @param $start
141 * @param $end
142 */
3bdca100 143 public static function paypal($paymentProcessor, $paymentMode, $start, $end) {
6a488035
TO
144 $url = "{$paymentProcessor['url_api']}nvp";
145
146 $keyArgs = array(
147 'user' => $paymentProcessor['user_name'],
148 'pwd' => $paymentProcessor['password'],
149 'signature' => $paymentProcessor['signature'],
150 'version' => 3.0,
151 );
152
153 $args = $keyArgs;
154 $args += array(
155 'method' => 'TransactionSearch',
156 'startdate' => $start,
157 'enddate' => $end,
158 );
159
160 require_once 'CRM/Core/Payment/PayPalImpl.php';
161
162 // as invokeAPI fetch only last 100 transactions.
163 // we should require recursive calls to process more than 100.
164 // first fetch transactions w/ give date intervals.
165 // if we get error code w/ result, which means we do have more than 100
166 // manipulate date interval accordingly and fetch again.
167
168 do {
169 $result = CRM_Core_Payment_PayPalImpl::invokeAPI($args, $url);
170 require_once "CRM/Contribute/BAO/Contribution/Utils.php";
171
172 $keyArgs['method'] = 'GetTransactionDetails';
173 foreach ($result as $name => $value) {
174 if (substr($name, 0, 15) == 'l_transactionid') {
175
176 // We don't/can't process subscription notifications, which appear
177 // to be identified by transaction ids beginning with S-
178 if (substr($value, 0, 2) == 'S-') {
179 continue;
180 }
181
182 // Before we bother making a remote API call to PayPal to lookup
183 // details about a transaction, let's make sure that it doesn't
184 // already exist in the database.
185 require_once 'CRM/Contribute/DAO/Contribution.php';
3bdca100 186 $dao = new CRM_Contribute_DAO_Contribution();
6a488035
TO
187 $dao->trxn_id = $value;
188 if ($dao->find(TRUE)) {
189 preg_match('/(\d+)$/', $name, $matches);
56fdfc52 190 $seq = $matches[1];
6a488035 191 $email = $result["l_email{$seq}"];
56fdfc52 192 $amt = $result["l_amt{$seq}"];
6a488035
TO
193 CRM_Core_Error::debug_log_message("Skipped (already recorded) - $email, $amt, $value ..<p>", TRUE);
194 continue;
195 }
196
197 $keyArgs['transactionid'] = $value;
198 $trxnDetails = CRM_Core_Payment_PayPalImpl::invokeAPI($keyArgs, $url);
199 if (is_a($trxnDetails, 'CRM_Core_Error')) {
200 echo "PAYPAL ERROR: Skipping transaction id: $value<p>";
201 continue;
202 }
203
204 // only process completed payments
205 if (strtolower($trxnDetails['paymentstatus']) != 'completed') {
206 continue;
207 }
208
209 // only process receipts, not payments
210 if (strtolower($trxnDetails['transactiontype']) == 'sendmoney') {
211 continue;
212 }
213
3c536a11 214 $params = self::formatAPIParams($trxnDetails,
6a488035
TO
215 self::$_paypalParamsMapper,
216 'paypal'
217 );
218 if ($paymentMode == 'test') {
219 $params['transaction']['is_test'] = 1;
220 }
221 else {
222 $params['transaction']['is_test'] = 0;
223 }
224
3c536a11 225 if (self::processAPIContribution($params)) {
6a488035
TO
226 CRM_Core_Error::debug_log_message("Processed - {$trxnDetails['email']}, {$trxnDetails['amt']}, {$value} ..<p>", TRUE);
227 }
228 else {
229 CRM_Core_Error::debug_log_message("Skipped - {$trxnDetails['email']}, {$trxnDetails['amt']}, {$value} ..<p>", TRUE);
230 }
231 }
232 }
233 if ($result['l_errorcode0'] == '11002') {
56fdfc52
TO
234 $end = $result['l_timestamp99'];
235 $end_time = strtotime("{$end}", time());
236 $end_date = date('Y-m-d\T00:00:00.00\Z', $end_time);
6a488035
TO
237 $args['enddate'] = $end_date;
238 }
239 } while ($result['l_errorcode0'] == '11002');
240 }
241
4e87860d
EM
242 /**
243 * @param $paymentProcessor
244 * @param $paymentMode
245 * @param $start
246 * @param $end
247 */
3bdca100 248 public static function google($paymentProcessor, $paymentMode, $start, $end) {
6a488035
TO
249 require_once "CRM/Contribute/BAO/Contribution/Utils.php";
250 require_once 'CRM/Core/Payment/Google.php';
251 $nextPageToken = TRUE;
252 $searchParams = array(
253 'start' => $start,
254 'end' => $end,
255 'notification-types' => array('charge-amount'),
256 );
257
258 $response = CRM_Core_Payment_Google::invokeAPI($paymentProcessor, $searchParams);
259
260 while ($nextPageToken) {
261 if ($response[0] == 'error') {
262 CRM_Core_Error::debug_log_message("GOOGLE ERROR: " .
263 $response[1]['error']['error-message']['VALUE'], TRUE
264 );
265 }
266 $nextPageToken = isset($response[1][$response[0]]['next-page-token']['VALUE']) ? $response[1][$response[0]]['next-page-token']['VALUE'] : FALSE;
267
268 if (is_array($response[1][$response[0]]['notifications']['charge-amount-notification'])) {
269
270 if (array_key_exists('google-order-number',
56fdfc52
TO
271 $response[1][$response[0]]['notifications']['charge-amount-notification']
272 )) {
6a488035
TO
273 // sometimes 'charge-amount-notification' itself is an absolute
274 // array and not array of arrays. This is the case when there is only one
275 // charge-amount-notification. Hack for this special case -
276 $chrgAmt = $response[1][$response[0]]['notifications']['charge-amount-notification'];
277 unset($response[1][$response[0]]['notifications']['charge-amount-notification']);
278 $response[1][$response[0]]['notifications']['charge-amount-notification'][] = $chrgAmt;
279 }
280
3bdca100 281 foreach ($response[1][$response[0]]['notifications']['charge-amount-notification'] as $amtData) {
a9e80afc 282 $searchParams = array(
56fdfc52 283 'order-numbers' => array($amtData['google-order-number']['VALUE']),
6a488035
TO
284 'notification-types' => array('risk-information', 'new-order', 'charge-amount'),
285 );
286 $response = CRM_Core_Payment_Google::invokeAPI($paymentProcessor,
287 $searchParams
288 );
289 // append amount information as well
290 $response[] = $amtData;
291
3c536a11 292 $params = self::formatAPIParams($response,
6a488035
TO
293 self::$_googleParamsMapper,
294 'google'
295 );
296 if ($paymentMode == 'test') {
297 $params['transaction']['is_test'] = 1;
298 }
299 else {
300 $params['transaction']['is_test'] = 0;
301 }
3c536a11 302 if (self::processAPIContribution($params)) {
6a488035
TO
303 CRM_Core_Error::debug_log_message("Processed - {$params['email']}, {$amtData['total-charge-amount']['VALUE']}, {$amtData['google-order-number']['VALUE']} ..<p>", TRUE);
304 }
305 else {
306 CRM_Core_Error::debug_log_message("Skipped - {$params['email']}, {$amtData['total-charge-amount']['VALUE']}, {$amtData['google-order-number']['VALUE']} ..<p>", TRUE);
307 }
308 }
309
310 if ($nextPageToken) {
311 $searchParams = array('next-page-token' => $nextPageToken);
312 $response = CRM_Core_Payment_Google::invokeAPI($paymentProcessor, $searchParams);
313 }
314 }
315 }
316 }
317
3bdca100 318 public static function csv() {
56fdfc52 319 $csvFile = '/home/deepak/Desktop/crm-4247.csv';
6a488035 320 $delimiter = ";";
56fdfc52 321 $row = 1;
6a488035
TO
322
323 $handle = fopen($csvFile, "r");
324 if (!$handle) {
325 CRM_Core_Error::fatal("Can't locate csv file.");
326 }
327
328 require_once "CRM/Contribute/BAO/Contribution/Utils.php";
329 while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
330 if ($row !== 1) {
331 $data['header'] = $header;
3c536a11 332 $params = self::formatAPIParams($data,
6a488035
TO
333 self::$_csvParamsMapper,
334 'csv'
335 );
3c536a11 336 if (self::processAPIContribution($params)) {
6a488035
TO
337 CRM_Core_Error::debug_log_message("Processed - line $row of csv file .. {$params['email']}, {$params['transaction']['total_amount']}, {$params['transaction']['trxn_id']} ..<p>", TRUE);
338 }
339 else {
340 CRM_Core_Error::debug_log_message("Skipped - line $row of csv file .. {$params['email']}, {$params['transaction']['total_amount']}, {$params['transaction']['trxn_id']} ..<p>", TRUE);
341 }
342
343 // clean up memory from dao's
344 CRM_Core_DAO::freeResult();
345 }
346 else {
347 // we assuming - first row is always the header line
348 $header = $data;
349 CRM_Core_Error::debug_log_message("Considering first row ( line $row ) as HEADER ..<p>", TRUE);
350
351 if (empty($header)) {
352 CRM_Core_Error::fatal("Header is empty.");
353 }
354 }
355 $row++;
356 }
357 fclose($handle);
358 }
359
3bdca100 360 public static function process() {
6a488035
TO
361 require_once 'CRM/Utils/Request.php';
362
363 $type = CRM_Utils_Request::retrieve('type', 'String', CRM_Core_DAO::$_nullObject, FALSE, 'csv', 'REQUEST');
364 $type = strtolower($type);
365
366 switch ($type) {
367 case 'paypal':
368 case 'google':
369 $start = CRM_Utils_Request::retrieve('start', 'String',
370 CRM_Core_DAO::$_nullObject, FALSE, 31, 'REQUEST'
371 );
372 $end = CRM_Utils_Request::retrieve('end', 'String',
373 CRM_Core_DAO::$_nullObject, FALSE, 0, 'REQUEST'
374 );
375 if ($start < $end) {
376 CRM_Core_Error::fatal("Start offset can't be less than End offset.");
377 }
378
379 $start = date('Y-m-d', time() - $start * 24 * 60 * 60) . 'T00:00:00.00Z';
380 $end = date('Y-m-d', time() - $end * 24 * 60 * 60) . 'T23:59:00.00Z';
381
382 $ppID = CRM_Utils_Request::retrieve('ppID', 'Integer',
383 CRM_Core_DAO::$_nullObject, TRUE, NULL, 'REQUEST'
384 );
385 $mode = CRM_Utils_Request::retrieve('ppMode', 'String',
386 CRM_Core_DAO::$_nullObject, FALSE, 'live', 'REQUEST'
387 );
388
6a488035
TO
389 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($ppID, $mode);
390
391 CRM_Core_Error::debug_log_message("Start Date=$start, End Date=$end, ppID=$ppID, mode=$mode <p>", TRUE);
392
393 return self::$type($paymentProcessor, $mode, $start, $end);
394
395 case 'csv':
396 return self::csv();
397 }
398 }
96025800 399
3c536a11
EM
400 /**
401 * @param array $apiParams
402 * @param $mapper
403 * @param string $type
404 * @param bool $category
405 *
406 * @return array
407 */
408 public static function formatAPIParams($apiParams, $mapper, $type = 'paypal', $category = TRUE) {
409 $type = strtolower($type);
410
411 if (!in_array($type, array(
412 'paypal',
413 'google',
414 'csv',
415 ))
416 ) {
417 // return the params as is
418 return $apiParams;
419 }
420 $params = $transaction = array();
421
422 if ($type == 'paypal') {
423 foreach ($apiParams as $detail => $val) {
424 if (isset($mapper['contact'][$detail])) {
425 $params[$mapper['contact'][$detail]] = $val;
426 }
427 elseif (isset($mapper['location'][$detail])) {
428 $params['address'][1][$mapper['location'][$detail]] = $val;
429 }
430 elseif (isset($mapper['transaction'][$detail])) {
431 switch ($detail) {
432 case 'l_period2':
433 // Sadly, PayPal seems to send two distinct data elements in a single field,
434 // so we break them out here. This is somewhat ugly and tragic.
435 $freqUnits = array(
436 'D' => 'day',
437 'W' => 'week',
438 'M' => 'month',
439 'Y' => 'year',
440 );
441 list($frequency_interval, $frequency_unit) = explode(' ', $val);
442 $transaction['frequency_interval'] = $frequency_interval;
443 $transaction['frequency_unit'] = $freqUnits[$frequency_unit];
444 break;
445
446 case 'subscriptiondate':
447 case 'timestamp':
448 // PayPal dates are in ISO-8601 format. We need a format that
449 // MySQL likes
450 $unix_timestamp = strtotime($val);
451 $transaction[$mapper['transaction'][$detail]] = date('YmdHis', $unix_timestamp);
452 break;
453
454 case 'note':
455 case 'custom':
456 case 'l_number0':
457 if ($val) {
458 $val = "[PayPal_field:{$detail}] {$val}";
459 $transaction[$mapper['transaction'][$detail]] = !empty($transaction[$mapper['transaction'][$detail]]) ? $transaction[$mapper['transaction'][$detail]] . " <br/> " . $val : $val;
460 }
461 break;
462
463 default:
464 $transaction[$mapper['transaction'][$detail]] = $val;
465 }
466 }
467 }
468
469 if (!empty($transaction) && $category) {
470 $params['transaction'] = $transaction;
471 }
472 else {
473 $params += $transaction;
474 }
475
476 CRM_Contribute_BAO_Contribution_Utils::_fillCommonParams($params, $type);
477
478 return $params;
479 }
480
481 if ($type == 'csv') {
482 $header = $apiParams['header'];
483 unset($apiParams['header']);
484 foreach ($apiParams as $key => $val) {
485 if (isset($mapper['contact'][$header[$key]])) {
486 $params[$mapper['contact'][$header[$key]]] = $val;
487 }
488 elseif (isset($mapper['location'][$header[$key]])) {
489 $params['address'][1][$mapper['location'][$header[$key]]] = $val;
490 }
491 elseif (isset($mapper['transaction'][$header[$key]])) {
492 $transaction[$mapper['transaction'][$header[$key]]] = $val;
493 }
494 else {
495 $params[$header[$key]] = $val;
496 }
497 }
498
499 if (!empty($transaction) && $category) {
500 $params['transaction'] = $transaction;
501 }
502 else {
503 $params += $transaction;
504 }
505
506 CRM_Contribute_BAO_Contribution_Utils::_fillCommonParams($params, $type);
507
508 return $params;
509 }
510
511 if ($type == 'google') {
512 // return if response smell invalid
513 if (!array_key_exists('risk-information-notification', $apiParams[1][$apiParams[0]]['notifications'])) {
514 return FALSE;
515 }
516 $riskInfo = &$apiParams[1][$apiParams[0]]['notifications']['risk-information-notification'];
517
518 if (array_key_exists('new-order-notification', $apiParams[1][$apiParams[0]]['notifications'])) {
519 $newOrder = &$apiParams[1][$apiParams[0]]['notifications']['new-order-notification'];
520 }
521
522 if ($riskInfo['google-order-number']['VALUE'] == $apiParams[2]['google-order-number']['VALUE']) {
523 foreach ($riskInfo['risk-information']['billing-address'] as $field => $info) {
524 if (!empty($mapper['location'][$field])) {
525 $params['address'][1][$mapper['location'][$field]] = $info['VALUE'];
526 }
527 elseif (!empty($mapper['contact'][$field])) {
528 if ($newOrder && !empty($newOrder['buyer-billing-address']['structured-name'])) {
529 foreach ($newOrder['buyer-billing-address']['structured-name'] as $namePart => $nameValue) {
530 $params[$mapper['contact'][$namePart]] = $nameValue['VALUE'];
531 }
532 }
533 else {
534 $params[$mapper['contact'][$field]] = $info['VALUE'];
535 }
536 }
537 elseif (!empty($mapper['transaction'][$field])) {
538 $transaction[$mapper['transaction'][$field]] = $info['VALUE'];
539 }
540 }
541
542 // Response is an huge array. Lets pickup only those which we ineterested in
543 // using a local mapper, rather than traversing the entire array.
544 $localMapper = array(
545 'google-order-number' => $riskInfo['google-order-number']['VALUE'],
546 'total-charge-amount' => $apiParams[2]['total-charge-amount']['VALUE'],
547 'currency' => $apiParams[2]['total-charge-amount']['currency'],
548 'item-name' => $newOrder['shopping-cart']['items']['item']['item-name']['VALUE'],
549 'timestamp' => $apiParams[2]['timestamp']['VALUE'],
550 );
551 if (array_key_exists('latest-charge-fee', $apiParams[2])) {
552 $localMapper['latest-charge-fee'] = $apiParams[2]['latest-charge-fee']['total']['VALUE'];
553 $localMapper['net-amount'] = $localMapper['total-charge-amount'] - $localMapper['latest-charge-fee'];
554 }
555
556 // This is a subscription (recurring) donation.
557 if (array_key_exists('subscription', $newOrder['shopping-cart']['items']['item'])) {
558 $subscription = $newOrder['shopping-cart']['items']['item']['subscription'];
559 $localMapper['amount'] = $newOrder['order-total']['VALUE'];
560 $localMapper['times'] = $subscription['payments']['subscription-payment']['times'];
561 // Convert Google's period to one compatible with the CiviCRM db field.
562 $freqUnits = array(
563 'DAILY' => 'day',
564 'WEEKLY' => 'week',
565 'MONHTLY' => 'month',
566 'YEARLY' => 'year',
567 );
568 $localMapper['period'] = $freqUnits[$subscription['period']];
569 // Unlike PayPal, Google has no concept of freq. interval, it is always 1.
570 $localMapper['frequency_interval'] = '1';
571 // Google Checkout dates are in ISO-8601 format. We need a format that
572 // MySQL likes
573 $unix_timestamp = strtotime($localMapper['timestamp']);
574 $mysql_date = date('YmdHis', $unix_timestamp);
575 $localMapper['modified_date'] = $mysql_date;
576 $localMapper['start_date'] = $mysql_date;
577 // This is PayPal's nomenclature, but just use it for Google as well since
578 // we act on the value of trxn_type in processAPIContribution().
579 $localMapper['trxn_type'] = 'subscrpayment';
580 }
581
582 foreach ($localMapper as $localKey => $localVal) {
583 if (!empty($mapper['transaction'][$localKey])) {
584 $transaction[$mapper['transaction'][$localKey]] = $localVal;
585 }
586 }
587
588 if (empty($params) && empty($transaction)) {
589 continue;
590 }
591
592 if (!empty($transaction) && $category) {
593 $params['transaction'] = $transaction;
594 }
595 else {
596 $params += $transaction;
597 }
598
599 CRM_Contribute_BAO_Contribution_Utils::_fillCommonParams($params, $type);
600 }
601 return $params;
602 }
603 }
604
605 /**
606 * @param array $params
607 *
608 * @return bool
609 */
610 public static function processAPIContribution($params) {
611 if (empty($params) || array_key_exists('error', $params)) {
612 return FALSE;
613 }
614
615 // add contact using dedupe rule
616 $dedupeParams = CRM_Dedupe_Finder::formatParams($params, 'Individual');
617 $dedupeParams['check_permission'] = FALSE;
618 $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
619 // if we find more than one contact, use the first one
620 if (!empty($dupeIds[0])) {
621 $params['contact_id'] = $dupeIds[0];
622 }
623 $contact = CRM_Contact_BAO_Contact::create($params);
624 if (!$contact->id) {
625 return FALSE;
626 }
627
628 // only pass transaction params to contribution::create, if available
629 if (array_key_exists('transaction', $params)) {
630 $params = $params['transaction'];
631 $params['contact_id'] = $contact->id;
632 }
633
634 // handle contribution custom data
635 $customFields = CRM_Core_BAO_CustomField::getFields('Contribution',
636 FALSE,
637 FALSE,
638 CRM_Utils_Array::value('financial_type_id',
639 $params
640 )
641 );
642 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
643 CRM_Utils_Array::value('id', $params, NULL),
644 'Contribution'
645 );
646 // create contribution
647
648 // if this is a recurring contribution then process it first
649 if ($params['trxn_type'] == 'subscrpayment') {
650 // see if a recurring record already exists
651 $recurring = new CRM_Contribute_BAO_ContributionRecur();
652 $recurring->processor_id = $params['processor_id'];
653 if (!$recurring->find(TRUE)) {
654 $recurring = new CRM_Contribute_BAO_ContributionRecur();
655 $recurring->invoice_id = $params['invoice_id'];
656 $recurring->find(TRUE);
657 }
658
659 // This is the same thing the CiviCRM IPN handler does to handle
660 // subsequent recurring payments to avoid duplicate contribution
661 // errors due to invoice ID. See:
662 // ./CRM/Core/Payment/PayPalIPN.php:200
663 if ($recurring->id) {
664 $params['invoice_id'] = md5(uniqid(rand(), TRUE));
665 }
666
667 $recurring->copyValues($params);
668 $recurring->save();
669 if (is_a($recurring, 'CRM_Core_Error')) {
670 return FALSE;
671 }
672 else {
673 $params['contribution_recur_id'] = $recurring->id;
674 }
675 }
676
677 $contribution = &CRM_Contribute_BAO_Contribution::create($params,
678 CRM_Core_DAO::$_nullArray
679 );
680 if (!$contribution->id) {
681 return FALSE;
682 }
683
684 return TRUE;
685 }
686
6a488035
TO
687}
688
689// bootstrap the environment and run the processor
690session_start();
691require_once '../civicrm.config.php';
692require_once 'CRM/Core/Config.php';
693$config = CRM_Core_Config::singleton();
694
695CRM_Utils_System::authenticateScript(TRUE);
696
697//log the execution of script
698CRM_Core_Error::debug_log_message('ContributionProcessor.php');
699
048222df 700$lock = Civi::service('lockManager')->acquire('worker.contribute.CiviContributeProcessor');
6a488035
TO
701
702if ($lock->isAcquired()) {
703 // try to unset any time limits
704 if (!ini_get('safe_mode')) {
705 set_time_limit(0);
706 }
707
708 CiviContributeProcessor::process();
709}
710else {
33c5988b 711 throw new Exception('Could not acquire lock, another CiviContributeProcessor process is running');
6a488035
TO
712}
713
714$lock->release();
715
716echo "Done processing<p>";