diff --git a/htdocs/core/lib/modulebuilder.lib.php b/htdocs/core/lib/modulebuilder.lib.php index 1d930013c1c..bf20c7e0a7f 100644 --- a/htdocs/core/lib/modulebuilder.lib.php +++ b/htdocs/core/lib/modulebuilder.lib.php @@ -1021,6 +1021,59 @@ function reWriteAllMenus($file, $menus, $menuWantTo, $key, $action) }return -1; } +/** + * Updates a dictionary in a module descriptor file. + * + * @param string $module The name of the module. + * @param string $file The path to the module descriptor file. + * @param array $dicts The dictionary data to be updated. + * @return int Returns the number of replacements made in the file. + */ +function updateDictionaryInFile($module, $file, $dicts) +{ + + $isEmpty = false; + $dicData = "\t\t\$this->dictionaries=array(\n"; + $module = strtolower($module); + foreach ($dicts as $key => $value) { + if (empty($value)) { + $isEmpty = true; + $dicData = "\t\t\$this->dictionaries=array();"; + break; + } + + $dicData .= "\t\t\t'$key'=>"; + + if ($key === 'tabcond') { + $conditions = array_map(function ($val) use ($module) { + return ($val === true || $val === false) ? "isModEnabled('$module')" : $val; + }, $value); + $dicData .= "array(" . implode(",", $conditions) . ")"; + } elseif ($key === 'tabhelp') { + $helpItems = array(); + foreach ($value as $key => $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 .= (!$isEmpty ? "\t\t);" : ''); + + $stringDic = getFromFile($file, '/* BEGIN MODULEBUILDER DICTIONARIES */', '/* END MODULEBUILDER DICTIONARIES */'); + $writeInfile = dolReplaceInFile($file, array($stringDic => $dicData."\n")); + + return $writeInfile; +} + /** * Creates a new dictionary table. * @@ -1071,7 +1124,7 @@ function createNewDictionnary($modulename, $file, $namedic, $dictionnaires = nul break; } } - // check if tablename exist in Database + // check if tablename exist in Database and create it if not $query = "SHOW TABLES LIKE '" . MAIN_DB_PREFIX.strtolower($namedic) . "'"; $checkTable = $db->query($query); if ($checkTable && $db->num_rows($checkTable) > 0) { @@ -1087,7 +1140,7 @@ function createNewDictionnary($modulename, $file, $namedic, $dictionnaires = nul } // rewrite dictionnary if - $dictionnaires['tabname'][] = $namedic; + $dictionnaires['tabname'][] = strtolower($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' : ''); @@ -1099,36 +1152,7 @@ function createNewDictionnary($modulename, $file, $namedic, $dictionnaires = nul $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")); + $writeInfile = updateDictionaryInFile($modulename, $file, $dictionnaires); 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 01e944c4051..56ffdf185a0 100644 --- a/htdocs/langs/en_US/errors.lang +++ b/htdocs/langs/en_US/errors.lang @@ -319,6 +319,7 @@ 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 +ErrorDictionaryNotFound=Dictionary %s not found # 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 4bd66be5d57..5a7e8fbd980 100644 --- a/htdocs/langs/en_US/modulebuilder.lang +++ b/htdocs/langs/en_US/modulebuilder.lang @@ -28,6 +28,7 @@ ModuleBuilderDescwidgets=This tab is dedicated to manage/build widgets. ModuleBuilderDescbuildpackage=You can generate here a "ready to distribute" package file (a normalized .zip file) of your module and a "ready to distribute" documentation file. Just click on button to build the package or documentation file. EnterNameOfModuleToDeleteDesc=You can delete your module. WARNING: All coding files of module (generated or created manually) AND structured data and documentation will be deleted! EnterNameOfObjectToDeleteDesc=You can delete an object. WARNING: All coding files (generated or created manually) related to object will be deleted! +EnterNameOfObjectToDeleteDesc=You can delete your dictionary. WARNING: All coding files of module (generated or created manually) AND structured data and documentation will be deleted! DangerZone=Danger zone BuildPackage=Build package BuildPackageDesc=You can generate a zip package of your application so your are ready to distribute it on any Dolibarr. You can also distribute it or sell it on marketplace like DoliStore.com. @@ -177,4 +178,5 @@ 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. -DictionariesCreated=Dictionary %s created successfully \ No newline at end of file +DictionariesCreated=Dictionary %s created successfully +DictionaryDeleted=Dictionary %s removed successfully \ No newline at end of file diff --git a/htdocs/langs/fr_FR/errors.lang b/htdocs/langs/fr_FR/errors.lang index 22d141795b0..976c8317165 100644 --- a/htdocs/langs/fr_FR/errors.lang +++ b/htdocs/langs/fr_FR/errors.lang @@ -318,6 +318,7 @@ 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 +ErrorDictionaryNotFound=Le dictionnaire %s introuvable # 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 f5aefbc4e38..4ca5ddc464c 100644 --- a/htdocs/langs/fr_FR/modulebuilder.lang +++ b/htdocs/langs/fr_FR/modulebuilder.lang @@ -28,6 +28,7 @@ ModuleBuilderDescwidgets=Cet onglet est dédié à la gestion/construction de wi ModuleBuilderDescbuildpackage=Vous pouvez générer ici un fichier de package "prêt à distribuer" (un fichier .zip normalisé) de votre module et un fichier de documentation "prêt à distribuer". Cliquez simplement sur le bouton pour créer le paquet ou le fichier de documentation. EnterNameOfModuleToDeleteDesc=Vous pouvez supprimer votre module. ATTENTION: Tous les fichiers relatifs a ce module (générés ou créés manuellement) ET toutes les données et documentation seront supprimés! EnterNameOfObjectToDeleteDesc=Vous pouvez effacer un objet. ATTENTION : Tous les fichiers (générés ou créés manuellement) en rapport avec cet objet seront définitivement effacés ! +EnterNameOfDictionnaryToDeleteDesc=Vous pouvez supprimer votre dictionnaire. ATTENTION : Tous les fichiers (générés ou créés manuellement) en rapport avec ce dictionnaire seront définitivement effacés ! DangerZone=Zone de danger BuildPackage=Construire le package BuildPackageDesc=Vous pouvez générer un package zip de votre application afin d'être prêt à le distribuer sur n’importe quel Dolibarr. Vous pouvez également le distribuer ou le vendre sur une place de marché, comme DoliStore.com . @@ -177,4 +178,5 @@ 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 +DictionariesCreated = Le dictionnaire %s a été créé avec succès +DictionaryDeleted=Le dictionnaire %s a été supprimé avec succès \ No newline at end of file diff --git a/htdocs/modulebuilder/index.php b/htdocs/modulebuilder/index.php index 680e61730f3..5e6ea71a22f 100644 --- a/htdocs/modulebuilder/index.php +++ b/htdocs/modulebuilder/index.php @@ -1935,6 +1935,87 @@ if ($dirins && $action == 'confirm_deleteobject' && $objectname) { } } +if ($dirins && $action == 'confirm_deletedictionary' && $dicname) { + $pathtofile = $listofmodules[strtolower($module)]['moduledescriptorrelpath']; + $destdir = $dirins.'/'.strtolower($module); + $moduledescriptorfile = $dirins.'/'.strtolower($module).'/core/modules/mod'.$module.'.class.php'; + + if (preg_match('/[^a-z0-9_]/i', $dicname)) { + $error++; + setEventMessages($langs->trans("SpaceOrSpecialCharAreNotAllowed"), null, 'errors'); + } + + $newdicname = $dicname; + if (!preg_match('/^c_/', $newdicname)) { + $newdicname = 'c_'.strtolower($dicname); + } + + dol_include_once($pathtofile); + $class = 'mod'.$module; + + 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; + } + $dicts = $moduleobj->dictionaries; + + //chercher la table dicname + $query = "SHOW TABLES LIKE '" . MAIN_DB_PREFIX.strtolower($newdicname) . "'"; + $checkTable = $db->query($query); + if ($checkTable && $db->num_rows($checkTable) <= 0) { + $error++; + } + + // search the key by name + $keyToDelete = null; + foreach ($dicts['tabname'] as $key => $table) { + //var_dump($table." /////// ".$newdicname);exit; + if (strtolower($table) === $newdicname) { + $keyToDelete = $key; + break; + } + } + // delete all dicname's key values from the dictionary + if ($keyToDelete !== null) { + $keysToDelete = ['tabname', 'tablib', 'tabsql', 'tabsqlsort', 'tabfield', 'tabfieldvalue', 'tabfieldinsert', 'tabrowid', 'tabcond', 'tabhelp']; + foreach ($keysToDelete as $key) { + unset($dicts[$key][$keyToDelete]); + } + } else { + $error++; + setEventMessages($langs->trans("ErrorDictionaryNotFound", ucfirst($dicname)), null, 'errors'); + } + if (!$error) { + // delete table + $_results = $db->DDLDropTable(MAIN_DB_PREFIX.strtolower($newdicname)); + if ($_results < 0) { + dol_print_error($db); + $langs->load("errors"); + setEventMessages($langs->trans("ErrorTableNotFound", $newdicname), null, 'errors'); + } + // rebuild file after update dictionaries + $result = updateDictionaryInFile($module, $moduledescriptorfile, $dicts); + if ($result > 0) { + setEventMessages($langs->trans("DictionaryDeleted", ucfirst(substr($newdicname, 2))), null); + } + 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; + } +} + if ($dirins && $action == 'generatedoc') { $modulelowercase = strtolower($module); @@ -4295,13 +4376,13 @@ if ($module == 'initmodule') { // Delete dic tab print '
'; } else {