From df5835aaa7f3fa393f791b13131329f16c635320 Mon Sep 17 00:00:00 2001
From: Alex Orluc <alex.orluc@maarch.org>
Date: Thu, 26 Apr 2018 15:57:56 +0200
Subject: [PATCH] FIX #5566 fix no check passwd if ldap

---
 apps/maarch_entreprise/log.php | 195 +++++-----
 core/class/class_security.php  | 636 ++++++++++++++++++---------------
 2 files changed, 437 insertions(+), 394 deletions(-)

diff --git a/apps/maarch_entreprise/log.php b/apps/maarch_entreprise/log.php
index fafa2d9bd0e..e055ba67b51 100755
--- a/apps/maarch_entreprise/log.php
+++ b/apps/maarch_entreprise/log.php
@@ -2,22 +2,23 @@
 
 
 /**
-* File : log.php
-*
-* User identification
-*
-* @package  Maarch PeopleBox 1.0
-* @version 2.1
-* @since 10/2005
-* @license GPL
-* @author  Claire Figueras  <dev@maarch.org>
-* @author  Laurent Giovannoni  <dev@maarch.org>
-*/
-if(empty($_COOKIE)){
+ * File : log.php.
+ *
+ * User identification
+ *
+ * @version 2.1
+ *
+ * @since 10/2005
+ *
+ * @license GPL
+ * @author  Claire Figueras  <dev@maarch.org>
+ * @author  Laurent Giovannoni  <dev@maarch.org>
+ */
+if (empty($_COOKIE)) {
     $_SESSION['error'] = 'Le cache utilisateur à été réinitialisé veuillez re-saisir vos identifiants';
     header(
-        'location: ' . $_SESSION['config']['businessappurl']
-        . 'index.php?display=true&page=login'
+        'location: '.$_SESSION['config']['businessappurl']
+        .'index.php?display=true&page=login'
     );
     exit;
 }
@@ -25,21 +26,21 @@ if(empty($_COOKIE)){
 if (file_exists('../../core/init.php')) {
     include_once '../../core/init.php';
 }
-require_once('core' . DIRECTORY_SEPARATOR . 'class' . DIRECTORY_SEPARATOR . 'class_functions.php');
-require_once('core' . DIRECTORY_SEPARATOR . 'class' . DIRECTORY_SEPARATOR . 'class_db.php');
-require_once('core' . DIRECTORY_SEPARATOR . 'class' . DIRECTORY_SEPARATOR . 'class_core_tools.php');
+require_once 'core'.DIRECTORY_SEPARATOR.'class'.DIRECTORY_SEPARATOR.'class_functions.php';
+require_once 'core'.DIRECTORY_SEPARATOR.'class'.DIRECTORY_SEPARATOR.'class_db.php';
+require_once 'core'.DIRECTORY_SEPARATOR.'class'.DIRECTORY_SEPARATOR.'class_core_tools.php';
 
 $core = new core_tools();
 $core->load_lang();
 $func = new functions();
 
 $_SESSION['error'] = '';
-if(isset($_SESSION['web_cas_url'])){
-    include_once('apps/maarch_entreprise/tools/phpCAS/CAS.php');
+if (isset($_SESSION['web_cas_url'])) {
+    include_once 'apps/maarch_entreprise/tools/phpCAS/CAS.php';
 
-    phpCAS::client(constant($_SESSION['cas_version']), $_SESSION['cas_serveur'], (int)$_SESSION['cas_port'], $_SESSION['cas_context'], true);
+    phpCAS::client(constant($_SESSION['cas_version']), $_SESSION['cas_serveur'], (int) $_SESSION['cas_port'], $_SESSION['cas_context'], true);
 
-    if(!empty($_SESSION['cas_certificate'])){
+    if (!empty($_SESSION['cas_certificate'])) {
         phpCAS::setCasServerCACert($_SESSION['cas_certificate']);
     } else {
         phpCAS::setNoCasServerValidation();
@@ -48,7 +49,7 @@ if(isset($_SESSION['web_cas_url'])){
     phpCAS::forceAuthentication();
     $Id = phpCAS::getUser();
 
-    if(!empty($_SESSION['cas_id_separator'])){
+    if (!empty($_SESSION['cas_id_separator'])) {
         $tmpId = explode($_SESSION['cas_id_separator'], $Id);
         $login = $tmpId[0];
     } else {
@@ -56,13 +57,13 @@ if(isset($_SESSION['web_cas_url'])){
     }
 
     $_REQUEST['pass'] = 'maarch';
-} else if (!empty($_SESSION['ozwillo']['userId'])) {
+} elseif (!empty($_SESSION['ozwillo']['userId'])) {
     $login = $_SESSION['ozwillo']['userId'];
     $_REQUEST['pass'] = 'maarch';
-} else if (!empty($_SESSION['sso']['userId'])) {
+} elseif (!empty($_SESSION['sso']['userId'])) {
     $login = $_SESSION['sso']['userId'];
     $_REQUEST['pass'] = 'maarch';
-} else if (isset($_REQUEST['login'])) {
+} elseif (isset($_REQUEST['login'])) {
     $login = $func->wash($_REQUEST['login'], 'no', _THE_ID, 'yes');
 } else {
     $login = '';
@@ -79,8 +80,8 @@ if (isset($_REQUEST['ra_code'])) {
 }
 require_once 'core/class/class_security.php';
 require_once 'core/class/class_request.php';
-require_once 'apps/' . $_SESSION['config']['app_id']
-    . '/class/class_business_app_tools.php';
+require_once 'apps/'.$_SESSION['config']['app_id']
+    .'/class/class_business_app_tools.php';
 $sec = new security();
 $businessAppTools = new business_app_tools();
 
@@ -103,36 +104,35 @@ if (count($_SESSION['config']) <= 0) {
     $core->load_menu($_SESSION['modules']);
 }
 
-if (! empty($_SESSION['error'])) {
+if (!empty($_SESSION['error'])) {
     header(
-        'location: ' . $_SESSION['config']['businessappurl']
-        . 'index.php?display=true&page=login'
+        'location: '.$_SESSION['config']['businessappurl']
+        .'index.php?display=true&page=login'
     );
     exit();
 } else {
-    if ($_SESSION['config']['ldap'] == 'true' && $login <> 'superadmin') {
+    if ($_SESSION['config']['ldap'] == 'true' && $login != 'superadmin') {
         //Extraction de /root/config dans le fichier de conf
-        if (file_exists($_SESSION['config']['corepath'] 
-            . '/custom/' . $_SESSION['custom_override_id']
-            . '/modules/ldap/xml/config.xml')
+        if (file_exists($_SESSION['config']['corepath']
+            .'/custom/'.$_SESSION['custom_override_id']
+            .'/modules/ldap/xml/config.xml')
         ) {
-            $pathtoConfig = $_SESSION['config']['corepath'] 
-            . '/custom/' . $_SESSION['custom_override_id']
-            . '/modules/ldap/xml/config.xml';
+            $pathtoConfig = $_SESSION['config']['corepath']
+            .'/custom/'.$_SESSION['custom_override_id']
+            .'/modules/ldap/xml/config.xml';
         } else {
-             $pathtoConfig = $_SESSION['config']['corepath'] 
-                . 'modules/ldap/xml/config.xml';
+            $pathtoConfig = $_SESSION['config']['corepath']
+                .'modules/ldap/xml/config.xml';
         }
         $ldapConf = new DomDocument();
         try {
-            if (!@$ldapConf->load($pathtoConfig)) 
-            {
+            if (!@$ldapConf->load($pathtoConfig)) {
                 throw new Exception(
                     'Impossible de charger le document : '
-                    . $pathtoConfig
+                    .$pathtoConfig
                 );
             }
-        } catch(Exception $e) {
+        } catch (Exception $e) {
             exit($e->getMessage());
         }
 
@@ -145,122 +145,120 @@ if (! empty($_SESSION['error'])) {
         //On inclus la class LDAP qui correspond à l'annuaire
         if (strtolower($type_ldap) == 'openldap') {
             $classLdap = 'class_openLDAP.php';
-        }else{
+        } else {
             $classLdap = 'class_adLDAP.php';
         }
 
         //customized or not
-        if (!@include $_SESSION['config']['corepath'] . '/custom/' . $_SESSION['custom_override_id'] . '/modules/ldap/class/'.$classLdap) 
-        {
-            if(!@include $_SESSION['config']['corepath'] . 'modules/ldap/class/'.$classLdap){
-                exit('Impossible de charger class_' . $_SESSION['config']['corepath'] . '/modules/ldap/class/'.$classLdap."\n"); 
+        if (!@include $_SESSION['config']['corepath'].'/custom/'.$_SESSION['custom_override_id'].'/modules/ldap/class/'.$classLdap) {
+            if (!@include $_SESSION['config']['corepath'].'modules/ldap/class/'.$classLdap) {
+                exit('Impossible de charger class_'.$_SESSION['config']['corepath'].'/modules/ldap/class/'.$classLdap."\n");
             }
         }
-        
-        if ($prefix_login <> '') {
-            $login_admin = $prefix_login . "\\" . $login_admin;
+
+        if ($prefix_login != '') {
+            $login_admin = $prefix_login.'\\'.$login_admin;
         }
-        
+
         //Try to create a new ldap instance
         if (strtolower($type_ldap) == 'openldap') {
             try {
                 $ad = new LDAP($domain, $login_admin, $pass, $ssl, $hostname);
-            } catch(Exception $conFailure) {
+            } catch (Exception $conFailure) {
                 echo functions::xssafe($conFailure->getMessage());
                 exit;
             }
-        }else{
+        } else {
             try {
                 $ad = new LDAP($domain, $login_admin, $pass, $ssl);
-            } catch(Exception $conFailure) {
+            } catch (Exception $conFailure) {
                 echo functions::xssafe($conFailure->getMessage());
                 exit;
             }
         }
-        
-        if ($prefix_login <> '') {
-            $loginToAd = $prefix_login . "\\" . $login;
+
+        if ($prefix_login != '') {
+            $loginToAd = $prefix_login.'\\'.$login;
         } else {
             $loginToAd = $login;
         }
-        
-        if ($ad -> authenticate($loginToAd, $password)) {
+
+        if ($ad->authenticate($loginToAd, $password)) {
             //TODO: protect sql injection with PDO
-                require_once 'core/class/class_db_pdo.php';
+            require_once 'core/class/class_db_pdo.php';
 
-                // Instantiate database.
-                $database = new Database();
-                $stmt = $database->query(
-                    "SELECT * FROM users WHERE user_id ILIKE ?", 
+            // Instantiate database.
+            $database = new Database();
+            $stmt = $database->query(
+                    'SELECT * FROM users WHERE user_id ILIKE ?',
                     array($login)
                 ); //permet de rechercher les utilisateurs dans le LDAP sans prendre en compte la casse
-                $result = $stmt->fetch();
+            $result = $stmt->fetch();
 
             if ($result) {
                 $_SESSION['error'] = '';
                 $res = $sec->login($login, $password, 'ldap');
                 $_SESSION['user'] = $res['user'];
-                if (empty($_SESSION['error'])) {
+                if ($res['error'] == '') {
+                    \SrcCore\models\SecurityModel::setCookieAuth(['userId' => $login]);
+                } else {
                     $_SESSION['error'] = $res['error'];
                 }
                 $core->load_menu($_SESSION['modules']);
                 header(
-                    'location: ' . $_SESSION['config']['businessappurl']
-                    . $res['url']
+                    'location: '.$_SESSION['config']['businessappurl']
+                    .$res['url']
                 );
                 exit();
             } else {
                 $_SESSION['error'] = _BAD_LOGIN_OR_PSW;
                 header(
-                    'location: ' . $_SESSION['config']['businessappurl']
-                    . 'index.php?display=true&page=login'
+                    'location: '.$_SESSION['config']['businessappurl']
+                    .'index.php?display=true&page=login'
                 );
                 exit;
             }
         } else {
             $_SESSION['error'] = _BAD_LOGIN_OR_PSW;
             header(
-                'location: ' . $_SESSION['config']['businessappurl']
-                . 'index.php?display=true&page=login'
+                'location: '.$_SESSION['config']['businessappurl']
+                .'index.php?display=true&page=login'
             );
             exit;
         }
-    }
-    elseif(isset($_REQUEST['ra_code'])) {
+    } elseif (isset($_REQUEST['ra_code'])) {
         if (empty($login) || empty($password) || empty($ra_code)) {
             $_SESSION['error'] = _IP_NOT_ALLOWED;
             header(
-                'location: ' . $_SESSION['config']['businessappurl']
-                . 'index.php?display=true&page=login'
+                'location: '.$_SESSION['config']['businessappurl']
+                .'index.php?display=true&page=login'
             );
             exit;
-        }
-        else {
+        } else {
             $_SESSION['error'] = '';
             $res = $sec->login($login, $password, false, $ra_code);
             //$core->show_array($res);
             $_SESSION['user'] = $res['user'];
             if ($res['error'] == '') {
-               // $businessAppTools->load_app_var_session($_SESSION['user']);
+                // $businessAppTools->load_app_var_session($_SESSION['user']);
                 //$core->load_var_session($_SESSION['modules'], $_SESSION['user']);
                 $core->load_menu($_SESSION['modules']);
-               // exit;
+                // exit;
             }
             if (empty($_SESSION['error'])) {
                 $_SESSION['error'] = $res['error'];
             }
             header(
-                'location: ' . $_SESSION['config']['businessappurl'] . $res['url']
+                'location: '.$_SESSION['config']['businessappurl'].$res['url']
             );
             exit();
         }
-    }
-    else {
+    } else {
         if (empty($login) || empty($password)) {
-            $_SESSION['error'] = _BAD_LOGIN_OR_PSW . '...';
+            $_SESSION['error'] = _BAD_LOGIN_OR_PSW.'...';
             header(
-                'location: ' . $_SESSION['config']['businessappurl']
-                . 'index.php?display=true&page=login'
+                'location: '.$_SESSION['config']['businessappurl']
+                .'index.php?display=true&page=login'
             );
             exit;
         } else {
@@ -270,22 +268,20 @@ if (! empty($_SESSION['error'])) {
             $_SESSION['user'] = $res['user'];
             if ($res['error'] == '') {
                 \SrcCore\models\SecurityModel::setCookieAuth(['userId' => $login]);
-               // $businessAppTools->load_app_var_session($_SESSION['user']);
+                // $businessAppTools->load_app_var_session($_SESSION['user']);
                 //$core->load_var_session($_SESSION['modules'], $_SESSION['user']);
                 $core->load_menu($_SESSION['modules']);
-               // exit;
-            }
-            else {
+                // exit;
+            } else {
                 $_SESSION['error'] = $res['error'];
             }
-            
+
             $pathToIPFilter = '';
-            if(file_exists($_SESSION['config']['corepath'].'custom'.DIRECTORY_SEPARATOR.$_SESSION['custom_override_id'].DIRECTORY_SEPARATOR.'apps'.DIRECTORY_SEPARATOR.$_SESSION['config']['app_id'].DIRECTORY_SEPARATOR.'xml'.DIRECTORY_SEPARATOR.'ip_filter.xml')){
+            if (file_exists($_SESSION['config']['corepath'].'custom'.DIRECTORY_SEPARATOR.$_SESSION['custom_override_id'].DIRECTORY_SEPARATOR.'apps'.DIRECTORY_SEPARATOR.$_SESSION['config']['app_id'].DIRECTORY_SEPARATOR.'xml'.DIRECTORY_SEPARATOR.'ip_filter.xml')) {
                 $pathToIPFilter = $_SESSION['config']['corepath'].'custom'.DIRECTORY_SEPARATOR.$_SESSION['custom_override_id'].DIRECTORY_SEPARATOR.'apps'.DIRECTORY_SEPARATOR.$_SESSION['config']['app_id'].DIRECTORY_SEPARATOR.'xml'.DIRECTORY_SEPARATOR.'ip_filter.xml';
             } elseif (file_exists('apps'.DIRECTORY_SEPARATOR.$_SESSION['config']['app_id'].DIRECTORY_SEPARATOR.'xml'.DIRECTORY_SEPARATOR.'ip_filter.xml')) {
                 $pathToIPFilter = 'apps'.DIRECTORY_SEPARATOR.$_SESSION['config']['app_id'].DIRECTORY_SEPARATOR.'xml'.DIRECTORY_SEPARATOR.'ip_filter.xml';
-            }
-            else {
+            } else {
                 $ipArray = array();
                 $ipArray['enabled'] = 'false';
                 $ipArray['duration'] = '0';
@@ -295,18 +291,17 @@ if (! empty($_SESSION['error'])) {
             //print_r($ipArray);
             if ($ipArray['enabled'] == 'true') {
                 $isAllowed = false;
-                if($ipArray['IP'] <> '') {
+                if ($ipArray['IP'] != '') {
                     $isAllowed = preg_match($ipArray['IP'], $_SERVER['REMOTE_ADDR']);
                 }
-                
+
                 if (empty($_SESSION['error'])) {
                     $_SESSION['error'] = $res['error'];
                 }
                 if (!$isAllowed && $res['error'] == '') {
                     if ($ipArray['duration'] == 0) {
                         $_SESSION['error'] = _IP_NOT_ALLOWED_NO_RA_CODE;
-                    }
-                    else {
+                    } else {
                         $_SESSION['error'] = _IP_NOT_ALLOWED;
                     }
                     $res['url'] = 'index.php?display=true&page=login';
@@ -316,7 +311,7 @@ if (! empty($_SESSION['error'])) {
                 $res['url'] .= '?administration=true';
             }
             header(
-                'location: ' . $_SESSION['config']['businessappurl'] . $res['url']
+                'location: '.$_SESSION['config']['businessappurl'].$res['url']
             );
             exit();
         }
diff --git a/core/class/class_security.php b/core/class/class_security.php
index fa91380aae6..b9b64868446 100755
--- a/core/class/class_security.php
+++ b/core/class/class_security.php
@@ -19,26 +19,28 @@
 */
 
 /**
-* @brief   Contains all the functions to manage the users groups security
-* and connexion to the application
-*
-* @file
-* @author Claire Figueras <dev@maarch.org>
-* @date $date$
-* @version $Revision$
-* @ingroup core
-*/
+ * @brief   Contains all the functions to manage the users groups security
+ * and connexion to the application
+ *
+ * @file
+ *
+ * @author Claire Figueras <dev@maarch.org>
+ * @date $date$
+ *
+ * @version $Revision$
+ * @ingroup core
+ */
 
 /**
-* @brief   contains all the functions to manage the users groups security
-* through session variables
-*
-*<ul>
-*  <li>Management of application connexion</li>
-*  <li>Management of user rigths</li>
-*</ul>
-* @ingroup core
-*/
+ * @brief   contains all the functions to manage the users groups security
+ * through session variables
+ *
+ *<ul>
+ *  <li>Management of application connexion</li>
+ *  <li>Management of user rigths</li>
+ *</ul>
+ * @ingroup core
+ */
 
 //Requires to launch history functions
 require_once 'core/class/class_db_pdo.php';
@@ -48,8 +50,8 @@ require_once 'core/class/class_core_tools.php';
 require_once 'core/where_targets.php';
 require_once 'core/class/users_controler.php';
 if (isset($_SESSION['config']['app_id'])) {
-    require_once 'apps/' . $_SESSION['config']['app_id']
-        . '/class/class_business_app_tools.php';
+    require_once 'apps/'.$_SESSION['config']['app_id']
+        .'/class/class_business_app_tools.php';
 }
 require_once 'core/class/usergroups_controler.php';
 require_once 'core/class/ServiceControler.php';
@@ -59,28 +61,30 @@ require_once 'core/class/ServiceControler.php';
 class security extends Database
 {
     /**
-    * Gets the indice of the collection in the  $_SESSION['collections'] array
-    *
-    * @param  $coll_id string  Collection identifier
-    * @return integer Indice of the collection in the $_SESSION['collections'] or -1 if not found
-    */
+     * Gets the indice of the collection in the  $_SESSION['collections'] array.
+     *
+     * @param  $coll_id string  Collection identifier
+     *
+     * @return int Indice of the collection in the $_SESSION['collections'] or -1 if not found
+     */
     public function get_ind_collection($coll_id)
     {
-        for ($i=0;$i< count($_SESSION['collections']); $i++) {
+        for ($i = 0; $i < count($_SESSION['collections']); ++$i) {
             if (trim($_SESSION['collections'][$i]['id']) == trim($coll_id)) {
                 return $i;
             }
         }
+
         return -1;
     }
 
     /**
-    * Logs a user
-    *
-    * @param  $s_login  string User login
-    * @param  $pass string User password
-    */
-    public function login($s_login, $pass, $method = false, $ra_code=false)
+     * Logs a user.
+     *
+     * @param  $s_login  string User login
+     * @param  $pass string User password
+     */
+    public function login($s_login, $pass, $method = false, $ra_code = false)
     {
         $array = array();
         $error = '';
@@ -104,23 +108,24 @@ class security extends Database
             if ($method == 'activex') {
                 $comp = " and STATUS <> 'DEL' and loginmode = 'activex'";
             } elseif ($method == 'ldap') {
-                $comp =" and STATUS <> 'DEL'";
+                $comp = " and STATUS <> 'DEL'";
+                $params = [];
             } else {
-                if ($ra_code <> false) {
-                    $comp = " and "
-                        . "ra_code = :ra_code and ra_expiration_date >= :ra_expiration_date "
-                        . "and status <> :status "
-                        . "and (loginmode = :loginmode1 or loginmode = :loginmode2)";
+                if ($ra_code != false) {
+                    $comp = ' and '
+                        .'ra_code = :ra_code and ra_expiration_date >= :ra_expiration_date '
+                        .'and status <> :status '
+                        .'and (loginmode = :loginmode1 or loginmode = :loginmode2)';
                     $params = array(
-                        'ra_code'            => $this->getPasswordHash($ra_code),
+                        'ra_code' => $this->getPasswordHash($ra_code),
                         'ra_expiration_date' => date('Y-m-d 00:00:00'),
-                        'status'             => 'DEL',
-                        'loginmode1'         => 'standard',
-                        'loginmode2'         => 'sso',
+                        'status' => 'DEL',
+                        'loginmode1' => 'standard',
+                        'loginmode2' => 'sso',
                     );
                 } else {
                     $comp = " and STATUS <> 'DEL' "
-                          . "and loginmode in (:loginmode1)";
+                          .'and loginmode in (:loginmode1)';
                     $params = ['loginmode1' => ['standard', 'sso', 'cas']];
                     if ($method == 'restMode') {
                         array_push($params['loginmode1'], 'restMode');
@@ -133,56 +138,56 @@ class security extends Database
         }
 
         $check = \SrcCore\models\SecurityModel::authentication(['userId' => $s_login, 'password' => $pass]);
-        if ($check) {
+        if ($check || $method == 'ldap') {
             $user = $uc->getWithComp($s_login, $comp, $params);
         }
 
         if (isset($user)) {
             if ($user->__get('enabled') == 'Y') {
-                $ugc            = new usergroups_controler();
-                $sec_controler  = new SecurityControler();
+                $ugc = new usergroups_controler();
+                $sec_controler = new SecurityControler();
                 $serv_controler = new ServiceControler();
                 if (isset($_SESSION['modules_loaded']['visa'])) {
-                    require_once "modules" . DIRECTORY_SEPARATOR . "visa" . DIRECTORY_SEPARATOR. "class" . DIRECTORY_SEPARATOR. "class_user_signatures.php";
+                    require_once 'modules'.DIRECTORY_SEPARATOR.'visa'.DIRECTORY_SEPARATOR.'class'.DIRECTORY_SEPARATOR.'class_user_signatures.php';
                     $us = new UserSignatures();
                     $db = new Database();
-                    $query = "select path_template from "
-                        . _DOCSERVERS_TABLE_NAME
-                        . " where docserver_id = 'TEMPLATES'";
-                    $stmt     = $db->query($query);
-                    $resDs    = $stmt->fetchObject();
+                    $query = 'select path_template from '
+                        ._DOCSERVERS_TABLE_NAME
+                        ." where docserver_id = 'TEMPLATES'";
+                    $stmt = $db->query($query);
+                    $resDs = $stmt->fetchObject();
                     $pathToDs = $resDs->path_template;
 
                     $tab_sign = $us->getForUser($s_login);
                     $_SESSION['user']['pathToSignature'] = array();
                     foreach ($tab_sign as $sign) {
-                        $path = $pathToDs . str_replace(
-                            "#",
+                        $path = $pathToDs.str_replace(
+                            '#',
                             DIRECTORY_SEPARATOR,
                             $sign['signature_path']
                         )
-                        . $sign['signature_file_name'];
+                        .$sign['signature_file_name'];
                         array_push($_SESSION['user']['pathToSignature'], $path);
                     }
 
                     $_SESSION['user']['code_session'] = $ra_code;
                 }
                 $array = array(
-                    'change_pass'     => $user->__get('change_password'),
-                    'UserId'          => $user->__get('user_id'),
-                    'FirstName'       => $user->__get('firstname'),
-                    'LastName'        => $user->__get('lastname'),
-                    'Initials'        => $user->__get('initials'),
-                    'Phone'           => $user->__get('phone'),
-                    'Mail'            => $user->__get('mail'),
-                    'department'      => $user->__get('department'),
-                    'thumbprint'      => $user->__get('thumbprint'),
+                    'change_pass' => $user->__get('change_password'),
+                    'UserId' => $user->__get('user_id'),
+                    'FirstName' => $user->__get('firstname'),
+                    'LastName' => $user->__get('lastname'),
+                    'Initials' => $user->__get('initials'),
+                    'Phone' => $user->__get('phone'),
+                    'Mail' => $user->__get('mail'),
+                    'department' => $user->__get('department'),
+                    'thumbprint' => $user->__get('thumbprint'),
                     'pathToSignature' => $_SESSION['user']['pathToSignature'],
-                    'Status'          => $user->__get('status'),
-                    'cookie_date'     => $user->__get('cookie_date'),
+                    'Status' => $user->__get('status'),
+                    'cookie_date' => $user->__get('cookie_date'),
                 );
 
-                $array['primarygroup'] = $ugc ->getPrimaryGroup(
+                $array['primarygroup'] = $ugc->getPrimaryGroup(
                     $array['UserId']
                 );
                 $tmp = $sec_controler->load_security(
@@ -195,7 +200,7 @@ class security extends Database
                 $core_tools = new core_tools();
                 $business_app_tools->load_app_var_session($array);
                 $core_tools->load_var_session($_SESSION['modules'], $array);
-                
+
                 /************Temporary fix*************/
                 // #TODO : revoir les functions load_var_session dans class_modules_tools pour ne plus charger en session les infos
                 if (isset($_SESSION['user']['baskets'])) {
@@ -215,7 +220,7 @@ class security extends Database
                 $array['services'] = $serv_controler->loadUserServices(
                     $array['UserId']
                 );
-                
+
                 if ($_SESSION['history']['userlogin'] == 'true') {
                     //add new instance in history table for the user's connexion
                     $hist = new history();
@@ -225,56 +230,58 @@ class security extends Database
                         $ip = $_SERVER['REMOTE_ADDR'];
                     }
                     $navigateur = addslashes($_SERVER['HTTP_USER_AGENT']);
-                    $_SESSION['user']['UserId']       = $s_login;
-                    $_SESSION['user']['department']   = $array['department'];
-                    $_SESSION['user']['thumbprint']   = $array['thumbprint'];
+                    $_SESSION['user']['UserId'] = $s_login;
+                    $_SESSION['user']['department'] = $array['department'];
+                    $_SESSION['user']['thumbprint'] = $array['thumbprint'];
                     $_SESSION['user']['primarygroup'] = $array['primarygroup'];
                     $hist->add(
                         $_SESSION['tablename']['users'],
                         $s_login,
                         'LOGIN', 'userlogin',
-                        _LOGIN_HISTORY . ' '. $s_login . ' IP : ' . $ip,
+                        _LOGIN_HISTORY.' '.$s_login.' IP : '.$ip,
                         $_SESSION['config']['databasetype']
                     );
                 }
 
                 if ($array['change_pass'] == 'Y' && !isset($_SESSION['web_cas_url']) && !isset($_SESSION['web_sso_url'])) {
                     return array(
-                        'user'  => $array,
+                        'user' => $array,
                         'error' => $error,
-                        'url'   => 'index.php?display=true&page=change_pass'
+                        'url' => 'index.php?display=true&page=change_pass',
                     );
                 } elseif (isset($_SESSION['requestUri'])
-                    && trim($_SESSION['requestUri']) <> ''
-                    && ! preg_match('/page=login/', $_SESSION['requestUri'])) {
+                    && trim($_SESSION['requestUri']) != ''
+                    && !preg_match('/page=login/', $_SESSION['requestUri'])) {
                     return array(
-                        'user'  => $array,
+                        'user' => $array,
                         'error' => $error,
-                        'url'   => 'index.php?' . $_SESSION['requestUri']
+                        'url' => 'index.php?'.$_SESSION['requestUri'],
                     );
                 } else {
                     return array(
-                        'user'  => $array,
+                        'user' => $array,
                         'error' => $error,
-                        'url'   => 'index.php'
+                        'url' => 'index.php',
                     );
                 }
             } else {
-                $error = _SUSPENDED_ACCOUNT . '. ' . _MORE_INFOS
-                    . " <a href=\"mailto:" . $_SESSION['config']['adminmail']
-                    . "\">" . $_SESSION['config']['adminname'] . "</a>";
+                $error = _SUSPENDED_ACCOUNT.'. '._MORE_INFOS
+                    .' <a href="mailto:'.$_SESSION['config']['adminmail']
+                    .'">'.$_SESSION['config']['adminname'].'</a>';
+
                 return array(
-                    'user'  => $array,
+                    'user' => $array,
                     'error' => $error,
-                    'url'   => 'index.php'
+                    'url' => 'index.php',
                 );
             }
         } else {
             $error = _BAD_LOGIN_OR_PSW;
+
             return array(
-                'user'  => $array,
+                'user' => $array,
                 'error' => $error,
-                'url'   => 'index.php?display=true&page=login'
+                'url' => 'index.php?display=true&page=login',
             );
         }
     }
@@ -287,7 +294,7 @@ class security extends Database
         } else {
             $current_ip = $_SERVER['REMOTE_ADDR'];
         }
-        $list_ip = "SELECT ip from allowed_ip";
+        $list_ip = 'SELECT ip from allowed_ip';
         $stmt = $db->query($list_ip, array());
         while ($res = $stmt->fetchObject()) {
             if ($res->ip == $current_ip) {
@@ -297,6 +304,7 @@ class security extends Database
         if ($stmt->rowCount() == 0) {
             return true;
         }
+
         return false;
     }
 
@@ -305,7 +313,7 @@ class security extends Database
         require_once 'apps/maarch_entreprise/class/class_users.php';
         $users = new class_users();
         $userInfo = $users->get_user($_SESSION['user']['UserId']);
-        
+
         $authorized_characters = '0123456789';
         $cpt_motDePasse = 1;
         $cptMax_motDePasse = 4;
@@ -313,26 +321,26 @@ class security extends Database
         $raCodeGenerated = '';
         while (strlen($raCodeGenerated) < $cptMax_motDePasse) {
             $raCodeGenerated .= rand(1, $max_rand);
-            $cpt_motDePasse++;
+            ++$cpt_motDePasse;
         }
-        $expireTSamp  = mktime(date("H"), date("i")+15, date("s"), date("m"), date("d"), date("Y"));
-        $expiration_date = date("d-m-Y H:i:s", $expireTSamp);
-        
+        $expireTSamp = mktime(date('H'), date('i') + 15, date('s'), date('m'), date('d'), date('Y'));
+        $expiration_date = date('d-m-Y H:i:s', $expireTSamp);
+
         $db = new Database();
-        $db->query("UPDATE users set ra_code = ? WHERE user_id = ?", array($this->getPasswordHash($raCodeGenerated), $_SESSION['user']['UserId']), false);
-        $db->query("UPDATE users set ra_expiration_date = ? WHERE user_id = ?", array($expiration_date, $_SESSION['user']['UserId']), false);
-        
+        $db->query('UPDATE users set ra_code = ? WHERE user_id = ?', array($this->getPasswordHash($raCodeGenerated), $_SESSION['user']['UserId']), false);
+        $db->query('UPDATE users set ra_expiration_date = ? WHERE user_id = ?', array($expiration_date, $_SESSION['user']['UserId']), false);
+
         /* GENERATION DU MAIL */
         $mailToSend = '<html>';
         $mailToSend .= '<body>';
         $mailToSend .= '<p>';
-        $mailToSend .= _CONFIRM_ASK_RA_CODE_1 . '<br />';
-        $mailToSend .= _CONFIRM_ASK_RA_CODE_2 . $raCodeGenerated . ' <br />';
-        $mailToSend .= _CONFIRM_ASK_RA_CODE_3 . $expiration_date . '<br />';
+        $mailToSend .= _CONFIRM_ASK_RA_CODE_1.'<br />';
+        $mailToSend .= _CONFIRM_ASK_RA_CODE_2.$raCodeGenerated.' <br />';
+        $mailToSend .= _CONFIRM_ASK_RA_CODE_3.$expiration_date.'<br />';
         $mailToSend .= '</p>';
         $mailToSend .= '</body>';
         $mailToSend .= '</html>';
-        
+
         if (file_exists($_SESSION['config']['corepath'].'custom'.DIRECTORY_SEPARATOR
             .$_SESSION['custom_override_id'].DIRECTORY_SEPARATOR.'apps'
             .DIRECTORY_SEPARATOR.$_SESSION['config']['app_id']
@@ -345,32 +353,32 @@ class security extends Database
             $path_to_config = 'apps'.DIRECTORY_SEPARATOR.$_SESSION['config']['app_id']
             .DIRECTORY_SEPARATOR.'xml'.DIRECTORY_SEPARATOR.'config_sendmail_security.xml';
         }
-        
+
         $xmlconfig = simplexml_load_file($path_to_config);
         $mailerParams = $xmlconfig->MAILER;
-        
-        require_once (string)$mailerParams->path_to_mailer;
+
+        require_once (string) $mailerParams->path_to_mailer;
         $mailer = new PHPMailerOAuth();
         $mailer->SMTPDebug = 0;
-        
+
         $mailer->Debugoutput = 'html';
-        $mailer->Host        = (string)$mailerParams->smtp_host;
-        $mailer->Port        = (string)$mailerParams->smtp_port;
-        $mailer->SMTPSecure  = (string)$mailerParams->smtp_secure;
-        $mailer->SMTPAuth    = filter_var($mailerParams->smtp_auth, FILTER_VALIDATE_BOOLEAN);
-        
-        $mailer->Username = (string)$mailerParams->smtp_user;
-        $mailer->Password = (string)$mailerParams->smtp_password;
-        $mailer->Helo     = (string)$mailerParams->domains;
-        
-        if ((string)$mailerParams->type == "smtp") {
+        $mailer->Host = (string) $mailerParams->smtp_host;
+        $mailer->Port = (string) $mailerParams->smtp_port;
+        $mailer->SMTPSecure = (string) $mailerParams->smtp_secure;
+        $mailer->SMTPAuth = filter_var($mailerParams->smtp_auth, FILTER_VALIDATE_BOOLEAN);
+
+        $mailer->Username = (string) $mailerParams->smtp_user;
+        $mailer->Password = (string) $mailerParams->smtp_password;
+        $mailer->Helo = (string) $mailerParams->domains;
+
+        if ((string) $mailerParams->type == 'smtp') {
             $mailer->isSMTP();
         }
-        $mailer->setFrom((string)$mailerParams->mailfrom, (string)$mailerParams->mailfromname);
-        $mailer->addReplyTo((string)$mailerParams->mailfrom, (string)$mailerParams->mailfromname);
+        $mailer->setFrom((string) $mailerParams->mailfrom, (string) $mailerParams->mailfromname);
+        $mailer->addReplyTo((string) $mailerParams->mailfrom, (string) $mailerParams->mailfromname);
         $mailer->addAddress($userInfo['mail']);
-        $mailer->Subject = (string)$mailerParams->subject;
-        $mailer->CharSet = (string)$mailerParams->charset;
+        $mailer->Subject = (string) $mailerParams->subject;
+        $mailer->CharSet = (string) $mailerParams->charset;
         $mailer->msgHTML($mailToSend);
         if (!$mailer->send()) {
             $_SESSION['error'] .= ' mail not send to '.$userInfo['mail'].': '.$mailer->ErrorInfo;
@@ -397,38 +405,39 @@ class security extends Database
     }
 
     /**
-    * Reopens a session with the user's cookie
-    *
-    * @param  $s_UserId  string User identifier
-    * @param  $s_key string Cookie key
-    */
+     * Reopens a session with the user's cookie.
+     *
+     * @param  $s_UserId  string User identifier
+     * @param  $s_key string Cookie key
+     */
     public function reopen($s_UserId, $s_key)
     {
-        header("location: ".$_SESSION['config']['businessappurl']."index.php?display=true&page=login");
+        header('location: '.$_SESSION['config']['businessappurl'].'index.php?display=true&page=login');
         exit();
     }
 
     /******************* COLLECTION MANAGEMENT FUNCTIONS *******************/
 
     /**
-    * Returns all collections where we can insert new documents (with tables)
-    *
-    * @return array Collections where inserts are allowed
-    */
+     * Returns all collections where we can insert new documents (with tables).
+     *
+     * @return array Collections where inserts are allowed
+     */
     public function retrieve_insert_collections()
     {
         $arr = array();
-        for ($i=0; $i<count($_SESSION['collections']);$i++) {
+        for ($i = 0; $i < count($_SESSION['collections']); ++$i) {
             if (isset($_SESSION['collections'][$i]['table']) && !empty($_SESSION['collections'][$i]['table'])) {
                 array_push($arr, $_SESSION['collections'][$i]);
             }
         }
+
         return $arr;
     }
 
     /**
-     *
      * @param  $textToHash
+     *
      * @return string hashedText
      */
     public function getPasswordHash($textToHash)
@@ -437,31 +446,34 @@ class security extends Database
     }
 
     /**
-    * Returns a script related to a collection
-    *
-    * @param  $coll_id  string Collection identifier
-    * @param  $script_name  string Script name "script_add", "script_search", "script_search_result", "script_details"
-    * @return string Script name or empty string if not found
-    */
+     * Returns a script related to a collection.
+     *
+     * @param  $coll_id  string Collection identifier
+     * @param  $script_name  string Script name "script_add", "script_search", "script_search_result", "script_details"
+     *
+     * @return string Script name or empty string if not found
+     */
     public function get_script_from_coll($coll_id, $script_name)
     {
-        for ($i=0; $i < count($_SESSION['collections']);$i++) {
+        for ($i = 0; $i < count($_SESSION['collections']); ++$i) {
             if (trim($_SESSION['collections'][$i]['id']) == trim($coll_id)) {
                 return trim($_SESSION['collections'][$i][$script_name]);
             }
         }
+
         return '';
     }
 
     /**
-    * Returns the collection identifier from a table
-    *
-    * @param  $table  string Tablename
-    * @return string Collection identifier or empty string if not found
-    */
+     * Returns the collection identifier from a table.
+     *
+     * @param  $table  string Tablename
+     *
+     * @return string Collection identifier or empty string if not found
+     */
     public function retrieve_coll_id_from_table($table)
     {
-        for ($i=0;$i<count($_SESSION['collections']);$i++) {
+        for ($i = 0; $i < count($_SESSION['collections']); ++$i) {
             if (
                 $_SESSION['collections'][$i]['table'] == $table
                 || $_SESSION['collections'][$i]['version_table'] == $table
@@ -469,252 +481,278 @@ class security extends Database
                 return $_SESSION['collections'][$i]['id'];
             }
         }
+
         return '';
     }
-    
+
     /**
-    * Returns the collection version table from a collId
-    *
-    * @param  $collId string collection ID
-    * @return string version table or empty string if not found
-    */
+     * Returns the collection version table from a collId.
+     *
+     * @param  $collId string collection ID
+     *
+     * @return string version table or empty string if not found
+     */
     public function retrieve_version_table_from_coll_id($collId)
     {
-        for ($i=0;$i<count($_SESSION['collections']);$i++) {
+        for ($i = 0; $i < count($_SESSION['collections']); ++$i) {
             if ($_SESSION['collections'][$i]['id'] == $collId) {
                 return $_SESSION['collections'][$i]['version_table'];
             }
         }
+
         return '';
     }
-    
+
     /**
-    * Returns the collection extension table from a collId
-    *
-    * @param  $collId string collection ID
-    * @return string version table or empty string if not found
-    */
+     * Returns the collection extension table from a collId.
+     *
+     * @param  $collId string collection ID
+     *
+     * @return string version table or empty string if not found
+     */
     public function retrieve_extension_table_from_coll_id($collId)
     {
-        for ($i=0;$i<count($_SESSION['collections']);$i++) {
+        for ($i = 0; $i < count($_SESSION['collections']); ++$i) {
             if ($_SESSION['collections'][$i]['id'] == $collId) {
                 return $_SESSION['collections'][$i]['extensions'][0];
             }
         }
+
         return '';
     }
-    
+
     /**
-    * Returns the adr table from a table
-    *
-    * @param  $table string Tablename
-    * @return string adr table or empty string if not found
-    */
+     * Returns the adr table from a table.
+     *
+     * @param  $table string Tablename
+     *
+     * @return string adr table or empty string if not found
+     */
     public function retrieve_adr_table_from_table($table)
     {
-        for ($i=0;$i<count($_SESSION['collections']);$i++) {
+        for ($i = 0; $i < count($_SESSION['collections']); ++$i) {
             if ($_SESSION['collections'][$i]['table'] == $table) {
                 return $_SESSION['collections'][$i]['adr'];
             }
         }
+
         return '';
     }
 
     /**
-    * Returns the collection table from a view
-    *
-    * @param  $view string View
-    * @return string Collection table or empty string if not found
-    */
+     * Returns the collection table from a view.
+     *
+     * @param  $view string View
+     *
+     * @return string Collection table or empty string if not found
+     */
     public function retrieve_coll_table_from_view($view)
     {
-        for ($i=0; $i<count($_SESSION['collections']);$i++) {
+        for ($i = 0; $i < count($_SESSION['collections']); ++$i) {
             if ($_SESSION['collections'][$i]['view'] == $view) {
                 return $_SESSION['collections'][$i]['table'];
             }
         }
+
         return '';
     }
 
     /**
-    * Returns the collection identifier from a view
-    *
-    * @param  $view string View
-    * @return string Collection identifier or empty string if not found
-    */
+     * Returns the collection identifier from a view.
+     *
+     * @param  $view string View
+     *
+     * @return string Collection identifier or empty string if not found
+     */
     public function retrieve_coll_id_from_view($view)
     {
-        for ($i=0; $i<count($_SESSION['collections']);$i++) {
+        for ($i = 0; $i < count($_SESSION['collections']); ++$i) {
             if ($_SESSION['collections'][$i]['view'] == $view) {
                 return $_SESSION['collections'][$i]['id'];
             }
         }
+
         return '';
     }
 
-
     /**
-    * Returns the view of a collection from the collection identifier
-    *
-    * @param string $coll_id  Collection identifier
-    * @return string View name or empty string if not found
-    */
+     * Returns the view of a collection from the collection identifier.
+     *
+     * @param string $coll_id Collection identifier
+     *
+     * @return string View name or empty string if not found
+     */
     public function retrieve_view_from_coll_id($coll_id)
     {
-        for ($i=0; $i<count($_SESSION['collections']);$i++) {
+        for ($i = 0; $i < count($_SESSION['collections']); ++$i) {
             if ($_SESSION['collections'][$i]['id'] == $coll_id) {
                 return $_SESSION['collections'][$i]['view'];
             }
         }
+
         return '';
     }
 
     /**
-    * Returns the view of a collection from the table of the collection
-    *
-    * @param string $table  Tablename
-    * @return string View name or empty string if not found
-    */
+     * Returns the view of a collection from the table of the collection.
+     *
+     * @param string $table Tablename
+     *
+     * @return string View name or empty string if not found
+     */
     public function retrieve_view_from_table($table)
     {
-        for ($i=0; $i<count($_SESSION['collections']);$i++) {
+        for ($i = 0; $i < count($_SESSION['collections']); ++$i) {
             if ($_SESSION['collections'][$i]['table'] == $table) {
                 return $_SESSION['collections'][$i]['view'];
             }
         }
+
         return '';
     }
 
     /**
-    * Returns the table of the collection from the collection identifier
-    *
-    * @param string $coll_id  Collection identifier
-    * @return string Table name or empty string if not found
-    */
+     * Returns the table of the collection from the collection identifier.
+     *
+     * @param string $coll_id Collection identifier
+     *
+     * @return string Table name or empty string if not found
+     */
     public function retrieve_table_from_coll($coll_id)
     {
-        for ($i=0; $i<count($_SESSION['collections']);$i++) {
+        for ($i = 0; $i < count($_SESSION['collections']); ++$i) {
             if ($_SESSION['collections'][$i]['id'] == $coll_id) {
                 return $_SESSION['collections'][$i]['table'];
             }
         }
+
         return '';
     }
-    
+
     /**
-    * Returns the adr table of the collection from the collection identifier
-    *
-    * @param string $collId  Collection identifier
-    * @return string adr table name or empty string if not found
-    */
+     * Returns the adr table of the collection from the collection identifier.
+     *
+     * @param string $collId Collection identifier
+     *
+     * @return string adr table name or empty string if not found
+     */
     public function retrieveAdrFromColl($collId)
     {
-        for ($i = 0;$i < count($_SESSION['collections']);$i++) {
+        for ($i = 0; $i < count($_SESSION['collections']); ++$i) {
             if ($_SESSION['collections'][$i]['id'] == $collId) {
                 return $_SESSION['collections'][$i]['adr'];
             }
         }
+
         return '';
     }
 
     /**
-    * Returns the table of the collection from the view of the collection
-    *
-    * @param string $view  View
-    * @return string Table name or empty string if not found
-    */
+     * Returns the table of the collection from the view of the collection.
+     *
+     * @param string $view View
+     *
+     * @return string Table name or empty string if not found
+     */
     public function retrieve_table_from_view($view)
     {
-        for ($i=0; $i<count($_SESSION['collections']);$i++) {
+        for ($i = 0; $i < count($_SESSION['collections']); ++$i) {
             if ($_SESSION['collections'][$i]['view'] == $view) {
                 return $_SESSION['collections'][$i]['table'];
             }
         }
+
         return '';
     }
 
     /**
-    * Returns the collection  label from the table of the collection
-    *
-    * @param string $table  Tablename
-    * @return string Collection label or empty string if not found
-    */
+     * Returns the collection  label from the table of the collection.
+     *
+     * @param string $table Tablename
+     *
+     * @return string Collection label or empty string if not found
+     */
     public function retrieve_coll_label_from_table($table)
     {
-        for ($i=0; $i<count($_SESSION['collections']);$i++) {
+        for ($i = 0; $i < count($_SESSION['collections']); ++$i) {
             if ($_SESSION['collections'][$i]['table'] == $table) {
                 return $_SESSION['collections'][$i]['label'];
             }
         }
+
         return '';
     }
 
     /**
-    * Returns the collection  label from the collection identifier
-    *
-    * @param string $coll_id  Collection identifier
-    * @return string Collection label or empty string if not found
-    */
+     * Returns the collection  label from the collection identifier.
+     *
+     * @param string $coll_id Collection identifier
+     *
+     * @return string Collection label or empty string if not found
+     */
     public function retrieve_coll_label_from_coll_id($coll_id)
     {
-        for ($i=0; $i<count($_SESSION['collections']);$i++) {
+        for ($i = 0; $i < count($_SESSION['collections']); ++$i) {
             if ($_SESSION['collections'][$i]['id'] == $coll_id) {
                 return $_SESSION['collections'][$i]['label'];
             }
         }
+
         return '';
     }
 
     ////////////////USER RELATED
 
     /**
-    * Returns the collection identifier for the current user from the collection table (using $_SESSION['user']['security'])
-    *
-    * @param  $table  string Tablename
-    * @return string Collection identifier or empty string if not found
-    */
-/*
-    public function retrieve_user_coll_id($table)
-    {
-
-        foreach(array_keys($_SESSION['user']['security']) as $coll_id)
+     * Returns the collection identifier for the current user from the collection table (using $_SESSION['user']['security']).
+     *
+     * @param  $table  string Tablename
+     *
+     * @return string Collection identifier or empty string if not found
+     */
+    /*
+        public function retrieve_user_coll_id($table)
         {
-            if($_SESSION['user']['security'][$coll_id]['DOC']['table'] == $table)
+
+            foreach(array_keys($_SESSION['user']['security']) as $coll_id)
             {
-                return $coll_id;
+                if($_SESSION['user']['security'][$coll_id]['DOC']['table'] == $table)
+                {
+                    return $coll_id;
+                }
             }
+            return false;
         }
-        return false;
-    }
-*/
+    */
 
+    //////////////////////// A REFAIRE
 
-//////////////////////// A REFAIRE
     /**
-    * Return all collections where the current user can insert new documents (with table)
-    *
-    * @return array Array of all collections where the current user can insert new documents
-    */
+     * Return all collections where the current user can insert new documents (with table).
+     *
+     * @return array Array of all collections where the current user can insert new documents
+     */
     public function retrieve_user_insert_coll()
     {
         $arr = array();
-        for ($i=0; $i<count($_SESSION['user']['security']);$i++) {
+        for ($i = 0; $i < count($_SESSION['user']['security']); ++$i) {
             if (isset($_SESSION['user']['security'][$i]['table']) && !empty($_SESSION['user']['security'][$i]['table']) && $_SESSION['user']['security'][$i]['can_insert'] == 'Y') {
                 $ind = $this->get_ind_collection($_SESSION['user']['security'][$i]['coll_id']);
-                array_push($arr, array('coll_id'=> $_SESSION['user']['security'][$i]['coll_id'], 'label_coll' => $_SESSION['collections'][$ind]['label'] , 'table' => $_SESSION['user']['security'][$i]['table']));
+                array_push($arr, array('coll_id' => $_SESSION['user']['security'][$i]['coll_id'], 'label_coll' => $_SESSION['collections'][$ind]['label'], 'table' => $_SESSION['user']['security'][$i]['table']));
             }
         }
+
         return $arr;
     }
 
-
     /**
-    * Checks if the current user can do the action on the collection
-    *
-    * @param string $coll_id  Collection identifier
-    * @param string $action  can_insert, can_update, can_delete
-    * @return True if the user can do the action on the collection, False otherwise
-    */
+     * Checks if the current user can do the action on the collection.
+     *
+     * @param string $coll_id Collection identifier
+     * @param string $action  can_insert, can_update, can_delete
+     *
+     * @return true if the user can do the action on the collection, False otherwise
+     */
     public function collection_user_right($coll_id, $action)
     {
         if (!isset($coll_id)) {
@@ -722,35 +760,40 @@ class security extends Database
         }
         $func = new functions();
         $flag = false;
-        for ($i=0; $i<count($_SESSION['user']['security']);$i++) {
-            if ((isset($_SESSION['user']['security'][$i]['coll_id']) && $_SESSION['user']['security'][$i]['coll_id'] == $coll_id)  && $_SESSION['user']['security'][$i][$action] == 'Y') {
+        for ($i = 0; $i < count($_SESSION['user']['security']); ++$i) {
+            if ((isset($_SESSION['user']['security'][$i]['coll_id']) && $_SESSION['user']['security'][$i]['coll_id'] == $coll_id) && $_SESSION['user']['security'][$i][$action] == 'Y') {
                 $flag = true;
             }
         }
+
         return $flag;
     }
-/////////////////////////////
+
+    /////////////////////////////
 
     /**
-    * Returns where clause of the collection for the current user from the collection identifier
-    *
-    * @param  $coll_id string Collection identifier
-    * @return string Collection where clause or empty string if not found or the where clause is empty
-    */
+     * Returns where clause of the collection for the current user from the collection identifier.
+     *
+     * @param  $coll_id string Collection identifier
+     *
+     * @return string Collection where clause or empty string if not found or the where clause is empty
+     */
     public function get_where_clause_from_coll_id($coll_id)
     {
         if (isset($_SESSION['user']['security'][$coll_id]['DOC']['where'])) {
             return $_SESSION['user']['security'][$coll_id]['DOC']['where'];
         }
+
         return '';
     }
 
     /**
-    * Returns where clause of the collection for the current user from the collection identifier and basket where clause
-    *
-    * @param  $coll_id string Collection identifier
-    * @return string Collection where clause
-    */
+     * Returns where clause of the collection for the current user from the collection identifier and basket where clause.
+     *
+     * @param  $coll_id string Collection identifier
+     *
+     * @return string Collection where clause
+     */
     public function get_where_clause_from_coll_id_and_basket($coll_id)
     {
         $collectionWhereClause = $this->get_where_clause_from_coll_id($coll_id);
@@ -761,11 +804,11 @@ class security extends Database
 
         $userBaskets = count($_SESSION['user']['baskets']);
 
-        for ($ind_bask = 0; $ind_bask < $userBaskets; $ind_bask++) {
+        for ($ind_bask = 0; $ind_bask < $userBaskets; ++$ind_bask) {
             if ($_SESSION['user']['baskets'][$ind_bask]['coll_id'] == $coll_id
                 && $_SESSION['user']['baskets'][$ind_bask]['is_folder_basket'] == 'N'
                 && isset($_SESSION['user']['baskets'][$ind_bask]['clause'])
-                && trim($_SESSION['user']['baskets'][$ind_bask]['clause']) <> '') {
+                && trim($_SESSION['user']['baskets'][$ind_bask]['clause']) != '') {
                 $basketWhereClause .= ' or ('.$_SESSION['user']['baskets'][$ind_bask]['clause'].')';
             }
         }
@@ -776,17 +819,18 @@ class security extends Database
             $basketWhereClause = preg_replace('/^ or/', '', $basketWhereClause);
         }
 
-        $whereRequest = '('.$collectionWhereClause.' or '. $basketWhereClause .')';
-        
+        $whereRequest = '('.$collectionWhereClause.' or '.$basketWhereClause.')';
+
         return $whereRequest;
     }
 
     /**
-    * Returns where clause of the collection for the current user from the collection view
-    *
-    * @param  $view string View
-    * @return string Collection where clause or empty string if not found or the where clause is empty
-    */
+     * Returns where clause of the collection for the current user from the collection view.
+     *
+     * @param  $view string View
+     *
+     * @return string Collection where clause or empty string if not found or the where clause is empty
+     */
     public function get_where_clause_from_view($view)
     {
         foreach (array_keys($_SESSION['user']['security']) as $coll_id) {
@@ -794,15 +838,17 @@ class security extends Database
                 return $_SESSION['user']['security'][$coll_id]['DOC']['where'];
             }
         }
+
         return '';
     }
 
     /**
-    * Returns the collection table for the current user from the collection view (using $_SESSION['user']['security'])
-    *
-    * @param  $table  string Tablename
-    * @return string Table name or False if not found
-    */
+     * Returns the collection table for the current user from the collection view (using $_SESSION['user']['security']).
+     *
+     * @param  $table  string Tablename
+     *
+     * @return string Table name or False if not found
+     */
     public function retrieve_user_coll_table($view)
     {
         foreach (array_keys($_SESSION['user']['security']) as $coll_id) {
@@ -810,11 +856,11 @@ class security extends Database
                 return $_SESSION['user']['security'][$coll_id]['DOC']['where'];
             }
         }
+
         return false;
     }
 
     /**
-     *
      * @return array
      */
     public function getEntitiesForCurrentUser()
@@ -823,16 +869,18 @@ class security extends Database
         foreach ($_SESSION['user']['entities'] as $tmp) {
             $entitiesTab[] = $tmp['ENTITY_ID'];
         }
+
         return $entitiesTab;
     }
 
     /**
-    * Checks the right on the document of a collection for the current user
-    *
-    * @param  $coll_id string Collection identifier
-    * @param  $s_id string Document Identifier (res_id)
-    * @return bool True if the current user has the right, False otherwise
-    */
+     * Checks the right on the document of a collection for the current user.
+     *
+     * @param  $coll_id string Collection identifier
+     * @param  $s_id string Document Identifier (res_id)
+     *
+     * @return bool True if the current user has the right, False otherwise
+     */
     public function test_right_doc($coll_id, $s_id)
     {
         if (empty($coll_id) || empty($s_id)) {
@@ -844,15 +892,15 @@ class security extends Database
         }
         $entitiesTab = $this->getEntitiesForCurrentUser();
         $where_clause = $this->get_where_clause_from_coll_id($coll_id);
-        $query = "select res_id from " . $view . " where res_id = ?";
+        $query = 'select res_id from '.$view.' where res_id = ?';
         if (!empty($entitiesTab)) {
             if (!empty($where_clause)) {
-                $query .= " and (" . $where_clause . " or folder_destination in (?)) ";
+                $query .= ' and ('.$where_clause.' or folder_destination in (?)) ';
             }
             $stmt = $this->query($query, array($s_id, $entitiesTab));
         } else {
             if (!empty($where_clause)) {
-                $query .= " and (" . $where_clause . ") ";
+                $query .= ' and ('.$where_clause.') ';
             }
             $stmt = $this->query($query, array($s_id));
         }
@@ -862,7 +910,7 @@ class security extends Database
             for (
                 $ind_bask = 0;
                 $ind_bask < count($_SESSION['user']['baskets']);
-                $ind_bask++
+                ++$ind_bask
             ) {
                 if (
                     $_SESSION['user']['baskets'][$ind_bask]['coll_id'] == $coll_id
@@ -870,19 +918,19 @@ class security extends Database
                     if (
                         isset($_SESSION['user']['baskets'][$ind_bask]['clause'])
                         && trim($_SESSION['user']['baskets'][$ind_bask]['clause']
-                        ) <> ''
+                        ) != ''
                         && $_SESSION['user']['baskets'][$ind_bask]['is_folder_basket'] == 'N'
                     ) {
                         $basketQuery .= ' or ('
-                            . $_SESSION['user']['baskets'][$ind_bask]['clause']
-                            . ')';
+                            .$_SESSION['user']['baskets'][$ind_bask]['clause']
+                            .')';
                     }
                 }
             }
-            if ($basketQuery <> '') {
+            if ($basketQuery != '') {
                 $basketQuery = preg_replace('/^ or/', '', $basketQuery);
-                $query = "select res_id from "
-                    . $view . " where (" . $basketQuery . ") and res_id = ?";
+                $query = 'select res_id from '
+                    .$view.' where ('.$basketQuery.') and res_id = ?';
                 $stmt = $this->query($query, array($s_id));
                 if ($stmt->rowCount() < 1) {
                     return false;
-- 
GitLab