From e6e469f1b1459cf7844d9ae5f9a85d397e9b6d40 Mon Sep 17 00:00:00 2001
From: "florian.azizian" <florian.azizian@maarch.org>
Date: Wed, 8 Apr 2020 11:56:38 +0100
Subject: [PATCH] FEAT #13679 TIME 3 continue refactoring notification scripts

---
 install/class/Class_Install.php               |   2 -
 install/scripts/testSmtp.php                  |   2 -
 .../batch/basket_event_stack.php              |   1 -
 .../batch/config/config.xml.default           |   5 -
 .../batch/load_basket_event_stack.php         |   1 -
 .../batch/load_process_email_stack.php        |   2 -
 .../batch/load_process_event_stack.php        |   1 -
 .../batch/load_stack_letterbox_alerts.php     |   1 -
 .../batch/process_event_stack.php             |  42 +-
 .../diffusion_type_controler_Abstract.php     |  50 +-
 .../datasources/letterbox_events.php          |   5 +-
 .../datasources/mlb_notes_content.php         |  24 +-
 .../templates/datasources/notif_events.php    |   7 +-
 sql/data_fr.sql                               |   6 +-
 .../group/models/PrivilegeModelAbstract.php   |   2 -
 .../controllers/DiffusionTypesController.php  | 622 ++++++++++++++++++
 .../controllers/NotificationController.php    |  42 +-
 .../models/NotificationModelAbstract.php      |  15 +-
 18 files changed, 701 insertions(+), 129 deletions(-)
 create mode 100644 src/app/notification/controllers/DiffusionTypesController.php

diff --git a/install/class/Class_Install.php b/install/class/Class_Install.php
index eae25893603..3f9fa0602f2 100755
--- a/install/class/Class_Install.php
+++ b/install/class/Class_Install.php
@@ -806,8 +806,6 @@ class Install extends functions
         $maarchUrl = $maarchUrl.'cs_'.$_SESSION['config']['databasename'].'/';
         $CONFIG->MaarchUrl    = $maarchUrl;
         $CONFIG->customID     = 'cs_'.$_SESSION['config']['databasename'];
-        $CONFIG->MaarchApps   = 'maarch_entreprise';
-        $CONFIG->TmpDirectory = realpath('.').'/modules/notifications/batch/tmp/';
 
         $res = $xmlconfig->asXML();
         $fp = @fopen(realpath('.').'/custom/cs_'.$_SESSION['config']['databasename'].'/modules/notifications/batch/config/config.xml', 'w+');
diff --git a/install/scripts/testSmtp.php b/install/scripts/testSmtp.php
index 7dc425aab8b..30100510d2e 100755
--- a/install/scripts/testSmtp.php
+++ b/install/scripts/testSmtp.php
@@ -40,8 +40,6 @@
      $maarchUrl = rtrim($chemin, "install");
      $maarchUrl = $maarchUrl . 'cs_'.$_SESSION['config']['databasename'].'/';
      $CONFIG->MaarchUrl = $maarchUrl;
-     $CONFIG->MaarchApps = 'maarch_entreprise';
-     $CONFIG->TmpDirectory = realpath('.').'/modules/notifications/batch/tmp/';
 
      $res = $xmlconfig->asXML();
      $fp = @fopen(realpath('.')."/custom/cs_".$_SESSION['config']['databasename']."/modules/notifications/batch/config/config.xml", "w+");
diff --git a/modules/notifications/batch/basket_event_stack.php b/modules/notifications/batch/basket_event_stack.php
index 8cdbdcb39f1..12be463a59b 100755
--- a/modules/notifications/batch/basket_event_stack.php
+++ b/modules/notifications/batch/basket_event_stack.php
@@ -191,7 +191,6 @@ while ($state != 'END') {
                         'events'       => $basket_list['events'],
                         'notification' => $notification,
                         'maarchUrl'    => $maarchUrl,
-                        'maarchApps'   => $maarchApps,
                         'coll_id'      => $coll_id,
                         'res_table'    => $coll_table,
                         'res_view'     => $coll_view,
diff --git a/modules/notifications/batch/config/config.xml.default b/modules/notifications/batch/config/config.xml.default
index f183af5ca56..5022b2e30a9 100755
--- a/modules/notifications/batch/config/config.xml.default
+++ b/modules/notifications/batch/config/config.xml.default
@@ -2,13 +2,8 @@
 <ROOT>
 <!-- le nom du fichier doit etre config.xml ou config_{custom_id}.xml -->
     <CONFIG>
-        <Lang>fr</Lang> <!-- fr, en-->
         <MaarchDirectory>/var/www/html/MaarchCourrier/</MaarchDirectory>
         <customID></customID>
         <MaarchUrl>http://preview.maarchcourrier.com</MaarchUrl>
-        <MaarchApps>maarch_entreprise</MaarchApps>
-        <TmpDirectory>/var/www/html/MaarchCourrier/modules/notifications/batch/tmp/</TmpDirectory>
-        <maxsize>5</maxsize> <!--In Mo: Taille maximum pour envoyer le courrier en pièce jointe afin d’éviter les erreurs du serveur mail-->
-        <maxitem>90</maxitem> <!-- Nombre de pièce jointe maximum à envoyer si transfert en pièce jointe-->
     </CONFIG>
 </ROOT>
diff --git a/modules/notifications/batch/load_basket_event_stack.php b/modules/notifications/batch/load_basket_event_stack.php
index 041b0540c9d..a5450780480 100755
--- a/modules/notifications/batch/load_basket_event_stack.php
+++ b/modules/notifications/batch/load_basket_event_stack.php
@@ -96,7 +96,6 @@ if ($customID <> '') {
 }
 chdir($maarchDirectory);
 $maarchUrl  = (string)$config->MaarchUrl;
-$maarchApps = (string) $config->MaarchApps;
 
 $GLOBALS['batchDirectory'] = $maarchDirectory . 'modules'
                            . DIRECTORY_SEPARATOR . 'notifications'
diff --git a/modules/notifications/batch/load_process_email_stack.php b/modules/notifications/batch/load_process_email_stack.php
index d50456f425d..5fb4da105c8 100755
--- a/modules/notifications/batch/load_process_email_stack.php
+++ b/modules/notifications/batch/load_process_email_stack.php
@@ -87,9 +87,7 @@ if ($customID <> '') {
     $customIDPath = $customID . '_';
 }
 chdir($maarchDirectory);
-$maarchApps = (string) $config->MaarchApps;
 
-$GLOBALS['TmpDirectory'] = (string)$config->TmpDirectory;
 $GLOBALS['batchDirectory'] = $GLOBALS['maarchDirectory'] . 'modules'
                            . DIRECTORY_SEPARATOR . 'notifications'
                            . DIRECTORY_SEPARATOR . 'batch';
diff --git a/modules/notifications/batch/load_process_event_stack.php b/modules/notifications/batch/load_process_event_stack.php
index f840f0cb1c1..58a08b0adc6 100755
--- a/modules/notifications/batch/load_process_event_stack.php
+++ b/modules/notifications/batch/load_process_event_stack.php
@@ -96,7 +96,6 @@ if ($customID <> '') {
 }
 chdir($maarchDirectory);
 $maarchUrl  = (string)$config->MaarchUrl;
-$maarchApps = (string) $config->MaarchApps;
 
 $GLOBALS['batchDirectory'] = $maarchDirectory . 'modules'
                            . DIRECTORY_SEPARATOR . 'notifications'
diff --git a/modules/notifications/batch/load_stack_letterbox_alerts.php b/modules/notifications/batch/load_stack_letterbox_alerts.php
index 7bf36329c9e..3bb7713ffa8 100755
--- a/modules/notifications/batch/load_stack_letterbox_alerts.php
+++ b/modules/notifications/batch/load_stack_letterbox_alerts.php
@@ -91,7 +91,6 @@ if ($customID <> '') {
 chdir($maarchDirectory);
 
 $maarchUrl = (string)$config->MaarchUrl;
-$maarchApps = (string) $config->MaarchApps;
 
 $GLOBALS['batchDirectory'] = $maarchDirectory . 'modules'
                            . DIRECTORY_SEPARATOR . 'notifications'
diff --git a/modules/notifications/batch/process_event_stack.php b/modules/notifications/batch/process_event_stack.php
index 6fbfda0414f..8b44b8c5dc8 100755
--- a/modules/notifications/batch/process_event_stack.php
+++ b/modules/notifications/batch/process_event_stack.php
@@ -62,15 +62,14 @@ while ($state != 'END') {
             foreach ($events as $event) {
                 Bt_writeLog(['level' => 'INFO', 'message' => "Getting recipients using diffusion type '".$notification['diffusion_type']."'"]);
                 // Diffusion type specific recipients
-                $recipients = array();
-                $recipients = $diffusion_type_controler->getRecipients($notification, $event);
+                $recipients = \Notification\controllers\DiffusionTypesController::getRecipients(['request' => 'recipients', 'notification' => $notification, 'event' => $event]);
                 // Diffusion type specific res_id
                 Bt_writeLog(['level' => 'INFO', 'message' => "Getting document ids using diffusion type '".$notification['diffusion_type']."'"]);
                 $res_id = false;
                 if ($event['table_name'] == $coll_table || $event['table_name'] == $coll_view) {
                     $res_id = $event['record_id'];
                 } else {
-                    $res_id = $diffusion_type_controler->getResId($notification, $event);
+                    $res_id = \Notification\controllers\DiffusionTypesController::getRecipients(['request' => 'res_id', 'notification' => $notification, 'event' => $event]);
                 }
                 $event['res_id'] = $res_id;
 
@@ -87,17 +86,14 @@ while ($state != 'END') {
                 Bt_writeLog(['level' => 'INFO', 'message' => $nbRecipients.' recipients found, checking active and absences']);
 
                 if ($notification['diffusion_type'] === 'dest_entity') {
-                    for ($i = 0; $i < $nbRecipients; ++$i) {
-                        $recipient = $recipients[$i];
-                        $entity_id = $recipient->entity_id;
+                    foreach ($recipients as $key => $recipient) {
+                        $entity_id = $recipient['entity_id'];
                         Bt_writeLog(['level' => 'INFO', 'message' => 'Recipient entity '.$entity_id]);
 
-                        $db = new Database();
-                        $query = 'SELECT param_value_int FROM parameters WHERE id = ?';
-                        $stmt = $db -> query($query, array('user_quota'));
-                        if (($recipient->enabled == 'N' && $stmt -> fetchColumn() == 0) || $recipient->mail == '') {
+                        $parameter = \Parameter\models\ParameterModel::getById(['select' => ['param_value_int'], 'id' => 'user_quota']);
+                        if (($recipient['enabled'] == 'N' && (empty($parameter) || $parameter['param_value_int'] == 0)) || $recipient['mail'] == '') {
                             Bt_writeLog(['level' => 'INFO', 'message' => $entity_id.' is disabled or mail is invalid, this notification will not be send']);
-                            unset($recipients[$i]);
+                            unset($recipients[$key]);
                             continue;
                         }
 
@@ -107,17 +103,14 @@ while ($state != 'END') {
                         $tmpNotifs[$entity_id]['events'][] = $event;
                     }
                 } else {
-                    for ($i = 0; $i < $nbRecipients; ++$i) {
-                        $recipient = $recipients[$i];
-                        $user_id = $recipient->user_id;
+                    foreach ($recipients as $key => $recipient) {
+                        $user_id = $recipient['user_id'];
                         Bt_writeLog(['level' => 'INFO', 'message' => 'Recipient '.$user_id]);
 
-                        $db = new Database();
-                        $query = 'SELECT param_value_int FROM parameters WHERE id = ?';
-                        $stmt = $db -> query($query, array('user_quota'));
-                        if (($recipient->status == 'SPD' && $stmt -> fetchColumn() == 0) || $recipient->status == 'DEL') {
+                        $parameter = \Parameter\models\ParameterModel::getById(['select' => ['param_value_int'], 'id' => 'user_quota']);
+                        if (($recipient['status'] == 'SPD' && (empty($parameter) || $parameter['param_value_int'] == 0)) || $recipient['status'] == 'DEL') {
                             Bt_writeLog(['level' => 'INFO', 'message' => $user_id.' is disabled or deleted, this notification will not be send']);
-                            unset($recipients[$i]);
+                            unset($recipients[$key]);
                             continue;
                         }
 
@@ -161,7 +154,6 @@ while ($state != 'END') {
                     'events'       => $tmpNotif['events'],
                     'notification' => $notification,
                     'maarchUrl'    => $maarchUrl,
-                    'maarchApps'   => $maarchApps,
                     'coll_id'      => $coll_id,
                     'res_table'    => $coll_table,
                     'res_view'     => $coll_view,
@@ -180,7 +172,7 @@ while ($state != 'END') {
                 }
 
                 // Prepare e-mail for stack
-                $recipient_mail = $tmpNotif['recipient']->mail;
+                $recipient_mail = $tmpNotif['recipient']['mail'];
                 $subject        = $notification['description'];
 
                 if (!empty($recipient_mail)) {
@@ -199,10 +191,10 @@ while ($state != 'END') {
                             if ($event['res_id'] != '') {
                                 $resourceToAttach = \Resource\models\ResModel::getById(['resId' => $event['res_id'], 'select' => ['path', 'filename', 'docserver_id']]);
                                 if (!empty($resourceToAttach['docserver_id'])) {
-                                    $docserver        = \Docserver\models\DocserverModel::getByDocserverId(['docserverId' => $resourceToAttach['docserver_id'], 'select' => ['path_template']]);
-                                    $path             = $docserver['path_template'] . str_replace('#', DIRECTORY_SEPARATOR, $resourceToAttach['path']) . $resourceToAttach['filename'];
-                                    $path = str_replace('//', '/', $path);
-                                    $path = str_replace('\\', '/', $path);
+                                    $docserver     = \Docserver\models\DocserverModel::getByDocserverId(['docserverId' => $resourceToAttach['docserver_id'], 'select' => ['path_template']]);
+                                    $path          = $docserver['path_template'] . str_replace('#', DIRECTORY_SEPARATOR, $resourceToAttach['path']) . $resourceToAttach['filename'];
+                                    $path          = str_replace('//', '/', $path);
+                                    $path          = str_replace('\\', '/', $path);
                                     $attachments[] = $path;
                                 }
                             }
diff --git a/modules/notifications/class/diffusion_type_controler_Abstract.php b/modules/notifications/class/diffusion_type_controler_Abstract.php
index 0c578d8126c..8be9ca101aa 100755
--- a/modules/notifications/class/diffusion_type_controler_Abstract.php
+++ b/modules/notifications/class/diffusion_type_controler_Abstract.php
@@ -41,8 +41,7 @@ try {
 /**
  * Class for controling docservers objects from database
  */
-abstract class diffusion_type_controler_Abstract
-    extends ObjectControler 
+abstract class diffusion_type_controler_Abstract extends ObjectControler
     //implements ObjectControlerIF
 {
     /**
@@ -51,22 +50,21 @@ abstract class diffusion_type_controler_Abstract
      * @param $id Id of event to get
      * @return event
      */
-    public function getAllDiffusion() {
+    public function getAllDiffusion()
+    {
         core_tools::load_lang();
         $return = array();
         $xmlfile = 'modules/notifications/xml/diffusion_type.xml';
-        $xmlfileCustom = $_SESSION['config']['corepath'] 
+        $xmlfileCustom = $_SESSION['config']['corepath']
             . 'custom/' . $_SESSION['custom_override_id'] . '/' . $xmlfile;
         if (file_exists($xmlfileCustom)) {
             $xmlfile = $xmlfileCustom;
         }
         $xmldiffusion = simplexml_load_file($xmlfile);
-        foreach($xmldiffusion->diffusion_type as $diffusion) {
-            //<id> <label> <script> 
-            
+        foreach ($xmldiffusion->diffusion_type as $diffusion) {
             $diffusion_type = new diffusion_type();
             
-            if(@constant((string) $diffusion->label)) {
+            if (@constant((string) $diffusion->label)) {
                 $label = constant((string)$diffusion->label);
             } else {
                 $label = (string) $diffusion->label;
@@ -86,45 +84,17 @@ abstract class diffusion_type_controler_Abstract
         }
     }
   
-    public function get($type_id) {
+    public function get($type_id)
+    {
         if ($type_id <> '') {
             $fulllist = array();
             $fulllist = $this->getAllDiffusion();
-            foreach ($fulllist as $dt_id => $dt)
-            {
-                if ($type_id == $dt_id){
+            foreach ($fulllist as $dt_id => $dt) {
+                if ($type_id == $dt_id) {
                     return $dt;
                 }
             }
         }
         return null;
     }
-   
-    public function getRecipients($notification, $event) 
-    {
-        $diffusionType = $this->get($notification->diffusion_type);
-        $request = 'recipients';
-        require($diffusionType->script);
-        return $recipients;
-    }
-    
-    public function getAttachFor($notification, $user_id) {
-        // No attachment defined
-        if($notification->attachfor_type == '') {
-            return false;
-        }
-        $attachforType = $this->get($notification->attachfor_type);
-        $request = 'attach';
-        require($attachforType->script);
-        return $attach;
-    }
-    
-    public function getResId($notification, $event) {
-        $diffusionType = $this->get($notification->diffusion_type);
-        $request = 'res_id';
-        require($diffusionType->script);
-        return $res_id;
-    }
-
 }
-
diff --git a/modules/templates/datasources/letterbox_events.php b/modules/templates/datasources/letterbox_events.php
index 33ea32e3f82..e5e13d3aea5 100755
--- a/modules/templates/datasources/letterbox_events.php
+++ b/modules/templates/datasources/letterbox_events.php
@@ -9,7 +9,6 @@
 /*
 * @requires
 *   $res_view   = Name of res view
-*   $maarchApps = name of app
 *   $maarchUrl  = Url to maarch (root url)
 *   $recipient  = recipient of notification
 *   $events     = array of events related to letterbox mails
@@ -30,7 +29,7 @@ $datasources['recipient'][0]  = (array) $recipient;
 $datasources['res_letterbox'] = [];
 $datasources['contact']       = [];
 
-$urlToApp = trim($maarchUrl, '/').'/apps/'.trim($maarchApps, '/').'/index.php?';
+$urlToApp = trim($maarchUrl, '/').'/apps/maarch_entreprise/index.php?';
 
 $basket = BasketModel::getByBasketId(['select' => ['id'], 'basketId' => 'MyBasket']);
 $preferenceBasket = UserBasketPreferenceModel::get([
@@ -106,6 +105,6 @@ foreach ($events as $event) {
         unset($postalAddress[0]);
         $contact['postal_address'] = implode("\n", $postalAddress);
 
-        $datasources['contact'][] = $contact;
+        $datasources['sender'][] = $contact;
     }
 }
diff --git a/modules/templates/datasources/mlb_notes_content.php b/modules/templates/datasources/mlb_notes_content.php
index 05b36682962..6548ee53e00 100755
--- a/modules/templates/datasources/mlb_notes_content.php
+++ b/modules/templates/datasources/mlb_notes_content.php
@@ -2,7 +2,6 @@
 /*
 * @requires
 *   $res_view	= Name of res view
-*   $maarchApps = name of app
 *   $maarchUrl	= Url to maarch (root url)
 * 	$recipient	= recipient of notification
 *	$events 	= array of events related to letterbox mails
@@ -23,6 +22,16 @@ use User\models\UserModel;
 $datasources['recipient'][0] = (array)$recipient;
 $datasources['notes'] = array();
 
+// Link to detail page
+$urlToApp = trim($maarchUrl, '/').'/apps/maarch_entreprise/index.php?';
+
+$basket = BasketModel::getByBasketId(['select' => ['id'], 'basketId' => 'MyBasket']);
+$preferenceBasket = UserBasketPreferenceModel::get([
+    'select'  => ['group_serial_id'],
+    'where'   => ['user_serial_id = ?', 'basket_id = ?'],
+    'data'    => [$recipient['user_id'], 'MyBasket']
+]);
+
 foreach ($events as $event) {
     $note = [];
     
@@ -41,16 +50,6 @@ foreach ($events as $event) {
         $resLetterbox = ResModel::getById(['select' => ['*'], 'resId'  => $resId]);
         $datasources['res_letterbox'][] = $resLetterbox;
     }
-    
-    // Link to detail page
-    $urlToApp = trim($maarchUrl, '/').'/apps/'.trim($maarchApps, '/').'/index.php?';
-
-    $basket = BasketModel::getByBasketId(['select' => ['id'], 'basketId' => 'MyBasket']);
-    $preferenceBasket = UserBasketPreferenceModel::get([
-        'select'  => ['group_serial_id'],
-        'where'   => ['user_serial_id = ?', 'basket_id = ?'],
-        'data'    => [$recipient['user_id'], 'MyBasket']
-    ]);
 
     $note['linktodoc']     = $urlToApp . 'linkToDoc='.$resId;
     $note['linktodetail']  = $urlToApp . 'linkToDetail='.$resId;
@@ -78,9 +77,8 @@ foreach ($events as $event) {
 
     if (!empty($resourceContacts)) {
         $contact = ContactModel::getById(['id' => $resourceContacts['item_id'], 'select' => ['*']]);
-        $datasources['contact'][] = $contact;
+        $datasources['sender'][] = $contact;
     }
     
-    // Insertion
     $datasources['notes'] = $note;
 }
diff --git a/modules/templates/datasources/notif_events.php b/modules/templates/datasources/notif_events.php
index 6f53b251c85..cea4e3d0737 100755
--- a/modules/templates/datasources/notif_events.php
+++ b/modules/templates/datasources/notif_events.php
@@ -6,15 +6,14 @@
 *   $recipient		= user recipient object
 *	$events			= array of notif_event objects
 *	$maarchUrl
-*	$maarchApps
 *	$coll_id
 *   $res_table
 *   $res_view
 *
 * @return datasources
-	[notification]	= one notification array
-	[recipient]		= one user recipient array
-	[events]		= array of events arrays
+    [notification]	= one notification array
+    [recipient]		= one user recipient array
+    [events]		= array of events arrays
 */
 
 $datasources['notification'][0] = (array)$notification;
diff --git a/sql/data_fr.sql b/sql/data_fr.sql
index 907c620dae5..45088089fbf 100755
--- a/sql/data_fr.sql
+++ b/sql/data_fr.sql
@@ -1279,7 +1279,7 @@ INSERT INTO templates (template_id, template_label, template_comment, template_c
 <td><font face="arial,helvetica,sans-serif" size="2">[res_letterbox.res_id]</font></td>
 <td><font face="arial,helvetica,sans-serif" size="2">[res_letterbox.typist]</font></td>
 <td>
-<p><font face="arial,helvetica,sans-serif" size="2">[res_letterbox.contact_society] [res_letterbox.contact_firstname] [res_letterbox.contact_lastname][res_letterbox.function][res_letterbox.address_num][res_letterbox.address_street][res_letterbox.address_postal_code][res_letterbox.address_town]</font></p>
+<p><font face="arial,helvetica,sans-serif" size="2">[sender.company] [sender.firstname] [sender.lastname][sender.function][sender.address_number][sender.address_street][sender.address_postcode][sender.address_town]</font></p>
 </td>
 <td><font face="arial,helvetica,sans-serif" size="2">[res_letterbox.doc_date;block=tr;frm=dd/mm/yyyy]</font></td>
 <td><font face="arial,helvetica,sans-serif" color="#FF0000"><strong><font size="2">[res_letterbox.subject]</font></strong></font></td>
@@ -1309,7 +1309,7 @@ INSERT INTO templates (template_id, template_label, template_comment, template_c
 <td><font face="arial,helvetica,sans-serif" size="2">[res_letterbox.res_id]</font></td>
 <td><font face="arial,helvetica,sans-serif" size="2">[res_letterbox.typist]</font></td>
 <td>
-<p><font face="arial,helvetica,sans-serif" size="2">[res_letterbox.contact_society] [res_letterbox.contact_firstname] [res_letterbox.contact_lastname][res_letterbox.function][res_letterbox.address_num][res_letterbox.address_street][res_letterbox.address_postal_code][res_letterbox.address_town]</font></p>
+<p><font face="arial,helvetica,sans-serif" size="2">[sender.company] [sender.firstname] [sender.lastname][sender.function][sender.address_number][sender.address_street][sender.address_postcode][sender.address_town]</font></p>
 </td>
 <td><font face="arial,helvetica,sans-serif" size="2">[res_letterbox.doc_date;block=tr;frm=dd/mm/yyyy]</font></td>
 <td><font face="arial,helvetica,sans-serif" color="#FF0000"><strong><font size="2">[res_letterbox.subject]</font></strong></font></td>
@@ -1335,7 +1335,7 @@ INSERT INTO templates (template_id, template_label, template_comment, template_c
 <tr>
 <td style="border: 1px solid #ddd; padding: 8px;">[res_letterbox.res_id]</td>
 <td style="border: 1px solid #ddd; padding: 8px;">[res_letterbox.typist]</td>
-<td style="border: 1px solid #ddd; padding: 8px;">[res_letterbox.contact_society] [res_letterbox.contact_firstname] [res_letterbox.contact_lastname][res_letterbox.function][res_letterbox.address_num][res_letterbox.address_street][res_letterbox.address_postal_code][res_letterbox.address_town]</td>
+<td style="border: 1px solid #ddd; padding: 8px;">[sender.company] [sender.firstname] [sender.lastname][sender.function][sender.address_number][sender.address_street][sender.address_postcode][sender.address_town]</td>
 <td style="border: 1px solid #ddd; padding: 8px;">[res_letterbox.doc_date;block=tr;frm=dd/mm/yyyy]</td>
 <td style="border: 1px solid #ddd; padding: 8px;">[res_letterbox.subject]</td>
 <td style="border: 1px solid #ddd; padding: 8px;">[res_letterbox.type_label]</td>
diff --git a/src/app/group/models/PrivilegeModelAbstract.php b/src/app/group/models/PrivilegeModelAbstract.php
index ee19cea7cfa..d17a716df8b 100644
--- a/src/app/group/models/PrivilegeModelAbstract.php
+++ b/src/app/group/models/PrivilegeModelAbstract.php
@@ -15,7 +15,6 @@ namespace Group\models;
 
 use SrcCore\models\DatabaseModel;
 use SrcCore\models\ValidatorModel;
-use User\models\UserGroupModel;
 
 abstract class PrivilegeModelAbstract
 {
@@ -153,6 +152,5 @@ abstract class PrivilegeModelAbstract
         ]);
 
         return true;
-
     }
 }
diff --git a/src/app/notification/controllers/DiffusionTypesController.php b/src/app/notification/controllers/DiffusionTypesController.php
new file mode 100644
index 00000000000..079992bd531
--- /dev/null
+++ b/src/app/notification/controllers/DiffusionTypesController.php
@@ -0,0 +1,622 @@
+<?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 Notifications Controller
+ *
+ * @author dev@maarch.org
+ * @ingroup notifications
+ */
+
+namespace Notification\controllers;
+
+use Notification\models\NotificationModel;
+use SrcCore\models\DatabaseModel;
+use User\models\UserModel;
+
+class DiffusionTypesController
+{
+    public function getRecipients($args = [])
+    {
+        $diffusionTypes = NotificationModel::getDiffusionType();
+        foreach ($diffusionTypes as $diffusionType) {
+            if ($diffusionType['id'] == $args['notification']['diffusionType']) {
+                $diffusionInfo = $diffusionType;
+                break;
+            }
+        }
+        $recipients = DiffusionTypesController::$diffusionInfo['function'](['request' => $args['request'], 'notification' => $args['notification']]);
+        return $recipients;
+    }
+
+    public function getRecipientsByContact($args = [])
+    {
+        if ($args['request'] == 'recipients') {
+            $contactsMatch = DatabaseModel::select([
+                'select'    => ['contact.id as user_id', 'contact.email as mail'],
+                'table'     => ['resource_contacts', 'contacts'],
+                'left_join' => ['resource_contacts.item_id = contacts.id'],
+                'where'     => ['res_id = ?', 'type = ?', 'mode = ?'],
+                'data'      => [$args['event']['record_id'], 'contact', 'sender']
+            ]);
+            return $contactsMatch;
+        } else {
+            return [];
+        }
+    }
+
+    public function getRecipientsByCopie($args = [])
+    {
+        switch ($request) {
+            case 'recipients':
+                $recipients = array();
+                $dbRecipients = new Database();
+        
+                // Copy to users
+                $select = 'SELECT distinct us.*';
+                $from = ' FROM listinstance li '
+                    .' JOIN users us ON li.item_id = us.user_id';
+                $where = " WHERE li.coll_id = 'letterbox_coll'   AND li.item_mode = 'cc'"
+                    ." AND item_type='user_id'";
+        
+                $arrayPDO = array(':recordid' => $event->record_id);
+        
+                switch ($event->table_name) {
+                    case 'notes':
+                        $from .= ' JOIN notes ON notes.identifier = li.res_id';
+                        $where .= ' AND notes.id = :recordid AND li.item_id != notes.user_id'
+                            .' AND ('
+                                .' notes.id not in (SELECT DISTINCT note_id FROM note_entities) '
+                                .' OR us.user_id IN (SELECT ue.user_id FROM note_entities ne JOIN users_entities ue ON ne.item_id = ue.entity_id WHERE ne.note_id = :recordid)'
+                            .')'
+                        ;
+                        break;
+        
+                    case 'res_letterbox':
+                    case 'res_view_letterbox':
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id';
+                        $where .= ' AND lb.res_id = :recordid';
+                        break;
+        
+                    case 'listinstance':
+                    default:
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id';
+                        $where .= " AND listinstance_id = :recordid AND lb.status not in ('INIT', 'AVAL') AND li.item_id <> :userid";
+                        $arrayPDO = array_merge($arrayPDO, array(':userid' => $event->user_id));
+                }
+        
+                $query = $select.$from.$where;
+        
+                $stmt = $dbRecipients->query($query, $arrayPDO);
+        
+                while ($recipient = $stmt->fetchObject()) {
+                    $recipients[] = $recipient;
+                }
+        
+                $arrayPDO = array(':recordid' => $event->record_id);
+                // Copy to entities
+                $select = 'SELECT distinct us.*';
+                $from = ' FROM listinstance li '
+                    .' LEFT JOIN users_entities ue ON li.item_id = ue.entity_id '
+                    .' JOIN users us ON ue.user_id = us.user_id';
+                $where = " WHERE li.coll_id = 'letterbox_coll'   AND li.item_mode = 'cc'"
+                    ." AND item_type='entity_id'";
+        
+                switch ($event->table_name) {
+                    case 'notes':
+                        $from .= ' JOIN notes ON notes.identifier = li.res_id';
+                        $where .= ' AND notes.id = :recordid AND li.item_id != notes.user_id'
+                            .' AND ('
+                                .' notes.id not in (SELECT DISTINCT note_id FROM note_entities) '
+                                .' OR us.user_id IN (SELECT ue.user_id FROM note_entities ne JOIN users_entities ue ON ne.item_id = ue.entity_id WHERE ne.note_id = :recordid)'
+                            .')'
+                        ;
+                        break;
+        
+                    case 'res_letterbox':
+                    case 'res_view_letterbox':
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id';
+                        $where .= ' AND lb.res_id = :recordid';
+                        break;
+        
+                    case 'listinstance':
+                    default:
+                        $where .= ' AND listinstance_id = :recordid';
+                }
+        
+                $query = $select.$from.$where;
+        
+                $stmt = $dbRecipients->query($query, $arrayPDO);
+        
+                while ($recipient = $stmt->fetchObject()) {
+                    $recipients[] = $recipient;
+                }
+                break;
+        
+            case 'res_id':
+                $arrayPDO = array(':recordid' => $event->record_id);
+                $select = 'SELECT li.res_id';
+                $from = ' FROM listinstance li';
+                $where = " WHERE li.coll_id = 'letterbox_coll'   ";
+        
+                switch ($event->table_name) {
+                    case 'notes':
+                        $from .= ' JOIN notes ON notes.identifier = li.res_id';
+                        $where .= ' AND notes.id = :recordid AND li.item_id != notes.user_id';
+                        break;
+        
+                    case 'res_letterbox':
+                    case 'res_view_letterbox':
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id';
+                        $where .= ' AND lb.res_id = :recordid';
+                        break;
+        
+                    case 'listinstance':
+                    default:
+                        $where .= ' AND listinstance_id = :recordid';
+                }
+        
+                $query = $query = $select.$from.$where;
+        
+                $dbResId = new Database();
+                $stmt = $dbResId->query($query, $arrayPDO);
+                $res_id_record = $stmt->fetchObject();
+                $res_id = $res_id_record->res_id;
+                break;
+        }
+    }
+
+    public function getRecipientsByDestEntity($args = [])
+    {
+        switch ($request) {
+            case 'recipients':
+                $recipients = array();
+                $dbRecipients = new Database();
+        
+                $select = 'SELECT distinct en.entity_id, en.enabled, en.email AS mail';
+                $from = ' FROM res_view_letterbox rvl JOIN entities en ON rvl.destination = en.entity_id';
+                $where = ' WHERE rvl.res_id = :recordid';
+        
+                $arrayPDO = array(':recordid' => $event->record_id);
+        
+                $query = $select.$from.$where;
+        
+                $stmt = $dbRecipients->query($query, $arrayPDO);
+        
+                while ($recipient = $stmt->fetchObject()) {
+                    $recipients[] = $recipient;
+                }
+                break;
+        
+            case 'res_id':
+                $select = 'SELECT li.res_id';
+                $from = ' FROM listinstance li';
+                $where = " WHERE li.coll_id = 'letterbox_coll'   ";
+        
+                $arrayPDO = array(':recordid' => $event->record_id);
+                switch ($event->table_name) {
+                    case 'notes':
+                        $from .= ' JOIN notes ON notes.identifier = li.res_id';
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = notes.identifier';
+                        $where .= ' AND notes.id = :recordid AND li.item_id != notes.user_id';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+                        break;
+        
+                    case 'res_letterbox':
+                    case 'res_view_letterbox':
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id';
+                        $where .= ' AND lb.res_id = :recordid';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+                        break;
+        
+                    case 'listinstance':
+                    default:
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id';
+                        $where .= ' AND listinstance_id = :recordid';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+                }
+        
+                $query = $query = $select.$from.$where;
+        
+                $dbResId = new Database();
+                $stmt = $dbResId->query($query, $arrayPDO);
+                $res_id_record = $stmt->fetchObject();
+                $res_id = $res_id_record->res_id;
+                break;
+        }
+    }
+
+    public function getRecipientsByDestUserSign($args = [])
+    {
+        switch ($request) {
+            case 'recipients':
+                $recipients = array();
+                $dbRecipients = new Database();
+        
+                $select = 'SELECT distinct us.*';
+                $from = ' FROM listinstance li JOIN users us ON li.item_id = us.user_id';
+                $where = " WHERE li.coll_id = 'letterbox_coll' AND li.item_mode = 'sign' "
+                    .'and process_date IS NULL ';
+        
+                $arrayPDO = array(':recordid' => $event->record_id);
+                switch ($event->table_name) {
+                    case 'notes':
+                        $from .= ' JOIN notes ON notes.identifier = li.res_id';
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = notes.identifier';
+                        $where .= ' AND notes.id = :recordid AND li.item_id != notes.user_id'
+                            .' AND ('
+                                .' notes.id not in (SELECT DISTINCT note_id FROM note_entities) '
+                                .' OR us.user_id IN (SELECT ue.user_id FROM note_entities ne JOIN '
+                                .' users_entities ue ON ne.item_id = ue.entity_id WHERE ne.note_id = :recordid)'
+                            .')';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+        
+                        break;
+        
+                    case 'res_letterbox':
+                    case 'res_view_letterbox':
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id';
+                        $where .= ' AND lb.res_id = :recordid';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+                        break;
+        
+                    case 'listinstance':
+                    default:
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id';
+                        $where .= ' AND listinstance_id = :recordid';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+                }
+        
+                $query = $select.$from.$where;
+        
+                $stmt = $dbRecipients->query($query, $arrayPDO);
+        
+                while ($recipient = $stmt->fetchObject()) {
+                    $recipients[] = $recipient;
+                }
+                break;
+        
+            case 'res_id':
+                $select = 'SELECT li.res_id';
+                $from = ' FROM listinstance li';
+                $where = " WHERE li.coll_id = 'letterbox_coll'   ";
+        
+                $arrayPDO = array(':recordid' => $event->record_id);
+                switch ($event->table_name) {
+                    case 'notes':
+                        $from .= ' JOIN notes ON notes.identifier = li.res_id';
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = notes.identifier';
+                        $where .= ' AND notes.id = :recordid AND li.item_id != notes.user_id';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+                        break;
+        
+                    case 'res_letterbox':
+                    case 'res_view_letterbox':
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id';
+                        $where .= ' AND lb.res_id = :recordid';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+                        break;
+        
+                    case 'listinstance':
+                    default:
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id';
+                        $where .= ' AND listinstance_id = :recordid';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+                }
+        
+                $query = $query = $select.$from.$where;
+        
+                $dbResId = new Database();
+                $stmt = $dbResId->query($query, $arrayPDO);
+                $res_id_record = $stmt->fetchObject();
+                $res_id = $res_id_record->res_id;
+                break;
+        }
+    }
+
+    public function getRecipientsByDestUserVisa($args = [])
+    {
+        switch ($request) {
+            case 'recipients':
+                $recipients = array();
+                $dbRecipients = new Database();
+        
+                $select = 'SELECT distinct us.*';
+                $from = ' FROM listinstance li JOIN users us ON li.item_id = us.user_id';
+                $where = " WHERE li.coll_id = 'letterbox_coll' AND li.item_mode = 'visa' "
+                    .'and process_date IS NULL ';
+        
+                $arrayPDO = array(':recordid' => $event->record_id);
+                switch ($event->table_name) {
+                    case 'notes':
+                        $from .= ' JOIN notes ON notes.identifier = li.res_id';
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = notes.identifier';
+                        $where .= ' AND notes.id = :recordid AND li.item_id != notes.user_id'
+                            .' AND ('
+                                .' notes.id not in (SELECT DISTINCT note_id FROM note_entities) '
+                                .' OR us.user_id IN (SELECT ue.user_id FROM note_entities ne JOIN '
+                                .' users_entities ue ON ne.item_id = ue.entity_id WHERE ne.note_id = :recordid)'
+                            .')';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+        
+                        break;
+        
+                    case 'res_letterbox':
+                    case 'res_view_letterbox':
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id';
+                        $where .= ' AND lb.res_id = :recordid';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+                        break;
+        
+                    case 'listinstance':
+                    default:
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id';
+                        $where .= ' AND listinstance_id = :recordid';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+                }
+        
+                $query = $select.$from.$where;
+        
+                $stmt = $dbRecipients->query($query, $arrayPDO);
+        
+                while ($recipient = $stmt->fetchObject()) {
+                    $recipients[] = $recipient;
+                }
+                break;
+        
+            case 'res_id':
+                $select = 'SELECT li.res_id';
+                $from = ' FROM listinstance li';
+                $where = " WHERE li.coll_id = 'letterbox_coll'   ";
+        
+                $arrayPDO = array(':recordid' => $event->record_id);
+                switch ($event->table_name) {
+                    case 'notes':
+                        $from .= ' JOIN notes ON notes.identifier = li.res_id';
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = notes.identifier';
+                        $where .= ' AND notes.id = :recordid AND li.item_id != notes.user_id';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+                        break;
+        
+                    case 'res_letterbox':
+                    case 'res_view_letterbox':
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id';
+                        $where .= ' AND lb.res_id = :recordid';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+                        break;
+        
+                    case 'listinstance':
+                    default:
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id';
+                        $where .= ' AND listinstance_id = :recordid';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+                }
+        
+                $query = $query = $select.$from.$where;
+        
+                $dbResId = new Database();
+                $stmt = $dbResId->query($query, $arrayPDO);
+                $res_id_record = $stmt->fetchObject();
+                $res_id = $res_id_record->res_id;
+                break;
+        }
+    }
+
+    public function getRecipientsByDestUser($args = [])
+    {
+        switch ($request) {
+            case 'recipients':
+                $recipients = array();
+                $dbRecipients = new Database();
+        
+                $select = 'SELECT distinct us.*';
+                $from = ' FROM listinstance li JOIN users us ON li.item_id = us.user_id';
+                $where = " WHERE li.item_mode = 'dest'";
+        
+                $arrayPDO = array(':recordid' => $event->record_id);
+                switch ($event->table_name) {
+                    case 'notes':
+                        $from .= ' JOIN notes ON notes.identifier = li.res_id';
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = notes.identifier';
+                        $where .= ' AND notes.id = :recordid AND us.id != notes.user_id'
+                            .' AND ('
+                                .' notes.id not in (SELECT DISTINCT note_id FROM note_entities) '
+                                .' OR us.user_id IN (SELECT ue.user_id FROM note_entities ne JOIN users_entities ue ON ne.item_id = ue.entity_id WHERE ne.note_id = :recordid)'
+                            .')';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+        
+                        break;
+        
+                    case 'res_letterbox':
+                    case 'res_view_letterbox':
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id';
+                        $where .= ' AND lb.res_id = :recordid';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+                        break;
+        
+                    case 'listinstance':
+                    default:
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id';
+                        $where .= ' AND listinstance_id = :recordid';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+                }
+        
+                $query = $select.$from.$where;
+        
+                $stmt = $dbRecipients->query($query, $arrayPDO);
+        
+                while ($recipient = $stmt->fetchObject()) {
+                    $recipients[] = $recipient;
+                }
+                break;
+        
+            case 'res_id':
+                $select = 'SELECT li.res_id';
+                $from = ' FROM listinstance li JOIN users us ON li.item_id = us.user_id';
+                $where = " WHERE ";
+        
+                $arrayPDO = array(':recordid' => $event->record_id);
+                switch ($event->table_name) {
+                    case 'notes':
+                        $from .= ' JOIN notes ON notes.identifier = li.res_id';
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = notes.identifier';
+                        $where .= ' notes.id = :recordid AND us.id != notes.user_id';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+                        break;
+        
+                    case 'res_letterbox':
+                    case 'res_view_letterbox':
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id';
+                        $where .= ' lb.res_id = :recordid';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+                        break;
+        
+                    case 'listinstance':
+                    default:
+                        $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id';
+                        $where .= ' listinstance_id = :recordid';
+                        if ($notification->diffusion_properties != '') {
+                            $status_tab = explode(',', $notification->diffusion_properties);
+                            $where .= ' AND lb.status in (:statustab)';
+                            $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab));
+                        }
+                }
+        
+                $query = $query = $select.$from.$where;
+        
+                $dbResId = new Database();
+                $stmt = $dbResId->query($query, $arrayPDO);
+                $res_id_record = $stmt->fetchObject();
+                $res_id = $res_id_record->res_id;
+                break;
+        }
+    }
+
+    public function getRecipientsByEntity($args = [])
+    {
+        if ($args['request'] == 'recipients') {
+            $aEntities  = explode(",", $args['notification']['diffusion_properties']);
+            $recipients = DatabaseModel::select([
+                'select'    => ['users.*'],
+                'table'     => ['users_entities, users'],
+                'where'     => ['users_entities.entity_id in (?)', 'users_entities.user_id = users.id', 'users.status != ?'],
+                'data'      => [$aEntities, 'DEL']
+            ]);
+            return $recipients;
+        } else {
+            return [];
+        }
+    }
+
+    public function getRecipientsByGroup($args = [])
+    {
+        if ($args['request'] == 'recipients') {
+            $aGroups  = explode(",", $args['notification']['diffusion_properties']);
+            $recipients = DatabaseModel::select([
+                'select'    => ['us.*'],
+                'table'     => ['usergroup_content ug, users us, usergroups'],
+                'where'     => ['us.id = ug.user_id', 'ug.group_id = usergroups.group_id', 'usergroups.group_id in (?)', 'us.status != ?'],
+                'data'      => [$aGroups, 'DEL']
+            ]);
+            return $recipients;
+        } else {
+            return [];
+        }
+    }
+
+    public function getRecipientsByUser($args = [])
+    {
+        if ($args['request'] == 'recipients') {
+            $aUsers     = explode(",", $args['notification']['diffusion_properties']);
+            $recipients = UserModel::get(['select' => ['*'], 'where' => ['id in (?)'], 'data' => [$aUsers]]);
+            return $recipients;
+        } else {
+            return [];
+        }
+    }
+}
diff --git a/src/app/notification/controllers/NotificationController.php b/src/app/notification/controllers/NotificationController.php
index 62665f2a46c..31afcae8f42 100755
--- a/src/app/notification/controllers/NotificationController.php
+++ b/src/app/notification/controllers/NotificationController.php
@@ -61,13 +61,13 @@ class NotificationController
 
         $data = [];
 
-        $data['event'] = NotificationModel::getEvents();
-        $data['template'] = NotificationModel::getTemplate();
+        $data['event']         = NotificationModel::getEvents();
+        $data['template']      = NotificationModel::getTemplate();
         $data['diffusionType'] = NotificationModel::getDiffusionType();
-        $data['groups'] = NotificationModel::getDiffusionTypeGroups();
-        $data['users'] = NotificationModel::getDiffusionTypesUsers();
-        $data['entities'] = NotificationModel::getDiffusionTypeEntities();
-        $data['status'] = NotificationModel::getDiffusionTypeStatus();
+        $data['groups']        = NotificationModel::getDiffusionTypeGroups();
+        $data['users']         = NotificationModel::getDiffusionTypesUsers();
+        $data['entities']      = NotificationModel::getDiffusionTypeEntities();
+        $data['status']        = NotificationModel::getDiffusionTypeStatus();
 
         $notification['event_id'] = (string)$notification['event_id'];
         $notification['data'] = $data;
@@ -137,10 +137,10 @@ class NotificationController
 
             HistoryController::add([
                 'tableName' => 'notifications',
-                'recordId' => $data['notification_id'],
+                'recordId'  => $data['notification_id'],
                 'eventType' => 'ADD',
-                'eventId' => 'notificationsadd',
-                'info' => _ADD_NOTIFICATIONS.' : '.$data['notification_id'],
+                'eventId'   => 'notificationsadd',
+                'info'      => _ADD_NOTIFICATIONS.' : '.$data['notification_id'],
             ]);
 
             return $response->withJson(NotificationModel::getByNotificationId(['notificationId' => $data['notification_id']]));
@@ -178,10 +178,10 @@ class NotificationController
 
         HistoryController::add([
             'tableName' => 'notifications',
-            'recordId' => $data['notification_sid'],
+            'recordId'  => $data['notification_sid'],
             'eventType' => 'UP',
-            'eventId' => 'notificationsup',
-            'info' => _MODIFY_NOTIFICATIONS.' : '.$data['notification_sid'],
+            'eventId'   => 'notificationsup',
+            'info'      => _MODIFY_NOTIFICATIONS.' : '.$data['notification_sid'],
         ]);
 
         return $response->withJson(['notification' => $notification]);
@@ -203,10 +203,10 @@ class NotificationController
 
         HistoryController::add([
                 'tableName' => 'notifications',
-                'recordId' => $aArgs['id'],
+                'recordId'  => $aArgs['id'],
                 'eventType' => 'DEL',
-                'eventId' => 'notificationsdel',
-                'info' => _DELETE_NOTIFICATIONS.' : '.$aArgs['id'],
+                'eventId'   => 'notificationsdel',
+                'info'      => _DELETE_NOTIFICATIONS.' : '.$aArgs['id'],
             ]);
 
         if (PHP_OS == 'Linux') {
@@ -303,13 +303,13 @@ class NotificationController
         $notification['attachfor_properties'] = [];
         $data = [];
 
-        $data['event'] = NotificationModel::getEvents();
-        $data['template'] = NotificationModel::getTemplate();
+        $data['event']         = NotificationModel::getEvents();
+        $data['template']      = NotificationModel::getTemplate();
         $data['diffusionType'] = NotificationModel::getDiffusionType();
-        $data['groups'] = NotificationModel::getDiffusionTypeGroups();
-        $data['users'] = NotificationModel::getDiffusionTypesUsers();
-        $data['entities'] = NotificationModel::getDiffusionTypeEntities();
-        $data['status'] = NotificationModel::getDiffusionTypeStatus();
+        $data['groups']        = NotificationModel::getDiffusionTypeGroups();
+        $data['users']         = NotificationModel::getDiffusionTypesUsers();
+        $data['entities']      = NotificationModel::getDiffusionTypeEntities();
+        $data['status']        = NotificationModel::getDiffusionTypeStatus();
 
         $notification['data'] = $data;
 
diff --git a/src/app/notification/models/NotificationModelAbstract.php b/src/app/notification/models/NotificationModelAbstract.php
index 1cf4028bea0..e23fade5d92 100755
--- a/src/app/notification/models/NotificationModelAbstract.php
+++ b/src/app/notification/models/NotificationModelAbstract.php
@@ -115,7 +115,7 @@ abstract class NotificationModelAbstract
         ValidatorModel::notEmpty($aArgs, ['notification_sid']);
         ValidatorModel::intVal($aArgs, ['notification_sid']);
 
-        $notification_sid = $aArgs['notification_sid'];
+        $notificationSid = $aArgs['notification_sid'];
         unset($aArgs['data']);
         unset($aArgs['notification_sid']);
 
@@ -123,7 +123,7 @@ abstract class NotificationModelAbstract
             'table' => 'notifications',
             'set'   => $aArgs,
             'where' => ['notification_sid = ?'],
-            'data'  => [$notification_sid],
+            'data'  => [$notificationSid],
         ]);
 
         return $aReturn;
@@ -172,48 +172,57 @@ abstract class NotificationModelAbstract
             'id'             => 'group',
             'label'          => 'Groupe',
             'add_attachment' => 'true',
+            'function'       => 'getRecipientsByContact'
         );
         $diffusionTypes[] = array(
             'id'             => 'entity',
             'label'          => 'Entité',
             'add_attachment' => 'true',
+            'function'       => 'getRecipientsByCopie'
         );
         $diffusionTypes[] = array(
             'id'             => 'dest_entity',
             'label'          => 'Service de l\'utilisateur destinataire',
             'add_attachment' => 'false',
+            'function'       => 'getRecipientsByDestEntity'
         );
         $diffusionTypes[] = array(
             'id'             => 'dest_user',
             'label'          => 'Liste de diffusion du document',
             'add_attachment' => 'false',
+            'function'       => 'getRecipientsByDestUserSign'
         );
         $diffusionTypes[] = array(
             'id'             => 'dest_user_visa',
             'label'          => 'Viseur actuel du document',
             'add_attachment' => 'true',
+            'function'       => 'getRecipientsByDestUserVisa'
         );
         $diffusionTypes[] = array(
             'id'             => 'dest_user_sign',
             'label'          => 'Signataire actuel du document',
             'add_attachment' => 'true',
+            'function'       => 'getRecipientsByDestUser'
         );
         $diffusionTypes[] = array(
             'id'             => 'user',
             'label'          => 'Utilisateur désigné',
             'add_attachment' => 'true',
+            'function'       => 'getRecipientsByEntity'
         );
 
         $diffusionTypes[] = array(
             'id'             => 'copy_list',
             'label'          => 'Liste de diffusion du document',
             'add_attachment' => 'false',
+            'function'       => 'getRecipientsByGroup'
         );
 
         $diffusionTypes[] = array(
             'id'             => 'contact',
             'label'          => 'Contact du document',
-            'add_attachment' => 'true'
+            'add_attachment' => 'true',
+            'function'       => 'getRecipientsByUser'
         );
 
         return $diffusionTypes;
-- 
GitLab