From 5741f2a398d25525e68b7b6acd7f18a69b5cbb22 Mon Sep 17 00:00:00 2001
From: Jean-Laurent <jean-laurent.duzant@xelians.fr>
Date: Wed, 21 Dec 2022 20:51:09 +0100
Subject: [PATCH] FEAT #23044 TIME 0:20 add useSMTPAuth parameter && Replace
 sender email by SMTP sender email when useSMTPAuth is active && remove SMTP
 sender rejected errors

---
 src/app/email/controllers/EmailController.php | 65 ++++++++++---------
 src/core/lang/lang-fr.php                     |  1 +
 .../sendmail-administration.component.html    | 10 ++-
 .../sendmail-administration.component.ts      |  3 +-
 src/lang/lang-fr.json                         |  4 +-
 5 files changed, 51 insertions(+), 32 deletions(-)

diff --git a/src/app/email/controllers/EmailController.php b/src/app/email/controllers/EmailController.php
index 5974f6c7b89..c6f8f16c760 100644
--- a/src/app/email/controllers/EmailController.php
+++ b/src/app/email/controllers/EmailController.php
@@ -46,11 +46,6 @@ use User\models\UserModel;
 
 class EmailController
 {
-    private const SMTP_ERRORS_SENDER_REJECTED = [
-        'Client does not have permissions to send as this sender',
-        'Sender address rejected'
-    ];
-
     public function send(Request $request, Response $response)
     {
         if (!PrivilegeController::hasPrivilege(['privilegeId' => 'sendmail', 'userId' => $GLOBALS['id']])) {
@@ -80,6 +75,16 @@ class EmailController
             return ['errors' => $check['errors'], 'code' => $check['code']];
         }
 
+        $configuration = ConfigurationModel::getByPrivilege(['privilege' => 'admin_email_server', 'select' => ['value']]);
+        $configuration = json_decode($configuration['value'], true);
+        if (empty($configuration)) {
+            return ['errors' => 'Configuration is missing'];
+        }
+
+        if (!empty($configuration['useSMTPAuth'])) {
+            $args['data']['sender']['email'] = $configuration['from'];
+        }
+
         $id = EmailModel::create([
             'userId'                => $args['userId'],
             'sender'                => empty($args['data']['sender']) ? '{}' : json_encode($args['data']['sender']),
@@ -121,12 +126,18 @@ class EmailController
                 exec("php src/app/email/scripts/sendEmail.php {$customId} {$id} {$args['userId']} '{$encryptKey}' '{$options}' > /dev/null &");
             }
             if (!empty($isSent)) {
+                $info = _EMAIL_ADDED ;
+                
+                if (!empty($configuration['useSMTPAuth'])) {
+                    $info .= ' : ' . _SENDER_EMAIL_REPLACED_SMTP_SENDER;
+                }
+
                 HistoryController::add([
                     'tableName' => 'emails',
                     'recordId'  => $id,
                     'eventType' => 'ADD',
                     'eventId'   => 'emailCreation',
-                    'info'      => _EMAIL_ADDED
+                    'info'      => $info
                 ]);
 
                 if (!empty($args['data']['document']['id'])) {
@@ -135,7 +146,7 @@ class EmailController
                         'recordId'  => $args['data']['document']['id'],
                         'eventType' => 'ADD',
                         'eventId'   => 'emailCreation',
-                        'info'      => _EMAIL_ADDED
+                        'info'      => $info
                     ]);
                 }
             }
@@ -289,6 +300,16 @@ class EmailController
             return $response->withStatus($check['code'])->withJson(['errors' => $check['errors']]);
         }
 
+        $configuration = ConfigurationModel::getByPrivilege(['privilege' => 'admin_email_server', 'select' => ['value']]);
+        $configuration = json_decode($configuration['value'], true);
+        if (empty($configuration)) {
+            return ['errors' => 'Configuration is missing'];
+        }
+
+        if (!empty($configuration['useSMTPAuth'])) {
+            $body['sender']['email'] = $configuration['from'];
+        }
+
         EmailModel::update([
             'set' => [
                 'sender'      => empty($body['sender']) ? '{}' : json_encode($body['sender']),
@@ -331,12 +352,18 @@ class EmailController
                 ]);
             }
         } else {
+            $info = _EMAIL_UPDATED ;
+            
+            if (!empty($configuration['useSMTPAuth'])) {
+                $info .= ' : ' . _SENDER_EMAIL_REPLACED_SMTP_SENDER;
+            }
+
             HistoryController::add([
                 'tableName'    => 'emails',
                 'recordId'     => $args['id'],
                 'eventType'    => 'UP',
                 'eventId'      => 'emailModification',
-                'info'         => _EMAIL_UPDATED
+                'info'         => $info
             ]);
 
             if (!empty($args['data']['document']['id'])) {
@@ -345,7 +372,7 @@ class EmailController
                     'recordId'  => $args['data']['document']['id'],
                     'eventType' => 'UP',
                     'eventId'   => 'emailModification',
-                    'info'      => _EMAIL_UPDATED
+                    'info'      => $info
                 ]);
             }
         }
@@ -761,26 +788,6 @@ class EmailController
 
             $errors = !empty($history[0]['info']) ? $history[0]['info'] : $phpmailer->ErrorInfo;
 
-            // If we cannot override from with the sender email address, we try sending the email with the from in the configuration
-            if ($email['sender']['email'] != $configuration['from']) {
-                $tryWithConfigFrom = false;
-                foreach (EmailController::SMTP_ERRORS_SENDER_REJECTED as $errorCandidate) {
-                    if (stripos($errors, $errorCandidate) !== false) {
-                        $tryWithConfigFrom = true;
-                        break;
-                    }
-                }
-                if ($tryWithConfigFrom) {
-                    $sender = [
-                        'email'    => $configuration['from'],
-                        'entityId' => $email['sender']['entityId'] ?? null
-                    ];
-                    EmailModel::update(['set' => ['sender' => json_encode($sender)], 'where' => ['id = ?'], 'data' => [$args['emailId']]]);
-
-                    return EmailController::sendEmail(['emailId' => $args['emailId'], 'userId' => $args['userId']]);
-                }
-            }
-
             return ['errors' => $errors];
         }
 
diff --git a/src/core/lang/lang-fr.php b/src/core/lang/lang-fr.php
index 2eebd3ca975..d2b81d80691 100755
--- a/src/core/lang/lang-fr.php
+++ b/src/core/lang/lang-fr.php
@@ -58,6 +58,7 @@ define('_DOCUMENT_OUT_PERIMETER', 'Courrier en dehors du périmètre');
 define('_EMAIL_ADDED', 'Courriel ajouté');
 define('_EMAIL_REMOVED', 'Courriel supprimé');
 define('_EMAIL_UPDATED', 'Courriel mis à jour');
+define('_SENDER_EMAIL_REPLACED_SMTP_SENDER', "L'email de l'expéditeur est remplacé par l'expéditeur SMTP");
 define('_ENTITY_CREATION', 'Création entité');
 define('_ENTITY_MODIFICATION', 'Modification entité');
 define('_ENTITY_SUPPRESSION', 'Suppression entité');
diff --git a/src/frontend/app/administration/sendmail/sendmail-administration.component.html b/src/frontend/app/administration/sendmail/sendmail-administration.component.html
index 69f22fc200f..004f8e06b8e 100644
--- a/src/frontend/app/administration/sendmail/sendmail-administration.component.html
+++ b/src/frontend/app/administration/sendmail/sendmail-administration.component.html
@@ -69,11 +69,19 @@
                                 </div>
                                 <div class="form-group"
                                     [style.opacity]="['smtp', 'mail'].indexOf(sendmail.type) > -1 ? '1' : '0.5'">
-                                    <div class="col-md-12">
+                                    <div class="col-md-4" style="margin-bottom: 10px;">
                                         <mat-slide-toggle color="primary" name="SMTPAuth" [(ngModel)]="sendmail.auth"
                                             [disabled]="['smtp', 'mail'].indexOf(sendmail.type) == -1"
                                             (change)="cleanAuthInfo($event)">{{'lang.enableAuth' | translate}}</mat-slide-toggle>
                                     </div>
+                                    <div class="col-md-8" style="margin-bottom: 10px;">
+                                        <mat-slide-toggle color="primary" name="canUseIt"
+                                            [(ngModel)]="sendmail.useSMTPAuth"
+                                            [title]="'lang.useSMTPAuthDesc' | translate"
+                                            [disabled]="['smtp', 'mail'].indexOf(sendmail.type) == -1">
+                                            {{'lang.useSMTPAuth' | translate}}
+                                        </mat-slide-toggle>
+                                    </div>
                                 </div>
                                 <div class="form-group"
                                     [style.opacity]="['smtp', 'mail'].indexOf(sendmail.type) > -1 ? '1' : '0.5'">
diff --git a/src/frontend/app/administration/sendmail/sendmail-administration.component.ts b/src/frontend/app/administration/sendmail/sendmail-administration.component.ts
index a12ed00e1b8..8631bdabfd7 100644
--- a/src/frontend/app/administration/sendmail/sendmail-administration.component.ts
+++ b/src/frontend/app/administration/sendmail/sendmail-administration.component.ts
@@ -80,7 +80,8 @@ export class SendmailAdministrationComponent implements OnInit {
     recipientTest: string = '';
     passwordLabel: string = '';
 
-
+    useSMTPAuth: boolean = false;
+    
     constructor(
         public translate: TranslateService,
         public http: HttpClient,
diff --git a/src/lang/lang-fr.json b/src/lang/lang-fr.json
index eb9bff77e1e..9d7b1390f9f 100644
--- a/src/lang/lang-fr.json
+++ b/src/lang/lang-fr.json
@@ -2688,5 +2688,7 @@
     "ixbus": "Ixbus",
     "iParapheur": "IParapheur",
     "xParaph": "XParaph",
-    "fastParapheurWorkflow": "Circuit de visa Fast Parapheur"
+    "fastParapheurWorkflow": "Circuit de visa Fast Parapheur",
+    "useSMTPAuth": "Utiliser l'adresse d'envoi configurée pour tous les envois de courriels",
+    "useSMTPAuthDesc": "Permet d'utiliser l'adresse d'envoi configurée pour toutes les emails sortante"
 }
-- 
GitLab