First go at useragent and IP based blacklits
[trustcommerce.git] / trustcommerce.php
1 <?php
2 /*
3 * This file is part of CiviCRM.
4 *
5 * CiviCRM is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * CiviCRM is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with CiviCRM. If not, see <http://www.gnu.org/licenses/>.
17 *
18 * Copyright (C) 2012
19 * Licensed to CiviCRM under the GPL v3 or higher
20 *
21 * Written and contributed by Ward Vandewege <ward@fsf.org> (http://www.fsf.org)
22 * Modified by Lisa Marie Maginnis <lisa@fsf.org> (http://www.fsf.org)
23 *
24 */
25
26 // Define logging level (0 = off, 4 = log everything)
27 define('TRUSTCOMMERCE_LOGGING_LEVEL', 4);
28
29 require_once 'CRM/Core/Payment.php';
30 class org_fsf_payment_trustcommerce extends CRM_Core_Payment {
31 CONST CHARSET = 'iso-8859-1';
32 CONST AUTH_APPROVED = 'approve';
33 CONST AUTH_DECLINED = 'decline';
34 CONST AUTH_BADDATA = 'baddata';
35 CONST AUTH_ERROR = 'error';
36 CONST AUTH_BLACKLIST = 'blacklisted';
37
38 static protected $_mode = NULL;
39
40 static protected $_params = array();
41
42 /**
43 * We only need one instance of this object. So we use the singleton
44 * pattern and cache the instance in this variable
45 *
46 * @var object
47 * @static
48 */
49 static private $_singleton = NULL;
50
51 /**
52 * Constructor
53 *
54 * @param string $mode the mode of operation: live or test
55 *
56 * @return void
57 */ function __construct($mode, &$paymentProcessor) {
58 $this->_mode = $mode;
59
60 $this->_paymentProcessor = $paymentProcessor;
61
62 $this->_processorName = ts('TrustCommerce');
63
64 $config = CRM_Core_Config::singleton();
65 $this->_setParam('user_name', $paymentProcessor['user_name']);
66 $this->_setParam('password', $paymentProcessor['password']);
67
68 $this->_setParam('timestamp', time());
69 srand(time());
70 $this->_setParam('sequence', rand(1, 1000));
71 $this->logging_level = TRUSTCOMMERCE_LOGGING_LEVEL;
72
73 }
74
75 /**
76 * singleton function used to manage this object
77 *
78 * @param string $mode the mode of operation: live or test
79 *
80 * @return object
81 * @static
82 *
83 */
84 static
85 function &singleton($mode, &$paymentProcessor) {
86 $processorName = $paymentProcessor['name'];
87 if (self::$_singleton[$processorName] === NULL) {
88 self::$_singleton[$processorName] = new org_fsf_payment_trustcommerce($mode, $paymentProcessor);
89 }
90 return self::$_singleton[$processorName];
91 }
92
93 /**
94 * Submit a payment using the TC API
95 * @param array $params The params we will be sending to tclink_send()
96 * @return mixed An array of our results, or an error object if the transaction fails.
97 * @public
98 */
99 function doDirectPayment(&$params) {
100 if (!extension_loaded("tclink")) {
101 return self::error(9001, 'TrustCommerce requires that the tclink module is loaded');
102 }
103
104 /* Copy our paramaters to ourself */
105 foreach ($params as $field => $value) {
106 $this->_setParam($field, $value);
107 }
108
109 /* Get our fields to pass to tclink_send() */
110 $tc_params = $this->_getTrustCommerceFields();
111
112 /* Are we recurring? If so add the extra API fields. */
113 if (CRM_Utils_Array::value('is_recur', $params) && $params['contributionRecurID']) {
114 $tc_params = $this->_getRecurPaymentFields($tc_params);
115 }
116
117 /* Pass our cooked params to the alter hook, per Core/Payment/Dummy.php */
118 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $tc_params);
119
120 // TrustCommerce will not refuse duplicates, so we should check if the user already submitted this transaction
121 if ($this->_checkDupe($tc_params['ticket'])) {
122 return self::error(9004, 'It appears that this transaction is a duplicate. Have you already submitted the form once? If so there may have been a connection problem. You can try your transaction again. If you continue to have problems please contact the site administrator.');
123 }
124
125 /* This implements a local blacklist, and passes us though as a normal failure
126 * if the luser is on the blacklist. */
127 if(!$this->_isBlacklisted()) {
128 /* Call the TC API, and grab the reply */
129 $reply = $this->_sendTCRequest($tc_params);
130 } else {
131 $this->_logger($tc_params);
132 $reply['status'] = self::AUTH_BLACKLIST;
133 }
134
135 /* Parse our reply */
136 $result = $this->_getTCReply($reply);
137
138 if($result == 0) {
139 /* We were successful, congrats. Lets wrap it up:
140 * Convert back to dollars
141 * Save the transaction ID
142 */
143 $params['trxn_id'] = $reply['transid'];
144 $params['gross_amount'] = $tc_params['amount'] / 100;
145
146 return $params;
147
148 } else {
149 /* Otherwise we return the error object */
150 return $result;
151 }
152 }
153
154 function _isBlacklisted() {
155 if($this->_isIPBlacklisted()) {
156 return TRUE;
157 } else if($this->_IsAgentBlacklisted()) {
158 return TRUE;
159 }
160 return FALSE;
161 }
162
163 function _isAgentBlacklisted() {
164 $ip = $_SERVER['REMOTE_ADDR'];
165 $agent = $_SERVER['HTTP_USER_AGENT'];
166 $dao = CRM_Core_DAO::executeQuery('SELECT * FROM `trustcommerce_useragent_blacklist`');
167 while($dao->fetch()) {
168 if(preg_match('/'.$dao->name.'/', $agent) === 1) {
169 error_log(' [client '.$ip.'] [agent '.$agent.'] - Blacklisted by USER_AGENT rule #'.$dao->id);
170 return TRUE;
171 }
172 }
173 return FALSE;
174 }
175
176 function _isIPBlacklisted() {
177 $ip = $_SERVER['REMOTE_ADDR'];
178 $ip = ip2long($ip);
179 $blacklist = array();
180 $dao = CRM_Core_DAO::executeQuery('SELECT * FROM `trustcommerce_blacklist`');
181 while($dao->fetch()) {
182 if($ip >= $dao->start && $ip <= $dao->end) {
183 error_log('[client '.$ip.'] [agent '.$agent.'] Blacklisted by IP rule #'.$dao->id);
184 return TRUE;
185 }
186 }
187 return FALSE;
188 }
189
190 function _sendTCRequest($request) {
191 $this->_logger($request);
192 return tclink_send($request);
193 }
194
195 function _logger($params) {
196 $msg = '';
197 foreach ($params as $key => $data) {
198 /* Delete any data we should not be writing to disk. This includes:
199 * custid, password, cc, exp, and cvv
200 */
201 switch($key) {
202 case 'custid':
203 case 'password':
204 case 'cc':
205 case 'exp':
206 case 'cvv':
207 break;
208 default:
209 $msg .= ' '.$key.' => '.$data;
210 }
211 }
212 error_log('[client '.$_SERVER['REMOTE_ADDR'].'] TrustCommerce:'.$msg);
213 }
214
215 /**
216 * Gets the recurring billing fields for the TC API
217 * @param array $fields The fields to modify.
218 * @return array The fields for tclink_send(), modified for recurring billing.
219 * @public
220 */
221 function _getRecurPaymentFields($fields) {
222 $payments = $this->_getParam('frequency_interval');
223 $cycle = $this->_getParam('frequency_unit');
224
225 /* Translate billing cycle from CiviCRM -> TC */
226 switch($cycle) {
227 case 'day':
228 $cycle = 'd';
229 break;
230 case 'week':
231 $cycle = 'w';
232 break;
233 case 'month':
234 $cycle = 'm';
235 break;
236 case 'year':
237 $cycle = 'y';
238 break;
239 }
240
241 /* Translate frequency interval from CiviCRM -> TC
242 * Payments are the same, HOWEVER a payment of 1 (forever) should be 0 in TC */
243 if($payments == 1) {
244 $payments = 0;
245 }
246
247 $fields['cycle'] = '1'.$cycle; /* The billing cycle in years, months, weeks, or days. */
248 $fields['payments'] = $payments;
249 $fields['action'] = 'store'; /* Change our mode to `store' mode. */
250
251 return $fields;
252 }
253
254 /* Parses a response from TC via the tclink_send() command.
255 * @param $reply array The result of a call to tclink_send().
256 * @return mixed self::error() if transaction failed, otherwise returns 0.
257 */
258 function _getTCReply($reply) {
259
260 /* DUPLIATE CODE, please refactor. ~lisa */
261 if (!$reply) {
262 return self::error(9002, 'Could not initiate connection to payment gateway');
263 }
264
265 $this->_logger($reply);
266
267 switch($reply['status']) {
268 case self::AUTH_BLACKLIST:
269 return self::error(9001, "Your transaction was declined: error #90210");
270 break;
271 case self::AUTH_APPROVED:
272 // It's all good
273 break;
274 case self::AUTH_DECLINED:
275 // TODO FIXME be more or less specific?
276 // declinetype can be: decline, avs, cvv, call, expiredcard, carderror, authexpired, fraud, blacklist, velocity
277 // See TC documentation for more info
278 return self::error(9009, "Your transaction was declined: {$reply['declinetype']}");
279 break;
280 case self::AUTH_BADDATA:
281 // TODO FIXME do something with $reply['error'] and $reply['offender']
282 return self::error(9011, "Invalid credit card information. The following fields were invalid: {$reply['offenders']}.");
283 break;
284 case self::AUTH_ERROR:
285 return self::error(9002, 'Could not initiate connection to payment gateway');
286 break;
287 }
288 return 0;
289 }
290
291 function _getTrustCommerceFields() {
292 // Total amount is from the form contribution field
293 $amount = $this->_getParam('total_amount');
294 // CRM-9894 would this ever be the case??
295 if (empty($amount)) {
296 $amount = $this->_getParam('amount');
297 }
298 $fields = array();
299 $fields['custid'] = $this->_getParam('user_name');
300 $fields['password'] = $this->_getParam('password');
301 $fields['action'] = 'sale';
302
303 // Enable address verification
304 $fields['avs'] = 'y';
305
306 $fields['address1'] = $this->_getParam('street_address');
307 $fields['zip'] = $this->_getParam('postal_code');
308
309 $fields['name'] = $this->_getParam('billing_first_name') . ' ' . $this->_getParam('billing_last_name');
310
311 // This assumes currencies where the . is used as the decimal point, like USD
312 $amount = preg_replace("/([^0-9\\.])/i", "", $amount);
313
314 // We need to pass the amount to TrustCommerce in dollar cents
315 $fields['amount'] = $amount * 100;
316
317 // Unique identifier
318 $fields['ticket'] = substr($this->_getParam('invoiceID'), 0, 20);
319
320 // cc info
321 $fields['cc'] = $this->_getParam('credit_card_number');
322 $fields['cvv'] = $this->_getParam('cvv2');
323 $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT);
324 $exp_year = substr($this->_getParam('year'),-2);
325 $fields['exp'] = "$exp_month$exp_year";
326
327 if ($this->_mode != 'live') {
328 $fields['demo'] = 'y';
329 }
330 return $fields;
331 }
332
333 /**
334 * Checks to see if invoice_id already exists in db
335 *
336 * @param int $invoiceId The ID to check
337 *
338 * @return bool True if ID exists, else false
339 */
340 function _checkDupe($invoiceId) {
341 require_once 'CRM/Contribute/DAO/Contribution.php';
342 $contribution = new CRM_Contribute_DAO_Contribution();
343 $contribution->invoice_id = $invoiceId;
344 return $contribution->find();
345 }
346
347 /**
348 * Get the value of a field if set
349 *
350 * @param string $field the field
351 *
352 * @return mixed value of the field, or empty string if the field is
353 * not set
354 */
355 function _getParam($field) {
356 return CRM_Utils_Array::value($field, $this->_params, '');
357 }
358
359 function &error($errorCode = NULL, $errorMessage = NULL) {
360 $e = CRM_Core_Error::singleton();
361 if ($errorCode) {
362 $e->push($errorCode, 0, NULL, $errorMessage);
363 }
364 else {
365 $e->push(9001, 0, NULL, 'Unknown System Error.');
366 }
367 return $e;
368 }
369
370 /**
371 * Set a field to the specified value. Value must be a scalar (int,
372 * float, string, or boolean)
373 *
374 * @param string $field
375 * @param mixed $value
376 *
377 * @return bool false if value is not a scalar, true if successful
378 */
379 function _setParam($field, $value) {
380 if (!is_scalar($value)) {
381 return FALSE;
382 }
383 else {
384 $this->_params[$field] = $value;
385 }
386 }
387
388 /**
389 * This function checks to see if we have the right config values
390 *
391 * @return string the error message if any
392 * @public
393 */
394 function checkConfig() {
395 $error = array();
396 if (empty($this->_paymentProcessor['user_name'])) {
397 $error[] = ts('Customer ID is not set for this payment processor');
398 }
399
400 if (empty($this->_paymentProcessor['password'])) {
401 $error[] = ts('Password is not set for this payment processor');
402 }
403
404 if (!empty($error)) {
405 return implode('<p>', $error);
406 } else {
407 return NULL;
408 }
409 }
410
411 function cancelSubscription(&$message = '', $params = array()) {
412 $tc_params['custid'] = $this->_getParam('user_name');
413 $tc_params['password'] = $this->_getParam('password');
414 $tc_params['action'] = 'unstore';
415 $tc_params['billingid'] = CRM_Utils_Array::value('trxn_id', $params);
416
417 $result = $this->_sendTCRequest($tc_params);
418
419 /* Test if call failed */
420 if(!$result) {
421 return self::error(9002, 'Could not initiate connection to payment gateway');
422 }
423 /* We are done, pass success */
424 return TRUE;
425 }
426
427 public function install() {
428 return TRUE;
429 }
430
431 public function uninstall() {
432 return TRUE;
433 }
434
435 }