dolibarr 21.0.0-alpha
DolibarrModules.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2003-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
4 * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
5 * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
6 * Copyright (C) 2005-2013 Laurent Destailleur <eldy@users.sourceforge.net>
7 * Copyright (C) 2005-2024 Regis Houssin <regis.houssin@inodbox.com>
8 * Copyright (C) 2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
9 * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
10 * Copyright (C) 2019-2024 Frédéric France <frederic.france@free.fr>
11 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
12 *
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 3 of the License, or
16 * (at your option) any later version.
17 *
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 *
23 * You should have received a copy of the GNU General Public License
24 * along with this program. If not, see <https://www.gnu.org/licenses/>.
25 */
26
38class DolibarrModules // Can not be abstract, because we need to instantiate it into unActivateModule to be able to disable a module whose files were removed.
39{
43 public $db;
44
49 public $numero;
50
54 public $editor_name;
55
59 public $editor_url;
60
64 public $editor_squarred_logo;
65
73 public $family;
74
87 public $familyinfo;
88
92 public $module_position = '50';
93
102 public $name;
103
109 public $dirs = array();
110
114 public $boxes = array();
115
120 public $const = array();
121
125 public $cronjobs = array();
126
130 public $rights;
131
135 public $rights_admin_allowed;
136
140 public $rights_class;
141
142 const KEY_ID = 0;
143 const KEY_LABEL = 1;
144 const KEY_TYPE = 2; // deprecated
145 const KEY_DEFAULT = 3;
146 const KEY_FIRST_LEVEL = 4;
147 const KEY_SECOND_LEVEL = 5;
148 const KEY_MODULE = 6;
149 const KEY_ENABLED = 7;
150
154 public $menu = array();
155
183 public $module_parts = array();
184
188 public $error;
189
193 public $errors;
194
205 public $version;
206
211 public $lastVersion = '';
212
217 public $needUpdate = false;
218
224 public $description;
225
232 public $descriptionlong;
233
237 public $dictionaries = array();
238
242 public $tabs;
243
244 // For exports
245
249 public $export_code;
250
254 public $export_label;
255
259 public $export_icon;
260
264 public $export_enabled;
268 public $export_permission;
272 public $export_fields_array;
276 public $export_TypeFields_array; // Array of key=>type where type can be 'Numeric', 'Date', 'Text', 'Boolean', 'Status', 'List:xxx:fieldlabel:rowid'
280 public $export_entities_array;
284 public $export_aggregate_array;
288 public $export_examplevalues_array;
292 public $export_help_array;
299 public $export_special_array; // special or computed field
306 public $export_dependencies_array;
310 public $export_sql_start;
314 public $export_sql_end;
318 public $export_sql_order;
319
320
321 // For import
322
326 public $import_code;
327
331 public $import_label;
332
336 public $import_icon;
340 public $import_entities_array;
344 public $import_tables_array;
348 public $import_tables_creator_array;
352 public $import_fields_array;
356 public $import_fieldshidden_array;
360 public $import_convertvalue_array;
364 public $import_regex_array;
368 public $import_examplevalues_array;
372 public $import_updatekeys_array;
376 public $import_run_sql_after_array;
380 public $import_TypeFields_array;
384 public $import_help_array;
385
389 public $const_name;
390
394 public $always_enabled;
395
399 public $disabled;
400
404 public $core_enabled;
405
412 public $picto;
413
420 public $config_page_url;
421
422
431 public $depends;
432
437 public $requiredby;
438
443 public $conflictwith;
444
448 public $langfiles;
449
455 public $warnings_activation;
456
462 public $warnings_activation_ext;
463
469 public $warnings_unactivation;
470
475 public $phpmin;
476
480 public $phpmax;
481
486 public $need_dolibarr_version;
487
491 public $need_javascript_ajax;
492
496 public $enabled_bydefault;
497
501 public $hidden = false;
502
506 public $url_last_version;
507
508
514 public function __construct($db)
515 {
516 $this->db = $db;
517 }
518 // We should but can't set this as abstract because this will make dolibarr hang
519 // after migration due to old module not implementing. We must wait PHP is able to make
520 // a try catch on Fatal error to manage this correctly.
521 // We need constructor into function unActivateModule into admin.lib.php
522
523
524 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
535 protected function _init($array_sql, $options = '')
536 {
537 // phpcs:enable
538 global $conf;
539 $err = 0;
540
541 $this->db->begin();
542
543 // Insert activation module constant
544 if (!$err) {
545 $err += $this->_active();
546 }
547
548 // Insert new pages for tabs (into llx_const)
549 if (!$err) {
550 $err += $this->insert_tabs();
551 }
552
553 // Insert activation of module's parts. Copy website templates into doctemplates.
554 if (!$err) {
555 $err += $this->insert_module_parts();
556 }
557
558 // Insert constant defined by modules (into llx_const)
559 if (!$err && !preg_match('/newboxdefonly/', $options)) {
560 $err += $this->insert_const(); // Test on newboxdefonly to avoid to erase value during upgrade
561 }
562
563 // Insert boxes def (into llx_boxes_def) and boxes setup (into llx_boxes)
564 if (!$err && !preg_match('/noboxes/', $options)) {
565 $err += $this->insert_boxes($options);
566 }
567
568 // Insert cron job entries (entry in llx_cronjobs)
569 if (!$err) {
570 $err += $this->insert_cronjobs();
571 }
572
573 // Insert permission definitions of module into llx_rights_def. If user is admin, grant this permission to user.
574 if (!$err) {
575 $err += $this->insert_permissions(1, null, 1);
576 }
577
578 // Insert specific menus entries into database
579 if (!$err) {
580 $err += $this->insert_menus();
581 }
582
583 // Create module's directories
584 if (!$err) {
585 $err += $this->create_dirs();
586 }
587
588 // Execute addons requests
589 $num = count($array_sql);
590 for ($i = 0; $i < $num; $i++) {
591 if (!$err) {
592 $val = $array_sql[$i];
593 $sql = $val;
594 $ignoreerror = 0;
595 if (is_array($val)) {
596 $sql = $val['sql'];
597 $ignoreerror = $val['ignoreerror'];
598 }
599 // Add current entity id
600 $sql = str_replace('__ENTITY__', (string) $conf->entity, $sql);
601
602 dol_syslog(get_class($this)."::_init ignoreerror=".$ignoreerror, LOG_DEBUG);
603 $result = $this->db->query($sql, $ignoreerror);
604 if (!$result) {
605 if (!$ignoreerror) {
606 $this->error = $this->db->lasterror();
607 $err++;
608 } else {
609 dol_syslog(get_class($this)."::_init Warning ".$this->db->lasterror(), LOG_WARNING);
610 }
611 }
612 }
613 }
614
615 // Return code
616 if (!$err) {
617 $this->db->commit();
618
619 $moduleNameInConf = strtolower(preg_replace('/^MAIN_MODULE_/', '', $this->const_name));
620 // two exceptions to handle
621 if ($moduleNameInConf === 'propale') {
622 $moduleNameInConf = 'propal';
623 } elseif ($moduleNameInConf === 'supplierproposal') {
624 $moduleNameInConf = 'supplier_proposal';
625 }
626
627 $conf->modules[$moduleNameInConf] = $moduleNameInConf; // Add this module in list of enabled modules so isModEnabled() will work (conf->module->enabled must no more be used)
628
629 return 1;
630 } else {
631 $this->db->rollback();
632 return 0;
633 }
634 }
635
636 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
645 protected function _remove($array_sql, $options = '')
646 {
647 global $conf;
648 // phpcs:enable
649 $err = 0;
650
651 $this->db->begin();
652
653 // Remove activation module line (constant MAIN_MODULE_MYMODULE in llx_const)
654 if (!$err) {
655 $err += $this->_unactive();
656 }
657
658 // Remove activation of module's new tabs (MAIN_MODULE_MYMODULE_TABS_XXX in llx_const)
659 if (!$err) {
660 $err += $this->delete_tabs();
661 }
662
663 // Remove activation of module's parts (MAIN_MODULE_MYMODULE_XXX in llx_const)
664 if (!$err) {
665 $err += $this->delete_module_parts();
666 }
667
668 // Remove constants defined by modules
669 if (!$err) {
670 $err += $this->delete_const();
671 }
672
673 // Remove list of module's available boxes (entry in llx_boxes)
674 if (!$err && !preg_match('/(newboxdefonly|noboxes)/', $options)) {
675 $err += $this->delete_boxes(); // We don't have to delete if option ask to keep boxes safe or ask to add new box def only
676 }
677
678 // Remove list of module's cron job entries (entry in llx_cronjobs)
679 if (!$err) {
680 $err += $this->delete_cronjobs();
681 }
682
683 // Remove module's permissions from list of available permissions (entries in llx_rights_def)
684 if (!$err) {
685 $err += $this->delete_permissions();
686 }
687
688 // Remove module's menus (entries in llx_menu)
689 if (!$err) {
690 $err += $this->delete_menus();
691 }
692
693 // Remove module's directories
694 if (!$err) {
695 $err += $this->delete_dirs();
696 }
697
698 // Run complementary sql requests
699 $num = count((array) $array_sql);
700 for ($i = 0; $i < $num; $i++) {
701 if (!$err) {
702 dol_syslog(get_class($this)."::_remove", LOG_DEBUG);
703 $result = $this->db->query($array_sql[$i]);
704 if (!$result) {
705 $this->error = $this->db->error();
706 $err++;
707 }
708 }
709 }
710
711 // Return code
712 if (!$err) {
713 $this->db->commit();
714
715 // Disable modules
716 $moduleNameInConf = strtolower(preg_replace('/^MAIN_MODULE_/', '', $this->const_name));
717 // two exceptions to handle
718 if ($moduleNameInConf === 'propale') {
719 $moduleNameInConf = 'propal';
720 } elseif ($moduleNameInConf === 'supplierproposal') {
721 $moduleNameInConf = 'supplier_proposal';
722 }
723
724 unset($conf->modules[$moduleNameInConf]); // Add this module in list of enabled modules so isModEnabled() will work (conf->module->enabled must no more be used)
725
726 return 1;
727 } else {
728 $this->db->rollback();
729 return 0;
730 }
731 }
732
733
740 public function getName()
741 {
742 global $langs;
743 $langs->load("admin");
744
745 if ($langs->transnoentitiesnoconv("Module".$this->numero."Name") != "Module".$this->numero."Name") {
746 // If module name translation exists
747 return $langs->transnoentitiesnoconv("Module".$this->numero."Name");
748 } else {
749 // If module name translation using it's unique id does not exist, we try to use its name to find translation
750 if (is_array($this->langfiles)) {
751 foreach ($this->langfiles as $val) {
752 if ($val) {
753 $langs->load($val);
754 }
755 }
756 }
757
758 if ($langs->trans("Module".$this->name."Name") != "Module".$this->name."Name") {
759 // If module name translation exists
760 return $langs->transnoentitiesnoconv("Module".$this->name."Name");
761 }
762
763 // Last chance with simple label
764 return $langs->transnoentitiesnoconv($this->name);
765 }
766 }
767
768
774 public function getDesc()
775 {
776 global $langs;
777 $langs->load("admin");
778
779 if ($langs->transnoentitiesnoconv("Module".$this->numero."Desc") != "Module".$this->numero."Desc") {
780 // If module description translation exists
781 return $langs->transnoentitiesnoconv("Module".$this->numero."Desc");
782 } else {
783 // If module description translation does not exist using its unique id, we can use its name to find translation
784 if (is_array($this->langfiles)) {
785 foreach ($this->langfiles as $val) {
786 if ($val) {
787 $langs->load($val);
788 }
789 }
790 }
791
792 if ($langs->transnoentitiesnoconv("Module".$this->name."Desc") != "Module".$this->name."Desc") {
793 // If module name translation exists
794 return $langs->trans("Module".$this->name."Desc");
795 }
796
797 // Last chance with simple label
798 return $langs->trans($this->description);
799 }
800 }
801
808 public function getDescLong()
809 {
810 global $langs;
811 $langs->load("admin");
812
813 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
814 include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
815
816 $content = '';
817 $pathoffile = $this->getDescLongReadmeFound();
818
819 if ($pathoffile) { // Mostly for external modules
820 $content = file_get_contents($pathoffile, false, null, 0, 1024 * 1024); // Max size loaded 1Mb
821
822 if ((float) DOL_VERSION >= 6.0) { // @phpstan-ignore-line
823 @include_once DOL_DOCUMENT_ROOT.'/core/lib/parsemd.lib.php';
824
825 $content = dolMd2Html(
826 $content,
827 'parsedown',
828 array(
829 'doc/' => dol_buildpath(strtolower($this->name).'/doc/', 1),
830 'img/' => dol_buildpath(strtolower($this->name).'/img/', 1),
831 'images/' => dol_buildpath(strtolower($this->name).'/images/', 1),
832 )
833 );
834
835 $content = preg_replace('/<a href="/', '<a target="_blank" rel="noopener noreferrer" href="', $content);
836 } else {
837 $content = nl2br($content);
838 }
839 } else {
840 // Mostly for internal modules
841 if (!empty($this->descriptionlong)) {
842 if (is_array($this->langfiles)) {
843 foreach ($this->langfiles as $val) {
844 if ($val) {
845 $langs->load($val);
846 }
847 }
848 }
849
850 $content = $langs->transnoentitiesnoconv($this->descriptionlong);
851 }
852 }
853
854 return '<div class="moduledesclong">'.$content.'</div>';
855 }
856
862 public function getDescLongReadmeFound()
863 {
864 global $langs;
865
866 $filefound = false;
867
868 // Define path to file README.md.
869 // First check README-la_LA.md then README-la.md then README.md
870 $pathoffile = dol_buildpath(strtolower($this->name).'/README-'.$langs->defaultlang.'.md', 0);
871 if (dol_is_file($pathoffile)) {
872 $filefound = true;
873 }
874 if (!$filefound) {
875 $tmp = explode('_', $langs->defaultlang);
876 $pathoffile = dol_buildpath(strtolower($this->name).'/README-'.$tmp[0].'.md', 0);
877 if (dol_is_file($pathoffile)) {
878 $filefound = true;
879 }
880 }
881 if (!$filefound) {
882 $pathoffile = dol_buildpath(strtolower($this->name).'/README.md', 0);
883 if (dol_is_file($pathoffile)) {
884 $filefound = true;
885 }
886 }
887
888 return ($filefound ? $pathoffile : '');
889 }
890
891
897 public function getChangeLog()
898 {
899 global $langs;
900 $langs->load("admin");
901
902 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
903 include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
904
905 $filefound = false;
906
907 // Define path to file README.md.
908 // First check ChangeLog-la_LA.md then ChangeLog.md
909 $pathoffile = dol_buildpath(strtolower($this->name).'/ChangeLog-'.$langs->defaultlang.'.md', 0);
910 if (dol_is_file($pathoffile)) {
911 $filefound = true;
912 }
913 if (!$filefound) {
914 $pathoffile = dol_buildpath(strtolower($this->name).'/ChangeLog.md', 0);
915 if (dol_is_file($pathoffile)) {
916 $filefound = true;
917 }
918 }
919
920 if ($filefound) { // Mostly for external modules
921 $content = file_get_contents($pathoffile);
922
923 if ((float) DOL_VERSION >= 6.0) { // @phpstan-ignore-line
924 @include_once DOL_DOCUMENT_ROOT.'/core/lib/parsemd.lib.php';
925
926 $content = dolMd2Html($content, 'parsedown', array('doc/' => dol_buildpath(strtolower($this->name).'/doc/', 1)));
927 } else {
928 $content = nl2br($content);
929 }
930 } else {
931 $content = '';
932 }
933
934 return $content;
935 }
936
942 public function getPublisher()
943 {
944 return $this->editor_name;
945 }
946
952 public function getPublisherUrl()
953 {
954 return $this->editor_url;
955 }
956
965 public function getVersion($translated = 1)
966 {
967 global $langs;
968 $langs->load("admin");
969
970 $ret = '';
971
972 $newversion = preg_replace('/_deprecated/', '', $this->version);
973 if ($newversion == 'experimental') {
974 $ret = ($translated ? $langs->transnoentitiesnoconv("VersionExperimental") : $newversion);
975 } elseif ($newversion == 'development') {
976 $ret = ($translated ? $langs->transnoentitiesnoconv("VersionDevelopment") : $newversion);
977 } elseif ($newversion == 'dolibarr') {
978 $ret = DOL_VERSION;
979 } elseif ($newversion) {
980 $ret = $newversion;
981 } else {
982 $ret = ($translated ? $langs->transnoentitiesnoconv("VersionUnknown") : 'unknown');
983 }
984
985 if (preg_match('/_deprecated/', $this->version)) {
986 $ret .= ($translated ? ' ('.$langs->transnoentitiesnoconv("Deprecated").')' : $this->version);
987 }
988 return $ret;
989 }
990
996 public function getModulePosition()
997 {
998 if (in_array($this->version, array('dolibarr', 'dolibarr_deprecated', 'experimental', 'development'))) { // core module
999 return $this->module_position;
1000 } else { // external module
1001 if ($this->module_position >= 100000) {
1002 return $this->module_position;
1003 } else {
1004 $position = intval($this->module_position) + 100000;
1005 return strval($position);
1006 }
1007 }
1008 }
1009
1016 public function isCoreOrExternalModule()
1017 {
1018 if ($this->version == 'dolibarr' || $this->version == 'dolibarr_deprecated') {
1019 return 'core';
1020 }
1021 if (!empty($this->version) && !in_array($this->version, array('experimental', 'development'))) {
1022 return 'external';
1023 }
1024 if (!empty($this->editor_name) || !empty($this->editor_url)) {
1025 return 'external';
1026 }
1027 if ($this->numero >= 100000) {
1028 return 'external';
1029 }
1030 return 'unknown';
1031 }
1032
1033
1039 public function getLangFilesArray()
1040 {
1041 return $this->langfiles;
1042 }
1043
1051 public function getExportDatasetLabel($r)
1052 {
1053 global $langs;
1054
1055 $langstring = "ExportDataset_".$this->export_code[$r];
1056 if ($langs->trans($langstring) == $langstring) {
1057 // Translation not found
1058 return $langs->trans($this->export_label[$r]);
1059 } else {
1060 // Translation found
1061 return $langs->trans($langstring);
1062 }
1063 }
1064
1065
1073 public function getImportDatasetLabel($r)
1074 {
1075 global $langs;
1076
1077 $langstring = "ImportDataset_".$this->import_code[$r];
1078 //print "x".$langstring;
1079 if ($langs->trans($langstring) == $langstring) {
1080 // Translation not found
1081 return $langs->transnoentitiesnoconv($this->import_label[$r]);
1082 } else {
1083 // Translation found
1084 return $langs->transnoentitiesnoconv($langstring);
1085 }
1086 }
1087
1088
1094 public function getLastActivationDate()
1095 {
1096 global $conf;
1097
1098 $err = 0;
1099
1100 $sql = "SELECT tms FROM ".MAIN_DB_PREFIX."const";
1101 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
1102 $sql .= " AND entity IN (0, ".((int) $conf->entity).")";
1103
1104 dol_syslog(get_class($this)."::getLastActiveDate", LOG_DEBUG);
1105 $resql = $this->db->query($sql);
1106 if (!$resql) {
1107 $err++;
1108 } else {
1109 $obj = $this->db->fetch_object($resql);
1110 if ($obj) {
1111 return $this->db->jdate($obj->tms);
1112 }
1113 }
1114
1115 return '';
1116 }
1117
1118
1124 public function getLastActivationInfo()
1125 {
1126 global $conf;
1127
1128 $err = 0;
1129
1130 $sql = "SELECT tms, note FROM ".MAIN_DB_PREFIX."const";
1131 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
1132 $sql .= " AND entity IN (0, ".$conf->entity.")";
1133
1134 dol_syslog(get_class($this)."::getLastActiveDate", LOG_DEBUG);
1135 $resql = $this->db->query($sql);
1136 if (!$resql) {
1137 $err++;
1138 } else {
1139 $obj = $this->db->fetch_object($resql);
1140 if ($obj) {
1141 $tmp = array();
1142 if ($obj->note) {
1143 $tmp = json_decode($obj->note, true);
1144 }
1145 return array(
1146 'authorid' => empty($tmp['authorid']) ? '' : (int) $tmp['authorid'],
1147 'ip' => empty($tmp['ip']) ? '' : (string) $tmp['ip'],
1148 'lastactivationdate' => $this->db->jdate($obj->tms),
1149 'lastactivationversion' => (!empty($tmp['lastactivationversion']) ? (string) $tmp['lastactivationversion'] : 'unknown'),
1150 );
1151 }
1152 }
1153
1154 return array();
1155 }
1156
1157
1158 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1164 protected function _active()
1165 {
1166 // phpcs:enable
1167 global $conf, $user;
1168
1169 $err = 0;
1170
1171 // Common module
1172 $entity = ((!empty($this->always_enabled) || !empty($this->core_enabled)) ? 0 : $conf->entity);
1173
1174 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
1175 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
1176 $sql .= " AND entity IN (0, ".$entity.")";
1177
1178 dol_syslog(get_class($this)."::_active delete activation constant", LOG_DEBUG);
1179 $resql = $this->db->query($sql);
1180 if (!$resql) {
1181 $err++;
1182 }
1183
1184 $note = json_encode(
1185 array(
1186 'authorid' => (is_object($user) ? $user->id : 0),
1187 'ip' => (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']),
1188 'lastactivationversion' => $this->version,
1189 )
1190 );
1191
1192 $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name, value, visible, entity, note) VALUES";
1193 $sql .= " (".$this->db->encrypt($this->const_name);
1194 $sql .= ", ".$this->db->encrypt('1');
1195 $sql .= ", 0, ".((int) $entity);
1196 $sql .= ", '".$this->db->escape($note)."')";
1197
1198 dol_syslog(get_class($this)."::_active insert activation constant", LOG_DEBUG);
1199 $resql = $this->db->query($sql);
1200 if (!$resql) {
1201 $err++;
1202 }
1203
1204 return $err;
1205 }
1206
1207
1208 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1214 protected function _unactive()
1215 {
1216 // phpcs:enable
1217 global $conf;
1218
1219 $err = 0;
1220
1221 // Common module
1222 $entity = ((!empty($this->always_enabled) || !empty($this->core_enabled)) ? 0 : $conf->entity);
1223
1224 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
1225 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
1226 $sql .= " AND entity IN (0, ".$entity.")";
1227
1228 dol_syslog(get_class($this)."::_unactive", LOG_DEBUG);
1229 $this->db->query($sql);
1230
1231 return $err;
1232 }
1233
1234
1235 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps,PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1251 protected function _load_tables($reldir, $onlywithsuffix = '')
1252 {
1253 // phpcs:enable
1254 global $conf;
1255
1256 $error = 0;
1257 $dirfound = 0;
1258 $ok = 1;
1259
1260 if (empty($reldir)) {
1261 return 1;
1262 }
1263
1264 include_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
1265
1266 foreach ($conf->file->dol_document_root as $dirroot) {
1267 if ($ok == 1) {
1268 $dirsql = $dirroot.$reldir;
1269 $ok = 0;
1270
1271 // We will loop on xxx/, xxx/tables/, xxx/data/
1272 $listofsubdir = array('', 'tables/', 'data/');
1273 if ($this->db->type == 'pgsql') {
1274 $listofsubdir[] = '../pgsql/functions/';
1275 }
1276
1277 foreach ($listofsubdir as $subdir) {
1278 $dir = $dirsql.$subdir;
1279
1280 $handle = @opendir($dir); // Dir may not exists
1281 if (is_resource($handle)) {
1282 $dirfound++;
1283
1284 // Run llx_mytable.sql files, then llx_mytable_*.sql
1285 $files = array();
1286 while (($file = readdir($handle)) !== false) {
1287 $files[] = $file;
1288 }
1289 sort($files);
1290 foreach ($files as $file) {
1291 if ($onlywithsuffix) {
1292 if (!preg_match('/\-'.preg_quote($onlywithsuffix, '/').'\./i', $file)) {
1293 //print 'File '.$file.' does not match suffix '.$onlywithsuffix.' so it is discarded<br>'."\n";
1294 continue;
1295 } else {
1296 //print 'File '.$file.' match suffix '.$onlywithsuffix.' so we keep it<br>'."\n";
1297 }
1298 }
1299 if (preg_match('/\.sql$/i', $file) && !preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 4) == 'llx_') {
1300 $result = run_sql($dir.$file, !getDolGlobalString('MAIN_DISPLAY_SQL_INSTALL_LOG') ? 1 : 0, 0, 1);
1301 if ($result <= 0) {
1302 $error++;
1303 }
1304 }
1305 }
1306
1307 rewinddir($handle);
1308
1309 // Run llx_mytable.key.sql files (Must be done after llx_mytable.sql) then then llx_mytable_*.key.sql
1310 $files = array();
1311 while (($file = readdir($handle)) !== false) {
1312 $files[] = $file;
1313 }
1314 sort($files);
1315 foreach ($files as $file) {
1316 if ($onlywithsuffix) {
1317 if (!preg_match('/\-'.preg_quote($onlywithsuffix, '/').'\./i', $file)) {
1318 //print 'File '.$file.' does not match suffix '.$onlywithsuffix.' so it is discarded<br>'."\n";
1319 continue;
1320 } else {
1321 //print 'File '.$file.' match suffix '.$onlywithsuffix.' so we keep it<br>'."\n";
1322 }
1323 }
1324 if (preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 4) == 'llx_') {
1325 $result = run_sql($dir.$file, !getDolGlobalString('MAIN_DISPLAY_SQL_INSTALL_LOG') ? 1 : 0, 0, 1);
1326 if ($result <= 0) {
1327 $error++;
1328 }
1329 }
1330 }
1331
1332 rewinddir($handle);
1333
1334 // Run functions-xxx.sql files (Must be done after llx_mytable.key.sql)
1335 $files = array();
1336 while (($file = readdir($handle)) !== false) {
1337 $files[] = $file;
1338 }
1339 sort($files);
1340 foreach ($files as $file) {
1341 if ($onlywithsuffix) {
1342 if (!preg_match('/\-'.preg_quote($onlywithsuffix, '/').'\./i', $file)) {
1343 //print 'File '.$file.' does not match suffix '.$onlywithsuffix.' so it is discarded<br>'."\n";
1344 continue;
1345 } else {
1346 //print 'File '.$file.' match suffix '.$onlywithsuffix.' so we keep it<br>'."\n";
1347 }
1348 }
1349 if (preg_match('/\.sql$/i', $file) && !preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 9) == 'functions') {
1350 $result = run_sql($dir.$file, !getDolGlobalString('MAIN_DISPLAY_SQL_INSTALL_LOG') ? 1 : 0, 0, 1);
1351 if ($result <= 0) {
1352 $error++;
1353 }
1354 }
1355 }
1356
1357 rewinddir($handle);
1358
1359 // Run data_xxx.sql files (Must be done after llx_mytable.key.sql)
1360 $files = array();
1361 while (($file = readdir($handle)) !== false) {
1362 $files[] = $file;
1363 }
1364 sort($files);
1365 foreach ($files as $file) {
1366 if ($onlywithsuffix) {
1367 if (!preg_match('/\-'.preg_quote($onlywithsuffix, '/').'\./i', $file)) {
1368 //print 'File '.$file.' does not match suffix '.$onlywithsuffix.' so it is discarded<br>'."\n";
1369 continue;
1370 } else {
1371 //print 'File '.$file.' match suffix '.$onlywithsuffix.' so we keep it<br>'."\n";
1372 }
1373 }
1374 if (preg_match('/\.sql$/i', $file) && !preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 4) == 'data') {
1375 $result = run_sql($dir.$file, !getDolGlobalString('MAIN_DISPLAY_SQL_INSTALL_LOG') ? 1 : 0, 0, 1);
1376 if ($result <= 0) {
1377 $error++;
1378 }
1379 }
1380 }
1381
1382 rewinddir($handle);
1383
1384 // Run update_xxx.sql files
1385 $files = array();
1386 while (($file = readdir($handle)) !== false) {
1387 $files[] = $file;
1388 }
1389 sort($files);
1390 foreach ($files as $file) {
1391 if ($onlywithsuffix) {
1392 if (!preg_match('/\-'.preg_quote($onlywithsuffix, '/').'\./i', $file)) {
1393 //print 'File '.$file.' does not match suffix '.$onlywithsuffix.' so it is discarded<br>'."\n";
1394 continue;
1395 } else {
1396 //print 'File '.$file.' match suffix '.$onlywithsuffix.' so we keep it<br>'."\n";
1397 }
1398 }
1399 if (preg_match('/\.sql$/i', $file) && !preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 6) == 'update') {
1400 $result = run_sql($dir.$file, !getDolGlobalString('MAIN_DISPLAY_SQL_INSTALL_LOG') ? 1 : 0, 0, 1);
1401 if ($result <= 0) {
1402 $error++;
1403 }
1404 }
1405 }
1406
1407 closedir($handle);
1408 }
1409 }
1410
1411 if ($error == 0) {
1412 $ok = 1;
1413 }
1414 }
1415 }
1416
1417 if (!$dirfound) {
1418 dol_syslog("A module wants to load sql files from ".$reldir." but this directory was not found.", LOG_WARNING);
1419 }
1420 return $ok;
1421 }
1422
1423
1424 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1432 public function insert_boxes($option = '')
1433 {
1434 // phpcs:enable
1435 include_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php';
1436
1437 global $conf;
1438
1439 $err = 0;
1440
1441 if (is_array($this->boxes)) {
1442 dol_syslog(get_class($this)."::insert_boxes", LOG_DEBUG);
1443
1444 $pos_name = InfoBox::getListOfPagesForBoxes();
1445
1446 foreach ($this->boxes as $key => $value) {
1447 $file = isset($this->boxes[$key]['file']) ? $this->boxes[$key]['file'] : '';
1448 $note = isset($this->boxes[$key]['note']) ? $this->boxes[$key]['note'] : '';
1449 $enabledbydefaulton = isset($this->boxes[$key]['enabledbydefaulton']) ? $this->boxes[$key]['enabledbydefaulton'] : 'Home';
1450
1451 if (empty($file)) {
1452 $file = isset($this->boxes[$key][1]) ? $this->boxes[$key][1] : ''; // For backward compatibility
1453 }
1454 if (empty($note)) {
1455 $note = isset($this->boxes[$key][2]) ? $this->boxes[$key][2] : ''; // For backward compatibility
1456 }
1457
1458 // Search if boxes def already present
1459 $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."boxes_def";
1460 $sql .= " WHERE file = '".$this->db->escape($file)."'";
1461 $sql .= " AND entity = ".$conf->entity;
1462 if ($note) {
1463 $sql .= " AND note ='".$this->db->escape($note)."'";
1464 }
1465
1466 $result = $this->db->query($sql);
1467 if ($result) {
1468 $obj = $this->db->fetch_object($result);
1469 if ($obj->nb == 0) {
1470 $this->db->begin();
1471
1472 if (!$err) {
1473 $sql = "INSERT INTO ".MAIN_DB_PREFIX."boxes_def (file, entity, note)";
1474 $sql .= " VALUES ('".$this->db->escape($file)."', ";
1475 $sql .= $conf->entity.", ";
1476 $sql .= $note ? "'".$this->db->escape($note)."'" : "null";
1477 $sql .= ")";
1478
1479 dol_syslog(get_class($this)."::insert_boxes", LOG_DEBUG);
1480 $resql = $this->db->query($sql);
1481 if (!$resql) {
1482 $err++;
1483 }
1484 }
1485 if (!$err && !preg_match('/newboxdefonly/', $option)) {
1486 $lastid = $this->db->last_insert_id(MAIN_DB_PREFIX."boxes_def", "rowid");
1487
1488 foreach ($pos_name as $key2 => $val2) {
1489 //print 'key2='.$key2.'-val2='.$val2."<br>\n";
1490 if ($enabledbydefaulton && $val2 != $enabledbydefaulton) {
1491 continue; // Not enabled by default onto this page.
1492 }
1493
1494 $sql = "INSERT INTO ".MAIN_DB_PREFIX."boxes (box_id, position, box_order, fk_user, entity)";
1495 $sql .= " VALUES (".((int) $lastid).", ".((int) $key2).", '0', 0, ".((int) $conf->entity).")";
1496
1497 dol_syslog(get_class($this)."::insert_boxes onto page ".$key2."=".$val2, LOG_DEBUG);
1498 $resql = $this->db->query($sql);
1499 if (!$resql) {
1500 $err++;
1501 }
1502 }
1503 }
1504
1505 if (!$err) {
1506 $this->db->commit();
1507 } else {
1508 $this->error = $this->db->lasterror();
1509 $this->db->rollback();
1510 }
1511 }
1512 // else box already registered into database
1513 } else {
1514 $this->error = $this->db->lasterror();
1515 $err++;
1516 }
1517 }
1518 }
1519
1520 return $err;
1521 }
1522
1523
1524 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1530 public function delete_boxes()
1531 {
1532 // phpcs:enable
1533 global $conf;
1534
1535 $err = 0;
1536
1537 if (is_array($this->boxes)) {
1538 foreach ($this->boxes as $key => $value) {
1539 //$titre = $this->boxes[$key][0];
1540 if (empty($this->boxes[$key]['file'])) {
1541 $file = isset($this->boxes[$key][1]) ? $this->boxes[$key][1] : ''; // For backward compatibility
1542 } else {
1543 $file = $this->boxes[$key]['file'];
1544 }
1545
1546 //$note = $this->boxes[$key][2];
1547
1548 // TODO If the box is also included by another module and the other module is still on, we should not remove it.
1549 // For the moment, we manage this with hard coded exception
1550 //print "Remove box ".$file.'<br>';
1551 if ($file == 'box_graph_product_distribution.php') {
1552 if (isModEnabled("product") || isModEnabled("service")) {
1553 dol_syslog("We discard deleting module ".$file." because another module still active requires it.");
1554 continue;
1555 }
1556 }
1557
1558 if ($this->db->type == 'sqlite3') {
1559 // sqlite doesn't support "USING" syntax.
1560 // TODO: remove this dependency.
1561 $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes ";
1562 $sql .= "WHERE ".MAIN_DB_PREFIX."boxes.box_id IN (";
1563 $sql .= "SELECT ".MAIN_DB_PREFIX."boxes_def.rowid ";
1564 $sql .= "FROM ".MAIN_DB_PREFIX."boxes_def ";
1565 $sql .= "WHERE ".MAIN_DB_PREFIX."boxes_def.file = '".$this->db->escape($file)."') ";
1566 $sql .= "AND ".MAIN_DB_PREFIX."boxes.entity = ".$conf->entity;
1567 } else {
1568 $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes";
1569 $sql .= " USING ".MAIN_DB_PREFIX."boxes, ".MAIN_DB_PREFIX."boxes_def";
1570 $sql .= " WHERE ".MAIN_DB_PREFIX."boxes.box_id = ".MAIN_DB_PREFIX."boxes_def.rowid";
1571 $sql .= " AND ".MAIN_DB_PREFIX."boxes_def.file = '".$this->db->escape($file)."'";
1572 $sql .= " AND ".MAIN_DB_PREFIX."boxes.entity = ".$conf->entity;
1573 }
1574
1575 dol_syslog(get_class($this)."::delete_boxes", LOG_DEBUG);
1576 $resql = $this->db->query($sql);
1577 if (!$resql) {
1578 $this->error = $this->db->lasterror();
1579 $err++;
1580 }
1581
1582 $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes_def";
1583 $sql .= " WHERE file = '".$this->db->escape($file)."'";
1584 $sql .= " AND entity = ".$conf->entity; // Do not use getEntity here, we want to delete only in current company
1585
1586 dol_syslog(get_class($this)."::delete_boxes", LOG_DEBUG);
1587 $resql = $this->db->query($sql);
1588 if (!$resql) {
1589 $this->error = $this->db->lasterror();
1590 $err++;
1591 }
1592 }
1593 }
1594
1595 return $err;
1596 }
1597
1598 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1604 public function insert_cronjobs()
1605 {
1606 // phpcs:enable
1607 include_once DOL_DOCUMENT_ROOT . '/core/class/infobox.class.php';
1608 include_once DOL_DOCUMENT_ROOT . '/cron/class/cronjob.class.php';
1609
1610 global $conf, $user;
1611
1612 $err = 0;
1613
1614 if (is_array($this->cronjobs)) {
1615 dol_syslog(get_class($this) . "::insert_cronjobs", LOG_DEBUG);
1616
1617 foreach ($this->cronjobs as $key => $value) {
1618 $now = dol_now();
1619
1620 $entity = isset($value['entity']) ? $value['entity'] : $conf->entity;
1621 $label = isset($value['label']) ? $value['label'] : '';
1622 $jobtype = isset($value['jobtype']) ? $value['jobtype'] : '';
1623 $classesname = isset($value['class']) ? $value['class'] : '';
1624 $objectname = isset($value['objectname']) ? $value['objectname'] : '';
1625 $methodename = isset($value['method']) ? $value['method'] : '';
1626 $command = isset($value['command']) ? $value['command'] : '';
1627 $params = isset($value['parameters']) ? $value['parameters'] : '';
1628 $md5params = isset($value['md5params']) ? $value['md5params'] : '';
1629 $comment = isset($value['comment']) ? $value['comment'] : '';
1630 $frequency = isset($value['frequency']) ? $value['frequency'] : '';
1631 $unitfrequency = isset($value['unitfrequency']) ? $value['unitfrequency'] : '';
1632 $priority = isset($value['priority']) ? $value['priority'] : '';
1633 $datestart = isset($value['datestart']) ? $value['datestart'] : '';
1634 $dateend = isset($value['dateend']) ? $value['dateend'] : '';
1635 $datenextrun = isset($value['datenextrun']) ? $value['datenextrun'] : $now;
1636 $status = isset($value['status']) ? $value['status'] : '';
1637 $maxrun = isset($value['maxrun']) ? $value['maxrun'] : 0;
1638 $libname = isset($value['libname']) ? $value['libname'] : '';
1639 $test = isset($value['test']) ? $value['test'] : ''; // Line must be enabled or not (so visible or not)
1640
1641 // Search if cron entry already present
1642 $sql = "SELECT count(*) as nb FROM " . MAIN_DB_PREFIX . "cronjob";
1643 //$sql .= " WHERE module_name = '" . $this->db->escape(empty($this->rights_class) ? strtolower($this->name) : $this->rights_class) . "'";
1644 $sql .= " WHERE label = '".$this->db->escape($label)."'";
1645 /* unique key is on label,entity so no need for this test
1646 if ($classesname) {
1647 $sql .= " AND classesname = '" . $this->db->escape($classesname) . "'";
1648 }
1649 if ($objectname) {
1650 $sql .= " AND objectname = '" . $this->db->escape($objectname) . "'";
1651 }
1652 if ($methodename) {
1653 $sql .= " AND methodename = '" . $this->db->escape($methodename) . "'";
1654 }
1655 if ($command) {
1656 $sql .= " AND command = '" . $this->db->escape($command) . "'";
1657 }
1658 if ($params) {
1659 $sql .= " AND params = '" . $this->db->escape($params) . "'";
1660 }
1661 */
1662 $sql .= " AND entity = " . ((int) $entity); // Must be exact entity
1663
1664 $result = $this->db->query($sql);
1665 if (!$result) {
1666 $this->error = $this->db->lasterror();
1667 $err++;
1668 break;
1669 // else box already registered into database
1670 }
1671
1672 $obj = $this->db->fetch_object($result);
1673 if ($obj->nb > 0) {
1674 continue;
1675 }
1676
1677 $cronjob = new Cronjob($this->db);
1678
1679 $cronjob->entity = $entity;
1680 $cronjob->label = $label;
1681 $cronjob->jobtype = $jobtype;
1682 $cronjob->classesname = $classesname;
1683 $cronjob->objectname = $objectname;
1684 $cronjob->methodename = $methodename;
1685 $cronjob->command = $command;
1686 $cronjob->params = $params;
1687 $cronjob->md5params = $md5params;
1688 $cronjob->comment = $comment;
1689 $cronjob->frequency = $frequency;
1690 $cronjob->unitfrequency = $unitfrequency;
1691 $cronjob->priority = $priority;
1692 $cronjob->datestart = $datestart;
1693 $cronjob->dateend = $dateend;
1694 $cronjob->datenextrun = $datenextrun;
1695 $cronjob->maxrun = $maxrun;
1696 $cronjob->status = $status;
1697 $cronjob->test = $test;
1698 $cronjob->libname = $libname;
1699 $cronjob->module_name = empty($this->rights_class) ? strtolower($this->name) : $this->rights_class;
1700
1701 $retCreate = $cronjob->create($user);
1702
1703 if ($retCreate < 0) {
1704 $this->error = implode("\n", array_merge([$cronjob->error], $cronjob->errors));
1705 return -1;
1706 }
1707 }
1708 }
1709
1710 return $err;
1711 }
1712
1713 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1719 public function delete_cronjobs()
1720 {
1721 // phpcs:enable
1722 global $conf;
1723
1724 $err = 0;
1725
1726 if (is_array($this->cronjobs)) {
1727 $sql = "DELETE FROM ".MAIN_DB_PREFIX."cronjob";
1728 $sql .= " WHERE module_name = '".$this->db->escape(empty($this->rights_class) ? strtolower($this->name) : $this->rights_class)."'";
1729 $sql .= " AND entity = ".$conf->entity;
1730 $sql .= " AND test = '1'"; // We delete on lines that are not set with a complete test that is '$conf->module->enabled' so when module is disabled, the cron is also removed.
1731 // For crons declared with a '$conf->module->enabled', there is no need to delete the line, so we don't loose setup if we reenable module.
1732
1733 dol_syslog(get_class($this)."::delete_cronjobs", LOG_DEBUG);
1734 $resql = $this->db->query($sql);
1735 if (!$resql) {
1736 $this->error = $this->db->lasterror();
1737 $err++;
1738 }
1739 }
1740
1741 return $err;
1742 }
1743
1744 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1750 public function delete_tabs()
1751 {
1752 // phpcs:enable
1753 global $conf;
1754
1755 $err = 0;
1756
1757 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
1758 $sql .= " WHERE ".$this->db->decrypt('name')." like '".$this->db->escape($this->const_name)."_TABS_%'";
1759 $sql .= " AND entity = ".$conf->entity;
1760
1761 dol_syslog(get_class($this)."::delete_tabs", LOG_DEBUG);
1762 if (!$this->db->query($sql)) {
1763 $this->error = $this->db->lasterror();
1764 $err++;
1765 }
1766
1767 return $err;
1768 }
1769
1770 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1776 public function insert_tabs()
1777 {
1778 // phpcs:enable
1779 global $conf;
1780
1781 $err = 0;
1782
1783 if (!empty($this->tabs)) {
1784 dol_syslog(get_class($this)."::insert_tabs", LOG_DEBUG);
1785
1786 $i = 0;
1787 foreach ($this->tabs as $key => $value) {
1788 if (is_array($value) && count($value) == 0) {
1789 continue; // Discard empty arrays
1790 }
1791
1792 $entity = $conf->entity;
1793 $newvalue = $value;
1794
1795 if (is_array($value)) {
1796 $newvalue = $value['data'];
1797 if (isset($value['entity'])) {
1798 $entity = $value['entity'];
1799 }
1800 }
1801
1802 if ($newvalue) {
1803 $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (";
1804 $sql .= "name";
1805 $sql .= ", type";
1806 $sql .= ", value";
1807 $sql .= ", note";
1808 $sql .= ", visible";
1809 $sql .= ", entity";
1810 $sql .= ")";
1811 $sql .= " VALUES (";
1812 $sql .= $this->db->encrypt($this->const_name."_TABS_".$i);
1813 $sql .= ", 'chaine'";
1814 $sql .= ", ".$this->db->encrypt($newvalue);
1815 $sql .= ", null";
1816 $sql .= ", '0'";
1817 $sql .= ", ".((int) $entity);
1818 $sql .= ")";
1819
1820 $resql = $this->db->query($sql);
1821 if (!$resql) {
1822 dol_syslog($this->db->lasterror(), LOG_ERR);
1823 if ($this->db->lasterrno() != 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1824 $this->error = $this->db->lasterror();
1825 $this->errors[] = $this->db->lasterror();
1826 $err++;
1827 break;
1828 }
1829 }
1830 }
1831 $i++;
1832 }
1833 }
1834 return $err;
1835 }
1836
1837 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1843 public function insert_const()
1844 {
1845 // phpcs:enable
1846 global $conf;
1847
1848 $err = 0;
1849
1850 if (empty($this->const)) {
1851 return 0;
1852 }
1853
1854 dol_syslog(__METHOD__, LOG_DEBUG);
1855
1856 foreach ($this->const as $key => $value) {
1857 $name = $this->const[$key][0];
1858 $type = $this->const[$key][1];
1859 $val = $this->const[$key][2];
1860 $note = isset($this->const[$key][3]) ? $this->const[$key][3] : '';
1861 $visible = isset($this->const[$key][4]) ? $this->const[$key][4] : 0;
1862 $entity = (!empty($this->const[$key][5]) && $this->const[$key][5] != 'current') ? 0 : $conf->entity;
1863
1864 // Clean
1865 if (empty($visible)) {
1866 $visible = '0';
1867 }
1868 if (empty($val) && $val != '0') {
1869 $val = '';
1870 }
1871
1872 $sql = "SELECT count(*) as nb";
1873 $sql .= " FROM ".MAIN_DB_PREFIX."const";
1874 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($name)."'";
1875 $sql .= " AND entity = ".((int) $entity);
1876
1877 $result = $this->db->query($sql);
1878 if ($result) {
1879 $row = $this->db->fetch_row($result);
1880
1881 if ($row[0] == 0) { // If not found
1882 $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name,type,value,note,visible,entity)";
1883 $sql .= " VALUES (";
1884 $sql .= $this->db->encrypt($name);
1885 $sql .= ",'".$this->db->escape($type)."'";
1886 $sql .= ",".(($val != '') ? $this->db->encrypt($val) : "''");
1887 $sql .= ",".($note ? "'".$this->db->escape($note)."'" : "null");
1888 $sql .= ",'".$this->db->escape($visible)."'";
1889 $sql .= ",".$entity;
1890 $sql .= ")";
1891
1892 if (!$this->db->query($sql)) {
1893 $err++;
1894 }
1895 } else {
1896 dol_syslog(__METHOD__." constant '".$name."' already exists", LOG_DEBUG);
1897 }
1898 } else {
1899 $err++;
1900 }
1901 }
1902
1903 return $err;
1904 }
1905
1906 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1912 public function delete_const()
1913 {
1914 // phpcs:enable
1915 global $conf;
1916
1917 $err = 0;
1918
1919 if (empty($this->const)) {
1920 return 0;
1921 }
1922
1923 foreach ($this->const as $key => $value) {
1924 $name = $this->const[$key][0];
1925 $deleteonunactive = (!empty($this->const[$key][6])) ? 1 : 0;
1926
1927 if ($deleteonunactive) {
1928 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
1929 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($name)."'";
1930 $sql .= " AND entity in (0, ".$conf->entity.")";
1931 dol_syslog(get_class($this)."::delete_const", LOG_DEBUG);
1932 if (!$this->db->query($sql)) {
1933 $this->error = $this->db->lasterror();
1934 $err++;
1935 }
1936 }
1937 }
1938
1939 return $err;
1940 }
1941
1942 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1951 public function insert_permissions($reinitadminperms = 0, $force_entity = null, $notrigger = 0)
1952 {
1953 // phpcs:enable
1954 global $conf, $user;
1955
1956 $err = 0;
1957 $entity = (!empty($force_entity) ? $force_entity : $conf->entity);
1958
1959 dol_syslog(get_class($this)."::insert_permissions", LOG_DEBUG);
1960
1961 // Test if module is activated
1962 $sql_del = "SELECT ".$this->db->decrypt('value')." as value";
1963 $sql_del .= " FROM ".MAIN_DB_PREFIX."const";
1964 $sql_del .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
1965 $sql_del .= " AND entity IN (0,".((int) $entity).")";
1966
1967 $resql = $this->db->query($sql_del);
1968
1969 if ($resql) {
1970 $obj = $this->db->fetch_object($resql);
1971
1972 if ($obj !== null && !empty($obj->value) && !empty($this->rights)) {
1973 include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1974
1975 // TODO rights parameters with integer indexes are deprecated
1976 // $this->rights[$key][0] = $this->rights[$key][self::KEY_ID]
1977 // $this->rights[$key][1] = $this->rights[$key][self::KEY_LABEL]
1978 // $this->rights[$key][3] = $this->rights[$key][self::KEY_DEFAULT]
1979 // $this->rights[$key][4] = $this->rights[$key][self::KEY_FIRST_LEVEL]
1980 // $this->rights[$key][5] = $this->rights[$key][self::KEY_SECOND_LEVEL]
1981
1982 // new parameters
1983 // $this->rights[$key][self::KEY_MODULE] // possibility to define user right for an another module (default: current module name)
1984 // $this->rights[$key][self::KEY_ENABLED] // condition to show or hide a user right (default: 1) (eg isModEnabled('anothermodule'))
1985
1986 // If the module is active
1987 foreach ($this->rights as $key => $value) {
1988 $r_id = $this->rights[$key][self::KEY_ID]; // permission id in llx_rights_def (not unique because primary key is couple id-entity)
1989 $r_label = $this->rights[$key][self::KEY_LABEL];
1990 $r_type = $this->rights[$key][self::KEY_TYPE] ?? 'w'; // TODO deprecated
1991 $r_default = $this->rights[$key][self::KEY_DEFAULT] ?? 0;
1992 $r_perms = $this->rights[$key][self::KEY_FIRST_LEVEL] ?? '';
1993 $r_subperms = $this->rights[$key][self::KEY_SECOND_LEVEL] ?? '';
1994
1995 // KEY_FIRST_LEVEL (perms) must not be empty
1996 if (empty($r_perms)) {
1997 continue;
1998 }
1999
2000 // name of module (default: current module name)
2001 $r_module = (empty($this->rights_class) ? strtolower($this->name) : $this->rights_class);
2002
2003 // name of the module from which the right comes (default: empty means same module the permission is for)
2004 $r_module_origin = '';
2005
2006 if (isset($this->rights[$key][self::KEY_MODULE])) {
2007 // name of the module to which the right must be applied
2008 $r_module = $this->rights[$key][self::KEY_MODULE];
2009 // name of the module from which the right comes
2010 $r_module_origin = (empty($this->rights_class) ? strtolower($this->name) : $this->rights_class);
2011 }
2012
2013 // condition to show or hide a user right (default: 1) (eg isModEnabled('anothermodule') or ($conf->global->MAIN_FEATURES_LEVEL > 0) or etc..)
2014 $r_enabled = $this->rights[$key][self::KEY_ENABLED] ?? '1';
2015
2016 // Search if perm already present
2017 $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."rights_def";
2018 $sql .= " WHERE entity = ".((int) $entity);
2019 $sql .= " AND id = ".((int) $r_id);
2020
2021 $resqlselect = $this->db->query($sql);
2022 if ($resqlselect) {
2023 $objcount = $this->db->fetch_object($resqlselect);
2024 if ($objcount && $objcount->nb == 0) {
2025 $sql = "INSERT INTO ".MAIN_DB_PREFIX."rights_def (";
2026 $sql .= "id";
2027 $sql .= ", entity";
2028 $sql .= ", libelle";
2029 $sql .= ", module";
2030 $sql .= ", module_origin";
2031 $sql .= ", type"; // TODO deprecated
2032 $sql .= ", bydefault";
2033 $sql .= ", perms";
2034 $sql .= ", subperms";
2035 $sql .= ", enabled";
2036 $sql .= ") VALUES (";
2037 $sql .= ((int) $r_id);
2038 $sql .= ", ".((int) $entity);
2039 $sql .= ", '".$this->db->escape($r_label)."'";
2040 $sql .= ", '".$this->db->escape($r_module)."'";
2041 $sql .= ", '".$this->db->escape($r_module_origin)."'";
2042 $sql .= ", '".$this->db->escape($r_type)."'"; // TODO deprecated
2043 $sql .= ", ".((int) $r_default);
2044 $sql .= ", '".$this->db->escape($r_perms)."'";
2045 $sql .= ", '".$this->db->escape($r_subperms)."'";
2046 $sql .= ", '".$this->db->escape($r_enabled)."'";
2047 $sql .= ")";
2048
2049 $resqlinsert = $this->db->query($sql, 1);
2050
2051 if (!$resqlinsert) {
2052 if ($this->db->errno() != "DB_ERROR_RECORD_ALREADY_EXISTS") {
2053 $this->error = $this->db->lasterror();
2054 $err++;
2055 break;
2056 } else {
2057 dol_syslog(get_class($this)."::insert_permissions record already exists", LOG_INFO);
2058 }
2059 }
2060
2061 $this->db->free($resqlinsert);
2062 }
2063
2064 $this->db->free($resqlselect);
2065 }
2066
2067 // If we want to init permissions on admin users
2068 if (!empty($reinitadminperms)) {
2069 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."user WHERE admin = 1";
2070 dol_syslog(get_class($this)."::insert_permissions Search all admin users", LOG_DEBUG);
2071
2072 $resqlseladmin = $this->db->query($sql, 1);
2073
2074 if ($resqlseladmin) {
2075 $num = $this->db->num_rows($resqlseladmin);
2076 $i = 0;
2077 while ($i < $num) {
2078 $obj2 = $this->db->fetch_object($resqlseladmin);
2079 dol_syslog(get_class($this)."::insert_permissions Add permission id ".$r_id." to user id=".$obj2->rowid);
2080
2081 $tmpuser = new User($this->db);
2082 $result = $tmpuser->fetch($obj2->rowid);
2083 if ($result > 0) {
2084 $tmpuser->addrights($r_id, '', '', 0, 1);
2085 } else {
2086 dol_syslog(get_class($this)."::insert_permissions Failed to add the permission to user because fetch return an error", LOG_ERR);
2087 }
2088 $i++;
2089 }
2090 } else {
2091 dol_print_error($this->db);
2092 }
2093 }
2094 }
2095
2096 if (!empty($reinitadminperms) && !empty($user->admin)) { // Reload permission for current user if defined
2097 // We reload permissions
2098 $user->clearrights();
2099 $user->loadRights();
2100 }
2101 }
2102 $this->db->free($resql);
2103 } else {
2104 $this->error = $this->db->lasterror();
2105 $err++;
2106 }
2107
2108 return $err;
2109 }
2110
2111
2112 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2118 public function delete_permissions()
2119 {
2120 // phpcs:enable
2121 global $conf;
2122
2123 $err = 0;
2124
2125 $module = empty($this->rights_class) ? strtolower($this->name) : $this->rights_class;
2126
2127 $sql = "DELETE FROM ".MAIN_DB_PREFIX."rights_def";
2128 $sql .= " WHERE (module = '".$this->db->escape($module)."' OR module_origin = '".$this->db->escape($module)."')";
2129
2130 // Delete all entities if core module
2131 if (empty($this->core_enabled)) {
2132 $sql .= " AND entity = ".((int) $conf->entity);
2133 }
2134
2135 dol_syslog(get_class($this)."::delete_permissions", LOG_DEBUG);
2136 if (!$this->db->query($sql)) {
2137 $this->error = $this->db->lasterror();
2138 $err++;
2139 }
2140
2141 return $err;
2142 }
2143
2144
2145 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2151 public function insert_menus()
2152 {
2153 // phpcs:enable
2154 global $conf, $user;
2155
2156 if (!is_array($this->menu) || empty($this->menu)) {
2157 return 0;
2158 }
2159
2160 include_once DOL_DOCUMENT_ROOT.'/core/class/menubase.class.php';
2161
2162 dol_syslog(get_class($this)."::insert_menus", LOG_DEBUG);
2163
2164 $err = 0;
2165
2166 // Common module
2167 $entity = ((!empty($this->always_enabled) || !empty($this->core_enabled)) ? 0 : $conf->entity);
2168
2169 $this->db->begin();
2170
2171 foreach ($this->menu as $key => $value) {
2172 $menu = new Menubase($this->db);
2173 $menu->menu_handler = 'all';
2174
2175 //$menu->module=strtolower($this->name); TODO When right_class will be same than module name
2176 $menu->module = (empty($this->rights_class) ? strtolower($this->name) : $this->rights_class);
2177
2178 if (!$this->menu[$key]['fk_menu']) {
2179 $menu->fk_menu = 0;
2180 } else {
2181 $foundparent = 0;
2182 $fk_parent = $this->menu[$key]['fk_menu'];
2183 $reg = array();
2184 if (preg_match('/^r=/', $fk_parent)) { // old deprecated method
2185 $fk_parent = str_replace('r=', '', $fk_parent);
2186 if (isset($this->menu[$fk_parent]['rowid'])) {
2187 $menu->fk_menu = $this->menu[$fk_parent]['rowid'];
2188 $foundparent = 1;
2189 }
2190 } elseif (preg_match('/^fk_mainmenu=([a-zA-Z0-9_]+),fk_leftmenu=([a-zA-Z0-9_]+)$/', $fk_parent, $reg)) {
2191 $menu->fk_menu = -1;
2192 $menu->fk_mainmenu = $reg[1];
2193 $menu->fk_leftmenu = $reg[2];
2194 $foundparent = 1;
2195 } elseif (preg_match('/^fk_mainmenu=([a-zA-Z0-9_]+)$/', $fk_parent, $reg)) {
2196 $menu->fk_menu = -1;
2197 $menu->fk_mainmenu = $reg[1];
2198 $menu->fk_leftmenu = '';
2199 $foundparent = 1;
2200 }
2201 if (!$foundparent) {
2202 $this->error = "ErrorBadDefinitionOfMenuArrayInModuleDescriptor";
2203 dol_syslog(get_class($this)."::insert_menus ".$this->error." ".$this->menu[$key]['fk_menu'], LOG_ERR);
2204 $err++;
2205 }
2206 }
2207 $menu->type = $this->menu[$key]['type'];
2208 $menu->mainmenu = isset($this->menu[$key]['mainmenu']) ? $this->menu[$key]['mainmenu'] : (isset($menu->fk_mainmenu) ? $menu->fk_mainmenu : '');
2209 $menu->leftmenu = isset($this->menu[$key]['leftmenu']) ? $this->menu[$key]['leftmenu'] : '';
2210 $menu->title = $this->menu[$key]['titre'];
2211 $menu->prefix = isset($this->menu[$key]['prefix']) ? $this->menu[$key]['prefix'] : '';
2212 $menu->url = $this->menu[$key]['url'];
2213 $menu->langs = isset($this->menu[$key]['langs']) ? $this->menu[$key]['langs'] : '';
2214 $menu->position = $this->menu[$key]['position'];
2215 $menu->perms = $this->menu[$key]['perms'];
2216 $menu->target = isset($this->menu[$key]['target']) ? $this->menu[$key]['target'] : '';
2217 $menu->user = $this->menu[$key]['user'];
2218 $menu->enabled = isset($this->menu[$key]['enabled']) ? $this->menu[$key]['enabled'] : 0;
2219 $menu->position = $this->menu[$key]['position'];
2220 $menu->entity = $entity;
2221
2222 if (!$err) {
2223 $result = $menu->create($user); // Save menu entry into table llx_menu
2224 if ($result > 0) {
2225 $this->menu[$key]['rowid'] = $result;
2226 } else {
2227 $this->error = $menu->error;
2228 dol_syslog(get_class($this).'::insert_menus result='.$result." ".$this->error, LOG_ERR);
2229 $err++;
2230 break;
2231 }
2232 }
2233 }
2234
2235 if (!$err) {
2236 $this->db->commit();
2237 } else {
2238 dol_syslog(get_class($this)."::insert_menus ".$this->error, LOG_ERR);
2239 $this->db->rollback();
2240 }
2241
2242 return $err;
2243 }
2244
2245
2246 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2252 public function delete_menus()
2253 {
2254 // phpcs:enable
2255 global $conf;
2256
2257 $err = 0;
2258
2259 //$module=strtolower($this->name); TODO When right_class will be same than module name
2260 $module = empty($this->rights_class) ? strtolower($this->name) : $this->rights_class;
2261
2262 $sql = "DELETE FROM ".MAIN_DB_PREFIX."menu";
2263 $sql .= " WHERE module = '".$this->db->escape($module)."'";
2264 $sql .= " AND menu_handler = 'all'"; // We delete only lines that were added manually or by the module activation. We keep entry added by menuhandler like 'auguria'
2265 $sql .= " AND entity IN (0, ".$conf->entity.")";
2266
2267 dol_syslog(get_class($this)."::delete_menus", LOG_DEBUG);
2268 $resql = $this->db->query($sql);
2269 if (!$resql) {
2270 $this->error = $this->db->lasterror();
2271 $err++;
2272 }
2273
2274 return $err;
2275 }
2276
2277 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2283 public function create_dirs()
2284 {
2285 // phpcs:enable
2286 global $langs, $conf;
2287
2288 $err = 0;
2289 $name = '';
2290
2291 if (isset($this->dirs) && is_array($this->dirs)) {
2292 foreach ($this->dirs as $key => $value) {
2293 $addtodatabase = 0;
2294
2295 if (!is_array($value)) {
2296 $dir = $value; // Default simple mode
2297 } else {
2298 $constname = $this->const_name."_DIR_";
2299 $dir = $this->dirs[$key][1];
2300 $addtodatabase = empty($this->dirs[$key][2]) ? '' : $this->dirs[$key][2]; // Create constante in llx_const
2301 $subname = empty($this->dirs[$key][3]) ? '' : strtoupper($this->dirs[$key][3]); // Add submodule name (ex: $conf->module->submodule->dir_output)
2302 $forcename = empty($this->dirs[$key][4]) ? '' : strtoupper($this->dirs[$key][4]); // Change the module name if different
2303
2304 if (!empty($forcename)) {
2305 $constname = 'MAIN_MODULE_'.$forcename."_DIR_";
2306 }
2307 if (!empty($subname)) {
2308 $constname = $constname.$subname."_";
2309 }
2310
2311 $name = $constname.strtoupper($this->dirs[$key][0]);
2312 }
2313
2314 // Define directory full path ($dir must start with "/")
2315 if (!getDolGlobalString('MAIN_MODULE_MULTICOMPANY') || $conf->entity == 1) {
2316 $fulldir = DOL_DATA_ROOT.$dir;
2317 } else {
2318 $fulldir = DOL_DATA_ROOT."/".$conf->entity.$dir;
2319 }
2320 // Create dir if it does not exists
2321 if (!empty($fulldir) && !file_exists($fulldir)) {
2322 if (dol_mkdir($fulldir, DOL_DATA_ROOT) < 0) {
2323 $this->error = $langs->trans("ErrorCanNotCreateDir", $fulldir);
2324 dol_syslog(get_class($this)."::_init ".$this->error, LOG_ERR);
2325 $err++;
2326 }
2327 }
2328
2329 // Define the constant in database if requested (not the default mode)
2330 if (!empty($addtodatabase) && !empty($name)) {
2331 $result = $this->insert_dirs($name, $dir);
2332 if ($result) {
2333 $err++;
2334 }
2335 }
2336 }
2337 }
2338
2339 return $err;
2340 }
2341
2342
2343 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2352 public function insert_dirs($name, $dir)
2353 {
2354 // phpcs:enable
2355 global $conf;
2356
2357 $err = 0;
2358
2359 $sql = "SELECT count(*)";
2360 $sql .= " FROM ".MAIN_DB_PREFIX."const";
2361 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($name)."'";
2362 $sql .= " AND entity = ".$conf->entity;
2363
2364 dol_syslog(get_class($this)."::insert_dirs", LOG_DEBUG);
2365 $result = $this->db->query($sql);
2366 if ($result) {
2367 $row = $this->db->fetch_row($result);
2368
2369 if ($row[0] == 0) {
2370 $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name, type, value, note, visible, entity)";
2371 $sql .= " VALUES (".$this->db->encrypt($name).", 'chaine', ".$this->db->encrypt($dir).", '".$this->db->escape("Directory for module ".$this->name)."', '0', ".((int) $conf->entity).")";
2372
2373 dol_syslog(get_class($this)."::insert_dirs", LOG_DEBUG);
2374 $this->db->query($sql);
2375 }
2376 } else {
2377 $this->error = $this->db->lasterror();
2378 $err++;
2379 }
2380
2381 return $err;
2382 }
2383
2384
2385 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2391 public function delete_dirs()
2392 {
2393 // phpcs:enable
2394 global $conf;
2395
2396 $err = 0;
2397
2398 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
2399 $sql .= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_DIR_%'";
2400 $sql .= " AND entity = ".$conf->entity;
2401
2402 dol_syslog(get_class($this)."::delete_dirs", LOG_DEBUG);
2403 if (!$this->db->query($sql)) {
2404 $this->error = $this->db->lasterror();
2405 $err++;
2406 }
2407
2408 return $err;
2409 }
2410
2411 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2418 public function insert_module_parts()
2419 {
2420 // phpcs:enable
2421 global $conf, $langs;
2422
2423 $error = 0;
2424
2425 if (is_array($this->module_parts)) {
2426 if (empty($this->module_parts['icon']) && !empty($this->picto) && preg_match('/^fa\-/', $this->picto)) {
2427 $this->module_parts['icon'] = $this->picto;
2428 }
2429
2430 foreach ($this->module_parts as $key => $value) {
2431 if (is_array($value) && count($value) == 0) {
2432 continue; // Discard empty arrays
2433 }
2434
2435 // If module brings website templates, we must generate the zip like we do whenenabling the website module
2436 if ($key == 'websitetemplates' && $value == 1) {
2437 $srcroot = dol_buildpath('/'.strtolower($this->name).'/doctemplates/websites');
2438
2439 // Copy templates in dir format (recommended) into zip file
2440 $docs = dol_dir_list($srcroot, 'directories', 0, 'website_.*$');
2441 foreach ($docs as $cursorfile) {
2442 $src = $srcroot.'/'.$cursorfile['name'];
2443 $dest = DOL_DATA_ROOT.'/doctemplates/websites/'.$cursorfile['name'];
2444
2445 dol_delete_file($dest.'.zip');
2446
2447 // Compress it
2448 global $errormsg;
2449 $errormsg = '';
2450 $result = dol_compress_dir($src, $dest.'.zip', 'zip');
2451 if ($result < 0) {
2452 $error++;
2453 $this->error = ($errormsg ? $errormsg : $langs->trans('ErrorFailToCreateZip', $dest));
2454 $this->errors[] = ($errormsg ? $errormsg : $langs->trans('ErrorFailToCreateZip', $dest));
2455 }
2456 }
2457
2458 // Copy also the preview website_xxx.jpg file
2459 $docs = dol_dir_list($srcroot, 'files', 0, 'website_.*\.jpg$');
2460 foreach ($docs as $cursorfile) {
2461 $src = $srcroot.'/'.$cursorfile['name'];
2462 $dest = DOL_DATA_ROOT.'/doctemplates/websites/'.$cursorfile['name'];
2463
2464 dol_copy($src, $dest);
2465 }
2466 }
2467
2468 $entity = $conf->entity; // Reset the current entity
2469 $newvalue = $value;
2470
2471 // Serialize array parameters
2472 if (is_array($value)) {
2473 // Can defined other parameters
2474 // Example when $key='hooks', then $value is an array('data'=>array('hookcontext1','hookcontext2'), 'entity'=>X)
2475 if (isset($value['data']) && is_array($value['data'])) {
2476 $newvalue = json_encode($value['data']);
2477 if (isset($value['entity'])) {
2478 $entity = $value['entity'];
2479 }
2480 } elseif (isset($value['data']) && !is_array($value['data'])) {
2481 $newvalue = $value['data'];
2482 if (isset($value['entity'])) {
2483 $entity = $value['entity'];
2484 }
2485 } else { // when hook is declared with syntax 'hook'=>array('hookcontext1','hookcontext2',...)
2486 $newvalue = json_encode($value);
2487 }
2488 }
2489
2490 if (!empty($newvalue)) {
2491 $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (";
2492 $sql .= "name";
2493 $sql .= ", type";
2494 $sql .= ", value";
2495 $sql .= ", note";
2496 $sql .= ", visible";
2497 $sql .= ", entity";
2498 $sql .= ")";
2499 $sql .= " VALUES (";
2500 $sql .= " ".$this->db->encrypt($this->const_name."_".strtoupper($key), 1);
2501 $sql .= ", 'chaine'";
2502 $sql .= ", ".$this->db->encrypt($newvalue, 1);
2503 $sql .= ", null";
2504 $sql .= ", '0'";
2505 $sql .= ", ".((int) $entity);
2506 $sql .= ")";
2507
2508 dol_syslog(get_class($this)."::insert_module_parts for key=".$this->const_name."_".strtoupper($key), LOG_DEBUG);
2509
2510 $resql = $this->db->query($sql, 1);
2511 if (!$resql) {
2512 if ($this->db->lasterrno() != 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2513 $error++;
2514 $this->error = $this->db->lasterror();
2515 } else {
2516 dol_syslog(get_class($this)."::insert_module_parts for ".$this->const_name."_".strtoupper($key)." Record already exists.", LOG_WARNING);
2517 }
2518 }
2519 }
2520 }
2521 }
2522 return $error;
2523 }
2524
2525 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2531 public function delete_module_parts()
2532 {
2533 // phpcs:enable
2534 global $conf;
2535
2536 $err = 0;
2537
2538 if (is_array($this->module_parts)) {
2539 dol_syslog(get_class($this)."::delete_module_parts", LOG_DEBUG);
2540
2541 if (empty($this->module_parts['icon']) && !empty($this->picto) && preg_match('/^fa\-/', $this->picto)) {
2542 $this->module_parts['icon'] = $this->picto;
2543 }
2544
2545 foreach ($this->module_parts as $key => $value) {
2546 // If entity is defined
2547 if (is_array($value) && isset($value['entity'])) {
2548 $entity = $value['entity'];
2549 } else {
2550 $entity = $conf->entity;
2551 }
2552
2553 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
2554 $sql .= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_".strtoupper($key)."'";
2555 $sql .= " AND entity = ".((int) $entity);
2556
2557 if (!$this->db->query($sql)) {
2558 $this->error = $this->db->lasterror();
2559 $err++;
2560 }
2561 }
2562 }
2563 return $err;
2564 }
2565
2575 public function init($options = '')
2576 {
2577 return $this->_init(array(), $options);
2578 }
2579
2588 public function remove($options = '')
2589 {
2590 return $this->_remove(array(), $options);
2591 }
2592
2593
2601 public function getKanbanView($codeenabledisable = '', $codetoconfig = '')
2602 {
2603 global $langs;
2604
2605 // Define imginfo
2606 $imginfo = "info";
2607 if ($this->isCoreOrExternalModule() == 'external') {
2608 $imginfo = "info_black";
2609 }
2610
2611 $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($this)));
2612
2613 $version = $this->getVersion(0);
2614 $versiontrans = '';
2615 if (preg_match('/development/i', $version)) {
2616 $versiontrans .= 'warning';
2617 }
2618 if (preg_match('/experimental/i', $version)) {
2619 $versiontrans .= 'warning';
2620 }
2621 if (preg_match('/deprecated/i', $version)) {
2622 $versiontrans .= 'warning';
2623 }
2624
2625 $return = '
2626 <div class="box-flex-item info-box-module'
2627 .(getDolGlobalString($const_name) ? '' : ' --disabled')
2628 .($this->isCoreOrExternalModule() == 'external' ? ' --external' : '')
2629 .($this->needUpdate ? ' --need-update' : '')
2630 .'">
2631 <div class="info-box info-box-sm info-box-module">
2632 <div class="info-box-icon'.(!getDolGlobalString($const_name) ? '' : ' info-box-icon-module-enabled'.($versiontrans ? ' info-box-icon-module-warning' : '')).'">';
2633
2634 $alttext = '';
2635 //if (is_array($objMod->need_dolibarr_version)) $alttext.=($alttext?' - ':'').'Dolibarr >= '.join('.',$objMod->need_dolibarr_version);
2636 //if (is_array($objMod->phpmin)) $alttext.=($alttext?' - ':'').'PHP >= '.join('.',$objMod->phpmin);
2637 if (!empty($this->picto)) {
2638 if (preg_match('/^\//i', $this->picto)) {
2639 $return .= img_picto($alttext, $this->picto, 'class="inline-block valignmiddle"', 1);
2640 } else {
2641 $return .= img_object($alttext, $this->picto, 'class="inline-block valignmiddle"');
2642 }
2643 } else {
2644 $return .= img_object($alttext, 'generic', 'class="inline-block valignmiddle"');
2645 }
2646
2647 if ($this->isCoreOrExternalModule() == 'external' || preg_match('/development|experimental|deprecated/i', $version)) {
2648 $versionTitle = $langs->trans("Version").' '.$this->getVersion(1);
2649 if ($this->needUpdate) {
2650 $versionTitle .= '<br>'.$langs->trans('ModuleUpdateAvailable').' : '.$this->lastVersion;
2651 }
2652
2653 $return .= '<span class="info-box-icon-version'.($versiontrans ? ' '.$versiontrans : '').' classfortooltip" title="'.dol_escape_js($versionTitle).'" >';
2654 $return .= $this->getVersion(1);
2655 $return .= '</span>';
2656 }
2657
2658 $return .= '</div>
2659 <div class="info-box-content info-box-text-module'.(!getDolGlobalString($const_name) ? '' : ' info-box-module-enabled'.($versiontrans ? ' info-box-content-warning' : '')).'">
2660 <span class="info-box-title">'.$this->getName().'</span>
2661 <span class="info-box-desc twolinesmax opacitymedium" title="'.dol_escape_htmltag($this->getDesc()).'">'.nl2br($this->getDesc()).'</span>';
2662
2663 $return .= '<div class="valignmiddle inline-block info-box-more">';
2664 //if ($versiontrans) print img_warning($langs->trans("Version").' '.$this->getVersion(1)).' ';
2665 $return .= '<a class="valignmiddle inline-block" href="javascript:document_preview(\''.DOL_URL_ROOT.'/admin/modulehelp.php?id='.((int) $this->numero).'\',\'text/html\',\''.dol_escape_js($langs->trans("Module")).'\')">'.img_picto(($this->isCoreOrExternalModule() == 'external' ? $langs->trans("ExternalModule").' - ' : '').$langs->trans("ClickToShowDescription"), $imginfo).'</a>';
2666 $return .= '</div><br>';
2667
2668 $return .= '<div class="valignmiddle inline-block info-box-actions">';
2669 $return .= '<div class="valignmiddle inline-block info-box-setup">';
2670 $return .= $codetoconfig;
2671 $return .= '</div>';
2672 $return .= '<div class="valignmiddle inline-block marginleftonly marginrightonly">';
2673 $return .= $codeenabledisable;
2674 $return .= '</div>';
2675 $return .= '</div>';
2676
2677 $return .= '
2678 </div><!-- /.info-box-content -->
2679 </div><!-- /.info-box -->
2680 </div>';
2681
2682 return $return;
2683 }
2684
2693 public function checkForUpdate()
2694 {
2695 require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
2696 if (!empty($this->url_last_version)) {
2697 $lastVersion = getURLContent($this->url_last_version, 'GET', '', 1, array(), array('http', 'https'), 0); // Accept http or https links on external remote server only
2698 if (isset($lastVersion['content']) && strlen($lastVersion['content']) < 30) {
2699 // Security warning : be careful with remote data content, the module editor could be hacked (or evil) so limit to a-z A-Z 0-9 _ . -
2700 $this->lastVersion = preg_replace("/[^a-zA-Z0-9_\.\-]+/", "", $lastVersion['content']);
2701 if (version_compare($this->lastVersion, $this->version) > 0) {
2702 $this->needUpdate = true;
2703 return 1;
2704 } else {
2705 $this->needUpdate = false;
2706 return 0;
2707 }
2708 } else {
2709 return -1;
2710 }
2711 }
2712 return 0;
2713 }
2714
2722 public function checkForCompliance($nametocheck = '')
2723 {
2724 global $conf, $langs;
2725
2726 if (empty($nametocheck)) {
2727 $nametocheck = $this->name;
2728 }
2729
2730 // Get list of illegal modules name or ID
2731 if (empty($conf->cache['noncompliantmodules'])) {
2732 require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
2733
2734 $urlforblacklistmodules = 'https://ping.dolibarr.org/modules-blacklist.txt';
2735
2736 $result = getURLContent($urlforblacklistmodules, 'GET', '', 1, array(), array('http', 'https'), 0); // Accept http or https links on external remote server only
2737 if (isset($result['content']) && $result['http_code'] == 200) {
2738 $langs->load("errors");
2739
2740 // Security warning : be careful with remote data content, the module editor could be hacked (or evil) so limit to a-z A-Z 0-9 _ . -
2741 $arrayoflines = preg_split("/[\n,]/", $result['content']);
2742 foreach ($arrayoflines as $line) {
2743 $tmpfieldsofline = explode(';', $line);
2744 $modulekey = strtolower($tmpfieldsofline[0]);
2745 $conf->cache['noncompliantmodules'][$modulekey]['name'] = $tmpfieldsofline[0];
2746 $conf->cache['noncompliantmodules'][$modulekey]['id'] = $tmpfieldsofline[1];
2747 $conf->cache['noncompliantmodules'][$modulekey]['signature'] = $tmpfieldsofline[2];
2748 $conf->cache['noncompliantmodules'][$modulekey]['message'] = $langs->trans(empty($tmpfieldsofline[3]) ? 'WarningModuleAffiliatedToAReportedCompany' : $tmpfieldsofline[3]);
2749 if (!empty($tmpfieldsofline[4])) {
2750 $message2 = $langs->trans("WarningModuleAffiliatedToAPiratPlatform", '{s}');
2751 $listofillegalurl = '';
2752 foreach (explode(" ", $tmpfieldsofline[4]) as $illegalurl) {
2753 $listofillegalurl .= ($listofillegalurl ? ' '.$langs->trans("or").' ' : '').'<b>'.preg_replace('/[^a-z0-9\.\-]/', '', $illegalurl).'</b>';
2754 }
2755 $message2 = str_replace('{s}', $listofillegalurl, $message2);
2756 $conf->cache['noncompliantmodules'][$modulekey]['message2'] = $message2;
2757 }
2758 }
2759 }
2760 }
2761
2762 if (!empty($conf->cache['noncompliantmodules'])) {
2763 $modulekey = strtolower($nametocheck);
2764 if (in_array($modulekey, array_keys($conf->cache['noncompliantmodules']))) {
2765 $answer = trim($conf->cache['noncompliantmodules'][$modulekey]['message']);
2766 if (!empty($conf->cache['noncompliantmodules'][$modulekey]['message2'])) {
2767 $answer .= '<br>'.$conf->cache['noncompliantmodules'][$modulekey]['message2'];
2768 }
2769 return $answer;
2770 }
2771 }
2772
2773 return 0;
2774 }
2775
2794 protected function declareNewDictionary($dictionaryArray, $langs = '')
2795 {
2796 $fields = array('name', 'lib', 'sql', 'sqlsort', 'field', 'fieldvalue', 'fieldinsert', 'rowid', 'cond', 'help', 'fieldcheck');
2797
2798 foreach ($fields as $field) {
2799 if (isset($dictionaryArray[$field])) {
2800 // @phan-suppress-next-line PhanTypeMismatchProperty
2801 $this->dictionaries['tab'.$field][] = $dictionaryArray[$field];
2802 }
2803 }
2804 if ($langs && !in_array($langs, $this->dictionaries[$langs])) {
2805 $this->dictionaries['langs'][] = $langs;
2806 }
2807 }
2808}
run_sql($sqlfile, $silent=1, $entity=0, $usesavepoint=1, $handler='', $okerror='default', $linelengthlimit=32768, $nocommentremoval=0, $offsetforchartofaccount=0, $colspan=0, $onlysqltoimportwebsite=0, $database='')
Launch a sql file.
Cron Job class.
Class DolibarrModules.
delete_permissions()
Removes access rights.
getImportDatasetLabel($r)
Gives translated label of an import dataset.
_init($array_sql, $options='')
Enables a module.
getLastActivationDate()
Gives the last date of activation.
$needUpdate
true indicate this module need update
delete_cronjobs()
Removes boxes.
getKanbanView($codeenabledisable='', $codetoconfig='')
Return Kanban view of a module.
getModulePosition()
Gives the module position.
insert_const()
Adds constants.
__construct($db)
Constructor.
delete_boxes()
Removes boxes.
isCoreOrExternalModule()
Tells if module is core or external.
getDescLongReadmeFound()
Return path of file if a README file was found.
insert_permissions($reinitadminperms=0, $force_entity=null, $notrigger=0)
Adds access rights.
delete_menus()
Removes menu entries.
delete_const()
Removes constants tagged 'deleteonunactive'.
_active()
Insert constants for module activation.
_remove($array_sql, $options='')
Disable function.
getDescLong()
Gives the long description of a module.
insert_boxes($option='')
Adds boxes.
getPublisher()
Gives the publisher name.
getChangeLog()
Gives the changelog.
insert_cronjobs()
Adds cronjobs.
create_dirs()
Creates directories.
delete_module_parts()
Removes generic parts.
getVersion($translated=1)
Gives module version (translated if param $translated is on) For 'experimental' modules,...
$lastVersion
Module last version.
_unactive()
Module deactivation.
getDesc()
Gives the translated module description if translation exists in admin.lang or the default module des...
getExportDatasetLabel($r)
Gives translated label of an export dataset.
getName()
Gives the translated module name if translation exists in admin.lang or into language files of module...
_load_tables($reldir, $onlywithsuffix='')
Create tables and keys required by module:
insert_dirs($name, $dir)
Adds directories definitions.
getLangFilesArray()
Gives module related language files list.
insert_menus()
Adds menu entries.
insert_module_parts()
Save configuration for generic features.
getPublisherUrl()
Gives the publisher url.
getLastActivationInfo()
Gives the last author of activation.
delete_dirs()
Removes directories.
init($options='')
Function called when module is enabled.
static getListOfPagesForBoxes()
Name of positions (See below)
Class to manage menu entries.
Class to manage Dolibarr users.
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
dol_copy($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=0)
Copy a file to another file.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_is_file($pathoffile)
Return if path is a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:63
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
dol_now($mode='auto')
Return date for now.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into javascript code.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
dolMd2Html($content, $parser='parsedown', $replaceimagepath=null)
Function to parse MD content into HTML.
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:140