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