Fixed blacklist code
[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 $agent = $_SERVER['HTTP_USER_AGENT'];
179 $ip = ip2long($ip);
180 $blacklist = array();
181 $dao = CRM_Core_DAO::executeQuery('SELECT * FROM `trustcommerce_blacklist`');
182 while($dao->fetch()) {
183 if($ip >= $dao->start && $ip <= $dao->end) {
184 error_log('[client '.long2ip($ip).'] [agent '.$agent.'] Blacklisted by IP rule #'.$dao->id);
185 return TRUE;
186 }
187 }
188 return FALSE;
189 }
190
191 function _sendTCRequest($request) {
192 $this->_logger($request);
193 return tclink_send($request);
194 }
195
196 function _logger($params) {
197 $msg = '';
198 foreach ($params as $key => $data) {
199 /* Delete any data we should not be writing to disk. This includes:
200 * custid, password, cc, exp, and cvv
201 */
202 switch($key) {
203 case 'custid':
204 case 'password':
205 case 'cc':
206 case 'exp':
207 case 'cvv':
208 break;
209 default:
210 $msg .= ' '.$key.' => '.$data;
211 }
212 }
213 error_log('[client '.$_SERVER['REMOTE_ADDR'].'] TrustCommerce:'.$msg);
214 }
215
216 /**
217 * Gets the recurring billing fields for the TC API
218 * @param array $fields The fields to modify.
219 * @return array The fields for tclink_send(), modified for recurring billing.
220 * @public
221 */
222 function _getRecurPaymentFields($fields) {
223 $payments = $this->_getParam('frequency_interval');
224 $cycle = $this->_getParam('frequency_unit');
225
226 /* Translate billing cycle from CiviCRM -> TC */
227 switch($cycle) {
228 case 'day':
229 $cycle = 'd';
230 break;
231 case 'week':
232 $cycle = 'w';
233 break;
234 case 'month':
235 $cycle = 'm';
236 break;
237 case 'year':
238 $cycle = 'y';
239 break;
240 }
241
242 /* Translate frequency interval from CiviCRM -> TC
243 * Payments are the same, HOWEVER a payment of 1 (forever) should be 0 in TC */
244 if($payments == 1) {
245 $payments = 0;
246 }
247
248 $fields['cycle'] = '1'.$cycle; /* The billing cycle in years, months, weeks, or days. */
249 $fields['payments'] = $payments;
250 $fields['action'] = 'store'; /* Change our mode to `store' mode. */
251
252 return $fields;
253 }
254
255 /* Parses a response from TC via the tclink_send() command.
256 * @param $reply array The result of a call to tclink_send().
257 * @return mixed self::error() if transaction failed, otherwise returns 0.
258 */
259 function _getTCReply($reply) {
260
261 /* DUPLIATE CODE, please refactor. ~lisa */
262 if (!$reply) {
263 return self::error(9002, 'Could not initiate connection to payment gateway');
264 }
265
266 $this->_logger($reply);
267
268 switch($reply['status']) {
269 case self::AUTH_BLACKLIST:
270 return self::error(9001, "Your transaction was declined: error #90210");
271 break;
272 case self::AUTH_APPROVED:
273 // It's all good
274 break;
275 case self::AUTH_DECLINED:
276 // TODO FIXME be more or less specific?
277 // declinetype can be: decline, avs, cvv, call, expiredcard, carderror, authexpired, fraud, blacklist, velocity
278 // See TC documentation for more info
279 return self::error(9009, "Your transaction was declined: {$reply['declinetype']}");
280 break;
281 case self::AUTH_BADDATA:
282 // TODO FIXME do something with $reply['error'] and $reply['offender']
283 return self::error(9011, "Invalid credit card information. The following fields were invalid: {$reply['offenders']}.");
284 break;
285 case self::AUTH_ERROR:
286 return self::error(9002, 'Could not initiate connection to payment gateway');
287 break;
288 }
289 return 0;
290 }
291
292 function _getTrustCommerceFields() {
293 // Total amount is from the form contribution field
294 $amount = $this->_getParam('total_amount');
295 // CRM-9894 would this ever be the case??
296 if (empty($amount)) {
297 $amount = $this->_getParam('amount');
298 }
299 $fields = array();
300 $fields['custid'] = $this->_getParam('user_name');
301 $fields['password'] = $this->_getParam('password');
302 $fields['action'] = 'sale';
303
304 // Enable address verification
305 $fields['avs'] = 'y';
306
307 $fields['address1'] = $this->_getParam('street_address');
308 $fields['zip'] = $this->_getParam('postal_code');
309
310 $fields['name'] = $this->_getParam('billing_first_name') . ' ' . $this->_getParam('billing_last_name');
311
312 // This assumes currencies where the . is used as the decimal point, like USD
313 $amount = preg_replace("/([^0-9\\.])/i", "", $amount);
314
315 // We need to pass the amount to TrustCommerce in dollar cents
316 $fields['amount'] = $amount * 100;
317
318 // Unique identifier
319 $fields['ticket'] = substr($this->_getParam('invoiceID'), 0, 20);
320
321 // cc info
322 $fields['cc'] = $this->_getParam('credit_card_number');
323 $fields['cvv'] = $this->_getParam('cvv2');
324 $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT);
325 $exp_year = substr($this->_getParam('year'),-2);
326 $fields['exp'] = "$exp_month$exp_year";
327
328 if ($this->_mode != 'live') {
329 $fields['demo'] = 'y';
330 }
331 return $fields;
332 }
333
334 /**
335 * Checks to see if invoice_id already exists in db
336 *
337 * @param int $invoiceId The ID to check
338 *
339 * @return bool True if ID exists, else false
340 */
341 function _checkDupe($invoiceId) {
342 require_once 'CRM/Contribute/DAO/Contribution.php';
343 $contribution = new CRM_Contribute_DAO_Contribution();
344 $contribution->invoice_id = $invoiceId;
345 return $contribution->find();
346 }
347
348 /**
349 * Get the value of a field if set
350 *
351 * @param string $field the field
352 *
353 * @return mixed value of the field, or empty string if the field is
354 * not set
355 */
356 function _getParam($field) {
357 return CRM_Utils_Array::value($field, $this->_params, '');
358 }
359
360 function &error($errorCode = NULL, $errorMessage = NULL) {
361 $e = CRM_Core_Error::singleton();
362 if ($errorCode) {
363 $e->push($errorCode, 0, NULL, $errorMessage);
364 }
365 else {
366 $e->push(9001, 0, NULL, 'Unknown System Error.');
367 }
368 return $e;
369 }
370
371 /**
372 * Set a field to the specified value. Value must be a scalar (int,
373 * float, string, or boolean)
374 *
375 * @param string $field
376 * @param mixed $value
377 *
378 * @return bool false if value is not a scalar, true if successful
379 */
380 function _setParam($field, $value) {
381 if (!is_scalar($value)) {
382 return FALSE;
383 }
384 else {
385 $this->_params[$field] = $value;
386 }
387 }
388
389 /**
390 * This function checks to see if we have the right config values
391 *
392 * @return string the error message if any
393 * @public
394 */
395 function checkConfig() {
396 $error = array();
397 if (empty($this->_paymentProcessor['user_name'])) {
398 $error[] = ts('Customer ID is not set for this payment processor');
399 }
400
401 if (empty($this->_paymentProcessor['password'])) {
402 $error[] = ts('Password is not set for this payment processor');
403 }
404
405 if (!empty($error)) {
406 return implode('<p>', $error);
407 } else {
408 return NULL;
409 }
410 }
411
412 function cancelSubscription(&$message = '', $params = array()) {
413 $tc_params['custid'] = $this->_getParam('user_name');
414 $tc_params['password'] = $this->_getParam('password');
415 $tc_params['action'] = 'unstore';
416 $tc_params['billingid'] = CRM_Utils_Array::value('trxn_id', $params);
417
418 $result = $this->_sendTCRequest($tc_params);
419
420 /* Test if call failed */
421 if(!$result) {
422 return self::error(9002, 'Could not initiate connection to payment gateway');
423 }
424 /* We are done, pass success */
425 return TRUE;
426 }
427
428 public function install() {
429 return TRUE;
430 }
431
432 public function uninstall() {
433 return TRUE;
434 }
435
436 }