From 477d510263699b14b5efba07b0307f128434e0d4 Mon Sep 17 00:00:00 2001
From: "florian.azizian" <florian.azizian@maarch.org>
Date: Wed, 8 Apr 2020 17:47:04 +0100
Subject: [PATCH] FEAT #13679 TIME 2:15 continue refactoring notification
 scripts

---
 .../retrieve_template_from_cm.php             |  73 -----
 .../batch/process_email_stack.php             |   9 +-
 .../class/templates_controler_Abstract.php    | 269 ------------------
 .../datasources/letterbox_events.php          | 110 -------
 .../datasources/mlb_notes_content.php         |  84 ------
 .../templates/datasources/notif_events.php    |  25 --
 modules/templates/xml/datasources.xml         |  21 --
 .../controllers/MergeController.php           |  25 +-
 .../DOMTemplateProcessorController.php        |  11 -
 .../history/controllers/HistoryController.php |   4 +-
 .../template/models/TemplateModelAbstract.php |  61 ++--
 .../controllers/AuthenticationController.php  |  40 +--
 .../app/template/TemplateControllerTest.php   |   4 +-
 .../VersionUpdateControllerTest.php           |   4 +-
 14 files changed, 76 insertions(+), 664 deletions(-)
 delete mode 100755 modules/content_management/retrieve_template_from_cm.php
 delete mode 100755 modules/templates/datasources/letterbox_events.php
 delete mode 100755 modules/templates/datasources/mlb_notes_content.php
 delete mode 100755 modules/templates/datasources/notif_events.php
 delete mode 100755 modules/templates/xml/datasources.xml

diff --git a/modules/content_management/retrieve_template_from_cm.php b/modules/content_management/retrieve_template_from_cm.php
deleted file mode 100755
index 11ceeeffef3..00000000000
--- a/modules/content_management/retrieve_template_from_cm.php
+++ /dev/null
@@ -1,73 +0,0 @@
-<?php
-
-//FOR ADD, UP TEMPLATES AND ADD ATTCHMENTS
-//case of template, templateStyle, or new attachment generation
-
-$func = new functions();
-
-if ($objectType == 'templateStyle') {
-    // a new template
-    $fileExtension = $func->extractFileExt($objectId);
-    $fileNameOnTmp = 'tmp_file_' . $_SESSION['user']['UserId']
-        . '_' . rand() . '.' . $fileExtension;
-    $filePathOnTmp = $_SESSION['config']['tmppath'] . $fileNameOnTmp;
-    if (!copy($objectId, $filePathOnTmp)) {
-        $result = array('ERROR' => _FAILED_TO_COPY_ON_TMP 
-            . ':' . $objectId . ' ' . $filePathOnTmp
-        );
-        createXML('ERROR', $result);
-    }
-} elseif ($objectType == 'template' || $objectType == 'attachmentFromTemplate' || $objectType == 'attachmentVersion' || $objectType == 'attachmentMailing' || $objectType == 'outgoingMail' || $objectType == 'transmission') {
-    if ($_SESSION['m_admin']['templates']['current_style'] <> '') {
-        // edition in progress
-        $fileExtension = $func->extractFileExt(
-            $_SESSION['m_admin']['templates']['current_style']
-        );
-        $filePathOnTmp = $_SESSION['m_admin']['templates']['current_style'];
-    } else {
-        //new attachment from a template
-        if (isset($_SESSION['cm']['resMaster']) && $_SESSION['cm']['resMaster'] <> '') {
-            $sec = new security();
-            $collId = $sec->retrieve_coll_id_from_table($objectTable);
-            $res_view = $sec->retrieve_view_from_table($objectTable);
-            $_SESSION['cm']['collId'] = $collId;
-        }
-        // new edition
-        require_once 'modules/templates/class/templates_controler.php';
-        $templateCtrl = new templates_controler();
-        $params = array(
-            'res_id' => $_SESSION['cm']['resMaster'],
-            'coll_id' => $_SESSION['cm']['collId'],
-            'res_view' => $res_view,
-            'res_table' => $objectTable,
-            'res_contact_id' => $_SESSION['cm']['contact_id'],
-            'res_address_id' => $_SESSION['cm']['address_id'],
-            'chronoAttachment' => $_SESSION['cm']['chronoAttachment']
-            );
-        if ($objectType == 'attachmentFromTemplate' || $objectType == 'attachmentVersion' || $objectType == 'outgoingMail' || $objectType == 'transmission') {
-            $filePathOnTmp = $templateCtrl->merge($objectId, $params, 'file');
-            $templateObj = $templateCtrl->get($objectId);
-            $_SESSION['cm']['templateStyle'] = $templateObj->template_style;
-        } elseif ($objectType == 'template') {
-            $filePathOnTmp = $templateCtrl->copyTemplateOnTmp($objectId);
-            if ($filePathOnTmp == '') {
-                $result = array('ERROR' => _FAILED_TO_COPY_ON_TMP 
-                    . ':' . $objectId . ' ' . $filePathOnTmp);
-                createXML('ERROR', $result);
-            }
-        } else if ($objectType == 'attachmentMailing') {
-            $params = array(
-                'res_id' => $_SESSION['cm']['resMaster'],
-                'coll_id' => $_SESSION['cm']['collId'],
-                'res_view' => $res_view,
-                'res_table' => $objectTable,
-                'chronoAttachment' => $_SESSION['cm']['chronoAttachment'],
-                'mailing' => true,
-                );
-            $filePathOnTmp = $templateCtrl->merge($objectId, $params, 'file');
-            $templateObj = $templateCtrl->get($objectId);
-            $_SESSION['cm']['templateStyle'] = $templateObj->template_style;
-        }
-        $fileExtension = $func->extractFileExt($filePathOnTmp);
-    }
-}
diff --git a/modules/notifications/batch/process_email_stack.php b/modules/notifications/batch/process_email_stack.php
index beb0a09f7e3..82b0d10e8e3 100755
--- a/modules/notifications/batch/process_email_stack.php
+++ b/modules/notifications/batch/process_email_stack.php
@@ -112,11 +112,12 @@ while ($state <> 'END') {
                 $phpmailer->SMTPDebug = 1;
                 $phpmailer->Debugoutput = function ($str) {
                     if (strpos($str, 'SMTP ERROR') !== false) {
-                        HistoryController::add([
+                        \History\controllers\HistoryController::add([
                             'tableName'    => 'emails',
                             'recordId'     => 'email',
                             'eventType'    => 'ERROR',
                             'eventId'      => 'sendEmail',
+                            'userId'       => 'superadmin',
                             'info'         => $str
                         ]);
                     }
@@ -137,7 +138,7 @@ while ($state <> 'END') {
                 \Notification\models\NotificationsEmailsModel::update([
                     'set'   => ['exec_date' => 'CURRENT_TIMESTAMP', 'exec_result' => $exec_result],
                     'where' => ['email_stack_sid = ?'],
-                    'data'  => [$email->email_stack_sid]
+                    'data'  => [$email['email_stack_sid']]
                 ]);
                 $state = 'SEND_AN_EMAIL';
             }
@@ -151,7 +152,9 @@ Bt_writeLog(['level' => 'INFO', 'message' => $emailSent.' notification(s) sent']
 Bt_writeLog(['level' => 'INFO', 'message' => 'End of process']);
 
 Bt_logInDataBase(
-    $totalEmailsToProcess, $err, $emailSent.' notification(s) sent'.$errTxt
+    $totalEmailsToProcess,
+    $err,
+    $emailSent.' notification(s) sent'.$errTxt
 );
 Bt_updateWorkBatch();
 
diff --git a/modules/templates/class/templates_controler_Abstract.php b/modules/templates/class/templates_controler_Abstract.php
index 90c9c2f7fbd..80eed6dca9d 100755
--- a/modules/templates/class/templates_controler_Abstract.php
+++ b/modules/templates/class/templates_controler_Abstract.php
@@ -516,30 +516,6 @@ abstract class templates_controler_Abstract extends ObjectControler implements O
         }
     }
     
-    public function getTemplatesDatasources($configXml)
-    {
-        $datasources = array();
-        //Browse all files of the style template dir
-        $xmlcontent = simplexml_load_file($configXml);
-        foreach ($xmlcontent->datasource as $datasource) {
-            //<id> <label> <script>
-            if (@constant((string) $datasource->label)) {
-                $label = constant((string)$datasource->label);
-            } else {
-                $label = (string) $datasource->label;
-            }
-            array_push(
-                $datasources,
-                array(
-                    'id' => (string)$datasource->id,
-                    'label'  => $label,
-                    'script' => (string)$datasource->script,
-                )
-            );
-        }
-        return $datasources;
-    }
-    
     //returns file ext
     public function extractFileExt($sFullPath)
     {
@@ -610,249 +586,4 @@ abstract class templates_controler_Abstract extends ObjectControler implements O
             }
         }
     }
-    
-    /**
-    * Make a copy of template to temp directory for merge process
-    *
-    * @param object $templateObj : template object
-    * @return string $templateCopyPath : path to working copy
-    */
-    protected function getWorkingCopy($templateObj)
-    {
-        if ($templateObj->template_type == 'HTML') {
-            $fileExtension = 'html';
-            $fileNameOnTmp = $_SESSION['config']['tmppath'] . 'tmp_template_' . $_SESSION['user']['UserId']
-            . '_' . rand() . '.' . $fileExtension;
-            $handle = fopen($fileNameOnTmp, 'w');
-            if (fwrite($handle, $templateObj->template_content) === false) {
-                return false;
-            }
-            fclose($handle);
-            return $fileNameOnTmp;
-        } elseif ($templateObj->template_type == 'TXT') {
-            $fileExtension = 'txt';
-            $fileNameOnTmp = $_SESSION['config']['tmppath'] . 'tmp_template_' . $_SESSION['user']['UserId']
-            . '_' . rand() . '.' . $fileExtension;
-            $handle = fopen($fileNameOnTmp, 'w');
-            if (fwrite($handle, $templateObj->template_content) === false) {
-                return false;
-            }
-            fclose($handle);
-            return $fileNameOnTmp;
-        } else {
-            $dbTemplate = new Database();
-            $query = "select path_template from " . _DOCSERVERS_TABLE_NAME
-                . " where docserver_id = 'TEMPLATES'";
-            $stmt = $dbTemplate->query($query);
-            $resDs = $stmt->fetchObject();
-            $pathToDs = $resDs->path_template;
-            $pathToTemplateOnDs = $pathToDs
-                . str_replace(
-                    "#",
-                    DIRECTORY_SEPARATOR,
-                    $templateObj->template_path
-                )
-                . $templateObj->template_file_name;
-            
-            return $pathToTemplateOnDs;
-        }
-    }
-    
-    protected function getDatasourceScript($datasourceId)
-    {
-        if ($datasourceId <> '') {
-            $xmlfile = 'modules/templates/xml/datasources.xml';
-            $xmlfileCustom = $_SESSION['config']['corepath']
-            . 'custom/' . $_SESSION['custom_override_id'] . '/' . $xmlfile;
-            
-            if (file_exists($xmlfileCustom)) {
-                $xmlfile = $xmlfileCustom;
-            }
-            $fulllist = $this->getTemplatesDatasources($xmlfile);
-            foreach ($fulllist as $ds) {
-                if ($datasourceId == $ds['id']) {
-                    return (object)$ds;
-                }
-            }
-        }
-        return null;
-    }
-    
-    protected function getBaseDatasources()
-    {
-        $datasources = array();
-        
-        // Date and time
-        $datasources['datetime'][0]['date'] = date('d-m-Y');
-        $datasources['datetime'][0]['time'] = date('H:i:s.u');
-        $datasources['datetime'][0]['timestamp'] = time();
-        
-        // Session
-        if (isset($_SESSION)) {
-            // Config (!!! database)
-            if (count($_SESSION['config']) > 0) {
-                $datasources['config'][0] = $_SESSION['config'];
-                $datasources['config'][0]['linktoapp'] = $_SESSION['config']['businessappurl']."index.php";
-            }
-            
-            // Current basket
-            if (!empty($_SESSION['current_basket']) && count($_SESSION['current_basket']) > 0) {
-                foreach ($_SESSION['current_basket'] as $name => $value) {
-                    if (!is_array($value)) {
-                        $datasources['basket'][0][$name] = $value;
-                    }
-                }
-            }
-            
-            // User
-            if (!empty($_SESSION['user']) && count($_SESSION['user']) > 0) {
-                foreach ($_SESSION['user'] as $name => $value) {
-                    if (!is_array($value)) {
-                        $datasources['user'][0][strtolower($name)] = $value;
-                    }
-                }
-                if (!empty($_SESSION['user']['entities']) && count($_SESSION['user']['entities']) > 0) {
-                    foreach ($_SESSION['user']['entities'] as $entity) {
-                        if ($entity['ENTITY_ID'] === $_SESSION['user']['primaryentity']['id']) {
-                            $datasources['user'][0]['entity'] = $_SESSION['user']['entities'][0]['ENTITY_LABEL'];
-                            $datasources['user'][0]['role'] = $_SESSION['user']['entities'][0]['ROLE'];
-                        }
-                    }
-                }
-            }
-        }
-        return $datasources;
-    }
-    
-    
-    /** Merge template with data from a datasource to the requested output
-    *
-    * @param string $templateId : templates identifier
-    * @param array $params : array of parameters for datasource retrieval
-    * @param string $outputType : save to 'file', retrieve 'content'
-    * @return merged content or path to file
-    */
-    public function merge($templateId, $params = array(), $outputType, $context = '')
-    {
-        include_once 'core/class/class_functions.php';
-        include_once 'modules/templates/templates_tables_definition.php';
-        include_once 'apps/maarch_entreprise/tools/tbs/tbs_class_php5.php';
-        include_once 'apps/maarch_entreprise/tools/tbs/tbs_plugin_opentbs.php';
-
-        $templateObj = $this->get($templateId);
-
-        // Get template path from docserver or copy HTML template to temp file
-        $pathToTemplate = $this->getWorkingCopy($templateObj);
-        $datasourceObj = $this->getDatasourceScript($templateObj->template_datasource);
- 
-        $datasources = $this->getBaseDatasources();
-        // Make params array for datasrouce script
-        foreach ($params as $paramName => $paramValue) {
-            $$paramName = $paramValue;
-        }
-        //Retrieve script for datasources
-        if ($datasourceObj->script) {
-            include $datasourceObj->script;
-        }
-        
-        // Merge with TBS
-        $TBS = new clsTinyButStrong;
-        $TBS->NoErr = true;
-        if ($templateObj->template_type == 'OFFICE') {
-            $TBS->Plugin(TBS_INSTALL, OPENTBS_PLUGIN);
-            $TBS->LoadTemplate($pathToTemplate, OPENTBS_ALREADY_UTF8);
-        } else {
-            $TBS->LoadTemplate($pathToTemplate);
-        }
-        
-        $ext = strrchr($pathToTemplate, '.');
-        foreach ($datasources as $name => $datasource) {
-            // Scalar values or arrays ?
-            if (!is_array($datasource)) {
-                $TBS->MergeField($name, $datasource);
-            } else {
-                $TBS->MergeBlock($name, 'array', $datasource);
-            }
-        }
-
-        if ($ext) {
-            if ($ext === '.odt') {
-                $TBS->LoadTemplate('#styles.xml');
-            } elseif ($ext === '.docx') {
-                $TBS->LoadTemplate('#word/header1.xml');
-            }
-
-            foreach ($datasources as $name => $datasource) {
-                // Scalar values or arrays ?
-                if (!is_array($datasource)) {
-                    $TBS->MergeField($name, $datasource);
-                } else {
-                    $TBS->MergeBlock($name, 'array', $datasource);
-                }
-            }
-
-            if ($ext === '.docx') {
-                $TBS->LoadTemplate('#word/footer1.xml');
-                foreach ($datasources as $name => $datasource) {
-                    // Scalar values or arrays ?
-                    if (!is_array($datasource)) {
-                        $TBS->MergeField($name, $datasource);
-                    } else {
-                        $TBS->MergeBlock($name, 'array', $datasource);
-                    }
-                }
-            }
-        }
-
-
-        switch ($outputType) {
-        case 'content':
-            if ($templateObj->template_type == 'OFFICE') {
-                $TBS->Show(OPENTBS_STRING);
-            } else {
-                $TBS->Show(TBS_NOTHING);
-            }
-            $myContent = $TBS->Source;
-            return $myContent;
-            
-        case 'file':
-            $func = new functions();
-            $fileExtension = $func->extractFileExt($pathToTemplate);
-            $fileNameOnTmp = 'tmp_file_' . $_SESSION['user']['UserId']
-            . '_' . rand() . '.' . $fileExtension;
-            $myFile = $_SESSION['config']['tmppath'] . $fileNameOnTmp;
-            if ($templateObj->template_type == 'OFFICE') {
-                $TBS->Show(OPENTBS_FILE, $myFile);
-            } else {
-                $TBS->Show(TBS_NOTHING);
-                $myContent = $TBS->Source;
-                $handle = fopen($myFile, 'w');
-                fwrite($handle, $myContent);
-                fclose($handle);
-            }
-            return $myFile;
-        }
-    }
-    
-    /** Copy a template master on tmp dir
-    *
-    * @param string $templateId : templates identifier
-    * @return string path of the template in tmp dir
-    */
-    public function copyTemplateOnTmp($templateId)
-    {
-        $templateObj = $this->get($templateId);
-        // Get template path from docserver
-        $pathToTemplate = $this->getWorkingCopy($templateObj);
-        $fileExtension = $this->extractFileExt($pathToTemplate);
-        $fileNameOnTmp = 'tmp_file_' . $_SESSION['user']['UserId']
-            . '_' . rand() . '.' . $fileExtension;
-        $filePathOnTmp = $_SESSION['config']['tmppath'] . $fileNameOnTmp;
-        // Copy the template from the DS to the tmp dir
-        if (!copy($pathToTemplate, $filePathOnTmp)) {
-            return '';
-        } else {
-            return $filePathOnTmp;
-        }
-    }
 }
diff --git a/modules/templates/datasources/letterbox_events.php b/modules/templates/datasources/letterbox_events.php
deleted file mode 100755
index e5e13d3aea5..00000000000
--- a/modules/templates/datasources/letterbox_events.php
+++ /dev/null
@@ -1,110 +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.
- */
-
-/*
-* @requires
-*   $res_view   = Name of res view
-*   $maarchUrl  = Url to maarch (root url)
-*   $recipient  = recipient of notification
-*   $events     = array of events related to letterbox mails
-*
-* @returns
-    [res_letterbox] = record of view + link to detail/doc page
-*/
-
-use Basket\models\BasketModel;
-use Contact\controllers\ContactController;
-use Contact\models\ContactModel;
-use Entity\models\EntityModel;
-use Resource\models\ResourceContactModel;
-use SrcCore\models\DatabaseModel;
-use User\models\UserBasketPreferenceModel;
-
-$datasources['recipient'][0]  = (array) $recipient;
-$datasources['res_letterbox'] = [];
-$datasources['contact']       = [];
-
-$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['id'], 'MyBasket']
-]);
-
-foreach ($events as $event) {
-    $table    = [$res_view . ' lb'];
-    $leftJoin = [];
-    $where    = [];
-    $arrayPDO = [];
-
-    switch ($event['table_name']) {
-        case 'notes':
-            $table[]    = 'notes';
-            $leftJoin[] = 'notes.identifier = lb.res_id';
-            $where[]    = 'notes.id = ?';
-            $arrayPDO[] = $event['record_id'];
-            break;
-
-        case 'listinstance':
-            $table[]    = 'listinstance li';
-            $leftJoin[] = 'lb.res_id = li.res_id';
-            $where[]    = 'listinstance_id = ?';
-            $arrayPDO[] = $event['record_id'];
-            break;
-
-        case 'res_letterbox':
-        case 'res_view_letterbox':
-        default:
-            $where[]    = 'lb.res_id = ?';
-            $arrayPDO[] = $event['record_id'];
-    }
-
-    // Main document resource from view
-    $res = DatabaseModel::select([
-        'select'    => ['lb.*'],
-        'table'     => $table,
-        'left_join' => $leftJoin,
-        'where'     => $where,
-        'data'      => $arrayPDO,
-    ])[0];
-
-    // Lien vers la page detail
-    $res['linktodoc']     = $urlToApp . 'linkToDoc='.$res['res_id'];
-    $res['linktodetail']  = $urlToApp . 'linkToDetail='.$res['res_id'];
-    if (!empty($res['res_id']) && !empty($preferenceBasket[0]['group_serial_id']) && !empty($basket['id']) && !empty($recipient['user_id'])) {
-        $res['linktoprocess'] = $urlToApp . 'linkToProcess='.$res['res_id'].'&groupId='.$preferenceBasket[0]['group_serial_id'].'&basketId='.$basket['id'].'&userId='.$recipient['user_id'];
-    }
-
-    if (!empty($res['initiator'])) {
-        $entityInfo = EntityModel::getByEntityId(['select' => ['*'], 'entityId' => $res['initiator']]);
-        foreach ($entityInfo as $key => $value) {
-            $res['initiator_'.$key] = $value;
-        }
-    }
-
-    $datasources['res_letterbox'][] = $res;
-
-    $resourceContacts = ResourceContactModel::get([
-        'where' => ['res_id = ?', "mode='sender'", "type='contact'"],
-        'data'  => [$res['res_id']],
-        'limit' => 1
-    ]);
-    $resourceContacts = $resourceContacts[0];
-
-    if (!empty($resourceContacts)) {
-        $contact = ContactModel::getById(['id' => $resourceContacts['item_id'], 'select' => ['*']]);
-
-        $postalAddress = ContactController::getContactAfnor($contact);
-        unset($postalAddress[0]);
-        $contact['postal_address'] = implode("\n", $postalAddress);
-
-        $datasources['sender'][] = $contact;
-    }
-}
diff --git a/modules/templates/datasources/mlb_notes_content.php b/modules/templates/datasources/mlb_notes_content.php
deleted file mode 100755
index 6548ee53e00..00000000000
--- a/modules/templates/datasources/mlb_notes_content.php
+++ /dev/null
@@ -1,84 +0,0 @@
-<?php
-/*
-* @requires
-*   $res_view	= Name of res view
-*   $maarchUrl	= Url to maarch (root url)
-* 	$recipient	= recipient of notification
-*	$events 	= array of events related to letterbox mails
-*
-* @returns
-    [notes] = detail of notes added
-*/
-
-use Basket\models\BasketModel;
-use Contact\models\ContactModel;
-use Note\models\NoteModel;
-use Resource\models\ResModel;
-use Resource\models\ResourceContactModel;
-use SrcCore\models\DatabaseModel;
-use SrcCore\models\TextFormatModel;
-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 = [];
-    
-    if ($event['table_name'] != 'notes') {
-        $note = DatabaseModel::select([
-            'select'    => ['mlb.*', 'notes.*', 'users.*'],
-            'table'     => ['listinstance', $res_view . ' mlb', 'notes', 'users'],
-            'left_join' => ['mlb.res_id = li.res_id', 'notes.identifier = li.res_id', 'users.id = notes.user_id'],
-            'where'     => ['li.item_id = ?', 'li.item_mode = \'dest\'', 'li.item_type = \'user_id\'', 'li.res_id = ?'],
-            'data'      => [$recipient['user_id'], $event['record_id']],
-        ])[0];
-        $resId = $note['identifier'];
-    } else {
-        $note         = NoteModel::getById(['id' => $event['record_id']]);
-        $resId        = $note['identifier'];
-        $resLetterbox = ResModel::getById(['select' => ['*'], 'resId'  => $resId]);
-        $datasources['res_letterbox'][] = $resLetterbox;
-    }
-
-    $note['linktodoc']     = $urlToApp . 'linkToDoc='.$resId;
-    $note['linktodetail']  = $urlToApp . 'linkToDetail='.$resId;
-
-    if (!empty($resId) && !empty($preferenceBasket[0]['group_serial_id']) && !empty($basket['id']) && !empty($recipient['user_id'])) {
-        $note['linktoprocess'] = $urlToApp . 'linkToProcess='.$resId.'&groupId='.$preferenceBasket[0]['group_serial_id'].'&basketId='.$basket['id'].'&userId='.$recipient['user_id'];
-    }
-
-    $resourceContacts = ResourceContactModel::get([
-        'where' => ['res_id = ?', "type = 'contact'", "mode = 'sender'"],
-        'data'  => [$resId],
-        'limit' => 1
-    ]);
-    $resourceContacts = $resourceContacts[0];
-
-    if ($event['table_name'] == 'notes') {
-        $datasources['res_letterbox'][0]['linktodoc']     = $note['linktodoc'];
-        $datasources['res_letterbox'][0]['linktodetail']  = $note['linktodetail'];
-        $datasources['res_letterbox'][0]['linktoprocess'] = $note['linktodoc'];
-
-        $labelledUser = UserModel::getLabelledUserById(['id' => $note['user_id']]);
-        $creationDate = TextFormatModel::formatDate($note['creation_date'], 'd/m/Y');
-        $note = "{$labelledUser}  {$creationDate} : {$note['note_text']}\n";
-    }
-
-    if (!empty($resourceContacts)) {
-        $contact = ContactModel::getById(['id' => $resourceContacts['item_id'], 'select' => ['*']]);
-        $datasources['sender'][] = $contact;
-    }
-    
-    $datasources['notes'] = $note;
-}
diff --git a/modules/templates/datasources/notif_events.php b/modules/templates/datasources/notif_events.php
deleted file mode 100755
index cea4e3d0737..00000000000
--- a/modules/templates/datasources/notif_events.php
+++ /dev/null
@@ -1,25 +0,0 @@
-<?php
-
-/*
-* @requires vars
-* 	$notification 	= notification object
-*   $recipient		= user recipient object
-*	$events			= array of notif_event objects
-*	$maarchUrl
-*	$coll_id
-*   $res_table
-*   $res_view
-*
-* @return datasources
-    [notification]	= one notification array
-    [recipient]		= one user recipient array
-    [events]		= array of events arrays
-*/
-
-$datasources['notification'][0] = (array)$notification;
-$datasources['recipient'][0]    = (array)$recipient;
-$datasources['events']          = [];
-
-foreach ($events as $event) {
-    $datasources['events'][] = (array)$event;
-}
diff --git a/modules/templates/xml/datasources.xml b/modules/templates/xml/datasources.xml
deleted file mode 100755
index 8c9ce2a32ef..00000000000
--- a/modules/templates/xml/datasources.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<root>
-	<datasource>
-		<id>notif_events</id>
-		<label>[notification] Informations événements systèmes</label>
-		<script>modules/templates/datasources/notif_events.php</script>
-		<target>notification</target>
-	</datasource>
-	<datasource>
-		<id>letterbox_events</id>
-		<label>[notification] Informations du courrier traité</label>
-		<script>modules/templates/datasources/letterbox_events.php</script>
-		<target>notification</target>
-	</datasource>
-	<datasource>
-		<id>notes</id>
-		<label>[notification] Informations sur notes associées au courrier</label>
-		<script>modules/templates/datasources/mlb_notes_content.php</script>
-		<target>notification</target>
-	</datasource>
-</root>
diff --git a/src/app/contentManagement/controllers/MergeController.php b/src/app/contentManagement/controllers/MergeController.php
index f4099825985..3599d236664 100644
--- a/src/app/contentManagement/controllers/MergeController.php
+++ b/src/app/contentManagement/controllers/MergeController.php
@@ -26,6 +26,7 @@ use Resource\models\ResourceContactModel;
 use SrcCore\models\CoreConfigModel;
 use SrcCore\models\TextFormatModel;
 use SrcCore\models\ValidatorModel;
+use Template\controllers\DatasourceController;
 use Template\models\TemplateModel;
 use User\models\UserModel;
 
@@ -404,12 +405,12 @@ class MergeController
     */
     public static function mergeNotification(array $args)
     {
-        $templateInfo = TemplateModel::getById(['id' => $args['templateId']]);
+        $templateInfo                     = TemplateModel::getById(['id' => $args['templateId']]);
         $templateInfo['template_content'] = str_replace('###', ';', $templateInfo['template_content']);
         $templateInfo['template_content'] = str_replace('___', '--', $templateInfo['template_content']);
-        $tmpPath      = CoreConfigModel::getTmpPath();
-        $pathToTemplate = $tmpPath . 'tmp_template_' . rand()
-        . '_' . rand() . '.html';
+        $tmpPath                          = CoreConfigModel::getTmpPath();
+        $pathToTemplate                   = $tmpPath . 'tmp_template_' . rand() . '_' . rand() . '.html';
+
         $handle = fopen($pathToTemplate, 'w');
         if (fwrite($handle, $templateInfo['template_content']) === false) {
             return false;
@@ -417,20 +418,16 @@ class MergeController
         fclose($handle);
 
         $datasourceObj = TemplateModel::getDatasourceById(['id' => $templateInfo['template_datasource']]);
- 
+
+        if ($datasourceObj['function']) {
+            $function = $datasourceObj['function'];
+            $datasources = DatasourceController::$function(['params' => $args['params']]);
+        }
+
         $datasources['datetime'][0]['date'] = date('d-m-Y');
         $datasources['datetime'][0]['time'] = date('H:i:s.u');
         $datasources['datetime'][0]['timestamp'] = time();
         
-        // Make params array for datasource script
-        foreach ($args['params'] as $paramName => $paramValue) {
-            $$paramName = $paramValue;
-        }
-
-        if ($datasourceObj['script']) {
-            include $datasourceObj['script'];
-        }
-        
         $TBS = new \clsTinyButStrong;
         $TBS->NoErr = true;
         $TBS->LoadTemplate($pathToTemplate);
diff --git a/src/app/external/exportSeda/controllers/DOMTemplateProcessorController.php b/src/app/external/exportSeda/controllers/DOMTemplateProcessorController.php
index 29181160906..468e5d3754f 100755
--- a/src/app/external/exportSeda/controllers/DOMTemplateProcessorController.php
+++ b/src/app/external/exportSeda/controllers/DOMTemplateProcessorController.php
@@ -243,9 +243,6 @@ class DOMTemplateProcessorController extends \DOMXPath
 
         // Get type of value
         $type = gettype($value);
-        //var_dump($type);
-        //if (isset($instr->params['source']))
-        //    var_dump($instr->params['source']);
 
         switch (true) {
             // If value is scalar, merge text before Pi
@@ -587,10 +584,6 @@ class DOMTemplateProcessorController extends \DOMXPath
     ------------------------------------------------------------------------ */
     protected function &getData($instr, $source = null)
     {
-        //var_dump("getData");
-        //var_dump($instr);
-        //var_dump($source);
-
         $value = null;
 
         $steps = $instr->source;
@@ -635,9 +628,6 @@ class DOMTemplateProcessorController extends \DOMXPath
 
     protected function &stepData($step, $source)
     {
-        //var_dump("stepData");
-        //var_dump($step);
-        //var_dump("from " . gettype($source));
         $value = null;
         switch ($step[0]) {
             case 'func':
@@ -673,7 +663,6 @@ class DOMTemplateProcessorController extends \DOMXPath
 
             return $value;
         }
-        //var_dump($params);
         switch ($name) {
             // Callback functions
             case 'func':
diff --git a/src/app/history/controllers/HistoryController.php b/src/app/history/controllers/HistoryController.php
index 896f521b17c..1869571ac22 100755
--- a/src/app/history/controllers/HistoryController.php
+++ b/src/app/history/controllers/HistoryController.php
@@ -153,6 +153,8 @@ class HistoryController
             $aArgs['userId'] = $GLOBALS['login'];
         }
 
+        $user = UserModel::getBylogin(['select' => ['id'], 'login' => $aArgs['userId']]);
+
         HistoryModel::create([
             'tableName' => $aArgs['tableName'],
             'recordId'  => $aArgs['recordId'],
@@ -167,7 +169,7 @@ class HistoryController
             "eventId"   => $aArgs['eventId'],
             "tableName" => $aArgs['tableName'],
             "recordId"  => $aArgs['recordId'],
-            "userId"    => $GLOBALS['id'],
+            "userId"    => $user['id'],
             "info"      => $aArgs['info'],
         ]);
     }
diff --git a/src/app/template/models/TemplateModelAbstract.php b/src/app/template/models/TemplateModelAbstract.php
index f7a636e058c..6f7c5f5fd31 100755
--- a/src/app/template/models/TemplateModelAbstract.php
+++ b/src/app/template/models/TemplateModelAbstract.php
@@ -144,20 +144,26 @@ abstract class TemplateModelAbstract
 
     public static function getDatasources()
     {
-        $datasources = [];
-
-        $loadedXml = CoreConfigModel::getXmlLoaded(['path' => 'modules/templates/xml/datasources.xml']);
-        if ($loadedXml) {
-            foreach ($loadedXml->datasource as $value) {
-                $value = (array)$value;
-                $datasources[] = [
-                    'id'        => (string)$value['id'],
-                    'label'     => (string)$value['label'],
-                    'script'    => (string)$value['script'],
-                    'target'    => (string)$value['target'],
-                ];
-            }
-        }
+        $datasources = [
+            [
+                'id'        => 'notif_events',
+                'label'     => '[notification] Informations événements systèmes',
+                'function'  => 'notifEvents',
+                'target'    => 'notification',
+            ],
+            [
+                'id'        => 'letterbox_events',
+                'label'     => '[notification] Informations du courrier traité',
+                'function'  => 'letterboxEvents',
+                'target'    => 'notification',
+            ],
+            [
+                'id'        => 'notes',
+                'label'     => '[notification] Informations sur notes associées au courrier',
+                'function'  => 'noteEvents',
+                'target'    => 'notification',
+            ]
+        ];
 
         return $datasources;
     }
@@ -166,21 +172,18 @@ abstract class TemplateModelAbstract
     {
         ValidatorModel::notEmpty($aArgs, ['id']);
 
-        $datasource = [];
-
-        $loadedXml = CoreConfigModel::getXmlLoaded(['path' => 'modules/templates/xml/datasources.xml']);
-        if ($loadedXml) {
-            foreach ($loadedXml->datasource as $value) {
-                $value = (array)$value;
-                if ($value['id'] == $aArgs['id']) {
-                    $datasource = [
-                        'id'        => (string)$value['id'],
-                        'label'     => (string)$value['label'],
-                        'script'    => (string)$value['script'],
-                        'target'    => (string)$value['target'],
-                    ];
-                    break;
-                }
+        $datasources = TemplateModel::getDatasources();
+        $datasource  = [];
+
+        foreach ($datasources as $value) {
+            if ($value['id'] == $aArgs['id']) {
+                $datasource = [
+                    'id'        => $value['id'],
+                    'label'     => $value['label'],
+                    'function'  => $value['function'],
+                    'target'    => $value['target'],
+                ];
+                break;
             }
         }
 
diff --git a/src/core/controllers/AuthenticationController.php b/src/core/controllers/AuthenticationController.php
index aca33e8a7ff..08d8910e737 100755
--- a/src/core/controllers/AuthenticationController.php
+++ b/src/core/controllers/AuthenticationController.php
@@ -63,25 +63,25 @@ class AuthenticationController
                 }
             }
         } else {
-           if (!empty($authorizationHeaders)) {
-               $token = null;
-               foreach ($authorizationHeaders as $authorizationHeader) {
-                   if (strpos($authorizationHeader, 'Bearer') === 0) {
-                       $token = str_replace('Bearer ', '', $authorizationHeader);
-                   }
-               }
-               if (!empty($token)) {
-                   try {
-                       $jwt = (array)JWT::decode($token, CoreConfigModel::getEncryptKey(), ['HS256']);
-                   } catch (\Exception $e) {
-                       return null;
-                   }
-                   $jwt['user'] = (array)$jwt['user'];
-                   if (!empty($jwt) && !empty($jwt['user']['id'])) {
-                       $userId = $jwt['user']['id'];
-                   }
-               }
-           }
+            if (!empty($authorizationHeaders)) {
+                $token = null;
+                foreach ($authorizationHeaders as $authorizationHeader) {
+                    if (strpos($authorizationHeader, 'Bearer') === 0) {
+                        $token = str_replace('Bearer ', '', $authorizationHeader);
+                    }
+                }
+                if (!empty($token)) {
+                    try {
+                        $jwt = (array)JWT::decode($token, CoreConfigModel::getEncryptKey(), ['HS256']);
+                    } catch (\Exception $e) {
+                        return null;
+                    }
+                    $jwt['user'] = (array)$jwt['user'];
+                    if (!empty($jwt) && !empty($jwt['user']['id'])) {
+                        $userId = $jwt['user']['id'];
+                    }
+                }
+            }
         }
 
         if (!empty($userId)) {
@@ -173,7 +173,7 @@ class AuthenticationController
         if (!$check) {
             return $response->withStatus(400)->withJson(['errors' => 'Bad Request']);
         }
-        var_dump('ttotoi');
+
         $login = strtolower($body['login']);
         $authenticated = AuthenticationModel::authentication(['login' => $login, 'password' => $body['password']]);
         if (empty($authenticated)) {
diff --git a/test/unitTests/app/template/TemplateControllerTest.php b/test/unitTests/app/template/TemplateControllerTest.php
index 4145ae00710..48391a865a7 100755
--- a/test/unitTests/app/template/TemplateControllerTest.php
+++ b/test/unitTests/app/template/TemplateControllerTest.php
@@ -304,7 +304,7 @@ class TemplateControllerTest extends TestCase
         $this->assertNotNull($responseBody->datasources);
         $this->assertNotNull($responseBody->datasources[0]->id);
         $this->assertNotNull($responseBody->datasources[0]->label);
-        $this->assertNotNull($responseBody->datasources[0]->script);
+        $this->assertNotNull($responseBody->datasources[0]->function);
         $this->assertNotNull($responseBody->datasources[0]->target);
         $this->assertNotNull($responseBody->entities);
         $this->assertNotNull($responseBody->entities[0]->entity_id);
@@ -723,7 +723,7 @@ class TemplateControllerTest extends TestCase
         $this->assertNotNull($responseBody->datasources);
         $this->assertNotNull($responseBody->datasources[0]->id);
         $this->assertNotNull($responseBody->datasources[0]->label);
-        $this->assertNotNull($responseBody->datasources[0]->script);
+        $this->assertNotNull($responseBody->datasources[0]->function);
         $this->assertNotNull($responseBody->datasources[0]->target);
         $this->assertNotNull($responseBody->entities);
         $this->assertNotNull($responseBody->entities[0]->entity_id);
diff --git a/test/unitTests/app/versionUpdate/VersionUpdateControllerTest.php b/test/unitTests/app/versionUpdate/VersionUpdateControllerTest.php
index 38e8ff5652e..a0c8f82f0f1 100755
--- a/test/unitTests/app/versionUpdate/VersionUpdateControllerTest.php
+++ b/test/unitTests/app/versionUpdate/VersionUpdateControllerTest.php
@@ -25,12 +25,12 @@ class VersionUpdateControllerTest extends TestCase
         $this->assertNotNull($responseBody->currentVersion);
         $this->assertRegExp('/^\d{2}\.\d{2}\.\d+$/', $responseBody->currentVersion, 'Invalid current version');
 
-        if( $responseBody->lastAvailableMinorVersion != null ) {
+        if ($responseBody->lastAvailableMinorVersion != null) {
             $this->assertIsString($responseBody->lastAvailableMinorVersion);
             $this->assertRegExp('/^\d{2}\.\d{2}\.\d+$/', $responseBody->lastAvailableMinorVersion, 'Invalid available minor version');
         }
 
-        if( $responseBody->lastAvailableMajorVersion != null ) {
+        if ($responseBody->lastAvailableMajorVersion != null) {
             $this->assertIsString($responseBody->lastAvailableMajorVersion);
             $this->assertRegExp('/^\d{2}\.\d{2}\.\d+$/', $responseBody->lastAvailableMajorVersion, 'Invalid available major version');
         }
-- 
GitLab