forked from PrestaShopCorp/twenga
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwenga.php
executable file
·1182 lines (1047 loc) · 45.4 KB
/
twenga.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
/**
* 2007-2014 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <[email protected]>
* @copyright 2007-2014 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Twenga module allow to use the Twenga API to :
* 1. subscribe to their Ready to Sell engine,
* 2. activate a tracking for order process if user has been used twenga engine,
* 3. submit a xml feed of shop products to Twenga.
* @version 2.0
*/
if (!defined('_PS_VERSION_')) exit;
class Twenga extends PaymentModule
{
/**
* path to load each needed files
* @var string
*/
private static $base_dir;
/**
* Url path to access of module file.
* @var string
*/
private static $base_path;
/**
* @var TwengaObj
*/
private static $obj_twenga;
/**
* @var PrestashopStats
*/
private static $obj_ps_stats;
/**
* @var string url used for the subscription to Twenga and prestashop
*/
private $site_url;
/**
* @var string url to acces of the product list for Twenga
*/
private $feed_url;
/**
* @var string url returned by Twenga API
*/
private $inscription_url;
/**
* @var string used for displaying html
*/
private $_html;
/**
* @var string
*/
private $current_index;
/**
* @var string
*/
private $token;
/**
* Countries where Twenga works.
* need to be in lowercase
* @var array
*/
public $limited_countries = array('fr', 'de', 'gb', 'uk', 'it', 'es', 'nl');
private $_allowToWork = true;
private $_currentIsoCodeCountry = NULL;
const ONLY_PRODUCTS = 1;
const ONLY_DISCOUNTS = 2;
const BOTH = 3;
const BOTH_WITHOUT_SHIPPING = 4;
const ONLY_SHIPPING = 5;
const ONLY_WRAPPING = 6;
const ONLY_PRODUCTS_WITHOUT_SHIPPING = 7;
/**
* The current country iso code for the shop.
* @var string
*/
private static $shop_country;
public function __construct()
{
// Basic vars
global $currentIndex;
$this->current_index = $currentIndex;
$this->token = Tools::getValue('token');
$this->name = 'twenga';
$this->tab = 'smart_shopping';
$this->version = '2.0';
$this->author = 'PrestaShop';
parent::__construct();
$this->displayName = $this->l('Twenga Module');
$this->description = $this->l('Export your products to Twenga Shopping Search Engine and get new online buyers immediately.');
/* Backward compatibility */
if (_PS_VERSION_ < '1.5')
require(_PS_MODULE_DIR_.$this->name.'/backward_compatibility/backward.php');
// For Twenga subscription
$protocol = 'http://';
if (isset($_SERVER['https']) && $_SERVER['https'] != 'off')
$protocol = 'https://';
$this->site_url = Tools::htmlentitiesutf8($protocol.$_SERVER['HTTP_HOST'].__PS_BASE_URI__);
self::$base_dir = _PS_ROOT_DIR_.'/modules/twenga/';
self::$base_path = $this->site_url.'/modules/twenga/';
$this->feed_url = self::$base_path.'export.php?twenga_token='.sha1(Configuration::get('TWENGA_TOKEN')._COOKIE_KEY_);
self::$shop_country = Country::getIsoById(Configuration::get('PS_COUNTRY_DEFAULT'));
require_once realpath(self::$base_dir.'/lib/PrestashopStats.php');
require_once realpath(self::$base_dir.'/lib/TwengaObj.php');
// set the base dir to load files needed for the TwengaObj class
TwengaObj::$base_dir = self::$base_dir.'/lib';
TwengaObj::setTranslationObject($this);
TwengaException::setTranslationObject($this);
if (!in_array(strtolower(self::$shop_country), $this->limited_countries))
{
$this->_allowToWork = false;
$this->warning = $this->l('Twenga module works only in specific countries (iso code list:').' '.implode(', ',$this->limited_countries).').';;
return false;
}
// instanciate (just once) the TwengaObj and PrestashopStats
if (self::$obj_twenga === NULL)
self::$obj_twenga = new TwengaObj();
if (self::$obj_ps_stats === NULL)
self::$obj_ps_stats = new PrestashopStats($this->site_url);
$this->_initCurrentIsoCodeCountry();
if (!extension_loaded('openssl'))
$this->warning = $this->l('OpenSSL should be activated on your PHP configuration to use all functionalities of Twenga.');
}
public function install()
{
if (Configuration::updateValue('TWENGA_TOKEN', Tools::passwdGen()))
return parent::install();
return false;
}
/**
* For uninstall just need to delete the Merchant Login.
* @return bool see parent class.
*/
public function uninstall()
{
if (!parent::uninstall() || !self::$obj_twenga->deleteMerchantLogin())
return false;
return true;
}
private function _initCurrentIsoCodeCountry()
{
global $cookie;
$country = Db::getInstance()->ExecuteS('
SELECT c.iso_code as iso
FROM '._DB_PREFIX_.'country as c
LEFT JOIN '._DB_PREFIX_.'country_lang as c_l
ON c_l.id_country = c.id_country
WHERE c_l.id_lang = '.(int)$cookie->id_lang.'
AND c.id_country = '. Configuration::get('PS_COUNTRY_DEFAULT'));
if (isset($country[0]['iso']))
$this->_currentIsoCodeCountry = $country[0]['iso'];
}
public function ajaxRequestType()
{
if (isset($_POST) && isset($_POST['type']) && isset($_POST['base']))
{
$link = 'http://addons.prestashop.com/'.Language::getIsoById($_POST['id_lang']).
'/2053-twenga-ready-to-sell.html';
$type = (($_POST['type'] == 'desactive') ? $this->l('Disable') :
(($_POST['type'] == 'reset') ? $this->l('Reset') :
(($_POST['type'] == 'uninstall') ? $this->l('Uninstall') : $this->l('Delete'))));
if ($_POST['type'] == 'delete')
$_POST['type'] = 'deleteModule';
$url = $_POST['base'].'&token='.$_POST['token'].'&module_name='.
$_POST['module_name'].'&tab_module='.$_POST['tab_module'].'&'.
$_POST['type'].'='.$_POST['module_name'];
$msg = '
<style>
#mainContent {
border:1px solid #B0C4DE;
background-color:#E2EBEE;
-moz-border-radius:10px;
-webkit-border-radius:10px;
line-height:18px;
font-size:14px; }
#mainContent a { text-decoration:none; color:#268CCD;}
</style>
<div id="mainContent" >
<p>'.$this->l('If you subscribe on Twenga, the activation of this module is mandatory.').
'<br /><br />'.$this->l('If there\'s a problem, uninstall this module, install the newer version here and enter the Twenga hashkey again and log in.').'
<br /><br />'.$this->l('To unsubscribe or for any question, please contact Twenga on your account.').'
<div style="margin: 10px 0 5px 0; font-size:14px; color:#FFF; text-align:center;">
<b><a '.(($_POST['type'] == 'uninstall') ?
'onClick="$.fancybox.close(); window.location=\''.Tools::safeOutput($url).'\' '.
$this->_getAjaxScript('send_mail.php', Tools::safeOutput($_POST['type']), Tools::safeOutput($url), false).'"' : ' ') .
'href="'.Tools::safeOutput($url).'">'.Tools::safeOutput($type).'</a></b> -
<b><a href="'.Tools::safeOutput($link).'">'.
$this->l('Newer version').'</a></b> -
<b><a href="javacript:void(0);"i onclick="$.fancybox.close(); return false;">'.
$this->l('Cancel').'</a></b>
</div></p>';
echo $msg;
}
}
/*
** Get the javascript code to fetch a distant file
** href will be automatically split cause of its '&'
*/
private function _getAjaxScript($file, $type, $href, $displayMsg = true)
{
global $cookie;
return '
$.ajax({
type: \'POST\',
url: \''._MODULE_DIR_.'twenga/'.$file.'\',
data: \'type='.$type.'&base='.$href.'&twenga_token='.sha1(Configuration::get('TWENGA_TOKEN')._COOKIE_KEY_).'&id_lang='.(int)$cookie->id_lang.'\',
success: function(msg) {
'.(($displayMsg) ? '
$.fancybox(msg, {
\'autoDimensions\' : false,
\'width\' : 450,
\'height\' : \'auto\',
\'transitionIn\' : \'none\',
\'transitionOut\' : \'none\' });'
: '') . '
}
});
return false;';
}
/**
* Method for beeing redirected to Twenga subscription
*/
private static function redirectTwengaSubscription($link)
{
echo '<script type="text/javascript" language="javascript">window.open("'.$link.'");</script>';
}
private function submitTwengaLogin()
{
if (!self::$obj_twenga->setHashkey($_POST['twenga_hashkey']))
$this->_errors[] = $this->l('Your hashkey is invalid. Please check the e-mail already sent by Twenga.');
if (!self::$obj_twenga->setUserName($_POST['twenga_user_name']))
$this->_errors[] = $this->l('Your user name is invalid. Please check the e-mail already sent by Twenga.');
if (!self::$obj_twenga->setPassword($_POST['twenga_password']))
$this->_errors[] = $this->l('Your password is invalid. Please check the e-mail already sent by Twenga.');
if (empty($this->_errors))
{
$bool_save = false;
try
{
$bool_save = self::$obj_twenga->saveMerchantLogin();
self::$obj_ps_stats->validateSubscription();
if (!$bool_save)
$this->_errors[] = $this->l('Authentication failed.')."<br />\n"
.$this->l('Please review the e-mail sent by Twenga after subscription. If error still occurred, contact Twenga service.');
else
{
self::$obj_twenga->addFeed(array('feed_url' => $this->feed_url));
$this->_html = '
<div class="conf feed_url">
'.$this->l('Your product export URL has successfully been created and shared with the Twenga team:').'<br /> <a href="'.$this->feed_url.'" target="_blank">'.$this->feed_url.'</a>
</div>
';
Configuration::updateValue('TWENGA_CONFIGURATION_OK', true);
}
}
catch (Exception $e)
{
$this->_errors[] = nl2br($e->getMessage());
}
}
}
private function submitTwengaActivateTracking()
{
$activate = false;
// Use TwengaObj::siteActivate() method to activate tracking.
try
{
$activate = self::$obj_twenga->siteActivate();
}
catch (Exception $e)
{
$this->_errors[] = $e->getMessage();
}
if ($activate)
{
$this->_html = '
<div class="conf">
'.$this->l('Your sales tracking is enabled.').'</a>
</div>
';
$this->registerHook('displayHome');
$this->registerHook('displayProductButtons');
$this->registerHook('displayShoppingCart');
$this->registerHook('displayPayment');
$this->registerHook('payment');
$this->registerHook('orderConfirmation');
}
}
private function submitTwengaDisableTracking()
{
$return = Db::getInstance()->ExecuteS('SELECT `id_hook` FROM `'._DB_PREFIX_.'hook_module` WHERE `id_module` = \''.pSQL($this->id).'\'');
foreach ($return as $hook)
$this->unregisterHook($hook['id_hook']);
}
public function preProcess()
{
if (isset($_POST['submitTwengaSubscription']))
$this->submitTwengaSubscription();
if (isset($_POST['submitTwengaLogin']))
$this->submitTwengaLogin();
if (isset($_POST['submitTwengaActivateTracking']))
$this->submitTwengaActivateTracking();
if (isset($_POST['submitTwengaDisableTracking']))
$this->submitTwengaDisableTracking();
}
/**
* Function HOOK Home
*/
public function hookDisplayHome($params)
{
return $this->doHook($params, 'home');
}
/**
* Function HOOK Product
*/
public function hookDisplayProductButtons($params)
{
return $this->doHook($params, 'product');
}
/**
* Function HOOK Basket
*/
public function hookDisplayShoppingCart($params)
{
return $this->doHook($params, 'basket');
}
/**
* Function HOOK Transaction
*/
public function hookPayment($params)
{
return $this->doHook($params, 'basket');
}
public function hookOrderConfirmation($params){
return $this->doHook($params, 'transaction');
}
/**
* Function DO HOOK
*/
public function doHook($aParams, $sEvent = '')
{
if ($this->_allowToWork == false) return;
$oCustomer = new Customer($aParams['cart']->id_customer);
$oCurrency = new Currency($aParams['cart']->id_currency);
$aAddress = $oCustomer->getAddresses($aParams['cart']->id_lang);
$aAddress = $aAddress[0];
$sUserCountry = '';
if(isset($aAddress['id_country']) && !empty($aAddress['id_country'])){
$sUserCountry = Country::getIsoById($aAddress['id_country']);
}
// for 1.3 compatibility
$tva = false;
if(isset($aParams['objOrder']) && !empty($aParams['objOrder'])){
$tax = ($aParams['objOrder']->total_paid_tax_incl-$aParams['objOrder']->total_shipping_tax_incl) - ($aParams['objOrder']->total_paid_tax_excl-$aParams['objOrder']->total_shipping_tax_excl);
$tva = $aParams['objOrder']->carrier_tax_rate;
}else{
$tax = $aParams['cart']->getOrderTotal(true, Twenga::ONLY_PRODUCTS_WITHOUT_SHIPPING)-$aParams['cart']->getOrderTotal(false, Twenga::ONLY_PRODUCTS_WITHOUT_SHIPPING);
if($aParams['cart']->getOrderTotal(false, Twenga::ONLY_PRODUCTS_WITHOUT_SHIPPING)>0){
$tva = ($tax * 100) / $aParams['cart']->getOrderTotal(false, Twenga::ONLY_PRODUCTS_WITHOUT_SHIPPING);
}
}
$aParamsToTwenga = array();
$aParamsToTwenga['event'] = $sEvent;
$aParamsToTwenga['user_id'] = $aParams['cart']->id_customer;
$aParamsToTwenga['user_global_id'] = md5($oCustomer->email);
$aParamsToTwenga['user_email'] = $oCustomer->email;
$aParamsToTwenga['user_firstname'] = $oCustomer->firstname;
$aParamsToTwenga['user_city'] = ($aParams['cart']->id_customer)? $aAddress['city'] : '';
$aParamsToTwenga['user_state'] = ($aParams['cart']->id_customer)? $aAddress['state'] : '';
$aParamsToTwenga['user_country'] = ($aParams['cart']->id_customer)? $sUserCountry : '';
$aParamsToTwenga['user_segment'] = '';
$aParamsToTwenga['user_is_customer'] = 1;
$aParamsToTwenga['ecommerce_platform'] = 'Prestashop';
$aParamsToTwenga['tag_platform'] = '';
$aParamsToTwenga['basket_id'] = $aParams['cart']->id;
$aParamsToTwenga['currency'] = $oCurrency->iso_code;
$aParamsToTwenga['total_ht'] = isset($aParams['objOrder']) ? $aParams['objOrder']->total_paid_tax_excl-$aParams['objOrder']->total_shipping_tax_excl : $aParams['cart']->getOrderTotal(false, Twenga::ONLY_PRODUCTS_WITHOUT_SHIPPING);
$aParamsToTwenga['tva'] = ($tva !== false) ? Tools::ps_round($tva, 2) : '';
$aParamsToTwenga['total_ttc'] = isset($aParams['objOrder']) ? $aParams['objOrder']->total_paid_tax_incl-$aParams['objOrder']->total_shipping_tax_incl : $aParams['cart']->getOrderTotal(true, Twenga::ONLY_PRODUCTS_WITHOUT_SHIPPING);
$aParamsToTwenga['shipping'] = isset($aParams['objOrder']) ? $aParams['objOrder']->total_shipping_tax_incl : $aParams['cart']->getOrderTotal(true, Twenga::ONLY_SHIPPING);
$aParamsToTwenga['tax'] = $tax;
if(isset($aParams['objOrder']) && !empty($aParams['objOrder'])){
$aParamsToTwenga['order_id'] = $aParams['objOrder']->id;
}
$aParamsToTwenga['items'] = array();
if($sEvent == 'product' && (isset($_POST['id_product'])) || isset($_GET['id_product'])){
$iIdProduct = (isset($_POST['id_product'])) ? $_POST['id_product'] : $_GET['id_product'];
$oProduct = new Product($iIdProduct);
if($oProduct){
$oCategory = new Category($oProduct->id_category_default);
if($oCategory){
$arr_item = array();
$arr_item['price'] = $oProduct->price;
$arr_item['quantity'] = '';
$arr_item['ref_id'] = $oProduct->reference;
$arr_item['item_id'] = $iIdProduct;
$arr_item['name'] = $oProduct->name[1];
$arr_item['category_name'] = $oCategory->name;
$aParamsToTwenga['items'][] = $arr_item;
}
}
}elseif(isset($aParams['objOrder']) && !empty($aParams['objOrder'])){
foreach ($aParams['objOrder']->getProducts() as $product)
{
$oCategory = new Category($product['id_category_default']);
$arr_item = array();
if ($product['unit_price_tax_excl']!= '')
$arr_item['price'] = (float)$product['unit_price_tax_excl'];
if ($product['product_quantity'] != '')
$arr_item['quantity'] = (int)$product['product_quantity'];
if ($product['reference'] != '')
$arr_item['ref_id'] = (string)$product['reference'];
if ($product['id_product'] != '')
$arr_item['item_id'] = (string)$product['id_product'];
if ($product['product_name'] != '')
$arr_item['name'] = (string)$product['product_name'];
if (isset($oCategory) && !empty($oCategory))
$arr_item['category_name'] = $oCategory->name;
$aParamsToTwenga['items'][] = $arr_item;
}
}else{
foreach ($aParams['cart']->getProducts() as $product)
{
$arr_item = array();
if ($product['price']!= '')
$arr_item['price'] = (float)$product['price'];
if ($product['cart_quantity'] != '')
$arr_item['quantity'] = (int)$product['cart_quantity'];
if ($product['reference'] != '')
$arr_item['ref_id'] = (string)$product['reference'];
if ($product['id_product'] != '')
$arr_item['item_id'] = (string)$product['id_product'];
if ($product['name'] != '')
$arr_item['name'] = (string)$product['name'];
if ($product['category'])
$arr_item['category_name'] = (string)$product['category'];
$aParamsToTwenga['items'][] = $arr_item;
}
}
$aParamsToTwenga = array_filter($aParamsToTwenga);
try
{
$tracking_code = self::$obj_twenga->getTrackingScript($aParamsToTwenga);
return $tracking_code;
}
catch (TwengaFieldsException $e)
{
return $this->l('Error occurred when params passed in Twenga API').' : <br />'.$e->getMessage();
}
catch (Exception $e)
{
return $e->getMessage();
}
}
/*
** Get the current country name used literaly
*/
public static function getCurrentCountryName()
{
global $cookie;
$id_lang = ((isset($cookie->id_lang)) ? (int)$cookie->id_lang :
((isset($_POST['id_lang'])) ? (int)$_POST['id_lang'] : NULL));
if ($id_lang === NULL)
return 'Undefined id_lang';
$country = Db::getInstance()->ExecuteS('
SELECT c.name as name
FROM '._DB_PREFIX_.'country_lang as c
WHERE c.id_lang = '.(int)$id_lang.'
AND c.id_country = '.(int)Configuration::get('PS_COUNTRY_DEFAULT'));
if (!isset($country[0]['name']))
$country[0]['name'] = 'Undefined';
return $country[0]['name'];
}
/*
** Check if the default country if available with the restricted ones
*/
private function _checkCurrentCountrie()
{
global $cookie;
if (!in_array(strtolower($this->_currentIsoCodeCountry), $this->limited_countries))
{
$query = '
SELECT c_l.name as name
FROM '._DB_PREFIX_.'country_lang as c_l
LEFT JOIN '._DB_PREFIX_.'country as c
ON c_l.id_country = c.id_country
WHERE c_l.id_lang = '.(int)$cookie->id_lang.'
AND c.iso_code IN (';
foreach ($this->limited_countries as $iso)
$query .= "'".strtoupper($iso)."', ";
$query = rtrim($query, ', ').')';
$countriesName = Db::getInstance()->ExecuteS($query);
$htmlError = '
<div class="error">
<p>'.$this->l('Your default country is').' : '.Twenga::getCurrentCountryName().'</p>
<p>'.$this->l('Please select one of these available countries approved by Twenga').' :</p>
<ul>';
foreach ($countriesName as $c)
$htmlError .= '<li>'.$c['name'].'</li>';
$url = Tools::getShopDomain(true).$_SERVER['PHP_SELF'].'?tab=AdminCountries&token='.
Tools::getAdminTokenLite('AdminCountries').'#Countries';
$htmlError .= '
</ul>
'.$this->l('Follow this link to change the country').
' : <a style="color:#0282dc;" href="'.$url.'">here</a>
</div>';
throw new Exception($htmlError);
}
}
public function getContent()
{
try
{
$this->_checkCurrentCountrie();
if ((Configuration::get('PS_ORDER_PROCESS_TYPE') == 1 && $this->isRegisteredInHook('displayPayment')) ||
(Configuration::get('PS_ORDER_PROCESS_TYPE') == 1 && $this->isRegisteredInHook('Payment')))
{
$this->submitTwengaActivateTracking();
}
}
catch (Exception $e)
{
return $e->getMessage();
}
// API can't be call if curl extension is not installed on PHP config.
if (!extension_loaded('curl'))
{
$this->_errors[] = $this->l('Please activate the PHP extension \'curl\' to allow use of Twenga webservice library.');
return $this->displayErrors();
}
$this->preProcess();
if ($this->_hasConfigTwenga() && !$this->isRegisteredInHook('displayPayment') && !$this->isRegisteredInHook('Payment')){
$this->_html .= $this->displayEnableTracker();
}
$this->_html .= '<h2>'.$this->displayName.'</h2>';
$this->_html .= $this->displayTwengaIntro();
if (!$this->_hasConfigTwenga()){
$this->_html .= $this->displayTwengaHowTo();
}
$this->_html .= $this->displayTwengaLogin();
if ($this->_hasConfigTwenga()){
if($this->isRegisteredInHook('displayPayment') || $this->isRegisteredInHook('Payment')){
$this->_html .= $this->displayDisableTracker();
}
$this->_html .= $this->displayFeedUrl();
}
$this->_html .= $this->displayTwengaTestimony();
return $this->displayErrors().$this->_html;
}
public function displayTwengaHowTo()
{
global $cookie;
$isoUser = strtolower(Language::getIsoById(intval($cookie->id_lang)));
if ($isoUser == 'gb' || $isoUser == 'en')
$link_tools = 'https://rts.twenga.co.uk/account';
elseif ($isoUser == 'es')
$link_tools = 'https://rts.twenga.es/account';
elseif ($isoUser == 'it')
$link_tools = 'https://rts.twenga.it/account';
elseif ($isoUser == 'de')
$link_tools = 'https://rts.twenga.de/account';
else
$link_tools = 'https://rts.twenga.fr/account';
$str_return = '
<fieldset class="moduleTwenga-referencement">
<legend><img src="../modules/'.$this->name.'/img/logo-small.png" width="16" height="16" class="middle" /> '.$this->l('A - List your website on Twenga').'</legend>
<div class="no-inscr">
<img src="../modules/'.$this->name.'/img/puce.png" width="16" height="16" alt="Twenga" /> <a href="#" class="display">'.$this->l('You have never had a Twenga Ready to Sell account').'</a>
<ol>
<li><a href="'.$this->inscription_url.'" target="_blank">'.$this->l('Fill out the Twenga Ready to Sell application forms.').'</a></li>
<li>'.$this->l('Once you have received your Twenga key/hashkey via e-mail, come back to this page and copy it into the "Hashkey" field below.').'</li>
<li>'.$this->l('Click on Activate my Twenga Export to create your export product feed.').'</li>
</ol>
</div>
<div class="inscr">
<img src="../modules/'.$this->name.'/img/puce.png" width="16" height="16" alt="Twenga" /> <a href="#" class="display">'.$this->l('You are already registered to the Twenga Ready to Sell programme').'</a>
<ol>
<li>'.$this->l('Get your Twenga key directly from your').' <a href="'.$link_tools.'" target="_blank"> '.$this->l('Twenga Ready to Sell interface.').'</a></li>
<li>'.$this->l('Return to this page and copy your key into the "Hashkey" field below.').'</li>
<li>'.$this->l('Click on Activate my Twenga Export to create your export product feed.').'</li>
</ol>
</div>
</fieldset>
';
return $str_return;
}
public function displayTwengaIntro()
{
global $cookie;
$isoUser = strtolower(Language::getIsoById(intval($cookie->id_lang)));
$defaultIsoCountry = strtolower($this->_currentIsoCodeCountry);
$errors = array();
try
{
$return = self::$obj_twenga->getSubscriptionLink(array('site_url' => $this->site_url, 'feed_url' => $this->feed_url, 'country' => $isoUser, 'module_version' => (string)$this->version, 'platform_version' => (string)_PS_VERSION_));
$this->inscription_url= $return['message'];
}
catch (TwengaFieldsException $e)
{
$errors[] = $e->getMessage();
}
catch (TwengaException $e)
{
$errors[] = $e->getMessage();
}
if (!empty($errors))
{
$str_error = $this->l('Errors occurred with the Twenga API subscription link:');
$str_error .= '<ol>';
foreach ($errors as $error)
$str_error .= '<li><em>'.$error.'</em></li>';
$str_error .= '</ol>';
$this->_errors[] = $str_error;
}
if ($isoUser == 'gb' || $isoUser == 'en')
$tarifs_link = 'https://rts.twenga.co.uk/ratecard';
elseif ($isoUser == 'es')
$tarifs_link = 'https://rts.twenga.es/ratecard';
elseif ($isoUser == 'it')
$tarifs_link = 'https://rts.twenga.it/ratecard';
elseif ($isoUser == 'de')
$tarifs_link = 'https://rts.twenga.de/ratecard';
else
$tarifs_link = 'https://rts.twenga.fr/ratecard';
$tarif_arr = array(950, 565);
if (extension_loaded('openssl') && file_exists($tarifs_link))
$tarif_arr = @getimagesize($tarifs_link);
$str_return = '
<script type="text/javascript">
$().ready(function()
{
$("#twenga_tarif").click(function(e){
e.preventDefault();
window.open("'.$tarifs_link.'", "", "width='.$tarif_arr[0].', height='.$tarif_arr[1].', scrollbars=no, menubar=no, status=no" );
});
$(".moduleTwenga-referencement ol").hide();
$(".display").click(function(){
$(this).next(".moduleTwenga-referencement ol").slideToggle();
$(this).prev(".moduleTwenga-referencement img").toggleClass("rotate");
return false;
});
});
</script>
<link type="text/css" rel="stylesheet" href="../modules/'.$this->name.'/css/module-twenga.css" />
<div class="module-twenga">
<div class="moduleTwenga-intro" style="background-image:url(../modules/'.$this->name.'/img/cible-twenga.png);")>
<p><img src="../modules/'.$this->name.'/img/logo-twenga.png" width="200" height="43" alt="Twenga" /></p>
<p class="module-title">'.$this->l('List your products and increase your sales.').'</p>
<dl>
<dt>'.$this->l('Manage your budget:').'</dt>
<dd>'.$this->l('You pay for the traffic that Twenga sends you using CPC. Joining Twenga and setting up your account is free of charge.').'<br /> '.$this->l('If needs be, you can set up a monthly budget limit.').'</dd>
<dt>'.$this->l('Manage your activity and sales:').'</dt>
<dd>'.$this->l('Dedicated merchant interface including detailed traffic & sales support tools.').'</dd>
<dt>'.$this->l('Manage your visibility:').'</dt>
<dd>'.$this->l('Boost product visibility whenever you like!').'</dd>
</dl>
<p class="module-title">'.$this->l('More than 15,000 merchants have already joined Twenga Ready to Sell.').'</p>
</div>
';
return $str_return;
}
public function displayFeedUrl()
{
$output = '
<br />
<fieldset class="moduleTwenga-referencement">
<legend><img src="../modules/'.$this->name.'/img/logo-small.png" width="16" height="16" class="middle" /> '.$this->l('Your Twenga Product Export').'</legend>
<p>'.$this->l('Your product export URL has successfully been created and shared with the Twenga team:').'</p>
<p>'.$this->feed_url.'</p>
</fieldset>
';
return $output;
}
/**
* @return string html form for log to Twenga API.
*/
private function displayTwengaLogin()
{
global $cookie;
$isoUser = strtolower(Language::getIsoById(intval($cookie->id_lang)));
if ($isoUser == 'gb' || $isoUser == 'en')
$lost_link = 'https://rts.twenga.co.uk/lostpassword';
else
$lost_link = 'https://rts.twenga.'.$isoUser.'/lostpassword';
if ($isoUser == 'gb' || $isoUser == 'en')
$tarifs_link = 'https://rts.twenga.co.uk/ratecard';
elseif ($isoUser == 'es')
$tarifs_link = 'https://rts.twenga.es/ratecard';
elseif ($isoUser == 'it')
$tarifs_link = 'https://rts.twenga.it/ratecard';
elseif ($isoUser == 'de')
$tarifs_link = 'https://rts.twenga.de/ratecard';
else
$tarifs_link = 'https://rts.twenga.fr/ratecard';
$output = '
<form name="form_set_hashkey" action="" method="post">
<fieldset class="moduleTwenga-installation">
<legend>
<img src="../modules/'.$this->name.'/img/logo-small.png" width="16" height="16" class="middle" /> ';
if (((self::$obj_twenga->getHashKey() === NULL || self::$obj_twenga->getHashKey() === '')) &&
((self::$obj_twenga->getUserName() === NULL || self::$obj_twenga->getUserName() === '')) &&
((self::$obj_twenga->getPassword() === NULL || self::$obj_twenga->getPassword() === '')))
$output .= $this->l('B - Installation of Sales Tracking');
else
$output .= $this->l('B - Configuration');
$output .= '</legend>';
if(self::$obj_twenga->getHashKey() === NULL || self::$obj_twenga->getHashKey() === '')
{
$output .= '<p class="marginBottom">'.$this->l('Enter here your Twenga Ready to Sell hashkey and Login / Pass').'</p>';
}
$output .= '
<div class="moduleTwenga-form">
<div class="field"><label for="key-twenga"> '.$this->l('Twenga key/HashKey').' <sup>*</sup> :</label> <input id="key-twenga" type="text" size="38" maxlength="32" name="twenga_hashkey" value="'.Tools::safeOutput(self::$obj_twenga->getHashKey()).'"/></div>
<div class="field"><label for="login-twenga">'.$this->l('Twenga Ready to Sell username (your email)').' <sup>*</sup> :</label> <input id="login-twenga" type="text" size="38" maxlength="64" name="twenga_user_name" value="'.Tools::safeOutput(self::$obj_twenga->getUserName()).'"/></div>
<div class="field"><label for="pass-twenga">'.$this->l('Twenga Ready to Sell password').' <sup>*</sup> :</label> <input id="pass-twenga" type="password" size="38" maxlength="64" name="twenga_password" value="'.Tools::safeOutput(self::$obj_twenga->getPassword()).'"/> <a href="'.$lost_link.'" target="_blank">'.$this->l('Forgotten your password?').'</a></div>'
.'<p><input type="submit" value="'.$this->l('Activate my Twenga export').'" name="submitTwengaLogin" class="button"/></p>
</div>
<p class="marginBottom">'.$this->l('Your catalogue will be listed in approximately 72 hours.').'</p>
<p class="marginBottom">'.$this->l('Once your products appear on Twenga, you will receive additional traffic which will by billed using CPC (cost per click).').'<br /> '.$this->l('You can consult').' <a href="'.$tarifs_link.'">'.$this->l('our CPC rates by category.').'</a></p>
<p class="marginBottom">'.$this->l('You will benefit from detailed traffic & sales supports tools, allowing you total control on your activity on Twenga.').'</p>
</fieldset>
</form>
</div>';
return $output;
}
/**
* @return string html testimony
*/
private function displayTwengaTestimony()
{
global $cookie;
$isoUser = strtolower(Language::getIsoById(intval($cookie->id_lang)));
if ($isoUser == 'gb' || $isoUser == 'en')
$link_banner = 'banner-en';
elseif ($isoUser == 'es')
$link_banner = 'banner-es';
elseif ($isoUser == 'it')
$link_banner = 'banner-it';
elseif ($isoUser == 'de')
$link_banner = 'banner-de';
else
$link_banner = 'banner-fr';
$output = '<div class="banner-twenga"><img src="../modules/'.$this->name.'/img/'.$link_banner.'.png" width="1000" height="150" alt="Awards" /></div>';
return $output;
}
/**
* @return bool if user has config twenga ok
*/
private function _hasConfigTwenga()
{
if ( (self::$obj_twenga->getHashKey() === NULL || self::$obj_twenga->getHashKey() === '')
|| (self::$obj_twenga->getUserName() === NULL || self::$obj_twenga->getUserName() === '')
|| (self::$obj_twenga->getPassword() === NULL || self::$obj_twenga->getPassword() === '')){
return false;
}else{
return true;
}
}
/**
* @return string html form for activate or disable the Twenga tracking
*/
private function displayEnableTracker()
{
global $cookie;
$isoUser = strtolower(Language::getIsoById(intval($cookie->id_lang)));
if ($isoUser == 'gb' || $isoUser == 'en')
$site_link = 'https://rts.twenga.co.uk/';
elseif ($isoUser == 'es')
$site_link = 'https://rts.twenga.es/';
elseif ($isoUser == 'it')
$site_link = 'https://rts.twenga.it/';
elseif ($isoUser == 'de')
$site_link = 'https://rts.twenga.de/';
else
$site_link = 'https://rts.twenga.fr/';
$str = '
<form name="form_twenga_activate" method="post" action="">
<fieldset class="moduleTwenga-activation">
<legend><img src="../modules/'.$this->name.'/img/logo-small.png" width="16" height="16" class="middle" />%s</legend>
<p>'.$this->l('Only one more step to go!').' <br />
%s</p>
<p><input type="submit" name="%s" class="button" value="%s" /></p>
<p>'.$this->l('Your statistics tracking is available from').' <a href="'.$site_link.'" target="_blank">'.$this->l('your Twenga Ready to Sell interface').'</a>.</p>
</fieldset>
</form>';
if ( !$this->isRegisteredInHook('displayCarrierList') && !$this->isRegisteredInHook('displayPayment') && !$this->isRegisteredInHook('Payment') ){
$str = sprintf($str, $this->l('Activate Tracking'), $this->l('To activate tracking, click on the following button :'), 'submitTwengaActivateTracking', $this->l('Install Twenga sales tracking in just 1 click'));
}
return $str;
}
/**
* @return string html form for activate or disable the Twenga tracking
*/
private function displayDisableTracker()
{
global $cookie;
$isoUser = strtolower(Language::getIsoById(intval($cookie->id_lang)));
if ($isoUser == 'gb' || $isoUser == 'en')
$site_link = 'https://rts.twenga.co.uk/';
elseif ($isoUser == 'es')
$site_link = 'https://rts.twenga.es/';
elseif ($isoUser == 'it')
$site_link = 'https://rts.twenga.it/';
elseif ($isoUser == 'de')
$site_link = 'https://rts.twenga.de/';
else
$site_link = 'https://rts.twenga.fr/';
$str = '
<div class="disable-twenga"><form name="form_twenga_activate" method="post" action="">
<fieldset>
<legend><img src="../modules/'.$this->name.'/img/logo-small.png" width="16" height="16" class="middle" />%s</legend>
<p>%s</p>
<p><input type="submit" name="%s" class="button" value="%s" /></p>
<p>'.$this->l('Your statistics tracking is available from').' <a target="_blank" href="'.$site_link.'">'.$this->l('your Twenga Ready to Sell interface').'</a>.</p>
</fieldset>
</form></div>';
if ( $this->isRegisteredInHook('displayCarrierList') || $this->isRegisteredInHook('displayPayment') || $this->isRegisteredInHook('Payment') ){
$str = sprintf($str, $this->l('Your Twenga sales tracking'), $this->l('Your sales tracking allow you to measure conversion and benefit from optimised traffic.'), 'submitTwengaDisableTracking', $this->l('Uninstall my Twenga Sales Tracking'));
}
return $str;
}
/**
* Just set in one method the displaying error message in PrestaShop back-office.
*/
private function displayErrors()
{
$string = '';
if (!empty($this->_errors))
foreach ($this->_errors as $error)
$string .= $this->displayError($error);
return $string;
}
/**
* Used by export.php to build the feed required by Twenga.
* See detailed comments in the body of the method
* @see Twenga::preparedValues() to see how needed tags for feed are filled
*/
public function buildXML()
{
// this check if the module is installed and if the site is registered at Twenga
$bool_site_exists = true;
if (self::$obj_twenga->getHashkey() === NULL)
{
$this->_errors[] = $this->l('The hash key must be set for used Twenga API.');
$bool_site_exists = false;
}
if ($bool_site_exists)
{
try
{
$bool_site_exists = self::$obj_twenga->siteExist();
}
catch (Exception $e)
{
$this->_errors[] = $e->getMessage().$this->l('Some parameters missing, or the site doesn\'t exist');
$bool_site_exists = false;
}
}
if (!$bool_site_exists)
return $this->displayErrors();
// Now method build the XML
echo '<?xml version="1.0" encoding="utf-8"?><catalog>';
$parameters = Configuration::getMultiple(array('PS_REWRITING_SETTINGS', 'PS_LANG_DEFAULT', 'PS_SHIPPING_FREE_PRICE', 'PS_SHIPPING_HANDLING', 'PS_SHIPPING_METHOD', 'PS_SHIPPING_FREE_WEIGHT', 'PS_COUNTRY_DEFAULT'));
$lang = (int)$parameters['PS_LANG_DEFAULT'];
$language = new Language($lang);
$carrier = new Carrier(Configuration::get('PS_CARRIER_DEFAULT'), $language->id);
$defaultCountry = new Country(Configuration::get('PS_COUNTRY_DEFAULT'), $language->id);