From 6043f8c5b863af1ffe3d282b4f72b1a10207f179 Mon Sep 17 00:00:00 2001
From: Damien <damien.burel@maarch.org>
Date: Wed, 17 Apr 2019 16:08:31 +0200
Subject: [PATCH] FEAT #8805 One file to rule them all

---
 {src/frontend/assets/i18n => lang}/en.json    | 29 +++++++-
 {src/frontend/assets/i18n => lang}/fr.json    | 29 +++++++-
 rest/index.php                                |  6 +-
 .../controllers/ConfigurationController.php   | 66 -------------------
 src/app/user/controllers/UserController.php   |  7 +-
 src/core/controllers/LangController.php       | 36 ++++++++--
 src/core/lang/lang-en.php                     | 43 ------------
 src/core/lang/lang-fr.php                     | 43 ------------
 src/frontend/app/app.module.ts                |  2 +-
 .../app/profile/profile.component.html        |  2 +-
 10 files changed, 97 insertions(+), 166 deletions(-)
 rename {src/frontend/assets/i18n => lang}/en.json (66%)
 rename {src/frontend/assets/i18n => lang}/fr.json (65%)
 delete mode 100755 src/core/lang/lang-en.php
 delete mode 100755 src/core/lang/lang-fr.php

diff --git a/src/frontend/assets/i18n/en.json b/lang/en.json
similarity index 66%
rename from src/frontend/assets/i18n/en.json
rename to lang/en.json
index 2c9f0a6e62..f1731fb1a3 100755
--- a/src/frontend/assets/i18n/en.json
+++ b/lang/en.json
@@ -105,6 +105,33 @@
 		"wouldLikeConfirm": "Would you like to confirm?",
 		"wrongLoginPassword": "Wrong login or password",
 		"wrongPassword": "Wrong password",
-		"wsUser": "Web service user"
+		"wsUser": "Web service user",
+		"actionDone"                                : "Action done",
+		"attachmentAdded"                           : "Attachment added",
+		"attachmentViewed"                          : "Attachment viewed",
+		"configurationUpdated"                      : "Configuration modifié",
+		"documentAdded"                             : "Document added",
+		"documentViewed"                            : "Document viewed",
+		"documentHistoryViewed"                     : "Document history viewed",
+		"processedDocumentViewed"                   : "Processed document viewed",
+		"emailAdded"                                : "Email added",
+		"emailNoSubject"                            : "No subject",
+		"emailFailed"                               : "Sending email failed",
+		"notificationDocumentAddedSubject"          : "[Maarch Parapheur] Notification",
+		"notificationDocumentAddedBody"             : "A document has been sent to you on Maarch Parapheur.<br/>Click on the link below to consult it :<br/>",
+		"notificationFooter"                        : "<br/><br/>This email is automatically generated by Maarch Parapheur.<br/>If you don't want to receive these notifications, mark it on your profile.",
+		"notificationForgotPasswordSubject"         : "[Maarch Parapheur] Reset password informations",
+		"notificationForgotPasswordBody"            : "Hello,<br/>You requested to reset the password for your Maarch Parapheur account.<br/>To change your password, please click on the link below :<br/>",
+		"notificationForgotPasswordFooter"          : "<br/><br/>If you did not perform this request, you can safely ignore this email.<br/>Please contact your administrator if you have any questions.",
+		"UserLogIn"                                 : "User log in",
+		"UserLogOut"                                : "User log out",
+		"userAdded"                                 : "User added",
+		"userUpdated"                               : "User updated",
+		"userPasswordUpdated"                       : "User password updated",
+		"userPasswordForgotten"                     : "User password forgotten",
+		"userForgottenPasswordUpdated"              : "User password updated after forgot request",
+		"userViewed"                                : "User viewed",
+		"userSignatureAdded"                        : "User signature added",
+		"userSignatureDeleted"                      : "User signature deleted"
 	}
 }
diff --git a/src/frontend/assets/i18n/fr.json b/lang/fr.json
similarity index 65%
rename from src/frontend/assets/i18n/fr.json
rename to lang/fr.json
index f8818386c2..73e99a3d3b 100755
--- a/src/frontend/assets/i18n/fr.json
+++ b/lang/fr.json
@@ -105,6 +105,33 @@
 		"wouldLikeConfirm": "Souhaitez-vous confirmer ?",
 		"wrongLoginPassword": "Mauvais identifiant ou mauvais mot de passe",
 		"wrongPassword": "Mauvais mot de passe",
-		"wsUser": "Utilisateur web service"
+		"wsUser": "Utilisateur web service",
+		"actionDone"                                : "Action effectuée",
+		"attachmentAdded"                           : "Pièce jointe ajoutée",
+		"attachmentViewed"                          : "Pièce jointe consulté",
+		"configurationUpdated"                      : "Configuration modifié",
+		"documentAdded"                             : "Document ajouté",
+		"documentViewed"                            : "Document consulté",
+		"documentHistoryViewed"                     : "Historique document consulté",
+		"processedDocumentViewed"                   : "Document traité consulté",
+		"emailAdded"                                : "Courriel ajouté",
+		"emailNoSubject"                            : "Sans objet",
+		"emailFailed"                               : "L'envoi du courriel a échoué",
+		"notificationDocumentAddedSubject"          : "[Maarch Parapheur] Notification",
+		"notificationDocumentAddedBody"             : "Un document vient de vous être transmis sur Maarch Parapheur.<br/>Cliquer sur le lien ci-dessous pour le consulter :<br/>",
+		"notificationFooter"                        : "<br/><br/>Ce courriel vous est envoyé automatiquement par Maarch Parapheur.<br/>Si vous souhaitez ne plus recevoir ces notifications, indiquez-le sur votre profil.",
+		"notificationForgotPasswordSubject"         : "[Maarch Parapheur] Demande de réinitialisation de mot de passe",
+		"notificationForgotPasswordBody"            : "Bonjour,<br/>Vous avez demandé à retrouver le mot de passe d'accès à votre compte Maarch Parapheur.<br/>Pour modifier votre mot de passe, merci de bien vouloir cliquer sur le lien ci-dessous :<br/>",
+		"notificationForgotPasswordFooter"          : "<br/><br/>Si vous n'êtes pas à l'origine de cette demande, merci d'ignorer ce courriel.<br/>Pour toutes questions, merci de contacter l'administrateur technique de la solution.",
+		"userLogIn"                                 : "Connexion utilisateur",
+		"userLogOut"                                : "Déconnexion utilisateur",
+		"userAdded"                                 : "Utilisateur ajouté",
+		"userUpdated"                               : "Utilisateur modifié",
+		"userPasswordUpdated"                       : "Mot de passe utilisateur modifié",
+		"userPasswordForgotten"                     : "Demande de mot de passe utilisateur oublié",
+		"userForgottenPasswordUpdated"              : "Mot de passe utilisateur modifié après demande d'oubli",
+		"userViewed"                                : "Utilisateur consulté",
+		"userSignatureAdded"                        : "Signature utilisateur ajouté",
+		"userSignatureDeleted"                      : "Signature utilisateur supprimé"
 	}
 }
diff --git a/rest/index.php b/rest/index.php
index 60ce7e1e85..c716173ef6 100755
--- a/rest/index.php
+++ b/rest/index.php
@@ -26,7 +26,7 @@ $app->add(function (\Slim\Http\Request $request, \Slim\Http\Response $response,
     if (!is_file($configPath . '/config.xml')) {
         return $response->withStatus(400)->withJson(['errors' => 'Configuration file is missing']);
     }
-    $routesWithoutAuthentication = ['POST/log', 'POST/password', 'PUT/password', 'GET/passwordRules', 'GET/langPath/{lang}'];
+    $routesWithoutAuthentication = ['POST/log', 'POST/password', 'PUT/password', 'GET/passwordRules', 'GET/languages/{lang}'];
     $route = $request->getAttribute('route');
     $currentMethod = empty($route) ? '' : $route->getMethods()[0];
     $currentRoute = empty($route) ? '' : $route->getPattern();
@@ -59,7 +59,6 @@ $app->get('/attachments/{id}', \Attachment\controllers\AttachmentController::cla
 
 //Configurations
 $app->put('/configurations/{identifier}', \Configuration\controllers\ConfigurationController::class . ':update');
-$app->get('/langPath/{lang}', \Configuration\controllers\ConfigurationController::class . ':getLangPath');
 
 //Documents
 $app->post('/documents', \Document\controllers\DocumentController::class . ':create');
@@ -70,6 +69,9 @@ $app->get('/documents/{id}/processedDocument', \Document\controllers\DocumentCon
 $app->get('/documents/{id}/history', \History\controllers\HistoryController::class . ':getByDocumentId');
 $app->put('/documents/{id}/actions/{actionId}', \Document\controllers\DocumentController::class . ':setAction');
 
+//Languages
+$app->get('/languages/{lang}', \SrcCore\controllers\LangController::class . ':getByLang');
+
 //PasswordRules
 $app->get('/passwordRules', \SrcCore\controllers\PasswordController::class . ':get');
 
diff --git a/src/app/configuration/controllers/ConfigurationController.php b/src/app/configuration/controllers/ConfigurationController.php
index 939690da1d..9be18f2e7b 100755
--- a/src/app/configuration/controllers/ConfigurationController.php
+++ b/src/app/configuration/controllers/ConfigurationController.php
@@ -21,7 +21,6 @@ use Slim\Http\Request;
 use Slim\Http\Response;
 use SrcCore\models\AuthenticationModel;
 use User\controllers\UserController;
-use SrcCore\models\CoreConfigModel;
 
 class ConfigurationController
 {
@@ -111,69 +110,4 @@ class ConfigurationController
 
         return ['success' => 'success'];
     }
-
-    public function getLangPath(Request $request, Response $response, array $args)
-    {
-        if (!Validator::stringType()->notEmpty()->validate($args['lang'])) {
-            return $response->withStatus(404)->withJson(['errors' => 'Lang missing']);
-        }
-
-        // Get Default lang file
-        $defaultLangFilepath = realpath('src/frontend/assets/i18n/'.$args['lang'].'.json');
-
-        if (file_exists($defaultLangFilepath)) {
-            $defaultLangFileContent = file_get_contents($defaultLangFilepath);
-
-            $defaultLangFile = json_decode($defaultLangFileContent);
-        } else {
-            $defaultLangFile = json_decode('{"lang":{}}');
-        }
-        
-
-        $loadedXml = CoreConfigModel::getConfig();
-        
-        // Get custom lang file
-        if (!empty((string)$loadedXml->config->customLangPathDirectory)) {
-            $customLangPathDirectory = rtrim((string)$loadedXml->config->customLangPathDirectory, '/');
-            $customLangFilepath = realpath($customLangPathDirectory.'/'.$args['lang'].'.json');
-
-            if (file_exists($customLangFilepath)) {
-                $customLangFileContent = file_get_contents($customLangFilepath);
-                $customLangFile = json_decode($customLangFileContent);
-        
-                foreach ($customLangFile->lang as $key => $value) {
-                    $defaultLangFile->lang->$key = $customLangFile->lang->$key;
-                }
-            }
-        }
-        
-        return $response->withJson($defaultLangFile);
-    }
-
-    public function getAvailableLang()
-    {
-
-        // Get Default lang list
-        $langFilenameList = array_diff(scandir(realpath('src/frontend/assets/i18n/')), array('..', '.'));
-        
-        $loadedXml = CoreConfigModel::getConfig();
-        
-        // Get custom lang list
-        if (!empty((string)$loadedXml->config->customLangPathDirectory)) {
-            $customLangPathDirectory = rtrim((string)$loadedXml->config->customLangPathDirectory, '/');
-
-            $customLangFilenameList = array_diff(scandir(realpath($customLangPathDirectory)), array('..', '.'));
-            
-            $mergedLangFilenameList = array_unique(array_merge($langFilenameList, $customLangFilenameList), SORT_REGULAR);
-        } else {
-            $mergedLangFilenameList =  $langFilenameList;
-        }
-        
-        $langFilenameList = [];
-        foreach ($mergedLangFilenameList as $key => $value) {
-            $langFilenameList[] = str_replace('.json', '', $value);
-        }
-
-        return ['lang' => $langFilenameList];
-    }
 }
diff --git a/src/app/user/controllers/UserController.php b/src/app/user/controllers/UserController.php
index 735313fb56..f7f608ed86 100755
--- a/src/app/user/controllers/UserController.php
+++ b/src/app/user/controllers/UserController.php
@@ -138,7 +138,7 @@ class UserController
         }
 
         $check = Validator::arrayType()->notEmpty()->validate($body['preferences']);
-        //$check = $check && Validator::stringType()->notEmpty()->validate($body['preferences']['lang']) && in_array($body['preferences']['lang'], ['fr', 'en']);
+        $check = $check && Validator::stringType()->notEmpty()->validate($body['preferences']['lang']);
         $check = $check && Validator::stringType()->notEmpty()->validate($body['preferences']['writingMode']);
         $check = $check && Validator::intType()->notEmpty()->validate($body['preferences']['writingSize']);
         $check = $check && Validator::stringType()->notEmpty()->validate($body['preferences']['writingColor']);
@@ -365,16 +365,15 @@ class UserController
 
         $user = UserModel::getById(['select' => ['id', 'login', 'email', 'firstname', 'lastname', 'picture', 'preferences'], 'id' => $args['id']]);
 
-        $langs = ConfigurationController::getAvailableLang();
-        $user['availableLang'] = $langs['lang'];
 
         if (empty($user['picture'])) {
             $user['picture'] = base64_encode(file_get_contents('src/frontend/assets/user_picture.png'));
             $user['picture'] = 'data:image/png;base64,' . $user['picture'];
         }
 
-        $user['preferences'] = json_decode($user['preferences'], true);
+        $user['preferences']        = json_decode($user['preferences'], true);
         $user['canManageRestUsers'] = UserController::hasPrivilege(['userId' => $args['id'], 'privilege' => 'manage_rest_users']);
+        $user['availableLanguages'] = LangController::getAvailableLanguages();
 
         return $user;
     }
diff --git a/src/core/controllers/LangController.php b/src/core/controllers/LangController.php
index e46d558d00..99d2bd7358 100644
--- a/src/core/controllers/LangController.php
+++ b/src/core/controllers/LangController.php
@@ -13,6 +13,8 @@
 
 namespace SrcCore\controllers;
 
+use Slim\Http\Request;
+use Slim\Http\Response;
 use SrcCore\models\ValidatorModel;
 use User\models\UserModel;
 
@@ -29,12 +31,38 @@ class LangController
         }
 
         $lang = [];
-        if ($args['lang'] == 'fr') {
-            require_once "src/core/lang/lang-fr.php";
-        } elseif ($args['lang'] == 'en') {
-            require_once "src/core/lang/lang-en.php";
+        if (is_file("lang/{$args['lang']}.json")) {
+            $file = file_get_contents("lang/{$args['lang']}.json");
+            $langFile = json_decode($file, true);
+            if (!empty($langFile['lang'])) {
+                $lang = $langFile['lang'];
+            }
         }
 
         return $lang;
     }
+
+    public function getByLang(Request $request, Response $response, array $args)
+    {
+        if (!is_file("lang/{$args['lang']}.json")) {
+            return $response->withStatus(400)->withJson(['errors' => 'Lang does not exist']);
+        }
+
+        $file = file_get_contents("lang/{$args['lang']}.json");
+        $lang = json_decode($file, true);
+
+        return $response->withJson($lang);
+    }
+
+    public static function getAvailableLanguages()
+    {
+        $files = array_diff(scandir('lang/'), ['..', '.']);
+
+        $languages = [];
+        foreach ($files as $value) {
+            $languages[] = str_replace('.json', '', $value);
+        }
+
+        return $languages;
+    }
 }
diff --git a/src/core/lang/lang-en.php b/src/core/lang/lang-en.php
deleted file mode 100755
index ad896d6a55..0000000000
--- a/src/core/lang/lang-en.php
+++ /dev/null
@@ -1,43 +0,0 @@
-<?php
-
-/**
- * Copyright Maarch since 2008 under licence GPLv3.
- * See LICENCE.txt file at the root folder for more details.
- * This file is part of Maarch software.
- */
-
-/**
- * @brief Lang English
- *
- * @author dev@maarch.org
- */
-
-$lang = [
-    'actionDone'                                => 'Action done',
-    'attachmentAdded'                           => 'Attachment added',
-    'attachmentViewed'                          => 'Attachment viewed',
-    'configurationUpdated'                      => 'Configuration modifié',
-    'documentAdded'                             => 'Document added',
-    'documentViewed'                            => 'Document viewed',
-    'documentHistoryViewed'                     => 'Document history viewed',
-    'processedDocumentViewed'                   => 'Processed document viewed',
-    'emailAdded'                                => 'Email added',
-    'emailNoSubject'                            => 'No subject',
-    'emailFailed'                               => 'Sending email failed',
-    'notificationDocumentAddedSubject'          => '[Maarch Parapheur] Notification       ',
-    'notificationDocumentAddedBody'             => 'A document has been sent to you on Maarch Parapheur.<br/>Click on the link below to consult it :<br/>',
-    'notificationFooter'                        => '<br/><br/>This email is automatically generated by Maarch Parapheur.<br/>If you don\'t want to receive these notifications, mark it on your profile.',
-    'notificationForgotPasswordSubject'         => '[Maarch Parapheur] Reset password informations',
-    'notificationForgotPasswordBody'            => 'Hello,<br/>You requested to reset the password for your Maarch Parapheur account.<br/>To change your password, please click on the link below :<br/>',
-    'notificationForgotPasswordFooter'          => '<br/><br/>If you did not perform this request, you can safely ignore this email.<br/>Please contact your administrator if you have any questions.',
-    'UserLogIn'                                 => 'User log in',
-    'UserLogOut'                                => 'User log out',
-    'userAdded'                                 => 'User added',
-    'userUpdated'                               => 'User updated',
-    'userPasswordUpdated'                       => 'User password updated',
-    'userPasswordForgotten'                     => 'User password forgotten',
-    'userForgottenPasswordUpdated'              => 'User password updated after forgot request',
-    'userViewed'                                => 'User viewed',
-    'userSignatureAdded'                        => 'User signature added',
-    'userSignatureDeleted'                      => 'User signature deleted'
-];
diff --git a/src/core/lang/lang-fr.php b/src/core/lang/lang-fr.php
deleted file mode 100755
index d576f2a919..0000000000
--- a/src/core/lang/lang-fr.php
+++ /dev/null
@@ -1,43 +0,0 @@
-<?php
-
-/**
- * Copyright Maarch since 2008 under licence GPLv3.
- * See LICENCE.txt file at the root folder for more details.
- * This file is part of Maarch software.
- */
-
-/**
- * @brief Lang Français
- *
- * @author dev@maarch.org
- */
-
-$lang = [
-    'actionDone'                                => 'Action effectuée',
-    'attachmentAdded'                           => 'Pièce jointe ajoutée',
-    'attachmentViewed'                          => 'Pièce jointe consulté',
-    'configurationUpdated'                      => 'Configuration modifié',
-    'documentAdded'                             => 'Document ajouté',
-    'documentViewed'                            => 'Document consulté',
-    'documentHistoryViewed'                     => 'Historique document consulté',
-    'processedDocumentViewed'                   => 'Document traité consulté',
-    'emailAdded'                                => 'Courriel ajouté',
-    'emailNoSubject'                            => 'Sans objet',
-    'emailFailed'                               => 'L\'envoi du courriel a échoué',
-    'notificationDocumentAddedSubject'          => '[Maarch Parapheur] Notification',
-    'notificationDocumentAddedBody'             => 'Un document vient de vous être transmis sur Maarch Parapheur.<br/>Cliquer sur le lien ci-dessous pour le consulter :<br/>',
-    'notificationFooter'                        => '<br/><br/>Ce courriel vous est envoyé automatiquement par Maarch Parapheur.<br/>Si vous souhaitez ne plus recevoir ces notifications, indiquez-le sur votre profil.',
-    'notificationForgotPasswordSubject'         => '[Maarch Parapheur] Demande de réinitialisation de mot de passe',
-    'notificationForgotPasswordBody'            => 'Bonjour,<br/>Vous avez demandé à retrouver le mot de passe d\'accès à votre compte Maarch Parapheur.<br/>Pour modifier votre mot de passe, merci de bien vouloir cliquer sur le lien ci-dessous :<br/>',
-    'notificationForgotPasswordFooter'          => '<br/><br/>Si vous n\'êtes pas à l\'origine de cette demande, merci d\'ignorer ce courriel.<br/>Pour toutes questions, merci de contacter l\'administrateur technique de la solution.',
-    'userLogIn'                                 => 'Connexion utilisateur',
-    'userLogOut'                                => 'Déconnexion utilisateur',
-    'userAdded'                                 => 'Utilisateur ajouté',
-    'userUpdated'                               => 'Utilisateur modifié',
-    'userPasswordUpdated'                       => 'Mot de passe utilisateur modifié',
-    'userPasswordForgotten'                     => 'Demande de mot de passe utilisateur oublié',
-    'userForgottenPasswordUpdated'              => 'Mot de passe utilisateur modifié après demande d\'oubli',
-    'userViewed'                                => 'Utilisateur consulté',
-    'userSignatureAdded'                        => 'Signature utilisateur ajouté',
-    'userSignatureDeleted'                      => 'Signature utilisateur supprimé'
-];
diff --git a/src/frontend/app/app.module.ts b/src/frontend/app/app.module.ts
index 2e215e05a2..ab157227f3 100755
--- a/src/frontend/app/app.module.ts
+++ b/src/frontend/app/app.module.ts
@@ -139,6 +139,6 @@ export class TranslateBackendHttpLoader implements TranslateLoader {
    */
   public getTranslation(lang: string): any {
 
-    return this.http.get(`../rest/langPath/` + lang);
+    return this.http.get(`../rest/languages/` + lang);
   }
 }
diff --git a/src/frontend/app/profile/profile.component.html b/src/frontend/app/profile/profile.component.html
index 9b80592b33..663c735828 100644
--- a/src/frontend/app/profile/profile.component.html
+++ b/src/frontend/app/profile/profile.component.html
@@ -106,7 +106,7 @@
                                     <div class="form-2-col">
                                         <mat-form-field>
                                             <mat-select #langSelect name="langUser" [(ngModel)]="this.profileInfo.preferences.lang">
-                                                <mat-option *ngFor="let lang of this.profileInfo.availableLang" [value]="lang">{{'lang.'+lang | translate }}</mat-option>
+                                                <mat-option *ngFor="let lang of this.profileInfo['availableLanguages']" [value]="lang">{{'lang.'+lang | translate }}</mat-option>
                                             </mat-select>
                                         </mat-form-field>
                                     </div>
-- 
GitLab