dolibarr 22.0.5
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-2025 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
494 public $max_dolibarr_version;
495
499 public $need_javascript_ajax;
500
504 public $enabled_bydefault;
505
509 public $hidden = false;
510
514 public $url_last_version;
515
516
522 public function __construct($db)
523 {
524 $this->db = $db;
525 }
526 // We should but can't set this as abstract because this will make dolibarr hang
527 // after migration due to old module not implementing. We must wait PHP is able to make
528 // a try catch on Fatal error to manage this correctly.
529 // We need constructor into function unActivateModule into admin.lib.php
530
531
532 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
543 protected function _init($array_sql, $options = '')
544 {
545 // phpcs:enable
546 global $conf;
547 $err = 0;
548
549 $this->db->begin();
550
551 // Insert activation module constant
552 if (!$err) {
553 $err += $this->_active();
554 }
555
556 // Insert new pages for tabs (into llx_const)
557 if (!$err) {
558 $err += $this->insert_tabs();
559 }
560
561 // Insert activation of module's parts. Copy website templates into doctemplates.
562 if (!$err) {
563 $err += $this->insert_module_parts();
564 }
565
566 // Insert constant defined by modules (into llx_const)
567 if (!$err && !preg_match('/newboxdefonly/', $options)) {
568 $err += $this->insert_const(); // Test on newboxdefonly to avoid to erase value during upgrade
569 }
570
571 // Insert boxes def (into llx_boxes_def) and boxes setup (into llx_boxes)
572 if (!$err && !preg_match('/noboxes/', $options)) {
573 $err += $this->insert_boxes($options);
574 }
575
576 // Insert cron job entries (entry in llx_cronjobs)
577 if (!$err) {
578 $err += $this->insert_cronjobs();
579 }
580
581 // Insert permission definitions of module into llx_rights_def. If user is admin, grant this permission to user.
582 if (!$err) {
583 $err += $this->insert_permissions(1, null, 1);
584 }
585
586 // Insert specific menus entries into database
587 if (!$err) {
588 $err += $this->insert_menus();
589 }
590
591 // Create module's directories
592 if (!$err) {
593 $err += $this->create_dirs();
594 }
595
596 // Execute addons requests
597 $num = count($array_sql);
598 for ($i = 0; $i < $num; $i++) {
599 if (!$err) {
600 $val = $array_sql[$i];
601 $sql = $val;
602 $ignoreerror = 0;
603 if (is_array($val)) {
604 $sql = $val['sql'];
605 $ignoreerror = $val['ignoreerror'] ?? 0;
606 }
607 // Add current entity id
608 $sql = str_replace('__ENTITY__', (string) $conf->entity, $sql);
609
610 dol_syslog(get_class($this)."::_init ignoreerror=".$ignoreerror, LOG_DEBUG);
611 $result = $this->db->query($sql, $ignoreerror);
612 if (!$result) {
613 if (!$ignoreerror) {
614 $this->error = $this->db->lasterror();
615 $err++;
616 } else {
617 dol_syslog(get_class($this)."::_init Warning ".$this->db->lasterror(), LOG_WARNING);
618 }
619 }
620 }
621 }
622
623 // Return code
624 if (!$err) {
625 $this->db->commit();
626
627 $moduleNameInConf = strtolower(preg_replace('/^MAIN_MODULE_/', '', $this->const_name));
628 // two exceptions to handle
629 if ($moduleNameInConf === 'propale') {
630 $moduleNameInConf = 'propal';
631 } elseif ($moduleNameInConf === 'supplierproposal') {
632 $moduleNameInConf = 'supplier_proposal';
633 }
634
635 $conf->modules[$moduleNameInConf] = $moduleNameInConf; // Add this module in list of enabled modules so isModEnabled() will work (conf->module->enabled must no more be used)
636
637 return 1;
638 } else {
639 $this->db->rollback();
640 return 0;
641 }
642 }
643
644 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
653 protected function _remove($array_sql, $options = '')
654 {
655 global $conf;
656 // phpcs:enable
657 $err = 0;
658
659 $this->db->begin();
660
661 // Remove activation module line (constant MAIN_MODULE_MYMODULE in llx_const)
662 if (!$err) {
663 $err += $this->_unactive();
664 }
665
666 // Remove activation of module's new tabs (MAIN_MODULE_MYMODULE_TABS_XXX in llx_const)
667 if (!$err) {
668 $err += $this->delete_tabs();
669 }
670
671 // Remove activation of module's parts (MAIN_MODULE_MYMODULE_XXX in llx_const)
672 if (!$err) {
673 $err += $this->delete_module_parts();
674 }
675
676 // Remove constants defined by modules
677 if (!$err) {
678 $err += $this->delete_const();
679 }
680
681 // Remove list of module's available boxes (entry in llx_boxes)
682 if (!$err && !preg_match('/(newboxdefonly|noboxes)/', $options)) {
683 $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
684 }
685
686 // Remove list of module's cron job entries (entry in llx_cronjobs)
687 if (!$err) {
688 $err += $this->delete_cronjobs();
689 }
690
691 // Remove module's permissions from list of available permissions (entries in llx_rights_def)
692 if (!$err) {
693 $err += $this->delete_permissions();
694 }
695
696 // Remove module's menus (entries in llx_menu)
697 if (!$err) {
698 $err += $this->delete_menus();
699 }
700
701 // Remove module's directories
702 if (!$err) {
703 $err += $this->delete_dirs();
704 }
705
706 // Run complementary sql requests
707 $num = count((array) $array_sql);
708 for ($i = 0; $i < $num; $i++) {
709 if (!$err) {
710 dol_syslog(get_class($this)."::_remove", LOG_DEBUG);
711 $result = $this->db->query($array_sql[$i]);
712 if (!$result) {
713 $this->error = $this->db->error();
714 $err++;
715 }
716 }
717 }
718
719 // Return code
720 if (!$err) {
721 $this->db->commit();
722
723 // Disable modules
724 $moduleNameInConf = strtolower(preg_replace('/^MAIN_MODULE_/', '', $this->const_name));
725 // two exceptions to handle
726 if ($moduleNameInConf === 'propale') {
727 $moduleNameInConf = 'propal';
728 } elseif ($moduleNameInConf === 'supplierproposal') {
729 $moduleNameInConf = 'supplier_proposal';
730 }
731
732 unset($conf->modules[$moduleNameInConf]); // Add this module in list of enabled modules so isModEnabled() will work (conf->module->enabled must no more be used)
733
734 return 1;
735 } else {
736 $this->db->rollback();
737 return 0;
738 }
739 }
740
741
748 public function getName()
749 {
750 global $langs;
751 $langs->load("admin");
752
753 if ($langs->transnoentitiesnoconv("Module".$this->numero."Name") != "Module".$this->numero."Name") {
754 // If module name translation exists
755 return $langs->transnoentitiesnoconv("Module".$this->numero."Name");
756 } else {
757 // If module name translation using it's unique id does not exist, we try to use its name to find translation
758 if (is_array($this->langfiles)) {
759 foreach ($this->langfiles as $val) {
760 if ($val) {
761 $langs->load($val);
762 }
763 }
764 }
765
766 if ($langs->trans("Module".$this->name."Name") != "Module".$this->name."Name") {
767 // If module name translation exists
768 return $langs->transnoentitiesnoconv("Module".$this->name."Name");
769 }
770
771 // Last chance with simple label
772 return $langs->transnoentitiesnoconv($this->name);
773 }
774 }
775
776
782 public function getDesc()
783 {
784 global $langs;
785 $langs->load("admin");
786
787 if ($langs->transnoentitiesnoconv("Module".$this->numero."Desc") != "Module".$this->numero."Desc") {
788 // If module description translation exists
789 return $langs->transnoentitiesnoconv("Module".$this->numero."Desc");
790 } else {
791 // If module description translation does not exist using its unique id, we can use its name to find translation
792 if (is_array($this->langfiles)) {
793 foreach ($this->langfiles as $val) {
794 if ($val) {
795 $langs->load($val);
796 }
797 }
798 }
799
800 if ($langs->transnoentitiesnoconv("Module".$this->name."Desc") != "Module".$this->name."Desc") {
801 // If module name translation exists
802 return $langs->trans("Module".$this->name."Desc");
803 }
804
805 // Last chance with simple label
806 return $langs->trans($this->description);
807 }
808 }
809
816 public function getDescLong()
817 {
818 global $langs;
819 $langs->load("admin");
820
821 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
822 include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
823
824 $content = '';
825 $pathoffile = $this->getDescLongReadmeFound();
826
827 if ($pathoffile) { // Mostly for external modules
828 $content = file_get_contents($pathoffile, false, null, 0, 1024 * 1024); // Max size loaded 1Mb
829
830 if ((float) DOL_VERSION >= 6.0) { // @phpstan-ignore-line
831 @include_once DOL_DOCUMENT_ROOT.'/core/lib/parsemd.lib.php';
832
833 $content = dolMd2Html(
834 $content,
835 'parsedown',
836 array(
837 'doc/' => dol_buildpath(strtolower($this->name).'/doc/', 1),
838 'img/' => dol_buildpath(strtolower($this->name).'/img/', 1),
839 'images/' => dol_buildpath(strtolower($this->name).'/images/', 1),
840 )
841 );
842
843 $content = preg_replace('/<a href="/', '<a target="_blank" rel="noopener noreferrer" href="', $content);
844 } else {
845 $content = nl2br($content);
846 }
847 } else {
848 // Mostly for internal modules
849 if (!empty($this->descriptionlong)) {
850 if (is_array($this->langfiles)) {
851 foreach ($this->langfiles as $val) {
852 if ($val) {
853 $langs->load($val);
854 }
855 }
856 }
857
858 $content = $langs->transnoentitiesnoconv($this->descriptionlong);
859 }
860 }
861
862 return '<div class="moduledesclong">'.$content.'</div>';
863 }
864
870 public function getDescLongReadmeFound()
871 {
872 global $langs;
873
874 $filefound = false;
875
876 // Define path to file README.md.
877 // First check README-la_LA.md then README-la.md then README.md
878 $pathoffile = dol_buildpath(strtolower($this->name).'/README-'.$langs->defaultlang.'.md', 0);
879 if (dol_is_file($pathoffile)) {
880 $filefound = true;
881 }
882 if (!$filefound) {
883 $tmp = explode('_', $langs->defaultlang);
884 $pathoffile = dol_buildpath(strtolower($this->name).'/README-'.$tmp[0].'.md', 0);
885 if (dol_is_file($pathoffile)) {
886 $filefound = true;
887 }
888 }
889 if (!$filefound) {
890 $pathoffile = dol_buildpath(strtolower($this->name).'/README.md', 0);
891 if (dol_is_file($pathoffile)) {
892 $filefound = true;
893 }
894 }
895
896 return ($filefound ? $pathoffile : '');
897 }
898
899
905 public function getChangeLog()
906 {
907 global $langs;
908 $langs->load("admin");
909
910 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
911 include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
912
913 $filefound = false;
914
915 // Define path to file README.md.
916 // First check ChangeLog-la_LA.md then ChangeLog.md
917 $pathoffile = dol_buildpath(strtolower($this->name).'/ChangeLog-'.$langs->defaultlang.'.md', 0);
918 if (dol_is_file($pathoffile)) {
919 $filefound = true;
920 }
921 if (!$filefound) {
922 $pathoffile = dol_buildpath(strtolower($this->name).'/ChangeLog.md', 0);
923 if (dol_is_file($pathoffile)) {
924 $filefound = true;
925 }
926 }
927
928 if ($filefound) { // Mostly for external modules
929 $content = file_get_contents($pathoffile);
930
931 if ((float) DOL_VERSION >= 6.0) { // @phpstan-ignore-line
932 @include_once DOL_DOCUMENT_ROOT.'/core/lib/parsemd.lib.php';
933
934 $content = dolMd2Html($content, 'parsedown', array('doc/' => dol_buildpath(strtolower($this->name).'/doc/', 1)));
935 } else {
936 $content = nl2br($content);
937 }
938 } else {
939 $content = '';
940 }
941
942 return $content;
943 }
944
950 public function getPublisher()
951 {
952 return $this->editor_name;
953 }
954
960 public function getPublisherUrl()
961 {
962 return $this->editor_url;
963 }
964
973 public function getVersion($translated = 1)
974 {
975 global $langs;
976 $langs->load("admin");
977
978 $ret = '';
979
980 $newversion = preg_replace('/_deprecated/', '', $this->version);
981 if ($newversion == 'experimental') {
982 $ret = ($translated ? $langs->transnoentitiesnoconv("VersionExperimental") : $newversion);
983 } elseif ($newversion == 'development') {
984 $ret = ($translated ? $langs->transnoentitiesnoconv("VersionDevelopment") : $newversion);
985 } elseif ($newversion == 'dolibarr') {
986 $ret = DOL_VERSION;
987 } elseif ($newversion) {
988 $ret = $newversion;
989 } else {
990 $ret = ($translated ? $langs->transnoentitiesnoconv("VersionUnknown") : 'unknown');
991 }
992
993 if (preg_match('/_deprecated/', $this->version)) {
994 $ret .= ($translated ? ' ('.$langs->transnoentitiesnoconv("Deprecated").')' : $this->version);
995 }
996 return $ret;
997 }
998
1004 public function getModulePosition()
1005 {
1006 if (in_array($this->version, array('dolibarr', 'dolibarr_deprecated', 'experimental', 'development'))) { // core module
1007 return $this->module_position;
1008 } else { // external module
1009 if ($this->module_position >= 100000) {
1010 return $this->module_position;
1011 } else {
1012 $position = intval($this->module_position) + 100000;
1013 return strval($position);
1014 }
1015 }
1016 }
1017
1024 public function isCoreOrExternalModule()
1025 {
1026 if ($this->version == 'dolibarr' || $this->version == 'dolibarr_deprecated') {
1027 return 'core';
1028 }
1029 if (!empty($this->version) && !in_array($this->version, array('experimental', 'development'))) {
1030 return 'external';
1031 }
1032 if (!empty($this->editor_name) || !empty($this->editor_url)) {
1033 return 'external';
1034 }
1035 if ($this->numero >= 100000) {
1036 return 'external';
1037 }
1038 return 'unknown';
1039 }
1040
1041
1047 public function getLangFilesArray()
1048 {
1049 return $this->langfiles;
1050 }
1051
1059 public function getExportDatasetLabel($r)
1060 {
1061 global $langs;
1062
1063 $langstring = "ExportDataset_".$this->export_code[$r];
1064 if ($langs->trans($langstring) == $langstring) {
1065 // Translation not found
1066 return $langs->trans($this->export_label[$r]);
1067 } else {
1068 // Translation found
1069 return $langs->trans($langstring);
1070 }
1071 }
1072
1073
1081 public function getImportDatasetLabel($r)
1082 {
1083 global $langs;
1084
1085 $langstring = "ImportDataset_".$this->import_code[$r];
1086 //print "x".$langstring;
1087 if ($langs->trans($langstring) == $langstring) {
1088 // Translation not found
1089 return $langs->transnoentitiesnoconv($this->import_label[$r]);
1090 } else {
1091 // Translation found
1092 return $langs->transnoentitiesnoconv($langstring);
1093 }
1094 }
1095
1096
1102 public function getLastActivationDate()
1103 {
1104 global $conf;
1105
1106 $err = 0;
1107
1108 $sql = "SELECT tms FROM ".MAIN_DB_PREFIX."const";
1109 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
1110 $sql .= " AND entity IN (0, ".((int) $conf->entity).")";
1111
1112 dol_syslog(get_class($this)."::getLastActiveDate", LOG_DEBUG);
1113 $resql = $this->db->query($sql);
1114 if (!$resql) {
1115 $err++;
1116 } else {
1117 $obj = $this->db->fetch_object($resql);
1118 if ($obj) {
1119 return $this->db->jdate($obj->tms);
1120 }
1121 }
1122
1123 return '';
1124 }
1125
1126
1132 public function getLastActivationInfo()
1133 {
1134 global $conf;
1135
1136 $err = 0;
1137
1138 $sql = "SELECT tms, note FROM ".MAIN_DB_PREFIX."const";
1139 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
1140 $sql .= " AND entity IN (0, ".$conf->entity.")";
1141
1142 dol_syslog(get_class($this)."::getLastActiveDate", LOG_DEBUG);
1143 $resql = $this->db->query($sql);
1144 if (!$resql) {
1145 $err++;
1146 } else {
1147 $obj = $this->db->fetch_object($resql);
1148 if ($obj) {
1149 $tmp = array();
1150 if ($obj->note) {
1151 $tmp = json_decode($obj->note, true);
1152 }
1153 return array(
1154 'authorid' => empty($tmp['authorid']) ? '' : (int) $tmp['authorid'],
1155 'ip' => empty($tmp['ip']) ? '' : (string) $tmp['ip'],
1156 'lastactivationdate' => $this->db->jdate($obj->tms),
1157 'lastactivationversion' => (!empty($tmp['lastactivationversion']) ? (string) $tmp['lastactivationversion'] : 'unknown'),
1158 );
1159 }
1160 }
1161
1162 return array();
1163 }
1164
1165
1166 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1172 protected function _active()
1173 {
1174 // phpcs:enable
1175 global $conf, $user;
1176
1177 $err = 0;
1178
1179 // Common module
1180 $entity = ((!empty($this->always_enabled) || !empty($this->core_enabled)) ? 0 : $conf->entity);
1181
1182 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
1183 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
1184 $sql .= " AND entity IN (0, ".$entity.")";
1185
1186 dol_syslog(get_class($this)."::_active delete activation constant", LOG_DEBUG);
1187 $resql = $this->db->query($sql);
1188 if (!$resql) {
1189 $err++;
1190 }
1191
1192 $note = json_encode(
1193 array(
1194 'authorid' => (is_object($user) ? $user->id : 0),
1195 'ip' => (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']),
1196 'lastactivationversion' => $this->version,
1197 )
1198 );
1199
1200 $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name, value, visible, entity, note) VALUES";
1201 $sql .= " (".$this->db->encrypt($this->const_name);
1202 $sql .= ", ".$this->db->encrypt('1');
1203 $sql .= ", 0, ".((int) $entity);
1204 $sql .= ", '".$this->db->escape($note)."')";
1205
1206 dol_syslog(get_class($this)."::_active insert activation constant", LOG_DEBUG);
1207 $resql = $this->db->query($sql);
1208 if (!$resql) {
1209 $err++;
1210 }
1211
1212 return $err;
1213 }
1214
1215
1216 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1222 protected function _unactive()
1223 {
1224 // phpcs:enable
1225 global $conf;
1226
1227 $err = 0;
1228
1229 // Common module
1230 $entity = ((!empty($this->always_enabled) || !empty($this->core_enabled)) ? 0 : $conf->entity);
1231
1232 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
1233 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
1234 $sql .= " AND entity IN (0, ".$entity.")";
1235
1236 dol_syslog(get_class($this)."::_unactive", LOG_DEBUG);
1237 $this->db->query($sql);
1238
1239 return $err;
1240 }
1241
1242
1243 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps,PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1259 protected function _load_tables($reldir, $onlywithsuffix = '')
1260 {
1261 // phpcs:enable
1262 global $conf;
1263
1264 $error = 0;
1265 $dirfound = 0;
1266 $ok = 1;
1267
1268 if (empty($reldir)) {
1269 return 1;
1270 }
1271
1272 include_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
1273
1274 foreach ($conf->file->dol_document_root as $dirroot) {
1275 if ($ok == 1) {
1276 $dirsql = $dirroot.$reldir;
1277 $ok = 0;
1278
1279 // We will loop on xxx/, xxx/tables/, xxx/data/
1280 $listofsubdir = array('', 'tables/', 'data/');
1281 if ($this->db->type == 'pgsql') {
1282 $listofsubdir[] = '../pgsql/functions/';
1283 }
1284
1285 foreach ($listofsubdir as $subdir) {
1286 $dir = $dirsql.$subdir;
1287
1288 $handle = @opendir($dir); // Dir may not exists
1289 if (is_resource($handle)) {
1290 $dirfound++;
1291
1292 // Run llx_mytable.sql files, then llx_mytable_*.sql
1293 $files = array();
1294 while (($file = readdir($handle)) !== false) {
1295 $files[] = $file;
1296 }
1297 sort($files);
1298 foreach ($files as $file) {
1299 if ($onlywithsuffix) {
1300 if (!preg_match('/\-'.preg_quote($onlywithsuffix, '/').'\./i', $file)) {
1301 //print 'File '.$file.' does not match suffix '.$onlywithsuffix.' so it is discarded<br>'."\n";
1302 continue;
1303 } else {
1304 //print 'File '.$file.' match suffix '.$onlywithsuffix.' so we keep it<br>'."\n";
1305 }
1306 }
1307 if (preg_match('/\.sql$/i', $file) && !preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 4) == 'llx_') {
1308 $result = run_sql($dir.$file, !getDolGlobalString('MAIN_DISPLAY_SQL_INSTALL_LOG') ? 1 : 0, 0, 1);
1309 if ($result <= 0) {
1310 $error++;
1311 }
1312 }
1313 }
1314
1315 rewinddir($handle);
1316
1317 // Run llx_mytable.key.sql files (Must be done after llx_mytable.sql) then then llx_mytable_*.key.sql
1318 $files = array();
1319 while (($file = readdir($handle)) !== false) {
1320 $files[] = $file;
1321 }
1322 sort($files);
1323 foreach ($files as $file) {
1324 if ($onlywithsuffix) {
1325 if (!preg_match('/\-'.preg_quote($onlywithsuffix, '/').'\./i', $file)) {
1326 //print 'File '.$file.' does not match suffix '.$onlywithsuffix.' so it is discarded<br>'."\n";
1327 continue;
1328 } else {
1329 //print 'File '.$file.' match suffix '.$onlywithsuffix.' so we keep it<br>'."\n";
1330 }
1331 }
1332 if (preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 4) == 'llx_') {
1333 $result = run_sql($dir.$file, !getDolGlobalString('MAIN_DISPLAY_SQL_INSTALL_LOG') ? 1 : 0, 0, 1);
1334 if ($result <= 0) {
1335 $error++;
1336 }
1337 }
1338 }
1339
1340 rewinddir($handle);
1341
1342 // Run functions-xxx.sql files (Must be done after llx_mytable.key.sql)
1343 $files = array();
1344 while (($file = readdir($handle)) !== false) {
1345 $files[] = $file;
1346 }
1347 sort($files);
1348 foreach ($files as $file) {
1349 if ($onlywithsuffix) {
1350 if (!preg_match('/\-'.preg_quote($onlywithsuffix, '/').'\./i', $file)) {
1351 //print 'File '.$file.' does not match suffix '.$onlywithsuffix.' so it is discarded<br>'."\n";
1352 continue;
1353 } else {
1354 //print 'File '.$file.' match suffix '.$onlywithsuffix.' so we keep it<br>'."\n";
1355 }
1356 }
1357 if (preg_match('/\.sql$/i', $file) && !preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 9) == 'functions') {
1358 $result = run_sql($dir.$file, !getDolGlobalString('MAIN_DISPLAY_SQL_INSTALL_LOG') ? 1 : 0, 0, 1);
1359 if ($result <= 0) {
1360 $error++;
1361 }
1362 }
1363 }
1364
1365 rewinddir($handle);
1366
1367 // Run data_xxx.sql files (Must be done after llx_mytable.key.sql)
1368 $files = array();
1369 while (($file = readdir($handle)) !== false) {
1370 $files[] = $file;
1371 }
1372 sort($files);
1373 foreach ($files as $file) {
1374 if ($onlywithsuffix) {
1375 if (!preg_match('/\-'.preg_quote($onlywithsuffix, '/').'\./i', $file)) {
1376 //print 'File '.$file.' does not match suffix '.$onlywithsuffix.' so it is discarded<br>'."\n";
1377 continue;
1378 } else {
1379 //print 'File '.$file.' match suffix '.$onlywithsuffix.' so we keep it<br>'."\n";
1380 }
1381 }
1382 if (preg_match('/\.sql$/i', $file) && !preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 4) == 'data') {
1383 $result = run_sql($dir.$file, !getDolGlobalString('MAIN_DISPLAY_SQL_INSTALL_LOG') ? 1 : 0, 0, 1);
1384 if ($result <= 0) {
1385 $error++;
1386 }
1387 }
1388 }
1389
1390 rewinddir($handle);
1391
1392 // Run update_xxx.sql files
1393 $files = array();
1394 while (($file = readdir($handle)) !== false) {
1395 $files[] = $file;
1396 }
1397 sort($files);
1398 foreach ($files as $file) {
1399 if ($onlywithsuffix) {
1400 if (!preg_match('/\-'.preg_quote($onlywithsuffix, '/').'\./i', $file)) {
1401 //print 'File '.$file.' does not match suffix '.$onlywithsuffix.' so it is discarded<br>'."\n";
1402 continue;
1403 } else {
1404 //print 'File '.$file.' match suffix '.$onlywithsuffix.' so we keep it<br>'."\n";
1405 }
1406 }
1407 if (preg_match('/\.sql$/i', $file) && !preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 6) == 'update') {
1408 $result = run_sql($dir.$file, !getDolGlobalString('MAIN_DISPLAY_SQL_INSTALL_LOG') ? 1 : 0, 0, 1);
1409 if ($result <= 0) {
1410 $error++;
1411 }
1412 }
1413 }
1414
1415 closedir($handle);
1416 }
1417 }
1418
1419 if ($error == 0) {
1420 $ok = 1;
1421 }
1422 }
1423 }
1424
1425 if (!$dirfound) {
1426 dol_syslog("A module wants to load sql files from ".$reldir." but this directory was not found.", LOG_WARNING);
1427 }
1428 return $ok;
1429 }
1430
1431
1432 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1440 public function insert_boxes($option = '')
1441 {
1442 // phpcs:enable
1443 include_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php';
1444
1445 global $conf;
1446
1447 $err = 0;
1448
1449 if (is_array($this->boxes)) {
1450 dol_syslog(get_class($this)."::insert_boxes", LOG_DEBUG);
1451
1452 $pos_name = InfoBox::getListOfPagesForBoxes();
1453
1454 foreach ($this->boxes as $key => $value) {
1455 $file = isset($this->boxes[$key]['file']) ? $this->boxes[$key]['file'] : '';
1456 $note = isset($this->boxes[$key]['note']) ? $this->boxes[$key]['note'] : '';
1457 $enabledbydefaulton = isset($this->boxes[$key]['enabledbydefaulton']) ? $this->boxes[$key]['enabledbydefaulton'] : 'Home';
1458
1459 if (empty($file)) {
1460 $file = isset($this->boxes[$key][1]) ? $this->boxes[$key][1] : ''; // For backward compatibility
1461 }
1462 if (empty($note)) {
1463 $note = isset($this->boxes[$key][2]) ? $this->boxes[$key][2] : ''; // For backward compatibility
1464 }
1465
1466 // Search if boxes def already present
1467 $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."boxes_def";
1468 $sql .= " WHERE file = '".$this->db->escape($file)."'";
1469 $sql .= " AND entity = ".$conf->entity;
1470 if ($note) {
1471 $sql .= " AND note ='".$this->db->escape($note)."'";
1472 }
1473
1474 $result = $this->db->query($sql);
1475 if ($result) {
1476 $obj = $this->db->fetch_object($result);
1477 if ($obj->nb == 0) {
1478 $this->db->begin();
1479
1480 if (!$err) {
1481 $sql = "INSERT INTO ".MAIN_DB_PREFIX."boxes_def (file, entity, note)";
1482 $sql .= " VALUES ('".$this->db->escape($file)."', ";
1483 $sql .= $conf->entity.", ";
1484 $sql .= $note ? "'".$this->db->escape($note)."'" : "null";
1485 $sql .= ")";
1486
1487 dol_syslog(get_class($this)."::insert_boxes", LOG_DEBUG);
1488 $resql = $this->db->query($sql);
1489 if (!$resql) {
1490 $err++;
1491 }
1492 }
1493 if (!$err && !preg_match('/newboxdefonly/', $option)) {
1494 $lastid = $this->db->last_insert_id(MAIN_DB_PREFIX."boxes_def", "rowid");
1495
1496 foreach ($pos_name as $key2 => $val2) {
1497 //print 'key2='.$key2.'-val2='.$val2."<br>\n";
1498 if ($enabledbydefaulton && $val2 != $enabledbydefaulton) {
1499 continue; // Not enabled by default onto this page.
1500 }
1501
1502 $sql = "INSERT INTO ".MAIN_DB_PREFIX."boxes (box_id, position, box_order, fk_user, entity)";
1503 $sql .= " VALUES (".((int) $lastid).", ".((int) $key2).", '0', 0, ".((int) $conf->entity).")";
1504
1505 dol_syslog(get_class($this)."::insert_boxes onto page ".$key2."=".$val2, LOG_DEBUG);
1506 $resql = $this->db->query($sql);
1507 if (!$resql) {
1508 $err++;
1509 }
1510 }
1511 }
1512
1513 if (!$err) {
1514 $this->db->commit();
1515 } else {
1516 $this->error = $this->db->lasterror();
1517 $this->db->rollback();
1518 }
1519 }
1520 // else box already registered into database
1521 } else {
1522 $this->error = $this->db->lasterror();
1523 $err++;
1524 }
1525 }
1526 }
1527
1528 return $err;
1529 }
1530
1531
1532 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1538 public function delete_boxes()
1539 {
1540 // phpcs:enable
1541 global $conf;
1542
1543 $err = 0;
1544
1545 if (is_array($this->boxes)) {
1546 foreach ($this->boxes as $key => $value) {
1547 //$titre = $this->boxes[$key][0];
1548 if (empty($this->boxes[$key]['file'])) {
1549 $file = isset($this->boxes[$key][1]) ? $this->boxes[$key][1] : ''; // For backward compatibility
1550 } else {
1551 $file = $this->boxes[$key]['file'];
1552 }
1553
1554 //$note = $this->boxes[$key][2];
1555
1556 // TODO If the box is also included by another module and the other module is still on, we should not remove it.
1557 // For the moment, we manage this with hard coded exception
1558 //print "Remove box ".$file.'<br>';
1559 if ($file == 'box_graph_product_distribution.php') {
1560 if (isModEnabled("product") || isModEnabled("service")) {
1561 dol_syslog("We discard deleting module ".$file." because another module still active requires it.");
1562 continue;
1563 }
1564 }
1565
1566 if ($this->db->type == 'sqlite3') {
1567 // sqlite doesn't support "USING" syntax.
1568 // TODO: remove this dependency.
1569 $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes ";
1570 $sql .= "WHERE ".MAIN_DB_PREFIX."boxes.box_id IN (";
1571 $sql .= "SELECT ".MAIN_DB_PREFIX."boxes_def.rowid ";
1572 $sql .= "FROM ".MAIN_DB_PREFIX."boxes_def ";
1573 $sql .= "WHERE ".MAIN_DB_PREFIX."boxes_def.file = '".$this->db->escape($file)."') ";
1574 $sql .= "AND ".MAIN_DB_PREFIX."boxes.entity = ".$conf->entity;
1575 } else {
1576 $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes";
1577 $sql .= " USING ".MAIN_DB_PREFIX."boxes, ".MAIN_DB_PREFIX."boxes_def";
1578 $sql .= " WHERE ".MAIN_DB_PREFIX."boxes.box_id = ".MAIN_DB_PREFIX."boxes_def.rowid";
1579 $sql .= " AND ".MAIN_DB_PREFIX."boxes_def.file = '".$this->db->escape($file)."'";
1580 $sql .= " AND ".MAIN_DB_PREFIX."boxes.entity = ".$conf->entity;
1581 }
1582
1583 dol_syslog(get_class($this)."::delete_boxes", LOG_DEBUG);
1584 $resql = $this->db->query($sql);
1585 if (!$resql) {
1586 $this->error = $this->db->lasterror();
1587 $err++;
1588 }
1589
1590 $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes_def";
1591 $sql .= " WHERE file = '".$this->db->escape($file)."'";
1592 $sql .= " AND entity = ".$conf->entity; // Do not use getEntity here, we want to delete only in current company
1593
1594 dol_syslog(get_class($this)."::delete_boxes", LOG_DEBUG);
1595 $resql = $this->db->query($sql);
1596 if (!$resql) {
1597 $this->error = $this->db->lasterror();
1598 $err++;
1599 }
1600 }
1601 }
1602
1603 return $err;
1604 }
1605
1606 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1612 public function insert_cronjobs()
1613 {
1614 // phpcs:enable
1615 include_once DOL_DOCUMENT_ROOT . '/core/class/infobox.class.php';
1616 include_once DOL_DOCUMENT_ROOT . '/cron/class/cronjob.class.php';
1617 include_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php';
1618
1619 global $conf, $user;
1620
1621 if (empty($user)) {
1622 $user = new User($this->db);
1623 }
1624
1625 $err = 0;
1626
1627 if (is_array($this->cronjobs)) {
1628 dol_syslog(get_class($this) . "::insert_cronjobs", LOG_DEBUG);
1629
1630 foreach ($this->cronjobs as $key => $value) {
1631 $now = dol_now();
1632
1633 $entity = isset($value['entity']) ? $value['entity'] : $conf->entity;
1634 $label = isset($value['label']) ? $value['label'] : '';
1635 $jobtype = isset($value['jobtype']) ? $value['jobtype'] : '';
1636 $classesname = isset($value['class']) ? $value['class'] : '';
1637 $objectname = isset($value['objectname']) ? $value['objectname'] : '';
1638 $methodename = isset($value['method']) ? $value['method'] : '';
1639 $command = isset($value['command']) ? $value['command'] : '';
1640 $params = isset($value['parameters']) ? $value['parameters'] : '';
1641 $md5params = isset($value['md5params']) ? $value['md5params'] : '';
1642 $comment = isset($value['comment']) ? $value['comment'] : '';
1643 $frequency = isset($value['frequency']) ? $value['frequency'] : '';
1644 $unitfrequency = isset($value['unitfrequency']) ? $value['unitfrequency'] : '';
1645 $priority = isset($value['priority']) ? $value['priority'] : '';
1646 $datestart = isset($value['datestart']) ? $value['datestart'] : '';
1647 $dateend = isset($value['dateend']) ? $value['dateend'] : '';
1648 $datenextrun = isset($value['datenextrun']) ? $value['datenextrun'] : $now;
1649 $status = isset($value['status']) ? $value['status'] : '';
1650 $maxrun = isset($value['maxrun']) ? $value['maxrun'] : 0;
1651 $libname = isset($value['libname']) ? $value['libname'] : '';
1652 $test = isset($value['test']) ? $value['test'] : ''; // Line must be enabled or not (so visible or not)
1653
1654 // Search if cron entry already present
1655 $sql = "SELECT count(*) as nb FROM " . MAIN_DB_PREFIX . "cronjob";
1656 //$sql .= " WHERE module_name = '" . $this->db->escape(empty($this->rights_class) ? strtolower($this->name) : $this->rights_class) . "'";
1657 $sql .= " WHERE label = '".$this->db->escape($label)."'";
1658 /* unique key is on label,entity so no need for this test
1659 if ($classesname) {
1660 $sql .= " AND classesname = '" . $this->db->escape($classesname) . "'";
1661 }
1662 if ($objectname) {
1663 $sql .= " AND objectname = '" . $this->db->escape($objectname) . "'";
1664 }
1665 if ($methodename) {
1666 $sql .= " AND methodename = '" . $this->db->escape($methodename) . "'";
1667 }
1668 if ($command) {
1669 $sql .= " AND command = '" . $this->db->escape($command) . "'";
1670 }
1671 if ($params) {
1672 $sql .= " AND params = '" . $this->db->escape($params) . "'";
1673 }
1674 */
1675 $sql .= " AND entity = " . ((int) $entity); // Must be exact entity
1676
1677 $result = $this->db->query($sql);
1678 if (!$result) {
1679 $this->error = $this->db->lasterror();
1680 $err++;
1681 break;
1682 // else box already registered into database
1683 }
1684
1685 $obj = $this->db->fetch_object($result);
1686 if ($obj->nb > 0) {
1687 continue;
1688 }
1689
1690 $cronjob = new Cronjob($this->db);
1691
1692 $cronjob->entity = $entity;
1693 $cronjob->label = $label;
1694 $cronjob->jobtype = $jobtype;
1695 $cronjob->classesname = $classesname;
1696 $cronjob->objectname = $objectname;
1697 $cronjob->methodename = $methodename;
1698 $cronjob->command = $command;
1699 $cronjob->params = $params;
1700 $cronjob->md5params = $md5params;
1701 $cronjob->note_private = $comment;
1702 $cronjob->frequency = $frequency;
1703 $cronjob->unitfrequency = $unitfrequency;
1704 $cronjob->priority = $priority;
1705 $cronjob->datestart = $datestart;
1706 $cronjob->dateend = $dateend;
1707 $cronjob->datenextrun = $datenextrun;
1708 $cronjob->maxrun = $maxrun;
1709 $cronjob->status = $status;
1710 $cronjob->test = $test;
1711 $cronjob->libname = $libname;
1712 $cronjob->module_name = empty($this->rights_class) ? strtolower($this->name) : $this->rights_class;
1713
1714 $retCreate = $cronjob->create($user);
1715
1716 if ($retCreate < 0) {
1717 $this->error = implode("\n", array_merge([$cronjob->error], $cronjob->errors));
1718 return -1;
1719 }
1720 }
1721 }
1722
1723 return $err;
1724 }
1725
1726 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1732 public function delete_cronjobs()
1733 {
1734 // phpcs:enable
1735 global $conf;
1736
1737 $err = 0;
1738
1739 if (is_array($this->cronjobs)) {
1740 $sql = "DELETE FROM ".MAIN_DB_PREFIX."cronjob";
1741 $sql .= " WHERE module_name = '".$this->db->escape(empty($this->rights_class) ? strtolower($this->name) : $this->rights_class)."'";
1742 $sql .= " AND entity = ".$conf->entity;
1743 $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.
1744 // 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.
1745
1746 dol_syslog(get_class($this)."::delete_cronjobs", LOG_DEBUG);
1747 $resql = $this->db->query($sql);
1748 if (!$resql) {
1749 $this->error = $this->db->lasterror();
1750 $err++;
1751 }
1752 }
1753
1754 return $err;
1755 }
1756
1757 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1763 public function delete_tabs()
1764 {
1765 // phpcs:enable
1766 global $conf;
1767
1768 $err = 0;
1769
1770 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
1771 $sql .= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_TABS_%'";
1772 $sql .= " AND entity = ".((int) $conf->entity);
1773
1774 dol_syslog(get_class($this)."::delete_tabs", LOG_DEBUG);
1775 if (!$this->db->query($sql)) {
1776 $this->error = $this->db->lasterror();
1777 $err++;
1778 }
1779
1780 return $err;
1781 }
1782
1783 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1789 public function insert_tabs()
1790 {
1791 // phpcs:enable
1792 global $conf;
1793
1794 $err = 0;
1795
1796 if (!empty($this->tabs)) {
1797 dol_syslog(get_class($this)."::insert_tabs", LOG_DEBUG);
1798
1799 $i = 0;
1800 foreach ($this->tabs as $key => $value) {
1801 if (is_array($value) && count($value) == 0) {
1802 continue; // Discard empty arrays
1803 }
1804
1805 $entity = $conf->entity;
1806 $newvalue = $value;
1807
1808 if (is_array($value)) {
1809 $newvalue = $value['data'];
1810 if (isset($value['entity'])) {
1811 $entity = $value['entity'];
1812 }
1813 }
1814
1815 if ($newvalue) {
1816 $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (";
1817 $sql .= "name";
1818 $sql .= ", type";
1819 $sql .= ", value";
1820 $sql .= ", note";
1821 $sql .= ", visible";
1822 $sql .= ", entity";
1823 $sql .= ")";
1824 $sql .= " VALUES (";
1825 $sql .= $this->db->encrypt($this->const_name."_TABS_".$i);
1826 $sql .= ", 'chaine'";
1827 $sql .= ", ".$this->db->encrypt($newvalue);
1828 $sql .= ", null";
1829 $sql .= ", '0'";
1830 $sql .= ", ".((int) $entity);
1831 $sql .= ")";
1832
1833 $resql = $this->db->query($sql);
1834 if (!$resql) {
1835 dol_syslog($this->db->lasterror(), LOG_ERR);
1836 if ($this->db->lasterrno() != 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1837 $this->error = $this->db->lasterror();
1838 $this->errors[] = $this->db->lasterror();
1839 $err++;
1840 break;
1841 }
1842 }
1843 }
1844 $i++;
1845 }
1846 }
1847 return $err;
1848 }
1849
1850 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1856 public function insert_const()
1857 {
1858 // phpcs:enable
1859 global $conf;
1860
1861 $err = 0;
1862
1863 if (empty($this->const)) {
1864 return 0;
1865 }
1866
1867 dol_syslog(__METHOD__, LOG_DEBUG);
1868
1869 foreach ($this->const as $key => $value) {
1870 $name = $this->const[$key][0];
1871 $type = $this->const[$key][1];
1872 $val = $this->const[$key][2];
1873 $note = isset($this->const[$key][3]) ? $this->const[$key][3] : '';
1874 $visible = isset($this->const[$key][4]) ? $this->const[$key][4] : 0;
1875 $entity = (!empty($this->const[$key][5]) && $this->const[$key][5] != 'current') ? 0 : $conf->entity;
1876
1877 // Clean
1878 if (empty($visible)) {
1879 $visible = '0';
1880 }
1881 if (empty($val) && $val != '0') {
1882 $val = '';
1883 }
1884
1885 if (!empty($name)) {
1886 $sql = "SELECT count(*) as nb";
1887 $sql .= " FROM ".MAIN_DB_PREFIX."const";
1888 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($name)."'";
1889 $sql .= " AND entity = ".((int) $entity);
1890
1891 $result = $this->db->query($sql);
1892 if ($result) {
1893 $row = $this->db->fetch_row($result);
1894
1895 if ($row[0] == 0) { // If not found
1896 $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name, type, value, note, visible, entity)";
1897 $sql .= " VALUES (";
1898 $sql .= $this->db->encrypt($name);
1899 $sql .= ", '".$this->db->escape($type)."'";
1900 $sql .= ", ".(($val != '') ? $this->db->encrypt($val) : "''");
1901 $sql .= ", ".($note ? "'".$this->db->escape($note)."'" : "null");
1902 $sql .= ", '".$this->db->escape($visible)."'";
1903 $sql .= ", ".((int) $entity);
1904 $sql .= ")";
1905
1906 if (!$this->db->query($sql)) {
1907 $err++;
1908 } else {
1909 // Set also the variable in running environment
1910 $conf->global->$name = $val;
1911 }
1912 } else {
1913 dol_syslog(__METHOD__." constant '".$name."' already exists", LOG_DEBUG);
1914 }
1915 } else {
1916 $err++;
1917 }
1918 }
1919 }
1920
1921 return $err;
1922 }
1923
1924 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1930 public function delete_const()
1931 {
1932 // phpcs:enable
1933 global $conf;
1934
1935 $err = 0;
1936
1937 if (empty($this->const)) {
1938 return 0;
1939 }
1940
1941 foreach ($this->const as $key => $value) {
1942 $name = $this->const[$key][0];
1943 $deleteonunactive = (!empty($this->const[$key][6])) ? 1 : 0;
1944
1945 if ($deleteonunactive) {
1946 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
1947 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($name)."'";
1948 $sql .= " AND entity in (0, ".$conf->entity.")";
1949 dol_syslog(get_class($this)."::delete_const", LOG_DEBUG);
1950 if (!$this->db->query($sql)) {
1951 $this->error = $this->db->lasterror();
1952 $err++;
1953 }
1954 }
1955 }
1956
1957 return $err;
1958 }
1959
1960 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1969 public function insert_permissions($reinitadminperms = 0, $force_entity = null, $notrigger = 0)
1970 {
1971 // phpcs:enable
1972 global $conf, $user;
1973
1974 $err = 0;
1975 $entity = (!empty($force_entity) ? $force_entity : $conf->entity);
1976
1977 dol_syslog(get_class($this)."::insert_permissions", LOG_DEBUG);
1978
1979 // Test if module is activated
1980 $sql_del = "SELECT ".$this->db->decrypt('value')." as value";
1981 $sql_del .= " FROM ".MAIN_DB_PREFIX."const";
1982 $sql_del .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
1983 $sql_del .= " AND entity IN (0,".((int) $entity).")";
1984
1985 $resql = $this->db->query($sql_del);
1986
1987 if ($resql) {
1988 $obj = $this->db->fetch_object($resql);
1989
1990 if ($obj !== null && !empty($obj->value) && !empty($this->rights)) {
1991 include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1992
1993 // TODO rights parameters with integer indexes are deprecated
1994 // $this->rights[$key][0] = $this->rights[$key][self::KEY_ID]
1995 // $this->rights[$key][1] = $this->rights[$key][self::KEY_LABEL]
1996 // $this->rights[$key][3] = $this->rights[$key][self::KEY_DEFAULT]
1997 // $this->rights[$key][4] = $this->rights[$key][self::KEY_FIRST_LEVEL]
1998 // $this->rights[$key][5] = $this->rights[$key][self::KEY_SECOND_LEVEL]
1999
2000 // new parameters
2001 // $this->rights[$key][self::KEY_MODULE] // possibility to define user right for an another module (default: current module name)
2002 // $this->rights[$key][self::KEY_ENABLED] // condition to show or hide a user right (default: 1) (eg isModEnabled('anothermodule'))
2003
2004 // If the module is active
2005 foreach ($this->rights as $key => $value) {
2006 $r_id = $this->rights[$key][self::KEY_ID]; // permission id in llx_rights_def (not unique because primary key is couple id-entity)
2007 $r_label = $this->rights[$key][self::KEY_LABEL];
2008 $r_type = $this->rights[$key][self::KEY_TYPE] ?? 'w'; // TODO deprecated
2009 $r_default = $this->rights[$key][self::KEY_DEFAULT] ?? 0;
2010 $r_perms = $this->rights[$key][self::KEY_FIRST_LEVEL] ?? '';
2011 $r_subperms = $this->rights[$key][self::KEY_SECOND_LEVEL] ?? '';
2012
2013 // KEY_FIRST_LEVEL (perms) must not be empty
2014 if (empty($r_perms)) {
2015 continue;
2016 }
2017
2018 // name of module (default: current module name)
2019 $r_module = (empty($this->rights_class) ? strtolower($this->name) : $this->rights_class);
2020
2021 // name of the module from which the right comes (default: empty means same module the permission is for)
2022 $r_module_origin = '';
2023
2024 if (isset($this->rights[$key][self::KEY_MODULE])) {
2025 // name of the module to which the right must be applied
2026 $r_module = $this->rights[$key][self::KEY_MODULE];
2027 // name of the module from which the right comes
2028 $r_module_origin = (empty($this->rights_class) ? strtolower($this->name) : $this->rights_class);
2029 }
2030
2031 // condition to show or hide a user right (default: 1) (eg isModEnabled('anothermodule') or ($conf->global->MAIN_FEATURES_LEVEL > 0) or etc..)
2032 $r_enabled = $this->rights[$key][self::KEY_ENABLED] ?? '1';
2033
2034 // Search if perm already present
2035 $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."rights_def";
2036 $sql .= " WHERE entity = ".((int) $entity);
2037 $sql .= " AND id = ".((int) $r_id);
2038
2039 $resqlselect = $this->db->query($sql);
2040 if ($resqlselect) {
2041 $objcount = $this->db->fetch_object($resqlselect);
2042 if ($objcount && $objcount->nb == 0) {
2043 $sql = "INSERT INTO ".MAIN_DB_PREFIX."rights_def (";
2044 $sql .= "id";
2045 $sql .= ", entity";
2046 $sql .= ", libelle";
2047 $sql .= ", module";
2048 $sql .= ", module_origin";
2049 $sql .= ", type"; // TODO deprecated
2050 $sql .= ", bydefault";
2051 $sql .= ", perms";
2052 $sql .= ", subperms";
2053 $sql .= ", enabled";
2054 $sql .= ") VALUES (";
2055 $sql .= ((int) $r_id);
2056 $sql .= ", ".((int) $entity);
2057 $sql .= ", '".$this->db->escape($r_label)."'";
2058 $sql .= ", '".$this->db->escape($r_module)."'";
2059 $sql .= ", '".$this->db->escape($r_module_origin)."'";
2060 $sql .= ", '".$this->db->escape($r_type)."'"; // TODO deprecated
2061 $sql .= ", ".((int) $r_default);
2062 $sql .= ", '".$this->db->escape($r_perms)."'";
2063 $sql .= ", '".$this->db->escape($r_subperms)."'";
2064 $sql .= ", '".$this->db->escape($r_enabled)."'";
2065 $sql .= ")";
2066
2067 $resqlinsert = $this->db->query($sql, 1);
2068
2069 if (!$resqlinsert) {
2070 if ($this->db->errno() != "DB_ERROR_RECORD_ALREADY_EXISTS") {
2071 $this->error = $this->db->lasterror();
2072 $err++;
2073 break;
2074 } else {
2075 dol_syslog(get_class($this)."::insert_permissions record already exists", LOG_INFO);
2076 }
2077 }
2078
2079 $this->db->free($resqlinsert);
2080 }
2081
2082 $this->db->free($resqlselect);
2083 }
2084
2085 // If we want to init permissions on admin users
2086 if (!empty($reinitadminperms)) {
2087 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."user WHERE admin = 1";
2088 dol_syslog(get_class($this)."::insert_permissions Search all admin users", LOG_DEBUG);
2089
2090 $resqlseladmin = $this->db->query($sql, 1);
2091
2092 if ($resqlseladmin) {
2093 $num = $this->db->num_rows($resqlseladmin);
2094 $i = 0;
2095 while ($i < $num) {
2096 $obj2 = $this->db->fetch_object($resqlseladmin);
2097 dol_syslog(get_class($this)."::insert_permissions Add permission id ".$r_id." to user id=".$obj2->rowid);
2098
2099 $tmpuser = new User($this->db);
2100 $result = $tmpuser->fetch($obj2->rowid);
2101 if ($result > 0) {
2102 $tmpuser->addrights($r_id, '', '', 0, 1);
2103 } else {
2104 dol_syslog(get_class($this)."::insert_permissions Failed to add the permission to user because fetch return an error", LOG_ERR);
2105 }
2106 $i++;
2107 }
2108 } else {
2109 dol_print_error($this->db);
2110 }
2111 }
2112 }
2113
2114 if (!empty($reinitadminperms) && !empty($user->admin)) { // Reload permission for current user if defined
2115 // We reload permissions
2116 $user->clearrights();
2117 $user->loadRights();
2118 }
2119 }
2120 $this->db->free($resql);
2121 } else {
2122 $this->error = $this->db->lasterror();
2123 $err++;
2124 }
2125
2126 return $err;
2127 }
2128
2129
2130 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2136 public function delete_permissions()
2137 {
2138 // phpcs:enable
2139 global $conf;
2140
2141 $err = 0;
2142
2143 $module = empty($this->rights_class) ? strtolower($this->name) : $this->rights_class;
2144
2145 $sql = "DELETE FROM ".MAIN_DB_PREFIX."rights_def";
2146 $sql .= " WHERE (module = '".$this->db->escape($module)."' OR module_origin = '".$this->db->escape($module)."')";
2147
2148 // Delete all entities if core module
2149 if (empty($this->core_enabled)) {
2150 $sql .= " AND entity = ".((int) $conf->entity);
2151 }
2152
2153 dol_syslog(get_class($this)."::delete_permissions", LOG_DEBUG);
2154 if (!$this->db->query($sql)) {
2155 $this->error = $this->db->lasterror();
2156 $err++;
2157 }
2158
2159 return $err;
2160 }
2161
2162
2163 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2169 public function insert_menus()
2170 {
2171 // phpcs:enable
2172 global $conf, $user;
2173
2174 if (!is_array($this->menu) || empty($this->menu)) {
2175 return 0;
2176 }
2177
2178 include_once DOL_DOCUMENT_ROOT.'/core/class/menubase.class.php';
2179
2180 dol_syslog(get_class($this)."::insert_menus", LOG_DEBUG);
2181
2182 $err = 0;
2183
2184 // Common module
2185 $entity = ((!empty($this->always_enabled) || !empty($this->core_enabled)) ? 0 : $conf->entity);
2186
2187 $this->db->begin();
2188
2189 foreach ($this->menu as $key => $value) {
2190 $menu = new Menubase($this->db);
2191 $menu->menu_handler = 'all';
2192
2193 //$menu->module=strtolower($this->name); TODO When right_class will be same than module name
2194 $menu->module = (empty($this->rights_class) ? strtolower($this->name) : $this->rights_class);
2195
2196 if (!$this->menu[$key]['fk_menu']) {
2197 $menu->fk_menu = 0;
2198 } else {
2199 $foundparent = 0;
2200 $fk_parent = $this->menu[$key]['fk_menu'];
2201 $reg = array();
2202 if (preg_match('/^r=/', $fk_parent)) { // old deprecated method
2203 $fk_parent = str_replace('r=', '', $fk_parent);
2204 if (isset($this->menu[$fk_parent]['rowid'])) {
2205 $menu->fk_menu = $this->menu[$fk_parent]['rowid'];
2206 $foundparent = 1;
2207 }
2208 } elseif (preg_match('/^fk_mainmenu=([a-zA-Z0-9_]+),fk_leftmenu=([a-zA-Z0-9_]+)$/', $fk_parent, $reg)) {
2209 $menu->fk_menu = -1;
2210 $menu->fk_mainmenu = $reg[1];
2211 $menu->fk_leftmenu = $reg[2];
2212 $foundparent = 1;
2213 } elseif (preg_match('/^fk_mainmenu=([a-zA-Z0-9_]+)$/', $fk_parent, $reg)) {
2214 $menu->fk_menu = -1;
2215 $menu->fk_mainmenu = $reg[1];
2216 $menu->fk_leftmenu = '';
2217 $foundparent = 1;
2218 }
2219 if (!$foundparent) {
2220 $this->error = "ErrorBadDefinitionOfMenuArrayInModuleDescriptor";
2221 dol_syslog(get_class($this)."::insert_menus ".$this->error." ".$this->menu[$key]['fk_menu'], LOG_ERR);
2222 $err++;
2223 }
2224 }
2225 $menu->type = $this->menu[$key]['type'];
2226 $menu->mainmenu = isset($this->menu[$key]['mainmenu']) ? $this->menu[$key]['mainmenu'] : (isset($menu->fk_mainmenu) ? $menu->fk_mainmenu : '');
2227 $menu->leftmenu = isset($this->menu[$key]['leftmenu']) ? $this->menu[$key]['leftmenu'] : '';
2228 $menu->title = $this->menu[$key]['titre'];
2229 $menu->prefix = isset($this->menu[$key]['prefix']) ? $this->menu[$key]['prefix'] : '';
2230 $menu->url = $this->menu[$key]['url'];
2231 $menu->langs = isset($this->menu[$key]['langs']) ? $this->menu[$key]['langs'] : '';
2232 $menu->position = $this->menu[$key]['position'];
2233 $menu->perms = $this->menu[$key]['perms'];
2234 $menu->target = isset($this->menu[$key]['target']) ? $this->menu[$key]['target'] : '';
2235 $menu->user = $this->menu[$key]['user'];
2236 $menu->enabled = isset($this->menu[$key]['enabled']) ? $this->menu[$key]['enabled'] : 0;
2237 $menu->position = $this->menu[$key]['position'];
2238 $menu->entity = $entity;
2239
2240 if (!$err) {
2241 $result = $menu->create($user); // Save menu entry into table llx_menu
2242 if ($result > 0) {
2243 $this->menu[$key]['rowid'] = $result;
2244 } else {
2245 $this->error = $menu->error;
2246 dol_syslog(get_class($this).'::insert_menus result='.$result." ".$this->error, LOG_ERR);
2247 $err++;
2248 break;
2249 }
2250 }
2251 }
2252
2253 if (!$err) {
2254 $this->db->commit();
2255 } else {
2256 dol_syslog(get_class($this)."::insert_menus ".$this->error, LOG_ERR);
2257 $this->db->rollback();
2258 }
2259
2260 return $err;
2261 }
2262
2263
2264 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2270 public function delete_menus()
2271 {
2272 // phpcs:enable
2273 global $conf;
2274
2275 $err = 0;
2276
2277 //$module=strtolower($this->name); TODO When right_class will be same than module name
2278 $module = empty($this->rights_class) ? strtolower($this->name) : $this->rights_class;
2279
2280 $sql = "DELETE FROM ".MAIN_DB_PREFIX."menu";
2281 $sql .= " WHERE module = '".$this->db->escape($module)."'";
2282 $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'
2283 $sql .= " AND entity IN (0, ".$conf->entity.")";
2284
2285 dol_syslog(get_class($this)."::delete_menus", LOG_DEBUG);
2286 $resql = $this->db->query($sql);
2287 if (!$resql) {
2288 $this->error = $this->db->lasterror();
2289 $err++;
2290 }
2291
2292 return $err;
2293 }
2294
2295 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2301 public function create_dirs()
2302 {
2303 // phpcs:enable
2304 global $langs, $conf;
2305
2306 $err = 0;
2307 $name = '';
2308
2309 if (isset($this->dirs) && is_array($this->dirs)) {
2310 foreach ($this->dirs as $key => $value) {
2311 $addtodatabase = 0;
2312
2313 if (!is_array($value)) {
2314 $dir = $value; // Default simple mode
2315 } else {
2316 $constname = $this->const_name."_DIR_";
2317 $dir = $this->dirs[$key][1];
2318 $addtodatabase = empty($this->dirs[$key][2]) ? '' : $this->dirs[$key][2]; // Create constante in llx_const
2319 $subname = empty($this->dirs[$key][3]) ? '' : strtoupper($this->dirs[$key][3]); // Add submodule name (ex: $conf->module->submodule->dir_output)
2320 $forcename = empty($this->dirs[$key][4]) ? '' : strtoupper($this->dirs[$key][4]); // Change the module name if different
2321
2322 if (!empty($forcename)) {
2323 $constname = 'MAIN_MODULE_'.$forcename."_DIR_";
2324 }
2325 if (!empty($subname)) {
2326 $constname = $constname.$subname."_";
2327 }
2328
2329 $name = $constname.strtoupper($this->dirs[$key][0]);
2330 }
2331
2332 // Define directory full path ($dir must start with "/")
2333 if (!getDolGlobalString('MAIN_MODULE_MULTICOMPANY') || $conf->entity == 1) {
2334 $fulldir = DOL_DATA_ROOT.$dir;
2335 } else {
2336 $fulldir = DOL_DATA_ROOT."/".$conf->entity.$dir;
2337 }
2338 // Create dir if it does not exists
2339 if (!empty($fulldir) && !file_exists($fulldir)) {
2340 if (dol_mkdir($fulldir, DOL_DATA_ROOT) < 0) {
2341 $this->error = $langs->trans("ErrorCanNotCreateDir", $fulldir);
2342 dol_syslog(get_class($this)."::_init ".$this->error, LOG_ERR);
2343 $err++;
2344 }
2345 }
2346
2347 // Define the constant in database if requested (not the default mode)
2348 if (!empty($addtodatabase) && !empty($name)) {
2349 $result = $this->insert_dirs($name, $dir);
2350 if ($result) {
2351 $err++;
2352 }
2353 }
2354 }
2355 }
2356
2357 return $err;
2358 }
2359
2360
2361 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2370 public function insert_dirs($name, $dir)
2371 {
2372 // phpcs:enable
2373 global $conf;
2374
2375 $err = 0;
2376
2377 $sql = "SELECT count(*)";
2378 $sql .= " FROM ".MAIN_DB_PREFIX."const";
2379 $sql .= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($name)."'";
2380 $sql .= " AND entity = ".$conf->entity;
2381
2382 dol_syslog(get_class($this)."::insert_dirs", LOG_DEBUG);
2383 $result = $this->db->query($sql);
2384 if ($result) {
2385 $row = $this->db->fetch_row($result);
2386
2387 if ($row[0] == 0) {
2388 $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name, type, value, note, visible, entity)";
2389 $sql .= " VALUES (".$this->db->encrypt($name).", 'chaine', ".$this->db->encrypt($dir).", '".$this->db->escape("Directory for module ".$this->name)."', '0', ".((int) $conf->entity).")";
2390
2391 dol_syslog(get_class($this)."::insert_dirs", LOG_DEBUG);
2392 $this->db->query($sql);
2393 }
2394 } else {
2395 $this->error = $this->db->lasterror();
2396 $err++;
2397 }
2398
2399 return $err;
2400 }
2401
2402
2403 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2409 public function delete_dirs()
2410 {
2411 // phpcs:enable
2412 global $conf;
2413
2414 $err = 0;
2415
2416 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
2417 $sql .= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_DIR_%'";
2418 $sql .= " AND entity = ".$conf->entity;
2419
2420 dol_syslog(get_class($this)."::delete_dirs", LOG_DEBUG);
2421 if (!$this->db->query($sql)) {
2422 $this->error = $this->db->lasterror();
2423 $err++;
2424 }
2425
2426 return $err;
2427 }
2428
2429 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2436 public function insert_module_parts()
2437 {
2438 // phpcs:enable
2439 global $conf, $langs;
2440
2441 $error = 0;
2442
2443 if (is_array($this->module_parts)) {
2444 if (empty($this->module_parts['icon']) && !empty($this->picto) && preg_match('/^fa\-/', $this->picto)) {
2445 $this->module_parts['icon'] = $this->picto;
2446 }
2447
2448 foreach ($this->module_parts as $key => $value) {
2449 if (is_array($value) && count($value) == 0) {
2450 continue; // Discard empty arrays
2451 }
2452
2453 // If module brings website templates, we must generate the zip like we do whenenabling the website module
2454 if ($key == 'websitetemplates' && $value == 1) {
2455 $srcroot = dol_buildpath('/'.strtolower($this->name).'/doctemplates/websites');
2456
2457 // Copy templates in dir format (recommended) into zip file
2458 $docs = dol_dir_list($srcroot, 'directories', 0, 'website_.*$');
2459 foreach ($docs as $cursorfile) {
2460 $src = $srcroot.'/'.$cursorfile['name'];
2461 $dest = DOL_DATA_ROOT.'/doctemplates/websites/'.$cursorfile['name'];
2462
2463 dol_delete_file($dest.'.zip');
2464
2465 // Compress it
2466 global $errormsg; // Used by dol_compress_dir
2467 $errormsg = '';
2468 $result = dol_compress_dir($src, $dest.'.zip', 'zip');
2469 if ($result < 0) {
2470 $error++;
2471 $this->error = ($errormsg ? $errormsg : $langs->trans('ErrorFailToCreateZip', $dest));
2472 $this->errors[] = ($errormsg ? $errormsg : $langs->trans('ErrorFailToCreateZip', $dest));
2473 }
2474 }
2475
2476 // Copy also the preview website_xxx.jpg file
2477 $docs = dol_dir_list($srcroot, 'files', 0, 'website_.*\.jpg$');
2478 foreach ($docs as $cursorfile) {
2479 $src = $srcroot.'/'.$cursorfile['name'];
2480 $dest = DOL_DATA_ROOT.'/doctemplates/websites/'.$cursorfile['name'];
2481
2482 dol_copy($src, $dest);
2483 }
2484 }
2485
2486 $entity = $conf->entity; // Reset the current entity
2487 $newvalue = $value;
2488
2489 // Serialize array parameters
2490 if (is_array($value)) {
2491 // Can defined other parameters
2492 // Example when $key='hooks', then $value is an array('data'=>array('hookcontext1','hookcontext2'), 'entity'=>X)
2493 if (isset($value['data']) && is_array($value['data'])) {
2494 $newvalue = json_encode($value['data']);
2495 if (isset($value['entity'])) {
2496 $entity = $value['entity'];
2497 }
2498 } elseif (isset($value['data']) && !is_array($value['data'])) {
2499 $newvalue = $value['data'];
2500 if (isset($value['entity'])) {
2501 $entity = $value['entity'];
2502 }
2503 } else { // when hook is declared with syntax 'hook'=>array('hookcontext1','hookcontext2',...)
2504 $newvalue = json_encode($value);
2505 }
2506 }
2507
2508 if (!empty($newvalue)) {
2509 $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (";
2510 $sql .= "name";
2511 $sql .= ", type";
2512 $sql .= ", value";
2513 $sql .= ", note";
2514 $sql .= ", visible";
2515 $sql .= ", entity";
2516 $sql .= ")";
2517 $sql .= " VALUES (";
2518 $sql .= " ".$this->db->encrypt($this->const_name."_".strtoupper($key), 1);
2519 $sql .= ", 'chaine'";
2520 $sql .= ", ".$this->db->encrypt($newvalue, 1);
2521 $sql .= ", null";
2522 $sql .= ", '0'";
2523 $sql .= ", ".((int) $entity);
2524 $sql .= ")";
2525
2526 dol_syslog(get_class($this)."::insert_module_parts for key=".$this->const_name."_".strtoupper($key), LOG_DEBUG);
2527
2528 $resql = $this->db->query($sql, 1);
2529 if (!$resql) {
2530 if ($this->db->lasterrno() != 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2531 $error++;
2532 $this->error = $this->db->lasterror();
2533 } else {
2534 dol_syslog(get_class($this)."::insert_module_parts for ".$this->const_name."_".strtoupper($key)." Record already exists.", LOG_WARNING);
2535 }
2536 }
2537 }
2538 }
2539 }
2540 return $error;
2541 }
2542
2543 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2549 public function delete_module_parts()
2550 {
2551 // phpcs:enable
2552 global $conf;
2553
2554 $err = 0;
2555
2556 if (is_array($this->module_parts)) {
2557 dol_syslog(get_class($this)."::delete_module_parts", LOG_DEBUG);
2558
2559 if (empty($this->module_parts['icon']) && !empty($this->picto) && preg_match('/^fa\-/', $this->picto)) {
2560 $this->module_parts['icon'] = $this->picto;
2561 }
2562
2563 foreach ($this->module_parts as $key => $value) {
2564 // If entity is defined
2565 if (is_array($value) && isset($value['entity'])) {
2566 $entity = $value['entity'];
2567 } else {
2568 $entity = $conf->entity;
2569 }
2570
2571 $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
2572 $sql .= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_".strtoupper($key)."'";
2573 $sql .= " AND entity = ".((int) $entity);
2574
2575 if (!$this->db->query($sql)) {
2576 $this->error = $this->db->lasterror();
2577 $err++;
2578 }
2579 }
2580 }
2581 return $err;
2582 }
2583
2593 public function init($options = '')
2594 {
2595 return $this->_init(array(), $options);
2596 }
2597
2606 public function remove($options = '')
2607 {
2608 return $this->_remove(array(), $options);
2609 }
2610
2611
2619 public function getKanbanView($codeenabledisable = '', $codetoconfig = '')
2620 {
2621 global $langs;
2622
2623 // Define imginfo
2624 $imginfo = "info";
2625 if ($this->isCoreOrExternalModule() == 'external') {
2626 $imginfo = "info_black";
2627 }
2628
2629 $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($this)));
2630
2631 $version = $this->getVersion(0);
2632 $versiontrans = '';
2633 if (preg_match('/development/i', $version)) {
2634 $versiontrans .= 'warning';
2635 }
2636 if (preg_match('/experimental/i', $version)) {
2637 $versiontrans .= 'warning';
2638 }
2639 if (preg_match('/deprecated/i', $version)) {
2640 $versiontrans .= 'warning';
2641 }
2642
2643 $return = '
2644 <div class="box-flex-item info-box-module'
2645 .(getDolGlobalString($const_name) ? '' : ' --disabled')
2646 .($this->isCoreOrExternalModule() == 'external' ? ' --external' : '')
2647 .($this->needUpdate ? ' --need-update' : '')
2648 .'">
2649 <div class="info-box info-box-sm info-box-module">
2650 <div class="info-box-icon'.(!getDolGlobalString($const_name) ? '' : ' info-box-icon-module-enabled'.($versiontrans ? ' info-box-icon-module-warning' : '')).'">';
2651
2652 $alttext = '';
2653 //if (is_array($objMod->need_dolibarr_version)) $alttext.=($alttext?' - ':'').'Dolibarr >= '.join('.',$objMod->need_dolibarr_version);
2654 //if (is_array($objMod->phpmin)) $alttext.=($alttext?' - ':'').'PHP >= '.join('.',$objMod->phpmin);
2655 if (!empty($this->picto)) {
2656 if (preg_match('/^\//i', $this->picto)) {
2657 $return .= img_picto($alttext, $this->picto, 'class="inline-block valignmiddle"', 1);
2658 } else {
2659 $return .= img_object($alttext, $this->picto, 'class="inline-block valignmiddle"');
2660 }
2661 } else {
2662 $return .= img_object($alttext, 'generic', 'class="inline-block valignmiddle"');
2663 }
2664
2665 if ($this->isCoreOrExternalModule() == 'external' || preg_match('/development|experimental|deprecated/i', $version)) {
2666 $versionTitle = $langs->trans("Version").' '.$this->getVersion(1);
2667 if ($this->needUpdate) {
2668 $versionTitle .= '<br>'.$langs->trans('ModuleUpdateAvailable').' : '.$this->lastVersion;
2669 }
2670
2671 $return .= '<span class="info-box-icon-version'.($versiontrans ? ' '.$versiontrans : '').' classfortooltip" title="'.dol_escape_js($versionTitle).'" >';
2672 $return .= $this->getVersion(1);
2673 $return .= '</span>';
2674 }
2675
2676 $return .= '</div>
2677 <div class="info-box-content info-box-text-module'.(!getDolGlobalString($const_name) ? '' : ' info-box-module-enabled'.($versiontrans ? ' info-box-content-warning' : '')).'">
2678 <span class="info-box-title">'.$this->getName().'</span>
2679 <span class="info-box-desc twolinesmax opacitymedium" title="'.dol_escape_htmltag($this->getDesc()).'">'.nl2br($this->getDesc()).'</span>';
2680
2681 $return .= '<div class="valignmiddle inline-block info-box-more">';
2682 //if ($versiontrans) print img_warning($langs->trans("Version").' '.$this->getVersion(1)).' ';
2683 $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>';
2684 $return .= '</div><br>';
2685
2686 $return .= '<div class="valignmiddle inline-block info-box-actions">';
2687 $return .= '<div class="valignmiddle inline-block info-box-setup">';
2688 $return .= $codetoconfig;
2689 $return .= '</div>';
2690 $return .= '<div class="valignmiddle inline-block marginleftonly marginrightonly">';
2691 $return .= $codeenabledisable;
2692 $return .= '</div>';
2693 $return .= '</div>';
2694
2695 $return .= '
2696 </div><!-- /.info-box-content -->
2697 </div><!-- /.info-box -->
2698 </div>';
2699
2700 return $return;
2701 }
2702
2711 public function checkForUpdate()
2712 {
2713 require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
2714 if (!empty($this->url_last_version)) {
2715 $lastVersion = getURLContent($this->url_last_version, 'GET', '', 1, array(), array('http', 'https'), 0); // Accept http or https links on external remote server only
2716 if (isset($lastVersion['content']) && strlen($lastVersion['content']) < 30) {
2717 // 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 _ . -
2718 $this->lastVersion = preg_replace("/[^a-zA-Z0-9_\.\-]+/", "", $lastVersion['content']);
2719 if (version_compare($this->lastVersion, $this->version) > 0) {
2720 $this->needUpdate = true;
2721 return 1;
2722 } else {
2723 $this->needUpdate = false;
2724 return 0;
2725 }
2726 } else {
2727 return -1;
2728 }
2729 }
2730 return 0;
2731 }
2732
2740 public function checkForCompliance($nametocheck = '')
2741 {
2742 global $conf, $langs;
2743
2744 if (empty($nametocheck)) {
2745 $nametocheck = $this->name;
2746 }
2747
2748 // Get list of illegal modules name or ID
2749 if (empty($conf->cache['noncompliantmodules'])) {
2750 require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
2751
2752 $result = getURLContent(self::URL_FOR_BLACKLISTED_MODULES, 'GET', '', 1, array(), array('http', 'https'), 0); // Accept http or https links on external remote server only
2753 if (isset($result['content']) && $result['http_code'] == 200) {
2754 $langs->load("errors");
2755
2756 // 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 _ . -
2757 $arrayoflines = preg_split("/[\n,]/", $result['content']);
2758 foreach ($arrayoflines as $line) {
2759 $tmpfieldsofline = explode(';', $line);
2760 $modulekey = strtolower($tmpfieldsofline[0]);
2761 $conf->cache['noncompliantmodules'][$modulekey]['name'] = $tmpfieldsofline[0];
2762 $conf->cache['noncompliantmodules'][$modulekey]['id'] = (isset($tmpfieldsofline[1]) ? $tmpfieldsofline[1] : '');
2763 $conf->cache['noncompliantmodules'][$modulekey]['signature'] = (isset($tmpfieldsofline[2]) ? $tmpfieldsofline[2] : '');
2764 $conf->cache['noncompliantmodules'][$modulekey]['message'] = $langs->trans(empty($tmpfieldsofline[3]) ? 'WarningModuleAffiliatedToAReportedCompany' : $tmpfieldsofline[3]);
2765 if (!empty($tmpfieldsofline[4])) {
2766 $message2 = $langs->trans("WarningModuleAffiliatedToAPiratPlatform", '{s}');
2767 $listofillegalurl = '';
2768 foreach (explode(" ", $tmpfieldsofline[4]) as $illegalurl) {
2769 $listofillegalurl .= ($listofillegalurl ? ' '.$langs->trans("or").' ' : '').'<b>'.preg_replace('/[^a-z0-9\.\-]/', '', $illegalurl).'</b>';
2770 }
2771 $message2 = str_replace('{s}', $listofillegalurl, $message2);
2772 $conf->cache['noncompliantmodules'][$modulekey]['message2'] = $message2;
2773 }
2774 }
2775 }
2776 }
2777
2778 if (!empty($conf->cache['noncompliantmodules'])) {
2779 $modulekey = strtolower($nametocheck);
2780 if (in_array($modulekey, array_keys($conf->cache['noncompliantmodules']))) {
2781 $answer = trim($conf->cache['noncompliantmodules'][$modulekey]['message']);
2782 if (!empty($conf->cache['noncompliantmodules'][$modulekey]['message2'])) {
2783 $answer .= '<br>'.$conf->cache['noncompliantmodules'][$modulekey]['message2'];
2784 }
2785 return $answer;
2786 }
2787 }
2788
2789 return 0;
2790 }
2791
2810 protected function declareNewDictionary($dictionaryArray, $langs = '')
2811 {
2812 $fields = array('name', 'lib', 'sql', 'sqlsort', 'field', 'fieldvalue', 'fieldinsert', 'rowid', 'cond', 'help', 'fieldcheck');
2813
2814 foreach ($fields as $field) {
2815 if (isset($dictionaryArray[$field])) {
2816 // @phan-suppress-next-line PhanTypeMismatchProperty
2817 $this->dictionaries['tab'.$field][] = $dictionaryArray[$field];
2818 }
2819 }
2820 if ($langs && !in_array($langs, $this->dictionaries[$langs])) {
2821 $this->dictionaries['langs'][] = $langs;
2822 }
2823 }
2824}
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.
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,...
_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_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (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:161