-
Notifications
You must be signed in to change notification settings - Fork 2
/
tgg_atos.php
1792 lines (1698 loc) · 69.3 KB
/
tgg_atos.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Atos/SIPS connector for Prestashop
* @license GNU/GPL version 3
* @author Damien VERON (TrogloGeek)
* @website prestashop.blog.capillotracteur.fr
*
*/
class tgg_atos extends PaymentModule
{
const RESPONSE_MODE_POST = 0;
const RESPONSE_MODE_GET = 1;
const FEES_TOTAL = 0;
const FEES_FIXED = 1;
const FEES_PERCENT = 2;
private $payment_ok = false;
private $_confVars = array(
'BASIC' => array(
'BANK',
'DEMO',
'MERCHANT_ID',
'OS_PAYMENT_SUCCESS',
'FALLBACK_CURRENCY',
'INT_MINAMOUNT',
'ISO_LANG',
'INT_CAPTURE_DAY',
'CAPTURE_MODE',
'BOOL_RESPONSE_LOG_TXT',
'BOOL_RESPONSE_LOG_CSV',
'LOG_PATH',
'BOOL_FORCE_RETURN',
'FLOAT_PAYMENT_FEES',
'FLOAT_PAYMENT_FEES_P',
'BOOL_ORDER_MESSAGE',
'BOOL_CHECK_VERSION',
'OS_PAYMENT_CANCELLED',
'OS_PAYMENT_FAILED'
),
'GRAPHIC' => array(
'CARD_IMG_PATH',
'LOGO_NAME'
),
'ADVANCED' => array(
'PAYMENT_MEANS',
'TID_TZ',
'INT_MIN_TID',
'BOOL_BINARIES_IN_PATH',
'BIN_PATH',
'PARAM_PATH',
'RETURN_PROTOCOL',
'RETURN_DOMAIN',
'RETURN_PROTOCOL_AUTO',
'RETURN_DOMAIN_AUTO',
'BOOL_DEBUG_MODE',
'BOOL_ADVANCED_CONTROLS',
'ADVANCED_CONTROLS',
'BOOL_CUSTOM_PARAMS',
'CUSTOM_PARAMS',
'ERRORS_MAILTO',
'ERRORS_SHOWTOIP'
),
'23TIMES' => array(
'BOOL_2TPAYMENT',
'INT_2TPAYMENT_MINAMOUNT',
'INT_2TPAYMENT_SPACING',
'INT_2TPAYMENT_DELAY',
'INT_2TPAYMENT_OS',
'FLOAT_2TPAYMENT_FEES',
'FLOAT_2TPAYMENT_FEES_P',
'FLOAT_2TPAYMENT_FP_FXD',
'FLOAT_2TPAYMENT_FP_PCT',
'BOOL_3TPAYMENT',
'INT_3TPAYMENT_MINAMOUNT',
'INT_3TPAYMENT_SPACING',
'INT_3TPAYMENT_DELAY',
'INT_3TPAYMENT_OS',
'FLOAT_3TPAYMENT_FEES',
'FLOAT_3TPAYMENT_FEES_P',
'FLOAT_3TPAYMENT_FP_FXD',
'FLOAT_3TPAYMENT_FP_PCT'
)
);
private $_newConfVars = array(
'1.2.7' => array(
'BOOL_ORDER_MESSAGE',
'BOOL_CHECK_VERSION',
'OS_PAYMENT_CANCELLED',
'OS_PAYMENT_FAILED',
'FLOAT_2TPAYMENT_FP_FXD',
'FLOAT_2TPAYMENT_FP_PCT',
'FLOAT_3TPAYMENT_FP_FXD',
'FLOAT_3TPAYMENT_FP_PCT'
),
'2.2.0' => array(
'TID_TZ'
)
);
private $_banks = array(
'cyberplus' => 'CyberPlus - Banque Populaire',
'etransactions' => 'E-Transactions - Crédit Agricole',
'elysnet' => 'ElysNet - CCF/HSBC',
'mercanet' => 'Mercanet - BNP',
'scelliusnet' => 'ScelliusNet - La Banque Postale',
'sherlocks' => 'Sherlocks - LCL',
'sogenactif' => 'Sogenactif - Société Générale',
'webaffaires' => 'WebAffaires - Crédit du Nord',
'citelis' => 'Citélis',
'smc' => 'Société Marseillaise de Crédit'
);
private $_demoCertificates = array(
'cyberplus' => '038862749811111',
'etransactions' => '013044876511111',
'elysnet' => '014102450311111',
'mercanet' => '082584341411111',
'scelliusnet' => '014141675911111',
'sherlocks' => '014295303911111',
'sogenactif' => '014213245611111',
'webaffaires' => '014022286611111',
'citelis' => '029800266211111',
'smc' => '011223344551111'
);
private $_currencies = array(
'EUR' => array('978', 2),
'USD' => array('840', 2),
'CHF' => array('756', 2),
'GBP' => array('826', 2),
'CAD' => array('124', 2),
'JPY' => array('392', 0),
'MXN' => array('484', 2),
'TRY' => array('949', 2),
'AUD' => array('036', 2),
'NZD' => array('554', 2),
'NOK' => array('578', 2),
'BRL' => array('986', 2),
'ARS' => array('032', 2),
'KHR' => array('116', 2),
'TWD' => array('901', 2),
'SEK' => array('752', 2),
'DKK' => array('208', 2),
'KRW' => array('410', 0),
'SGD' => array('702', 2),
'XPF' => array('953', 0),
'XOF' => array('952', 0)
);
private $_responseFields = array(
'merchant_id',
'merchant_country',
'amount',
'transaction_id',
'payment_means',
'transmission_date',
'payment_time',
'payment_date',
'response_code',
'payment_certificate',
'authorisation_id',
'currency_code',
'card_number',
'cvv_flag',
'cvv_response_code',
'bank_response_code',
'complementary_code',
'complementary_info',
'return_context',
'caddie',
'receipt_complement',
'merchant_language',
'language',
'customer_id',
'order_id',
'customer_email',
'customer_ip_address',
'capture_day',
'capture_mode',
'data'
);
private $_responseFieldsLoggedInOrder = array(
'amount',
'merchant_id',
'transaction_id',
'transmission_date',
'payment_time',
'payment_date',
'response_code',
'payment_certificate',
'authorisation_id',
'currency_code',
'cvv_flag',
'cvv_response_code',
'bank_response_code',
'complementary_code',
'complementary_info',
'return_context',
'receipt_complement',
'merchant_language',
'language',
'customer_email',
'customer_ip_address',
'capture_day',
'capture_mode',
'data'
);
private $_hasTransacIDAvailableCached = null;
public function __construct()
{
$this->name = 'tgg_atos';
$this->tab = self::PsVersionCompare('1.4', '<') ? 'Payment' : 'payments_gateways';
if (self::PsVersionCompare('1.4', '>=')) {
$this->need_instance = 1;
}
if (self::PsVersionCompare('1.5', '>=')) {
if (!defined('_USER_ID_LANG_')) {
define('_USER_ID_LANG_', Context::getContext()->language->id);
}
}
$this->version = '2.2.1';
$this->currencies_mode = 'checkbox';
parent::__construct();
$this->displayName = $this->l('SIPS/ATOS');
$this->description = $this->l('SIPS/ATOS payment module by TrogloGeek', 'tgg_atos');
$this->confirmUninstall = $this->l('If you uninstall this module, all configuration related to ATOS payment will be deleted, including any production certificate file you could have uploaded. Only logfiles are left in place for security reasons. If you intended only to stop using ATOS for a while and use it again later you should consider disabling this module instead of uninstalling it. Uninstall it anyway ?');
$this->_autoCheck();
}
public static function PsVersionCompare($version, $operator = '>=')
{
return version_compare(_PS_VERSION_, $version, $operator);
}
public static function redirect($to = '', $code = 302)
{
$baseUri = _MODULE_DIR_ . basename(dirname(__FILE__)) . '/front-ctrl/';
if (self::PsVersionCompare('1.5', '<')) {
return Tools::redirect($baseUri . $to);
}
header('Location: ' . $baseUri . $to, TRUE, $code);
exit;
}
public static function redirectToShop($to = '', $code = 302)
{
if (!empty($to) || self::PsVersionCompare('1.5', '<')) {
return Tools::redirect($to);
}
header('Location: ' . __PS_BASE_URI__, TRUE, $code);
exit;
}
/**
* Checks if module installation generated errors log, if yes displays warning message in PS module administration
*/
protected function _autoCheck()
{
$this->warning = '';
if (!Module::isInstalled($this->name)) {
return;
}
if (version_compare($this->version, $this->_get('VERSION'), '>')) {
$this->_postUpdate();
}
/* @var $cookie Cookie */
global $cookie;
if ($cookie->isLoggedBack()) {
$installLogFile = $this->_getModPath() . 'log/install.log';
if (file_exists($installLogFile)) {
$this->warning = sprintf(
$this->l('Errors occured during installation, see %s, delete, move or rename the file to stop seeing this message.'), $installLogFile
);
} elseif (!$this->_get('TID_TZ')) {
$this->warning = $this->l('No timezone configured');
} elseif (!$this->_get('ERRORS_MAILTO')) {
$this->warning = $this->l('No address has been configured to receive Tgg_Atos disfonctionnement alert. Contact address of your shop will be used until another one is specified.');
} elseif ($this->_get('BOOL_CHECK_VERSION')) {
if (is_array($current_version = $this->_check_new_version())) {
list ($version, $url) = $current_version;
$this->warning = sprintf($this->l('New version %s avalaible at %s'), $version, $url);
} elseif (!$current_version) {
$this->warning = $this->l('New version check failure, you should check manually');
}
}
}
}
protected function _check_new_version()
{
try {
$context = stream_context_create(array('http' => array('header' => 'Connection: close', 'timeout' => 3)));
$current_version = @file_get_contents('http://www.capillotracteur.fr/tgg_atos/current_version.txt', false, $context);
if (!$current_version) {
return false;
}
$current_version = explode('|', $current_version);
if (count($current_version) > 1) {
if (version_compare($this->version, $current_version[0], '<')) {
return $current_version;
}
return true;
}
} catch (Exception $e) {
}
return false;
}
/**
* Install hook override
* @return boolean Success state
*/
public function install()
{
$errors = array();
$installed = false;
try {
if (!$installed = parent::install()) {
$errors[] = $this->l('Standard module installation (parent::install()) failed');
}
if (!$this->_installTable()) {
$errors[] = $this->l('Unable to create needed database table');
$DB = Db::getInstance();
if ($DB->getMsgError()) {
$errors[] = sprintf('Db error: %s', $DB->getMsgError());
}
}
if (!$this->_setDefaults()) {
$errors[] = $this->l('Unable to register module variables');
}
if (!$this->_writeConf()) {
$errors[] = $this->l('Unable to write configuration file on disk, check permissions on param dir');
}
if (!$this->registerHook('payment')) {
$errors[] = $this->l('Hook registration: Registration as a payment choice in final order step failed ($this->registerHook("payment"))');
}
if (!$this->registerHook('paymentReturn')) {
$errors[] = $this->l('Hook registration: Registration to hook needed to display payment confirmation page failed ($this->registerHook("paymentReturn"))');
}
$bankReturnHook = new Hook();
$bankReturnHook->name = 'tggAtosBankReturn';
if (!$bankReturnHook->add()) {
$errors[] = $this->l('Hook declaration: internal hook "tggAtosBankReturn" declaration failed');
}
$orderConfirmHook = new Hook();
$orderConfirmHook->name = 'tggAtosOrderConfirm';
if (!$orderConfirmHook->add()) {
$errors[] = $this->l('Hook declaration: internal hook "tggAtosOrderConfirm" declaration failed');
}
} catch (Exception $e) {
/* @var $e Exception */
$errors[] = $e->getMessage() . "\n" . $e->getTraceAsString();
}
$this->_logInstall($errors);
$this->_autoCheck();
$this->_set('VERSION', $this->version);
return $installed;
}
/**
* Module table installation
* @return bool success
*/
protected function _installTable()
{
return Db::getInstance()->Execute('
CREATE TABLE `' . _DB_PREFIX_ . $this->name . '_transactions_today` (
`date` date NOT NULL,
`atos_transaction_id` mediumint(9) UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`date`, `atos_transaction_id`)
)
ENGINE = MyISAM
AUTO_INCREMENT=1
;');
}
/**
* Uninstall hook override
* @return boolean Success state
*/
public function uninstall()
{
try {
$bankReturnHook = new Hook(Hook::get('tggAtosBankReturn'));
$bankReturnHook->delete();
} catch (Exception $e) {
}
try {
$orderConfirmHook = new Hook(Hook::get('tggAtosOrderConfirm'));
$orderConfirmHook->delete();
} catch (Exception $e) {
}
//pathfile, parmcom & certif
$path = $this->_getPath('PARAM');
if (is_dir($path)) {
if (file_exists($path . 'pathfile')) {
unlink($path . 'pathfile');
}
@chdir($path);
$prefix = 'parmcom.';
$prefix_length = strlen($prefix);
$files = glob($prefix . '*');
foreach ($files as $file) {
$file = substr($file, $prefix_length);
if (preg_match('/^[0-9]+$/', $file))
unlink($path . $prefix . $file);
}
$certif_ids = $this->_getMerchantIdList();
foreach ($certif_ids as $id) {
@unlink($path . 'certif.fr.' . $id);
}
}
//transaction_id table
Db::getInstance()->Execute('DROP TABLE IF EXISTS `' . _DB_PREFIX_ . $this->name . '_transactions_today`;');
//Config vars
foreach ($this->_confVars as $s) {
foreach ($s as $k) {
$this->_unset($k);
}
}
return parent::uninstall();
}
/**
* Admin configuration Hook, allow to make a config page for the module
* @global Smarty $smarty Uses template processing
* @return string|html
*/
public function getContent()
{
global $smarty;
$validation_string = '';
$errors = array();
$highlights = array('BASIC' => array(), 'GRAPHIC' => array(), 'ADVANCED' => array(), '23TIMES' => array());
$actions = array(
'updateBasic' => 0,
'updateGraphic' => 1,
'updateAdvanced' => 2,
'update23Times' => 3,
'restoreDefault' => 0,
'renameCertif' => 0,
'makeTheme' => 1,
null => 0
);
$pos_select = 0;
foreach ($actions as $action => $pos) {
$pos_select = $pos;
if (is_null($action)) {
break;
}
if (Tools::isSubmit($action)) {
$actionMethod = '_admin_' . $action;
$validation_string = $this->$actionMethod($errors);
break;
}
}
$this->_autoCheck();
if (is_file($this->_getPath('PARAM') . 'CERTIF~1')) {
return $this->display(__FILE__, 'admin-tpl/' . $this->name . '-back-ask-merchant-id.tpl');
}
//BASIC checks
if (($this->_get('BOOL_RESPONSE_LOG_TXT') || $this->_get('BOOL_RESPONSE_LOG_CSV')) && !is_dir($this->_getPath('LOG'))) {
$errors[] = $this->l('Logfiles path points to a non existing dir or the dir hasn\'t enough rights');
$highlights['BASIC'][] = 'log_path';
}
if (!Currency::getIdByIsoCode($this->_get('FALLBACK_CURRENCY'))) {
$errors[] = $this->l('Fallback currency isn\'t set or doesn\'t exist anymore');
$highlights['BASIC'][] = 'fallback_currency';
}
if (!$this->_get('DEMO') && (!$this->_get('MERCHANT_ID'))) {
$errors[] = $this->l('Merchant id is required in production mode');
$highlights['BASIC'][] = 'merchant_id';
}
$capture_day = intval($this->_get('INT_CAPTURE_DAY'));
if (($capture_day < 0) || (strlen((string) $capture_day) > 2)) {
$this->_set('INT_CAPTURE_DAY', 0);
$errors[] = $this->l('specified CAPTURE_DAY was invalid, must be a natural integer < 100');
$highlights['BASIC'][] = 'int_capture_day';
}
//GRAPHIC checks
if (!strlen($this->_getPath('CARD_IMG'))) {
$errors[] = $this->l('Cards logos URL is needed');
$highlights['GRAPHIC'][] = 'card_img_path';
}
if (strlen($this->_get('LOGO_NAME')) == 0) {
$errors[] = $this->l('Merchant logo filename is required');
$highlights['GRAPHIC'][] = 'logo_name';
}
//ADVANCED checks
if (!$this->_get('BOOL_BINARIES_IN_PATH')) {
if (!is_dir($this->_getPath('BIN'))) {
$errors[] = $this->l('Binaries path points to a non existing dir or the dir hasn\'t enough rights');
$highlights['ADVANCED'][] = 'bin_path';
} elseif (!$this->_checkBinariesPath()) {
$errors[] = $this->l('Binaries not found');
$highlights['ADVANCED'][] = 'bin_path';
}
}
if (!is_dir($param_path = $this->_getPath('PARAM'))) {
$errors[] = $this->l('Parameters files path points to a non existing dir or the dir hasn\'t enough rights');
$highlights['ADVANCED'][] = 'param_path';
}
if (strlen($param_path) > 54) {
$errors[] = $this->l('Parameters files path is too long, 54 characters max');
$highlights['ADVANCED'][] = 'param_path';
}
if (!$this->_get('TID_TZ')) {
$errors[] = $this->l('A timezone has to be set');
$highlights['ADVANCED'][] = 'tid_tz';
}
$min_tid = intval($this->_get('INT_MIN_TID'));
if (($min_tid < 1) || ($min_tid > 999999)) {
$this->_set('INT_MIN_TID', 1);
$errors[] = $this->l('Minimum transaction ID you specified was invalid, must be an integer between 1 and 999999.');
$highlights['ADVANCED'][] = 'int_min_tid';
}
foreach ($this->_confVars as $s) {
foreach ($s as $k) {
$smarty->assign(strtolower($k), $this->_get($k));
}
}
$smarty->assign(array(
'browsing_through' => empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['REMOTE_ADDR'] : $_SERVER['HTTP_X_FORWARDED_FOR'] . ':' . $_SERVER['REMOTE_ADDR'],
'pos_select' => $pos_select,
'banks' => $this->_banks,
'errors' => $errors,
'merchant_ids' => $this->_getMerchantIdList(),
'currencies' => $this->_getCurrencies(),
'default_currency' => $this->_getFallBackCurrency(),
'order_states' => OrderState::getOrderStates(_USER_ID_LANG_),
'validation_string' => $validation_string,
'module_version' => $this->version,
'tpl_path' => $this->_getModPath() . 'admin-tpl/',
'highlights' => $highlights,
'warning' => $this->warning,
'capture_modes' => array(
'AUTHOR_CAPTURE',
'VALIDATION'
)
));
return $this->display(__FILE__, 'admin-tpl/' . $this->name . '-back-admin.tpl');
}
/**
* Hook for displaying ATOS as a payment module
* @global Smarty $smarty Uses templates processing
* @param array $params
* @return string|html HTML to display
*/
public function hookPayment($params)
{
/* @var $smarty Smarty */
global $smarty;
/* @var $cart Cart */
$cart = $params['cart'];
$payment_currency = null;
$smarty->assign(array(
'controller' => _MODULE_DIR_ . $this->name . '/' . 'front-ctrl/payment-redirect.php',
'bank' => $this->_get('BANK'),
'willSwitchCurrency' => $this->_willSwitchCurrency($cart),
'canProcess' => $this->canProcess($cart),
'fees' => $this->getCartFeesStr($cart, $payment_currency),
'total' => Tools::displayPrice($cart->getOrderTotal() + $this->getCartFees($cart, $payment_currency), $payment_currency),
'canProcess2t' => $this->canProcess($cart, 2),
'canProcess3t' => $this->canProcess($cart, 3),
'2t_allowed' => $this->_get('BOOL_2TPAYMENT'),
'2t_fees' => $this->getCartFeesStr($cart, $payment_currency, 2),
'2t_total' => Tools::displayPrice($cart->getOrderTotal() + $this->getCartFees($cart, $payment_currency, 2), $payment_currency),
'3t_allowed' => $this->_get('BOOL_3TPAYMENT'),
'3t_fees' => $this->getCartFeesStr($cart, $payment_currency, 3),
'3t_total' => Tools::displayPrice($cart->getOrderTotal() + $this->getCartFees($cart, $payment_currency, 3), $payment_currency)
));
return $this->display(__FILE__, 'tpl/' . $this->name . '-front-hookpayment.tpl');
}
/**
* Hook for displaying things on payment return page
* @return string|html HTML to display
*/
public function hookPaymentReturn()
{
return $this->display(__FILE__, 'tpl/' . $this->name . '-front-order-confirmation.tpl');
}
/**
* Generate a payment form, will initiate a transaction in an ATOS way of speaking
* @global Cart $cart Gets amount informations, alters currency to fit module configuration if required
* @global Cookie $cookie Alters currency to fit module configuration if required
* @param float &$amount Amount to be paid
* @param array &$payment_currency Will be setted with array_assoc representation of the Currency that will be used
* @param false|2|3 &$splitted FALSE if one time payment, else: number of transactions (2 or 3)
* @return html|boolean Payment form generated by ATOS API
*/
public function getPaymentForm(&$amount, &$payment_currency, &$splitted = FALSE)
{
global $cart;
global $cookie;
//check currency and convert price
$payment_currency = $this->_getCurrencyToUse($cart);
if ($payment_currency['id_currency'] != $cart->id_currency) {
$cookie->id_currency = $payment_currency['id_currency'];
$cart->id_currency = $payment_currency['id_currency'];
$cart->update();
//Currency updated, refresh to avoid bugs
Tools::redirectLink($_SERVER['REQUEST_URI']);
}
$amount = $this->_round($cart->getOrderTotal(true), _PS_PRICE_DISPLAY_PRECISION_);
$amount += $this->getCartFees($cart, $payment_currency, $splitted ? $splitted : 1);
$atos_amount = (string) round($amount * pow(10, intval($payment_currency['nb_decimals'])));
$atos_amount = str_repeat("0", max(0, 3 - strlen($atos_amount))) . $atos_amount;
$Customer = new Customer($cart->id_customer);
$Lang = new Language(_USER_ID_LANG_);
$cmd = $this->_getPath('BIN') . 'request';
$return_base_url = $this->_getReturnBaseURL();
$params = array(
'amount' => $atos_amount,
'automatic_response_url' => $this->_getReturnBaseURL(TRUE) . 'front-ctrl/payment-autoresponse.php',
'cancel_return_url' => $return_base_url . 'front-ctrl/payment-return.php',
'capture_day' => $this->_get('INT_CAPTURE_DAY'),
'capture_mode' => $this->_get('CAPTURE_MODE'),
'currency_code' => $payment_currency['atos_code'],
'customer_id' => $Customer->id,
'customer_email' => $Customer->email,
'customer_ip_address' => substr($_SERVER['REMOTE_ADDR'], 0, 19),
'language' => ($this->_get('ISO_LANG') ? $this->_get('ISO_LANG') : $Lang->iso_code),
'merchant_id' => $this->_getMerchantId(),
'normal_return_url' => $return_base_url . 'front-ctrl/payment-return.php',
'order_id' => $cart->id,
'transaction_id' => $this->_generateTransactionID()
);
if (($splitted = intval($splitted)) && (($namespace = $splitted . 'TPAYMENT') && $this->_get('BOOL_' . $namespace))) {
$params = array_merge($params, array(
'capture_mode' => 'PAYMENT_N', //let ATOS know that we want a splitted payment
'capture_day' => $this->_get('INT_' . $namespace . '_DELAY'),
'data' => implode(';', array(
'NB_PAYMENT=' . $splitted,
'PERIOD=' . $this->_get('INT_' . $namespace . '_SPACING'),
'INITIAL_AMOUNT=' . round($this->_defaultCurrencyConvert($this->_getFloat($namespace . '_FP_FXD'), $payment_currency) * pow(10, intval($payment_currency['nb_decimals'])) + $atos_amount * $this->_getFloat($namespace . '_FP_PCT') / 100)
))
));
} else {
$splitted = FALSE;
}
if ($this->_get('BOOL_FORCE_RETURN')) {
if (isset($params['data'])) {
$params['data'] .= ';NO_RESPONSE_PAGE';
} else {
$params['data'] = 'NO_RESPONSE_PAGE';
}
}
//Adding advanced cards control
if ($this->_get('BOOL_ADVANCED_CONTROLS')) {
if (($cbcontrols = $this->_get('ADVANCED_CONTROLS')) != '') {
if (isset($params['data'])) {
$params['data'] .= ';<CONTROLS>'.$cbcontrols.'</CONTROLS>';
} else {
$params['data'] = '<CONTROLS>'.$cbcontrols.'</CONTROLS>';
}
}
unset($cbcontrols);
}
//Adding custom params
if ($this->_get('BOOL_CUSTOM_PARAMS')) {
if (($customparams = $this->_get('CUSTOM_PARAMS')) != '') {
if (isset($params['data'])) {
$params['data'] .= ';'.$customparams;
} else {
$params['data'] = $customparams;
}
}
unset($customparams);
}
$this->_requestParamsXmlOverride($params, $splitted);
$output = $this->_call('request', $params);
if (is_array($output)) {
return $output[0];
}
return FALSE;
}
/**
* wrapper for ATOS API response unencryption
* @param string $data DATA returned by bank server
* @return boolean|StdClass Hashmap object representation of unencrypted DATA.
*/
public function decryptResponse($data)
{
$output = $this->_call('response', array('message' => $data));
if (!is_array($output)) {
return FALSE;
}
$response = array();
foreach ($output as $k => $v) {
$response[$this->_responseFields[$k]] = $v;
}
return (object) $response;
}
/**
* Process the unencrypted bank response, Prestashop logics about order creation and logs goes here
* @global Cookie $cookie Alters currency if needed to correspond to the one used by bank
* @param stdClass $Response Response hashmap
* @param Customer $Customer Will be set with the Customer who holds the order
* @param Order $Order Will be set with the Order that has been validated
* @param Currency $Currency Will be set with the Currency hat has been used by paiement
* @param float $amount Will be set to effective paiement amount
* @param Cart $cart Will be set to the cart being turned into Order
* @return boolean Return true if the order has been created (even if created by a former call)
*/
public function processResponse($Response, &$Customer, &$Order, &$Currency, &$amount, &$cart)
{
global $cookie;
$Order = null;
$Response->caller_ip_address = $_SERVER['REMOTE_ADDR'];
$this->_logResponse($Response);
$cart = new Cart($Response->order_id);
if (!Validate::isLoadedObject($cart)) {
return $this->_invalid_response($this->l('Cart ID returned in id_order field does not exist'), $Response);
}
if (!empty($Response->customer_id)) {
$Customer = new Customer($Response->customer_id);
if ($cart->id_customer != $Customer->id) {
return $this->_invalid_response($this->l('Cart which ID has been returned in field id_order does not belong to Customer which ID has been returned in field id_customer'), $Response);
}
} else {
$Customer = new Customer($cart->id_customer);
}
if (!Validate::isLoadedObject($Customer)) {
return $this->_invalid_response($this->l('Customer ID returned in id_customer field does not exist'), $Response);
}
$currency_used = NULL;
foreach ($this->_currencies as $k => $v) {
if ($v[0] == $Response->currency_code) {
$currency_used = $k;
break;
}
}
if (is_null($currency_used)) {
return $this->_invalid_response($this->l('Unknown currency_code'), $Response);
}
$Currency = new Currency(Currency::getIdByIsoCode($currency_used));
$amount = $Response->amount / pow(10, $this->_currencies[$currency_used][1]);
if (!Validate::isLoadedObject($Currency)) {
return $this->_invalid_response($this->l('ISO Currency Code ') . $currency_used . $this->l(' isn\'t implemented in Prestashop, can\'t process order.'), $Response);
}
Module::hookExec('tggAtosBankReturn', array('Response' => $Response, 'Cart' => $cart, 'Customer' => $Customer));
if (($Response->response_code === '00')) {
$this->payment_ok = true;
} else {
if (
!(($Response->response_code === '17') && ($order_state = $this->_get('OS_PAYMENT_CANCELLED'))) &&
!($order_state = $this->_get('OS_PAYMENT_CANCELLED'))
) {
return FALSE;
}
}
//Which order state to apply ?
if ($Response->capture_mode == 'PAYMENT_N') {
$data = explode(';', $Response->data);
$Data = new stdClass();
foreach ($data as $field) {
$field = explode('=', $field);
$Data->{$field[0]} = $field[1];
}
if (!$order_state) {
$order_state = $this->_get('INT_' . $Data->NB_PAYMENT . 'TPAYMENT_OS');
}
$payment_n = $Data->NB_PAYMENT;
/* We have to reserve transaction_id for automated transactions */
$timezone = new DateTimeZone($this->_get('TID_TZ'));
$paymentDate = DateTime::createFromFormat('Ymd', $Response->payment_date, $timezone);
$period = new DateInterval(sprintf('P%uD', intval($Data->PERIOD)));
$DB = Db::getInstance();
for ($pn = 1; $pn < $payment_n; $pn++) {
$paymentDate->add($period);
$DB->Execute('INSERT IGNORE INTO `' . _DB_PREFIX_ . $this->name . '_transactions_today` SET date = \'' . $paymentDate->format('Y-m-d') . '\', atos_transaction_id = ' . intval($Response->transaction_id));
}
} else {
if (!$order_state) {
$order_state = $this->_get('OS_PAYMENT_SUCCESS');
}
$payment_n = false;
}
$payment_currency = null;
if (!$cart->OrderExists()) {
if ($cart->id_currency != $Currency->id) {
$cart->id_currency = $Currency->id;
$cookie->id_currency = $Currency->id;
$cart->update();
}
if ($this->validateOrder(
$cart->id, $order_state, ($amount - $this->getCartFees($cart, $payment_currency, $payment_n ? $payment_n : 1)), $this->displayName, $this->_makeOrderMessage($Response), array(), ($cart->id_currency != $Currency->id) ? $Currency->id : NULL, FALSE, $Customer->secure_key
)) {
$Order = new Order($this->currentOrder);
if ($this->payment_ok) {
Module::hookExec('tggAtosOrderConfirm', array('Response' => $Response, 'Cart' => $cart, 'Customer' => $Customer, 'Order' => $Order));
} else if (
(is_callable(array($cart, 'duplicate'))) &&
is_array($duplication_result = $cart->duplicate()) &&
($duplication_result['success'])
) {
$cart = $duplication_result['cart'];
$cookie->id_cart = $cart->id;
}
} else {
return FALSE;
}
}
if (!$Order) {
$Order = new Order(Order::getOrderByCartId($cart->id));
}
return $this->payment_ok;
}
/**
* Check if module graphical ressources are exported to ps theme dir
* @return boolean
*/
public function isThemeExportedDir()
{
return is_dir(_PS_THEME_DIR_ . 'modules/' . $this->name . '/tpl/');
}
/**
* Returns module graphical ressources container fs path
* @return string filesystem path
*/
public function getThemePath()
{
if ($this->isThemeExportedDir()) {
return _PS_THEME_DIR_ . 'modules/' . $this->name . '/';
} else {
return _PS_MODULE_DIR_ . $this->name . '/';
}
}
/**
* Returns module graphical ressources container uri
* @return string uri
*/
public function getThemeUri()
{
if ($this->isThemeExportedDir()) {
return _THEME_DIR_ . 'modules/' . $this->name . '/';
} else {
return _MODULE_DIR_ . $this->name . '/';
}
}
protected function _adminUpdateFromPost($section)
{
$localeconf = localeconv();
foreach ($this->_confVars[$section] as $k) {
if (strpos($k, 'BOOL_') === 0) {
if (Tools::getIsset(strtolower($k)) && Tools::getValue(strtolower($k))) {
$this->_set($k, 1);
} else {
$this->_set($k, 0);
}
} elseif (strpos($k, 'INT_') === 0) {
if (Tools::getIsset(strtolower($k))) {
$this->_set($k, intval(Tools::getValue(strtolower($k))));
} else {
$this->_set($k, 0);
}
} elseif (strpos($k, 'FLOAT_') === 0) {
if (Tools::getIsset(strtolower($k))) {
$this->_set($k, floatval(preg_replace('/[.,]/', $localeconf['decimal_point'], Tools::getValue(strtolower($k)))));
} else {
$this->_set($k, 0);
}
} else {
if (Tools::getIsset(strtolower($k))) {
$this->_set($k, Tools::getValue(strtolower($k)));
}
}
}
}
protected function _admin_updateBasic(&$errors)
{
$this->_adminUpdateFromPost('BASIC');
if (is_uploaded_file($_FILES['new_certificate']['tmp_name'])) {
if (!$this->_uploadCertificate()) {
$errors[] = $this->l('Unable to write certificate file, check permitions on param dir');
}
}
if (!$this->_writeConf()) {
$errors[] = $this->l('Unable to write configuration file, check permitions on param dir');
}
return $this->l('Basic configuration updated');
}
protected function _admin_updateGraphic(&$errors)
{
$this->_adminUpdateFromPost('GRAPHIC');
if (!$this->_writeConf()) {
$errors[] = $this->l('Unable to write configuration file, check permitions on param dir');
}
return $this->l('Graphic configuration updated');
}
protected function _admin_updateAdvanced(&$errors)
{
$this->_adminUpdateFromPost('ADVANCED');
if (!$this->_writeConf()) {
$errors[] = $this->l('Unable to write configuration file, check permitions on param dir');
}
return $this->l('Advanced configuration updated');
}
protected function _admin_update23Times(&$errors)
{
$this->_adminUpdateFromPost('23TIMES');
return $this->l('2/3 times payment configuration updated');
}
protected function _admin_restoreDefault(&$errors)
{
$this->_setDefaults();
if (!$this->_writeConf()) {
$errors[] = $this->l('Unable to write configuration file, check permitions on param dir');
}
return $this->l('Default configuration loaded');
}
protected function _admin_renameCertif(&$errors)
{
$merchant_id = trim(Tools::getValue('merchant_id'));
if (preg_match('/^[0-9]{15}$/', $merchant_id)) {
rename($this->_getPath('PARAM') . 'CERTIF~1', $this->_getPath('PARAM') . 'certif.fr.' . $merchant_id);
$this->_set('MERCHANT_ID', $merchant_id);
$this->_writeConf();
return $this->l('Certificate file renamed');
} else {
$errors[] = 'Merchant ID was invalid, must be a 15 digits number';
}
}
protected function _admin_makeTheme(&$errors)
{
try {
chdir($this->_getModPath());
umask(0);
$theme_path = _PS_THEME_DIR_ . 'modules/' . $this->name . '/';
if (!is_dir($theme_path)) {
mkdir($theme_path, 0775, TRUE);
}
$mod_path = $this->_getModPath();
exec('cp -R ' . $mod_path . 'images ' . $theme_path);
exec('cp -R ' . $mod_path . 'tpl ' . $theme_path);
$lang_files = glob('??.php');
foreach ($lang_files as $lang_file) {
if ($Fo = fopen($lang_file, 'r')) {
if ($Fd = fopen($theme_path . $lang_file, 'w')) {
while ($line = fgets($Fo)) {
$line = str_replace('<{' . $this->name . '}prestashop>', '<{' . $this->name . '}' . strtolower(_THEME_NAME_) . '>', $line);
fputs($Fd, $line);
}
fclose($Fd);
return $this->l('Theme dir created.') . '<br />' . $theme_path;
} else {
throw new Exception('Unable to open (write) lang file ' . $theme_path . $lang_file);
}
fclose($Fo);
} else {
throw new Exception('Unable to open (read) lang file ' . $this->_getModPath() . $lang_file);
}
}
} catch (Exception $e) {
try {
if ($Fo) {
fclose($Fo);
}
if ($Fd) {
fclose($Fd);
}
} catch (Exception $e2) {
}
$errors[] = $e->getMessage();
}
}
protected function _hasTransacIDAvailable()
{
if (is_null($this->_hasTransacIDAvailableCached)) {
$this->_hasTransacIDAvailableCached = (Db::getInstance()->getValue('SELECT MAX(`atos_transaction_id`) FROM ' . _DB_PREFIX_ . $this->name . '_transactions_today` WHERE date = \'' . date('Y-m-d') . '\'') < 999999);
}
return $this->_hasTransacIDAvailableCached;
}
protected function _canGenerateTransacID()