INFRA-132 - tests/ - PHPStorm cleanup
[civicrm-core.git] / bin / ContributionProcessor.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
f5721b07 6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
f5721b07 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35class CiviContributeProcessor {
36 static $_paypalParamsMapper = array(
37 //category => array(paypal_param => civicrm_field);
38 'contact' => array(
39 'salutation' => 'prefix_id',
40 'firstname' => 'first_name',
41 'lastname' => 'last_name',
42 'middlename' => 'middle_name',
43 'suffix' => 'suffix_id',
44 'email' => 'email',
45 ),
46 'location' => array(
47 'shiptoname' => 'address_name',
48 'shiptostreet' => 'street_address',
49 'shiptostreet2' => 'supplemental_address_1',
50 'shiptocity' => 'city',
51 'shiptostate' => 'state_province',
52 'shiptozip' => 'postal_code',
53 'countrycode' => 'country',
54 ),
55 'transaction' => array(
56 'amt' => 'total_amount',
57 'feeamt' => 'fee_amount',
58 'transactionid' => 'trxn_id',
59 'currencycode' => 'currency',
60 'l_name0' => 'source',
61 'ordertime' => 'receive_date',
62 'note' => 'note',
63 'custom' => 'note',
64 'l_number0' => 'note',
65 'is_test' => 'is_test',
66 'transactiontype' => 'trxn_type',
67 'recurrences' => 'installments',
68 'l_amt2' => 'amount',
69 'l_period2' => 'lol',
70 'invnum' => 'invoice_id',
71 'subscriptiondate' => 'start_date',
72 'subscriptionid' => 'processor_id',
73 'timestamp' => 'modified_date',
74 ),
75 );
76
77 static $_googleParamsMapper = array(
78 //category => array(google_param => civicrm_field);
79 'contact' => array(
80 'first-name' => 'first_name',
81 'last-name' => 'last_name',
82 'contact-name' => 'display_name',
83 'email' => 'email',
84 ),
85 'location' => array(
86 'address1' => 'street_address',
87 'address2' => 'supplemental_address_1',
88 'city' => 'city',
89 'postal-code' => 'postal_code',
90 'country-code' => 'country',
91 ),
92 'transaction' => array(
93 'total-charge-amount' => 'total_amount',
94 'google-order-number' => 'trxn_id',
95 'currency' => 'currency',
96 'item-name' => 'source',
97 'item-description' => 'note',
98 'timestamp' => 'receive_date',
99 'latest-charge-fee' => 'fee_amount',
100 'net-amount' => 'net_amount',
101 'times' => 'installments',
102 'period' => 'frequency_unit',
103 'frequency_interval' => 'frequency_interval',
104 'start_date' => 'start_date',
105 'modified_date' => 'modified_date',
106 'trxn_type' => 'trxn_type',
107 'amount' => 'amount',
108 ),
109 );
110
111 static $_csvParamsMapper = array(
112 // Note: if csv header is not present in the mapper, header itself
113 // is considered as a civicrm field.
114 //category => array(csv_header => civicrm_field);
115 'contact' => array(
116 'first_name' => 'first_name',
117 'last_name' => 'last_name',
118 'middle_name' => 'middle_name',
119 'email' => 'email',
120 ),
121 'location' => array(
122 'street_address' => 'street_address',
123 'supplemental_address_1' => 'supplemental_address_1',
124 'city' => 'city',
125 'postal_code' => 'postal_code',
126 'country' => 'country',
127 ),
128 'transaction' => array(
129 'total_amount' => 'total_amount',
130 'trxn_id' => 'trxn_id',
131 'currency' => 'currency',
132 'source' => 'source',
133 'receive_date' => 'receive_date',
134 'note' => 'note',
135 'is_test' => 'is_test',
136 ),
137 );
138
4e87860d
EM
139 /**
140 * @param $paymentProcessor
141 * @param $paymentMode
142 * @param $start
143 * @param $end
144 */
6a488035
TO
145 static
146 function paypal($paymentProcessor, $paymentMode, $start, $end) {
147 $url = "{$paymentProcessor['url_api']}nvp";
148
149 $keyArgs = array(
150 'user' => $paymentProcessor['user_name'],
151 'pwd' => $paymentProcessor['password'],
152 'signature' => $paymentProcessor['signature'],
153 'version' => 3.0,
154 );
155
156 $args = $keyArgs;
157 $args += array(
158 'method' => 'TransactionSearch',
159 'startdate' => $start,
160 'enddate' => $end,
161 );
162
163 require_once 'CRM/Core/Payment/PayPalImpl.php';
164
165 // as invokeAPI fetch only last 100 transactions.
166 // we should require recursive calls to process more than 100.
167 // first fetch transactions w/ give date intervals.
168 // if we get error code w/ result, which means we do have more than 100
169 // manipulate date interval accordingly and fetch again.
170
171 do {
172 $result = CRM_Core_Payment_PayPalImpl::invokeAPI($args, $url);
173 require_once "CRM/Contribute/BAO/Contribution/Utils.php";
174
175 $keyArgs['method'] = 'GetTransactionDetails';
176 foreach ($result as $name => $value) {
177 if (substr($name, 0, 15) == 'l_transactionid') {
178
179 // We don't/can't process subscription notifications, which appear
180 // to be identified by transaction ids beginning with S-
181 if (substr($value, 0, 2) == 'S-') {
182 continue;
183 }
184
185 // Before we bother making a remote API call to PayPal to lookup
186 // details about a transaction, let's make sure that it doesn't
187 // already exist in the database.
188 require_once 'CRM/Contribute/DAO/Contribution.php';
189 $dao = new CRM_Contribute_DAO_Contribution;
190 $dao->trxn_id = $value;
191 if ($dao->find(TRUE)) {
192 preg_match('/(\d+)$/', $name, $matches);
193 $seq = $matches[1];
194 $email = $result["l_email{$seq}"];
195 $amt = $result["l_amt{$seq}"];
196 CRM_Core_Error::debug_log_message("Skipped (already recorded) - $email, $amt, $value ..<p>", TRUE);
197 continue;
198 }
199
200 $keyArgs['transactionid'] = $value;
201 $trxnDetails = CRM_Core_Payment_PayPalImpl::invokeAPI($keyArgs, $url);
202 if (is_a($trxnDetails, 'CRM_Core_Error')) {
203 echo "PAYPAL ERROR: Skipping transaction id: $value<p>";
204 continue;
205 }
206
207 // only process completed payments
208 if (strtolower($trxnDetails['paymentstatus']) != 'completed') {
209 continue;
210 }
211
212 // only process receipts, not payments
213 if (strtolower($trxnDetails['transactiontype']) == 'sendmoney') {
214 continue;
215 }
216
217 $params = CRM_Contribute_BAO_Contribution_Utils::formatAPIParams($trxnDetails,
218 self::$_paypalParamsMapper,
219 'paypal'
220 );
221 if ($paymentMode == 'test') {
222 $params['transaction']['is_test'] = 1;
223 }
224 else {
225 $params['transaction']['is_test'] = 0;
226 }
227
228 if (CRM_Contribute_BAO_Contribution_Utils::processAPIContribution($params)) {
229 CRM_Core_Error::debug_log_message("Processed - {$trxnDetails['email']}, {$trxnDetails['amt']}, {$value} ..<p>", TRUE);
230 }
231 else {
232 CRM_Core_Error::debug_log_message("Skipped - {$trxnDetails['email']}, {$trxnDetails['amt']}, {$value} ..<p>", TRUE);
233 }
234 }
235 }
236 if ($result['l_errorcode0'] == '11002') {
237 $end = $result['l_timestamp99'];
238 $end_time = strtotime("{$end}", time());
239 $end_date = date('Y-m-d\T00:00:00.00\Z', $end_time);
240 $args['enddate'] = $end_date;
241 }
242 } while ($result['l_errorcode0'] == '11002');
243 }
244
4e87860d
EM
245 /**
246 * @param $paymentProcessor
247 * @param $paymentMode
248 * @param $start
249 * @param $end
250 */
6a488035
TO
251 static
252 function google($paymentProcessor, $paymentMode, $start, $end) {
253 require_once "CRM/Contribute/BAO/Contribution/Utils.php";
254 require_once 'CRM/Core/Payment/Google.php';
255 $nextPageToken = TRUE;
256 $searchParams = array(
257 'start' => $start,
258 'end' => $end,
259 'notification-types' => array('charge-amount'),
260 );
261
262 $response = CRM_Core_Payment_Google::invokeAPI($paymentProcessor, $searchParams);
263
264 while ($nextPageToken) {
265 if ($response[0] == 'error') {
266 CRM_Core_Error::debug_log_message("GOOGLE ERROR: " .
267 $response[1]['error']['error-message']['VALUE'], TRUE
268 );
269 }
270 $nextPageToken = isset($response[1][$response[0]]['next-page-token']['VALUE']) ? $response[1][$response[0]]['next-page-token']['VALUE'] : FALSE;
271
272 if (is_array($response[1][$response[0]]['notifications']['charge-amount-notification'])) {
273
274 if (array_key_exists('google-order-number',
275 $response[1][$response[0]]['notifications']['charge-amount-notification']
276 )) {
277 // sometimes 'charge-amount-notification' itself is an absolute
278 // array and not array of arrays. This is the case when there is only one
279 // charge-amount-notification. Hack for this special case -
280 $chrgAmt = $response[1][$response[0]]['notifications']['charge-amount-notification'];
281 unset($response[1][$response[0]]['notifications']['charge-amount-notification']);
282 $response[1][$response[0]]['notifications']['charge-amount-notification'][] = $chrgAmt;
283 }
284
285 foreach ($response[1][$response[0]]['notifications']['charge-amount-notification']
a9e80afc 286 as $amtData
6a488035 287 ) {
a9e80afc
TO
288 $searchParams = array(
289 'order-numbers' => array($amtData['google-order-number']['VALUE']),
6a488035
TO
290 'notification-types' => array('risk-information', 'new-order', 'charge-amount'),
291 );
292 $response = CRM_Core_Payment_Google::invokeAPI($paymentProcessor,
293 $searchParams
294 );
295 // append amount information as well
296 $response[] = $amtData;
297
298 $params = CRM_Contribute_BAO_Contribution_Utils::formatAPIParams($response,
299 self::$_googleParamsMapper,
300 'google'
301 );
302 if ($paymentMode == 'test') {
303 $params['transaction']['is_test'] = 1;
304 }
305 else {
306 $params['transaction']['is_test'] = 0;
307 }
308 if (CRM_Contribute_BAO_Contribution_Utils::processAPIContribution($params)) {
309 CRM_Core_Error::debug_log_message("Processed - {$params['email']}, {$amtData['total-charge-amount']['VALUE']}, {$amtData['google-order-number']['VALUE']} ..<p>", TRUE);
310 }
311 else {
312 CRM_Core_Error::debug_log_message("Skipped - {$params['email']}, {$amtData['total-charge-amount']['VALUE']}, {$amtData['google-order-number']['VALUE']} ..<p>", TRUE);
313 }
314 }
315
316 if ($nextPageToken) {
317 $searchParams = array('next-page-token' => $nextPageToken);
318 $response = CRM_Core_Payment_Google::invokeAPI($paymentProcessor, $searchParams);
319 }
320 }
321 }
322 }
323
324 static
325 function csv() {
326 $csvFile = '/home/deepak/Desktop/crm-4247.csv';
327 $delimiter = ";";
328 $row = 1;
329
330 $handle = fopen($csvFile, "r");
331 if (!$handle) {
332 CRM_Core_Error::fatal("Can't locate csv file.");
333 }
334
335 require_once "CRM/Contribute/BAO/Contribution/Utils.php";
336 while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
337 if ($row !== 1) {
338 $data['header'] = $header;
339 $params = CRM_Contribute_BAO_Contribution_Utils::formatAPIParams($data,
340 self::$_csvParamsMapper,
341 'csv'
342 );
343 if (CRM_Contribute_BAO_Contribution_Utils::processAPIContribution($params)) {
344 CRM_Core_Error::debug_log_message("Processed - line $row of csv file .. {$params['email']}, {$params['transaction']['total_amount']}, {$params['transaction']['trxn_id']} ..<p>", TRUE);
345 }
346 else {
347 CRM_Core_Error::debug_log_message("Skipped - line $row of csv file .. {$params['email']}, {$params['transaction']['total_amount']}, {$params['transaction']['trxn_id']} ..<p>", TRUE);
348 }
349
350 // clean up memory from dao's
351 CRM_Core_DAO::freeResult();
352 }
353 else {
354 // we assuming - first row is always the header line
355 $header = $data;
356 CRM_Core_Error::debug_log_message("Considering first row ( line $row ) as HEADER ..<p>", TRUE);
357
358 if (empty($header)) {
359 CRM_Core_Error::fatal("Header is empty.");
360 }
361 }
362 $row++;
363 }
364 fclose($handle);
365 }
366
367 static
368 function process() {
369 require_once 'CRM/Utils/Request.php';
370
371 $type = CRM_Utils_Request::retrieve('type', 'String', CRM_Core_DAO::$_nullObject, FALSE, 'csv', 'REQUEST');
372 $type = strtolower($type);
373
374 switch ($type) {
375 case 'paypal':
376 case 'google':
377 $start = CRM_Utils_Request::retrieve('start', 'String',
378 CRM_Core_DAO::$_nullObject, FALSE, 31, 'REQUEST'
379 );
380 $end = CRM_Utils_Request::retrieve('end', 'String',
381 CRM_Core_DAO::$_nullObject, FALSE, 0, 'REQUEST'
382 );
383 if ($start < $end) {
384 CRM_Core_Error::fatal("Start offset can't be less than End offset.");
385 }
386
387 $start = date('Y-m-d', time() - $start * 24 * 60 * 60) . 'T00:00:00.00Z';
388 $end = date('Y-m-d', time() - $end * 24 * 60 * 60) . 'T23:59:00.00Z';
389
390 $ppID = CRM_Utils_Request::retrieve('ppID', 'Integer',
391 CRM_Core_DAO::$_nullObject, TRUE, NULL, 'REQUEST'
392 );
393 $mode = CRM_Utils_Request::retrieve('ppMode', 'String',
394 CRM_Core_DAO::$_nullObject, FALSE, 'live', 'REQUEST'
395 );
396
6a488035
TO
397 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($ppID, $mode);
398
399 CRM_Core_Error::debug_log_message("Start Date=$start, End Date=$end, ppID=$ppID, mode=$mode <p>", TRUE);
400
401 return self::$type($paymentProcessor, $mode, $start, $end);
402
403 case 'csv':
404 return self::csv();
405 }
406 }
407}
408
409// bootstrap the environment and run the processor
410session_start();
411require_once '../civicrm.config.php';
412require_once 'CRM/Core/Config.php';
413$config = CRM_Core_Config::singleton();
414
415CRM_Utils_System::authenticateScript(TRUE);
416
417//log the execution of script
418CRM_Core_Error::debug_log_message('ContributionProcessor.php');
419
420require_once 'CRM/Core/Lock.php';
421$lock = new CRM_Core_Lock('CiviContributeProcessor');
422
423if ($lock->isAcquired()) {
424 // try to unset any time limits
425 if (!ini_get('safe_mode')) {
426 set_time_limit(0);
427 }
428
429 CiviContributeProcessor::process();
430}
431else {
432 throw new Exception('Could not acquire lock, another CiviMailProcessor process is running');
433}
434
435$lock->release();
436
437echo "Done processing<p>";