CVE-2017-15055: Improper Privilege Management (CWE-269)
value: TeamPass before 2.1.27.9 does not properly enforce item access control when requesting items.queries.php. It is then possible to copy any arbitrary item into a directory controlled by the attacker, edit any item within a read-only directory, delete an arbitrary item, delete the file attachments of an arbitrary item, copy the password of an arbitrary item to the copy/paste buffer, access the history of an arbitrary item, and edit attributes of an arbitrary directory. To exploit the vulnerability, an authenticated attacker must tamper with the requests sent directly, for example by changing the "item_id" parameter when invoking "copy_item" on items.queries.php.
CWE description: The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.
CVSS v3 base score: 8.1
Published: 2017-11-27T19:29Z
Repository: https://github.com/nilsteampassnet/TeamPass
Language: PHP
Files changed: index.php, items.load.php, sources/core.php, sources/items.queries.php, sources/main.functions.php
Commit date: 2017-09-30 13:07:36 +0200
Commit message: 2.1.27

Several fixes

Diff: diff --git a/index.php b/index.php
index 0622a42e0..46d0c9937 100644
--- a/index.php
+++ b/index.php
@@ -175,11 +175,13 @@ if (isset($SETTINGS['cpassman_dir']) === false || $SETTINGS['cpassman_dir'] ===
     $SETTINGS['cpassman_url'] = (string) $server_request_uri;
 }
 
 // Load user languages files
 if (in_array($session_user_language, $languagesList) === true) {
-    require_once $SETTINGS['cpassman_dir'].'/includes/language/'.$session_user_language.'.php';
+    if (file_exists($SETTINGS['cpassman_dir'].'/includes/language/'.$session_user_language.'.php') === true) {
+        require_once $SETTINGS['cpassman_dir'].'/includes/language/'.$session_user_language.'.php';
+    }
 } else {
     $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
     include $SETTINGS['cpassman_dir'].'/error.php';
 }
 
diff --git a/items.load.php b/items.load.php
index b6f44eb2e..aeabc8f06 100755
--- a/items.load.php
+++ b/items.load.php
@@ -288,11 +288,13 @@ function ListerItems(groupe_id, restricted, start, stop_listing_current_folder)
                     } else {
                         $("#items_path_var").html('');
                     }
 
                     // store the categories to be displayed
-                    $("#display_categories").val(data.displayCategories);
+                    if (data.displayCategories !== undefined) {
+                        $("#display_categories").val(data.displayCategories);
+                    }
 
                     // store type of access on folder
                     $("#access_level").val(data.access_level);
 
                     // warn about a required change of personal SK
@@ -348,11 +350,11 @@ function ListerItems(groupe_id, restricted, start, stop_listing_current_folder)
                         $("#query_next_start").val(data.next_start);
                     } else {
                         $("#query_next_start").val(data.list_to_be_continued);
 
                         // display Categories if needed
-                        if ($(".tr_fields") != undefined && data.displayCategories != "") {
+                        if ($(".tr_fields") !== undefined && data.displayCategories !== undefined && data.displayCategories !== "") {
                             var liste = data.displayCategories.split(';');
                             for (var i=0; i<liste.length; i++) {
                                 $(".itemCatName_"+liste[i]+", #newItemCatName_"+liste[i]+", #editItemCatName_"+liste[i]).show();
                             }
                         }
@@ -380,11 +382,11 @@ function ListerItems(groupe_id, restricted, start, stop_listing_current_folder)
                         $("#query_next_start").val(data.next_start);
                     } else {
                         $("#query_next_start").val(data.list_to_be_continued);
 
                         // display Categories if needed
-                        if ($(".tr_fields") != undefined && data.displayCategories != "") {
+                        if ($(".tr_fields") != undefined && data.displayCategories !== undefined && data.displayCategories != "") {
                             var liste = data.displayCategories.split(';');
                             for (var i=0; i<liste.length; i++) {
                                 $(".itemCatName_"+liste[i]+", #newItemCatName_"+liste[i]+", #editItemCatName_"+liste[i]).show();
                             }
                         }
@@ -418,14 +420,14 @@ function ListerItems(groupe_id, restricted, start, stop_listing_current_folder)
                                 LoadingPage();
                                 //move item
                                 $.post(
                                     "sources/items.queries.php",
                                     {
-                                        type     : "move_item",
-                                        item_id : ui.draggable.attr("id"),
+                                        type      : "move_item",
+                                        item_id   : ui.draggable.attr("id"),
                                         folder_id : $(this).attr("id").substring(4),
-                                        key        : "<?php echo $_SESSION['key']; ?>"
+                                        key       : "<?php echo $_SESSION['key']; ?>"
                                     },
                                     function(data) {
                                         //increment / decrement number of items in folders
                                         $("#itcount_"+data[0].from_folder).text(Math.floor($("#itcount_"+data[0].from_folder).text())-1);
                                         $("#itcount_"+data[0].to_folder).text(Math.floor($("#itcount_"+data[0].to_folder).text())+1);
@@ -924,38 +926,44 @@ function EditerItem()
                         $("#div_dialog_message").dialog("open");
                         return;
                     }
 
                     //check if format error
-                    if (data.error == "ERR_JSON_FORMAT") {
+                    if (data.error === "ERR_JSON_FORMAT") {
                         $("#div_loading").addClass("hidden");
-                        $("#edit_show_error").html(data.error + ' ERROR (JSON is broken)!!!!!');
-                        $("#edit_show_error").show();
-                    } else if (data.error == "ERR_KEY_NOT_CORRECT") {
+                        $("#edit_show_error")
+                            .html(data.error + ' ERROR (JSON is broken)!!!!!')
+                            .show();
+                    } else if (data.error === "ERR_KEY_NOT_CORRECT") {
                         $("#div_loading").addClass("hidden");
-                        $("#edit_show_error").html('Key verification for Query is not correct!');
-                        $("#edit_show_error").show();
+                        $("#edit_show_error")
+                            .html('Key verification for Query is not correct!')
+                            .show();
                         LoadingPage();
-                    }else if (data.error == "ERR_ENCRYPTION_NOT_CORRECT") {
+                    }else if (data.error === "ERR_ENCRYPTION_NOT_CORRECT") {
                         $("#div_loading").addClass("hidden");
-                        $("#edit_show_error").html('Item password could not be correctly encrypted!');
-                        $("#edit_show_error").show();
+                        $("#edit_show_error")
+                            .html('Item password could not be correctly encrypted!')
+                            .show();
                         LoadingPage();
-                    } else if (data.error == "ERR_PWD_TOO_LONG") {
+                    } else if (data.error === "ERR_PWD_TOO_LONG") {
                         $("#div_loading").addClass("hidden");
-                        $("#edit_show_error").html('<?php echo addslashes($LANG['error_pw_too_long']); ?>');
-                        $("#edit_show_error").show();
+                        $("#edit_show_error")
+                            .html('<?php echo addslashes($LANG['error_pw_too_long']); ?>')
+                            .show();
                         LoadingPage();
-                    } else if (data.error == "ERR_NOT_ALLOWED_TO_EDIT") {
+                    } else if (data.error === "ERR_NOT_ALLOWED_TO_EDIT") {
                         $("#div_formulaire_saisi").dialog("open");
-                        $("#new_show_error").html('User not allowed to edit this Item!');
-                        $("#new_show_error").show();
+                        $("#new_show_error")
+                            .html('User not allowed to edit this Item!')
+                            .show();
                         LoadingPage();
-                    } else if (data.error != "") {
+                    } else if (data.error !== "") {
                         $("#div_loading").addClass("hidden");
-                        $("#edit_show_error").html('<?php echo addslashes($LANG['error_not_allowed_to']); ?>');
-                        $("#edit_show_error").show();
+                        $("#edit_show_error")
+                            .html('<?php echo addslashes($LANG['error_not_allowed_to']); ?>')
+                            .show();
                         LoadingPage();
                     } else {
                         //refresh item in list
                         $("#fileclass"+data.id).text($('#edit_label').val());
 
@@ -1266,23 +1274,27 @@ function AfficherDetailsItem(id, salt_key_required, expired_item, restricted, di
             $("#request_ongoing").val("");
             LoadingPage();
             return;
         } else {
             $("#timestamp_item_displayed").val("");
+            var data = {
+                "id" : id,
+                "folder_id" : $('#hid_cat').val(),
+                "salt_key_required" : $('#recherche_group_pf').val(),
+                "salt_key_set" : $('#personal_sk_set').val(),
+                "expired_item" : expired_item,
+                "restricted" : restricted,
+                "page" : "items"
+            };
+
             //Send query
             $.post(
                 "sources/items.queries.php",
                 {
-                    type                : 'show_details_item',
-                    id                  : id,
-                    folder_id           : $('#hid_cat').val(),
-                    salt_key_required   : $('#recherche_group_pf').val(),
-                    salt_key_set        : $('#personal_sk_set').val(),
-                    expired_item        : expired_item,
-                    restricted          : restricted,
-                    page                : "items",
-                    key                 : "<?php echo $_SESSION['key']; ?>"
+                    type : 'show_details_item',
+                    data : prepareExchangedData(JSON.stringify(data), "encode", "<?php echo $_SESSION['key']; ?>"),
+                    key  : "<?php echo $_SESSION['key']; ?>"
                 },
                 function(data_raw) {
                     //decrypt data
                     try {
                         data = prepareExchangedData(data_raw , "decode", "<?php echo $_SESSION['key']; ?>");
@@ -1587,11 +1599,11 @@ function AfficherDetailsItem(id, salt_key_required, expired_item, restricted, di
                         $(".round-grey").addClass("ui-state-highlight ui-corner-all");
 
                         // continue loading data
                         showDetailsStep2(id, param);
 
-                    } else if (data.show_details == "1" && data.show_detail_option == "2") {
+                    } else if (data.show_details === "1" && data.show_detail_option === "2") {
                         $("#item_details_nok").addClass("hidden");
                         $("#item_details_ok").addClass("hidden");
                         $("#item_details_expired_full").show();
                         $("#menu_button_edit_item, #menu_button_del_item, #menu_button_copy_item, #menu_button_add_fav, #menu_button_del_fav, #menu_button_show_pw, #menu_button_copy_pw, #menu_button_copy_login, #menu_button_copy_link").attr("disabled","disabled");
                         $("#div_loading").addClass("hidden");
@@ -1656,10 +1668,15 @@ function showDetailsStep2(id, param)
                 $("#div_dialog_message").dialog("open");
 
                 return;
             }
 
+            if (data.error !== "") {
+                $("#div_dialog_message_text").html(data.error_text);
+                $("#div_dialog_message").show();
+            }
+
             $("#item_history_log").html(htmlspecialchars_decode(data.history));
             $("#edit_past_pwds").attr('title', htmlspecialchars_decode(data.history_of_pwds));
             $("#edit_past_pwds_div").html(htmlspecialchars_decode(data.history_of_pwds));
 
             $("#id_files").html(data.files_id);
@@ -2599,11 +2616,11 @@ $(function() {
 
                     //Send query
                     $.post(
                         "sources/items.queries.php",
                         {
-                            type    : "update_rep",
+                            type    : "update_folder",
                             data      : prepareExchangedData(JSON.stringify(data), "encode", "<?php echo $_SESSION['key']; ?>"),
                             key        : "<?php echo $_SESSION['key']; ?>"
                         },
                         function(data) {
                             //check if format error
diff --git a/sources/core.php b/sources/core.php
index 1f79d2c1c..1c64fbe7c 100644
--- a/sources/core.php
+++ b/sources/core.php
@@ -69,11 +69,13 @@ if (isset($_SERVER['HTTPS']) === true
 
 // Load pwComplexity
 if (isset($SETTINGS_EXT['pwComplexity']) === false) {
     // Pw complexity levels
     if (isset($_SESSION['user_language']) === true && $_SESSION['user_language'] !== "0") {
-        require_once $SETTINGS['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
+        if (file_exists($SETTINGS['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php') === true) {
+            require_once $SETTINGS['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
+        }
         $SETTINGS_EXT['pwComplexity'] = array(
             0=>array(0, $LANG['complex_level0']),
             25=>array(25, $LANG['complex_level1']),
             50=>array(50, $LANG['complex_level2']),
             60=>array(60, $LANG['complex_level3']),
diff --git a/sources/items.queries.php b/sources/items.queries.php
index f294700c1..925827fe8 100644
--- a/sources/items.queries.php
+++ b/sources/items.queries.php
@@ -127,14 +127,14 @@ if (null !== $post_type) {
                 $post_data,
                 "decode"
             );
 
             // Prepare variables
-            $label = noHTML(htmlspecialchars_decode($dataReceived['label']));
-            $url = htmlspecialchars_decode($dataReceived['url']);
+            $label = filter_var(htmlspecialchars_decode($dataReceived['label']), FILTER_SANITIZE_STRING);
+            $url = filter_var(htmlspecialchars_decode($dataReceived['url']), FILTER_SANITIZE_STRING);
             $pw = htmlspecialchars_decode($dataReceived['pw']);
-            $login = htmlspecialchars_decode($dataReceived['login']);
+            $login = filter_var(htmlspecialchars_decode($dataReceived['login']), FILTER_SANITIZE_STRING);
             $tags = htmlspecialchars_decode($dataReceived['tags']);
 
             // is author authorized to create in this folder
             if (count($_SESSION['list_folders_limited']) > 0) {
                 if (!in_array($dataReceived['categorie'], array_keys($_SESSION['list_folders_limited']))
@@ -479,16 +479,16 @@ if (null !== $post_type) {
                 "decode"
             );
 
             if (count($dataReceived) > 0) {
                 // Prepare variables
-                $label = noHTML(($dataReceived['label']));
-                $url = noHTML(htmlspecialchars_decode($dataReceived['url']));
+                $label = filter_var(($dataReceived['label']), FILTER_SANITIZE_STRING);
+                $url = filter_var(htmlspecialchars_decode($dataReceived['url']), FILTER_SANITIZE_STRING);
                 $pw = $original_pw = $sentPw = htmlspecialchars_decode($dataReceived['pw']);
-                $login = noHTML(htmlspecialchars_decode($dataReceived['login']));
+                $login = filter_var(htmlspecialchars_decode($dataReceived['login']), FILTER_SANITIZE_STRING);
                 $tags = htmlspecialchars_decode($dataReceived['tags']);
-                $email = noHTML(htmlspecialchars_decode($dataReceived['email']));
+                $email = filter_var(htmlspecialchars_decode($dataReceived['email']), FILTER_SANITIZE_STRING);
 
                 // perform a check in case of Read-Only user creating an item in his PF
                 if ($_SESSION['user_read_only'] === true && (!in_array($dataReceived['categorie'], $_SESSION['personal_folders']) || $dataReceived['is_pf'] !== '1')) {
                     echo prepareExchangedData(array("error" => "ERR_FOLDER_NOT_ALLOWED"), "encode");
                     break;
@@ -531,14 +531,15 @@ if (null !== $post_type) {
                         && $dataItem['anyone_can_modify'] === '1'
                         && (in_array($dataItem['id_tree'], $_SESSION['groupes_visibles']) || $_SESSION['is_admin'] === '1')
                         && $restrictionActive === false
                     )
                     ||
-                    (@in_array(
-                        $post_id,
-                        $_SESSION['list_folders_limited'][$post_folder_id]
-                    ))
+                    (null !== $post_folder_id
+                    && isset($_SESSION['list_restricted_folders_for_items'][$post_folder_id])
+                    && in_array($post_id, $_SESSION['list_restricted_folders_for_items'][$post_folder_id])
+                    && $post_restricted === '1'
+                    && $restrictionActive === false)
                 ) {
                     // Is pwd empty?
                     if (empty($pw) && isset($_SESSION['user_settings']['create_item_without_password']) && $_SESSION['user_settings']['create_item_without_password'] !== '1') {
                         echo prepareExchangedData(array("error" => "ERR_PWD_EMPTY"), "encode");
                         break;
@@ -1070,28 +1071,36 @@ if (null !== $post_type) {
             // perform a check in case of Read-Only user creating an item in his PF
             if ($_SESSION['user_read_only'] === '1'
                 && (!in_array($post_source_id, $_SESSION['personal_folders'])
                     || !in_array($post_dest_id, $_SESSION['personal_folders']))
             ) {
-                $returnValues = '[{"error" : "not_allowed"}, {"error_text" : "2'.addslashes($LANG['error_not_allowed_to']).'"}]';
+                $returnValues = '[{"error" : "not_allowed"}, {"error_text" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
                 echo $returnValues;
                 break;
             }
 
             $returnValues = $pw = "";
             $is_perso = 0;
 
-            if (null !== $post_item_id
-                && empty($post_item_id) === false
+            if (empty($post_item_id) === false
                 && empty($post_dest_id) === false
             ) {
                 // load the original record into an array
                 $originalRecord = DB::queryfirstrow(
                     "SELECT * FROM ".prefix_table("items")."
                     WHERE id=%i",
                     $post_item_id
                 );
+
+                // Check if the folder where this item is, is accessible to the user
+                if (in_array($originalRecord['id_tree'], $_SESSION['groupes_visibles'])) {
+                    $returnValues = '[{"error" : "not_allowed"}, {"error_text" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
+                    echo $returnValues;
+                    break;
+                }
+
+                // Load the destination folder record into an array
                 $dataDestination = DB::queryfirstrow(
                     "SELECT personal_folder FROM ".prefix_table("nested_tree")."
                     WHERE id=%i",
                     $post_dest_id
                 );
@@ -1301,10 +1310,21 @@ if (null !== $post_type) {
                 $returnValues = '[{"error" : "not_allowed"}, {"error_text" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
                 echo prepareExchangedData($returnValues, "encode");
                 break;
             }
 
+            // Decrypt and retreive data in JSON format
+            $dataReceived = prepareExchangedData($post_data, "decode");
+            // Init post variables
+            $post_id = filter_var(htmlspecialchars_decode($dataReceived['id']), FILTER_SANITIZE_NUMBER_INT);
+            $post_folder_id = filter_var(htmlspecialchars_decode($dataReceived['folder_id']), FILTER_SANITIZE_NUMBER_INT);
+            $post_salt_key_required = filter_var(htmlspecialchars_decode($dataReceived['salt_key_required']), FILTER_SANITIZE_STRING);
+            $post_salt_key_set = filter_var(htmlspecialchars_decode($dataReceived['salt_key_set']), FILTER_SANITIZE_STRING);
+            $post_expired_item = filter_var(htmlspecialchars_decode($dataReceived['expired_item']), FILTER_SANITIZE_STRING);
+            $post_restricted = filter_var(htmlspecialchars_decode($dataReceived['restricted']), FILTER_SANITIZE_STRING);
+            $post_page = filter_var(htmlspecialchars_decode($dataReceived['page']), FILTER_SANITIZE_STRING);
+
             $arrData = array();
             // return ID
             $arrData['id'] = $post_id;
             $arrData['id_user'] = API_USER_ID;
             $arrData['author'] = "API";
@@ -1353,10 +1373,11 @@ if (null !== $post_type) {
             // INNER JOIN ".$pre."automatic_del as d ON (d.item_id = i.id)
             // Get all USERS infos
             $listNotif = array_filter(explode(";", $dataItem['notification']));
             $listRest = array_filter(explode(";", $dataItem['restricted_to']));
             $listeRestriction = $listNotification = $listNotificationEmails = "";
+            $user_in_restricted_list_of_item = false;
             $rows = DB::query("SELECT id, login, email FROM ".prefix_table("users"));
             foreach ($rows as $record) {
                 // Get auhtor
                 if ($record['id'] === $dataItem['id_user']) {
                     $arrData['author'] = $record['login'];
@@ -1370,10 +1391,13 @@ if (null !== $post_type) {
                 }
 
                 // Get restriction list for users
                 if (in_array($record['id'], $listRest)) {
                     $listeRestriction .= $record['login'].";";
+                    if ($_SESSION['user_id'] === $record['id']) {
+                        $user_in_restricted_list_of_item = true;
+                    }
                 }
                 // Get notification list for users
                 if (in_array($record['id'], $listNotif)) {
                     $listNotification .= $record['login'].";";
                     $listNotificationEmails .= $record['email'].",";
@@ -1406,22 +1430,30 @@ if (null !== $post_type) {
                 $restrictionActive = false;
             }
             if (empty($dataItem['restricted_to'])) {
                 $restrictionActive = false;
             }
+
+
             // Check if user has a role that is accepted
-            $rows_tmp = DB::query("SELECT role_id FROM ".prefix_table("restriction_to_roles")." WHERE item_id=%i", $post_id);
-            $myTest = 0;
-            if (in_array($_SESSION['user_id'], $rows_tmp)) {
-                $myTest = 1;
+            $rows_tmp = DB::query(
+                "SELECT role_id
+                FROM ".prefix_table("restriction_to_roles")."
+                WHERE item_id=%i",
+                $post_id
+            );
+            foreach ($rows_tmp as $rec_tmp) {
+                if (in_array($rec_tmp['role_id'], explode(';', $_SESSION['fonction_id']))) {
+                    $restrictionActive = false;
+                }
             }
 
             // Uncrypt PW
-            if (null !== filter_input(INPUT_POST, 'salt_key_required', FILTER_SANITIZE_STRING)
-                && filter_input(INPUT_POST, 'salt_key_required', FILTER_SANITIZE_STRING) === '1'
-                && null !== filter_input(INPUT_POST, 'salt_key_set', FILTER_SANITIZE_STRING)
-                && filter_input(INPUT_POST, 'salt_key_set', FILTER_SANITIZE_STRING) === '1'
+            if (null !== $post_salt_key_required
+                && $post_salt_key_required === '1'
+                && null !== $post_salt_key_set
+                && $post_salt_key_set === '1'
             ) {
                 $pw = cryption(
                     $dataItem['pw'],
                     $_SESSION['user_settings']['session_psk'],
                     "decrypt"
@@ -1440,29 +1472,37 @@ if (null !== $post_type) {
             if (!isUTF8($pw)) {
                 $pw = '';
             }
 
             // check if item is expired
-            if (null !== filter_input(INPUT_POST, 'expired_item', FILTER_SANITIZE_STRING)
-                && filter_input(INPUT_POST, 'expired_item', FILTER_SANITIZE_STRING) === '1'
+            if (null !== $post_expired_item
+                && $post_expired_item === '1'
             ) {
                 $item_is_expired = true;
             } else {
                 $item_is_expired = false;
             }
+
+
             // check user is admin
             if ($_SESSION['user_admin'] === '1' && $dataItem['perso'] != 1 && (isset($SETTINGS_EXT['admin_full_right']) && $SETTINGS_EXT['admin_full_right'] === true) || !isset($SETTINGS_EXT['admin_full_right'])) {
                 $arrData['show_details'] = 0;
             // Check if actual USER can see this ITEM
             } elseif ((
                 (in_array($dataItem['id_tree'], $_SESSION['groupes_visibles']) || $_SESSION['is_admin'] === '1') && ($dataItem['perso'] === '0' || ($dataItem['perso'] === '1' && $dataItem['id_user'] == $_SESSION['user_id'])) && $restrictionActive === false)
                 ||
                 (isset($SETTINGS['anyone_can_modify']) && $SETTINGS['anyone_can_modify'] === '1' && $dataItem['anyone_can_modify'] === '1' && (in_array($dataItem['id_tree'], $_SESSION['groupes_visibles']) || $_SESSION['is_admin'] === '1') && $restrictionActive === false)
                 ||
                 (null !== $post_folder_id
-                    && isset($_SESSION['list_folders_limited'][$post_folder_id])
-                    && in_array($post_id, $_SESSION['list_folders_limited'][$post_folder_id]))
+                    && isset($_SESSION['list_restricted_folders_for_items'][$post_folder_id])
+                    && in_array($post_id, $_SESSION['list_restricted_folders_for_items'][$post_folder_id])
+                    && $post_restricted === '1'
+                    && $user_in_restricted_list_of_item === true)
+                ||
+                (isset($SETTINGS['restricted_to_roles']) && $SETTINGS['restricted_to_roles'] === '1'
+                    && $restrictionActive === false
+                )
             ) {
                 // Allow show details
                 $arrData['show_details'] = 1;
                 // Display menu icon for deleting if user is allowed
                 if ($dataItem['id_user'] == $_SESSION['user_id']
@@ -1624,12 +1664,12 @@ if (null !== $post_type) {
                 }
                 $arrData['fields'] = $fieldsTmp;
                 $arrData['categories'] = $arrCatList;
 
                 // Manage user restriction
-                if (null !== filter_input(INPUT_POST, 'restricted', FILTER_SANITIZE_STRING)) {
-                    $arrData['restricted'] = filter_input(INPUT_POST, 'restricted', FILTER_SANITIZE_STRING);
+                if (null !== $post_restricted) {
+                    $arrData['restricted'] = $post_restricted;
                 } else {
                     $arrData['restricted'] = "";
                 }
                 // Decrement the number before being deleted
                 $dataDelete = DB::queryfirstrow("SELECT * FROM ".prefix_table("automatic_del")." WHERE item_id=%i", $post_id);
@@ -1722,10 +1762,17 @@ if (null !== $post_type) {
         */
         case "showDetailsStep2":
             // get Item info
             $dataItem = DB::queryfirstrow("SELECT * FROM ".prefix_table("items")." WHERE id=%i", $post_id);
 
+            // Check if the folder where this item is, is accessible to the user
+            if (in_array($dataItem['id_tree'], $_SESSION['groupes_visibles'])) {
+                $returnValues = '[{"error" : "not_allowed"}, {"error_text" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
+                echo prepareExchangedData($returnValues, "encode");
+                break;
+            }
+
             // GET Audit trail
             $history = "";
             $historyOfPws = "";
             $rows = DB::query(
                 "SELECT l.date as date, l.action as action, l.raison as raison, u.login as login, l.raison_iv AS raison_iv
@@ -1842,11 +1889,12 @@ if (null !== $post_type) {
                     "history" => htmlspecialchars($history, ENT_QUOTES, 'UTF-8'),
                     "history_of_pwds" => htmlspecialchars($historyOfPws, ENT_QUOTES, 'UTF-8'),
                     "favourite" => $favourite,
                     "files_edit" => $filesEdit,
                     "files_id" => $files_id,
-                    "has_change_proposal" => DB::count()
+                    "has_change_proposal" => DB::count(),
+                    "error" => ""
                 ),
                 "encode"
             );
             break;
 
@@ -1866,10 +1914,25 @@ if (null !== $post_type) {
             if ($_SESSION['user_read_only'] === true && !in_array($dataReceived['categorie'], $_SESSION['personal_folders'])) {
                 echo prepareExchangedData(array("error" => "ERR_FOLDER_NOT_ALLOWED"), "encode");
                 break;
             }
 
+            // Check that user can access this item
+            $granted = accessToItemIsGranted($post_id);
+            if ($granted !== true) {
+                echo prepareExchangedData(array("error" => $granted), "encode");
+                break;
+            }
+
+            // Load item data
+            $data = DB::queryFirstRow(
+                "SELECT id_tree
+                FROM ".prefix_table("items")."
+                WHERE id = %i",
+                $post_id
+            );
+
             // delete item consists in disabling it
             DB::update(
                 prefix_table("items"),
                 array(
                     'inactif' => '1',
@@ -1885,22 +1948,30 @@ if (null !== $post_type) {
 
         /*
         * CASE
         * Update a Group
         */
-        case "update_rep":
+        case "update_folder":
             // Check KEY and rights
             if ($post_key !== $_SESSION['key'] || $_SESSION['user_read_only'] === true) {
                 $returnValues = '[{"error" : "not_allowed"}, {"error_text" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
                 echo $returnValues;
                 break;
             }
             // decrypt and retreive data in JSON format
             $dataReceived = prepareExchangedData($post_data, "decode");
 
             // Prepare variables
-            $title = htmlspecialchars_decode($dataReceived['title']);
+            $title = filter_var(htmlspecialchars_decode($dataReceived['title']), FILTER_SANITIZE_STRING);
+            $post_folder_id = filter_var(htmlspecialchars_decode($dataReceived['folder']), FILTER_SANITIZE_NUMBER_INT);
+
+            // Check if user is allowed to access this folder
+            if (!in_array($post_folder_id, $_SESSION['groupes_visibles'])) {
+                echo '[{"error" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
+                break;
+            }
+
             // Check if title doesn't contains html codes
             if (preg_match_all("|<[^>]+>(.*)</[^>]+>|U", $title, $out)) {
                 echo '[ { "error" : "'.addslashes($LANG['error_html_codes']).'" } ]';
                 break;
             }
@@ -1923,11 +1994,11 @@ if (null !== $post_type) {
             // query on folder
             $data = DB::queryfirstrow(
                 "SELECT parent_id, personal_folder
                 FROM ".prefix_table("nested_tree")."
                 WHERE id = %i",
-                $dataReceived['folder']
+                $post_folder_id
             );
 
             // check if complexity level is good
             // if manager or admin don't care
             if ($_SESSION['is_admin'] != 1 && $_SESSION['user_manager'] != 1 && $data['personal_folder'] === '0') {
@@ -1954,20 +2025,20 @@ if (null !== $post_type) {
                     prefix_table("nested_tree"),
                     array(
                         'title' => $title
                         ),
                     'id=%s',
-                    $dataReceived['folder']
+                    $post_folder_id
                 );
                 // update complixity value
                 DB::update(
                     prefix_table("misc"),
                     array(
                         'valeur' => $dataReceived['complexity']
                         ),
                     'intitule = %s AND type = %s',
-                    $dataReceived['folder'],
+                    $post_folder_id,
                     "complex"
                 );
                 // rebuild fuild tree folder
                 $tree->rebuild();
             }
@@ -1986,27 +2057,38 @@ if (null !== $post_type) {
                 echo $returnValues;
                 break;
             }
             // decrypt and retreive data in JSON format
             $dataReceived = prepareExchangedData($post_data, "decode");
+            $post_source_folder_id = filter_var(htmlspecialchars_decode($dataReceived['source_folder_id']), FILTER_SANITIZE_NUMBER_INT);
+            $post_target_folder_id = filter_var(htmlspecialchars_decode($dataReceived['target_folder_id']), FILTER_SANITIZE_NUMBER_INT);
+
+            // Check that user can access this folder
+            if (!in_array($post_source_folder_id, $_SESSION['groupes_visibles'])
+                || !in_array($post_target_folder_id, $_SESSION['groupes_visibles'])
+            ) {
+                $returnValues = '[{"error" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
+                echo $returnValues;
+                break;
+            }
 
             $tmp_source = DB::queryFirstRow(
                 "SELECT title, parent_id, personal_folder
                 FROM ".prefix_table("nested_tree")."
                 WHERE id = %i",
-                $dataReceived['source_folder_id']
+                $post_source_folder_id
             );
 
             $tmp_target = DB::queryFirstRow(
                 "SELECT title, parent_id, personal_folder
                 FROM ".prefix_table("nested_tree")."
                 WHERE id = %i",
-                $dataReceived['target_folder_id']
+                $post_target_folder_id
             );
 
             // check if target is not a child of source
-            if ($tree->isChildOf($dataReceived['target_folder_id'], $dataReceived['source_folder_id']) === true) {
+            if ($tree->isChildOf($post_target_folder_id, $post_source_folder_id) === true) {
                 $returnValues = '[{"error" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
                 echo $returnValues;
                 break;
             }
 
@@ -2027,14 +2109,14 @@ if (null !== $post_type) {
             if ($tmp_source['parent_id'] !== "0") {
                 // moving SOURCE folder
                 DB::update(
                     prefix_table("nested_tree"),
                     array(
-                        'parent_id' => $dataReceived['target_folder_id']
+                        'parent_id' => $post_target_folder_id
                         ),
                     'id=%s',
-                    $dataReceived['source_folder_id']
+                    $post_source_folder_id
                 );
                 $tree->rebuild();
             }
 
 
@@ -2820,53 +2902,37 @@ if (null !== $post_type) {
                 "personal" => $folder_is_personal
             );
             echo prepareExchangedData($returnValues, "encode");
             break;
 
-        /*
-          * CASE
-          * WANT TO CLIPBOARD PW/LOGIN OF ITEM
-        */
-        case "get_clipboard_item":
-            $dataItem = DB::queryfirstrow(
-                "SELECT pw,login,perso FROM ".prefix_table("items")." WHERE id=%i",
-                $post_id
-            );
-
-            if (filter_input(INPUT_POST, 'field', FILTER_SANITIZE_STRING) === "pw") {
-                if ($dataItem['perso'] === '1') {
-                    $data = cryption(
-                        $dataItem['pw'],
-                        $_SESSION['user_settings']['session_psk'],
-                        "decrypt"
-                    );
-                } else {
-                    $data = cryption(
-                        $dataItem['pw'],
-                        "",
-                        "decrypt"
-                    );
-                }
-            } else {
-                $data = $dataItem['login'];
-            }
-            // Encrypt data to return
-            echo prepareExchangedData($data, "encode");
-            break;
-
         /*
         * CASE
         * DELETE attached file from an item
         */
         case "delete_attached_file":
             // Get some info before deleting
             $data = DB::queryFirstRow(
-                "SELECT name,id_item,file
+                "SELECT name, id_item, file
                 FROM ".prefix_table("files")."
                 WHERE id = %i",
                 filter_input(INPUT_POST, 'file_id', FILTER_SANITIZE_NUMBER_INT)
             );
+
+            // Load item data
+            $data_item = DB::queryFirstRow(
+                "SELECT id_tree
+                FROM ".prefix_table("items")."
+                WHERE id = %i",
+                $data['id_item']
+            );
+
+            // Check that user can access this folder
+            if (!in_array($data_item['id_tree'], $_SESSION['groupes_visibles'])) {
+                echo prepareExchangedData(array("error" => "ERR_FOLDER_NOT_ALLOWED"), "encode");
+                break;
+            }
+
             if (!empty($data['id_item'])) {
                 // Delete from FILES table
                 DB::delete(
                     prefix_table("files"),
                     "id = %i",
@@ -3000,10 +3066,18 @@ if (null !== $post_type) {
             $dataDestination = DB::queryfirstrow(
                 "SELECT personal_folder, title FROM ".prefix_table("nested_tree")." WHERE id = %i",
                 $post_folder_id
             );
 
+            // Check that user can access this folder
+            if (!in_array($dataSource['id_tree'], $_SESSION['groupes_visibles'])
+                || !in_array($post_folder_id, $_SESSION['groupes_visibles'])
+            ) {
+                echo '[{"error" => "ERR_FOLDER_NOT_ALLOWED"}]';
+                break;
+            }
+
             // previous is non personal folder and new too
             if ($dataSource['personal_folder'] === '0' && $dataDestination['personal_folder'] === '0') {
                 // just update is needed. Item key is the same
                 DB::update(
                     prefix_table("items"),
@@ -3106,10 +3180,19 @@ if (null !== $post_type) {
                         FROM ".prefix_table("items")." as i
                         INNER JOIN ".prefix_table("nested_tree")." as f ON (i.id_tree=f.id)
                         WHERE i.id=%i",
                         $item_id
                     );
+
+                    // Check that user can access this folder
+                    if (!in_array($dataSource['id_tree'], $_SESSION['groupes_visibles'])
+                        || !in_array($post_folder_id, $_SESSION['groupes_visibles'])
+                    ) {
+                        echo '[{"error":"not_allowed" , "status":"ok"}]';
+                        break;
+                    }
+
                     // get data about new folder
                     $dataDestination = DB::queryfirstrow(
                         "SELECT personal_folder, title FROM ".prefix_table("nested_tree")." WHERE id = %i",
                         $post_folder_id
                     );
@@ -3225,10 +3308,18 @@ if (null !== $post_type) {
                         FROM ".prefix_table("items")."
                         WHERE id=%i",
                         $item_id
                     );
 
+                    // Check that user can access this folder
+                    if (!in_array($dataSource['id_tree'], $_SESSION['groupes_visibles'])
+                        || !in_array($post_folder_id, $_SESSION['groupes_visibles'])
+                    ) {
+                        echo prepareExchangedData(array("error" => "ERR_FOLDER_NOT_ALLOWED"), "encode");
+                        break;
+                    }
+
                     // perform a check in case of Read-Only user creating an item in his PF
                     if ($_SESSION['user_read_only'] === true) {
                         echo prepareExchangedData(array("error" => "ERR_FOLDER_NOT_ALLOWED"), "encode");
                         break;
                     }
diff --git a/sources/main.functions.php b/sources/main.functions.php
index 991afa305..f40bee68c 100644
--- a/sources/main.functions.php
+++ b/sources/main.functions.php
@@ -628,11 +628,11 @@ function identifyUserRights($groupesVisiblesUser, $groupesInterditsUser, $isAdmi
                 }
             }
         }
 
         // get complete list of ROLES
-        $tmp = explode(";", $_SESSION['fonction_id']);
+        $tmp = explode(";", $idFonctions);
         $rows = DB::query(
             "SELECT * FROM ".prefix_table("roles_title")."
             ORDER BY title ASC"
         );
         foreach ($rows as $record) {
@@ -654,10 +654,11 @@ function identifyUserRights($groupesVisiblesUser, $groupesInterditsUser, $isAdmi
         $_SESSION['groupes_visibles'] = array();
         $_SESSION['personal_folders'] = array();
         $_SESSION['groupes_interdits'] = array();
         $_SESSION['personal_visible_groups'] = array();
         $_SESSION['read_only_folders'] = array();
+        $_SESSION['fonction_id'] = $idFonctions;
         $groupesInterdits = array();
         if (!is_array($groupesInterditsUser)) {
             $groupesInterditsUser = explode(';', trimElement($groupesInterditsUser, ";"));
         }
         if (!empty($groupesInterditsUser) && count($groupesInterditsUser) > 0) {
@@ -2108,5 +2109,27 @@ function chmodRecursive($dir, $dirPermissions, $filePermissions)
         $res = @chmod($dir, $dirPermissions);
     }
 
     return $res;
 }
+
+/**
+ * Check if user can access to this item
+ * @param $item_id
+ */
+function accessToItemIsGranted($item_id)
+{
+    // Load item data
+    $data = DB::queryFirstRow(
+        "SELECT id_tree
+        FROM ".prefix_table("items")."
+        WHERE id = %i",
+        $item_id
+    );
+
+    // Check if user can access this folder
+    if (!in_array($data['id'], $_SESSION['groupes_visibles'])) {
+        return "ERR_FOLDER_NOT_ALLOWED";
+    }
+
+    return true;
+}

Vulnerable code:     require_once $SETTINGS['cpassman_dir'].'/includes/language/'.$session_user_language.'.php';
                    $("#display_categories").val(data.displayCategories);
                        if ($(".tr_fields") != undefined && data.displayCategories != "") {
                        if ($(".tr_fields") != undefined && data.displayCategories != "") {
                                        type     : "move_item",
                                        item_id : ui.draggable.attr("id"),
                                        key        : "<?php echo $_SESSION['key']; ?>"
                    if (data.error == "ERR_JSON_FORMAT") {
                        $("#edit_show_error").html(data.error + ' ERROR (JSON is broken)!!!!!');
                        $("#edit_show_error").show();
                    } else if (data.error == "ERR_KEY_NOT_CORRECT") {
                        $("#edit_show_error").html('Key verification for Query is not correct!');
                        $("#edit_show_error").show();
                    }else if (data.error == "ERR_ENCRYPTION_NOT_CORRECT") {
                        $("#edit_show_error").html('Item password could not be correctly encrypted!');
                        $("#edit_show_error").show();
                    } else if (data.error == "ERR_PWD_TOO_LONG") {
                        $("#edit_show_error").html('<?php echo addslashes($LANG['error_pw_too_long']); ?>');
                        $("#edit_show_error").show();
                    } else if (data.error == "ERR_NOT_ALLOWED_TO_EDIT") {
                        $("#new_show_error").html('User not allowed to edit this Item!');
                        $("#new_show_error").show();
                    } else if (data.error != "") {
                        $("#edit_show_error").html('<?php echo addslashes($LANG['error_not_allowed_to']); ?>');
                        $("#edit_show_error").show();
                    type                : 'show_details_item',
                    id                  : id,
                    folder_id           : $('#hid_cat').val(),
                    salt_key_required   : $('#recherche_group_pf').val(),
                    salt_key_set        : $('#personal_sk_set').val(),
                    expired_item        : expired_item,
                    restricted          : restricted,
                    page                : "items",
                    key                 : "<?php echo $_SESSION['key']; ?>"
                    } else if (data.show_details == "1" && data.show_detail_option == "2") {
                            type    : "update_rep",
        require_once $SETTINGS['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
            $label = noHTML(htmlspecialchars_decode($dataReceived['label']));
            $url = htmlspecialchars_decode($dataReceived['url']);
            $login = htmlspecialchars_decode($dataReceived['login']);
                $label = noHTML(($dataReceived['label']));
                $url = noHTML(htmlspecialchars_decode($dataReceived['url']));
                $login = noHTML(htmlspecialchars_decode($dataReceived['login']));
                $email = noHTML(htmlspecialchars_decode($dataReceived['email']));
                    (@in_array(
                        $post_id,
                        $_SESSION['list_folders_limited'][$post_folder_id]
                    ))
                $returnValues = '[{"error" : "not_allowed"}, {"error_text" : "2'.addslashes($LANG['error_not_allowed_to']).'"}]';
            if (null !== $post_item_id
                && empty($post_item_id) === false
            $rows_tmp = DB::query("SELECT role_id FROM ".prefix_table("restriction_to_roles")." WHERE item_id=%i", $post_id);
            $myTest = 0;
            if (in_array($_SESSION['user_id'], $rows_tmp)) {
                $myTest = 1;
            if (null !== filter_input(INPUT_POST, 'salt_key_required', FILTER_SANITIZE_STRING)
                && filter_input(INPUT_POST, 'salt_key_required', FILTER_SANITIZE_STRING) === '1'
                && null !== filter_input(INPUT_POST, 'salt_key_set', FILTER_SANITIZE_STRING)
                && filter_input(INPUT_POST, 'salt_key_set', FILTER_SANITIZE_STRING) === '1'
            if (null !== filter_input(INPUT_POST, 'expired_item', FILTER_SANITIZE_STRING)
                && filter_input(INPUT_POST, 'expired_item', FILTER_SANITIZE_STRING) === '1'
                    && isset($_SESSION['list_folders_limited'][$post_folder_id])
                    && in_array($post_id, $_SESSION['list_folders_limited'][$post_folder_id]))
                if (null !== filter_input(INPUT_POST, 'restricted', FILTER_SANITIZE_STRING)) {
                    $arrData['restricted'] = filter_input(INPUT_POST, 'restricted', FILTER_SANITIZE_STRING);
                    "has_change_proposal" => DB::count()
        case "update_rep":
            $title = htmlspecialchars_decode($dataReceived['title']);
                $dataReceived['folder']
                    $dataReceived['folder']
                    $dataReceived['folder'],
                $dataReceived['source_folder_id']
                $dataReceived['target_folder_id']
            if ($tree->isChildOf($dataReceived['target_folder_id'], $dataReceived['source_folder_id']) === true) {
                        'parent_id' => $dataReceived['target_folder_id']
                    $dataReceived['source_folder_id']
        /*
          * CASE
          * WANT TO CLIPBOARD PW/LOGIN OF ITEM
        */
        case "get_clipboard_item":
            $dataItem = DB::queryfirstrow(
                "SELECT pw,login,perso FROM ".prefix_table("items")." WHERE id=%i",
                $post_id
            );

            if (filter_input(INPUT_POST, 'field', FILTER_SANITIZE_STRING) === "pw") {
                if ($dataItem['perso'] === '1') {
                    $data = cryption(
                        $dataItem['pw'],
                        $_SESSION['user_settings']['session_psk'],
                        "decrypt"
                    );
                } else {
                    $data = cryption(
                        $dataItem['pw'],
                        "",
                        "decrypt"
                    );
                }
            } else {
                $data = $dataItem['login'];
            }
            // Encrypt data to return
            echo prepareExchangedData($data, "encode");
            break;

                "SELECT name,id_item,file
        $tmp = explode(";", $_SESSION['fonction_id']);
Fixed code:     if (file_exists($SETTINGS['cpassman_dir'].'/includes/language/'.$session_user_language.'.php') === true) {
        require_once $SETTINGS['cpassman_dir'].'/includes/language/'.$session_user_language.'.php';
    }
                    if (data.displayCategories !== undefined) {
                        $("#display_categories").val(data.displayCategories);
                    }
                        if ($(".tr_fields") !== undefined && data.displayCategories !== undefined && data.displayCategories !== "") {
                        if ($(".tr_fields") != undefined && data.displayCategories !== undefined && data.displayCategories != "") {
                                        type      : "move_item",
                                        item_id   : ui.draggable.attr("id"),
                                        key       : "<?php echo $_SESSION['key']; ?>"
                    if (data.error === "ERR_JSON_FORMAT") {
                        $("#edit_show_error")
                            .html(data.error + ' ERROR (JSON is broken)!!!!!')
                            .show();
                    } else if (data.error === "ERR_KEY_NOT_CORRECT") {
                        $("#edit_show_error")
                            .html('Key verification for Query is not correct!')
                            .show();
                    }else if (data.error === "ERR_ENCRYPTION_NOT_CORRECT") {
                        $("#edit_show_error")
                            .html('Item password could not be correctly encrypted!')
                            .show();
                    } else if (data.error === "ERR_PWD_TOO_LONG") {
                        $("#edit_show_error")
                            .html('<?php echo addslashes($LANG['error_pw_too_long']); ?>')
                            .show();
                    } else if (data.error === "ERR_NOT_ALLOWED_TO_EDIT") {
                        $("#new_show_error")
                            .html('User not allowed to edit this Item!')
                            .show();
                    } else if (data.error !== "") {
                        $("#edit_show_error")
                            .html('<?php echo addslashes($LANG['error_not_allowed_to']); ?>')
                            .show();
            var data = {
                "id" : id,
                "folder_id" : $('#hid_cat').val(),
                "salt_key_required" : $('#recherche_group_pf').val(),
                "salt_key_set" : $('#personal_sk_set').val(),
                "expired_item" : expired_item,
                "restricted" : restricted,
                "page" : "items"
            };

                    type : 'show_details_item',
                    data : prepareExchangedData(JSON.stringify(data), "encode", "<?php echo $_SESSION['key']; ?>"),
                    key  : "<?php echo $_SESSION['key']; ?>"
                    } else if (data.show_details === "1" && data.show_detail_option === "2") {
            if (data.error !== "") {
                $("#div_dialog_message_text").html(data.error_text);
                $("#div_dialog_message").show();
            }

                            type    : "update_folder",
        if (file_exists($SETTINGS['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php') === true) {
            require_once $SETTINGS['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
        }
            $label = filter_var(htmlspecialchars_decode($dataReceived['label']), FILTER_SANITIZE_STRING);
            $url = filter_var(htmlspecialchars_decode($dataReceived['url']), FILTER_SANITIZE_STRING);
            $login = filter_var(htmlspecialchars_decode($dataReceived['login']), FILTER_SANITIZE_STRING);
                $label = filter_var(($dataReceived['label']), FILTER_SANITIZE_STRING);
                $url = filter_var(htmlspecialchars_decode($dataReceived['url']), FILTER_SANITIZE_STRING);
                $login = filter_var(htmlspecialchars_decode($dataReceived['login']), FILTER_SANITIZE_STRING);
                $email = filter_var(htmlspecialchars_decode($dataReceived['email']), FILTER_SANITIZE_STRING);
                    (null !== $post_folder_id
                    && isset($_SESSION['list_restricted_folders_for_items'][$post_folder_id])
                    && in_array($post_id, $_SESSION['list_restricted_folders_for_items'][$post_folder_id])
                    && $post_restricted === '1'
                    && $restrictionActive === false)
                $returnValues = '[{"error" : "not_allowed"}, {"error_text" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
            if (empty($post_item_id) === false

                // Check if the folder where this item is, is accessible to the user
                if (in_array($originalRecord['id_tree'], $_SESSION['groupes_visibles'])) {
                    $returnValues = '[{"error" : "not_allowed"}, {"error_text" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
                    echo $returnValues;
                    break;
                }

                // Load the destination folder record into an array
            // Decrypt and retreive data in JSON format
            $dataReceived = prepareExchangedData($post_data, "decode");
            // Init post variables
            $post_id = filter_var(htmlspecialchars_decode($dataReceived['id']), FILTER_SANITIZE_NUMBER_INT);
            $post_folder_id = filter_var(htmlspecialchars_decode($dataReceived['folder_id']), FILTER_SANITIZE_NUMBER_INT);
            $post_salt_key_required = filter_var(htmlspecialchars_decode($dataReceived['salt_key_required']), FILTER_SANITIZE_STRING);
            $post_salt_key_set = filter_var(htmlspecialchars_decode($dataReceived['salt_key_set']), FILTER_SANITIZE_STRING);
            $post_expired_item = filter_var(htmlspecialchars_decode($dataReceived['expired_item']), FILTER_SANITIZE_STRING);
            $post_restricted = filter_var(htmlspecialchars_decode($dataReceived['restricted']), FILTER_SANITIZE_STRING);
            $post_page = filter_var(htmlspecialchars_decode($dataReceived['page']), FILTER_SANITIZE_STRING);

            $user_in_restricted_list_of_item = false;
                    if ($_SESSION['user_id'] === $record['id']) {
                        $user_in_restricted_list_of_item = true;
                    }


            $rows_tmp = DB::query(
                "SELECT role_id
                FROM ".prefix_table("restriction_to_roles")."
                WHERE item_id=%i",
                $post_id
            );
            foreach ($rows_tmp as $rec_tmp) {
                if (in_array($rec_tmp['role_id'], explode(';', $_SESSION['fonction_id']))) {
                    $restrictionActive = false;
                }
            if (null !== $post_salt_key_required
                && $post_salt_key_required === '1'
                && null !== $post_salt_key_set
                && $post_salt_key_set === '1'
            if (null !== $post_expired_item
                && $post_expired_item === '1'


                    && isset($_SESSION['list_restricted_folders_for_items'][$post_folder_id])
                    && in_array($post_id, $_SESSION['list_restricted_folders_for_items'][$post_folder_id])
                    && $post_restricted === '1'
                    && $user_in_restricted_list_of_item === true)
                ||
                (isset($SETTINGS['restricted_to_roles']) && $SETTINGS['restricted_to_roles'] === '1'
                    && $restrictionActive === false
                )
                if (null !== $post_restricted) {
                    $arrData['restricted'] = $post_restricted;
            // Check if the folder where this item is, is accessible to the user
            if (in_array($dataItem['id_tree'], $_SESSION['groupes_visibles'])) {
                $returnValues = '[{"error" : "not_allowed"}, {"error_text" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
                echo prepareExchangedData($returnValues, "encode");
                break;
            }

                    "has_change_proposal" => DB::count(),
                    "error" => ""
            // Check that user can access this item
            $granted = accessToItemIsGranted($post_id);
            if ($granted !== true) {
                echo prepareExchangedData(array("error" => $granted), "encode");
                break;
            }

            // Load item data
            $data = DB::queryFirstRow(
                "SELECT id_tree
                FROM ".prefix_table("items")."
                WHERE id = %i",
                $post_id
            );

        case "update_folder":
            $title = filter_var(htmlspecialchars_decode($dataReceived['title']), FILTER_SANITIZE_STRING);
            $post_folder_id = filter_var(htmlspecialchars_decode($dataReceived['folder']), FILTER_SANITIZE_NUMBER_INT);

            // Check if user is allowed to access this folder
            if (!in_array($post_folder_id, $_SESSION['groupes_visibles'])) {
                echo '[{"error" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
                break;
            }

                $post_folder_id
                    $post_folder_id
                    $post_folder_id,
            $post_source_folder_id = filter_var(htmlspecialchars_decode($dataReceived['source_folder_id']), FILTER_SANITIZE_NUMBER_INT);
            $post_target_folder_id = filter_var(htmlspecialchars_decode($dataReceived['target_folder_id']), FILTER_SANITIZE_NUMBER_INT);

            // Check that user can access this folder
            if (!in_array($post_source_folder_id, $_SESSION['groupes_visibles'])
                || !in_array($post_target_folder_id, $_SESSION['groupes_visibles'])
            ) {
                $returnValues = '[{"error" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
                echo $returnValues;
                break;
            }
                $post_source_folder_id
                $post_target_folder_id
            if ($tree->isChildOf($post_target_folder_id, $post_source_folder_id) === true) {
                        'parent_id' => $post_target_folder_id
                    $post_source_folder_id
                "SELECT name, id_item, file

            // Load item data
            $data_item = DB::queryFirstRow(
                "SELECT id_tree
                FROM ".prefix_table("items")."
                WHERE id = %i",
                $data['id_item']
            );

            // Check that user can access this folder
            if (!in_array($data_item['id_tree'], $_SESSION['groupes_visibles'])) {
                echo prepareExchangedData(array("error" => "ERR_FOLDER_NOT_ALLOWED"), "encode");
                break;
            }

            // Check that user can access this folder
            if (!in_array($dataSource['id_tree'], $_SESSION['groupes_visibles'])
                || !in_array($post_folder_id, $_SESSION['groupes_visibles'])
            ) {
                echo '[{"error" => "ERR_FOLDER_NOT_ALLOWED"}]';
                break;
            }


                    // Check that user can access this folder
                    if (!in_array($dataSource['id_tree'], $_SESSION['groupes_visibles'])
                        || !in_array($post_folder_id, $_SESSION['groupes_visibles'])
                    ) {
                        echo '[{"error":"not_allowed" , "status":"ok"}]';
                        break;
                    }

                    // Check that user can access this folder
                    if (!in_array($dataSource['id_tree'], $_SESSION['groupes_visibles'])
                        || !in_array($post_folder_id, $_SESSION['groupes_visibles'])
                    ) {
                        echo prepareExchangedData(array("error" => "ERR_FOLDER_NOT_ALLOWED"), "encode");
                        break;
                    }

        $tmp = explode(";", $idFonctions);
        $_SESSION['fonction_id'] = $idFonctions;

/**
 * Check if user can access to this item
 * @param $item_id
 */
function accessToItemIsGranted($item_id)
{
    // Load item data
    $data = DB::queryFirstRow(
        "SELECT id_tree
        FROM ".prefix_table("items")."
        WHERE id = %i",
        $item_id
    );

    // Check if user can access this folder
    if (!in_array($data['id'], $_SESSION['groupes_visibles'])) {
        return "ERR_FOLDER_NOT_ALLOWED";
    }

    return true;
}