added ignorefile for phpdoc
[trustcommerce.git] / trustcommerce.php
CommitLineData
71a6ba5c
LMM
1<?php
2/*
93b42747
LMM
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 *
71a6ba5c
LMM
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)
68f3cf09 22 * Modified by Lisa Marie Maginnis <lisa@fsf.org> (http://www.fsf.org)
4efc3ebe 23 * Copyright © 2015 David Thompson <davet@gnu.org>
71a6ba5c
LMM
24 *
25 */
26
27// Define logging level (0 = off, 4 = log everything)
28define('TRUSTCOMMERCE_LOGGING_LEVEL', 4);
29
30require_once 'CRM/Core/Payment.php';
31class org_fsf_payment_trustcommerce extends CRM_Core_Payment {
32 CONST CHARSET = 'iso-8859-1';
33 CONST AUTH_APPROVED = 'approve';
34 CONST AUTH_DECLINED = 'decline';
35 CONST AUTH_BADDATA = 'baddata';
36 CONST AUTH_ERROR = 'error';
4d58ae2f 37 CONST AUTH_BLACKLIST = 'blacklisted';
45f26143 38 CONST AUTH_ACCEPTED = 'accepted';
71a6ba5c
LMM
39
40 static protected $_mode = NULL;
41
42 static protected $_params = array();
43
44 /**
45 * We only need one instance of this object. So we use the singleton
46 * pattern and cache the instance in this variable
47 *
48 * @var object
49 * @static
50 */
51 static private $_singleton = NULL;
52
53 /**
54 * Constructor
55 *
56 * @param string $mode the mode of operation: live or test
57 *
58 * @return void
59 */ function __construct($mode, &$paymentProcessor) {
60 $this->_mode = $mode;
61
62 $this->_paymentProcessor = $paymentProcessor;
63
64 $this->_processorName = ts('TrustCommerce');
65
66 $config = CRM_Core_Config::singleton();
67 $this->_setParam('user_name', $paymentProcessor['user_name']);
68 $this->_setParam('password', $paymentProcessor['password']);
69
70 $this->_setParam('timestamp', time());
71 srand(time());
72 $this->_setParam('sequence', rand(1, 1000));
73 $this->logging_level = TRUSTCOMMERCE_LOGGING_LEVEL;
4d58ae2f 74
71a6ba5c
LMM
75 }
76
77 /**
78 * singleton function used to manage this object
79 *
80 * @param string $mode the mode of operation: live or test
81 *
82 * @return object
83 * @static
84 *
85 */
86 static
87 function &singleton($mode, &$paymentProcessor) {
88 $processorName = $paymentProcessor['name'];
89 if (self::$_singleton[$processorName] === NULL) {
90 self::$_singleton[$processorName] = new org_fsf_payment_trustcommerce($mode, $paymentProcessor);
91 }
92 return self::$_singleton[$processorName];
93 }
94
95 /**
e0273c0a
LMM
96 * Submit a payment using the TC API
97 * @param array $params The params we will be sending to tclink_send()
98 * @return mixed An array of our results, or an error object if the transaction fails.
71a6ba5c
LMM
99 * @public
100 */
101 function doDirectPayment(&$params) {
102 if (!extension_loaded("tclink")) {
103 return self::error(9001, 'TrustCommerce requires that the tclink module is loaded');
104 }
105
f322addf
LMM
106 /* Copy our paramaters to ourself */
107 foreach ($params as $field => $value) {
71a6ba5c
LMM
108 $this->_setParam($field, $value);
109 }
110
f322addf
LMM
111 /* Get our fields to pass to tclink_send() */
112 $tc_params = $this->_getTrustCommerceFields();
71a6ba5c 113
f322addf 114 /* Are we recurring? If so add the extra API fields. */
7d2018fa 115 if (CRM_Utils_Array::value('is_recur', $params) == 1) {
f322addf 116 $tc_params = $this->_getRecurPaymentFields($tc_params);
7d2018fa 117 $recur=1;
f322addf 118 }
71a6ba5c 119
f322addf 120 /* Pass our cooked params to the alter hook, per Core/Payment/Dummy.php */
32bf0975 121 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $tc_params);
71a6ba5c
LMM
122
123 // TrustCommerce will not refuse duplicates, so we should check if the user already submitted this transaction
f322addf 124 if ($this->_checkDupe($tc_params['ticket'])) {
71a6ba5c
LMM
125 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.');
126 }
127
4d58ae2f
LMM
128 /* This implements a local blacklist, and passes us though as a normal failure
129 * if the luser is on the blacklist. */
130 if(!$this->_isBlacklisted()) {
131 /* Call the TC API, and grab the reply */
132 $reply = $this->_sendTCRequest($tc_params);
133 } else {
134 $this->_logger($tc_params);
135 $reply['status'] = self::AUTH_BLACKLIST;
136 }
71a6ba5c 137
f322addf 138 /* Parse our reply */
5efae07f 139 $result = $this->_getTCReply($reply);
71a6ba5c 140
f322addf
LMM
141 if($result == 0) {
142 /* We were successful, congrats. Lets wrap it up:
143 * Convert back to dollars
144 * Save the transaction ID
145 */
06f2e425 146
7d2018fa
DT
147 if (array_key_exists('billingid', $reply)) {
148 $params['recurr_profile_id'] = $reply['billingid'];
149 CRM_Core_DAO::setFieldValue(
150 'CRM_Contribute_DAO_ContributionRecur',
151 $this->_getParam('contributionRecurID'),
152 'processor_id', $reply['billingid']
153 );
154 }
f322addf 155 $params['trxn_id'] = $reply['transid'];
06f2e425 156
f322addf 157 $params['gross_amount'] = $tc_params['amount'] / 100;
71a6ba5c 158
f322addf 159 return $params;
71a6ba5c 160
f322addf
LMM
161 } else {
162 /* Otherwise we return the error object */
163 return $result;
164 }
71a6ba5c
LMM
165 }
166
4efc3ebe
DT
167 /**
168 * Update CC info for a recurring contribution
169 */
170 function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
171 $expYear = $params['credit_card_exp_date']['Y'];
172 $expMonth = $params['credit_card_exp_date']['M'];
173
174 $tc_params = array(
175 'custid' => $this->_paymentProcessor['user_name'],
176 'password' => $this->_paymentProcessor['password'],
177 'action' => 'store',
178 'billingid' => $params['subscriptionId'],
179 'avs' => 'y', // Enable address verification
180 'address1' => $params['street_address'],
181 'zip' => $params['postal_code'],
182 'name' => $this->_formatBillingName($params['first_name'],
183 $params['last_name']),
184 'cc' => $params['credit_card_number'],
185 'cvv' => $params['cvv2'],
186 'exp' => $this->_formatExpirationDate($expYear, $expMonth),
187 'amount' => $this->_formatAmount($params['amount']),
188 );
189
190 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $tc_params);
191
192 $reply = $this->_sendTCRequest($tc_params);
193 $result = $this->_getTCReply($reply);
194
195 if($result === 0) {
196 $message = 'Successfully updated TC billing id ' . $tc_params['billingid'];
197
198 return TRUE;
199 } else {
200 return FALSE;
201 }
202 }
203
204 // TODO: Use the formatting functions throughout the entire class to
205 // dedupe the conversions done elsewhere in a less reusable way.
206 function _formatAmount($amount) {
207 return $amount * 100;
208 }
209
210 function _formatBillingName($firstName, $lastName) {
211 return "$firstName $lastName";
212 }
213
214 function _formatExpirationDate($year, $month) {
215 $exp_month = str_pad($month, 2, '0', STR_PAD_LEFT);
216 $exp_year = substr($year, -2);
217
218 return "$exp_month$exp_year";
219 }
220
4d58ae2f 221 function _isBlacklisted() {
d5e500b0
LMM
222 if($this->_isIPBlacklisted()) {
223 return TRUE;
224 } else if($this->_IsAgentBlacklisted()) {
225 return TRUE;
0b6767d8 226 }
d5e500b0 227 return FALSE;
4d58ae2f
LMM
228 }
229
230 function _isAgentBlacklisted() {
231 $ip = $_SERVER['REMOTE_ADDR'];
232 $agent = $_SERVER['HTTP_USER_AGENT'];
233 $dao = CRM_Core_DAO::executeQuery('SELECT * FROM `trustcommerce_useragent_blacklist`');
234 while($dao->fetch()) {
235 if(preg_match('/'.$dao->name.'/', $agent) === 1) {
d5e500b0
LMM
236 error_log(' [client '.$ip.'] [agent '.$agent.'] - Blacklisted by USER_AGENT rule #'.$dao->id);
237 return TRUE;
4d58ae2f
LMM
238 }
239 }
240 return FALSE;
241 }
242
243 function _isIPBlacklisted() {
244 $ip = $_SERVER['REMOTE_ADDR'];
c389ccec 245 $agent = $_SERVER['HTTP_USER_AGENT'];
4d58ae2f
LMM
246 $ip = ip2long($ip);
247 $blacklist = array();
248 $dao = CRM_Core_DAO::executeQuery('SELECT * FROM `trustcommerce_blacklist`');
249 while($dao->fetch()) {
250 if($ip >= $dao->start && $ip <= $dao->end) {
d5e500b0
LMM
251 error_log('[client '.long2ip($ip).'] [agent '.$agent.'] Blacklisted by IP rule #'.$dao->id);
252 return TRUE;
4d58ae2f
LMM
253 }
254 }
255 return FALSE;
256 }
257
e055e8ef
LMM
258 function _sendTCRequest($request) {
259 $this->_logger($request);
260 return tclink_send($request);
261 }
262
263 function _logger($params) {
e990a9a5 264 $msg = '';
69a1e975 265 foreach ($params as $key => $data) {
e055e8ef
LMM
266 /* Delete any data we should not be writing to disk. This includes:
267 * custid, password, cc, exp, and cvv
268 */
e055e8ef 269 switch($key) {
e990a9a5
LMM
270 case 'custid':
271 case 'password':
272 case 'cc':
273 case 'exp':
274 case 'cvv':
e055e8ef
LMM
275 break;
276 default:
e990a9a5 277 $msg .= ' '.$key.' => '.$data;
e055e8ef
LMM
278 }
279 }
4d58ae2f 280 error_log('[client '.$_SERVER['REMOTE_ADDR'].'] TrustCommerce:'.$msg);
e055e8ef
LMM
281 }
282
71a6ba5c 283 /**
f322addf
LMM
284 * Gets the recurring billing fields for the TC API
285 * @param array $fields The fields to modify.
286 * @return array The fields for tclink_send(), modified for recurring billing.
71a6ba5c
LMM
287 * @public
288 */
f322addf 289 function _getRecurPaymentFields($fields) {
285eaf25
LMM
290 $payments = $this->_getParam('frequency_interval');
291 $cycle = $this->_getParam('frequency_unit');
71a6ba5c 292
f322addf 293 /* Translate billing cycle from CiviCRM -> TC */
285eaf25
LMM
294 switch($cycle) {
295 case 'day':
296 $cycle = 'd';
297 break;
298 case 'week':
299 $cycle = 'w';
300 break;
301 case 'month':
302 $cycle = 'm';
303 break;
304 case 'year':
305 $cycle = 'y';
306 break;
71a6ba5c 307 }
0b6767d8 308
bc323ec4
LMM
309 /* Translate frequency interval from CiviCRM -> TC
310 * Payments are the same, HOWEVER a payment of 1 (forever) should be 0 in TC */
311 if($payments == 1) {
312 $payments = 0;
71a6ba5c 313 }
71a6ba5c 314
bc323ec4
LMM
315 $fields['cycle'] = '1'.$cycle; /* The billing cycle in years, months, weeks, or days. */
316 $fields['payments'] = $payments;
317 $fields['action'] = 'store'; /* Change our mode to `store' mode. */
71a6ba5c 318
bc323ec4 319 return $fields;
a79ba043
LMM
320 }
321
322 /* Parses a response from TC via the tclink_send() command.
323 * @param $reply array The result of a call to tclink_send().
324 * @return mixed self::error() if transaction failed, otherwise returns 0.
325 */
5efae07f 326 function _getTCReply($reply) {
71a6ba5c 327
285eaf25 328 /* DUPLIATE CODE, please refactor. ~lisa */
bc323ec4 329 if (!$reply) {
3be283c0 330 return self::error(9002, 'Could not initiate connection to payment gateway.');
71a6ba5c
LMM
331 }
332
4d58ae2f
LMM
333 $this->_logger($reply);
334
bc323ec4 335 switch($reply['status']) {
4d58ae2f
LMM
336 case self::AUTH_BLACKLIST:
337 return self::error(9001, "Your transaction was declined: error #90210");
338 break;
285eaf25 339 case self::AUTH_APPROVED:
45f26143
LMM
340 break;
341 case self::AUTH_ACCEPTED:
285eaf25
LMM
342 // It's all good
343 break;
344 case self::AUTH_DECLINED:
0b6767d8 345 // TODO FIXME be more or less specific?
285eaf25
LMM
346 // declinetype can be: decline, avs, cvv, call, expiredcard, carderror, authexpired, fraud, blacklist, velocity
347 // See TC documentation for more info
da1932b6
LMM
348 switch($reply['declinetype']) {
349 case 'avs':
78390e15 350 return self::error(9009, "Your transaction was declined for address verification reasons. If your address was correct please contact us at donate@fsf.org before attempting to retry your transaction.");
da1932b6
LMM
351 break;
352 }
a8c5366f 353 return self::error(9009, "Your transaction was declined: {$reply['declinetype']}");
285eaf25
LMM
354 break;
355 case self::AUTH_BADDATA:
a8c5366f
LMM
356 // TODO FIXME do something with $reply['error'] and $reply['offender']
357 return self::error(9011, "Invalid credit card information. The following fields were invalid: {$reply['offenders']}.");
285eaf25
LMM
358 break;
359 case self::AUTH_ERROR:
360 return self::error(9002, 'Could not initiate connection to payment gateway');
361 break;
71a6ba5c 362 }
a79ba043 363 return 0;
71a6ba5c
LMM
364 }
365
366 function _getTrustCommerceFields() {
367 // Total amount is from the form contribution field
368 $amount = $this->_getParam('total_amount');
369 // CRM-9894 would this ever be the case??
370 if (empty($amount)) {
371 $amount = $this->_getParam('amount');
372 }
373 $fields = array();
374 $fields['custid'] = $this->_getParam('user_name');
375 $fields['password'] = $this->_getParam('password');
376 $fields['action'] = 'sale';
377
378 // Enable address verification
379 $fields['avs'] = 'y';
380
381 $fields['address1'] = $this->_getParam('street_address');
382 $fields['zip'] = $this->_getParam('postal_code');
383
384 $fields['name'] = $this->_getParam('billing_first_name') . ' ' . $this->_getParam('billing_last_name');
385
386 // This assumes currencies where the . is used as the decimal point, like USD
387 $amount = preg_replace("/([^0-9\\.])/i", "", $amount);
388
389 // We need to pass the amount to TrustCommerce in dollar cents
390 $fields['amount'] = $amount * 100;
391
392 // Unique identifier
393 $fields['ticket'] = substr($this->_getParam('invoiceID'), 0, 20);
394
395 // cc info
396 $fields['cc'] = $this->_getParam('credit_card_number');
397 $fields['cvv'] = $this->_getParam('cvv2');
398 $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT);
399 $exp_year = substr($this->_getParam('year'),-2);
400 $fields['exp'] = "$exp_month$exp_year";
401
402 if ($this->_mode != 'live') {
403 $fields['demo'] = 'y';
404 }
71a6ba5c
LMM
405 return $fields;
406 }
407
408 /**
409 * Checks to see if invoice_id already exists in db
410 *
411 * @param int $invoiceId The ID to check
412 *
413 * @return bool True if ID exists, else false
414 */
415 function _checkDupe($invoiceId) {
416 require_once 'CRM/Contribute/DAO/Contribution.php';
417 $contribution = new CRM_Contribute_DAO_Contribution();
418 $contribution->invoice_id = $invoiceId;
419 return $contribution->find();
420 }
421
422 /**
423 * Get the value of a field if set
424 *
425 * @param string $field the field
426 *
427 * @return mixed value of the field, or empty string if the field is
428 * not set
429 */
430 function _getParam($field) {
431 return CRM_Utils_Array::value($field, $this->_params, '');
432 }
433
434 function &error($errorCode = NULL, $errorMessage = NULL) {
435 $e = CRM_Core_Error::singleton();
436 if ($errorCode) {
437 $e->push($errorCode, 0, NULL, $errorMessage);
438 }
439 else {
440 $e->push(9001, 0, NULL, 'Unknown System Error.');
441 }
442 return $e;
443 }
444
445 /**
446 * Set a field to the specified value. Value must be a scalar (int,
447 * float, string, or boolean)
448 *
449 * @param string $field
450 * @param mixed $value
451 *
452 * @return bool false if value is not a scalar, true if successful
453 */
454 function _setParam($field, $value) {
455 if (!is_scalar($value)) {
456 return FALSE;
457 }
458 else {
459 $this->_params[$field] = $value;
460 }
461 }
462
463 /**
464 * This function checks to see if we have the right config values
465 *
466 * @return string the error message if any
467 * @public
468 */
469 function checkConfig() {
470 $error = array();
471 if (empty($this->_paymentProcessor['user_name'])) {
472 $error[] = ts('Customer ID is not set for this payment processor');
473 }
474
475 if (empty($this->_paymentProcessor['password'])) {
476 $error[] = ts('Password is not set for this payment processor');
477 }
478
479 if (!empty($error)) {
480 return implode('<p>', $error);
481 } else {
482 return NULL;
483 }
484 }
485
14f15ff3 486 function cancelSubscription(&$message = '', $params = array()) {
7964e0e9
LMM
487 $tc_params['custid'] = $this->_getParam('user_name');
488 $tc_params['password'] = $this->_getParam('password');
489 $tc_params['action'] = 'unstore';
ee0485c3 490 $tc_params['billingid'] = CRM_Utils_Array::value('subscriptionId', $params);
0b6767d8 491
e990a9a5 492 $result = $this->_sendTCRequest($tc_params);
71a6ba5c 493
7964e0e9
LMM
494 /* Test if call failed */
495 if(!$result) {
71a6ba5c
LMM
496 return self::error(9002, 'Could not initiate connection to payment gateway');
497 }
7964e0e9 498 /* We are done, pass success */
71a6ba5c
LMM
499 return TRUE;
500 }
2ff31643
DT
501
502 function changeSubscriptionAmount(&$message = '', $params = array()) {
1d268593
DT
503 $tc_params['custid'] = $this->_paymentProcessor['user_name'];
504 $tc_params['password'] = $this->_paymentProcessor['password'];
2ff31643
DT
505 $tc_params['action'] = 'store';
506
507 $tc_params['billingid'] = CRM_Utils_Array::value('subscriptionId', $params);
508 $tc_params['payments'] = CRM_Utils_Array::value('installments', $params);
509 $tc_params['amount'] = CRM_Utils_Array::value('amount', $params) * 100;
510
511 if($tc_params['payments'] == 1) {
512 $tc_params['payments'] = 0;
513 }
514 $reply = $this->_sendTCRequest($tc_params);
515 $result = $this->_getTCReply($reply);
516
2ff31643
DT
517 /* We are done, pass success */
518 return TRUE;
519
520 }
521
71a6ba5c
LMM
522 public function install() {
523 return TRUE;
524 }
525
526 public function uninstall() {
527 return TRUE;
528 }
529
530}