From 8ad1b847c1cd303db62b6c13a14a1cbcb929fe85 Mon Sep 17 00:00:00 2001
From: "florian.azizian" <florian.azizian@maarch.org>
Date: Mon, 6 Apr 2020 18:52:26 +0100
Subject: [PATCH] FEAT #12520 TIME 6:30 Begin remove pear + refactoring
 notification scripts

---
 README.md                                     |   1 -
 install/lang/en.php                           |   3 -
 install/lang/fr.php                           |   3 -
 install/view/prerequisites_view.php           |  13 --
 .../batch/basket_event_stack.php              | 189 +++++++---------
 modules/notifications/batch/batch_tools.php   |  21 +-
 .../batch/load_basket_event_stack.php         | 213 ++++--------------
 .../NotificationsEventsModelAbstract.php      |  35 +++
 8 files changed, 176 insertions(+), 302 deletions(-)

diff --git a/README.md b/README.md
index 537b9f26674..375a9d91f3e 100755
--- a/README.md
+++ b/README.md
@@ -26,7 +26,6 @@ Documentation : https://docs.maarch.org/
 * PostgreSQL >= 9.6
 * PHP 7.2. 7.3, 7.4
    * Extensions PHP (adaptées à votre version de PHP) : PHP-[XSL](http://php.net/manual/en/book.xsl.php), PHP-[XML-RPC](http://php.net/manual/en/book.xmlrpc.php), PHP-[Gettext](http://php.net/manual/en/b$
-   * Bibliothèques pear/CLITools
 * [ImageMagick](http://imagemagick.org/), avec PHP-[ImageMagick](http://php.net/manual/en/book.imagick.php)
 * [Ghostscript](https://www.ghostscript.com/)
 * [wkhtmltopdf et wkhtmltoimage](http://wkhtmltopdf.org/downloads.html)
diff --git a/install/lang/en.php b/install/lang/en.php
index ce298305a90..c2ffc6458ff 100755
--- a/install/lang/en.php
+++ b/install/lang/en.php
@@ -178,9 +178,6 @@ if (!defined('_PEAR')) {
 if (!defined('_MIMETYPE')) {
     define('_MIMETYPE', 'MIME-TYPE');
 }
-if (!defined('_CLITOOLS')) {
-    define('_CLITOOLS', 'CLITools');
-}
 if (!defined('_ERROR_REPORTING')) {
     define('_ERROR_REPORTING', 'error_reporting = E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT');
 }
diff --git a/install/lang/fr.php b/install/lang/fr.php
index 0e51d0df621..06b8ad23a78 100755
--- a/install/lang/fr.php
+++ b/install/lang/fr.php
@@ -138,9 +138,6 @@ if (!defined('_PEAR')) {
 if (!defined('_MIMETYPE')) {
     define('_MIMETYPE', 'MIME-TYPE');
 }
-if (!defined('_CLITOOLS')) {
-    define('_CLITOOLS', 'CLITools');
-}
 if (!defined('_ERROR_REPORTING')) {
     define('_ERROR_REPORTING', 'error_reporting = E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT');
 }
diff --git a/install/view/prerequisites_view.php b/install/view/prerequisites_view.php
index cf3a0c6e8f0..4bac41e920c 100755
--- a/install/view/prerequisites_view.php
+++ b/install/view/prerequisites_view.php
@@ -279,19 +279,6 @@
                         <?php echo _PEAR;?>
                     </td>
                 </tr>
-                <tr>
-                    <td class="voyantPrerequisites">
-                        <?php echo $Class_Install->checkPrerequisites(
-                            $Class_Install->isPearRequirements(
-                                'Maarch_CLITools/FileHandler.php'
-                            ),
-                            true
-                        );?>
-                    </td>
-                    <td>
-                        <?php echo _CLITOOLS;?>
-                    </td>
-                </tr>
                 <tr>
                     <td>&nbsp;
 
diff --git a/modules/notifications/batch/basket_event_stack.php b/modules/notifications/batch/basket_event_stack.php
index fd8435b683f..915fcf88cd5 100755
--- a/modules/notifications/batch/basket_event_stack.php
+++ b/modules/notifications/batch/basket_event_stack.php
@@ -18,7 +18,7 @@ include 'load_basket_event_stack.php';
 $state = 'LOAD_NOTIFICATIONS';
 while ($state != 'END') {
     if (isset($logger)) {
-        $logger->write('STATE:'.$state, 'INFO');
+        Bt_writeLog(['level' => 'INFO', 'message' => 'STATE:'.$state]);
     }
     switch ($state) {
         /**********************************************************************/
@@ -26,18 +26,19 @@ while ($state != 'END') {
         /* Load notification defsidentified with notification id              */
         /**********************************************************************/
         case 'LOAD_NOTIFICATIONS':
-            $logger->write('Loading configuration for notification id '.$notificationId, 'INFO');
-            $notification = $notifications_controler->getByNotificationId($notificationId);
+            Bt_writeLog(['level' => 'INFO', 'message' => 'Loading configuration for notification id '.$notificationId]);
+            
+            $notification = \Notification\models\NotificationModel::getByNotificationId(['notificationId' => $notificationId, 'select' => ['*']]);
             if ($notification === false) {
                 Bt_exitBatch(1, "Notification '".$notificationId."' not found");
             }
-            if ($notification->is_enabled === 'N') {
+            if ($notification['is_enabled'] === 'N') {
                 Bt_exitBatch(100, "Notification '".$notificationId."' is disabled");
             }
             //Attach Mode ?
-            if (!empty($notification->attachfor_type) || $notification->attachfor_type != null) {
+            if (!empty($notification['attachfor_type']) || $notification['attachfor_type'] != null) {
                 $attachMode = true;
-                $logger->write('The document will be attached for each recipient', 'INFO');
+                Bt_writeLog(['level' => 'INFO', 'message' => 'The document will be attached for each recipient']);
             } else {
                 $attachMode = false;
             }
@@ -50,84 +51,78 @@ while ($state != 'END') {
         /**********************************************************************/
         case 'ADD_EVENTS':
             $db = new Database();
-            $secCtrl = new SecurityControler();
-            $entities = new entities();
 
-            $stmt = $db->query("SELECT basket_id, basket_clause FROM baskets WHERE flag_notif = 'Y'");
+            $baskets = \Basket\models\BasketModel::get(['select' => ['basket_id', 'basket_clause'], 'where' => ['flag_notif = ?'], 'data' => ['Y']]);
 
-            while ($line = $stmt->fetchObject()) {
-                $logger->write('BASKET: '.$line->basket_id.' in progess ...', 'INFO');
-                $exceptUsers[$line->basket_id] = [];
-                $stmt2 = $db->query('SELECT group_id FROM groupbasket WHERE basket_id = ?', array($line->basket_id));
+            foreach ($baskets as $basket) {
+                Bt_writeLog(['level' => 'INFO', 'message' => 'BASKET: '.$basket['basket_id'].' in progess ...']);
+                $exceptUsers[$basket['basket_id']] = [];
+                $groups = \Basket\models\GroupBasketModel::get(['select' => ['group_id'], 'where' => ['basket_id = ?'], 'data' => [$basket['basket_id']]]);
+                $nbGroups = count($groups);
 
                 $u = 1;
-                while ($line2 = $stmt2->fetchObject()) {
-                    $group = \Group\models\GroupModel::getByGroupId(['groupId' => $line2->group_id, 'select' => ['id']]);
-                    if ($notification->diffusion_type == 'groups') {
-                        $recipients = array();
-                        $recipients = $diffusion_type_controler->getRecipients($notification, '');
-                        $aRecipients = [];
-                        foreach ($recipients as $itemRecipient) {
-                            array_push($aRecipients, $itemRecipient->user_id);
-                        }
-                        if (empty($aRecipients)) {
-                            $aRecipients = '0=1';
-                        }
-                        $stmt3 = $db->query("SELECT users.user_id, users.id, users.status FROM usergroup_content, users WHERE group_id = ? and users.status in ('OK','ABS') and usergroup_content.user_id=users.id and users.user_id in (?)", array($group['id'], $aRecipients));
+                foreach ($groups as $group) {
+                    $groupInfo = \Group\models\GroupModel::getByGroupId(['groupId' => $group['group_id'], 'select' => ['id']]);
+                    if ($notification['diffusion_type'] == 'group') {
+                        $users = \Group\models\GroupModel::getUsersById(['select' => ['users.user_id', 'users.id'], 'id' => $groupInfo['id']]);
                     } else {
-                        $stmt3 = $db->query("SELECT users.user_id, users.id, users.status FROM usergroup_content, users WHERE group_id = ? and users.status in ('OK','ABS') and usergroup_content.user_id=users.id", array($group['id']));
+                        $users = \Group\models\GroupModel::getUsersById(['select' => ['users.user_id', 'users.id'], 'id' => 0]);
                     }
 
-                    $baskets_notif = array();
-                    $rowCount3 = $stmt3->rowCount();
-                    $logger->write('GROUP: '.$line2->group_id.' ... '.$rowCount3.' user(s) to notify', 'INFO');
+                    $countUsersToNotify = count($users);
+                    Bt_writeLog(['level' => 'INFO', 'message' => 'GROUP: '.$group['group_id'].' ... '.$countUsersToNotify.' user(s) to notify']);
                     $z = 1;
-                    while ($line3 = $stmt3->fetchObject()) {
+                    foreach ($users as $userToNotify) {
                         $real_user_id = '';
-                        $whereClause = $secCtrl->process_security_where_clause($line->basket_clause, $line3->user_id);
-                        $whereClause = $entities->process_where_clause($whereClause, $line3->user_id);
-                        $user_id = $line3->user_id;
-                        $group = \Group\models\GroupModel::getByGroupId(['select' => ['id'], 'groupId' => $line2->group_id]);
-                        $query = 'SELECT actual_user_id FROM redirected_baskets WHERE owner_user_id = ? AND basket_id = ? AND group_id = ?';
-                        $redirStmt = $db->query($query, array($line3->id, $line->basket_id, $group['id']));
-                        $queryResult = $redirStmt->fetchObject();
-                        if ($queryResult) {
+                        $whereClause  = \SrcCore\controllers\PreparedClauseController::getPreparedClause(['clause' => $basket['basket_clause'], 'login' => $userToNotify['user_id']]);
+                        $user_id      = $userToNotify['user_id'];
+                        $redirectedBasket = \Basket\models\RedirectBasketModel::get([
+                            'select'    => ['actual_user_id'],
+                            'where'     => ['owner_user_id = ?', 'basket_id = ?', 'group_id = ?'],
+                            'data'      => [$userToNotify['id'], $basket['basket_id'], $groupInfo['id']]
+                        ]);
+                        if (!empty($redirectedBasket)) {
                             $real_user_id = $user_id;
-                            $user = \User\models\UserModel::getById(['id' => $queryResult->actual_user_id, 'select' => ['user_id']]);
-                            $user_id = $user['user_id'];
+                            $user         = \User\models\UserModel::getById(['id' => $redirectedBasket[0]['actual_user_id'], 'select' => ['user_id']]);
+                            $user_id      = $user['user_id'];
                         }
 
-
-                        $stmt4 = $db->query('SELECT res_id FROM res_view_letterbox '.$whereClause);
-                        if (!empty($stmt4)) {
-                            $userNbDoc = $stmt4->rowCount();
-                            $logger->write($userNbDoc.' document(s) to process for '.$line3->user_id, 'INFO');
+                        $resources = \Resource\models\ResModel::getOnView([
+                            'select'    => ['res_id'],
+                            'where'     => [$whereClause],
+                            'data'      => []
+                        ]);
+                        if (!empty($resources)) {
+                            $userNbDoc = count($resources);
+                            Bt_writeLog(['level' => 'INFO', 'message' => $userNbDoc.' document(s) to process for '.$userToNotify['user_id']]);
                             $i = 1;
-                            $info = 'Notification ['.$line->basket_id.'] pour '.$line3->user_id;
+                            $info = 'Notification ['.$basket['basket_id'].'] pour '.$userToNotify['user_id'];
                             if (!empty($real_user_id)) {
-                                $stmt6 = $db->query('SELECT record_id FROM notif_event_stack WHERE event_info = ? and (user_id = ? OR user_id = ?)', array($info, $line3->user_id, $user_id));
+                                $notificationEvents = \Notification\models\NotificationsEventsModel::get(['select' => ['record_id'], 'where' => ['event_info', '(user_id = ? OR user_id = ?)'], 'data' => [$info, $userToNotify['user_id'], $user_id]]);
                             } else {
-                                $stmt6 = $db->query('SELECT record_id FROM notif_event_stack WHERE event_info = ? and user_id = ?', array($info, $line3->user_id));
+                                $notificationEvents = \Notification\models\NotificationsEventsModel::get(['select' => ['record_id'], 'where' => ['event_info', 'user_id = ?'], 'data' => [$info, $userToNotify['user_id']]]);
                             }
-                            $aRecordId = [];
-                            while ($line6 = $stmt6->fetchObject()) {
-                                $aRecordId[$line6->record_id] = $line6->record_id;
-                            }
-                            $queryValues = '';
-                            while ($line4 = $stmt4->fetchObject()) {
-                                echo 'DOCUMENT '.$i.'/'.$userNbDoc.' for USER '.$z.'/'.$rowCount3.' and GROUP '.$u.'/'.$stmt2->rowCount()."\n";
-                                if (empty($aRecordId[$line4->res_id])) {
-                                    $queryValues .= "('res_letterbox','500','".$line4->res_id."','".$user_id."','".$info."',CURRENT_DATE),";
-                                    preg_match_all('#\[(\w+)]#', $info, $result);
-                                    $basket_id = $result[1];
-                                    if (!in_array($basket_id[0], $baskets_notif)) {
-                                        $baskets_notif[] = $basket_id[0];
-                                    }
+
+                            $aValues = [];
+                            foreach ($resources as $resource) {
+                                echo 'DOCUMENT '.$i.'/'.$userNbDoc.' for USER '.$z.'/'.$countUsersToNotify.' and GROUP '.$u.'/'.$nbGroups."\n";
+                                if (empty($aRecordId[$resource['res_id']])) {
+                                    $aValues[] = [
+                                        'res_letterbox',
+                                        '500',
+                                        $resource['res_id'],
+                                        $user_id,
+                                        $info
+                                    ];
                                 }
                                 ++$i;
                             }
-                            if (!empty($queryValues)) {
-                                $db->query('INSERT INTO notif_event_stack (table_name, notification_sid, record_id, user_id, event_info, event_date) VALUES '.substr($queryValues, 0, -1));
+                            if (!empty($aValues)) {
+                                \SrcCore\models\DatabaseModel::insertMultiple([
+                                    'table'     => 'notif_event_stack',
+                                    'columns'   => ['table_name', 'notification_sid', 'record_id', 'user_id', 'event_info'],
+                                    'values'    => $aValues
+                                ]);
                             }
                         }
                         ++$z;
@@ -135,14 +130,14 @@ while ($state != 'END') {
                     ++$u;
                 }
             }
-            $logger->write('Scanning events for notification sid '.$notification->notification_sid, 'INFO');
-            $events = $events_controler->getEventsByNotificationSid('500');
+            Bt_writeLog(['level' => 'INFO', 'message' => 'Scanning events for notification sid '.$notification['notification_sid']]);
+            $events = \Notification\models\NotificationsEventsModel::getById(['select' => ['*'], 'notificationSid' => '500']);
             $totalEventsToProcess = count($events);
             $currentEvent = 0;
             if ($totalEventsToProcess === 0) {
                 Bt_exitBatch(0, 'No event to process');
             }
-            $logger->write($totalEventsToProcess.' event(s) to scan', 'INFO');
+            Bt_writeLog(['level' => 'INFO', 'message' => $totalEventsToProcess.' event(s) to scan']);
             $tmpNotifs = array();
             $state = 'SCAN_EVENT';
             break;
@@ -155,39 +150,32 @@ while ($state != 'END') {
             $i = 1;
 
             foreach ($events as $event) {
-                $logger->write('scanning EVENT : '.$i.'/'.$totalEventsToProcess.' (BASKET => '.$basket_id[0].', DOCUMENT => '.$res_id.', RECIPIENT => '.$user_id.')', 'INFO');
-                preg_match_all('#\[(\w+)]#', $event->event_info, $result);
+                preg_match_all('#\[(\w+)]#', $event['event_info'], $result);
                 $basket_id = $result[1];
-                //$logger->write("Basket => " .$basket_id[0], 'INFO');
+                Bt_writeLog(['level' => 'INFO', 'message' => 'scanning EVENT : '.$i.'/'.$totalEventsToProcess.' (BASKET => '.$basket_id[0].', DOCUMENT => '.$res_id.', RECIPIENT => '.$user_id.')']);
 
                 // Diffusion type specific res_id
                 $res_id = false;
-                if ($event->table_name == $coll_table || $event->table_name == $coll_view) {
-                    $res_id = $event->record_id;
+                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);
                 }
-                $event->res_id = $res_id;
 
-                //$logger->write('Document => ' . $res_id, 'INFO');
-                $user_id = $event->user_id;
-                //$logger->write('Recipient => ' . $user_id, 'INFO');
+                $event['res_id'] = $res_id;
+                $user_id = $event['user_id'];
 
                 if (!isset($tmpNotifs[$user_id])) {
-                    $query = 'SELECT * FROM users WHERE user_id = ?';
-                    $arrayPDO = array($user_id);
-                    $stmt = $db->query($query, $arrayPDO);
-                    $tmpNotifs[$user_id]['recipient'] = $stmt->fetchObject();
-                    //$tmpNotifs[$user_id]['recipient'] = $user_id;
+                    $tmpNotifs[$user_id]['recipient'] = \User\models\UserModel::getByLogin(['select' => ['*'], 'login' => $user_id]);
                 }
-                preg_match_all('#\[(\w+)]#', $event->event_info, $result);
+                preg_match_all('#\[(\w+)]#', $event['event_info'], $result);
                 $basket_id = $result[1];
                 $tmpNotifs[$user_id]['baskets'][$basket_id[0]]['events'][] = $event;
 
                 ++$i;
             }
             $totalNotificationsToProcess = count($tmpNotifs);
-            $logger->write($totalNotificationsToProcess.' notifications to process', 'INFO');
+            Bt_writeLog(['level' => 'INFO', 'message' => $totalNotificationsToProcess.' notifications to process']);
 
         /**********************************************************************/
         /*                      FILL_EMAIL_STACK                              */
@@ -196,29 +184,24 @@ while ($state != 'END') {
             $logger->write('STATE:MERGE NOTIF', 'INFO');
             $i = 1;
             foreach ($tmpNotifs as $user_id => $tmpNotif) {
-                foreach ($tmpNotif['baskets'] as $key => $basket_list) {
-                    $basketId = $key;
-                    $stmt6 = $db->query('SELECT basket_name FROM baskets WHERE basket_id = ?', array($key));
-                    $line6 = $stmt6->fetchObject();
-                    $subject = $line6->basket_name;
+                foreach ($tmpNotif['baskets'] as $basketId => $basket_list) {
+                    $baskets = \Basket\models\BasketModel::getByBasketId(['select' => ['basket_name'], 'basketId' => $basketId]);
+                    $subject = $baskets['basket_name'];
 
                     // Merge template with data and style
-                    $logger->write('generate e-mail '.$i.'/'.$totalNotificationsToProcess.' (TEMPLATE =>'.$notification->template_id.', SUBJECT => '.$subject.', RECIPIENT => '.$user_id.', DOCUMENT(S) => '.count($basket_list['events']), 'INFO');
-
-                    //$logger->write('Merging template #' . $notification->template_id
-                    //    . ' to basket '.$subject.' for user ' . $user_id . ' ('.count($basket_list['events']).' documents)', 'INFO');
+                    Bt_writeLog(['level' => 'INFO', 'message' => 'generate e-mail '.$i.'/'.$totalNotificationsToProcess.' (TEMPLATE =>'.$notification['template_id'].', SUBJECT => '.$subject.', RECIPIENT => '.$user_id.', DOCUMENT(S) => '.count($basket_list['events'])]);
 
                     $params = array(
-                        'recipient' => $tmpNotif['recipient'],
-                        'events' => $basket_list['events'],
+                        'recipient'    => $tmpNotif['recipient'],
+                        'events'       => $basket_list['events'],
                         'notification' => $notification,
-                        'maarchUrl' => $maarchUrl,
-                        'maarchApps' => $maarchApps,
-                        'coll_id' => $coll_id,
-                        'res_table' => $coll_table,
-                        'res_view' => $coll_view,
+                        'maarchUrl'    => $maarchUrl,
+                        'maarchApps'   => $maarchApps,
+                        'coll_id'      => $coll_id,
+                        'res_table'    => $coll_table,
+                        'res_view'     => $coll_view,
                     );
-                    $html = $templates_controler->merge($notification->template_id, $params, 'content');
+                    $html = $templates_controler->merge($notification['template_id'], $params, 'content');
 
                     if (strlen($html) === 0) {
                         foreach ($tmpNotif['events'] as $event) {
@@ -232,7 +215,8 @@ while ($state != 'END') {
                     $recipient_mail = $tmpNotif['recipient']->mail;
 
                     if (!empty($recipient_mail)) {
-                        $html = $func->protect_string_db($html, '', 'no');
+                        $html = str_replace("&#039;", "'", $html);
+                        $html = pg_escape_string($html);
                         $html = str_replace('&amp;', '&', $html);
                         $html = str_replace('&', '#and#', $html);
 
@@ -315,5 +299,4 @@ Bt_logInDataBase(
     $totalNotificationsToProcess.' notification(s) processed without error'
 );
 
-//unlink($GLOBALS['lckFile']);
 exit($GLOBALS['exitCode']);
diff --git a/modules/notifications/batch/batch_tools.php b/modules/notifications/batch/batch_tools.php
index b19885273e9..4c493a467a6 100755
--- a/modules/notifications/batch/batch_tools.php
+++ b/modules/notifications/batch/batch_tools.php
@@ -84,10 +84,10 @@ function Bt_exitBatch($returnCode, $message='')
             fwrite($semaphore, '1');
             fclose($semaphore);
         }
-        $GLOBALS['logger']->write($message, 'ERROR', $returnCode);
+        Bt_writeLog(['level' => 'ERROR', 'message' => $message]);
         Bt_logInDataBase($GLOBALS['totalProcessedResources'], 1, $message.' (return code: '. $returnCode.')');
     } elseif ($message <> '') {
-        $GLOBALS['logger']->write($message, 'INFO', $returnCode);
+        Bt_writeLog(['level' => 'INFO', 'message' => $message]);
         Bt_logInDataBase($GLOBALS['totalProcessedResources'], 0, $message.' (return code: '. $returnCode.')');
     }
     Bt_updateWorkBatch();
@@ -113,7 +113,7 @@ function Bt_logInDataBase($totalProcessed=0, $totalErrors=0, $info='')
  * 
  * @return nothing
  */
-function Bt_getWorkBatch() 
+function Bt_getWorkBatch()
 {
     $req = "SELECT param_value_int FROM parameters WHERE id = ? ";
     $stmt = $GLOBALS['db']->query($req, array($GLOBALS['batchName']."_id"));
@@ -148,8 +148,21 @@ function Bt_updateWorkBatch()
 function Bt_myInclude($file) 
 {
     if (file_exists($file)) {
-        include_once ($file);
+        include_once($file);
     } else {
         throw new IncludeFileError($file);
     }
 }
+
+function Bt_writeLog($args = [])
+{
+    \SrcCore\controllers\LogsController::add([
+        'isTech'    => true,
+        'moduleId'  => $GLOBALS['batchName'],
+        'level'     => $args['level'],
+        'tableName' => '',
+        'recordId'  => $GLOBALS['batchName'],
+        'eventType' => $GLOBALS['batchName'],
+        'eventId'   => $args['message']
+    ]);
+}
diff --git a/modules/notifications/batch/load_basket_event_stack.php b/modules/notifications/batch/load_basket_event_stack.php
index 0e15938ec0a..15613b650bb 100755
--- a/modules/notifications/batch/load_basket_event_stack.php
+++ b/modules/notifications/batch/load_basket_event_stack.php
@@ -42,16 +42,6 @@ class IncludeFileError extends Exception
     }
 }
 
-try {
-    include('Maarch_CLITools/ArgsParser.php');
-    include('LoggerLog4php.php');
-    include('Maarch_CLITools/FileHandler.php');
-    include('Maarch_CLITools/ConsoleHandler.php');
-} catch (IncludeFileError $e) {
-    echo 'Maarch_CLITools required ! \n (pear.maarch.org)\n';
-    exit(106);
-}
-
 // Globals variables definition
 $GLOBALS['batchName'] = 'basket_event_stack';
 $GLOBALS['wb'] = '';
@@ -59,63 +49,23 @@ $totalProcessedResources = 0;
 $batchDirectory = '';
 $log4PhpEnabled = false;
 
-//Create folder basket_event_stack
-if (!is_dir('logs' . DIRECTORY_SEPARATOR . $GLOBALS['batchName'])) {
-    if (!mkdir('logs' . DIRECTORY_SEPARATOR . $GLOBALS['batchName'], 0775, true)) {
-        die('Create log directory failed...');
-    }
-}
-// Open Logger
-$logger = new Logger4Php();
-$logger->set_threshold_level('INFO');
-
-$logFile = 'logs' . DIRECTORY_SEPARATOR . $GLOBALS['batchName']
-             . DIRECTORY_SEPARATOR . date('Y-m-d_H-i-s') . '.log';
-             
-$file = new FileHandler($logFile);
-$logger->add_handler($file);
-
 // Load tools
 include('batch_tools.php');
 
-// Defines scripts arguments
-$argsparser = new ArgsParser();
-// The config file
-$argsparser->add_arg(
-    'config',
-    array(
-        'short' => 'c',
-        'long' => 'config',
-        'mandatory' => true,
-        'help' => 'Config file path is mandatory.',
-    )
-);
-$argsparser->add_arg(
-    'notif',
-    array(
-        'short' => 'n',
-        'long' => 'notif',
-        'mandatory' => true,
-        'help' => 'Notification id is mandatory.',
-    )
-);
-
-// Parsing script options
-try {
-    $options = $argsparser->parse_args($GLOBALS['argv']);
-    // If option = help then options = false and the script continues ...
-    if ($options == false) {
-        exit(0);
-    }
-} catch (MissingArgumentError $e) {
-    if ($e->arg_name == 'config') {
-        $logger->write('Configuration file missing', 'ERROR', 101);
-        exit(101);
-    }
-    if ($e->arg_name == 'notif') {
-        $logger->write('Notification id missing', 'ERROR', 102);
-        exit(101);
-    }
+$options = getopt("c:n:", ["config:", "notif:"]);
+if (empty($options['c']) && empty($options['config'])) {
+    print("Configuration file missing\n");
+    exit(101);
+} elseif (!empty($options['c']) && empty($options['config'])) {
+    $options['config'] = $options['c'];
+    unset($options['c']);
+}
+if (empty($options['n']) && empty($options['notif'])) {
+    print("Notification id missing\n");
+    exit(102);
+} elseif (!empty($options['n']) && empty($options['notif'])) {
+    $options['notif'] = $options['n'];
+    unset($options['n']);
 }
 
 $txt = '';
@@ -126,36 +76,26 @@ foreach (array_keys($options) as $key) {
         $txt .= $key . '=' . $options[$key] . ',';
     }
 }
-$logger->write($txt, 'DEBUG');
+print($txt . "\n");
 $GLOBALS['configFile'] = $options['config'];
 $notificationId = $options['notif'];
 
-$logger->write('Load xml config file:' . $GLOBALS['configFile'], 'INFO');
+print("Load xml config file:" . $GLOBALS['configFile'] . "\n");
 
 // Tests existence of config file
 if (!file_exists($GLOBALS['configFile'])) {
-    $logger->write(
-        'Configuration file ' . $GLOBALS['configFile']
-        . ' does not exist',
-        'ERROR',
-        102
+    print(
+        "Configuration file " . $GLOBALS['configFile']
+        . " does not exist\n"
     );
     exit(102);
 }
 // Loading config file
-$logger->write(
-    'Load xml config file:' . $GLOBALS['configFile'],
-    'INFO'
-);
+print("Load xml config file:" . $GLOBALS['configFile'] . "\n");
 $xmlconfig = simplexml_load_file($GLOBALS['configFile']);
 
 if ($xmlconfig == false) {
-    $logger->write(
-        'Error on loading config file:'
-        . $GLOBALS['configFile'],
-        'ERROR',
-        103
-    );
+    print("Error on loading config file:" . $GLOBALS['configFile'] . "\n");
     exit(103);
 }
 
@@ -189,99 +129,33 @@ $GLOBALS['batchDirectory'] = $maarchDirectory . 'modules'
 
 set_include_path(get_include_path() . PATH_SEPARATOR . $maarchDirectory);
 
-//log4php params
-$log4phpParams = $xmlconfig->LOG4PHP;
-if ((string) $log4phpParams->enabled == 'true') {
-    $logger->set_log4PhpLibrary(
-        $maarchDirectory . 'apps/maarch_entreprise/tools/log4php/Logger.php'
-    );
-    $logger->set_log4PhpLogger((string) $log4phpParams->Log4PhpLogger);
-    $logger->set_log4PhpBusinessCode((string) $log4phpParams->Log4PhpBusinessCode);
-    $logger->set_log4PhpConfigPath((string) $log4phpParams->Log4PhpConfigPath);
-    $logger->set_log4PhpBatchName('basket_event_stack');
-} else {
-    echo "\n/!\ WARNING /!\ LOG4PHP is disabled ! Informations of batch process will not show !\n\n";
-}
-
 $mailerParams = $xmlconfig->MAILER;
 
 // INCLUDES
 try {
     Bt_myInclude('vendor/autoload.php');
 
-    Bt_myInclude(
-        'core' . DIRECTORY_SEPARATOR . 'class'
-        . DIRECTORY_SEPARATOR . 'class_functions.php'
-    );
-    Bt_myInclude(
-        'core' . DIRECTORY_SEPARATOR . 'class'
-        . DIRECTORY_SEPARATOR . 'class_db_pdo.php'
-    );
-    Bt_myInclude(
-        'core' . DIRECTORY_SEPARATOR . 'class'
-        . DIRECTORY_SEPARATOR . 'class_core_tools.php'
-    );
-    
-    // Notifications
-    Bt_myInclude(
-        "modules" . DIRECTORY_SEPARATOR . "notifications"
-        . DIRECTORY_SEPARATOR . "notifications_tables_definition.php"
-    );
-    Bt_myInclude(
-        "modules" . DIRECTORY_SEPARATOR . "notifications"
-        . DIRECTORY_SEPARATOR . "class" . DIRECTORY_SEPARATOR . "notifications_controler.php"
-    );
-    Bt_myInclude(
-        "modules" . DIRECTORY_SEPARATOR . "notifications"
-        . DIRECTORY_SEPARATOR . "class" . DIRECTORY_SEPARATOR . "diffusion_type_controler.php"
-    );
-    Bt_myInclude(
-        "modules" . DIRECTORY_SEPARATOR . "notifications"
-        . DIRECTORY_SEPARATOR . "class" . DIRECTORY_SEPARATOR . "events_controler.php"
-    );
-    // Templates
-    Bt_myInclude(
-        'modules' . DIRECTORY_SEPARATOR . 'templates'
-        . DIRECTORY_SEPARATOR . 'class' . DIRECTORY_SEPARATOR . 'templates_controler.php'
-    );
-
-    Bt_myInclude(
-        'core' . DIRECTORY_SEPARATOR . 'class'
-        . DIRECTORY_SEPARATOR . 'SecurityControler.php'
-    );
-
-    // Entities
-    Bt_myInclude(
-        "modules" . DIRECTORY_SEPARATOR . "entities" . DIRECTORY_SEPARATOR . "class"
-        . DIRECTORY_SEPARATOR . "class_modules_tools.php"
-    );
+    // // Notifications
+    // Bt_myInclude(
+    //     "modules" . DIRECTORY_SEPARATOR . "notifications"
+    //     . DIRECTORY_SEPARATOR . "notifications_tables_definition.php"
+    // );
+    // Bt_myInclude(
+    //     "modules" . DIRECTORY_SEPARATOR . "notifications"
+    //     . DIRECTORY_SEPARATOR . "class" . DIRECTORY_SEPARATOR . "events_controler.php"
+    // );
+    // // Templates
+    // Bt_myInclude(
+    //     'modules' . DIRECTORY_SEPARATOR . 'templates'
+    //     . DIRECTORY_SEPARATOR . 'class' . DIRECTORY_SEPARATOR . 'templates_controler.php'
+    // );
 } catch (IncludeFileError $e) {
-    $logger->write(
-        'Problem with the php include path:' .$e .' '. get_include_path(),
-        'ERROR'
-    );
+    Bt_writeLog(['level' => 'ERROR', 'message' => 'Problem with the php include path:' .$e .' '. get_include_path()]);
     exit();
 }
 
-// Controlers and objects
-$dbConfig = $xmlconfig->CONFIG_BASE;
-$_SESSION['config']['databaseserver'] 		= (string)$dbConfig->databaseserver;
-$_SESSION['config']['databaseserverport'] 	= (string)$dbConfig->databaseserverport;
-$_SESSION['config']['databaseuser']			= (string)$dbConfig->databaseuser;
-$_SESSION['config']['databasepassword']		= (string)$dbConfig->databasepassword;
-$_SESSION['config']['databasename'] 		= (string)$dbConfig->databasename;
-$_SESSION['config']['databasetype']			= (string)$dbConfig->databasetype;
-
-$coreTools = new core_tools();
-$coreTools->load_lang($lang, $maarchDirectory, $maarchApps);
-$func = new functions();
-
-$notifications_controler  = new notifications_controler();
-$diffusion_type_controler = new diffusion_type_controler();
-$events_controler         = new events_controler();
-$templates_controler      = new templates_controler();
-
-$db = new Database();
+// $events_controler         = new events_controler();
+// $templates_controler      = new templates_controler();
 
 \SrcCore\models\DatabasePDO::reset();
 new \SrcCore\models\DatabasePDO(['customId' => $_SESSION['custom_override_id']]);
@@ -308,15 +182,4 @@ if (file_exists($GLOBALS['errorLckFile'])) {
     exit(13);
 }
 
-/*if (file_exists($GLOBALS['lckFile'])) {
-    $logger->write(
-        'An instance of the batch is already in progress',
-        'ERROR', 109
-    );
-    exit(109);
-}
-$semaphore = fopen($GLOBALS['lckFile'], 'a');
-fwrite($semaphore, '1');
-fclose($semaphore);*/
-
 Bt_getWorkBatch();
diff --git a/src/app/notification/models/NotificationsEventsModelAbstract.php b/src/app/notification/models/NotificationsEventsModelAbstract.php
index 8a4e783a369..a36ec4cba11 100755
--- a/src/app/notification/models/NotificationsEventsModelAbstract.php
+++ b/src/app/notification/models/NotificationsEventsModelAbstract.php
@@ -19,6 +19,23 @@ use SrcCore\models\DatabaseModel;
 
 abstract class NotificationsEventsModelAbstract
 {
+    public static function get(array $args = [])
+    {
+        ValidatorModel::arrayType($args, ['select', 'where', 'data', 'orderBy']);
+        ValidatorModel::intType($args, ['limit']);
+
+        $groups = DatabaseModel::select([
+            'select'    => empty($args['select']) ? ['*'] : $args['select'],
+            'table'     => ['notif_event_stack'],
+            'where'     => $args['where'] ?? [],
+            'data'      => $args['data'] ?? [],
+            'order_by'  => $args['orderBy'] ?? [],
+            'limit'     => $args['limit'] ?? 0
+        ]);
+
+        return $groups;
+    }
+
     public static function create(array $aArgs)
     {
         ValidatorModel::notEmpty($aArgs, ['notification_sid', 'table_name', 'record_id', 'user_id', 'event_info']);
@@ -34,4 +51,22 @@ abstract class NotificationsEventsModelAbstract
 
         return $aReturn;
     }
+
+    public static function getById(array $aArgs)
+    {
+        ValidatorModel::notEmpty($aArgs, ['notificationSid']);
+
+        $aNotification = DatabaseModel::select([
+            'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'],
+            'table'  => ['notif_event_stack'],
+            'where'  => ['notification_sid = ?', 'exec_date is NULL'],
+            'data'   => [$aArgs['notificationSid']],
+        ]);
+
+        if (empty($aNotification[0])) {
+            return [];
+        }
+
+        return $aNotification[0];
+    }
 }
-- 
GitLab