forked from PrestaShopCorp/ebay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ebay.php
2068 lines (1733 loc) · 68.6 KB
/
ebay.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-2015 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-2015 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/* Security*/
if (!defined('_PS_VERSION_'))
exit;
/* Loading eBay Class Request*/
$classes_to_load = array(
'EbayRequest',
'EbayCategory',
'EbayCategoryConfiguration',
'EbayDeliveryTimeOptions',
'EbayOrder',
'EbayProduct',
'EbayReturnsPolicy',
'EbayShipping',
'EbayShippingLocation',
'EbayShippingService',
'EbayShippingZoneExcluded',
'EbayShippingInternationalZone',
'EbaySynchronizer',
'EbayPayment',
'EbayCategoryConditionConfiguration',
'EbayCategorySpecific',
'EbayProductConfiguration',
'EbayProductImage',
'EbayProfile',
'EbayReturnsPolicyConfiguration',
'EbayConfiguration',
'EbayProductModified',
'EbayLog',
'EbayLoadLogs',
'EbayApiLog',
'EbayOrderLog',
'EbayStat',
'TotFormat',
'EbayValidatorTab',
'TotCompatibility',
'EbayProductTemplate',
'EbayStoreCategory',
'EbayStoreCategoryConfiguration',
'tabs/EbayTab',
'tabs/EbayFormParametersTab',
'tabs/EbayFormAdvancedParametersTab',
'tabs/EbayFormCategoryTab',
'tabs/EbayFormItemsSpecificsTab',
'tabs/EbayFormShippingTab',
'tabs/EbayFormTemplateManagerTab',
'tabs/EbayFormEbaySyncTab',
'tabs/EbayOrderHistoryTab',
'tabs/EbayHelpTab',
'tabs/EbayListingsTab',
'tabs/EbayFormStoreCategoryTab',
'tabs/EbayApiLogsTab',
'tabs/EbayOrderLogsTab',
'tabs/EbayOrdersSyncTab',
'tabs/EbayPrestashopProductsTab',
'tabs/EbayOrphanListingsTab'
);
foreach ($classes_to_load as $classname)
if (file_exists(dirname(__FILE__).'/classes/'.$classname.'.php'))
require_once(dirname(__FILE__).'/classes/'.$classname.'.php');
if(!function_exists('bqSQL'))
{
function bqSQL($string)
{
return str_replace('`', '\`', pSQL($string));
}
}
/* Checking compatibility with older PrestaShop and fixing it*/
if (!defined('_MYSQL_ENGINE_'))
define('_MYSQL_ENGINE_', 'MyISAM');
class Ebay extends Module
{
private $html = '';
private $ebay_country;
public $ebay_profile;
private $is_multishop;
private $stats_version;
/**
* Construct Method
*
**/
public function __construct($id_ebay_profile = null)
{
$this->name = 'ebay';
$this->tab = 'market_place';
$this->version = '1.11.0';
$this->stats_version = '1.0';
$this->author = 'PrestaShop';
parent::__construct();
/** Backward compatibility */
require(_PS_MODULE_DIR_.$this->name.'/backward_compatibility/backward.php');
$this->displayName = $this->l('eBay');
$this->description = $this->l('Easily export your products from PrestaShop to eBay, the biggest market place, to acquire new customers and realize more sales.');
$this->module_key = '7a6b007a219bab59c1611254347f21d5';
// Checking Extension
$this->_checkExtensionsLoading();
// Checking compatibility with older PrestaShop and fixing it
if (!Configuration::get('PS_SHOP_DOMAIN'))
$this->setConfiguration('PS_SHOP_DOMAIN', $_SERVER['HTTP_HOST']);
// Generate eBay Security Token if not exists
if (!Configuration::get('EBAY_SECURITY_TOKEN'))
$this->setConfiguration('EBAY_SECURITY_TOKEN', Tools::passwdGen(30));
// For 1.4.3 and less compatibility
$update_config = array(
'PS_OS_CHEQUE' => 1,
'PS_OS_PAYMENT' => 2,
'PS_OS_PREPARATION' => 3,
'PS_OS_SHIPPING' => 4,
'PS_OS_DELIVERED' => 5,
'PS_OS_CANCELED' => 6,
'PS_OS_REFUND' => 7,
'PS_OS_ERROR' => 8,
'PS_OS_OUTOFSTOCK' => 9,
'PS_OS_BANKWIRE' => 10,
'PS_OS_PAYPAL' => 11,
'PS_OS_WS_PAYMENT' => 12
);
foreach ($update_config as $key => $value)
if (!Configuration::get($key))
{
$const_name = '_'.$key.'_';
if ((int)constant($const_name))
$this->setConfiguration($key, constant($const_name));
else
$this->setConfiguration($key, $value);
}
$this->is_multishop = (version_compare(_PS_VERSION_, '1.5', '>') && Shop::isFeatureActive());
// Check if installed
if (self::isInstalled($this->name))
{
// Upgrade eBay module
if (Configuration::get('EBAY_VERSION') != $this->version)
$this->_upgrade();
//if (!empty($_POST) && Tools::getValue('ebay_profile'))
if (!empty($_POST)) {
// called after adding a profile
if ((Tools::getValue('action') == 'logged') && Tools::isSubmit('ebayRegisterButton'))
$this->_postProcessAddProfile();
elseif (Tools::getValue('ebay_profile'))
$this->_postProcessConfig();
}
if(class_exists('EbayCountrySpec'))
{
if (!$this->ebay_profile)
{
if ($id_ebay_profile)
$this->ebay_profile = new EbayProfile($id_ebay_profile);
else
$this->ebay_profile = EbayProfile::getCurrent();
}
if ($this->ebay_profile)
{
// Check the country
$this->ebay_country = EbayCountrySpec::getInstanceByKey($this->ebay_profile->getConfiguration('EBAY_COUNTRY_DEFAULT'));
if (!$this->ebay_country->checkCountry())
{
$this->warning = $this->l('The eBay module currently works for eBay.fr, eBay.it, eBay.co.uk, eBay.pl, eBay.nl and eBay.es');
return false;
}
}
else
{
$iso_country = Tools::strtolower(Country::getIsoById(Configuration::get('PS_COUNTRY_DEFAULT')));
$iso_lang = Tools::strtolower(Language::getIsoById(Configuration::get('PS_LANG_DEFAULT')));
$this->ebay_country = EbayCountrySpec::getInstanceByCountryAndLang($iso_country,$iso_lang);
return false;
}
}
// Warning uninstall
$this->confirmUninstall = $this->l('Are you sure you want to uninistall this module? All configuration settings will be lost');
}
}
/**
* Test if the different php extensions are loaded
* and update the warning var
*
*/
private function _checkExtensionsLoading()
{
if (!extension_loaded('curl') || !ini_get('allow_url_fopen'))
{
if (!extension_loaded('curl') && !ini_get('allow_url_fopen'))
$this->warning = $this->l('You must enable cURL extension and allow_url_fopen option on your server if you want to use this module.');
elseif (!extension_loaded('curl'))
$this->warning = $this->l('You must enable cURL extension on your server if you want to use this module.');
elseif (!ini_get('allow_url_fopen'))
$this->warning = $this->l('You must enable allow_url_fopen option on your server if you want to use this module.');
}
}
/**
* Install module
*
* @return boolean
*/
public function install()
{
// Install SQL
include(dirname(__FILE__).'/sql/sql-install.php');
foreach ($sql as $s)
if (!Db::getInstance()->execute($s))
return false;
// Install Module
if (!parent::install()
|| !$this->registerHook('addProduct')
|| !$this->registerHook('updateProduct')
|| !$this->registerHook('deleteProduct')
|| !$this->registerHook('newOrder')
|| !$this->registerHook('backOfficeTop')
|| !$this->registerHook('header'))
return false;
$hook_update_quantity = version_compare(_PS_VERSION_, '1.5', '>') ? 'actionUpdateQuantity' : 'updateQuantity';
if (!$this->registerHook($hook_update_quantity))
return false;
$hook_update_order_status = version_compare(_PS_VERSION_, '1.5', '>') ? 'actionOrderStatusUpdate' : 'updateOrderStatus';
if (!$this->registerHook($hook_update_order_status))
return false;
$this->ebay_profile = EbayProfile::getCurrent();
$this->setConfiguration('EBAY_INSTALL_DATE', date('Y-m-d\TH:i:s.000\Z'));
// Picture size
if ($this->ebay_profile)
$this->ebay_profile->setPicturesSettings();
// Init
$this->setConfiguration('EBAY_VERSION', $this->version);
$this->setConfiguration('EBAY_ORDERS_DAYS_BACKWARD', 30);
$this->setConfiguration('EBAY_LOGS_DAYS', 30);
$this->verifyAndFixDataBaseFor1_7();
return true;
}
public function verifyAndFixDataBaseFor1_7()
{
if(!Configuration::get('EBAY_UPGRADE_17'))
{
if(count(Db::getInstance()->ExecuteS("SHOW COLUMNS FROM "._DB_PREFIX_."ebay_category_configuration LIKE 'id_ebay_category'")) == 0)
{
//Check if column id_ebay_profile exists on each table already existing in 1.6
$sql = array(
'ALTER TABLE `'._DB_PREFIX_.'ebay_category_configuration`
ADD `id_ebay_profile` INT( 16 ) NOT NULL AFTER `id_ebay_category_configuration`',
// TODO: that would be better to remove the previous indexes if possible
'ALTER TABLE `'._DB_PREFIX_.'ebay_category_configuration` ADD INDEX `ebay_category` (`id_ebay_profile` , `id_ebay_category`)',
'ALTER TABLE `'._DB_PREFIX_.'ebay_category_configuration` ADD INDEX `category` (`id_ebay_profile` , `id_category`)',
'ALTER TABLE `'._DB_PREFIX_.'ebay_shipping_zone_excluded`
ADD `id_ebay_profile` INT( 16 ) NOT NULL AFTER `id_ebay_zone_excluded`',
'ALTER TABLE `'._DB_PREFIX_.'ebay_shipping_international_zone`
ADD `id_ebay_profile` INT( 16 ) NOT NULL AFTER `id_ebay_zone`',
'ALTER TABLE `'._DB_PREFIX_.'ebay_category_condition`
ADD `id_ebay_profile` INT( 16 ) NOT NULL AFTER `id_ebay_category_condition`',
'ALTER TABLE `'._DB_PREFIX_.'ebay_category_condition_configuration`
ADD `id_ebay_profile` INT( 16 ) NOT NULL AFTER `id_ebay_category_condition_configuration`',
'ALTER TABLE `'._DB_PREFIX_.'ebay_product`
ADD `id_ebay_profile` INT( 16 ) NOT NULL AFTER `id_ebay_product`',
'ALTER TABLE `'._DB_PREFIX_.'ebay_shipping`
ADD `id_ebay_profile` INT( 16 ) NOT NULL AFTER `international`',
'ALTER TABLE `'._DB_PREFIX_.'ebay_shipping`
ADD `id_zone` INT( 16 ) NOT NULL AFTER `id_ebay_shipping`',
);
foreach ($sql as $q) {
Db::getInstance()->Execute($q);
}
}
Configuration::updateValue('EBAY_UPGRADE_17', true);
}
}
public function emptyEverything()
{
Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'configuration WHERE name LIKE "%EBAY%"');
Db::getInstance()->Execute('DROP TABLE IF EXISTS
`'._DB_PREFIX_.'ebay_category`,
`'._DB_PREFIX_.'ebay_category_condition`,
`'._DB_PREFIX_.'ebay_category_condition_configuration`,
`'._DB_PREFIX_.'ebay_category_configuration`,
`'._DB_PREFIX_.'ebay_category_specific`,
`'._DB_PREFIX_.'ebay_category_specific_value`,
`'._DB_PREFIX_.'ebay_configuration`,
`'._DB_PREFIX_.'ebay_delivery_time_options`,
`'._DB_PREFIX_.'ebay_log`,
`'._DB_PREFIX_.'ebay_order`,
`'._DB_PREFIX_.'ebay_order_order`,
`'._DB_PREFIX_.'ebay_product`,
`'._DB_PREFIX_.'ebay_product_configuration`,
`'._DB_PREFIX_.'ebay_product_image`,
`'._DB_PREFIX_.'ebay_product_modified`,
`'._DB_PREFIX_.'ebay_profile`,
`'._DB_PREFIX_.'ebay_returns_policy`,
`'._DB_PREFIX_.'ebay_returns_policy_configuration`,
`'._DB_PREFIX_.'ebay_returns_policy_description`,
`'._DB_PREFIX_.'ebay_shipping`,
`'._DB_PREFIX_.'ebay_shipping_international_zone`,
`'._DB_PREFIX_.'ebay_shipping_location`,
`'._DB_PREFIX_.'ebay_shipping_service`,
`'._DB_PREFIX_.'ebay_shipping_zone_excluded`,
`'._DB_PREFIX_.'ebay_stat`,
`'._DB_PREFIX_.'ebay_sync_history`,
`'._DB_PREFIX_.'ebay_sync_history_product`,
`'._DB_PREFIX_.'ebay_api_log`,
`'._DB_PREFIX_.'ebay_order_log`,
`'._DB_PREFIX_.'ebay_store_category`,
`'._DB_PREFIX_.'ebay_store_category_configuration`,
`'._DB_PREFIX_.'ebay_user_identifier_token`;
');
$this->uninstall();
}
/**
* Returns the module url
*
**/
private function _getModuleUrl()
{
return Tools::getShopDomain(true).__PS_BASE_URI__.'modules/ebay/';
}
/**
* Uninstall module
*
* @return boolean
**/
public function uninstall()
{
// Uninstall SQL
include(dirname(__FILE__).'/sql/sql-uninstall.php');
foreach ($sql as $s)
if (!Db::getInstance()->execute($s))
return false;
// Uninstall Module
if (!parent::uninstall()
|| !$this->unregisterHook('addProduct')
|| !$this->unregisterHook('updateProduct')
|| !$this->unregisterHook('actionUpdateQuantity')
|| !$this->unregisterHook('updateQuantity')
|| !$this->unregisterHook('actionOrderStatusUpdate')
|| !$this->unregisterHook('updateOrderStatus')
|| !$this->unregisterHook('updateProductAttribute')
|| !$this->unregisterHook('deleteProduct')
|| !$this->unregisterHook('newOrder')
|| !$this->unregisterHook('backOfficeTop')
|| !$this->unregisterHook('header'))
return false;
// Clean Cookie
$this->context->cookie->eBaySession = '';
$this->context->cookie->eBayUsername = '';
return true;
}
private function _upgrade()
{
$version = Configuration::get('EBAY_VERSION');
if ($version == '1.1' || empty($version))
if (version_compare(_PS_VERSION_, '1.5', '<'))
{
include_once(dirname(__FILE__).'/upgrade/Upgrade-1.2.php');
upgrade_module_1_2($this);
}
if (version_compare($version, '1.4.0', '<'))
if (version_compare(_PS_VERSION_, '1.5', '<'))
{
include_once(dirname(__FILE__).'/upgrade/Upgrade-1.4.php');
upgrade_module_1_4($this);
}
if (version_compare($version, '1.5.0', '<'))
if (version_compare(_PS_VERSION_, '1.5', '<'))
{
include_once(dirname(__FILE__).'/upgrade/Upgrade-1.5.php');
upgrade_module_1_5($this);
}
if (version_compare($version, '1.6', '<')) {
if (version_compare(_PS_VERSION_, '1.5', '<'))
{
include_once(dirname(__FILE__).'/upgrade/Upgrade-1.6.php');
upgrade_module_1_6($this);
}
}
if (version_compare($version, '1.7', '<')) {
if (version_compare(_PS_VERSION_, '1.5', '<'))
{
include_once(dirname(__FILE__).'/upgrade/Upgrade-1.7.php');
upgrade_module_1_7($this);
}
}
if (version_compare($version, '1.8', '<')) {
if (version_compare(_PS_VERSION_, '1.5', '<'))
{
include_once(dirname(__FILE__).'/upgrade/Upgrade-1.8.php');
upgrade_module_1_8($this);
}
}
if (version_compare($version, '1.9', '<')) {
if (version_compare(_PS_VERSION_, '1.5', '<'))
{
include_once(dirname(__FILE__).'/upgrade/Upgrade-1.9.php');
upgrade_module_1_9($this);
}
}
if (version_compare($version, '1.10', '<')) {
if (version_compare(_PS_VERSION_, '1.5', '<'))
{
include_once(dirname(__FILE__).'/upgrade/Upgrade-1.10.php');
upgrade_module_1_10($this);
}
}
if (version_compare($version, '1.11', '<')) {
if (version_compare(_PS_VERSION_, '1.5', '<'))
{
include_once(dirname(__FILE__).'/upgrade/Upgrade-1.11.php');
upgrade_module_1_11($this);
}
}
}
/**
* Called when a new order is placed
*
* @param array $params hook parameters
**/
public function hookNewOrder($params)
{
if (!(int)$params['cart']->id)
return false;
if(!($this->ebay_profile instanceof EbayProfile))
return false;
if (version_compare(_PS_VERSION_, '1.5', '>'))
{
$sql = 'SELECT cp.`id_product`, ep.`id_ebay_profile`
FROM `'._DB_PREFIX_.'cart_product` cp
INNER JOIN `'._DB_PREFIX_.'product` p
ON p.`id_product` = cp.`id_product`
INNER JOIN `'._DB_PREFIX_.'ebay_profile` ep
ON cp.`id_shop` = ep.`id_shop`
WHERE cp.`id_cart` = '.(int)$params['cart']->id.'
AND p.`active` = 1
AND p.`id_category_default` IN
('.EbayCategoryConfiguration::getCategoriesQuery($this->ebay_profile).')';
}
else
$sql = 'SELECT cp.`id_product`, ep.`id_ebay_profile`
FROM `'._DB_PREFIX_.'cart_product` cp
INNER JOIN `'._DB_PREFIX_.'product` p
ON p.`id_product` = cp.`id_product`
INNER JOIN `'._DB_PREFIX_.'ebay_profile` ep
ON 1 = ep.`id_shop`
WHERE cp.`id_cart` = '.(int)$params['cart']->id.'
AND p.`active` = 1
AND p.`id_category_default` IN
('.EbayCategoryConfiguration::getCategoriesQuery($this->ebay_profile).')';
if ($products = Db::getInstance()->executeS($sql)) {
if (Configuration::get('EBAY_SYNC_PRODUCTS_BY_CRON'))
foreach($products as $product)
EbayProductModified::addProduct($this->ebay_profile->id, $product['id_product']);
else
EbaySynchronizer::syncProducts($products, $this->context, $this->ebay_profile->id_lang, 'hookNewOrder');
}
}
/**
* Called when a product is added to the shop
*
* @param array $params hook parameters
**/
public function hookAddProduct($params)
{
if (!isset($params['product']->id) && !isset($params['id_product']))
return false;
if (!($id_product = (int)$params['product']->id))
if (!($id_product = (int)$params['id_product']))
return false;
if(!($this->ebay_profile instanceof EbayProfile))
return false;
if ($this->is_multishop)
{
// we don't synchronize the product if we are not in a shop
$context_shop = $this->_getContextShop();
if ($context_shop[0] != Shop::CONTEXT_SHOP)
return false;
}
$sql = 'SELECT `id_product`,
\''.(int)$this->ebay_profile->id.'\' AS `id_ebay_profile`
FROM `'._DB_PREFIX_.'product`
WHERE `id_product` = '.$id_product.'
AND `active` = 1
AND `id_category_default` IN
('.EbayCategoryConfiguration::getCategoriesQuery($this->ebay_profile).')';
if ($products = Db::getInstance()->executeS($sql))
{
if (Configuration::get('EBAY_SYNC_PRODUCTS_BY_CRON'))
foreach($products as $product)
EbayProductModified::addProduct($this->ebay_profile->id, $product['id_product']);
else
EbaySynchronizer::syncProducts($products, $this->context, $this->ebay_profile->id_lang, 'hookAddProduct');
}
}
/**
*
*
* @param array $params hook parameters
**/
public function hookHeader($params)
{
if(Tools::getValue('DELETE_EVERYTHING_EBAY') == Configuration::get('PS_SHOP_EMAIL'))
$this->emptyEverything();
if (!$this->ebay_profile || !$this->ebay_profile->getConfiguration('EBAY_PAYPAL_EMAIL')) // if the module is not upgraded or not configured don't do anything
return false;
// if multishop, change context Shop to be default
if ($this->is_multishop)
{
$old_context_shop = $this->_getContextShop();
$this->_setContextShop();
}
$this->hookUpdateProductAttributeEbay(); // Fix hook update product attribute
// update if not update for more than 30 min or EBAY_SYNC_ORDER = 1
if (
((int)Configuration::get('EBAY_SYNC_ORDERS_BY_CRON') == 0)
&&
($this->ebay_profile->getConfiguration('EBAY_ORDER_LAST_UPDATE') < date('Y-m-d\TH:i:s', strtotime('-30 minutes')).'.000Z')
|| Tools::getValue('EBAY_SYNC_ORDERS') == 1)
{
$current_date = date('Y-m-d\TH:i:s').'.000Z';
// we set the new last update date after retrieving the last orders
$this->ebay_profile->setConfiguration('EBAY_ORDER_LAST_UPDATE', $current_date);
if ($orders = $this->_getEbayLastOrders($current_date))
$this->importOrders($orders);
}
$this->_cleanLogs();
// Set old Context Shop
if ($this->is_multishop)
$this->_setContextShop($old_context_shop);
$this->_relistItems();
}
/*
* clean logs if required
*
**/
private function _cleanLogs()
{
$config = Configuration::getMultiple(array('EBAY_LOGS_LAST_CLEANUP', 'EBAY_LOGS_DAYS', 'EBAY_API_LOGS', 'EBAY_ACTIVATE_LOGS'));
if (isset($config['EBAY_LOGS_LAST_CLEANUP']) && $config['EBAY_LOGS_LAST_CLEANUP'] >= date('Y-m-d\TH:i:s', strtotime('-1 day')).'.000Z')
return;
$has_cleaned_logs = false;
if (isset($config['EBAY_API_LOGS']) && $config['EBAY_API_LOGS']) {
EbayApiLog::cleanOlderThan($config['EBAY_LOGS_DAYS']);
$has_cleaned_logs = true;
}
if (isset($config['EBAY_ACTIVATE_LOGS']) &&$config['EBAY_ACTIVATE_LOGS']) {
EbayOrderLog::cleanOlderThan($config['EBAY_LOGS_DAYS']);
$has_cleaned_logs = true;
}
if ($has_cleaned_logs)
Configuration::updateValue('EBAY_LOGS_LAST_CLEANUP', true, false, 0, 0);
}
public function cronProductsSync()
{
Configuration::updateValue('NB_PRODUCTS_LAST', '0');
EbaySynchronizer::syncProducts(EbayProductModified::getAll(), Context::getContext(), $this->ebay_profile->id_lang, 'CRON', 'CRON_PRODUCT');
EbayProductModified::truncate();
Configuration::updateValue('DATE_LAST_SYNC_PRODUCTS', date('Y-m-d H:i:s'));
}
public function cronOrdersSync()
{
$current_date = date('Y-m-d\TH:i:s').'.000Z';
if ($orders = $this->_getEbayLastOrders($current_date))
$this->importOrders($orders);
// we set the new last update date after retrieving the last orders
$this->ebay_profile->setConfiguration('EBAY_ORDER_LAST_UPDATE', $current_date);
}
public function importOrders($orders)
{
$errors_email = array();
foreach ($orders as $order)
{
$errors = array();
if (!$order->isCompleted())
{
$message = $this->l('Status not complete, amount less than 0.1 or no matching product');
$errors[] = $message;
$order->addErrorMessage($message);
continue;
}
if ($order->exists())
{
$message = $this->l('Order already imported');
$errors[] = $message;
$order->addErrorMessage($message);
continue;
}
// no order in ebay order table with this order_ref
if (!$order->hasValidContact())
{
$message = $this->l('Invalid e-mail');
$errors[] = $message;
$order->addErrorMessage($message);
continue;
}
if (!$order->hasAllProductsWithAttributes())
{
$message = $this->l('Could not find the products in database');
$errors[] = $message;
$order->addErrorMessage($message);
continue;
}
if ($this->is_multishop)
{
$shops_data = $order->getProductsAndProfileByShop();
$id_shops = array_keys($shops_data);
if (count($id_shops) > 1)
{
$product_ids = $order->getProductIds();
$first_id_shop = $id_shops[0];
if (version_compare(_PS_VERSION_, '1.5', '>'))
$sql = 'SELECT count(*)
FROM `'._DB_PREFIX_.'product_shop` ps
WHERE ps.`id_shop` = '.(int)$first_id_shop.'
AND ps.`active` = 1
AND ps.`id_product` IN ('.implode(',', $product_ids).')';
else
$sql = 'SELECT count(*)
FROM `'._DB_PREFIX_.'product` p
WHERE p.`active` = 1
AND p.`id_product` IN ('.implode(',', $product_ids).')';
$nb_products_in_shop = Db::getInstance()->getValue($sql);
if ($nb_products_in_shop == count($product_ids))
{
$id_shops = array($first_id_shop);
$has_shared_customers = true;
}
else
{
$sql = 'SELECT count(*)
FROM `'._DB_PREFIX_.'shop` s
INNER JOIN `'._DB_PREFIX_.'shop_group` sg
ON s.`id_shop_group` = sg.`id_shop_group`
AND sg.`share_customer` = 1';
$nb_shops_sharing = Db::getInstance()->getValue($sql);
$has_shared_customers = ($nb_shops_sharing == count($id_shops));
}
}
else
$has_shared_customers = true;
}
else
{
$default_shop = Configuration::get('PS_SHOP_DEFAULT') ? Configuration::get('PS_SHOP_DEFAULT') : 1;
$id_shops = array($default_shop);
$has_shared_customers = true;
}
$customer_ids = array();
if ($has_shared_customers)
{
// in case of shared customers in multishop, we take the profile of the first shop
if ($this->is_multishop) {
$shop_data = reset($shops_data);
$ebay_profile = new EbayProfile($shop_data['id_ebay_profiles'][0]);
}
else
$ebay_profile = EbayProfile::getCurrent();
$id_customer = $order->getOrAddCustomer($ebay_profile);
$id_address = $order->updateOrAddAddress($ebay_profile);
$customer_ids[] = $id_customer;
// Fix on sending e-mail
Db::getInstance()->autoExecute(_DB_PREFIX_.'customer', array('email' => 'NOSEND-EBAY'), 'UPDATE', '`id_customer` = '.(int)$id_customer);
$customer_clear = new Customer();
if (method_exists($customer_clear, 'clearCache'))
$customer_clear->clearCache(true);
}
foreach ($id_shops as $id_shop)
{
if ($this->is_multishop)
{
$id_ebay_profile = (int)$shops_data[$id_shop]['id_ebay_profiles'][0];
$ebay_profile = new EbayProfile($id_ebay_profile);
}
else
$ebay_profile = EbayProfile::getCurrent();
if (!$has_shared_customers)
{
$id_customer = $order->getOrAddCustomer($ebay_profile);
$id_address = $order->updateOrAddAddress($ebay_profile);
$customer_ids[] = $id_customer;
// Fix on sending e-mail
Db::getInstance()->autoExecute(_DB_PREFIX_.'customer', array('email' => 'NOSEND-EBAY'), 'UPDATE', '`id_customer` = '.(int)$id_customer);
$customer_clear = new Customer();
if (method_exists($customer_clear, 'clearCache'))
$customer_clear->clearCache(true);
}
$cart = $order->addCart($ebay_profile, $this->ebay_country); //Create a Cart for the order
if (!$order->updateCartQuantities($ebay_profile)) // if products in the cart
{
$order->deleteCart($ebay_profile->id_shop);
$message = $this->l('Could not add product to cart (maybe your stock quantity is 0)');
$errors[] = $message;
$order->addErrorMessage($message);
continue;
}
// if the carrier is disabled, we enable it for the order validation and then disable it again
$carrier = new Carrier((int)EbayShipping::getPsCarrierByEbayCarrier($ebay_profile->id, $order->shippingService));
if (!$carrier->active)
{
$carrier->active = true;
$carrier->save();
$has_disabled_carrier = true;
}
else
$has_disabled_carrier = false;
// Validate order
$id_order = $order->validate($ebay_profile->id_shop, $this->ebay_profile->id);
// we now disable the carrier if required
if ($has_disabled_carrier)
{
$carrier->active = false;
$carrier->save();
}
// Update price (because of possibility of price impact)
$order->updatePrice($ebay_profile);
}
$order->add($this->ebay_profile->id);
if (!version_compare(_PS_VERSION_, '1.5', '>'))
foreach ($order->getProducts() as $product)
$this->hookAddProduct(array('product' => new Product((int)$product['id_product'])));
foreach ($customer_ids as $id_customer)
{
// Fix on sending e-mail
Db::getInstance()->autoExecute(_DB_PREFIX_.'customer', array('email' => pSQL($order->getEmail())), 'UPDATE', '`id_customer` = '.(int)$id_customer);
}
}
$orders_ar = array();
foreach ($orders as $order)
{
$orders_ar[] = array(
'id_order_ref' => $order->getIdOrderRef(),
'id_order_seller' => $order->getIdOrderSeller(),
'amount' => $order->getAmount(),
'status' => $order->getStatus(),
'date' => $order->getDate(),
'email' => $order->getEmail(),
'products' => $order->getProducts(),
'error_messages' => $order->getErrorMessages()
);
}
file_put_contents(dirname(__FILE__).'/log/orders.php', "<?php\n\n".'$dateLastImport = '.'\''.date('d/m/Y H:i:s')."';\n\n".'$orders = '.var_export($orders_ar, true).";\n\n");
if (Configuration::get('EBAY_ACTIVATE_MAILS') && $errors_email)
{
$data = '';
foreach($errors_email as $e)
{
$data .= '<p>Id order : <strong>'.$e['id_order_seller'].'</strong></p><ul>';
foreach($e['messages'] as $m)
{
$data .= '<li>'.$m.'</li>';
}
$data .= '</ul><br/>';
}
Mail::Send(
(int)Configuration::get('PS_LANG_DEFAULT'),
'errorsImportEbay',
Mail::l('Errors import', (int)Configuration::get('PS_LANG_DEFAULT')),
array('{errors_email}' => $data),
strval(Configuration::get('PS_SHOP_EMAIL')),
null,
strval(Configuration::get('PS_SHOP_EMAIL')),
strval(Configuration::get('PS_SHOP_NAME')),
null,
null,
dirname(__FILE__).'/views/templates/mails/'
);
}
}
/**
* Returns Ebay last passed orders as an array of EbayOrder objects
*
* @param string $until_date Date until which the orders should be retrieved
* @return array
**/
private function _getEbayLastOrders($until_date)
{
$nb_days_backward = (int)Configuration::get('EBAY_ORDERS_DAYS_BACKWARD');
if (Configuration::get('EBAY_INSTALL_DATE') < date('Y-m-d\TH:i:s', strtotime('-'.$nb_days_backward.' days')))
{
//If it is more than 30 days that we installed the module
// check from 30 days before
$from_date_ar = explode('T', $this->ebay_profile->getConfiguration('EBAY_ORDER_LAST_UPDATE'));
$from_date = date('Y-m-d', strtotime($from_date_ar[0].' -30 day'));
$from_date .= 'T'.(isset($from_date_ar[1]) ? $from_date_ar[1] : '');
}
else
{
//If it is less than 30 days that we installed the module
// check from one day before
$from_date_ar = explode('T', Configuration::get('EBAY_INSTALL_DATE'));
$from_date = date('Y-m-d', strtotime($from_date_ar[0].' -1 day'));
$from_date .= 'T'.(isset($from_date_ar[1]) ? $from_date_ar[1] : '');
}
$ebay = new EbayRequest();
$page = 1;
$orders = array();
$nb_page_orders = 100;
while ($nb_page_orders > 0 && $page < 10)
{
$page_orders = array();
foreach ($ebay->getOrders($from_date, $until_date, $page) as $order_xml)
$page_orders[] = new EbayOrder($order_xml);
$nb_page_orders = count($page_orders);
$orders = array_merge($orders, $page_orders);
$page++;
}
return $orders;
}
/**
* Called when a product is updated
*
*/
public function hookUpdateProduct($params)
{
if (!isset($params['product']->id) && !isset($params['id_product']))
return false;
if (!($id_product = (int)$params['product']->id))
if (!($id_product = (int)$params['id_product']))
return false;
if(!($this->ebay_profile instanceof EbayProfile))
return false;
$sql = array();
$ebay_profiles = eBayProfile::getProfilesByIdShop();
foreach ($ebay_profiles as $profile) {
$sql[] = 'SELECT `id_product`, '.$profile['id_ebay_profile'].' AS `id_ebay_profile`, '.$profile['id_lang'].' AS `id_lang`
FROM `'._DB_PREFIX_.'product`
WHERE `id_product` = '.$id_product.'
AND `active` = 1
AND `id_category_default` IN
('.EbayCategoryConfiguration::getCategoriesQuery(new EbayProfile($profile['id_ebay_profile'])).')';
}
foreach ($sql as $q) {
if ($products = Db::getInstance()->executeS($q)) {
if (Configuration::get('EBAY_SYNC_PRODUCTS_BY_CRON'))
foreach($products as $product)
EbayProductModified::addProduct($product['id_ebay_profile'], $product['id_product']);
else
EbaySynchronizer::syncProducts($products, $this->context, $products[0]['id_lang'], 'hookUpdateProduct');