CVE-2017-15054: Unrestricted Upload of File with Dangerous Type (CWE-434)
value: An arbitrary file upload vulnerability, present in TeamPass before 2.1.27.9, allows remote authenticated users to upload arbitrary files leading to Remote Command Execution. To exploit this vulnerability, an authenticated attacker has to tamper with parameters of a request to upload.files.php, in order to select the correct branch and be able to upload any arbitrary file. From there, it can simply access the file to execute code on the server.
CWE description: The product allows the upload or transfer of dangerous file types that are automatically processed within its environment.
CVSS v3 base score: 7.5
Published: 2017-11-27T19:29Z
Repository: https://github.com/nilsteampassnet/TeamPass
Language: PHP
Files changed: admin.settings.load.php, admin.settings.php, api/functions.php, changelog.md, items.import.php, items.load.php, items.php, profile.php, sources/admin.queries.php, sources/import.queries.php, sources/items.queries.php, sources/main.functions.php, sources/upload/upload.files.php
Commit date: 2017-10-02 21:27:30 +0200
Commit message: 2.1.27

Improved security regarding uploading files
Fixed issue while restoring DB from administration page

Diff: diff --git a/admin.settings.load.php b/admin.settings.load.php
index 4f8d388f0..33231fe79 100644
--- a/admin.settings.load.php
+++ b/admin.settings.load.php
@@ -250,11 +250,14 @@ function LaunchAdminActions(action, option)
     $("#email_testing_results, #result_admin_script_backup").hide();
     $("#result_admin_action_db_backup").html("");
     if (action === "admin_action_db_backup") {
         option = $("#result_admin_action_db_backup_key").val();
     } else if (action === "admin_action_db_restore") {
-        $("#restore_bck_encryption_key_dialog_error").html("").hide();
+        $("#restore_bck_encryption_key_dialog_error")
+            .html("<span class='fa fa-cog fa-spin fa'>&nbsp;</span><?php echo addslashes($LANG['please_wait']); ?>")
+            .attr("class","ui-corner-all ui-state-focus")
+            .show();
     } else if (action === "admin_action_backup_decrypt") {
         option = $("#bck_script_decrypt_file").val();
     } else if (action === "admin_action_change_salt_key") {
         option = prepareExchangedData(
             sanitizeString($("#new_salt_key").val()),
@@ -291,10 +294,11 @@ function LaunchAdminActions(action, option)
         if (option === "" || option.length === 0) return;
 
         // convert to json string
         option = prepareExchangedData(JSON.stringify(option) , "encode", "<?php echo $_SESSION['key']; ?>");
     }
+
     //Lauchn ajax query
     $.post(
         "sources/admin.queries.php",
         {
            type        : action,
@@ -307,11 +311,14 @@ function LaunchAdminActions(action, option)
                     $("#result_admin_action_db_backup").html("<span class='fa fa-file-code-o'></span>&nbsp;<a href='"+data[0].href+"'><?php echo $LANG['pdf_download']; ?></a>").show();
                 } else if (data[0].result == "pf_done") {
                     $("#result_admin_action_check_pf").html("<span class='fa fa-check mi-green'></span>").show();
                 } else if (data[0].result == "db_restore") {
                     if (data[0].message !== "") {
-                        $("#restore_bck_encryption_key_dialog_error").html(data[0].message).show();
+                        $("#restore_bck_encryption_key_dialog_error")
+                            .html(data[0].message)
+                            .attr("class","ui-corner-all ui-state-error")
+                            .show();
                     } else {
                         $("#restore_bck_encryption_key_dialog").dialog("close");
                         $("#result_admin_action_db_restore").html("<span class='fa fa-check mi-green'></span>").show();
                         $("#result_admin_action_db_restore_get_file").hide();
                         //deconnect userd
@@ -832,10 +839,11 @@ $(function() {
             $("#restore_bck_encryption_key_dialog").dialog("close");
         }
     });
 
     // SQL IMPORT FOR RESTORING
+    var restore_operation_id = '';
     var uploader_restoreDB = new plupload.Uploader({
         runtimes : "gears,html5,flash,silverlight,browserplus",
         browse_button : "pickfiles_restoreDB",
         container : "upload_container_restoreDB",
         max_file_size : "10mb",
@@ -874,21 +882,19 @@ $(function() {
                 );
             },
             BeforeUpload: function (up, file) {
                 $("#import_status_ajax_loader").show();
                 up.settings.multipart_params = {
-                    "PHPSESSID":"'.$_SESSION['user_id'].'",
+                    "PHPSESSID":"<?php echo $_SESSION['user_id']; ?>",
                     "File":file.name,
                     "type_upload":"restore_db",
                     "user_token": $("#user_token").val()
                 };
             },
             UploadComplete: function(up, files) {
-                $.each(files, function(i, file) {
-                    $("#restore_bck_fileObj").val(file.name);
-                    $("#restore_bck_encryption_key_dialog").dialog("open");
-                });
+                $("#restore_bck_fileObj").val(restore_operation_id);
+                $("#restore_bck_encryption_key_dialog").dialog("open");
             }
         }
     });
     // Uploader options
     uploader_restoreDB.bind("UploadProgress", function(up, file) {
@@ -903,10 +909,15 @@ $(function() {
         up.refresh(); // Reposition Flash/Silverlight
     });
     uploader_restoreDB.bind("+", function(up, file) {
         $("#" + file.id + " b").html("100%");
     });
+    uploader_restoreDB.bind('FileUploaded', function(upldr, file, object) {
+        var myData = prepareExchangedData(object.response, "decode", "<?php echo $_SESSION['key']; ?>");
+
+        restore_operation_id = myData.operation_id;
+    });
     // Load CSV click
     $("#uploadfiles_restoreDB").click(function(e) {
         uploader_restoreDB.start();
         e.preventDefault();
     });
diff --git a/admin.settings.php b/admin.settings.php
index f818f1e3e..279cdc6e0 100644
--- a/admin.settings.php
+++ b/admin.settings.php
@@ -1616,8 +1616,8 @@ echo '
 echo '
 <input id="restore_bck_fileObj" name="restore_bck_fileObj" type="hidden" value="" />
 <div id="restore_bck_encryption_key_dialog" style="display:none; text-align:center;">
     <input id="restore_bck_encryption_key" name="restore_bck_encryption_key" type="text" value="" />
     <br>
-    <div class=ui-state-error ui-corner-all" style="display:none;padding:5px;display:none;margin:2px;" id="restore_bck_encryption_key_dialog_error"></div>
+    <div class="ui-state-error ui-corner-all" style="display:none;padding:5px;display:none;margin:2px;" id="restore_bck_encryption_key_dialog_error"></div>
 </div>';
 include "admin.settings.load.php";
diff --git a/api/functions.php b/api/functions.php
index 0da1ffc76..ee5f4df55 100644
--- a/api/functions.php
+++ b/api/functions.php
@@ -186,20 +186,20 @@ function rest_delete()
 
                 if (count($array_category) > 1 && count($array_category) < 5) {
                     for ($i = count($array_category); $i > 0; $i--) {
                         $slot = $i - 1;
                         if (!$slot) {
-                            $category_query .= "select id from ".prefix_table("nested_tree")." where title LIKE '".$array_category[$slot]."' AND parent_id = 0";
+                            $category_query .= "select id from ".prefix_table("nested_tree")." where title LIKE '".filter_var($array_category[$slot], FILTER_SANITIZE_STRING)."' AND parent_id = 0";
                         } else {
-                            $category_query .= "select id from ".prefix_table("nested_tree")." where title LIKE '".$array_category[$slot]."' AND parent_id = (";
+                            $category_query .= "select id from ".prefix_table("nested_tree")." where title LIKE '".filter_var($array_category[$slot], FILTER_SANITIZE_STRING)."' AND parent_id = (";
                         }
                     }
                     for ($i = 1; $i < count($array_category); $i++) {
                         $category_query .= ")";
                     }
                 } elseif (count($array_category) == 1) {
-                    $category_query = "select id from ".prefix_table("nested_tree")." where title LIKE '".$array_category[0]."' AND parent_id = 0";
+                    $category_query = "select id from ".prefix_table("nested_tree")." where title LIKE '".filter_var($array_category[0], FILTER_SANITIZE_STRING)."' AND parent_id = 0";
                 } else {
                     rest_error('NO_CATEGORY');
                 }
 
                 // Delete items which in category
@@ -234,26 +234,26 @@ function rest_delete()
 
                 if (count($array_category) > 1 && count($array_category) < 5) {
                     for ($i = count($array_category); $i > 0; $i--) {
                         $slot = $i - 1;
                         if (!$slot) {
-                            $category_query .= "select id from ".prefix_table("nested_tree")." where title LIKE '".$array_category[$slot]."' AND parent_id = 0";
+                            $category_query .= "select id from ".prefix_table("nested_tree")." where title LIKE '".filter_var($array_category[$slot], FILTER_SANITIZE_STRING)."' AND parent_id = 0";
                         } else {
-                            $category_query .= "select id from ".prefix_table("nested_tree")." where title LIKE '".$array_category[$slot]."' AND parent_id = (";
+                            $category_query .= "select id from ".prefix_table("nested_tree")." where title LIKE '".filter_var($array_category[$slot], FILTER_SANITIZE_STRING)."' AND parent_id = (";
                         }
                     }
                     for ($i = 1; $i < count($array_category); $i++) {
                         $category_query .= ")";
                     }
                 } elseif (count($array_category) == 1) {
-                    $category_query = "select id from ".prefix_table("nested_tree")." where title LIKE '".$array_category[0]."' AND parent_id = 0";
+                    $category_query = "select id from ".prefix_table("nested_tree")." where title LIKE '".filter_var($array_category[0], FILTER_SANITIZE_STRING)."' AND parent_id = 0";
                 } else {
                     rest_error('NO_CATEGORY');
                 }
 
                 // Delete item
-                $response = DB::delete(prefix_table("items"), "id_tree = (".$category_query.") and label LIKE '".$item."'");
+                $response = DB::delete(prefix_table("items"), "id_tree = (".$category_query.") and label LIKE '".filter_var($item, FILTER_SANITIZE_STRING)."'");
                 $json['type'] = 'item';
                 $json['item'] = $item;
                 $json['category'] = $GLOBALS['request'][2];
                 if ($response) {
                     $json['status'] = 'OK';
@@ -380,21 +380,31 @@ function rest_get()
                 // about the user
                 $username = $GLOBALS['request'][2];
                 if (strcmp($username, "admin") == 0) {
                     // forbid admin access
                 }
-                $response = DB::query("SELECT fonction_id FROM ".prefix_table("users")." WHERE login='".$username."'");
+                $response = DB::query(
+                    "SELECT fonction_id
+                    FROM ".prefix_table("users")."
+                    WHERE login = %s'",
+                    $username
+                );
                 if (count($response) === 0) {
                     rest_error('USER_NOT_EXISTS');
                 }
                 foreach ($response as $data) {
                     $role_str = $data['fonction_id'];
                 }
                 $folder_arr = array();
                 $roles = explode(";", $role_str);
                 foreach ($roles as $role) {
-                    $response = DB::query("SELECT folder_id FROM ".prefix_table("roles_values")." WHERE role_id='".$role."'");
+                    $response = DB::query(
+                        "SELECT folder_id
+                        FROM ".prefix_table("roles_values")."
+                        WHERE role_id = %i",
+                        $role
+                    );
                     foreach ($response as $data) {
                         $folder_id = $data['folder_id'];
                         if (!array_key_exists($folder_id, $folder_arr)) {
                             array_push($folder_arr, $folder_id);
                         }
@@ -454,11 +464,16 @@ function rest_get()
                 $json = "";
                 $username = $GLOBALS['request'][2];
                 if (strcmp($username, "admin") == 0) {
                     // forbid admin access
                 }
-                $response = DB::query("SELECT fonction_id FROM ".prefix_table("users")." WHERE login='".$username."'");
+                $response = DB::query(
+                    "SELECT fonction_id
+                    FROM ".prefix_table("users")."
+                    WHERE login = %s",
+                    $username
+                );
                 if (count($response) === 0) {
                     rest_error('USER_NOT_EXISTS');
                 }
                 foreach ($response as $data) {
                     $role_str = $data['fonction_id'];
@@ -466,17 +481,27 @@ function rest_get()
 
                 $folder_arr = array();
                 $roles = explode(";", $role_str);
                 $inc = 0;
                 foreach ($roles as $role) {
-                    $response = DB::query("SELECT folder_id, type FROM ".prefix_table("roles_values")." WHERE role_id='".$role."'");
+                    $response = DB::query(
+                        "SELECT folder_id, type
+                        FROM ".prefix_table("roles_values")."
+                        WHERE role_id = %i",
+                        $role
+                    );
                     foreach ($response as $data) {
                         $folder_id = $data['folder_id'];
                         if (!array_key_exists($folder_id, $folder_arr)) {
                             array_push($folder_arr, $folder_id);
 
-                            $response2 = DB::queryFirstRow("SELECT title, nlevel FROM ".prefix_table("nested_tree")." WHERE id='".$folder_id."'");
+                            $response2 = DB::queryFirstRow(
+                                "SELECT title, nlevel
+                                FROM ".prefix_table("nested_tree")."
+                                WHERE id = %i",
+                                $folder_id
+                            );
 
                             if (!empty($response2['title'])) {
                                 $json[$folder_id]['id'] = $folder_id;
                                 $json[$folder_id]['title'] = $response2['title'];
                                 $json[$folder_id]['level'] = $response2['nlevel'];
@@ -665,11 +690,17 @@ function rest_get()
                     }
 
                     // check if element doesn't already exist
                     $item_duplicate_allowed = getSettingValue("duplicate_item");
                     if ($item_duplicate_allowed !== "1") {
-                        DB::query("SELECT * FROM ".prefix_table("items")." WHERE label = %s AND inactif = %i", addslashes($item_label), "0");
+                        DB::query(
+                            "SELECT *
+                            FROM ".prefix_table("items")."
+                            WHERE label = %s AND inactif = %i",
+                            addslashes($item_label),
+                            "0"
+                        );
                         $counter = DB::count();
                         if ($counter != 0) {
                             $itemExists = 1;
                             // prevent the error if the label already exists
                             // so lets just add the time() as a random factor
@@ -802,12 +833,13 @@ function rest_get()
                 if (mysqli_escape_string($link, htmlspecialchars_decode($login)) == "") {
                     rest_error('USERLOGINEMPTY');
                 }
                 // Check if user already exists
                 $data = DB::query(
-                    "SELECT id, fonction_id, groupes_interdits, groupes_visibles FROM ".prefix_table("users")."
-            WHERE login LIKE %ss",
+                    "SELECT id, fonction_id, groupes_interdits, groupes_visibles
+                    FROM ".prefix_table("users")."
+                    WHERE login LIKE %ss",
                     mysqli_escape_string($link, stripslashes($login))
                 );
 
                 if (DB::count() == 0) {
                     try {
@@ -819,20 +851,24 @@ function rest_get()
                             mysqli_escape_string($link, stripslashes($adminby))
                         );
 
                         // get default language
                         $lang = DB::queryFirstRow(
-                            "SELECT `valeur` FROM ".prefix_table("misc")." WHERE type = %s AND intitule = %s",
+                            "SELECT `valeur`
+                            FROM ".prefix_table("misc")."
+                            WHERE type = %s AND intitule = %s",
                             "admin",
                             "default_language"
                         );
 
                         // prepare roles list
                         $rolesList = "";
                         foreach (explode(',', $roles) as $role) {//echo $role."-";
                             $tmp = DB::queryFirstRow(
-                                "SELECT `id` FROM ".prefix_table("roles_title")." WHERE title = %s",
+                                "SELECT `id`
+                                FROM ".prefix_table("roles_title")."
+                                WHERE title = %s",
                                 $role
                             );
                             if (empty($rolesList)) {
                                 $rolesList = $tmp['id'];
                             } else {
@@ -942,11 +978,16 @@ function rest_get()
                             "admin",
                             "duplicate_folder"
                         );
                         // if valeur = 0 then duplicate folders not allowed
                         if ($data === 0) {
-                            DB::query("SELECT * FROM ".prefix_table("nested_tree")." WHERE title = %s", $params[0]);
+                            DB::query(
+                                "SELECT *
+                                FROM ".prefix_table("nested_tree")."
+                                WHERE title = %s",
+                                $params[0]
+                            );
                             $counter = DB::count();
                             if ($counter != 0) {
                                 rest_error('ALREADY_EXISTS');
                             }
                         }
@@ -1033,19 +1074,26 @@ function rest_get()
                         if (strlen($params[1]) > 50) {
                             rest_error('PASSWORDTOOLONG');
                         }
 
                         // Check Folder ID
-                        DB::query("SELECT * FROM ".prefix_table("nested_tree")." WHERE id = %i", $params[3]);
+                        DB::query(
+                            "SELECT *
+                            FROM ".prefix_table("nested_tree")."
+                            WHERE id = %i",
+                            $params[3]
+                        );
                         $counter = DB::count();
                         if ($counter == 0) {
                             rest_error('NOSUCHFOLDER');
                         }
 
                         // check if item exists
                         DB::query(
-                            "SELECT * FROM ".prefix_table("items")." WHERE id = %i",
+                            "SELECT *
+                            FROM ".prefix_table("items")."
+                            WHERE id = %i",
                             $GLOBALS['request'][2]
                         );
                         $counter = DB::count();
                         if ($counter > 0) {
                             // encrypt pwd
@@ -1092,11 +1140,13 @@ function rest_get()
                                 $tags = explode(' ', $params[7]);
                                 foreach ((array) $tags as $tag) {
                                     if (!empty($tag)) {
                                         // check if already exists
                                         DB::query(
-                                            "SELECT * FROM ".prefix_table("tags")." WHERE tag = %s AND item_id = %i",
+                                            "SELECT *
+                                            FROM ".prefix_table("tags")."
+                                            WHERE tag = %s AND item_id = %i",
                                             strtolower($tag),
                                             $GLOBALS['request'][2]
                                         );
                                         $counter = DB::count();
                                         if ($counter === 0) {
@@ -1161,11 +1211,16 @@ function rest_get()
                         if (empty($params[2])) {
                             $params[2] = 0;
                         }
 
                         // check if folder exists and get folder data
-                        $data_folder = DB::queryfirstrow("SELECT * FROM ".prefix_table("nested_tree")." WHERE id = %s", $GLOBALS['request'][2]);
+                        $data_folder = DB::queryfirstrow(
+                            "SELECT *
+                            FROM ".prefix_table("nested_tree")."
+                            WHERE id = %s",
+                            $GLOBALS['request'][2]
+                        );
                         $counter = DB::count();
                         if ($counter === 0) {
                             rest_error('NO_DATA_EXIST');
                         }
 
@@ -1250,11 +1305,13 @@ function rest_get()
             if (isset($GLOBALS['request'][3]) && isset($GLOBALS['request'][4])) {
                 // get url
                 if (isset($GLOBALS['request'][1]) && isset($GLOBALS['request'][2])) {
                     // is user granted?
                     $userData = DB::queryFirstRow(
-                        "SELECT `id`, `pw`, `groupes_interdits`, `groupes_visibles`, `fonction_id` FROM ".$pre."users WHERE login = %s",
+                        "SELECT `id`, `pw`, `groupes_interdits`, `groupes_visibles`, `fonction_id`
+                        FROM ".$pre."users
+                        WHERE login = %s",
                         $GLOBALS['request'][3]
                     );
 
                     // load passwordLib library
                     require_once '../sources/SplClassLoader.php';
@@ -1343,11 +1400,13 @@ function rest_get()
                     $user_saltkey = base64_decode($GLOBALS['request'][4]);
 
                     // is user granted?
                     //db::debugMode(true);
                     $userData = DB::queryFirstRow(
-                        "SELECT `id`, `pw`, `groupes_interdits`, `groupes_visibles`, `fonction_id`, `encrypted_psk` FROM ".$pre."users WHERE login = %s",
+                        "SELECT `id`, `pw`, `groupes_interdits`, `groupes_visibles`, `fonction_id`, `encrypted_psk`
+                        FROM ".$pre."users
+                        WHERE login = %s",
                         $GLOBALS['request'][2]
                     );
 
                     // check if psk is correct.
                     $user_saltkey = defuse_validate_personal_key(
@@ -1461,11 +1520,13 @@ function rest_get()
             if (isset($GLOBALS['request'][4]) && isset($GLOBALS['request'][5])) {
                 // get url
                 if (isset($GLOBALS['request'][1]) && isset($GLOBALS['request'][2]) && isset($GLOBALS['request'][3])) {
                     // is user granted?
                     $userData = DB::queryFirstRow(
-                        "SELECT `id`, `pw`, `groupes_interdits`, `groupes_visibles`, `fonction_id` FROM ".$pre."users WHERE login = %s",
+                        "SELECT `id`, `pw`, `groupes_interdits`, `groupes_visibles`, `fonction_id`
+                        FROM ".$pre."users
+                        WHERE login = %s",
                         $GLOBALS['request'][4]
                     );
                     if (DB::count() == 0) {
                         rest_error('AUTH_NO_IDENTIFIER');
                     }
@@ -1594,11 +1655,13 @@ function rest_get()
             if (isset($GLOBALS['request'][2]) && isset($GLOBALS['request'][3])) {
                 // get url
                 if (isset($GLOBALS['request'][1])) {
                     // is user granted?
                     $userData = DB::queryFirstRow(
-                        "SELECT `id`, `pw`, `groupes_interdits`, `groupes_visibles`, `fonction_id`, `encrypted_psk` FROM ".$pre."users WHERE login = %s",
+                        "SELECT `id`, `pw`, `groupes_interdits`, `groupes_visibles`, `fonction_id`, `encrypted_psk`
+                        FROM ".$pre."users
+                        WHERE login = %s",
                         $GLOBALS['request'][2]
                     );
                     if (DB::count() == 0) {
                         rest_error('AUTH_NO_IDENTIFIER');
                     }
diff --git a/changelog.md b/changelog.md
index 51841e50d..878d2192a 100755
--- a/changelog.md
+++ b/changelog.md
@@ -5,10 +5,12 @@
  	> a manager could potentially act on users not related to him
  Improved security related to Items Management
  	> a user could potentially act on Items he should not have access to
  Securized script.backup.php by adding a security key
  Fixed some other security failures (credit to ​security at Amossys)
+ Improved security regarding uploading files
+ Fixed issue while restoring DB from administration page
  #1945 Cannot delete items
  #1944 File upload results in error
  #1941 Visualisation problems
 
  8/
diff --git a/items.import.php b/items.import.php
index 7b9bf3ff1..2e6cb791e 100644
--- a/items.import.php
+++ b/items.import.php
@@ -221,14 +221,12 @@ foreach ($folders as $t) {
                         "type_upload":"import_items_from_csv",
                         "user_token": $("#import_user_token").val()
                     };
                 },
                 UploadComplete: function(up, files) {
-                    $.each(files, function(i, file) {
-                        ImportCSV(csv_filename);
-                        up.splice();    // clear the file queue
-                    });
+                    ImportCSV(csv_filename);
+                    up.splice();    // clear the file queue
                 }
             }
         });
 
         // Uploader options
@@ -246,17 +244,13 @@ foreach ($folders as $t) {
         });
         uploader_csv.bind("+", function(up, file) {
             $("#" + file.id + " b").html("100%");
         });
         uploader_csv.bind('FileUploaded', function(upldr, file, object) {
-            var myData;
-            try {
-                myData = eval(object.response);
-            } catch(err) {
-                myData = eval('(' + object.response + ')');
-            }
-            csv_filename = myData.newfilename;
+            var myData = prepareExchangedData(object.response, "decode", "<?php echo $_SESSION['key']; ?>");
+
+            csv_filename = myData.operation_id;
         });
 
         // Load CSV click
         $("#uploadfiles_csv").click(function(e) {
             uploader_csv.start();
@@ -335,17 +329,13 @@ foreach ($folders as $t) {
         });
         uploader_kp.bind("+", function(up, file) {
             $("#" + file.id + " b").html("100%");
         });
         uploader_kp.bind('FileUploaded', function(upldr, file, object) {
-            var myData;
-            try {
-                myData = eval(object.response);
-            } catch(err) {
-                myData = eval('(' + object.response + ')');
-            }
-            kp_filename = myData.newfilename;
+            var myData = prepareExchangedData(object.response, "decode", "<?php echo $_SESSION['key']; ?>");
+
+            kp_filename = myData.operation_id;
         });
 
         // Load CSV click
         $("#uploadfiles_kp").click(function(e) {
             uploader_kp.start();
@@ -481,15 +471,15 @@ foreach ($folders as $t) {
             },
             function(data) {
                 $("#kp_import_information").html(data[0].message + "<?php echo '<br><br><b>'.$LANG['alert_page_will_reload'].'</b>'; ?>");
                 $("#import_information").show().html("<i class='fa fa-exclamation-circle'></i>&nbsp;<?php echo $LANG['alert_message_done']; ?>").attr("class","ui-state-highlight");
                 // Reload page
-                $(this).delay(2000).queue(function() {
+                /*$(this).delay(2000).queue(function() {
                     $("#import_information").effect( "fade", "slow" );
                     document.location = "index.php?page=items";
                     $(this).dequeue();
-                });
+                });*/
             },
             "json"
         );
     }
 </script>
diff --git a/items.load.php b/items.load.php
index c751ff7ff..630923dcc 100755
--- a/items.load.php
+++ b/items.load.php
@@ -3359,11 +3359,11 @@ if ($SETTINGS['upload_imageresize_options'] == 1) {
 <?php
 }
 ?>
         init: {
             BeforeUpload: function (up, file) {
-                $("#item_upload_wait").show();
+                $("#item_upload_wait").removeClass("hidden");
 
                 if ($("#random_id").val() == "") {
                     var post_id = CreateRandomString(9,"num_no_0");
                     $("#random_id").val(post_id);
                 }
@@ -3468,11 +3468,11 @@ if ($SETTINGS['upload_imageresize_options'] == 1) {
         },<?php
 }
 ?>
         init: {
             BeforeUpload: function (up, file) {
-                $("#item_edit_upload_wait").show();
+                $("#item_edit_upload_wait").removeClass("hidden");
 
                 up.setOption('multipart_params', {
                     PHPSESSID : "<?php echo $_SESSION['user_id']; ?>",
                     itemId : $('#selected_items').val(),
                     type_upload : "item_attachments",
diff --git a/items.php b/items.php
index 57c120a5b..d1480e8a6 100644
--- a/items.php
+++ b/items.php
@@ -547,11 +547,11 @@ echo '
 // Tabs EDIT N?3
 echo '
         <div id="tabs-03">
             <div id="item_upload">
                 <div id="item_upload_list"></div><br />
-                <div id="item_upload_wait" class="ui-state-focus ui-corner-all" style="display:none;padding:2px;margin:5px 0 5px 0;">'.$LANG['please_wait'].'...</div>
+                <div id="item_upload_wait" class="ui-state-focus ui-corner-all hidden" style="padding:2px;margin:5px 0 5px 0;">'.$LANG['please_wait'].'...</div>
                 <a id="item_attach_pickfiles" href="#" class="button">'.$LANG['select'].'</a>
                 <a id="item_attach_uploadfiles" href="#" class="button">'.$LANG['start_upload'].'</a>
                 <input type="hidden" id="files_number" value="0" />
             </div>
         </div>';
@@ -741,11 +741,11 @@ echo '
             <div style="margin-top:10px;font-weight:bold;font-size:12px;">
                 <span class="fa fa-folder-open mi-grey-1">&nbsp;</span>'.$LANG['upload_files'].'
             </div>
             <div id="item_edit_upload">
                 <div id="item_edit_upload_list"></div><br />
-                <div id="item_edit_upload_wait" class="ui-state-focus ui-corner-all" style="display:none;padding:2px;margin:5px 0 5px 0;">'.$LANG['please_wait'].'...</div>
+                <div id="item_edit_upload_wait" class="ui-state-focus ui-corner-all hidden" style="padding:2px;margin:5px 0 5px 0;">'.$LANG['please_wait'].'...</div>
                 <a id="item_edit_attach_pickfiles" href="#" class="button">'.$LANG['select'].'</a>
                 <a id="item_edit_attach_uploadfiles" href="#sd" class="button">'.$LANG['start_upload'].'</a>
                 <input type="hidden" id="edit_files_number" value="0" />
             </div>
         </div>';
diff --git a/profile.php b/profile.php
index ba3ecdf81..4f872eb48 100644
--- a/profile.php
+++ b/profile.php
@@ -258,10 +258,11 @@ if (isset($_SESSION['user_language']) && $_SESSION['user_language'] !== "0") {
         80=>array(80, $LANG['complex_level5']),
         90=>array(90, $LANG['complex_level6'])
     );
 }
 ?>
+<script type="text/javascript" src="includes/js/functions.js"></script>
 <script type="text/javascript">
 $(function() {
     $(".tip").tooltipster({multiple: true});
     // password
     $("#but_change_password").click(function() {
@@ -422,11 +423,10 @@ $(function() {
             BeforeUpload: function (up, file) {
                 var tmp = Math.random().toString(36).substring(7);
 
                 up.settings.multipart_params = {
                     "PHPSESSID":"<?php echo $_SESSION['user_id']; ?>",
-                    "newFileName":"user<?php echo $_SESSION['user_id']; ?>"+tmp,
                     "type_upload":"upload_profile_photo",
                     "user_token": $("#profile_user_token").val()
                 };
             }
         }
@@ -448,16 +448,14 @@ $(function() {
         up.refresh(); // Reposition Flash/Silverlight
     });
 
      // get response
     uploader_photo.bind("FileUploaded", function(up, file, object) {
-        var myData;
-        try {
-            myData = eval(object.response);
-        } catch(err) {
-            myData = eval('(' + object.response + ')');
-        }
+        // Decode returned data
+        var myData = prepareExchangedData(object.response, "decode", "<?php echo $_SESSION['key']; ?>");
+
+        // update form
         $("#profile_photo").html('<img src="includes/avatars/'+myData.filename+'" />');
         $("#user_avatar_thumb").attr('src', 'includes/avatars/'+myData.filename_thumb);
         $("#filelist_photo").html('').hide();
     });
 
@@ -716,9 +714,7 @@ function changePersonalSaltKey(credentials, ids, nb_total)
                     "json"
                 );
             }
         }
     );
-
-
 }
- </script>
\ No newline at end of file
+</script>
diff --git a/sources/admin.queries.php b/sources/admin.queries.php
index 4bbf91358..1a2ac2a31 100644
--- a/sources/admin.queries.php
+++ b/sources/admin.queries.php
@@ -390,10 +390,27 @@ switch ($post_type) {
 
         $dataPost = explode('&', $post_option);
         $file = htmlspecialchars($dataPost[0]);
         $key = htmlspecialchars($dataPost[1]);
 
+        // Get filename from database
+        $data = DB::queryFirstRow(
+            "SELECT valeur
+            FROM ".$pre."misc
+            WHERE increment_id = %i",
+            $file
+        );
+
+        $file = $data['valeur'];
+
+        // Delete operation id
+        DB::delete(
+            prefix_table('misc'),
+            "increment_id = %i",
+            $file
+        );
+
         // Undecrypt the file
         if (empty($key) === false) {
             // Decrypt the file
             $ret = prepareFileWithDefuse(
                 'decrypt',
@@ -430,11 +447,11 @@ switch ($post_type) {
 
         //delete file
         fileDelete($file);
 
         //Show done
-        echo '[{"result":"db_restore"}]';
+        echo '[{"result":"db_restore" , "message":""}]';
         break;
 
     ###########################################################
     #CASE for optimizing the DB
     case "admin_action_db_optimize":
@@ -481,11 +498,11 @@ switch ($post_type) {
                 );
             }
         }
 
         //Show done
-        echo '[{"result":"db_optimize"}]';
+        echo '[{"result":"db_optimize" , "message":""}]';
         break;
 
     ###########################################################
     #CASE for deleted old files in folder "files"
     case "admin_action_purge_old_files":
diff --git a/sources/import.queries.php b/sources/import.queries.php
index 936b04e0e..843aa14c1 100644
--- a/sources/import.queries.php
+++ b/sources/import.queries.php
@@ -103,13 +103,30 @@ switch (filter_input(INPUT_POST, 'type', FILTER_SANITIZE_STRING)) {
     //Check if import CSV file format is what expected
     case "import_file_format_csv":
         //load full tree
         $tree->rebuild();
         $tree = $tree->getDescendants();
+       // Init post variable
+        $post_operation_id = filter_input(INPUT_POST, 'file', FILTER_SANITIZE_NUMBER_INT);
+
+        // Get filename from database
+        $data = DB::queryFirstRow(
+            "SELECT valeur
+            FROM ".$pre."misc
+            WHERE increment_id = %i",
+            $post_operation_id
+        );
+
+        // Delete operation id
+        DB::delete(
+            prefix_table('misc'),
+            "increment_id = %i",
+            $post_operation_id
+        );
 
         // do some initializations
-        $file = $SETTINGS['path_to_files_folder']."/".filter_input(INPUT_POST, 'file', FILTER_SANITIZE_STRING);
+        $file = $SETTINGS['path_to_files_folder']."/".$data['valeur'];
         $size = 4096;
         $separator = ",";
         $enclosure = '"';
         $fields_expected = array("Label", "Login", "Password", "URL", "Comments"); //requiered fields from CSV
         $importation_possible = true;
@@ -235,10 +252,11 @@ switch (filter_input(INPUT_POST, 'type', FILTER_SANITIZE_STRING)) {
             $display .= '</select></div>';
 
             // Show results to user.
             echo '[{"error":"no" , "output" : "'.$display.'"}]';
         }
+
         break;
 
     //Insert into DB the items the user has selected
     case "import_items":
         //decrypt and retreive data in JSON format
@@ -374,14 +392,35 @@ switch (filter_input(INPUT_POST, 'type', FILTER_SANITIZE_STRING)) {
         $cacheFile = fopen($cacheFileName, "w");
         $cacheFileF = fopen($cacheFileNameFolder, "w");
         $logFileName = "/keepassImport_".date('YmdHis').".log";
         $cacheLogFile = fopen($SETTINGS['path_to_files_folder'].$logFileName, 'w');
 
+        // Init post variable
+        $post_operation_id = filter_input(INPUT_POST, 'file', FILTER_SANITIZE_STRING);
+
+        // Get filename from database
+        $data = DB::queryFirstRow(
+            "SELECT valeur
+            FROM ".$pre."misc
+            WHERE increment_id = %i",
+            $post_operation_id
+        );
+
+        // Delete operation id
+        DB::delete(
+            prefix_table('misc'),
+            "increment_id = %i",
+            $post_operation_id
+        );
+
+        // do some initializations
+        $file = $data['valeur'];
+
         //read xml file
-        if (file_exists("'".$SETTINGS['path_to_files_folder']."/".filter_input(INPUT_POST, 'file', FILTER_SANITIZE_STRING))."'") {
+        if (file_exists($SETTINGS['path_to_files_folder']."/".$file)) {
             $xml = simplexml_load_file(
-                $SETTINGS['path_to_files_folder']."/".filter_input(INPUT_POST, 'file', FILTER_SANITIZE_STRING)
+                $SETTINGS['path_to_files_folder']."/".$file
             );
         }
 
         /**
         Recursive function that will permit to read each level of XML nodes
diff --git a/sources/items.queries.php b/sources/items.queries.php
index ba81c02b9..85ac3d90e 100644
--- a/sources/items.queries.php
+++ b/sources/items.queries.php
@@ -450,12 +450,14 @@ if (null !== $post_type) {
                 // Encrypt data to return
                 echo prepareExchangedData(array("error" => "item_exists"), "encode");
                 break;
             }
 
-            // Update CACHE table
-            updateCacheTable("add_value", $newID);
+            // Add item to CACHE table if new item has been created
+            if (isset($newID) === true) {
+                updateCacheTable("add_value", $newID);
+            }
 
             // Encrypt data to return
             echo prepareExchangedData($returnValues, "encode");
             break;
 
@@ -3385,12 +3387,14 @@ if (null !== $post_type) {
                             'inactif' => '1',
                             ),
                         "id = %i",
                         $item_id
                     );
+
                     // log
                     logItems($item_id, $dataSource['label'], $_SESSION['user_id'], 'at_delete', $_SESSION['login']);
+
                     // Update CACHE table
                     updateCacheTable("delete_value", $item_id);
                 }
             }
 
diff --git a/sources/main.functions.php b/sources/main.functions.php
index 7903e92c3..3b4f05b9d 100644
--- a/sources/main.functions.php
+++ b/sources/main.functions.php
@@ -1284,11 +1284,11 @@ function prepareExchangedData($data, $type)
     global $SETTINGS;
 
     //load ClassLoader
     require_once $SETTINGS['cpassman_dir'].'/sources/SplClassLoader.php';
     //Load AES
-    $aes = new SplClassLoader('Encryption\Crypt', '../includes/libraries');
+    $aes = new SplClassLoader('Encryption\Crypt', $SETTINGS['cpassman_dir'].'/includes/libraries');
     $aes->register();
 
     if ($type == "encode") {
         if (isset($SETTINGS['encryptClientServer'])
             && $SETTINGS['encryptClientServer'] === "0"
@@ -1370,12 +1370,15 @@ function prefix_table($table)
 /*
  * Creates a KEY using PasswordLib
  */
 function GenerateCryptKey($size = "", $secure = false, $numerals = false, $capitalize = false, $ambiguous = false, $symbols = false)
 {
+    global $SETTINGS;
+    require_once $SETTINGS['cpassman_dir'].'/sources/SplClassLoader.php';
+
     // load library
-    $pwgen = new SplClassLoader('Encryption\PwGen', '../includes/libraries');
+    $pwgen = new SplClassLoader('Encryption\PwGen', $SETTINGS['cpassman_dir'].'/includes/libraries');
     $pwgen->register();
     $pwgen = new Encryption\PwGen\pwgen();
 
     // init
     if (!empty($size)) {
diff --git a/sources/upload/upload.files.php b/sources/upload/upload.files.php
index 7b7c25f80..bb188e447 100644
--- a/sources/upload/upload.files.php
+++ b/sources/upload/upload.files.php
@@ -71,11 +71,11 @@ if (null === $post_user_token) {
         // increase end_timestamp for token
         DB::update(
             prefix_table('tokens'),
             array(
                 'end_timestamp' => time() + 10
-                ),
+            ),
             "user_id = %i AND token = %s",
             $_SESSION['user_id'],
             $post_user_token
         );
     } else {
@@ -308,35 +308,85 @@ if (!$chunks || $chunk == $chunks - 1) {
 } else {
     // continue uploading other chunks
     die();
 }
 
+// generate file name
+$newFileName = GenerateCryptKey(40, false, true, true, false, false);
+
+//Connect to mysql server
+require_once '../../includes/config/settings.php';
+require_once $SETTINGS['cpassman_dir'].'/includes/libraries/Database/Meekrodb/db.class.php';
+$pass = defuse_return_decrypted($pass);
+DB::$host = $server;
+DB::$user = $user;
+DB::$password = $pass;
+DB::$dbName = $database;
+DB::$port = $port;
+DB::$encoding = $encoding;
+DB::$error_handler = true;
+$link = mysqli_connect($server, $user, $pass, $database, $port);
+$link->set_charset($encoding);
 
 if (null !== ($post_type_upload)
     && empty($post_type_upload) === false
     && $post_type_upload === "import_items_from_csv"
 ) {
-    $newFileName = time()."_".$_SESSION['user_id'];
     rename(
         $filePath,
-        $targetDir.DIRECTORY_SEPARATOR.$newFileName
+        $targetDir.DIRECTORY_SEPARATOR.$newFileName.".".$ext
+    );
+
+    // Add in DB
+    DB::insert(
+        prefix_table("misc"),
+        array(
+            'type' => "temp_file",
+            'intitule' => "filename",
+            'valeur' => $newFileName.".".$ext
+        )
     );
+
+    // return info
+    echo prepareExchangedData(
+        array(
+            "operation_id" => DB::insertId()
+        ),
+        "encode"
+    );
+
+    exit();
 } elseif (null !== ($post_type_upload)
     && $post_type_upload === "import_items_from_keypass"
 ) {
-    $newFileName = time()."_".$_SESSION['user_id'];
     rename(
         $filePath,
-        $targetDir.DIRECTORY_SEPARATOR.$newFileName
+        $targetDir.DIRECTORY_SEPARATOR.$newFileName.".".$ext
+    );
+
+    // Add in DB
+    DB::insert(
+        prefix_table("misc"),
+        array(
+            'type' => "temp_file",
+            'intitule' => "filename",
+            'valeur' => $newFileName.".".$ext
+        )
     );
+
+    // return info
+    echo prepareExchangedData(
+        array(
+            "operation_id" => DB::insertId()
+        ),
+        "encode"
+    );
+
+    exit();
 } elseif (null !== ($post_type_upload)
     && $post_type_upload === "upload_profile_photo"
 ) {
-    // sanitize the new file name
-    $newFileName = preg_replace('/[^\w\._]+/', '_', htmlentities($post_newFileName, ENT_QUOTES));
-    $newFileName = preg_replace('/[^'.$valid_chars_regex.'\.]/', '', strtolower(basename($newFileName)));
-
     // get file extension
     $ext = pathinfo($filePath, PATHINFO_EXTENSION);
 
     // rename the file
     rename(
@@ -349,24 +399,10 @@ if (null !== ($post_type_upload)
         $targetDir.DIRECTORY_SEPARATOR.$newFileName.'.'.$ext,
         $targetDir.DIRECTORY_SEPARATOR.$newFileName."_thumb".'.'.$ext,
         40
     );
 
-    //Connect to mysql server
-    require_once '../../includes/config/settings.php';
-    require_once $SETTINGS['cpassman_dir'].'/includes/libraries/Database/Meekrodb/db.class.php';
-    $pass = defuse_return_decrypted($pass);
-DB::$host = $server;
-    DB::$user = $user;
-    DB::$password = $pass;
-    DB::$dbName = $database;
-    DB::$port = $port;
-    DB::$encoding = $encoding;
-    DB::$error_handler = true;
-    $link = mysqli_connect($server, $user, $pass, $database, $port);
-    $link->set_charset($encoding);
-
     // get current avatar and delete it
     $data = DB::queryFirstRow("SELECT avatar, avatar_thumb FROM ".$pre."users WHERE id=%i", $_SESSION['user_id']);
     fileDelete($targetDir.DIRECTORY_SEPARATOR.$data['avatar']);
     fileDelete($targetDir.DIRECTORY_SEPARATOR.$data['avatar_thumb']);
 
@@ -380,22 +416,49 @@ DB::$host = $server;
 
     // store in session
     $_SESSION['user_avatar'] = $newFileName.'.'.$ext;
     $_SESSION['user_avatar_thumb'] = $newFileName."_thumb".'.'.$ext;
 
-    echo '{"filename" : "'.htmlentities($_SESSION['user_avatar'], ENT_QUOTES).'" , "filename_thumb" : "'.htmlentities($_SESSION['user_avatar_thumb'], ENT_QUOTES).'"}';
+    // return info
+    echo prepareExchangedData(
+        array(
+            "filename" => htmlentities($_SESSION['user_avatar'], ENT_QUOTES),
+            "filename_thumb" => htmlentities($_SESSION['user_avatar_thumb'], ENT_QUOTES)
+        ),
+        "encode"
+    );
+
     exit();
-} else {
-    $newFileName = time()."_".$_SESSION['user_id'];
+} elseif (null !== ($post_type_upload)
+    && $post_type_upload === "restore_db"
+) {
     rename(
         $filePath,
-        $targetDir.DIRECTORY_SEPARATOR.$newFileName
+        $targetDir.DIRECTORY_SEPARATOR.$newFileName.".".$ext
+    );
+
+    // Add in DB
+    DB::insert(
+        prefix_table("misc"),
+        array(
+            'type' => "temp_file",
+            'intitule' => "filename",
+            'valeur' => $newFileName.".".$ext
+        )
     );
+
+    // return info
+    echo prepareExchangedData(
+        array(
+            "operation_id" => DB::insertId()
+        ),
+        "encode"
+    );
+
+    exit();
 }
 
-// Return JSON-RPC response
-die('{"jsonrpc" : "2.0", "result" : null, "id" : "id" , "newfilename" : "'.$newFileName.'"}');
 
 
 /* Handles the error output. */
 function handleUploadError($message)
 {

Vulnerable code:         $("#restore_bck_encryption_key_dialog_error").html("").hide();
                        $("#restore_bck_encryption_key_dialog_error").html(data[0].message).show();
                    "PHPSESSID":"'.$_SESSION['user_id'].'",
                $.each(files, function(i, file) {
                    $("#restore_bck_fileObj").val(file.name);
                    $("#restore_bck_encryption_key_dialog").dialog("open");
                });
    <div class=ui-state-error ui-corner-all" style="display:none;padding:5px;display:none;margin:2px;" id="restore_bck_encryption_key_dialog_error"></div>
                            $category_query .= "select id from ".prefix_table("nested_tree")." where title LIKE '".$array_category[$slot]."' AND parent_id = 0";
                            $category_query .= "select id from ".prefix_table("nested_tree")." where title LIKE '".$array_category[$slot]."' AND parent_id = (";
                    $category_query = "select id from ".prefix_table("nested_tree")." where title LIKE '".$array_category[0]."' AND parent_id = 0";
                            $category_query .= "select id from ".prefix_table("nested_tree")." where title LIKE '".$array_category[$slot]."' AND parent_id = 0";
                            $category_query .= "select id from ".prefix_table("nested_tree")." where title LIKE '".$array_category[$slot]."' AND parent_id = (";
                    $category_query = "select id from ".prefix_table("nested_tree")." where title LIKE '".$array_category[0]."' AND parent_id = 0";
                $response = DB::delete(prefix_table("items"), "id_tree = (".$category_query.") and label LIKE '".$item."'");
                $response = DB::query("SELECT fonction_id FROM ".prefix_table("users")." WHERE login='".$username."'");
                    $response = DB::query("SELECT folder_id FROM ".prefix_table("roles_values")." WHERE role_id='".$role."'");
                $response = DB::query("SELECT fonction_id FROM ".prefix_table("users")." WHERE login='".$username."'");
                    $response = DB::query("SELECT folder_id, type FROM ".prefix_table("roles_values")." WHERE role_id='".$role."'");
                            $response2 = DB::queryFirstRow("SELECT title, nlevel FROM ".prefix_table("nested_tree")." WHERE id='".$folder_id."'");
                        DB::query("SELECT * FROM ".prefix_table("items")." WHERE label = %s AND inactif = %i", addslashes($item_label), "0");
                    "SELECT id, fonction_id, groupes_interdits, groupes_visibles FROM ".prefix_table("users")."
            WHERE login LIKE %ss",
                            "SELECT `valeur` FROM ".prefix_table("misc")." WHERE type = %s AND intitule = %s",
                                "SELECT `id` FROM ".prefix_table("roles_title")." WHERE title = %s",
                            DB::query("SELECT * FROM ".prefix_table("nested_tree")." WHERE title = %s", $params[0]);
                        DB::query("SELECT * FROM ".prefix_table("nested_tree")." WHERE id = %i", $params[3]);
                            "SELECT * FROM ".prefix_table("items")." WHERE id = %i",
                                            "SELECT * FROM ".prefix_table("tags")." WHERE tag = %s AND item_id = %i",
                        $data_folder = DB::queryfirstrow("SELECT * FROM ".prefix_table("nested_tree")." WHERE id = %s", $GLOBALS['request'][2]);
                        "SELECT `id`, `pw`, `groupes_interdits`, `groupes_visibles`, `fonction_id` FROM ".$pre."users WHERE login = %s",
                        "SELECT `id`, `pw`, `groupes_interdits`, `groupes_visibles`, `fonction_id`, `encrypted_psk` FROM ".$pre."users WHERE login = %s",
                        "SELECT `id`, `pw`, `groupes_interdits`, `groupes_visibles`, `fonction_id` FROM ".$pre."users WHERE login = %s",
                        "SELECT `id`, `pw`, `groupes_interdits`, `groupes_visibles`, `fonction_id`, `encrypted_psk` FROM ".$pre."users WHERE login = %s",
                    $.each(files, function(i, file) {
                        ImportCSV(csv_filename);
                        up.splice();    // clear the file queue
                    });
            var myData;
            try {
                myData = eval(object.response);
            } catch(err) {
                myData = eval('(' + object.response + ')');
            }
            csv_filename = myData.newfilename;
            var myData;
            try {
                myData = eval(object.response);
            } catch(err) {
                myData = eval('(' + object.response + ')');
            }
            kp_filename = myData.newfilename;
                $(this).delay(2000).queue(function() {
                });
                $("#item_upload_wait").show();
                $("#item_edit_upload_wait").show();
                <div id="item_upload_wait" class="ui-state-focus ui-corner-all" style="display:none;padding:2px;margin:5px 0 5px 0;">'.$LANG['please_wait'].'...</div>
                <div id="item_edit_upload_wait" class="ui-state-focus ui-corner-all" style="display:none;padding:2px;margin:5px 0 5px 0;">'.$LANG['please_wait'].'...</div>
                    "newFileName":"user<?php echo $_SESSION['user_id']; ?>"+tmp,
        var myData;
        try {
            myData = eval(object.response);
        } catch(err) {
            myData = eval('(' + object.response + ')');
        }


 </script>
        echo '[{"result":"db_restore"}]';
        echo '[{"result":"db_optimize"}]';
        $file = $SETTINGS['path_to_files_folder']."/".filter_input(INPUT_POST, 'file', FILTER_SANITIZE_STRING);
        if (file_exists("'".$SETTINGS['path_to_files_folder']."/".filter_input(INPUT_POST, 'file', FILTER_SANITIZE_STRING))."'") {
                $SETTINGS['path_to_files_folder']."/".filter_input(INPUT_POST, 'file', FILTER_SANITIZE_STRING)
            // Update CACHE table
            updateCacheTable("add_value", $newID);
    $aes = new SplClassLoader('Encryption\Crypt', '../includes/libraries');
    $pwgen = new SplClassLoader('Encryption\PwGen', '../includes/libraries');
                ),
    $newFileName = time()."_".$_SESSION['user_id'];
        $targetDir.DIRECTORY_SEPARATOR.$newFileName
    $newFileName = time()."_".$_SESSION['user_id'];
        $targetDir.DIRECTORY_SEPARATOR.$newFileName
    // sanitize the new file name
    $newFileName = preg_replace('/[^\w\._]+/', '_', htmlentities($post_newFileName, ENT_QUOTES));
    $newFileName = preg_replace('/[^'.$valid_chars_regex.'\.]/', '', strtolower(basename($newFileName)));

    //Connect to mysql server
    require_once '../../includes/config/settings.php';
    require_once $SETTINGS['cpassman_dir'].'/includes/libraries/Database/Meekrodb/db.class.php';
    $pass = defuse_return_decrypted($pass);
DB::$host = $server;
    DB::$user = $user;
    DB::$password = $pass;
    DB::$dbName = $database;
    DB::$port = $port;
    DB::$encoding = $encoding;
    DB::$error_handler = true;
    $link = mysqli_connect($server, $user, $pass, $database, $port);
    $link->set_charset($encoding);

    echo '{"filename" : "'.htmlentities($_SESSION['user_avatar'], ENT_QUOTES).'" , "filename_thumb" : "'.htmlentities($_SESSION['user_avatar_thumb'], ENT_QUOTES).'"}';
} else {
    $newFileName = time()."_".$_SESSION['user_id'];
        $targetDir.DIRECTORY_SEPARATOR.$newFileName
// Return JSON-RPC response
die('{"jsonrpc" : "2.0", "result" : null, "id" : "id" , "newfilename" : "'.$newFileName.'"}');
Fixed code:         $("#restore_bck_encryption_key_dialog_error")
            .html("<span class='fa fa-cog fa-spin fa'>&nbsp;</span><?php echo addslashes($LANG['please_wait']); ?>")
            .attr("class","ui-corner-all ui-state-focus")
            .show();

                        $("#restore_bck_encryption_key_dialog_error")
                            .html(data[0].message)
                            .attr("class","ui-corner-all ui-state-error")
                            .show();
    var restore_operation_id = '';
                    "PHPSESSID":"<?php echo $_SESSION['user_id']; ?>",
                $("#restore_bck_fileObj").val(restore_operation_id);
                $("#restore_bck_encryption_key_dialog").dialog("open");
    uploader_restoreDB.bind('FileUploaded', function(upldr, file, object) {
        var myData = prepareExchangedData(object.response, "decode", "<?php echo $_SESSION['key']; ?>");

        restore_operation_id = myData.operation_id;
    });
    <div class="ui-state-error ui-corner-all" style="display:none;padding:5px;display:none;margin:2px;" id="restore_bck_encryption_key_dialog_error"></div>
                            $category_query .= "select id from ".prefix_table("nested_tree")." where title LIKE '".filter_var($array_category[$slot], FILTER_SANITIZE_STRING)."' AND parent_id = 0";
                            $category_query .= "select id from ".prefix_table("nested_tree")." where title LIKE '".filter_var($array_category[$slot], FILTER_SANITIZE_STRING)."' AND parent_id = (";
                    $category_query = "select id from ".prefix_table("nested_tree")." where title LIKE '".filter_var($array_category[0], FILTER_SANITIZE_STRING)."' AND parent_id = 0";
                            $category_query .= "select id from ".prefix_table("nested_tree")." where title LIKE '".filter_var($array_category[$slot], FILTER_SANITIZE_STRING)."' AND parent_id = 0";
                            $category_query .= "select id from ".prefix_table("nested_tree")." where title LIKE '".filter_var($array_category[$slot], FILTER_SANITIZE_STRING)."' AND parent_id = (";
                    $category_query = "select id from ".prefix_table("nested_tree")." where title LIKE '".filter_var($array_category[0], FILTER_SANITIZE_STRING)."' AND parent_id = 0";
                $response = DB::delete(prefix_table("items"), "id_tree = (".$category_query.") and label LIKE '".filter_var($item, FILTER_SANITIZE_STRING)."'");
                $response = DB::query(
                    "SELECT fonction_id
                    FROM ".prefix_table("users")."
                    WHERE login = %s'",
                    $username
                );
                    $response = DB::query(
                        "SELECT folder_id
                        FROM ".prefix_table("roles_values")."
                        WHERE role_id = %i",
                        $role
                    );
                $response = DB::query(
                    "SELECT fonction_id
                    FROM ".prefix_table("users")."
                    WHERE login = %s",
                    $username
                );
                    $response = DB::query(
                        "SELECT folder_id, type
                        FROM ".prefix_table("roles_values")."
                        WHERE role_id = %i",
                        $role
                    );
                            $response2 = DB::queryFirstRow(
                                "SELECT title, nlevel
                                FROM ".prefix_table("nested_tree")."
                                WHERE id = %i",
                                $folder_id
                            );
                        DB::query(
                            "SELECT *
                            FROM ".prefix_table("items")."
                            WHERE label = %s AND inactif = %i",
                            addslashes($item_label),
                            "0"
                        );
                    "SELECT id, fonction_id, groupes_interdits, groupes_visibles
                    FROM ".prefix_table("users")."
                    WHERE login LIKE %ss",
                            "SELECT `valeur`
                            FROM ".prefix_table("misc")."
                            WHERE type = %s AND intitule = %s",
                                "SELECT `id`
                                FROM ".prefix_table("roles_title")."
                                WHERE title = %s",
                            DB::query(
                                "SELECT *
                                FROM ".prefix_table("nested_tree")."
                                WHERE title = %s",
                                $params[0]
                            );
                        DB::query(
                            "SELECT *
                            FROM ".prefix_table("nested_tree")."
                            WHERE id = %i",
                            $params[3]
                        );
                            "SELECT *
                            FROM ".prefix_table("items")."
                            WHERE id = %i",
                                            "SELECT *
                                            FROM ".prefix_table("tags")."
                                            WHERE tag = %s AND item_id = %i",
                        $data_folder = DB::queryfirstrow(
                            "SELECT *
                            FROM ".prefix_table("nested_tree")."
                            WHERE id = %s",
                            $GLOBALS['request'][2]
                        );
                        "SELECT `id`, `pw`, `groupes_interdits`, `groupes_visibles`, `fonction_id`
                        FROM ".$pre."users
                        WHERE login = %s",
                        "SELECT `id`, `pw`, `groupes_interdits`, `groupes_visibles`, `fonction_id`, `encrypted_psk`
                        FROM ".$pre."users
                        WHERE login = %s",
                        "SELECT `id`, `pw`, `groupes_interdits`, `groupes_visibles`, `fonction_id`
                        FROM ".$pre."users
                        WHERE login = %s",
                        "SELECT `id`, `pw`, `groupes_interdits`, `groupes_visibles`, `fonction_id`, `encrypted_psk`
                        FROM ".$pre."users
                        WHERE login = %s",
 Improved security regarding uploading files
 Fixed issue while restoring DB from administration page
                    ImportCSV(csv_filename);
                    up.splice();    // clear the file queue
            var myData = prepareExchangedData(object.response, "decode", "<?php echo $_SESSION['key']; ?>");

            csv_filename = myData.operation_id;
            var myData = prepareExchangedData(object.response, "decode", "<?php echo $_SESSION['key']; ?>");

            kp_filename = myData.operation_id;
                /*$(this).delay(2000).queue(function() {
                });*/
                $("#item_upload_wait").removeClass("hidden");
                $("#item_edit_upload_wait").removeClass("hidden");
                <div id="item_upload_wait" class="ui-state-focus ui-corner-all hidden" style="padding:2px;margin:5px 0 5px 0;">'.$LANG['please_wait'].'...</div>
                <div id="item_edit_upload_wait" class="ui-state-focus ui-corner-all hidden" style="padding:2px;margin:5px 0 5px 0;">'.$LANG['please_wait'].'...</div>
<script type="text/javascript" src="includes/js/functions.js"></script>
        // Decode returned data
        var myData = prepareExchangedData(object.response, "decode", "<?php echo $_SESSION['key']; ?>");

        // update form
</script>
        // Get filename from database
        $data = DB::queryFirstRow(
            "SELECT valeur
            FROM ".$pre."misc
            WHERE increment_id = %i",
            $file
        );

        $file = $data['valeur'];

        // Delete operation id
        DB::delete(
            prefix_table('misc'),
            "increment_id = %i",
            $file
        );

        echo '[{"result":"db_restore" , "message":""}]';
        echo '[{"result":"db_optimize" , "message":""}]';
       // Init post variable
        $post_operation_id = filter_input(INPUT_POST, 'file', FILTER_SANITIZE_NUMBER_INT);

        // Get filename from database
        $data = DB::queryFirstRow(
            "SELECT valeur
            FROM ".$pre."misc
            WHERE increment_id = %i",
            $post_operation_id
        );

        // Delete operation id
        DB::delete(
            prefix_table('misc'),
            "increment_id = %i",
            $post_operation_id
        );
        $file = $SETTINGS['path_to_files_folder']."/".$data['valeur'];

        // Init post variable
        $post_operation_id = filter_input(INPUT_POST, 'file', FILTER_SANITIZE_STRING);

        // Get filename from database
        $data = DB::queryFirstRow(
            "SELECT valeur
            FROM ".$pre."misc
            WHERE increment_id = %i",
            $post_operation_id
        );

        // Delete operation id
        DB::delete(
            prefix_table('misc'),
            "increment_id = %i",
            $post_operation_id
        );

        // do some initializations
        $file = $data['valeur'];

        if (file_exists($SETTINGS['path_to_files_folder']."/".$file)) {
                $SETTINGS['path_to_files_folder']."/".$file
            // Add item to CACHE table if new item has been created
            if (isset($newID) === true) {
                updateCacheTable("add_value", $newID);
            }


    $aes = new SplClassLoader('Encryption\Crypt', $SETTINGS['cpassman_dir'].'/includes/libraries');
    global $SETTINGS;
    require_once $SETTINGS['cpassman_dir'].'/sources/SplClassLoader.php';

    $pwgen = new SplClassLoader('Encryption\PwGen', $SETTINGS['cpassman_dir'].'/includes/libraries');
            ),
// generate file name
$newFileName = GenerateCryptKey(40, false, true, true, false, false);

//Connect to mysql server
require_once '../../includes/config/settings.php';
require_once $SETTINGS['cpassman_dir'].'/includes/libraries/Database/Meekrodb/db.class.php';
$pass = defuse_return_decrypted($pass);
DB::$host = $server;
DB::$user = $user;
DB::$password = $pass;
DB::$dbName = $database;
DB::$port = $port;
DB::$encoding = $encoding;
DB::$error_handler = true;
$link = mysqli_connect($server, $user, $pass, $database, $port);
$link->set_charset($encoding);
        $targetDir.DIRECTORY_SEPARATOR.$newFileName.".".$ext
    );

    // Add in DB
    DB::insert(
        prefix_table("misc"),
        array(
            'type' => "temp_file",
            'intitule' => "filename",
            'valeur' => $newFileName.".".$ext
        )

    // return info
    echo prepareExchangedData(
        array(
            "operation_id" => DB::insertId()
        ),
        "encode"
    );

    exit();
        $targetDir.DIRECTORY_SEPARATOR.$newFileName.".".$ext
    );

    // Add in DB
    DB::insert(
        prefix_table("misc"),
        array(
            'type' => "temp_file",
            'intitule' => "filename",
            'valeur' => $newFileName.".".$ext
        )

    // return info
    echo prepareExchangedData(
        array(
            "operation_id" => DB::insertId()
        ),
        "encode"
    );

    exit();
    // return info
    echo prepareExchangedData(
        array(
            "filename" => htmlentities($_SESSION['user_avatar'], ENT_QUOTES),
            "filename_thumb" => htmlentities($_SESSION['user_avatar_thumb'], ENT_QUOTES)
        ),
        "encode"
    );

} elseif (null !== ($post_type_upload)
    && $post_type_upload === "restore_db"
) {
        $targetDir.DIRECTORY_SEPARATOR.$newFileName.".".$ext
    );

    // Add in DB
    DB::insert(
        prefix_table("misc"),
        array(
            'type' => "temp_file",
            'intitule' => "filename",
            'valeur' => $newFileName.".".$ext
        )

    // return info
    echo prepareExchangedData(
        array(
            "operation_id" => DB::insertId()
        ),
        "encode"
    );

    exit();