diff --git a/htdocs/core/lib/modulebuilder.lib.php b/htdocs/core/lib/modulebuilder.lib.php index de26ad0462d..1d930013c1c 100644 --- a/htdocs/core/lib/modulebuilder.lib.php +++ b/htdocs/core/lib/modulebuilder.lib.php @@ -1020,3 +1020,116 @@ function reWriteAllMenus($file, $menus, $menuWantTo, $key, $action) return 1; }return -1; } + +/** + * Creates a new dictionary table. + * + * for creating a new dictionary table in Dolibarr. It generates the necessary SQL code to define the table structure, + * including columns such as 'rowid', 'code', 'label', 'position', 'use_default', 'active', etc. The table name is constructed based on the provided $namedic parameter. + * + * @param string $modulename The lowercase name of the module for which the dictionary table is being created. + * @param string $file The file path to the Dolibarr module builder file where the dictionaries are defined. + * @param string $namedic The name of the dictionary, which will also be used as the base for the table name. + * @param array|null $dictionnaires An optional array containing pre-existing dictionary data, including 'tabname', 'tablib', 'tabsql', etc. + * @return void + */ +function createNewDictionnary($modulename, $file, $namedic, $dictionnaires = null) +{ + global $db, $langs; + + if (empty($namedic)) { + setEventMessages($langs->trans("ErrorEmptyNameDic"), null, 'errors'); + return; + } + if (!file_exists($file)) { + return -1; + } + $modulename = strtolower($modulename); + + if (empty($dictionnaires)) { + $dictionnaires = array('tabname' => array(), 'tablib' => array(), 'tabsql' => array(), 'tabsqlsort' => array(), 'tabfield' => array(), 'tabfieldvalue' => array(), 'tabfieldinsert' => array(), 'tabrowid' => array(), 'tabcond' => array(), 'tabhelp' => array()); + } + + $columns = array( + 'rowid' => array('type' => 'integer(11)'), + 'code' => array('type' => 'varchar(255) NOT NULL'), + 'label' => array('type' => 'varchar(255) NOT NULL'), + 'position' => array('type' => 'integer(11) NULL'), + 'use_default' => array('type' => 'varchar(255) DEFAULT 1'), + 'active' => array('type' => 'integer') + ); + + + $primaryKey = 'rowid'; + foreach ($columns as $key => $value) { + if ($key === 'rowid') { + $primaryKey = 'rowid'; + break; + } + if (!array_key_exists('rowid', $columns)) { + $primaryKey = array_key_first($columns); + break; + } + } + // check if tablename exist in Database + $query = "SHOW TABLES LIKE '" . MAIN_DB_PREFIX.strtolower($namedic) . "'"; + $checkTable = $db->query($query); + if ($checkTable && $db->num_rows($checkTable) > 0) { + setEventMessages($langs->trans("ErrorTableExist", $namedic), null, 'errors'); + return; + } else { + $_results = $db->DDLCreateTable(MAIN_DB_PREFIX.strtolower($namedic), $columns, $primaryKey, "InnoDB"); + if ($_results < 0) { + dol_print_error($db); + $langs->load("errors"); + setEventMessages($langs->trans("ErrorTableNotFound", $namedic), null, 'errors'); + } + } + + // rewrite dictionnary if + $dictionnaires['tabname'][] = $namedic; + $dictionnaires['tablib'][] = ucfirst(substr($namedic, 2)); + $dictionnaires['tabsql'][] = 'SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.strtolower($namedic).' as f'; + $dictionnaires['tabsqlsort'][] = (array_key_exists('label', $columns) ? 'label ASC' : ''); + $dictionnaires['tabfield'][] = (array_key_exists('code', $columns) && array_key_exists('label', $columns) ? 'code,label' : ''); + $dictionnaires['tabfieldvalue'][] = (array_key_exists('code', $columns) && array_key_exists('label', $columns) ? 'code,label' : ''); + $dictionnaires['tabfieldinsert'][] = (array_key_exists('code', $columns) && array_key_exists('label', $columns) ? 'code,label' : ''); + $dictionnaires['tabrowid'][] = $primaryKey; + $dictionnaires['tabcond'][] = isModEnabled('$modulename'); + $dictionnaires['tabhelp'][] = (array_key_exists('code', $columns) ? array('code'=>$langs->trans('CodeTooltipHelp'), 'field2' => 'field2tooltip') : ''); + + // Build the dictionary string + $dicData = "\t\t\$this->dictionaries=array(\n"; + + foreach ($dictionnaires as $key => $value) { + $dicData .= "\t\t\t'$key'=>"; + + if ($key === 'tabcond') { + $conditions = array_map(function ($val) use ($modulename) { + return ($val === true || $val === false) ? "isModEnabled('$modulename')" : $val; + }, $value); + $dicData .= "array(" . implode(",", $conditions) . ")"; + } elseif ($key === 'tabhelp') { + $helpItems = array(); + foreach ($value as $helpValue) { + $helpItems[] = "array('code'=>\$langs->trans('".$helpValue['code']."'), 'field2' => 'field2tooltip')"; + } + $dicData .= "array(" . implode(",", $helpItems) . ")"; + } else { + if (is_array($value)) { + $dicData .= "array(" . implode(",", array_map(function ($val) { + return "'$val'"; + }, $value)) . ")"; + } else { + $dicData .= "'$value'"; + } + } + $dicData .= ",\n"; + } + $dicData .= "\t\t);"; + $stringDic = getFromFile($file, '/* BEGIN MODULEBUILDER DICTIONARIES */', '/* END MODULEBUILDER DICTIONARIES */'); + $writeInfile = dolReplaceInFile($file, array($stringDic => $dicData."\n")); + if ($writeInfile > 0) { + setEventMessages($langs->trans("DictionariesCreated", ucfirst(substr($namedic, 2))), null); + } +} diff --git a/htdocs/langs/en_US/errors.lang b/htdocs/langs/en_US/errors.lang index 571802e6d5f..01e944c4051 100644 --- a/htdocs/langs/en_US/errors.lang +++ b/htdocs/langs/en_US/errors.lang @@ -318,7 +318,7 @@ ErrorTheUrlOfYourDolInstanceDoesNotMatchURLIntoOAuthSetup=Error: The URL of you ErrorMenuExistValue=A Menu already exist with this Title or URL ErrorSVGFilesNotAllowedAsLinksWithout=SVG files are not allowed as external links without the option %s ErrorTypeMenu=Impossible to add another menu for the same module on the navbar, not handle yet - +ErrorTableExist=Table %s already exist # Warnings WarningParamUploadMaxFileSizeHigherThanPostMaxSize=Your PHP parameter upload_max_filesize (%s) is higher than PHP parameter post_max_size (%s). This is not a consistent setup. WarningPasswordSetWithNoAccount=A password was set for this member. However, no user account was created. So this password is stored but can't be used to login to Dolibarr. It may be used by an external module/interface but if you don't need to define any login nor password for a member, you can disable option "Manage a login for each member" from Member module setup. If you need to manage a login but don't need any password, you can keep this field empty to avoid this warning. Note: Email can also be used as a login if the member is linked to a user. diff --git a/htdocs/langs/en_US/modulebuilder.lang b/htdocs/langs/en_US/modulebuilder.lang index 02fb5b5d6a9..4bd66be5d57 100644 --- a/htdocs/langs/en_US/modulebuilder.lang +++ b/htdocs/langs/en_US/modulebuilder.lang @@ -176,4 +176,5 @@ MenuUpdatedSuccessfuly=Menu has been successfully updated ApiObjectDeleted=API for object %s has been successfully deleted CRUDRead=Read CRUDCreateWrite=Create or Update -FailedToAddCodeIntoDescriptor=Failed to add code into descriptor. Check that the string comment "%s" is still present into the file. \ No newline at end of file +FailedToAddCodeIntoDescriptor=Failed to add code into descriptor. Check that the string comment "%s" is still present into the file. +DictionariesCreated=Dictionary %s created successfully \ No newline at end of file diff --git a/htdocs/langs/fr_FR/errors.lang b/htdocs/langs/fr_FR/errors.lang index d81be42b602..22d141795b0 100644 --- a/htdocs/langs/fr_FR/errors.lang +++ b/htdocs/langs/fr_FR/errors.lang @@ -317,6 +317,7 @@ ErrorTheUrlOfYourDolInstanceDoesNotMatchURLIntoOAuthSetup=Erreur : L'URL de vot ErrorMenuExistValue=Un menu existe déjà avec ce titre ou cette URL ErrorSVGFilesNotAllowedAsLinksWithout=Les fichiers SVG ne sont pas autorisés en tant que liens externes sans l'option %s ErrorTypeMenu=Impossible d'ajouter un autre menu pour le même module sur la barre de navigation, pas encore géré +ErrorTableExist=La table %s existe déja # Warnings WarningParamUploadMaxFileSizeHigherThanPostMaxSize=Votre paramètre PHP upload_max_filesize (%s) est supérieur au paramètre PHP post_max_size (%s). Ceci n'est pas une configuration cohérente. diff --git a/htdocs/langs/fr_FR/modulebuilder.lang b/htdocs/langs/fr_FR/modulebuilder.lang index 5fa2c474900..f5aefbc4e38 100644 --- a/htdocs/langs/fr_FR/modulebuilder.lang +++ b/htdocs/langs/fr_FR/modulebuilder.lang @@ -177,3 +177,4 @@ ApiObjectDeleted=L'API pour l'objet %s a été supprimée avec succès CRUDRead=Lire CRUDCreateWrite=Créer ou mettre à jour FailedToAddCodeIntoDescriptor=Échec de l'ajout de code dans le descripteur. Vérifiez que le commentaire de chaîne "%s" est toujours présent dans le fichier. +DictionariesCreated = Le dictionnaire %s a été créé avec succès \ No newline at end of file diff --git a/htdocs/modulebuilder/index.php b/htdocs/modulebuilder/index.php index edead052752..680e61730f3 100644 --- a/htdocs/modulebuilder/index.php +++ b/htdocs/modulebuilder/index.php @@ -1553,15 +1553,39 @@ if ($dirins && $action == 'initobject' && $module && $objectname) { // Add a dictionary if ($dirins && $action == 'initdic' && $module && $dicname) { + $pathtofile = $listofmodules[strtolower($module)]['moduledescriptorrelpath']; + $destdir = $dirins.'/'.strtolower($module); + $moduledescriptorfile = $dirins.'/'.strtolower($module).'/core/modules/mod'.$module.'.class.php'; + if (!$error) { $newdicname = $dicname; if (!preg_match('/^c_/', $newdicname)) { $newdicname = 'c_'.$dicname; } + dol_include_once($pathtofile); + $class = 'mod'.$module; - // TODO - - setEventMessages($langs->trans("FeatureNotYetAvailable"), null, 'errors'); + if (class_exists($class)) { + try { + $moduleobj = new $class($db); + } catch (Exception $e) { + $error++; + dol_print_error($db, $e->getMessage()); + } + } else { + $error++; + $langs->load("errors"); + dol_print_error($db, $langs->trans("ErrorFailedToLoadModuleDescriptorForXXX", $module)); + exit; + } + $dictionaries = $moduleobj->dictionaries; + createNewDictionnary($module, $moduledescriptorfile, $newdicname, $dictionaries); + if (function_exists('opcache_invalidate')) { + opcache_reset(); // remove the include cache hell ! + } + clearstatcache(true); + header("Location: ".DOL_URL_ROOT.'/modulebuilder/index.php?tab=dictionaries&module='.$module.($forceddirread ? '@'.$dirread : '')); + exit; } } @@ -4088,6 +4112,7 @@ if ($module == 'initmodule') { $pathtofile = $listofmodules[strtolower($module)]['moduledescriptorrelpath']; $dicts = $moduleobj->dictionaries; + //var_dump($dicts);exit; if ($action != 'editfile' || empty($file)) { print ''; @@ -4217,11 +4242,11 @@ if ($module == 'initmodule') { print $dicts['tabfieldinsert'][$i]; print ''; - print '