forked from Qloapps/QloApps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathModule.php
3245 lines (2816 loc) · 128 KB
/
Module.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-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 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/osl-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 license@prestashop.com 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 <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
abstract class ModuleCore
{
/** @var int Module ID */
public $id = null;
/** @var float Version */
public $version;
public $database_version;
/**
* @since 1.5.0.1
* @var string Registered Version in database
*/
public $registered_version;
/** @var array filled with known compliant PS versions */
public $ps_versions_compliancy = array();
/** @var array filled with known compliant QloApps versions */
public $qloapps_versions_compliancy = array();
/** @var array filled with modules needed for install */
public $dependencies = array();
/** @var string Unique name */
public $name;
/** @var string Human name */
public $displayName;
/** @var string A little description of the module */
public $description;
/** @var string author of the module */
public $author;
/** @var string URI author of the module */
public $author_uri = '';
/** @var string Module key provided by addons.prestashop.com */
public $module_key = '';
public $description_full;
public $additional_description;
public $compatibility;
public $nb_rates;
public $avg_rate;
public $badges;
/** @var int need_instance */
public $need_instance = 1;
/** @var string Admin tab corresponding to the module */
public $tab = null;
/** @var bool Status */
public $active = false;
/** @var bool Is the module certified by addons.prestashop.com */
public $trusted = false;
/** @var string Fill it if the module is installed but not yet set up */
public $warning;
public $enable_device = 7;
/** @var array to store the limited country */
public $limited_countries = array();
/** @var array names of the controllers */
public $controllers = array();
/** @var array used by AdminTab to determine which lang file to use (admin.php or module lang file) */
public static $classInModule = array();
/** @var array current language translations */
protected $_lang = array();
/** @var string Module web path (eg. '/shop/modules/modulename/') */
protected $_path = null;
/**
* @since 1.5.0.1
* @var string Module local path (eg. '/home/prestashop/modules/modulename/')
*/
protected $local_path = null;
/** @var array Array filled with module errors */
protected $_errors = array();
/** @var array Array array filled with module success */
protected $_confirmations = array();
/** @var string Main table used for modules installed */
protected $table = 'module';
/** @var string Identifier of the main table */
protected $identifier = 'id_module';
/** @var array Array cache filled with modules informations */
protected static $modules_cache;
/** @var array Array cache filled with modules instances */
protected static $_INSTANCE = array();
/** @var bool Config xml generation mode */
protected static $_generate_config_xml_mode = false;
/** @var array Array filled with cache translations */
protected static $l_cache = array();
/** @var array Array filled with cache permissions (modules / employee profiles) */
protected static $cache_permissions = array();
/** @var Context */
protected $context;
/** @var Smarty_Data */
protected $smarty;
/** @var Smarty_Internal_Template|null */
protected $current_subtemplate = null;
protected static $update_translations_after_install = true;
protected static $_batch_mode = false;
protected static $_defered_clearCache = array();
protected static $_defered_func_call = array();
/** @var bool If true, allow push */
public $allow_push;
public $push_time_limit = 180;
/** @var bool Define if we will log modules performances for this session */
public static $_log_modules_perfs = null;
/** @var bool Random session for modules perfs logs*/
public static $_log_modules_perfs_session = null;
const CACHE_FILE_MODULES_LIST = '/config/xml/modules_list.xml';
const CACHE_FILE_TAB_MODULES_LIST = '/config/xml/tab_modules_list.xml';
// const CACHE_FILE_ALL_COUNTRY_MODULES_LIST = '/config/xml/modules_native_addons.xml';
const CACHE_FILE_DEFAULT_COUNTRY_MODULES_LIST = '/config/xml/default_country_modules_list.xml';
const CACHE_FILE_CUSTOMER_MODULES_LIST = '/config/xml/customer_modules_list.xml';
const CACHE_FILE_MUST_HAVE_MODULES_LIST = '/config/xml/must_have_modules_list.xml';
const CACHE_FILE_ADDONS_MODULES_LIST = '/config/xml/addons_modules_list.xml';
const CACHE_FILE_TRUSTED_MODULES_LIST = '/config/xml/trusted_modules_list.xml';
const CACHE_FILE_UNTRUSTED_MODULES_LIST = '/config/xml/untrusted_modules_list.xml';
public static $hosted_modules_blacklist = array('autoupgrade');
/**
* Set the flag to indicate we are doing an import
*
* @param bool $value
*/
public static function setBatchMode($value)
{
self::$_batch_mode = (bool)$value;
}
/**
* @return bool
*/
public static function getBatchMode()
{
return self::$_batch_mode;
}
public static function processDeferedFuncCall()
{
self::setBatchMode(false);
foreach (self::$_defered_func_call as $func_call) {
call_user_func_array($func_call[0], $func_call[1]);
}
self::$_defered_func_call = array();
}
/**
* Clear the caches stored in $_defered_clearCache
*
*/
public static function processDeferedClearCache()
{
self::setBatchMode(false);
foreach (self::$_defered_clearCache as $clearCache_array) {
self::_deferedClearCache($clearCache_array[0], $clearCache_array[1], $clearCache_array[2]);
}
self::$_defered_clearCache = array();
}
/**
* Constructor
*
* @param string $name Module unique name
* @param Context $context
*/
public function __construct($name = null, Context $context = null)
{
// for Prestashop version compliancy
if (isset($this->ps_versions_compliancy) && !isset($this->ps_versions_compliancy['min'])) {
$this->ps_versions_compliancy['min'] = '1.4.0.0';
}
if (isset($this->ps_versions_compliancy) && !isset($this->ps_versions_compliancy['max'])) {
$this->ps_versions_compliancy['max'] = _PS_VERSION_;
}
if (strlen($this->ps_versions_compliancy['min']) == 3) {
$this->ps_versions_compliancy['min'] .= '.0.0';
}
if (strlen($this->ps_versions_compliancy['max']) == 3) {
$this->ps_versions_compliancy['max'] .= '.999.999';
}
// for QloApps version compliancy
if (isset($this->qloapps_versions_compliancy) && !isset($this->qloapps_versions_compliancy['min'])) {
$this->qloapps_versions_compliancy['min'] = '0.9.0.0';
}
if (isset($this->qloapps_versions_compliancy) && !isset($this->qloapps_versions_compliancy['max'])) {
$this->qloapps_versions_compliancy['max'] = _QLOAPPS_VERSION_;
}
if (strlen($this->qloapps_versions_compliancy['min']) == 3) {
$this->qloapps_versions_compliancy['min'] .= '.0.0';
}
if (strlen($this->qloapps_versions_compliancy['max']) == 3) {
$this->qloapps_versions_compliancy['max'] .= '.999.999';
}
if (strlen($this->qloapps_versions_compliancy['min']) == 5) {
$this->qloapps_versions_compliancy['min'] .= '.0';
}
if (strlen($this->qloapps_versions_compliancy['max']) == 5) {
$this->qloapps_versions_compliancy['max'] .= '.999';
}
// Load context and smarty
$this->context = $context ? $context : Context::getContext();
if (is_object($this->context->smarty)) {
$this->smarty = $this->context->smarty->createData($this->context->smarty);
}
// If the module has no name we gave him its id as name
if ($this->name === null) {
$this->name = $this->id;
}
// If the module has the name we load the corresponding data from the cache
if ($this->name != null) {
// If cache is not generated, we generate it
if (self::$modules_cache == null && !is_array(self::$modules_cache)) {
$id_shop = (Validate::isLoadedObject($this->context->shop) ? $this->context->shop->id : Configuration::get('PS_SHOP_DEFAULT'));
self::$modules_cache = array();
// Join clause is done to check if the module is activated in current shop context
$result = Db::getInstance()->executeS('
SELECT m.`id_module`, m.`name`, (
SELECT id_module
FROM `'._DB_PREFIX_.'module_shop` ms
WHERE m.`id_module` = ms.`id_module`
AND ms.`id_shop` = '.(int)$id_shop.'
LIMIT 1
) as mshop
FROM `'._DB_PREFIX_.'module` m');
foreach ($result as $row) {
self::$modules_cache[$row['name']] = $row;
self::$modules_cache[$row['name']]['active'] = ($row['mshop'] > 0) ? 1 : 0;
}
}
// We load configuration from the cache
if (isset(self::$modules_cache[$this->name])) {
if (isset(self::$modules_cache[$this->name]['id_module'])) {
$this->id = self::$modules_cache[$this->name]['id_module'];
}
foreach (self::$modules_cache[$this->name] as $key => $value) {
if (property_exists($this, $key)) {
$this->{$key} = $value;
}
}
$this->_path = __PS_BASE_URI__.'modules/'.$this->name.'/';
}
if (!$this->context->controller instanceof Controller) {
self::$modules_cache = null;
}
$this->local_path = _PS_MODULE_DIR_.$this->name.'/';
}
}
/**
* Insert module into datable
*/
public function install()
{
Hook::exec('actionModuleInstallBefore', array('object' => $this));
// Check module name validation
if (!Validate::isModuleName($this->name)) {
$this->_errors[] = Tools::displayError('Unable to install the module (Module name is not valid).');
return false;
}
// Check PS version compliancy
if (!$this->checkCompliancy()) {
$this->_errors[] = Tools::displayError('The version of your module is not compliant with your QloApps version.');
return false;
}
// Check module dependencies
if (count($this->dependencies) > 0) {
foreach ($this->dependencies as $dependency) {
if (!Db::getInstance()->getRow('SELECT `id_module` FROM `'._DB_PREFIX_.'module` WHERE LOWER(`name`) = \''.pSQL(Tools::strtolower($dependency)).'\'')) {
$error = Tools::displayError('Before installing this module, you have to install this/these module(s) first:').'<br />';
foreach ($this->dependencies as $d) {
$error .= '- '.$d.'<br />';
}
$this->_errors[] = $error;
return false;
}
}
}
// Check if module is installed
$result = Module::isInstalled($this->name);
if ($result) {
$this->_errors[] = Tools::displayError('This module has already been installed.');
return false;
}
// Install overrides
try {
$this->installOverrides();
} catch (Exception $e) {
$this->_errors[] = sprintf(Tools::displayError('Unable to install override: %s'), $e->getMessage());
$this->uninstallOverrides();
return false;
}
if (!$this->installControllers()) {
return false;
}
// Install module and retrieve the installation id
$result = Db::getInstance()->insert($this->table, array('name' => $this->name, 'active' => 1, 'version' => $this->version));
if (!$result) {
$this->_errors[] = Tools::displayError('Technical error: PrestaShop could not install this module.');
return false;
}
$this->id = Db::getInstance()->Insert_ID();
Cache::clean('Module::isInstalled'.$this->name);
// Enable the module for current shops in context
$this->enable();
// Permissions management
Db::getInstance()->execute('
INSERT INTO `'._DB_PREFIX_.'module_access` (`id_profile`, `id_module`, `view`, `configure`, `uninstall`) (
SELECT id_profile, '.(int)$this->id.', 1, 1, 1
FROM '._DB_PREFIX_.'access a
WHERE id_tab = (
SELECT `id_tab` FROM '._DB_PREFIX_.'tab
WHERE class_name = \'AdminModules\' LIMIT 1)
AND a.`view` = 1)');
Db::getInstance()->execute('
INSERT INTO `'._DB_PREFIX_.'module_access` (`id_profile`, `id_module`, `view`, `configure`, `uninstall`) (
SELECT id_profile, '.(int)$this->id.', 1, 0, 0
FROM '._DB_PREFIX_.'access a
WHERE id_tab = (
SELECT `id_tab` FROM '._DB_PREFIX_.'tab
WHERE class_name = \'AdminModules\' LIMIT 1)
AND a.`view` = 0)');
// Adding Restrictions for client groups
Group::addRestrictionsForModule($this->id, Shop::getShops(true, null, true));
Hook::exec('actionModuleInstallAfter', array('object' => $this));
if (Module::$update_translations_after_install) {
$this->updateModuleTranslations();
}
return true;
}
public function checkCompliancy()
{
if (version_compare(_PS_VERSION_, $this->ps_versions_compliancy['min'], '<')
|| version_compare(_PS_VERSION_, $this->ps_versions_compliancy['max'], '>')
|| version_compare(_QLOAPPS_VERSION_, $this->qloapps_versions_compliancy['min'], '<')
|| version_compare(_QLOAPPS_VERSION_, $this->qloapps_versions_compliancy['max'], '>')
) {
return false;
} else {
return true;
}
}
public static function updateTranslationsAfterInstall($update = true)
{
Module::$update_translations_after_install = (bool)$update;
}
public function updateModuleTranslations()
{
return Language::updateModulesTranslations(array($this->name));
}
/**
* Set errors, warning or success message of a module upgrade
*
* @param $upgrade_detail
*/
protected function setUpgradeMessage($upgrade_detail)
{
// Store information if a module has been upgraded (memory optimization)
if ($upgrade_detail['available_upgrade']) {
if ($upgrade_detail['success']) {
$this->_confirmations[] = sprintf(Tools::displayError('Current version: %s'), $this->version);
$this->_confirmations[] = sprintf(Tools::displayError('%d file upgrade applied'), $upgrade_detail['number_upgraded']);
} else {
if (!$upgrade_detail['number_upgraded']) {
$this->_errors[] = Tools::displayError('No upgrade has been applied');
} else {
$this->_errors[] = sprintf(Tools::displayError('Upgraded from: %s to %s'), $upgrade_detail['upgraded_from'], $upgrade_detail['upgraded_to']);
$this->_errors[] = sprintf(Tools::displayError('%d upgrade left'), $upgrade_detail['number_upgrade_left']);
}
if (isset($upgrade_detail['duplicate']) && $upgrade_detail['duplicate']) {
$this->_errors[] = sprintf(Tools::displayError('Module %s cannot be upgraded this time: please refresh this page to update it.'), $this->name);
} else {
$this->_errors[] = Tools::displayError('To prevent any problem, this module has been turned off');
}
}
}
}
/**
* Init the upgrade module
*
* @param $module
* @return bool
*/
public static function initUpgradeModule($module)
{
if (((int)$module->installed == 1) & (empty($module->database_version) === true)) {
Module::upgradeModuleVersion($module->name, $module->version);
$module->database_version = $module->version;
}
// Init cache upgrade details
self::$modules_cache[$module->name]['upgrade'] = array(
'success' => false, // bool to know if upgrade succeed or not
'available_upgrade' => 0, // Number of available module before any upgrade
'number_upgraded' => 0, // Number of upgrade done
'number_upgrade_left' => 0,
'upgrade_file_left' => array(), // List of the upgrade file left
'version_fail' => 0, // Version of the upgrade failure
'upgraded_from' => 0, // Version number before upgrading anything
'upgraded_to' => 0, // Last upgrade applied
);
// Need Upgrade will check and load upgrade file to the moduleCache upgrade case detail
$ret = $module->installed && Module::needUpgrade($module);
return $ret;
}
/**
* Run the upgrade for a given module name and version
*
* @return array
*/
public function runUpgradeModule()
{
$upgrade = &self::$modules_cache[$this->name]['upgrade'];
foreach ($upgrade['upgrade_file_left'] as $num => $file_detail) {
foreach ($file_detail['upgrade_function'] as $item) {
if (function_exists($item)) {
$upgrade['success'] = false;
$upgrade['duplicate'] = true;
break 2;
}
}
include($file_detail['file']);
// Call the upgrade function if defined
$upgrade['success'] = false;
foreach ($file_detail['upgrade_function'] as $item) {
if (function_exists($item)) {
$upgrade['success'] = $item($this);
}
}
// Set detail when an upgrade succeed or failed
if ($upgrade['success']) {
$upgrade['number_upgraded'] += 1;
$upgrade['upgraded_to'] = $file_detail['version'];
unset($upgrade['upgrade_file_left'][$num]);
} else {
$upgrade['version_fail'] = $file_detail['version'];
// If any errors, the module is disabled
$this->disable();
break;
}
}
$upgrade['number_upgrade_left'] = count($upgrade['upgrade_file_left']);
// Update module version in DB with the last succeed upgrade
if ($upgrade['upgraded_to']) {
Module::upgradeModuleVersion($this->name, $upgrade['upgraded_to']);
}
$this->setUpgradeMessage($upgrade);
return $upgrade;
}
/**
* Upgrade the registered version to a new one
*
* @param $name
* @param $version
* @return bool
*/
public static function upgradeModuleVersion($name, $version)
{
return Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'module` m
SET m.version = \''.pSQL($version).'\'
WHERE m.name = \''.pSQL($name).'\'');
}
/**
* Check if a module need to be upgraded.
* This method modify the module_cache adding an upgrade list file
*
* @param $module
* @return bool
*/
public static function needUpgrade($module)
{
self::$modules_cache[$module->name]['upgrade']['upgraded_from'] = $module->database_version;
// Check the version of the module with the registered one and look if any upgrade file exist
if (Tools::version_compare($module->version, $module->database_version, '>')) {
$old_version = $module->database_version;
$module = Module::getInstanceByName($module->name);
if ($module instanceof Module) {
return $module->loadUpgradeVersionList($module->name, $module->version, $old_version);
}
}
return null;
}
/**
* Load the available list of upgrade of a specified module
* with an associated version
*
* @param $module_name
* @param $module_version
* @param $registered_version
* @return bool to know directly if any files have been found
*/
protected static function loadUpgradeVersionList($module_name, $module_version, $registered_version)
{
$list = array();
$upgrade_path = _PS_MODULE_DIR_.$module_name.'/upgrade/';
// Check if folder exist and it could be read
if (file_exists($upgrade_path) && ($files = scandir($upgrade_path))) {
// Read each file name
foreach ($files as $file) {
if (!in_array($file, array('.', '..', '.svn', 'index.php')) && preg_match('/\.php$/', $file)) {
$tab = explode('-', $file);
if (!isset($tab[1])) {
continue;
}
$file_version = basename($tab[1], '.php');
// Compare version, if minor than actual, we need to upgrade the module
if (count($tab) == 2 &&
(Tools::version_compare($file_version, $module_version, '<=') &&
Tools::version_compare($file_version, $registered_version, '>'))) {
$list[] = array(
'file' => $upgrade_path.$file,
'version' => $file_version,
'upgrade_function' => array(
'upgrade_module_'.str_replace('.', '_', $file_version),
'upgradeModule'.str_replace('.', '', $file_version))
);
}
}
}
}
// No files upgrade, then upgrade succeed
if (count($list) == 0) {
self::$modules_cache[$module_name]['upgrade']['success'] = true;
Module::upgradeModuleVersion($module_name, $module_version);
}
usort($list, 'ps_module_version_sort');
// Set the list to module cache
self::$modules_cache[$module_name]['upgrade']['upgrade_file_left'] = $list;
self::$modules_cache[$module_name]['upgrade']['available_upgrade'] = count($list);
return (bool)count($list);
}
/**
* Return the status of the upgraded module
*
* @param $module_name
* @return bool
*/
public static function getUpgradeStatus($module_name)
{
return (isset(self::$modules_cache[$module_name]) &&
self::$modules_cache[$module_name]['upgrade']['success']);
}
/**
* Delete module from datable
*
* @return bool result
*/
public function uninstall()
{
// Check module installation id validation
if (!Validate::isUnsignedId($this->id)) {
$this->_errors[] = Tools::displayError('The module is not installed.');
return false;
}
// Uninstall overrides
if (!$this->uninstallOverrides()) {
return false;
}
// Retrieve hooks used by the module
$sql = 'SELECT `id_hook` FROM `'._DB_PREFIX_.'hook_module` WHERE `id_module` = '.(int)$this->id;
$result = Db::getInstance()->executeS($sql);
foreach ($result as $row) {
$this->unregisterHook((int)$row['id_hook']);
$this->unregisterExceptions((int)$row['id_hook']);
}
foreach ($this->controllers as $controller) {
$page_name = 'module-'.$this->name.'-'.$controller;
$meta = Db::getInstance()->getValue('SELECT id_meta FROM `'._DB_PREFIX_.'meta` WHERE page="'.pSQL($page_name).'"');
if ((int)$meta > 0) {
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'theme_meta` WHERE id_meta='.(int)$meta);
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'meta_lang` WHERE id_meta='.(int)$meta);
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'meta` WHERE id_meta='.(int)$meta);
}
}
// Disable the module for all shops
$this->disable(true);
// Delete permissions module access
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'module_access` WHERE `id_module` = '.(int)$this->id);
// Remove restrictions for client groups
Group::truncateRestrictionsByModule($this->id);
// Uninstall the module
if (Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'module` WHERE `id_module` = '.(int)$this->id)) {
Cache::clean('Module::isInstalled'.$this->name);
Cache::clean('Module::getModuleIdByName_'.pSQL($this->name));
return true;
}
return false;
}
/**
* This function enable module $name. If an $name is an array,
* this will enable all of them
*
* @param array|string $name
* @return true if succeed
* @since 1.4.1
*/
public static function enableByName($name)
{
// If $name is not an array, we set it as an array
if (!is_array($name)) {
$name = array($name);
}
$res = true;
// Enable each module
foreach ($name as $n) {
if (Validate::isModuleName($n)) {
$res &= Module::getInstanceByName($n)->enable();
}
}
return $res;
}
/**
* Activate current module.
*
* @param bool $force_all If true, enable module for all shop
*/
public function enable($force_all = false)
{
// Retrieve all shops where the module is enabled
$list = Shop::getContextListShopID();
if (!$this->id || !is_array($list)) {
return false;
}
$sql = 'SELECT `id_shop` FROM `'._DB_PREFIX_.'module_shop`
WHERE `id_module` = '.(int)$this->id.
((!$force_all) ? ' AND `id_shop` IN('.implode(', ', $list).')' : '');
// Store the results in an array
$items = array();
if ($results = Db::getInstance($sql)->executeS($sql)) {
foreach ($results as $row) {
$items[] = $row['id_shop'];
}
}
// Enable module in the shop where it is not enabled yet
foreach ($list as $id) {
if (!in_array($id, $items)) {
Db::getInstance()->insert('module_shop', array(
'id_module' => $this->id,
'id_shop' => $id,
));
}
}
return true;
}
public function enableDevice($device)
{
Db::getInstance()->execute('
UPDATE '._DB_PREFIX_.'module_shop
SET enable_device = enable_device + '.(int)$device.'
WHERE (enable_device &~ '.(int)$device.' OR enable_device = 0) AND id_module='.(int)$this->id.
Shop::addSqlRestriction()
);
return true;
}
public function disableDevice($device)
{
Db::getInstance()->execute('
UPDATE '._DB_PREFIX_.'module_shop
SET enable_device = enable_device - '.(int)$device.'
WHERE enable_device & '.(int)$device.' AND id_module='.(int)$this->id.
Shop::addSqlRestriction()
);
return true;
}
/**
* This function disable module $name. If an $name is an array,
* this will disable all of them
*
* @param array|string $name
* @return true if succeed
* @since 1.4.1
*/
public static function disableByName($name)
{
// If $name is not an array, we set it as an array
if (!is_array($name)) {
$name = array($name);
}
$res = true;
// Disable each module
foreach ($name as $n) {
if (Validate::isModuleName($n)) {
$res &= Module::getInstanceByName($n)->disable();
}
}
return $res;
}
/**
* Desactivate current module.
*
* @param bool $force_all If true, disable module for all shop
*/
public function disable($force_all = false)
{
// Disable module for all shops
$sql = 'DELETE FROM `'._DB_PREFIX_.'module_shop` WHERE `id_module` = '.(int)$this->id.' '.((!$force_all) ? ' AND `id_shop` IN('.implode(', ', Shop::getContextListShopID()).')' : '');
Db::getInstance()->execute($sql);
}
/**
* Display flags in forms for translations
* @deprecated since 1.6.0.10
*
* @param array $languages All languages available
* @param int $default_language Default language id
* @param string $ids Multilingual div ids in form
* @param string $id Current div id]
* @param bool $return define the return way : false for a display, true for a return
* @param bool $use_vars_instead_of_ids use an js vars instead of ids seperate by "¤"
*/
public function displayFlags($languages, $default_language, $ids, $id, $return = false, $use_vars_instead_of_ids = false)
{
if (count($languages) == 1) {
return false;
}
$output = '
<div class="displayed_flag">
<img src="../img/l/'.$default_language.'.jpg" class="pointer" id="language_current_'.$id.'" onclick="toggleLanguageFlags(this);" alt="" />
</div>
<div id="languages_'.$id.'" class="language_flags">
'.$this->l('Choose language:').'<br /><br />';
foreach ($languages as $language) {
if ($use_vars_instead_of_ids) {
$output .= '<img src="../img/l/'.(int)$language['id_lang'].'.jpg" class="pointer" alt="'.$language['name'].'" title="'.$language['name'].'" onclick="changeLanguage(\''.$id.'\', '.$ids.', '.$language['id_lang'].', \''.$language['iso_code'].'\');" /> ';
} else {
$output .= '<img src="../img/l/'.(int)$language['id_lang'].'.jpg" class="pointer" alt="'.$language['name'].'" title="'.$language['name'].'" onclick="changeLanguage(\''.$id.'\', \''.$ids.'\', '.$language['id_lang'].', \''.$language['iso_code'].'\');" /> ';
}
}
$output .= '</div>';
if ($return) {
return $output;
}
echo $output;
}
/**
* Connect module to a hook
*
* @param string $hook_name Hook name
* @param array $shop_list List of shop linked to the hook (if null, link hook to all shops)
* @return bool result
*/
public function registerHook($hook_name, $shop_list = null)
{
$return = true;
if (is_array($hook_name)) {
$hook_names = $hook_name;
} else {
$hook_names = array($hook_name);
}
foreach ($hook_names as $hook_name) {
// Check hook name validation and if module is installed
if (!Validate::isHookName($hook_name)) {
throw new PrestaShopException('Invalid hook name');
}
if (!isset($this->id) || !is_numeric($this->id)) {
return false;
}
// Retrocompatibility
$hook_name_bak = $hook_name;
if ($alias = Hook::getRetroHookName($hook_name)) {
$hook_name = $alias;
}
Hook::exec('actionModuleRegisterHookBefore', array('object' => $this, 'hook_name' => $hook_name));
// Get hook id
$id_hook = Hook::getIdByName($hook_name);
// If hook does not exist, we create it
if (!$id_hook) {
$new_hook = new Hook();
$new_hook->name = pSQL($hook_name);
$new_hook->title = pSQL($hook_name);
$new_hook->live_edit = (bool)preg_match('/^display/i', $new_hook->name);
$new_hook->position = (bool)$new_hook->live_edit;
$new_hook->add();
$id_hook = $new_hook->id;
if (!$id_hook) {
return false;
}
}
// If shop lists is null, we fill it with all shops
if (is_null($shop_list)) {
$shop_list = Shop::getCompleteListOfShopsID();
}
$shop_list_employee = Shop::getShops(true, null, true);
foreach ($shop_list as $shop_id) {
// Check if already register
$sql = 'SELECT hm.`id_module`
FROM `'._DB_PREFIX_.'hook_module` hm, `'._DB_PREFIX_.'hook` h
WHERE hm.`id_module` = '.(int)$this->id.' AND h.`id_hook` = '.$id_hook.'
AND h.`id_hook` = hm.`id_hook` AND `id_shop` = '.(int)$shop_id;
if (Db::getInstance()->getRow($sql)) {
continue;
}
// Get module position in hook
$sql = 'SELECT MAX(`position`) AS position
FROM `'._DB_PREFIX_.'hook_module`
WHERE `id_hook` = '.(int)$id_hook.' AND `id_shop` = '.(int)$shop_id;
if (!$position = Db::getInstance()->getValue($sql)) {
$position = 0;
}
// Register module in hook
$return &= Db::getInstance()->insert('hook_module', array(
'id_module' => (int)$this->id,
'id_hook' => (int)$id_hook,
'id_shop' => (int)$shop_id,
'position' => (int)($position + 1),
));
if (!in_array($shop_id, $shop_list_employee)) {
$where = '`id_module` = '.(int)$this->id.' AND `id_shop` = '.(int)$shop_id;
$return &= Db::getInstance()->delete('module_shop', $where);
}
}
Hook::exec('actionModuleRegisterHookAfter', array('object' => $this, 'hook_name' => $hook_name));
}
return $return;
}
/**
* Unregister module from hook
*
* @param mixed $id_hook Hook id (can be a hook name since 1.5.0)
* @param array $shop_list List of shop
* @return bool result
*/
public function unregisterHook($hook_id, $shop_list = null)
{
// Get hook id if a name is given as argument
if (!is_numeric($hook_id)) {
$hook_name = (string)$hook_id;
// Retrocompatibility
$hook_id = Hook::getIdByName($hook_name);
if (!$hook_id) {
return false;
}
} else {
$hook_name = Hook::getNameById((int)$hook_id);
}
Hook::exec('actionModuleUnRegisterHookBefore', array('object' => $this, 'hook_name' => $hook_name));
// Unregister module on hook by id
$sql = 'DELETE FROM `'._DB_PREFIX_.'hook_module`
WHERE `id_module` = '.(int)$this->id.' AND `id_hook` = '.(int)$hook_id