Merge pull request #25598 from lamrani002/removeDictionaryInMB

New|NEW functionality for remove dictionary in ModuleBuilder
This commit is contained in:
Laurent Destailleur 2023-08-09 15:20:41 +02:00 committed by GitHub
commit 298522d791
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 148 additions and 37 deletions

View file

@ -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);
}

View file

@ -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 <b>%s</b> already exist
ErrorDictionaryNotFound=Dictionary <b>%s</b> 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.

View file

@ -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 <a href="https://www.dolistore.com">DoliStore.com</a>.
@ -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 <b>%s</b> created successfully
DictionariesCreated=Dictionary <b>%s</b> created successfully
DictionaryDeleted=Dictionary <b>%s</b> removed successfully

View file

@ -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 <b>%s</b> existe déja
ErrorDictionaryNotFound=Le dictionnaire <b>%s</b> 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.

View file

@ -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 <a href="https://www.dolistore.com">DoliStore.com</a> .
@ -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 <b>%s</b> a été créé avec succès
DictionariesCreated = Le dictionnaire <b>%s</b> a été créé avec succès
DictionaryDeleted=Le dictionnaire <b>%s</b> a été supprimé avec succès

View file

@ -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 '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="confirm_deleteobject">';
print '<input type="hidden" name="action" value="confirm_deletedictionary">';
print '<input type="hidden" name="tab" value="dictionaries">';
print '<input type="hidden" name="module" value="'.dol_escape_htmltag($module).'">';
print $langs->trans("EnterNameOfObjectToDeleteDesc").'<br><br>';
print $langs->trans("EnterNameOfDictionnaryToDeleteDesc").'<br><br>';
print '<input type="text" name="objectname" value="'.dol_escape_htmltag($modulename).'" placeholder="'.dol_escape_htmltag($langs->trans("ObjectKey")).'">';
print '<input type="text" name="dicname" value="'.dol_escape_htmltag($modulename).'" placeholder="'.dol_escape_htmltag($langs->trans("DicKey")).'">';
print '<input type="submit" class="button smallpaddingimp" name="delete" value="'.dol_escape_htmltag($langs->trans("Delete")).'"'.($dirins ? '' : ' disabled="disabled"').'>';
print '</form>';
} else {