dolibarr 21.0.0-beta
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 URL_FOR_BLACKLISTED_MODULES = 'https://ping.dolibarr.org/modules-blacklist.txt';
143
144 const KEY_ID = 0;
145 const KEY_LABEL = 1;
146 const KEY_TYPE = 2; // deprecated
147 const KEY_DEFAULT = 3;
148 const KEY_FIRST_LEVEL = 4;
149 const KEY_SECOND_LEVEL = 5;
150 const KEY_MODULE = 6;
151 const KEY_ENABLED = 7;
152
156 public $menu = array();
157
185 public $module_parts = array();
186
190 public $error;
191
195 public $errors;
196
207 public $version;
208
213 public $lastVersion = '';
214
219 public $needUpdate = false;
220
226 public $description;
227
234 public $descriptionlong;
235
239 public $dictionaries = array();
240
244 public $tabs;
245
246 // For exports
247
251 public $export_code;
252
256 public $export_label;
257
261 public $export_icon;
262
266 public $export_enabled;
270 public $export_permission;
274 public $export_fields_array;
278 public $export_TypeFields_array; // Array of key=>type where type can be 'Numeric', 'Date', 'Text', 'Boolean', 'Status', 'List:xxx:fieldlabel:rowid'
282 public $export_entities_array;
286 public $export_aggregate_array;
290 public $export_examplevalues_array;
294 public $export_help_array;
301 public $export_special_array; // special or computed field
308 public $export_dependencies_array;
312 public $export_sql_start;
316 public $export_sql_end;
320 public $export_sql_order;
321
322
323 // For import
324
328 public $import_code;
329
333 public $import_label;
334
338 public $import_icon;
342 public $import_entities_array;
346 public $import_tables_array;
350 public $import_tables_creator_array;
354 public $import_fields_array;
358 public $import_fieldshidden_array;
362 public $import_convertvalue_array;
366 public $import_regex_array;
370 public $import_examplevalues_array;
374 public $import_updatekeys_array;
378 public $import_run_sql_after_array;
382 public $import_TypeFields_array;
386 public $import_help_array;
387
391 public $const_name;
392
396 public $always_enabled;
397
401 public $disabled;
402
406 public $core_enabled;
407
414 public $picto;
415
422 public $config_page_url;
423
424
433 public $depends;
434
439 public $requiredby;
440
445 public $conflictwith;
446
450 public $langfiles;
451
457 public $warnings_activation;
458
464 public $warnings_activation_ext;
465
471 public $warnings_unactivation;
472
477 public $phpmin;
478
482 public $phpmax;
483
488 public $need_dolibarr_version;
489
493 public $need_javascript_ajax;
494
498 public $enabled_bydefault;
499
503 public $hidden = false;
504
508 public $url_last_version;
509
510
516 public function __construct($db)
517 {
518 $this->db = $db;
519 }
520 // We should but can't set this as abstract because this will make dolibarr hang
521 // after migration due to old module not implementing. We must wait PHP is able to make
522 // a try catch on Fatal error to manage this correctly.
523 // We need constructor into function unActivateModule into admin.lib.php
524
525
526 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
537 protected function _init($array_sql, $options = '')
538 {
539 // phpcs:enable
540 global $conf;
541 $err = 0;
542
543 $this->db->begin();
544
545 // Insert activation module constant
546 if (!$err) {
547 $err += $this->_active();
548 }
549
550 // Insert new pages for tabs (into llx_const)
551 if (!$err) {
552 $err += $this->insert_tabs();
553 }
554
555 // Insert activation of module's parts. Copy website templates into doctemplates.
556 if (!$err) {
557 $err += $this->insert_module_parts();
558 }
559
560 // Insert constant defined by modules (into llx_const)
561 if (!$err && !preg_match('/newboxdefonly/', $options)) {
562 $err += $this->insert_const(); // Test on newboxdefonly to avoid to erase value during upgrade
563 }
564
565 // Insert boxes def (into llx_boxes_def) and boxes setup (into llx_boxes)
566 if (!$err && !preg_match('/noboxes/', $options)) {
567 $err += $this->insert_boxes($options);
568 }
569
570 // Insert cron job entries (entry in llx_cronjobs)
571 if (!$err) {
572 $err += $this->insert_cronjobs();
573 }
574
575 // Insert permission definitions of module into llx_rights_def. If user is admin, grant this permission to user.
576 if (!$err) {
577 $err += $this->insert_permissions(1, null, 1);
578 }
579
580 // Insert specific menus entries into database
581 if (!$err) {
582 $err += $this->insert_menus();
583 }
584
585 // Create module's directories
586 if (!$err) {
587 $err += $this->create_dirs();
588 }
589
590 // Execute addons requests
591 $num = count($array_sql);
592 for ($i = 0; $i < $num; $i++) {
593 if (!$err) {
594 $val = $array_sql[$i];
595 $sql = $val;
596 $ignoreerror = 0;
597 if (is_array($val)) {
598 $sql = $val['sql'];
599 $ignoreerror = $val['ignoreerror'];
600 }
601 // Add current entity id
602 $sql = str_replace('__ENTITY__', (string) $conf->entity, $sql);
603
604 dol_syslog(get_class($this)."::_init ignoreerror=".$ignoreerror, LOG_DEBUG);
605 $result = $this->db->query($sql, $ignoreerror);
606 if (!$result) {
607 if (!$ignoreerror) {
608 $this->error = $this->db->lasterror();
609 $err++;
610 } else {
611 dol_syslog(get_class($this)."::_init Warning ".$this->db->lasterror(), LOG_WARNING);
612 }
613 }
614 }
615 }
616
617 // Return code
618 if (!$err) {
619 $this->db->commit();
620
621 $moduleNameInConf = strtolower(preg_replace('/^MAIN_MODULE_/', '', $this->const_name));
622 // two exceptions to handle
623 if ($moduleNameInConf === 'propale') {
624 $moduleNameInConf = 'propal';
625 } elseif ($moduleNameInConf === 'supplierproposal') {
626 $moduleNameInConf = 'supplier_proposal';
627 }
628
629 $conf->modules[$moduleNameInConf] = $moduleNameInConf; // Add this module in list of enabled modules so isModEnabled() will work (conf->module->enabled must no more be used)
630
631 return 1;
632 } else {
633 $this->db->rollback();
634 return 0;
635 }
636 }
637
638 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
647 protected function _remove($array_sql, $options = '')
648 {
649 global $conf;
650 // phpcs:enable
651 $err = 0;
652
653 $this->db->begin();
654
655 // Remove activation module line (constant MAIN_MODULE_MYMODULE in llx_const)
656 if (!$err) {
657 $err += $this->_unactive();
658 }
659
660 // Remove activation of module's new tabs (MAIN_MODULE_MYMODULE_TABS_XXX in llx_const)
661 if (!$err) {
662 $err += $this->delete_tabs();
663 }
664
665 // Remove activation of module's parts (MAIN_MODULE_MYMODULE_XXX in llx_const)
666 if (!$err) {
667 $err += $this->delete_module_parts();
668 }
669
670 // Remove constants defined by modules
671 if (!$err) {
672 $err += $this->delete_const();
673 }
674
675 // Remove list of module's available boxes (entry in llx_boxes)
676 if (!$err && !preg_match('/(newboxdefonly|noboxes)/', $options)) {
677 $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
678 }
679
680 // Remove list of module's cron job entries (entry in llx_cronjobs)
681 if (!$err) {
682 $err += $this->delete_cronjobs();
683 }
684
685 // Remove module's permissions from list of available permissions (entries in llx_rights_def)
686 if (!$err) {
687 $err += $this->delete_permissions();
688 }
689
690 // Remove module's menus (entries in llx_menu)
691 if (!$err) {
692 $err += $this->delete_menus();
693 }
694
695 // Remove module's directories
696 if (!$err) {
697 $err += $this->delete_dirs();
698 }
699
700 // Run complementary sql requests
701 $num = count((array) $array_sql);
702 for ($i = 0; $i < $num; $i++) {
703 if (!$err) {
704 dol_syslog(get_class($this)."::_remove", LOG_DEBUG);
705 $result = $this->db->query($array_sql[$i]);
706 if (!$result) {
707 $this->error = $this->db->error();
708 $err++;
709 }
710 }
711 }
712
713 // Return code
714 if (!$err) {
715 $this->db->commit();
716
717 // Disable modules
718 $moduleNameInConf = strtolower(preg_replace('/^MAIN_MODULE_/', '', $this->const_name));
719 // two exceptions to handle
720 if ($moduleNameInConf === 'propale') {
721 $moduleNameInConf = 'propal';
722 } elseif ($moduleNameInConf === 'supplierproposal') {
723 $moduleNameInConf = 'supplier_proposal';
724 }
725
726 unset($conf->modules[$moduleNameInConf]); // Add this module in list of enabled modules so isModEnabled() will work (conf->module->enabled must no more be used)
727
728 return 1;
729 } else {
730 $this->db->rollback();
731 return 0;
732 }
733 }
734
735
742 public function getName()
743 {
744 global $langs;
745 $langs->load("admin");
746
747 if ($langs->transnoentitiesnoconv("Module".$this->numero."Name") != "Module".$this->numero."Name") {
748 // If module name translation exists
749 return $langs->transnoentitiesnoconv("Module".$this->numero."Name");
750 } else {
751 // If module name translation using it's unique id does not exist, we try to use its name to find translation
752 if (is_array($this->langfiles)) {
753 foreach ($this->langfiles as $val) {
754 if ($val) {
755 $langs->load($val);
756 }
757 }
758 }
759
760 if ($langs->trans("Module".$this->name."Name") != "Module".$this->name."Name") {
761 // If module name translation exists
762 return $langs->transnoentitiesnoconv("Module".$this->name."Name");
763 }
764
765 // Last chance with simple label
766 return $langs->transnoentitiesnoconv($this->name);
767 }
768 }
769
770
776 public function getDesc()
777 {
778 global $langs;
779 $langs->load("admin");
780
781 if ($langs->transnoentitiesnoconv("Module".$this->numero."Desc") != "Module".$this->numero."Desc") {
782 // If module description translation exists
783 return $langs->transnoentitiesnoconv("Module".$this->numero."Desc");
784 } else {
785 // If module description translation does not exist using its unique id, we can use its name to find translation
786 if (is_array($this->langfiles)) {
787 foreach ($this->langfiles as $val) {
788 if ($val) {
789 $langs->load($val);
790 }
791 }
792 }
793
794 if ($langs->transnoentitiesnoconv("Module".$this->name."Desc") != "Module".$this->name."Desc") {
795 // If module name translation exists
796 return $langs->trans("Module".$this->name."Desc");
797 }
798
799 // Last chance with simple label
800 return $langs->trans($this->description);
801 }
802 }
803
810 public function getDescLong()
811 {
812 global $langs;
813 $langs->load("admin");
814
815 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
816 include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
817
818 $content = '';
819 $pathoffile = $this->getDescLongReadmeFound();
820
821 if ($pathoffile) { // Mostly for external modules
822 $content = file_get_contents($pathoffile, false, null, 0, 1024 * 1024); // Max size loaded 1Mb
823
824 if ((float) DOL_VERSION >= 6.0) { // @phpstan-ignore-line
825 @include_once DOL_DOCUMENT_ROOT.'/core/lib/parsemd.lib.php';
826
827 $content = dolMd2Html(
828 $content,
829 'parsedown',
830 array(
831 'doc/' => dol_buildpath(strtolower($this->name).'/doc/', 1),
832 'img/' => dol_buildpath(strtolower($this->name).'/img/', 1),
833 'images/' => dol_buildpath(strtolower($this->name).'/images/', 1),
834 )
835 );
836
837 $content = preg_replace('/<a href="/', '<a target="_blank" rel="noopener noreferrer" href="', $content);
838 } else {
839 $content = nl2br($content);
840 }
841 } else {
842 // Mostly for internal modules
843 if (!empty($this->descriptionlong)) {
844 if (is_array($this->langfiles)) {
845 foreach ($this->langfiles as $val) {
846 if ($val) {
847 $langs->load($val);
848 }
849 }
850 }
851
852 $content = $langs->transnoentitiesnoconv($this->descriptionlong);
853 }
854 }
855
856 return '<div class="moduledesclong">'.$content.'</div>';
857 }
858
864 public function getDescLongReadmeFound()
865 {
866 global $langs;
867
868 $filefound = false;
869
870 // Define path to file README.md.
871 // First check README-la_LA.md then README-la.md then README.md
872 $pathoffile = dol_buildpath(strtolower($this->name).'/README-'.$langs->defaultlang.'.md', 0);
873 if (dol_is_file($pathoffile)) {
874 $filefound = true;
875 }
876 if (!$filefound) {
877 $tmp = explode('_', $langs->defaultlang);
878 $pathoffile = dol_buildpath(strtolower($this->name).'/README-'.$tmp[0].'.md', 0);
879 if (dol_is_file($pathoffile)) {
880 $filefound = true;
881 }
882 }
883 if (!$filefound) {
884 $pathoffile = dol_buildpath(strtolower($this->name).'/README.md', 0);
885 if (dol_is_file($pathoffile)) {
886 $filefound = true;
887 }
888 }
889
890 return ($filefound ? $pathoffile : '');
891 }
892
893
899 public function getChangeLog()
900 {
901 global $langs;
902 $langs->load("admin");
903
904 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
905 include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
906
907 $filefound = false;
908
909 // Define path to file README.md.
910 // First check ChangeLog-la_LA.md then ChangeLog.md
911 $pathoffile = dol_buildpath(strtolower($this->name).'/ChangeLog-'.$langs->defaultlang.'.md', 0);
912 if (dol_is_file($pathoffile)) {
913 $filefound = true;
914 }
915 if (!$filefound) {
916 $pathoffile = dol_buildpath(strtolower($this->name).'/ChangeLog.md', 0);
917 if (dol_is_file($pathoffile)) {
918 $filefound = true;
919 }
920 }
921
922 if ($filefound) { // Mostly for external modules
923 $content = file_get_contents($pathoffile);
924
925 if ((float) DOL_VERSION >= 6.0) { // @phpstan-ignore-line
926 @include_once DOL_DOCUMENT_ROOT.'/core/lib/parsemd.lib.php';
927
928 $content = dolMd2Html($content, 'parsedown', array('doc/' => dol_buildpath(strtolower($this->name).'/doc/', 1)));
929 } else {
930 $content = nl2br($content);
931 }
932 } else {
933 $content = '';
934 }
935
936 return $content;
937 }
938
944 public function getPublisher()
945 {
946 return $this->editor_name;
947 }
948
954 public function getPublisherUrl()
955 {
956 return $this->editor_url;
957 }
958
967 public function getVersion($translated = 1)
968 {
969 global $langs;
970 $langs->load("admin");
971
972 $ret = '';
973
974 $newversion = preg_replace('/_deprecated/', '', $this->version);
975 if ($newversion == 'experimental') {
976 $ret = ($translated ? $langs->transnoentitiesnoconv("VersionExperimental") : $newversion);
977 } elseif ($newversion == 'development') {
978 $ret = ($translated ? $langs->transnoentitiesnoconv("VersionDevelopment") : $newversion);
979 } elseif ($newversion == 'dolibarr') {
980 $ret = DOL_VERSION;
981 } elseif ($newversion) {
982 $ret = $newversion;
983 } else {
984 $ret = ($translated ? $langs->transnoentitiesnoconv("VersionUnknown") : 'unknown');
985 }
986
987 if (preg_match('/_deprecated/', $this->version)) {
988 $ret .= ($translated ? ' ('.$langs->transnoentitiesnoconv("Deprecated").')' : $this->version);
989 }
990 return $ret;
991 }
992
998 public function getModulePosition()
999 {
1000 if (in_array($this->version, array('dolibarr', 'dolibarr_deprecated', 'experimental', 'development'))) { // core module
1001 return $this->module_position;
1002 } else { // external module
1003 if ($this->module_position >= 100000) {
1004 return $this->module_position;
1005 } else {
1006 $position = intval($this->module_position) + 100000;
1007 return strval($position);
1008 }
1009 }
1010 }
1011
1018 public function isCoreOrExternalModule()
1019 {
1020 if ($this->version == 'dolibarr' || $this->version == 'dolibarr_deprecated') {
1021 return 'core';
1022 }
1023 if (!empty($this->version) && !in_array($this->version, array('experimental', 'development'))) {
1024 return 'external';
1025 }
1026 if (!empty($this->editor_name) || !empty($this->editor_url)) {
1027 return 'external';
1028 }
1029 if ($this->numero >= 100000) {
1030 return 'external';
1031 }
1032 return 'unknown';
1033 }
1034
1035
1041 public function getLangFilesArray()
1042 {
1043 return $this->langfiles;
1044 }
1045
1053 public function getExportDatasetLabel($r)
1054 {
1055 global $langs;
1056
1057 $langstring = "ExportDataset_".$this->export_code[$r];
1058 if ($langs->trans($langstring) == $langstring) {
1059 // Translation not found
1060 return $langs->trans($this->export_label[$r]);
1061 } else {
1062 // Translation found
1063 return $langs->trans($langstring);
1064 }
1065 }
1066
1067
1075 public function getImportDatasetLabel($r)
1076 {
1077 global $langs;
1078
1079 $langstring = "ImportDataset_".$this->import_code[$r];
1080 //print "x".$langstring;
1081 if ($langs->trans($langstring) == $langstring) {
1082 // Translation not found
1083 return $langs->transnoentitiesnoconv($this->import_label[$r]);
1084 } else {
1085 // Translation found
1086 return $langs->transnoentitiesnoconv($langstring);
1087 }
1088 }
1089
1090
1096 public function getLastActivationDate()
1097 {
1098 global $conf;
1099
1100 $err = 0;
1101
1102 $sql = "SELECT tms FROM ".MAIN_DB_PREFIX."const";
1103 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
1104 $sql .= " AND entity IN (0, ".((int) $conf->entity).")";
1105
1106 dol_syslog(get_class($this)."::getLastActiveDate", LOG_DEBUG);
1107 $resql = $this->db->query($sql);
1108 if (!$resql) {
1109 $err++;
1110 } else {
1111 $obj = $this->db->fetch_object($resql);
1112 if ($obj) {
1113 return $this->db->jdate($obj->tms);
1114 }
1115 }
1116
1117 return '';
1118 }
1119
1120
1126 public function getLastActivationInfo()
1127 {
1128 global $conf;
1129
1130 $err = 0;
1131
1132 $sql = "SELECT tms, note FROM ".MAIN_DB_PREFIX."const";
1133 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
1134 $sql .= " AND entity IN (0, ".$conf->entity.")";
1135
1136 dol_syslog(get_class($this)."::getLastActiveDate", LOG_DEBUG);
1137 $resql = $this->db->query($sql);
1138 if (!$resql) {
1139 $err++;
1140 } else {
1141 $obj = $this->db->fetch_object($resql);
1142 if ($obj) {
1143 $tmp = array();
1144 if ($obj->note) {
1145 $tmp = json_decode($obj->note, true);
1146 }
1147 return array(
1148 'authorid' => empty($tmp['authorid']) ? '' : (int) $tmp['authorid'],
1149 'ip' => empty($tmp['ip']) ? '' : (string) $tmp['ip'],
1150 'lastactivationdate' => $this->db->jdate($obj->tms),
1151 'lastactivationversion' => (!empty($tmp['lastactivationversion']) ? (string) $tmp['lastactivationversion'] : 'unknown'),
1152 );
1153 }
1154 }
1155
1156 return array();
1157 }
1158
1159
1160 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1166 protected function _active()
1167 {
1168 // phpcs:enable
1169 global $conf, $user;
1170
1171 $err = 0;
1172
1173 // Common module
1174 $entity = ((!empty($this->always_enabled) || !empty($this->core_enabled)) ? 0 : $conf->entity);
1175
1176 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
1177 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
1178 $sql .= " AND entity IN (0, ".$entity.")";
1179
1180 dol_syslog(get_class($this)."::_active delete activation constant", LOG_DEBUG);
1181 $resql = $this->db->query($sql);
1182 if (!$resql) {
1183 $err++;
1184 }
1185
1186 $note = json_encode(
1187 array(
1188 'authorid' => (is_object($user) ? $user->id : 0),
1189 'ip' => (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']),
1190 'lastactivationversion' => $this->version,
1191 )
1192 );
1193
1194 $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name, value, visible, entity, note) VALUES";
1195 $sql .= " (".$this->db->encrypt($this->const_name);
1196 $sql .= ", ".$this->db->encrypt('1');
1197 $sql .= ", 0, ".((int) $entity);
1198 $sql .= ", '".$this->db->escape($note)."')";
1199
1200 dol_syslog(get_class($this)."::_active insert activation constant", LOG_DEBUG);
1201 $resql = $this->db->query($sql);
1202 if (!$resql) {
1203 $err++;
1204 }
1205
1206 return $err;
1207 }
1208
1209
1210 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1216 protected function _unactive()
1217 {
1218 // phpcs:enable
1219 global $conf;
1220
1221 $err = 0;
1222
1223 // Common module
1224 $entity = ((!empty($this->always_enabled) || !empty($this->core_enabled)) ? 0 : $conf->entity);
1225
1226 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
1227 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
1228 $sql .= " AND entity IN (0, ".$entity.")";
1229
1230 dol_syslog(get_class($this)."::_unactive", LOG_DEBUG);
1231 $this->db->query($sql);
1232
1233 return $err;
1234 }
1235
1236
1237 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps,PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1253 protected function _load_tables($reldir, $onlywithsuffix = '')
1254 {
1255 // phpcs:enable
1256 global $conf;
1257
1258 $error = 0;
1259 $dirfound = 0;
1260 $ok = 1;
1261
1262 if (empty($reldir)) {
1263 return 1;
1264 }
1265
1266 include_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
1267
1268 foreach ($conf->file->dol_document_root as $dirroot) {
1269 if ($ok == 1) {
1270 $dirsql = $dirroot.$reldir;
1271 $ok = 0;
1272
1273 // We will loop on xxx/, xxx/tables/, xxx/data/
1274 $listofsubdir = array('', 'tables/', 'data/');
1275 if ($this->db->type == 'pgsql') {
1276 $listofsubdir[] = '../pgsql/functions/';
1277 }
1278
1279 foreach ($listofsubdir as $subdir) {
1280 $dir = $dirsql.$subdir;
1281
1282 $handle = @opendir($dir); // Dir may not exists
1283 if (is_resource($handle)) {
1284 $dirfound++;
1285
1286 // Run llx_mytable.sql files, then llx_mytable_*.sql
1287 $files = array();
1288 while (($file = readdir($handle)) !== false) {
1289 $files[] = $file;
1290 }
1291 sort($files);
1292 foreach ($files as $file) {
1293 if ($onlywithsuffix) {
1294 if (!preg_match('/\-'.preg_quote($onlywithsuffix, '/').'\./i', $file)) {
1295 //print 'File '.$file.' does not match suffix '.$onlywithsuffix.' so it is discarded<br>'."\n";
1296 continue;
1297 } else {
1298 //print 'File '.$file.' match suffix '.$onlywithsuffix.' so we keep it<br>'."\n";
1299 }
1300 }
1301 if (preg_match('/\.sql$/i', $file) && !preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 4) == 'llx_') {
1302 $result = run_sql($dir.$file, !getDolGlobalString('MAIN_DISPLAY_SQL_INSTALL_LOG') ? 1 : 0, 0, 1);
1303 if ($result <= 0) {
1304 $error++;
1305 }
1306 }
1307 }
1308
1309 rewinddir($handle);
1310
1311 // Run llx_mytable.key.sql files (Must be done after llx_mytable.sql) then then llx_mytable_*.key.sql
1312 $files = array();
1313 while (($file = readdir($handle)) !== false) {
1314 $files[] = $file;
1315 }
1316 sort($files);
1317 foreach ($files as $file) {
1318 if ($onlywithsuffix) {
1319 if (!preg_match('/\-'.preg_quote($onlywithsuffix, '/').'\./i', $file)) {
1320 //print 'File '.$file.' does not match suffix '.$onlywithsuffix.' so it is discarded<br>'."\n";
1321 continue;
1322 } else {
1323 //print 'File '.$file.' match suffix '.$onlywithsuffix.' so we keep it<br>'."\n";
1324 }
1325 }
1326 if (preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 4) == 'llx_') {
1327 $result = run_sql($dir.$file, !getDolGlobalString('MAIN_DISPLAY_SQL_INSTALL_LOG') ? 1 : 0, 0, 1);
1328 if ($result <= 0) {
1329 $error++;
1330 }
1331 }
1332 }
1333
1334 rewinddir($handle);
1335
1336 // Run functions-xxx.sql files (Must be done after llx_mytable.key.sql)
1337 $files = array();
1338 while (($file = readdir($handle)) !== false) {
1339 $files[] = $file;
1340 }
1341 sort($files);
1342 foreach ($files as $file) {
1343 if ($onlywithsuffix) {
1344 if (!preg_match('/\-'.preg_quote($onlywithsuffix, '/').'\./i', $file)) {
1345 //print 'File '.$file.' does not match suffix '.$onlywithsuffix.' so it is discarded<br>'."\n";
1346 continue;
1347 } else {
1348 //print 'File '.$file.' match suffix '.$onlywithsuffix.' so we keep it<br>'."\n";
1349 }
1350 }
1351 if (preg_match('/\.sql$/i', $file) && !preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 9) == 'functions') {
1352 $result = run_sql($dir.$file, !getDolGlobalString('MAIN_DISPLAY_SQL_INSTALL_LOG') ? 1 : 0, 0, 1);
1353 if ($result <= 0) {
1354 $error++;
1355 }
1356 }
1357 }
1358
1359 rewinddir($handle);
1360
1361 // Run data_xxx.sql files (Must be done after llx_mytable.key.sql)
1362 $files = array();
1363 while (($file = readdir($handle)) !== false) {
1364 $files[] = $file;
1365 }
1366 sort($files);
1367 foreach ($files as $file) {
1368 if ($onlywithsuffix) {
1369 if (!preg_match('/\-'.preg_quote($onlywithsuffix, '/').'\./i', $file)) {
1370 //print 'File '.$file.' does not match suffix '.$onlywithsuffix.' so it is discarded<br>'."\n";
1371 continue;
1372 } else {
1373 //print 'File '.$file.' match suffix '.$onlywithsuffix.' so we keep it<br>'."\n";
1374 }
1375 }
1376 if (preg_match('/\.sql$/i', $file) && !preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 4) == 'data') {
1377 $result = run_sql($dir.$file, !getDolGlobalString('MAIN_DISPLAY_SQL_INSTALL_LOG') ? 1 : 0, 0, 1);
1378 if ($result <= 0) {
1379 $error++;
1380 }
1381 }
1382 }
1383
1384 rewinddir($handle);
1385
1386 // Run update_xxx.sql files
1387 $files = array();
1388 while (($file = readdir($handle)) !== false) {
1389 $files[] = $file;
1390 }
1391 sort($files);
1392 foreach ($files as $file) {
1393 if ($onlywithsuffix) {
1394 if (!preg_match('/\-'.preg_quote($onlywithsuffix, '/').'\./i', $file)) {
1395 //print 'File '.$file.' does not match suffix '.$onlywithsuffix.' so it is discarded<br>'."\n";
1396 continue;
1397 } else {
1398 //print 'File '.$file.' match suffix '.$onlywithsuffix.' so we keep it<br>'."\n";
1399 }
1400 }
1401 if (preg_match('/\.sql$/i', $file) && !preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 6) == 'update') {
1402 $result = run_sql($dir.$file, !getDolGlobalString('MAIN_DISPLAY_SQL_INSTALL_LOG') ? 1 : 0, 0, 1);
1403 if ($result <= 0) {
1404 $error++;
1405 }
1406 }
1407 }
1408
1409 closedir($handle);
1410 }
1411 }
1412
1413 if ($error == 0) {
1414 $ok = 1;
1415 }
1416 }
1417 }
1418
1419 if (!$dirfound) {
1420 dol_syslog("A module wants to load sql files from ".$reldir." but this directory was not found.", LOG_WARNING);
1421 }
1422 return $ok;
1423 }
1424
1425
1426 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1434 public function insert_boxes($option = '')
1435 {
1436 // phpcs:enable
1437 include_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php';
1438
1439 global $conf;
1440
1441 $err = 0;
1442
1443 if (is_array($this->boxes)) {
1444 dol_syslog(get_class($this)."::insert_boxes", LOG_DEBUG);
1445
1446 $pos_name = InfoBox::getListOfPagesForBoxes();
1447
1448 foreach ($this->boxes as $key => $value) {
1449 $file = isset($this->boxes[$key]['file']) ? $this->boxes[$key]['file'] : '';
1450 $note = isset($this->boxes[$key]['note']) ? $this->boxes[$key]['note'] : '';
1451 $enabledbydefaulton = isset($this->boxes[$key]['enabledbydefaulton']) ? $this->boxes[$key]['enabledbydefaulton'] : 'Home';
1452
1453 if (empty($file)) {
1454 $file = isset($this->boxes[$key][1]) ? $this->boxes[$key][1] : ''; // For backward compatibility
1455 }
1456 if (empty($note)) {
1457 $note = isset($this->boxes[$key][2]) ? $this->boxes[$key][2] : ''; // For backward compatibility
1458 }
1459
1460 // Search if boxes def already present
1461 $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."boxes_def";
1462 $sql .= " WHERE file = '".$this->db->escape($file)."'";
1463 $sql .= " AND entity = ".$conf->entity;
1464 if ($note) {
1465 $sql .= " AND note ='".$this->db->escape($note)."'";
1466 }
1467
1468 $result = $this->db->query($sql);
1469 if ($result) {
1470 $obj = $this->db->fetch_object($result);
1471 if ($obj->nb == 0) {
1472 $this->db->begin();
1473
1474 if (!$err) {
1475 $sql = "INSERT INTO ".MAIN_DB_PREFIX."boxes_def (file, entity, note)";
1476 $sql .= " VALUES ('".$this->db->escape($file)."', ";
1477 $sql .= $conf->entity.", ";
1478 $sql .= $note ? "'".$this->db->escape($note)."'" : "null";
1479 $sql .= ")";
1480
1481 dol_syslog(get_class($this)."::insert_boxes", LOG_DEBUG);
1482 $resql = $this->db->query($sql);
1483 if (!$resql) {
1484 $err++;
1485 }
1486 }
1487 if (!$err && !preg_match('/newboxdefonly/', $option)) {
1488 $lastid = $this->db->last_insert_id(MAIN_DB_PREFIX."boxes_def", "rowid");
1489
1490 foreach ($pos_name as $key2 => $val2) {
1491 //print 'key2='.$key2.'-val2='.$val2."<br>\n";
1492 if ($enabledbydefaulton && $val2 != $enabledbydefaulton) {
1493 continue; // Not enabled by default onto this page.
1494 }
1495
1496 $sql = "INSERT INTO ".MAIN_DB_PREFIX."boxes (box_id, position, box_order, fk_user, entity)";
1497 $sql .= " VALUES (".((int) $lastid).", ".((int) $key2).", '0', 0, ".((int) $conf->entity).")";
1498
1499 dol_syslog(get_class($this)."::insert_boxes onto page ".$key2."=".$val2, LOG_DEBUG);
1500 $resql = $this->db->query($sql);
1501 if (!$resql) {
1502 $err++;
1503 }
1504 }
1505 }
1506
1507 if (!$err) {
1508 $this->db->commit();
1509 } else {
1510 $this->error = $this->db->lasterror();
1511 $this->db->rollback();
1512 }
1513 }
1514 // else box already registered into database
1515 } else {
1516 $this->error = $this->db->lasterror();
1517 $err++;
1518 }
1519 }
1520 }
1521
1522 return $err;
1523 }
1524
1525
1526 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1532 public function delete_boxes()
1533 {
1534 // phpcs:enable
1535 global $conf;
1536
1537 $err = 0;
1538
1539 if (is_array($this->boxes)) {
1540 foreach ($this->boxes as $key => $value) {
1541 //$titre = $this->boxes[$key][0];
1542 if (empty($this->boxes[$key]['file'])) {
1543 $file = isset($this->boxes[$key][1]) ? $this->boxes[$key][1] : ''; // For backward compatibility
1544 } else {
1545 $file = $this->boxes[$key]['file'];
1546 }
1547
1548 //$note = $this->boxes[$key][2];
1549
1550 // TODO If the box is also included by another module and the other module is still on, we should not remove it.
1551 // For the moment, we manage this with hard coded exception
1552 //print "Remove box ".$file.'<br>';
1553 if ($file == 'box_graph_product_distribution.php') {
1554 if (isModEnabled("product") || isModEnabled("service")) {
1555 dol_syslog("We discard deleting module ".$file." because another module still active requires it.");
1556 continue;
1557 }
1558 }
1559
1560 if ($this->db->type == 'sqlite3') {
1561 // sqlite doesn't support "USING" syntax.
1562 // TODO: remove this dependency.
1563 $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes ";
1564 $sql .= "WHERE ".MAIN_DB_PREFIX."boxes.box_id IN (";
1565 $sql .= "SELECT ".MAIN_DB_PREFIX."boxes_def.rowid ";
1566 $sql .= "FROM ".MAIN_DB_PREFIX."boxes_def ";
1567 $sql .= "WHERE ".MAIN_DB_PREFIX."boxes_def.file = '".$this->db->escape($file)."') ";
1568 $sql .= "AND ".MAIN_DB_PREFIX."boxes.entity = ".$conf->entity;
1569 } else {
1570 $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes";
1571 $sql .= " USING ".MAIN_DB_PREFIX."boxes, ".MAIN_DB_PREFIX."boxes_def";
1572 $sql .= " WHERE ".MAIN_DB_PREFIX."boxes.box_id = ".MAIN_DB_PREFIX."boxes_def.rowid";
1573 $sql .= " AND ".MAIN_DB_PREFIX."boxes_def.file = '".$this->db->escape($file)."'";
1574 $sql .= " AND ".MAIN_DB_PREFIX."boxes.entity = ".$conf->entity;
1575 }
1576
1577 dol_syslog(get_class($this)."::delete_boxes", LOG_DEBUG);
1578 $resql = $this->db->query($sql);
1579 if (!$resql) {
1580 $this->error = $this->db->lasterror();
1581 $err++;
1582 }
1583
1584 $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes_def";
1585 $sql .= " WHERE file = '".$this->db->escape($file)."'";
1586 $sql .= " AND entity = ".$conf->entity; // Do not use getEntity here, we want to delete only in current company
1587
1588 dol_syslog(get_class($this)."::delete_boxes", LOG_DEBUG);
1589 $resql = $this->db->query($sql);
1590 if (!$resql) {
1591 $this->error = $this->db->lasterror();
1592 $err++;
1593 }
1594 }
1595 }
1596
1597 return $err;
1598 }
1599
1600 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1606 public function insert_cronjobs()
1607 {
1608 // phpcs:enable
1609 include_once DOL_DOCUMENT_ROOT . '/core/class/infobox.class.php';
1610 include_once DOL_DOCUMENT_ROOT . '/cron/class/cronjob.class.php';
1611 include_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php';
1612
1613 global $conf, $user;
1614
1615 if (empty($user)) {
1616 $user = new User($this->db);
1617 }
1618
1619 $err = 0;
1620
1621 if (is_array($this->cronjobs)) {
1622 dol_syslog(get_class($this) . "::insert_cronjobs", LOG_DEBUG);
1623
1624 foreach ($this->cronjobs as $key => $value) {
1625 $now = dol_now();
1626
1627 $entity = isset($value['entity']) ? $value['entity'] : $conf->entity;
1628 $label = isset($value['label']) ? $value['label'] : '';
1629 $jobtype = isset($value['jobtype']) ? $value['jobtype'] : '';
1630 $classesname = isset($value['class']) ? $value['class'] : '';
1631 $objectname = isset($value['objectname']) ? $value['objectname'] : '';
1632 $methodename = isset($value['method']) ? $value['method'] : '';
1633 $command = isset($value['command']) ? $value['command'] : '';
1634 $params = isset($value['parameters']) ? $value['parameters'] : '';
1635 $md5params = isset($value['md5params']) ? $value['md5params'] : '';
1636 $comment = isset($value['comment']) ? $value['comment'] : '';
1637 $frequency = isset($value['frequency']) ? $value['frequency'] : '';
1638 $unitfrequency = isset($value['unitfrequency']) ? $value['unitfrequency'] : '';
1639 $priority = isset($value['priority']) ? $value['priority'] : '';
1640 $datestart = isset($value['datestart']) ? $value['datestart'] : '';
1641 $dateend = isset($value['dateend']) ? $value['dateend'] : '';
1642 $datenextrun = isset($value['datenextrun']) ? $value['datenextrun'] : $now;
1643 $status = isset($value['status']) ? $value['status'] : '';
1644 $maxrun = isset($value['maxrun']) ? $value['maxrun'] : 0;
1645 $libname = isset($value['libname']) ? $value['libname'] : '';
1646 $test = isset($value['test']) ? $value['test'] : ''; // Line must be enabled or not (so visible or not)
1647
1648 // Search if cron entry already present
1649 $sql = "SELECT count(*) as nb FROM " . MAIN_DB_PREFIX . "cronjob";
1650 //$sql .= " WHERE module_name = '" . $this->db->escape(empty($this->rights_class) ? strtolower($this->name) : $this->rights_class) . "'";
1651 $sql .= " WHERE label = '".$this->db->escape($label)."'";
1652 /* unique key is on label,entity so no need for this test
1653 if ($classesname) {
1654 $sql .= " AND classesname = '" . $this->db->escape($classesname) . "'";
1655 }
1656 if ($objectname) {
1657 $sql .= " AND objectname = '" . $this->db->escape($objectname) . "'";
1658 }
1659 if ($methodename) {
1660 $sql .= " AND methodename = '" . $this->db->escape($methodename) . "'";
1661 }
1662 if ($command) {
1663 $sql .= " AND command = '" . $this->db->escape($command) . "'";
1664 }
1665 if ($params) {
1666 $sql .= " AND params = '" . $this->db->escape($params) . "'";
1667 }
1668 */
1669 $sql .= " AND entity = " . ((int) $entity); // Must be exact entity
1670
1671 $result = $this->db->query($sql);
1672 if (!$result) {
1673 $this->error = $this->db->lasterror();
1674 $err++;
1675 break;
1676 // else box already registered into database
1677 }
1678
1679 $obj = $this->db->fetch_object($result);
1680 if ($obj->nb > 0) {
1681 continue;
1682 }
1683
1684 $cronjob = new Cronjob($this->db);
1685
1686 $cronjob->entity = $entity;
1687 $cronjob->label = $label;
1688 $cronjob->jobtype = $jobtype;
1689 $cronjob->classesname = $classesname;
1690 $cronjob->objectname = $objectname;
1691 $cronjob->methodename = $methodename;
1692 $cronjob->command = $command;
1693 $cronjob->params = $params;
1694 $cronjob->md5params = $md5params;
1695 $cronjob->note_private = $comment;
1696 $cronjob->frequency = $frequency;
1697 $cronjob->unitfrequency = $unitfrequency;
1698 $cronjob->priority = $priority;
1699 $cronjob->datestart = $datestart;
1700 $cronjob->dateend = $dateend;
1701 $cronjob->datenextrun = $datenextrun;
1702 $cronjob->maxrun = $maxrun;
1703 $cronjob->status = $status;
1704 $cronjob->test = $test;
1705 $cronjob->libname = $libname;
1706 $cronjob->module_name = empty($this->rights_class) ? strtolower($this->name) : $this->rights_class;
1707
1708 $retCreate = $cronjob->create($user);
1709
1710 if ($retCreate < 0) {
1711 $this->error = implode("\n", array_merge([$cronjob->error], $cronjob->errors));
1712 return -1;
1713 }
1714 }
1715 }
1716
1717 return $err;
1718 }
1719
1720 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1726 public function delete_cronjobs()
1727 {
1728 // phpcs:enable
1729 global $conf;
1730
1731 $err = 0;
1732
1733 if (is_array($this->cronjobs)) {
1734 $sql = "DELETE FROM ".MAIN_DB_PREFIX."cronjob";
1735 $sql .= " WHERE module_name = '".$this->db->escape(empty($this->rights_class) ? strtolower($this->name) : $this->rights_class)."'";
1736 $sql .= " AND entity = ".$conf->entity;
1737 $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.
1738 // 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.
1739
1740 dol_syslog(get_class($this)."::delete_cronjobs", LOG_DEBUG);
1741 $resql = $this->db->query($sql);
1742 if (!$resql) {
1743 $this->error = $this->db->lasterror();
1744 $err++;
1745 }
1746 }
1747
1748 return $err;
1749 }
1750
1751 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1757 public function delete_tabs()
1758 {
1759 // phpcs:enable
1760 global $conf;
1761
1762 $err = 0;
1763
1764 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
1765 $sql .= " WHERE ".$this->db->decrypt('name')." like '".$this->db->escape($this->const_name)."_TABS_%'";
1766 $sql .= " AND entity = ".$conf->entity;
1767
1768 dol_syslog(get_class($this)."::delete_tabs", LOG_DEBUG);
1769 if (!$this->db->query($sql)) {
1770 $this->error = $this->db->lasterror();
1771 $err++;
1772 }
1773
1774 return $err;
1775 }
1776
1777 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1783 public function insert_tabs()
1784 {
1785 // phpcs:enable
1786 global $conf;
1787
1788 $err = 0;
1789
1790 if (!empty($this->tabs)) {
1791 dol_syslog(get_class($this)."::insert_tabs", LOG_DEBUG);
1792
1793 $i = 0;
1794 foreach ($this->tabs as $key => $value) {
1795 if (is_array($value) && count($value) == 0) {
1796 continue; // Discard empty arrays
1797 }
1798
1799 $entity = $conf->entity;
1800 $newvalue = $value;
1801
1802 if (is_array($value)) {
1803 $newvalue = $value['data'];
1804 if (isset($value['entity'])) {
1805 $entity = $value['entity'];
1806 }
1807 }
1808
1809 if ($newvalue) {
1810 $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (";
1811 $sql .= "name";
1812 $sql .= ", type";
1813 $sql .= ", value";
1814 $sql .= ", note";
1815 $sql .= ", visible";
1816 $sql .= ", entity";
1817 $sql .= ")";
1818 $sql .= " VALUES (";
1819 $sql .= $this->db->encrypt($this->const_name."_TABS_".$i);
1820 $sql .= ", 'chaine'";
1821 $sql .= ", ".$this->db->encrypt($newvalue);
1822 $sql .= ", null";
1823 $sql .= ", '0'";
1824 $sql .= ", ".((int) $entity);
1825 $sql .= ")";
1826
1827 $resql = $this->db->query($sql);
1828 if (!$resql) {
1829 dol_syslog($this->db->lasterror(), LOG_ERR);
1830 if ($this->db->lasterrno() != 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1831 $this->error = $this->db->lasterror();
1832 $this->errors[] = $this->db->lasterror();
1833 $err++;
1834 break;
1835 }
1836 }
1837 }
1838 $i++;
1839 }
1840 }
1841 return $err;
1842 }
1843
1844 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1850 public function insert_const()
1851 {
1852 // phpcs:enable
1853 global $conf;
1854
1855 $err = 0;
1856
1857 if (empty($this->const)) {
1858 return 0;
1859 }
1860
1861 dol_syslog(__METHOD__, LOG_DEBUG);
1862
1863 foreach ($this->const as $key => $value) {
1864 $name = $this->const[$key][0];
1865 $type = $this->const[$key][1];
1866 $val = $this->const[$key][2];
1867 $note = isset($this->const[$key][3]) ? $this->const[$key][3] : '';
1868 $visible = isset($this->const[$key][4]) ? $this->const[$key][4] : 0;
1869 $entity = (!empty($this->const[$key][5]) && $this->const[$key][5] != 'current') ? 0 : $conf->entity;
1870
1871 // Clean
1872 if (empty($visible)) {
1873 $visible = '0';
1874 }
1875 if (empty($val) && $val != '0') {
1876 $val = '';
1877 }
1878
1879 $sql = "SELECT count(*) as nb";
1880 $sql .= " FROM ".MAIN_DB_PREFIX."const";
1881 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($name)."'";
1882 $sql .= " AND entity = ".((int) $entity);
1883
1884 $result = $this->db->query($sql);
1885 if ($result) {
1886 $row = $this->db->fetch_row($result);
1887
1888 if ($row[0] == 0) { // If not found
1889 $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name,type,value,note,visible,entity)";
1890 $sql .= " VALUES (";
1891 $sql .= $this->db->encrypt($name);
1892 $sql .= ",'".$this->db->escape($type)."'";
1893 $sql .= ",".(($val != '') ? $this->db->encrypt($val) : "''");
1894 $sql .= ",".($note ? "'".$this->db->escape($note)."'" : "null");
1895 $sql .= ",'".$this->db->escape($visible)."'";
1896 $sql .= ",".$entity;
1897 $sql .= ")";
1898
1899 if (!$this->db->query($sql)) {
1900 $err++;
1901 }
1902 } else {
1903 dol_syslog(__METHOD__." constant '".$name."' already exists", LOG_DEBUG);
1904 }
1905 } else {
1906 $err++;
1907 }
1908 }
1909
1910 return $err;
1911 }
1912
1913 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1919 public function delete_const()
1920 {
1921 // phpcs:enable
1922 global $conf;
1923
1924 $err = 0;
1925
1926 if (empty($this->const)) {
1927 return 0;
1928 }
1929
1930 foreach ($this->const as $key => $value) {
1931 $name = $this->const[$key][0];
1932 $deleteonunactive = (!empty($this->const[$key][6])) ? 1 : 0;
1933
1934 if ($deleteonunactive) {
1935 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
1936 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($name)."'";
1937 $sql .= " AND entity in (0, ".$conf->entity.")";
1938 dol_syslog(get_class($this)."::delete_const", LOG_DEBUG);
1939 if (!$this->db->query($sql)) {
1940 $this->error = $this->db->lasterror();
1941 $err++;
1942 }
1943 }
1944 }
1945
1946 return $err;
1947 }
1948
1949 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1958 public function insert_permissions($reinitadminperms = 0, $force_entity = null, $notrigger = 0)
1959 {
1960 // phpcs:enable
1961 global $conf, $user;
1962
1963 $err = 0;
1964 $entity = (!empty($force_entity) ? $force_entity : $conf->entity);
1965
1966 dol_syslog(get_class($this)."::insert_permissions", LOG_DEBUG);
1967
1968 // Test if module is activated
1969 $sql_del = "SELECT ".$this->db->decrypt('value')." as value";
1970 $sql_del .= " FROM ".MAIN_DB_PREFIX."const";
1971 $sql_del .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
1972 $sql_del .= " AND entity IN (0,".((int) $entity).")";
1973
1974 $resql = $this->db->query($sql_del);
1975
1976 if ($resql) {
1977 $obj = $this->db->fetch_object($resql);
1978
1979 if ($obj !== null && !empty($obj->value) && !empty($this->rights)) {
1980 include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1981
1982 // TODO rights parameters with integer indexes are deprecated
1983 // $this->rights[$key][0] = $this->rights[$key][self::KEY_ID]
1984 // $this->rights[$key][1] = $this->rights[$key][self::KEY_LABEL]
1985 // $this->rights[$key][3] = $this->rights[$key][self::KEY_DEFAULT]
1986 // $this->rights[$key][4] = $this->rights[$key][self::KEY_FIRST_LEVEL]
1987 // $this->rights[$key][5] = $this->rights[$key][self::KEY_SECOND_LEVEL]
1988
1989 // new parameters
1990 // $this->rights[$key][self::KEY_MODULE] // possibility to define user right for an another module (default: current module name)
1991 // $this->rights[$key][self::KEY_ENABLED] // condition to show or hide a user right (default: 1) (eg isModEnabled('anothermodule'))
1992
1993 // If the module is active
1994 foreach ($this->rights as $key => $value) {
1995 $r_id = $this->rights[$key][self::KEY_ID]; // permission id in llx_rights_def (not unique because primary key is couple id-entity)
1996 $r_label = $this->rights[$key][self::KEY_LABEL];
1997 $r_type = $this->rights[$key][self::KEY_TYPE] ?? 'w'; // TODO deprecated
1998 $r_default = $this->rights[$key][self::KEY_DEFAULT] ?? 0;
1999 $r_perms = $this->rights[$key][self::KEY_FIRST_LEVEL] ?? '';
2000 $r_subperms = $this->rights[$key][self::KEY_SECOND_LEVEL] ?? '';
2001
2002 // KEY_FIRST_LEVEL (perms) must not be empty
2003 if (empty($r_perms)) {
2004 continue;
2005 }
2006
2007 // name of module (default: current module name)
2008 $r_module = (empty($this->rights_class) ? strtolower($this->name) : $this->rights_class);
2009
2010 // name of the module from which the right comes (default: empty means same module the permission is for)
2011 $r_module_origin = '';
2012
2013 if (isset($this->rights[$key][self::KEY_MODULE])) {
2014 // name of the module to which the right must be applied
2015 $r_module = $this->rights[$key][self::KEY_MODULE];
2016 // name of the module from which the right comes
2017 $r_module_origin = (empty($this->rights_class) ? strtolower($this->name) : $this->rights_class);
2018 }
2019
2020 // condition to show or hide a user right (default: 1) (eg isModEnabled('anothermodule') or ($conf->global->MAIN_FEATURES_LEVEL > 0) or etc..)
2021 $r_enabled = $this->rights[$key][self::KEY_ENABLED] ?? '1';
2022
2023 // Search if perm already present
2024 $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."rights_def";
2025 $sql .= " WHERE entity = ".((int) $entity);
2026 $sql .= " AND id = ".((int) $r_id);
2027
2028 $resqlselect = $this->db->query($sql);
2029 if ($resqlselect) {
2030 $objcount = $this->db->fetch_object($resqlselect);
2031 if ($objcount && $objcount->nb == 0) {
2032 $sql = "INSERT INTO ".MAIN_DB_PREFIX."rights_def (";
2033 $sql .= "id";
2034 $sql .= ", entity";
2035 $sql .= ", libelle";
2036 $sql .= ", module";
2037 $sql .= ", module_origin";
2038 $sql .= ", type"; // TODO deprecated
2039 $sql .= ", bydefault";
2040 $sql .= ", perms";
2041 $sql .= ", subperms";
2042 $sql .= ", enabled";
2043 $sql .= ") VALUES (";
2044 $sql .= ((int) $r_id);
2045 $sql .= ", ".((int) $entity);
2046 $sql .= ", '".$this->db->escape($r_label)."'";
2047 $sql .= ", '".$this->db->escape($r_module)."'";
2048 $sql .= ", '".$this->db->escape($r_module_origin)."'";
2049 $sql .= ", '".$this->db->escape($r_type)."'"; // TODO deprecated
2050 $sql .= ", ".((int) $r_default);
2051 $sql .= ", '".$this->db->escape($r_perms)."'";
2052 $sql .= ", '".$this->db->escape($r_subperms)."'";
2053 $sql .= ", '".$this->db->escape($r_enabled)."'";
2054 $sql .= ")";
2055
2056 $resqlinsert = $this->db->query($sql, 1);
2057
2058 if (!$resqlinsert) {
2059 if ($this->db->errno() != "DB_ERROR_RECORD_ALREADY_EXISTS") {
2060 $this->error = $this->db->lasterror();
2061 $err++;
2062 break;
2063 } else {
2064 dol_syslog(get_class($this)."::insert_permissions record already exists", LOG_INFO);
2065 }
2066 }
2067
2068 $this->db->free($resqlinsert);
2069 }
2070
2071 $this->db->free($resqlselect);
2072 }
2073
2074 // If we want to init permissions on admin users
2075 if (!empty($reinitadminperms)) {
2076 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."user WHERE admin = 1";
2077 dol_syslog(get_class($this)."::insert_permissions Search all admin users", LOG_DEBUG);
2078
2079 $resqlseladmin = $this->db->query($sql, 1);
2080
2081 if ($resqlseladmin) {
2082 $num = $this->db->num_rows($resqlseladmin);
2083 $i = 0;
2084 while ($i < $num) {
2085 $obj2 = $this->db->fetch_object($resqlseladmin);
2086 dol_syslog(get_class($this)."::insert_permissions Add permission id ".$r_id." to user id=".$obj2->rowid);
2087
2088 $tmpuser = new User($this->db);
2089 $result = $tmpuser->fetch($obj2->rowid);
2090 if ($result > 0) {
2091 $tmpuser->addrights($r_id, '', '', 0, 1);
2092 } else {
2093 dol_syslog(get_class($this)."::insert_permissions Failed to add the permission to user because fetch return an error", LOG_ERR);
2094 }
2095 $i++;
2096 }
2097 } else {
2098 dol_print_error($this->db);
2099 }
2100 }
2101 }
2102
2103 if (!empty($reinitadminperms) && !empty($user->admin)) { // Reload permission for current user if defined
2104 // We reload permissions
2105 $user->clearrights();
2106 $user->loadRights();
2107 }
2108 }
2109 $this->db->free($resql);
2110 } else {
2111 $this->error = $this->db->lasterror();
2112 $err++;
2113 }
2114
2115 return $err;
2116 }
2117
2118
2119 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2125 public function delete_permissions()
2126 {
2127 // phpcs:enable
2128 global $conf;
2129
2130 $err = 0;
2131
2132 $module = empty($this->rights_class) ? strtolower($this->name) : $this->rights_class;
2133
2134 $sql = "DELETE FROM ".MAIN_DB_PREFIX."rights_def";
2135 $sql .= " WHERE (module = '".$this->db->escape($module)."' OR module_origin = '".$this->db->escape($module)."')";
2136
2137 // Delete all entities if core module
2138 if (empty($this->core_enabled)) {
2139 $sql .= " AND entity = ".((int) $conf->entity);
2140 }
2141
2142 dol_syslog(get_class($this)."::delete_permissions", LOG_DEBUG);
2143 if (!$this->db->query($sql)) {
2144 $this->error = $this->db->lasterror();
2145 $err++;
2146 }
2147
2148 return $err;
2149 }
2150
2151
2152 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2158 public function insert_menus()
2159 {
2160 // phpcs:enable
2161 global $conf, $user;
2162
2163 if (!is_array($this->menu) || empty($this->menu)) {
2164 return 0;
2165 }
2166
2167 include_once DOL_DOCUMENT_ROOT.'/core/class/menubase.class.php';
2168
2169 dol_syslog(get_class($this)."::insert_menus", LOG_DEBUG);
2170
2171 $err = 0;
2172
2173 // Common module
2174 $entity = ((!empty($this->always_enabled) || !empty($this->core_enabled)) ? 0 : $conf->entity);
2175
2176 $this->db->begin();
2177
2178 foreach ($this->menu as $key => $value) {
2179 $menu = new Menubase($this->db);
2180 $menu->menu_handler = 'all';
2181
2182 //$menu->module=strtolower($this->name); TODO When right_class will be same than module name
2183 $menu->module = (empty($this->rights_class) ? strtolower($this->name) : $this->rights_class);
2184
2185 if (!$this->menu[$key]['fk_menu']) {
2186 $menu->fk_menu = 0;
2187 } else {
2188 $foundparent = 0;
2189 $fk_parent = $this->menu[$key]['fk_menu'];
2190 $reg = array();
2191 if (preg_match('/^r=/', $fk_parent)) { // old deprecated method
2192 $fk_parent = str_replace('r=', '', $fk_parent);
2193 if (isset($this->menu[$fk_parent]['rowid'])) {
2194 $menu->fk_menu = $this->menu[$fk_parent]['rowid'];
2195 $foundparent = 1;
2196 }
2197 } elseif (preg_match('/^fk_mainmenu=([a-zA-Z0-9_]+),fk_leftmenu=([a-zA-Z0-9_]+)$/', $fk_parent, $reg)) {
2198 $menu->fk_menu = -1;
2199 $menu->fk_mainmenu = $reg[1];
2200 $menu->fk_leftmenu = $reg[2];
2201 $foundparent = 1;
2202 } elseif (preg_match('/^fk_mainmenu=([a-zA-Z0-9_]+)$/', $fk_parent, $reg)) {
2203 $menu->fk_menu = -1;
2204 $menu->fk_mainmenu = $reg[1];
2205 $menu->fk_leftmenu = '';
2206 $foundparent = 1;
2207 }
2208 if (!$foundparent) {
2209 $this->error = "ErrorBadDefinitionOfMenuArrayInModuleDescriptor";
2210 dol_syslog(get_class($this)."::insert_menus ".$this->error." ".$this->menu[$key]['fk_menu'], LOG_ERR);
2211 $err++;
2212 }
2213 }
2214 $menu->type = $this->menu[$key]['type'];
2215 $menu->mainmenu = isset($this->menu[$key]['mainmenu']) ? $this->menu[$key]['mainmenu'] : (isset($menu->fk_mainmenu) ? $menu->fk_mainmenu : '');
2216 $menu->leftmenu = isset($this->menu[$key]['leftmenu']) ? $this->menu[$key]['leftmenu'] : '';
2217 $menu->title = $this->menu[$key]['titre'];
2218 $menu->prefix = isset($this->menu[$key]['prefix']) ? $this->menu[$key]['prefix'] : '';
2219 $menu->url = $this->menu[$key]['url'];
2220 $menu->langs = isset($this->menu[$key]['langs']) ? $this->menu[$key]['langs'] : '';
2221 $menu->position = $this->menu[$key]['position'];
2222 $menu->perms = $this->menu[$key]['perms'];
2223 $menu->target = isset($this->menu[$key]['target']) ? $this->menu[$key]['target'] : '';
2224 $menu->user = $this->menu[$key]['user'];
2225 $menu->enabled = isset($this->menu[$key]['enabled']) ? $this->menu[$key]['enabled'] : 0;
2226 $menu->position = $this->menu[$key]['position'];
2227 $menu->entity = $entity;
2228
2229 if (!$err) {
2230 $result = $menu->create($user); // Save menu entry into table llx_menu
2231 if ($result > 0) {
2232 $this->menu[$key]['rowid'] = $result;
2233 } else {
2234 $this->error = $menu->error;
2235 dol_syslog(get_class($this).'::insert_menus result='.$result." ".$this->error, LOG_ERR);
2236 $err++;
2237 break;
2238 }
2239 }
2240 }
2241
2242 if (!$err) {
2243 $this->db->commit();
2244 } else {
2245 dol_syslog(get_class($this)."::insert_menus ".$this->error, LOG_ERR);
2246 $this->db->rollback();
2247 }
2248
2249 return $err;
2250 }
2251
2252
2253 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2259 public function delete_menus()
2260 {
2261 // phpcs:enable
2262 global $conf;
2263
2264 $err = 0;
2265
2266 //$module=strtolower($this->name); TODO When right_class will be same than module name
2267 $module = empty($this->rights_class) ? strtolower($this->name) : $this->rights_class;
2268
2269 $sql = "DELETE FROM ".MAIN_DB_PREFIX."menu";
2270 $sql .= " WHERE module = '".$this->db->escape($module)."'";
2271 $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'
2272 $sql .= " AND entity IN (0, ".$conf->entity.")";
2273
2274 dol_syslog(get_class($this)."::delete_menus", LOG_DEBUG);
2275 $resql = $this->db->query($sql);
2276 if (!$resql) {
2277 $this->error = $this->db->lasterror();
2278 $err++;
2279 }
2280
2281 return $err;
2282 }
2283
2284 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2290 public function create_dirs()
2291 {
2292 // phpcs:enable
2293 global $langs, $conf;
2294
2295 $err = 0;
2296 $name = '';
2297
2298 if (isset($this->dirs) && is_array($this->dirs)) {
2299 foreach ($this->dirs as $key => $value) {
2300 $addtodatabase = 0;
2301
2302 if (!is_array($value)) {
2303 $dir = $value; // Default simple mode
2304 } else {
2305 $constname = $this->const_name."_DIR_";
2306 $dir = $this->dirs[$key][1];
2307 $addtodatabase = empty($this->dirs[$key][2]) ? '' : $this->dirs[$key][2]; // Create constante in llx_const
2308 $subname = empty($this->dirs[$key][3]) ? '' : strtoupper($this->dirs[$key][3]); // Add submodule name (ex: $conf->module->submodule->dir_output)
2309 $forcename = empty($this->dirs[$key][4]) ? '' : strtoupper($this->dirs[$key][4]); // Change the module name if different
2310
2311 if (!empty($forcename)) {
2312 $constname = 'MAIN_MODULE_'.$forcename."_DIR_";
2313 }
2314 if (!empty($subname)) {
2315 $constname = $constname.$subname."_";
2316 }
2317
2318 $name = $constname.strtoupper($this->dirs[$key][0]);
2319 }
2320
2321 // Define directory full path ($dir must start with "/")
2322 if (!getDolGlobalString('MAIN_MODULE_MULTICOMPANY') || $conf->entity == 1) {
2323 $fulldir = DOL_DATA_ROOT.$dir;
2324 } else {
2325 $fulldir = DOL_DATA_ROOT."/".$conf->entity.$dir;
2326 }
2327 // Create dir if it does not exists
2328 if (!empty($fulldir) && !file_exists($fulldir)) {
2329 if (dol_mkdir($fulldir, DOL_DATA_ROOT) < 0) {
2330 $this->error = $langs->trans("ErrorCanNotCreateDir", $fulldir);
2331 dol_syslog(get_class($this)."::_init ".$this->error, LOG_ERR);
2332 $err++;
2333 }
2334 }
2335
2336 // Define the constant in database if requested (not the default mode)
2337 if (!empty($addtodatabase) && !empty($name)) {
2338 $result = $this->insert_dirs($name, $dir);
2339 if ($result) {
2340 $err++;
2341 }
2342 }
2343 }
2344 }
2345
2346 return $err;
2347 }
2348
2349
2350 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2359 public function insert_dirs($name, $dir)
2360 {
2361 // phpcs:enable
2362 global $conf;
2363
2364 $err = 0;
2365
2366 $sql = "SELECT count(*)";
2367 $sql .= " FROM ".MAIN_DB_PREFIX."const";
2368 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($name)."'";
2369 $sql .= " AND entity = ".$conf->entity;
2370
2371 dol_syslog(get_class($this)."::insert_dirs", LOG_DEBUG);
2372 $result = $this->db->query($sql);
2373 if ($result) {
2374 $row = $this->db->fetch_row($result);
2375
2376 if ($row[0] == 0) {
2377 $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name, type, value, note, visible, entity)";
2378 $sql .= " VALUES (".$this->db->encrypt($name).", 'chaine', ".$this->db->encrypt($dir).", '".$this->db->escape("Directory for module ".$this->name)."', '0', ".((int) $conf->entity).")";
2379
2380 dol_syslog(get_class($this)."::insert_dirs", LOG_DEBUG);
2381 $this->db->query($sql);
2382 }
2383 } else {
2384 $this->error = $this->db->lasterror();
2385 $err++;
2386 }
2387
2388 return $err;
2389 }
2390
2391
2392 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2398 public function delete_dirs()
2399 {
2400 // phpcs:enable
2401 global $conf;
2402
2403 $err = 0;
2404
2405 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
2406 $sql .= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_DIR_%'";
2407 $sql .= " AND entity = ".$conf->entity;
2408
2409 dol_syslog(get_class($this)."::delete_dirs", LOG_DEBUG);
2410 if (!$this->db->query($sql)) {
2411 $this->error = $this->db->lasterror();
2412 $err++;
2413 }
2414
2415 return $err;
2416 }
2417
2418 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2425 public function insert_module_parts()
2426 {
2427 // phpcs:enable
2428 global $conf, $langs;
2429
2430 $error = 0;
2431
2432 if (is_array($this->module_parts)) {
2433 if (empty($this->module_parts['icon']) && !empty($this->picto) && preg_match('/^fa\-/', $this->picto)) {
2434 $this->module_parts['icon'] = $this->picto;
2435 }
2436
2437 foreach ($this->module_parts as $key => $value) {
2438 if (is_array($value) && count($value) == 0) {
2439 continue; // Discard empty arrays
2440 }
2441
2442 // If module brings website templates, we must generate the zip like we do whenenabling the website module
2443 if ($key == 'websitetemplates' && $value == 1) {
2444 $srcroot = dol_buildpath('/'.strtolower($this->name).'/doctemplates/websites');
2445
2446 // Copy templates in dir format (recommended) into zip file
2447 $docs = dol_dir_list($srcroot, 'directories', 0, 'website_.*$');
2448 foreach ($docs as $cursorfile) {
2449 $src = $srcroot.'/'.$cursorfile['name'];
2450 $dest = DOL_DATA_ROOT.'/doctemplates/websites/'.$cursorfile['name'];
2451
2452 dol_delete_file($dest.'.zip');
2453
2454 // Compress it
2455 global $errormsg;
2456 $errormsg = '';
2457 $result = dol_compress_dir($src, $dest.'.zip', 'zip');
2458 if ($result < 0) {
2459 $error++;
2460 $this->error = ($errormsg ? $errormsg : $langs->trans('ErrorFailToCreateZip', $dest));
2461 $this->errors[] = ($errormsg ? $errormsg : $langs->trans('ErrorFailToCreateZip', $dest));
2462 }
2463 }
2464
2465 // Copy also the preview website_xxx.jpg file
2466 $docs = dol_dir_list($srcroot, 'files', 0, 'website_.*\.jpg$');
2467 foreach ($docs as $cursorfile) {
2468 $src = $srcroot.'/'.$cursorfile['name'];
2469 $dest = DOL_DATA_ROOT.'/doctemplates/websites/'.$cursorfile['name'];
2470
2471 dol_copy($src, $dest);
2472 }
2473 }
2474
2475 $entity = $conf->entity; // Reset the current entity
2476 $newvalue = $value;
2477
2478 // Serialize array parameters
2479 if (is_array($value)) {
2480 // Can defined other parameters
2481 // Example when $key='hooks', then $value is an array('data'=>array('hookcontext1','hookcontext2'), 'entity'=>X)
2482 if (isset($value['data']) && is_array($value['data'])) {
2483 $newvalue = json_encode($value['data']);
2484 if (isset($value['entity'])) {
2485 $entity = $value['entity'];
2486 }
2487 } elseif (isset($value['data']) && !is_array($value['data'])) {
2488 $newvalue = $value['data'];
2489 if (isset($value['entity'])) {
2490 $entity = $value['entity'];
2491 }
2492 } else { // when hook is declared with syntax 'hook'=>array('hookcontext1','hookcontext2',...)
2493 $newvalue = json_encode($value);
2494 }
2495 }
2496
2497 if (!empty($newvalue)) {
2498 $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (";
2499 $sql .= "name";
2500 $sql .= ", type";
2501 $sql .= ", value";
2502 $sql .= ", note";
2503 $sql .= ", visible";
2504 $sql .= ", entity";
2505 $sql .= ")";
2506 $sql .= " VALUES (";
2507 $sql .= " ".$this->db->encrypt($this->const_name."_".strtoupper($key), 1);
2508 $sql .= ", 'chaine'";
2509 $sql .= ", ".$this->db->encrypt($newvalue, 1);
2510 $sql .= ", null";
2511 $sql .= ", '0'";
2512 $sql .= ", ".((int) $entity);
2513 $sql .= ")";
2514
2515 dol_syslog(get_class($this)."::insert_module_parts for key=".$this->const_name."_".strtoupper($key), LOG_DEBUG);
2516
2517 $resql = $this->db->query($sql, 1);
2518 if (!$resql) {
2519 if ($this->db->lasterrno() != 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2520 $error++;
2521 $this->error = $this->db->lasterror();
2522 } else {
2523 dol_syslog(get_class($this)."::insert_module_parts for ".$this->const_name."_".strtoupper($key)." Record already exists.", LOG_WARNING);
2524 }
2525 }
2526 }
2527 }
2528 }
2529 return $error;
2530 }
2531
2532 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2538 public function delete_module_parts()
2539 {
2540 // phpcs:enable
2541 global $conf;
2542
2543 $err = 0;
2544
2545 if (is_array($this->module_parts)) {
2546 dol_syslog(get_class($this)."::delete_module_parts", LOG_DEBUG);
2547
2548 if (empty($this->module_parts['icon']) && !empty($this->picto) && preg_match('/^fa\-/', $this->picto)) {
2549 $this->module_parts['icon'] = $this->picto;
2550 }
2551
2552 foreach ($this->module_parts as $key => $value) {
2553 // If entity is defined
2554 if (is_array($value) && isset($value['entity'])) {
2555 $entity = $value['entity'];
2556 } else {
2557 $entity = $conf->entity;
2558 }
2559
2560 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
2561 $sql .= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_".strtoupper($key)."'";
2562 $sql .= " AND entity = ".((int) $entity);
2563
2564 if (!$this->db->query($sql)) {
2565 $this->error = $this->db->lasterror();
2566 $err++;
2567 }
2568 }
2569 }
2570 return $err;
2571 }
2572
2582 public function init($options = '')
2583 {
2584 return $this->_init(array(), $options);
2585 }
2586
2595 public function remove($options = '')
2596 {
2597 return $this->_remove(array(), $options);
2598 }
2599
2600
2608 public function getKanbanView($codeenabledisable = '', $codetoconfig = '')
2609 {
2610 global $langs;
2611
2612 // Define imginfo
2613 $imginfo = "info";
2614 if ($this->isCoreOrExternalModule() == 'external') {
2615 $imginfo = "info_black";
2616 }
2617
2618 $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($this)));
2619
2620 $version = $this->getVersion(0);
2621 $versiontrans = '';
2622 if (preg_match('/development/i', $version)) {
2623 $versiontrans .= 'warning';
2624 }
2625 if (preg_match('/experimental/i', $version)) {
2626 $versiontrans .= 'warning';
2627 }
2628 if (preg_match('/deprecated/i', $version)) {
2629 $versiontrans .= 'warning';
2630 }
2631
2632 $return = '
2633 <div class="box-flex-item info-box-module'
2634 .(getDolGlobalString($const_name) ? '' : ' --disabled')
2635 .($this->isCoreOrExternalModule() == 'external' ? ' --external' : '')
2636 .($this->needUpdate ? ' --need-update' : '')
2637 .'">
2638 <div class="info-box info-box-sm info-box-module">
2639 <div class="info-box-icon'.(!getDolGlobalString($const_name) ? '' : ' info-box-icon-module-enabled'.($versiontrans ? ' info-box-icon-module-warning' : '')).'">';
2640
2641 $alttext = '';
2642 //if (is_array($objMod->need_dolibarr_version)) $alttext.=($alttext?' - ':'').'Dolibarr >= '.join('.',$objMod->need_dolibarr_version);
2643 //if (is_array($objMod->phpmin)) $alttext.=($alttext?' - ':'').'PHP >= '.join('.',$objMod->phpmin);
2644 if (!empty($this->picto)) {
2645 if (preg_match('/^\//i', $this->picto)) {
2646 $return .= img_picto($alttext, $this->picto, 'class="inline-block valignmiddle"', 1);
2647 } else {
2648 $return .= img_object($alttext, $this->picto, 'class="inline-block valignmiddle"');
2649 }
2650 } else {
2651 $return .= img_object($alttext, 'generic', 'class="inline-block valignmiddle"');
2652 }
2653
2654 if ($this->isCoreOrExternalModule() == 'external' || preg_match('/development|experimental|deprecated/i', $version)) {
2655 $versionTitle = $langs->trans("Version").' '.$this->getVersion(1);
2656 if ($this->needUpdate) {
2657 $versionTitle .= '<br>'.$langs->trans('ModuleUpdateAvailable').' : '.$this->lastVersion;
2658 }
2659
2660 $return .= '<span class="info-box-icon-version'.($versiontrans ? ' '.$versiontrans : '').' classfortooltip" title="'.dol_escape_js($versionTitle).'" >';
2661 $return .= $this->getVersion(1);
2662 $return .= '</span>';
2663 }
2664
2665 $return .= '</div>
2666 <div class="info-box-content info-box-text-module'.(!getDolGlobalString($const_name) ? '' : ' info-box-module-enabled'.($versiontrans ? ' info-box-content-warning' : '')).'">
2667 <span class="info-box-title">'.$this->getName().'</span>
2668 <span class="info-box-desc twolinesmax opacitymedium" title="'.dol_escape_htmltag($this->getDesc()).'">'.nl2br($this->getDesc()).'</span>';
2669
2670 $return .= '<div class="valignmiddle inline-block info-box-more">';
2671 //if ($versiontrans) print img_warning($langs->trans("Version").' '.$this->getVersion(1)).' ';
2672 $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>';
2673 $return .= '</div><br>';
2674
2675 $return .= '<div class="valignmiddle inline-block info-box-actions">';
2676 $return .= '<div class="valignmiddle inline-block info-box-setup">';
2677 $return .= $codetoconfig;
2678 $return .= '</div>';
2679 $return .= '<div class="valignmiddle inline-block marginleftonly marginrightonly">';
2680 $return .= $codeenabledisable;
2681 $return .= '</div>';
2682 $return .= '</div>';
2683
2684 $return .= '
2685 </div><!-- /.info-box-content -->
2686 </div><!-- /.info-box -->
2687 </div>';
2688
2689 return $return;
2690 }
2691
2700 public function checkForUpdate()
2701 {
2702 require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
2703 if (!empty($this->url_last_version)) {
2704 $lastVersion = getURLContent($this->url_last_version, 'GET', '', 1, array(), array('http', 'https'), 0); // Accept http or https links on external remote server only
2705 if (isset($lastVersion['content']) && strlen($lastVersion['content']) < 30) {
2706 // 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 _ . -
2707 $this->lastVersion = preg_replace("/[^a-zA-Z0-9_\.\-]+/", "", $lastVersion['content']);
2708 if (version_compare($this->lastVersion, $this->version) > 0) {
2709 $this->needUpdate = true;
2710 return 1;
2711 } else {
2712 $this->needUpdate = false;
2713 return 0;
2714 }
2715 } else {
2716 return -1;
2717 }
2718 }
2719 return 0;
2720 }
2721
2729 public function checkForCompliance($nametocheck = '')
2730 {
2731 global $conf, $langs;
2732
2733 if (empty($nametocheck)) {
2734 $nametocheck = $this->name;
2735 }
2736
2737 // Get list of illegal modules name or ID
2738 if (empty($conf->cache['noncompliantmodules'])) {
2739 require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
2740
2741 $result = getURLContent(self::URL_FOR_BLACKLISTED_MODULES, 'GET', '', 1, array(), array('http', 'https'), 0); // Accept http or https links on external remote server only
2742 if (isset($result['content']) && $result['http_code'] == 200) {
2743 $langs->load("errors");
2744
2745 // 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 _ . -
2746 $arrayoflines = preg_split("/[\n,]/", $result['content']);
2747 foreach ($arrayoflines as $line) {
2748 $tmpfieldsofline = explode(';', $line);
2749 $modulekey = strtolower($tmpfieldsofline[0]);
2750 $conf->cache['noncompliantmodules'][$modulekey]['name'] = $tmpfieldsofline[0];
2751 $conf->cache['noncompliantmodules'][$modulekey]['id'] = $tmpfieldsofline[1];
2752 $conf->cache['noncompliantmodules'][$modulekey]['signature'] = $tmpfieldsofline[2];
2753 $conf->cache['noncompliantmodules'][$modulekey]['message'] = $langs->trans(empty($tmpfieldsofline[3]) ? 'WarningModuleAffiliatedToAReportedCompany' : $tmpfieldsofline[3]);
2754 if (!empty($tmpfieldsofline[4])) {
2755 $message2 = $langs->trans("WarningModuleAffiliatedToAPiratPlatform", '{s}');
2756 $listofillegalurl = '';
2757 foreach (explode(" ", $tmpfieldsofline[4]) as $illegalurl) {
2758 $listofillegalurl .= ($listofillegalurl ? ' '.$langs->trans("or").' ' : '').'<b>'.preg_replace('/[^a-z0-9\.\-]/', '', $illegalurl).'</b>';
2759 }
2760 $message2 = str_replace('{s}', $listofillegalurl, $message2);
2761 $conf->cache['noncompliantmodules'][$modulekey]['message2'] = $message2;
2762 }
2763 }
2764 }
2765 }
2766
2767 if (!empty($conf->cache['noncompliantmodules'])) {
2768 $modulekey = strtolower($nametocheck);
2769 if (in_array($modulekey, array_keys($conf->cache['noncompliantmodules']))) {
2770 $answer = trim($conf->cache['noncompliantmodules'][$modulekey]['message']);
2771 if (!empty($conf->cache['noncompliantmodules'][$modulekey]['message2'])) {
2772 $answer .= '<br>'.$conf->cache['noncompliantmodules'][$modulekey]['message2'];
2773 }
2774 return $answer;
2775 }
2776 }
2777
2778 return 0;
2779 }
2780
2799 protected function declareNewDictionary($dictionaryArray, $langs = '')
2800 {
2801 $fields = array('name', 'lib', 'sql', 'sqlsort', 'field', 'fieldvalue', 'fieldinsert', 'rowid', 'cond', 'help', 'fieldcheck');
2802
2803 foreach ($fields as $field) {
2804 if (isset($dictionaryArray[$field])) {
2805 // @phan-suppress-next-line PhanTypeMismatchProperty
2806 $this->dictionaries['tab'.$field][] = $dictionaryArray[$field];
2807 }
2808 }
2809 if ($langs && !in_array($langs, $this->dictionaries[$langs])) {
2810 $this->dictionaries['langs'][] = $langs;
2811 }
2812 }
2813}
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...
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
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:152