CVE-2014-3773: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') (CWE-89)
value: Multiple SQL injection vulnerabilities in TeamPass before 2.1.20 allow remote attackers to execute arbitrary SQL commands via the login parameter in a (1) send_pw_by_email or (2) generate_new_password action in sources/main.queries.php; iDisplayStart parameter to (3) datatable.logs.php or (4) a file in source/datatable/; or iDisplayLength parameter to (5) datatable.logs.php or (6) a file in source/datatable/; or allow remote authenticated users to execute arbitrary SQL commands via a sSortDir_ parameter to (7) datatable.logs.php or (8) a file in source/datatable/.
CWE description: The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. Without sufficient removal or quoting of SQL syntax in user-controllable inputs, the generated SQL query can cause those inputs to be interpreted as SQL instead of ordinary user data.
Published: 2014-08-07T11:13Z
Repository: https://github.com/nilsteampassnet/TeamPass
Language: PHP
Files changed: admin.php, admin.settings.php, admin.settings_categories.php, changelog.md, datatable.logs.php, error.php, find.php, folders.php, home.php, includes/include.php, includes/language/english.php, includes/libraries/Authentication/GoogleAuthenticator/GoogleAuthenticator.php, includes/libraries/Database/Core/DbCore.php, includes/settings.php, index.php, items.load.php, items.php, kb.php, load.php, roles.php, sources/admin.queries.php, sources/categories.queries.php, sources/checks.php, sources/core.php, sources/datatable/datatable.item_edition.php, sources/datatable/datatable.kb.php, sources/datatable/datatable.logs.php, sources/datatable/datatable.users_logged.php, sources/export.queries.php, sources/favourites.queries.php, sources/find.queries.php, sources/folders.queries.php, sources/import.queries.php, sources/items.queries.php, sources/kb.queries.php, sources/logs.queries.php, sources/main.functions.php, sources/main.queries.php, sources/roles.queries.php, sources/upload/upload.attachments.php, sources/upload/upload.files.php, sources/users.queries.php, sources/views.queries.php, users.load.php, users.php, views.php, views_database.php, views_logs.php
Commit date: 2014-04-18 11:55:28 +0200
Commit message: 2.1.20

Diff: diff --git a/admin.php b/admin.php
index 08ef332c..f35fcea4 100644
--- a/admin.php
+++ b/admin.php
@@ -10,14 +10,26 @@
  * This library is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
 
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
+if (
+    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
+    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
+    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
+{
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "users.php")) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    include 'error.php';
+    exit();
+}
+
 echo '
     <div class="title ui-widget-content ui-corner-all">'.$txt['admin'].'</div>
     <div style="width:900px;margin-left:50px; line-height:25px;height:100%;overflow:auto;">';
 
     // Div for tool info
diff --git a/admin.settings.php b/admin.settings.php
index 1dacde5d..76a14338 100644
--- a/admin.settings.php
+++ b/admin.settings.php
@@ -11,14 +11,26 @@
  * This library is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
 
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
+if (
+    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
+    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
+    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
+{
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], curPage())) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    include 'error.php';
+    exit();
+}
+
 /*
 * FUNCTION permitting to store into DB the settings changes
 */
 function updateSettings ($setting, $val, $type = '')
 {
@@ -35,11 +47,18 @@ function updateSettings ($setting, $val, $type = '')
     $db->register();
     $db = new Database\Core\DbCore($server, $user, $pass, $database, $pre);
     $db->connect();
 
     // Check if setting is already in DB. If NO then insert, if YES then update.
-    $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."misc WHERE type='".$type."' AND intitule = '".$setting."'");
+    //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."misc WHERE type='".$type."' AND intitule = '".$setting."'");
+    $data = $db->queryCount(
+        "misc",
+        array(
+            "type" => $type,
+            "intitule" => $setting
+        )
+    );
     if ($data[0] == 0) {
         $db->queryInsert(
             "misc",
             array(
                 'valeur' => $val,
@@ -67,11 +86,18 @@ function updateSettings ($setting, $val, $type = '')
             "type='".$type."' AND intitule = '".$setting."'"
         );
         // in case of stats enabled, update the actual time
         if ($setting == 'send_stats') {
             // Check if previous time exists, if not them insert this value in DB
-            $data_time = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."misc WHERE type='".$type."' AND intitule = '".$setting."_time'");
+            //$data_time = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."misc WHERE type='".$type."' AND intitule = '".$setting."_time'");
+            $data_time = $db->queryCount(
+                "misc",
+                array(
+                    "type" => $type,
+                    "intitule" => $setting."_time"
+                )
+            );
             if ($data_time[0] == 0) {
                 $db->queryInsert(
                     "misc",
                     array(
                         'valeur' => 0,
@@ -1841,11 +1867,15 @@ echo '
                         <td>
                             <img src="includes/images/asterisk.png" class="tip" alt="" title="'.$txt['admin_action_db_backup_start_tip'].'" onclick="LaunchAdminActions(\'admin_email_test_configuration\')" style="cursor:pointer;" />
                         </td>
                     </tr>';
 // Send emails backlog
-$nb_emails = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."emails WHERE status = 'not_sent' OR status = ''");
+//$nb_emails = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."emails WHERE status = 'not_sent' OR status = ''");
+$nb_emails = $db->queryCount(
+    "emails",
+    "status = 'not_sent' OR status = ''"
+);
 echo '
                     <tr style="margin-bottom:3px">
                         <td>
                         <span class="ui-icon ui-icon-gear" style="float: left; margin-right: .3em;">&nbsp;</span>
                             '.str_replace("#nb_emails#", $nb_emails[0], $txt['admin_email_send_backlog']).'
diff --git a/admin.settings_categories.php b/admin.settings_categories.php
index a857bc3a..125ac7b6 100644
--- a/admin.settings_categories.php
+++ b/admin.settings_categories.php
@@ -187,11 +187,18 @@ echo '
         <br />
         <div style="text-align:center; margin-top:10px;">
         <select id="cat_folders_selection" multiple size="12">';
         $folders = $tree->getDescendants();
         foreach ($folders as $folder) {
-            $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."nested_tree WHERE personal_folder=0 AND id = ".$folder->id);
+            //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."nested_tree WHERE personal_folder=0 AND id = ".$folder->id);
+            $data = $db->queryCount(
+                "nested_tree",
+                array(
+                    "personal_folder" => 0,
+                    "id" => $folder->id
+                )
+            );
             if ($data[0] > 0) {
                 echo '
                 <option value="'.$folder->id.'">'.str_replace("&", "&amp;", $folder->title).'</option>';
             }
         }
diff --git a/changelog.md b/changelog.md
index 4c363a34..fa99fa65 100644
--- a/changelog.md
+++ b/changelog.md
@@ -10,10 +10,11 @@
  #477-#452 - Fix for upgrade
  #459 - Turn off strict mode
  #472 - Error on line 582 index.php
  #474 - Set default to checked for secure passwords
  #497 - Moved GA QR code creation to administration
+ #xxx - Off-line mode, link make the page scroll up
  Fork from slimm609 - Encrypted Sessions and CSRFGuard enabled
  Issues with folder creation in "personal folder"
 
 2.1.19
  #413 - fix for PHP Parse error: syntax error, unexpected '['
diff --git a/datatable.logs.php b/datatable.logs.php
index b5a28dbf..2326627d 100644
--- a/datatable.logs.php
+++ b/datatable.logs.php
@@ -1,25 +1,37 @@
 <?php
 /**
- * @file          datatable.users_logged.php
- * @author        Nils Laumaill�
+ * @file          datatable.logs.php
+ * @author        Nils Laumaillé
  * @version       2.1.19
- * @copyright     (c) 2009-2014 Nils Laumaill�
+ * @copyright     (c) 2009-2014 Nils Laumaillé
  * @licensing     GNU AFFERO GPL 3.0
  * @link          http://www.teampass.net
  *
  * This library is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
 
 require_once('sources/sessions.php');
 session_start();
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
+if (
+    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 ||
+    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
+    !isset($_SESSION['key']) || empty($_SESSION['key']))
+{
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_views")) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    include 'error.php';
+    exit();
+}
+
 require_once $_SESSION['settings']['cpassman_dir'].'/sources/SplClassLoader.php';
 
 global $k, $settings;
 include $_SESSION['settings']['cpassman_dir'].'/includes/settings.php';
 header("Content-type: text/html; charset=utf-8");
@@ -40,21 +52,21 @@ if (isset($_GET['action']) && $_GET['action'] == "connections") {
 
     /* BUILD QUERY */
     //Paging
     $sLimit = "";
     if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
-        $sLimit = "LIMIT ". $_GET['iDisplayStart'] .", ". $_GET['iDisplayLength'] ;
+        $sLimit = "LIMIT ". mysql_real_escape_string($_GET['iDisplayStart']) .", ". mysql_real_escape_string($_GET['iDisplayLength']) ."" ;
     }
 
     //Ordering
 
     if (isset($_GET['iSortCol_0'])) {
         $sOrder = "ORDER BY  ";
         for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
             if ($_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true") {
-                $sOrder .= $aColumns[ intval($_GET['iSortCol_'.$i]) ]."
-                        ".mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
+                $sOrder .= $aColumns[ intval(mysql_real_escape_string($_GET['iSortCol_'.$i])) ]."
+                        '".mysql_real_escape_string($_GET['sSortDir_'.$i]) ."', ";
             }
         }
 
         $sOrder = substr_replace($sOrder, "", -2);
         if ($sOrder == "ORDER BY") {
diff --git a/error.php b/error.php
index b5fca571..68014726 100644
--- a/error.php
+++ b/error.php
@@ -61,10 +61,13 @@ if (isset($_POST['session']) && $_POST['session'] == "expired") {
         echo '
         <div class="ui-state-error ui-corner-all error" style="text-align:center;" >'.$txt['index_session_expired'].'<br /><br /><a href="index.php" />'.$txt['home'] .'</a></div>';
     } elseif (@$_SESSION['error']['code'] == ERR_NO_MCRYPT) {
         echo '
         <div class="ui-state-error ui-corner-all error" style="text-align:center;" >'.$txt['error_mcrypt_not_loaded'].'<br /><br /><a href="index.php" />'.$txt['home'] .'</a></div>';
+    } elseif (@$_SESSION['error']['code'] == ERR_VALID_SESSION) {
+        echo '
+        <div class="ui-state-error ui-corner-all error" style="text-align:center;" >'.$txt['error_not_authorized'].'<br /><br /><a href="index.php" />'.$txt['home'] .'</a></div>';
     }
 }
 
 // erase session table
 $_SESSION = array();
diff --git a/find.php b/find.php
index 3fd5dd8b..789c5b60 100644
--- a/find.php
+++ b/find.php
@@ -7,14 +7,26 @@
  * @copyright 	  (c) 2009-2014 Nils Laumaillé
  * @licensing	  GNU AFFERO GPL 3.0
  * @link
  */
 
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
+if (
+    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
+    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
+    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
+{
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], curPage())) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    include 'error.php';
+    exit();
+}
+
 require_once $_SESSION['settings']['cpassman_dir'].'/sources/SplClassLoader.php';
 
 // Build list of visible folders
 $select_visible_folders_options = $select_visible_nonpersonal_folders_options = "";
 if (isset($_SESSION['list_folders_limited']) && count($_SESSION['list_folders_limited']) > 0) {
diff --git a/folders.php b/folders.php
index 81c1ce36..bb6ed80f 100644
--- a/folders.php
+++ b/folders.php
@@ -11,14 +11,26 @@
  * This library is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
 
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
+if (
+    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
+    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
+    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
+{
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], curPage())) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    include 'error.php';
+    exit();
+}
+
 require_once $_SESSION['settings']['cpassman_dir'].'/sources/SplClassLoader.php';
 
 /* load help*/
 require_once $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'_admin_help.php';
 
@@ -87,11 +99,20 @@ echo '
 $x = 0;
 $arr_ids = array();
 foreach ($tst as $t) {
     if (in_array($t->id, $_SESSION['groupes_visibles']) && !in_array($t->id, $_SESSION['personal_visible_groups'])) {
         // r?cup $t->parent_id
-        $data = $db->fetchRow("SELECT title FROM ".$pre."nested_tree WHERE id = ".$t->parent_id);
+        //$data = $db->fetchRow("SELECT title FROM ".$pre."nested_tree WHERE id = ".$t->parent_id);
+        $data = $db->queryGetRow(
+            "nested_tree",
+            array(
+                "title"
+            ),
+            array(
+                "id" => intval($t->parent_id)
+            )
+        );
         if ($t->nlevel == 1) {
             $data[0] = $txt['root'];
         }
         // r?cup les droits associ?s ? ce groupe
         $tab_droits = array();
@@ -103,52 +124,78 @@ foreach ($tst as $t) {
         $ident = "";
         for ($l = 1; $l < $t->nlevel; $l++) {
             $ident .= "&nbsp;&nbsp;";
         }
         // Get some elements from DB concerning this node
-        $node_data = $db->fetchRow(
+        /*$node_data = $db->fetchRow(
             "SELECT m.valeur as valeur, n.renewal_period as renewal_period
             FROM ".$pre."misc as m,
             ".$pre."nested_tree as n
             WHERE m.type='complex'
             AND m.intitule = n.id
             AND m.intitule = ".$t->id
+        );*/
+        $node_data = $db->queryGetRow(
+            array(
+                "misc" => "m",
+                "nested_tree" => "n"
+            ),
+            array(
+                "m.valeur" => "valeur",
+                "n.renewal_period" => "renewal_period"
+            ),
+            array(
+                "m.type" => "complex",
+                "m.intitule" => intval(n.id),
+                "m.intitule" => intval($t->id)
+            )
         );
 
-        echo '<tr class="ligne0" id="row_'.$t->id.'">
-                        <td align="center" onclick="open_edit_folder_dialog('.$t->id.')">'.$t->id.'</td>
-                        <td width="50%" onclick="open_edit_folder_dialog('.$t->id.')">
-                            '.$ident.'<span id="title_'.$t->id.'">'.$t->title.'</span>
-                        </td>
-                        <td align="center" onclick="open_edit_folder_dialog('.$t->id.')">
-                            <span id="complexite_'.$t->id.'">'.@$pwComplexity[$node_data[0]][1].'</span>
-                        </td>
-                        <td align="center" onclick="open_edit_folder_dialog('.$t->id.')">
-                            <span id="parent_'.$t->id.'">'.$data[0].'</span>
-                        </td>
-                        <td align="center" onclick="open_edit_folder_dialog('.$t->id.')">
-                            '.$t->nlevel.'
-                        </td>
-                        <td align="center" onclick="open_edit_folder_dialog('.$t->id.')">
-                            <span id="renewal_'.$t->id.'">'.$node_data[1].'</span>
-                        </td>
-                        <td align="center">
-                            <img src="includes/images/folder--minus.png" onclick="supprimer_groupe(\''.$t->id.'\')" style="cursor:pointer;" />
-                        </td>';
+        echo '
+                <tr class="ligne0" id="row_'.$t->id.'">
+                    <td align="center" onclick="open_edit_folder_dialog('.$t->id.')">'.$t->id.'</td>
+                    <td width="50%" onclick="open_edit_folder_dialog('.$t->id.')">
+                        '.$ident.'<span id="title_'.$t->id.'">'.$t->title.'</span>
+                    </td>
+                    <td align="center" onclick="open_edit_folder_dialog('.$t->id.')">
+                        <span id="complexite_'.$t->id.'">'.@$pwComplexity[$node_data[0]][1].'</span>
+                    </td>
+                    <td align="center" onclick="open_edit_folder_dialog('.$t->id.')">
+                        <span id="parent_'.$t->id.'">'.$data[0].'</span>
+                    </td>
+                    <td align="center" onclick="open_edit_folder_dialog('.$t->id.')">
+                        '.$t->nlevel.'
+                    </td>
+                    <td align="center" onclick="open_edit_folder_dialog('.$t->id.')">
+                        <span id="renewal_'.$t->id.'">'.$node_data[1].'</span>
+                    </td>
+                    <td align="center">
+                        <img src="includes/images/folder--minus.png" onclick="supprimer_groupe(\''.$t->id.'\')" style="cursor:pointer;" />
+                    </td>';
 
-        $data3 = $db->fetchRow("SELECT bloquer_creation,bloquer_modification FROM ".$pre."nested_tree WHERE id = ".$t->id);
+        //$data3 = $db->fetchRow("SELECT bloquer_creation,bloquer_modification FROM ".$pre."nested_tree WHERE id = ".$t->id);
+        $data3 = $db->queryGetRow(
+            array(
+                "bloquer_creation",
+                "bloquer_modification"
+            ),
+            "nested_tree",
+            array(
+                "id" => intval($t->id)
+            )
+        );
         echo '
-                        <td align="center">
-                            <input type="checkbox" id="cb_droit_'.$t->id.'" onchange="Changer_Droit_Complexite(\''.$t->id.'\',\'creation\')"', isset($data3[0]) && $data3[0] == 1 ? 'checked' : '', ' />
-                        </td>
-                        <td align="center">
-                            <input type="checkbox" id="cb_droit_modif_'.$t->id.'" onchange="Changer_Droit_Complexite(\''.$t->id.'\',\'modification\')"', isset($data3[1]) && $data3[1] == 1 ? 'checked' : '', ' />
-                        </td>
-                        <td>
-                            <input type="hidden"  id="parent_id_'.$t->id.'" value="'.$t->parent_id.'" />
-                            <input type="hidden"  id="renewal_id_'.$t->id.'" value="'.$node_data[0].'" />
-                        </td>
+                    <td align="center">
+                        <input type="checkbox" id="cb_droit_'.$t->id.'" onchange="Changer_Droit_Complexite(\''.$t->id.'\',\'creation\')"', isset($data3[0]) && $data3[0] == 1 ? 'checked' : '', ' />
+                    </td>
+                    <td align="center">
+                        <input type="checkbox" id="cb_droit_modif_'.$t->id.'" onchange="Changer_Droit_Complexite(\''.$t->id.'\',\'modification\')"', isset($data3[1]) && $data3[1] == 1 ? 'checked' : '', ' />
+                    </td>
+                    <td>
+                        <input type="hidden"  id="parent_id_'.$t->id.'" value="'.$t->parent_id.'" />
+                        <input type="hidden"  id="renewal_id_'.$t->id.'" value="'.$node_data[0].'" />
+                    </td>
                 </tr>';
         array_push($arr_ids, $t->id);
         $x++;
     }
 }
diff --git a/home.php b/home.php
index 62201232..5c5c36e8 100644
--- a/home.php
+++ b/home.php
@@ -71,11 +71,18 @@ if (empty($_SESSION['last_pw_change']) || $_SESSION['validite_pw'] == false) {
                         LIMIT 0,10
                         ";
         $cpt=1;
         $rows = $db->fetchAllArray($sql);
         foreach ($rows as $record) {
-            $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."log_items WHERE id_item = '".$record['id']."' AND action = 'at_delete'");
+            //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."log_items WHERE id_item = '".$record['id']."' AND action = 'at_delete'");
+            $data = $db->queryCount(
+                "log_items",
+                array(
+                    "id_item" => intval($record['id']),
+                    "action" => "at_delete"
+                )
+            );
             if ($data[0] == 0) {
                 echo '<span class="ui-icon ui-icon-tag" style="float: left; margin-right: .3em;">&nbsp;</span>
                 <a href="#" onClick="javascript:$(\'#menu_action\').val(\'action\');window.location.href =\'index.php?page=items&amp;group='.$record['id_tree'].'&amp;id='.$record['id'].'\';" style="cursor:pointer;">'.stripslashes($record['label']).'</a><br />';
                 if ($cpt==5) {
                     break;
diff --git a/includes/images/ajax-loader.gif b/includes/images/ajax-loader.gif
index 09d621ed..e192ca89 100644
Binary files a/includes/images/ajax-loader.gif and b/includes/images/ajax-loader.gif differ
diff --git a/includes/images/ajax-loader_old.gif b/includes/images/ajax-loader_old.gif
deleted file mode 100644
index e192ca89..00000000
Binary files a/includes/images/ajax-loader_old.gif and /dev/null differ
diff --git a/includes/images/phone.png b/includes/images/phone.png
deleted file mode 100644
index c39f162f..00000000
Binary files a/includes/images/phone.png and /dev/null differ
diff --git a/includes/images/phone_add.png b/includes/images/phone_add.png
deleted file mode 100644
index d3555e02..00000000
Binary files a/includes/images/phone_add.png and /dev/null differ
diff --git a/includes/images/phone_sound.png b/includes/images/phone_sound.png
deleted file mode 100644
index 7fdf1c58..00000000
Binary files a/includes/images/phone_sound.png and /dev/null differ
diff --git a/includes/images/ui-toolbar-bookmark.png b/includes/images/ui-toolbar-bookmark.png
new file mode 100644
index 00000000..5525d339
Binary files /dev/null and b/includes/images/ui-toolbar-bookmark.png differ
diff --git a/includes/include.php b/includes/include.php
index ad894dec..95415fe2 100644
--- a/includes/include.php
+++ b/includes/include.php
@@ -11,11 +11,10 @@
 // DONT'T CHANGE BELOW THIS LINE
 global $settings, $languagesList;
 
 $k['version'] = "2.1.20";
 $k['tool_name'] = "TeamPass";
-$k['copyright'] = "&nbsp;&copy;&nbsp;copyright 2009-2014";
 $k['jquery-version'] = "1.9.1";
 $k['jquery-ui-version'] = "1.10.3";
 $k['jquery-ui-theme'] = "overcast";
 $k['one_month_seconds'] = 2592000;
 $k['image_file_ext'] = array('jpg', 'gif', 'png', 'jpeg', 'tiff', 'bmp');
diff --git a/includes/language/english.php b/includes/language/english.php
index 8ab29ac0..540f0524 100644
--- a/includes/language/english.php
+++ b/includes/language/english.php
@@ -4,17 +4,10 @@ if (!isset($_SESSION['settings']['cpassman_url'])) {
     $TeamPass_url = '';
 } else {
     $TeamPass_url = $_SESSION['settings']['cpassman_url'];
 }
 
-$txt['user_ga_code'] = "Send GoogleAuthenticator to user by email";
-$txt['send_ga_code'] = "Google Authenticator for user";
-$txt['error_no_email'] = "This user has no email set!";
-$txt['error_no_user'] = "No user found!";
-$txt['email_ga_subject'] = "Your Google Authenticator flash code for Teampass";
-$txt['email_ga_text'] = "Hello,<br><br>Please click this <a href='#link#'>LINK</a> and flash it with GoogleAuthenticator application to get your OTP credentials for Teampass.<br /><br />Cheers";
-
 $txt['settings_attachments_encryption'] = "Enable encryption of Items attachments";
 $txt['settings_attachments_encryption_tip'] = "THIS OPTION COULD BREAK EXISTING ATTACHMENTS, please read carefully the next. If enabled, Items attachments are stored encrypted on the server. The ecryption uses the SALT defined for Teampass. This requieres more server ressources. WARNING: once you change strategy, it is mandatory to run the script to adapt existing attachments. See tab 'Specific Actions'.";
 $txt['admin_action_attachments_cryption'] = "Encrypt or Decrypt the Items attachments";
 $txt['admin_action_attachments_cryption_tip'] = "WARNING: this action has ONLY to be performed after changing the associated option in Teampass settings. Please make a copy of the folder 'upload' before doing any action, just in case ...";
 $txt['encrypt'] = "Encrypt";
@@ -97,11 +90,11 @@ $txt['settings_anyone_can_modify_bydefault'] = "Activate '<b><i>Anyone can modif
 $txt['channel_encryption_in_progress'] = "Encrypting channel ...";
 $txt['channel_encryption_failed'] = "Authentication failed!";
 $txt['purge_log'] = "Purge logs from";
 $txt['to'] = "to";
 $txt['purge_now'] = "Purge Now!";
-$txt['purge_done'] = "Purge done! Number of elements deleted: ";
+$txt['purge_done'] = "The purge has been performed!<br />Number of elements deleted: ";
 
 $txt['settings_upload_maxfilesize_tip'] = "Maximum file size you allow. It should be coherant with your server settings.";
 $txt['settings_upload_docext_tip'] = "Document types. Indicate the file extensions allowed separated with a coma (,)";
 $txt['settings_upload_imagesext_tip'] = "Image types. Indicate the file extensions allowed separated with a coma (,)";
 $txt['settings_upload_pkgext_tip'] = "Package types. Indicate the file extensions allowed separated with a coma (,)";
diff --git a/includes/libraries/Authentication/GoogleAuthenticator/GoogleAuthenticator.php b/includes/libraries/Authentication/GoogleAuthenticator/GoogleAuthenticator.php
index 1d4eddb4..97ccba28 100644
--- a/includes/libraries/Authentication/GoogleAuthenticator/GoogleAuthenticator.php
+++ b/includes/libraries/Authentication/GoogleAuthenticator/GoogleAuthenticator.php
@@ -36,28 +36,18 @@ class GoogleAuthenticator
     /**
      * @param $secret
      * @param $code
      * @return bool
      */
-    public function checkCode($secret, $code, $discrepancy = 3)
+    public function checkCode($secret, $code)
     {
-        /*
-       $time = floor(time() / 30);
+        $time = floor(time() / 30);
         for ($i = -1; $i <= 1; $i++) {
             if ($this->getCode($secret, $time + $i) == $code) {
                 return true;
             }
         }
-   		*/
-    	$currentTimeSlice = floor(time() / 30);
-
-    	for ($i = -$discrepancy; $i <= $discrepancy; $i++) {
-    		$calculatedCode = $this->getCode($secret, $currentTimeSlice + $i);
-    		if ($calculatedCode == $code ) {
-    			return true;
-    		}
-    	}
 
         return false;
     }
 
     /**
diff --git a/includes/libraries/Database/Core/DbCore.php b/includes/libraries/Database/Core/DbCore.php
index cbc79a43..e5214f93 100644
--- a/includes/libraries/Database/Core/DbCore.php
+++ b/includes/libraries/Database/Core/DbCore.php
@@ -165,11 +165,152 @@ class DbCore
         $record = mysql_fetch_row($this->query_id);
 
         $this->freeResult($query_id);
 
         return $record;
-    }#-#fetchArray()
+    }#-#fetchRow()
+
+    #-#############################################
+    # desc: builds the sql query
+    # param: tables, inputs, conditions, extras
+    # return: string SQL query
+    public function prepareData($table, $data, $where, $extra = "", $inner = "")
+    {
+        $q = "SELECT ";
+
+        // data
+        $d = "";
+        if (is_array($data)) {
+            foreach ($data as $key => $val) {
+                if (is_int($key)) {
+                    $d .= "`".$this->escape($val)."`, ";
+                } else {
+                    if (strpos($key,'.') === false) {
+                        $d .= "`$key` AS $val, ";
+                    } else {
+                        $d .= "$key AS $val, ";
+                    }
+                }
+            }
+            $q .= substr_replace($d, "", -2);
+        } else {
+            $d = $data." ";
+        }
+
+        // table
+        if (is_array($table)) {
+            $t = "";
+            $q .= " FROM ";
+            foreach ($table as $key => $val) {
+                $t .= "`".$this->pre.$key."` AS ".$this->escape($val).", ";
+            }
+            $q .= substr_replace($t, "", -2)." ";
+        } else {
+            $q .= " FROM `".$this->pre.$table."` ";
+        }
+
+        // inner join conditions
+        if (!empty($inner)) {
+            $i = "";
+            foreach ($inner as $key => $val) {
+                $i .= "INNER JOIN ".$this->pre.$key." ON ".$val." ";
+            }
+            $q .= $i;
+        }
+
+        // where
+        $w = "";
+        foreach ($where as $key => $val) {
+            if (strtolower($val) == 'null') {
+                $w .= "`$key` = NULL, ";
+            } elseif (strtolower($val)=='now()') {
+                $w .= "`$key` = NOW(), ";
+            } else {
+                if (strpos($key,'.') === false) {
+                    $w .= "`$key` = '".$this->escape($val)."' AND ";
+                } else {
+                    $w .= "$key = '".$this->escape($val)."' AND ";
+                }
+            }
+        }
+
+        // compile
+        return rtrim($q, ', ').' WHERE '. rtrim($w, ' AND ') . $extra .';';
+    }#-#prepareData()
+
+    #-#############################################
+    # desc: fetches and return result of one line
+    # param: table (no prefix), array of fields to return, array for where conditions
+    # return: (array) fetched record
+    public function queryGetRow($table, $data, $where, $extra = "", $inner = "")
+    {
+        $q =  $this->prepareData($table, $data, $where, $extra, $inner);
+
+        $query_id = $this->query($q);
+
+        if (isset($this->query_id)) {
+            $record = mysql_fetch_row($this->query_id);
+        } else {
+            $this->oops("Invalid query_id: <b>$this->query_id</b>. Records could not be fetched.");
+        }
+
+        $this->freeResult($query_id);
+
+        return $record;
+    }#-#queryGetRow()
+
+    #-#############################################
+    # desc: fetches and return result of one line
+    # param: table (no prefix), array of fields to return, array for where conditions
+    # return: (array) fetched record
+    public function queryGetArray($table, $data, $where, $extra = "", $inner = "")
+    {
+        $q =  $this->prepareData($table, $data, $where, $extra, $inner);
+
+        $query_id = $this->query($q);
+
+        if (isset($this->query_id)) {
+            $record = mysql_fetch_assoc($this->query_id) or die(mysql_error()." | ".$q);
+        } else {
+            $this->oops("Invalid query_id: <b>$this->query_id</b>. Records could not be fetched.");
+        }
+
+        $this->freeResult($query_id);
+
+        return $record;
+    }#-#queryGetRow()
+
+    #-#############################################
+    # desc: fetches and return the number of lines
+    # param: table (no prefix), array of fields to return, array for where conditions
+    # return: (array) fetched record
+    public function queryCount($table, $where)
+    {
+        $q = "SELECT COUNT(*) FROM `".$this->pre.$table."` ";
+
+        if (is_array($where)) {
+            $w = "";
+            foreach ($where as $key => $val) {
+                if (strtolower($val) == 'null') {
+                    $w .= "`$key` = NULL, ";
+                } elseif (strtolower($val)=='now()') {
+                    $w .= "`$key` = NOW(), ";
+                } else {
+                    $w .= "`$key`='".$this->escape($val)."' AND ";
+                }
+            }
+        } else {
+            $w = $where;
+        }
+        $q = rtrim($q, ', ').' WHERE '. rtrim($w, ' AND ') .';';
+
+        $query_id = $this->query($q);
+        $out = mysql_fetch_row($query_id);
+        $this->freeResult($query_id);
+
+        return $out;
+    }
 
 
     #-#############################################
     # desc: returns all the results (not one row)
     # param: (MySQL query) the query to run on server
@@ -287,16 +428,16 @@ class DbCore
                 $v.= "'".$this->escape($val)."', ";
             }
         }
 
         $q .= "(". rtrim($n, ', ') .") VALUES (". rtrim($v, ', ') .");";
-        
+
         $this->query($q);
-        
+
         if (isset($this->link_id)) {
             return mysql_insert_id($this->link_id);
-        } else {            
+        } else {
             $this->oops("Result ID: <b>$this->query_id</b> could not be executed.");
             return false;
         }
 
     }#-#queryInsert()
diff --git a/includes/settings.php b/includes/settings.php
index 8015351e..989a2bdf 100644
--- a/includes/settings.php
+++ b/includes/settings.php
@@ -4,12 +4,12 @@ global $server, $user, $pass, $database, $pre, $db;
 
 ### DATABASE connexion parameters ###
 $server = "localhost";
 $user = "root";
 $pass = "";
-$database = "tp";
+$database = "tpssl";
 $pre = "teampass_";
 
 @date_default_timezone_set($_SESSION['settings']['timezone']);
-@define('SECUREPATH', 'E:/xampp/security');
-require_once "E:/xampp/security/sk.php";
+@define('SECUREPATH', 'C:/nils.laumaille/utils/xamppssl/security');
+require_once "C:/nils.laumaille/utils/xamppssl/security/sk.php";
 @define('COST', '13'); // Don't change this.
\ No newline at end of file
diff --git a/index.php b/index.php
index 2d94e60b..600031a0 100644
--- a/index.php
+++ b/index.php
@@ -20,10 +20,11 @@ session_start();
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
 
 $_SESSION['CPM'] = 1;
 session_id();
+
 // Test if settings.file exists, if not then install
 if (!file_exists('includes/settings.php')) {
     echo '
     <script language="javascript" type="text/javascript">
     <!--
@@ -52,15 +53,25 @@ $db->connect();
 require_once 'sources/main.functions.php';
 
 /* DEFINE WHAT LANGUAGE TO USE */
 if (!isset($_SESSION['user_id']) && !isset($_POST['language'])) {
     //get default language
-    $dataLanguage =
+    /*$dataLanguage =
         $db->fetchRow(
             "SELECT valeur FROM ".$pre."misc
             WHERE type = 'admin' AND intitule = 'default_language'"
-        );
+        );*/
+    $dataLanguage = $db->queryGetRow(
+        "misc",
+        array(
+            "valeur"
+        ),
+        array(
+            "type" => "admin",
+            "intitule" => "default_language"
+        )
+    );
     if (empty($dataLanguage[0])) {
         $_SESSION['user_language'] = "english";
         $_SESSION['user_language_flag'] = "us.png";
     } else {
         $_SESSION['user_language'] = $dataLanguage[0];
@@ -276,11 +287,13 @@ if (isset($_SESSION['autoriser']) && $_SESSION['autoriser'] == true && isset($_G
             <br />
             <button title="'.$txt['item_menu_copy_elem'].'" id="menu_button_copy_item" onclick="open_copy_item_to_folder_div()" style="margin-bottom:5px;"><img src="includes/images/key_copy.png" alt="" /></button>
             <br />
             <button title="'.$txt['pw_copy_clipboard'].'" id="menu_button_copy_pw" class="copy_clipboard"><img src="includes/images/ui-text-field-password.png" id="div_copy_pw" alt="" /></button>
             <br />
-            <button title="'.$txt['login_copy'].'" style="margin-bottom:5px;" id="menu_button_copy_login" class="copy_clipboard"><img src="includes/images/ui-text-field.png" id="div_copy_login" alt="" /></button>
+            <button title="'.$txt['login_copy'].'" id="menu_button_copy_login" class="copy_clipboard"><img src="includes/images/ui-text-field.png" id="div_copy_login" alt="" /></button>
+            <br />
+            <button title="'.$txt['url_copy'].'" style="margin-bottom:5px;" id="menu_button_copy_url" class="copy_clipboard"><img src="includes/images/ui-toolbar-bookmark.png" id="div_copy_url" alt="" /></button>
             <br />
             <button title="'.$txt['mask_pw'].'" style="margin-bottom:5px;" id="menu_button_show_pw" onclick="ShowPassword()"><img src="includes/images/eye.png" alt="" /></button>
             <br />
             <button title="'.$txt['link_copy'].'" style="margin-bottom:5px;" id="menu_button_copy_link" class="copy_clipboard"><img src="includes/images/target.png" id="div_copy_link" alt="" /></button>
             <br />
@@ -441,10 +454,19 @@ if (isset($_SESSION['validite_pw']) && $_SESSION['validite_pw'] == true && !empt
 } elseif ((!isset($_SESSION['validite_pw']) || empty($_SESSION['validite_pw']) || empty($_SESSION['user_id'])) && !empty($_GET['page'])) {
     // case where user not logged and can't access a direct link
     $_SESSION['error']['code'] = ERR_SESS_EXPIRED;
     $_SESSION['initial_url'] = substr($_SERVER["REQUEST_URI"], strpos($_SERVER["REQUEST_URI"], "index.php?"));
     include 'error.php';
+} elseif ((!isset($_SESSION['validite_pw']) || empty($_SESSION['validite_pw']) || empty($_SESSION['user_id'])) && isset($_GET['otv']) && $_GET['otv'] == "true") {
+    // case where one-shot viewer
+    if (isset($_GET['session']) && !empty($_GET['session'])) {
+        include 'otv.php?session='.$_GET['session'];
+    } else {
+        $_SESSION['error']['code'] = ERR_VALID_SESSION;
+        $_SESSION['initial_url'] = substr($_SERVER["REQUEST_URI"], strpos($_SERVER["REQUEST_URI"], "index.php?"));
+        include 'error.php';
+    }    
 } elseif (empty($_SESSION['user_id']) && isset($_GET['action']) && $_GET['action'] == "password_recovery") {
     // Case where user has asked new PW
     echo '
         <div style="width:400px;margin:50px auto 50px auto;padding:25px;" class="ui-state-highlight ui-corner-all">
             <div style="text-align:center;font-weight:bold;margin-bottom:20px;">
diff --git a/items.load.php b/items.load.php
index 62acb50e..6051f129 100644
--- a/items.load.php
+++ b/items.load.php
@@ -337,25 +337,30 @@ function pwGenerate(elem)
 
     //show ajax image
     $("#"+elem+"pw_wait").show();
 
     $.post(
-        "sources/items.queries.php",
+        "sources/main.queries.php",
         {
-            type    : "pw_generate",
+            type    : "generate_a_password",
             size      : $("#"+elem+'pw_size').val(),
             num      : $("#"+elem+'pw_numerics').prop("checked"),
             maj      : $("#"+elem+'pw_maj').prop("checked"),
             symb      : $("#"+elem+'pw_symbols').prop("checked"),
             secure  : $("#"+elem+'pw_secure').prop("checked"),
             elem      : elem,
             force      : "false"
         },
         function(data) {
-        	data = prepareExchangedData(data, "decode");
-            $("#"+elem+"pw1").val(data.key).focus();
-			$("#visible_pw").text(data.key);
+			data = prepareExchangedData(data, "decode");
+           	if (data.error == "true") {
+           		$("#div_dialog_message_text").html(data.error_msg);
+           		$("#div_dialog_message").dialog("open");
+           	} else {
+           		$("#"+elem+"pw1").val(data.key).focus();
+				$("#visible_pw").text(data.key);
+           	}
             $("#"+elem+"pw_wait").hide();
         }
    );
 }
 
@@ -927,11 +932,11 @@ function AfficherDetailsItem(id, salt_key_required, expired_item, restricted, di
     if (display == "no_display") {
         $("#item_details_nok").show();
         $("#item_details_ok").hide();
         $("#item_details_expired").hide();
         $("#item_details_expired_full").hide();
-        $("#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");
+        $("#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_url, #menu_button_copy_link").attr("disabled","disabled");
         $("#request_ongoing").val("");
         return false;
     }
     $("#div_loading").show();//LoadingPage();
     if ($("#is_admin").val() == "1") {
@@ -1155,10 +1160,19 @@ function AfficherDetailsItem(id, salt_key_required, expired_item, restricted, di
                             clip.addEventListener('complete', function(client, text) {
                                     $("#message_box").html("<?php echo addslashes($txt['login_copied_clipboard']);?>").show().fadeOut(1000);
                             });
                             clip.glue('menu_button_copy_login');
                         }
+                        // #XXX
+                        if (data.url != "") {
+                            var clip = new ZeroClipboard.Client();
+                            clip.setText(data.url);
+                            clip.addEventListener('complete', function(client, text) {
+                                    $("#message_box").html("<?php echo addslashes($txt['url_copied_clipboard']);?>").show().fadeOut(1000);
+                            });
+                            clip.glue('menu_button_copy_url');
+                        }
                         //prepare link to clipboard
                         var clip = new ZeroClipboard.Client();
                         clip.setText("<?php echo $_SESSION['settings']['cpassman_url'];?>/index.php?page=items&group="+data.folder+"&id="+data.id);
                         clip.addEventListener('complete', function(client, text) {
                                 $("#message_box").html("<?php echo addslashes($txt['url_copied']);?>").show().fadeOut(1000);
diff --git a/items.php b/items.php
index a0a5a704..45741676 100644
--- a/items.php
+++ b/items.php
@@ -11,16 +11,24 @@
  * This library is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
 
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
+if (
+    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
+    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
+    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
+{
     die('Hacking attempt...');
 }
 
-if (!isset($_SESSION['login'])) {
-    break;
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], curPage())) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    //include 'error.php';
+    exit();
 }
 
 require_once $_SESSION['settings']['cpassman_dir'].'/sources/SplClassLoader.php';
 
 //Build tree
@@ -165,11 +173,18 @@ foreach ($folders as $folder) {
         // Check if any allowed folder is part of the descendants of this node
         $nodeDescendants = $tree->getDescendants($folder->id, true, false, true);
         foreach ($nodeDescendants as $node) {
             // manage tree counters
             if (isset($_SESSION['settings']['tree_counters']) && $_SESSION['settings']['tree_counters'] == 1) {
-                $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."items WHERE inactif=0 AND id_tree = ".$node);
+                //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."items WHERE inactif=0 AND id_tree = ".$node);
+                $data = $db->queryCount(
+                    "items",
+                    array(
+                        "inactif" => 0,
+                        "id_tree" => intval($node)
+                    )
+                );
                 $nbChildrenItems += $data[0];
             }
             if (
                 in_array(
                     $node,
@@ -187,11 +202,18 @@ foreach ($folders as $folder) {
             $ident = "";
             for ($x = 1; $x < $folder->nlevel; $x++) {
                 $ident .= "&nbsp;&nbsp;";
             }
 
-            $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."items WHERE inactif=0 AND id_tree = ".$folder->id);
+            //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."items WHERE inactif=0 AND id_tree = ".$folder->id);
+            $data = $db->queryCount(
+                "items",
+                array(
+                    "inactif" => 0,
+                    "id_tree" => intval($folder->id)
+                )
+            );
             $itemsNb = $data[0];
 
             // get 1st folder
             if (empty($firstGroup)) {
                 $firstGroup = $folder->id;
@@ -1008,8 +1030,8 @@ echo '
 </div>';
 // DIALOG FOR ITEM IS UPDATED
 echo '
 <div id="div_item_updated" style="display:none;">
     <div style="">'.$txt['item_updated_text'].'</div>
-</div>';
+</div><br />';
 
 require_once 'items.load.php';
diff --git a/kb.php b/kb.php
index d1831e41..e7abcad6 100644
--- a/kb.php
+++ b/kb.php
@@ -10,17 +10,28 @@
  * This library is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
 
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1
+if (
+        !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 ||
+        !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) ||
+        !isset($_SESSION['key']) || empty($_SESSION['key'])
         || !isset($_SESSION['settings']['enable_kb'])
-        || $_SESSION['settings']['enable_kb'] != 1
-) {
+        || $_SESSION['settings']['enable_kb'] != 1)
+{
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], curPage())) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    include 'error.php';
+    exit();
+}
+
 //load language
 require_once $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'_kb.php';
 
 //build list of categories
 $tab_users = array();
diff --git a/load.php b/load.php
index 3d101d5f..901cd082 100644
--- a/load.php
+++ b/load.php
@@ -232,15 +232,17 @@ $htmlHeaders .= '
     * Manage generation of new password
     */
     function GenerateNewPassword(key, login)
     {
         $("#ajax_loader_send_mail").show();
+        // prepare data
+        data = \'{"login":"\'+sanitizeString(login)+\'" ,\'+
+            \'"key":"\'+sanitizeString(key)+\'"}\';
         //send query
         $.post("sources/main.queries.php", {
                 type :    "generate_new_password",
-                login:    login,
-                key :    key
+    		    data : prepareExchangedData(data, "encode")
             },
             function(data) {
                 if (data == "done") {
                     window.location.href="index.php";
                 } else {
@@ -282,15 +284,16 @@ $htmlHeaders .= '
 
     //Change language using icon flags
     function ChangeLanguage(lang)
     {
         $("#language").val(lang);
+        data = \'{"lang":"\'+sanitizeString(lang)+\'"}\';    		        
         $.post(
             "sources/main.queries.php",
             {
-                type    : "change_user_language",
-                lang    : lang
+                type : "change_user_language",
+                data : prepareExchangedData(data, "encode")
             },
             function(data) {
             	if (data == "done") {
 	                $("#language").val(lang);
 	                document.location.href="index.php";
diff --git a/patch.php b/patch.php
deleted file mode 100644
index 6a08bb36..00000000
--- a/patch.php
+++ /dev/null
@@ -1,37 +0,0 @@
-<?php
-session_start();
-
-include './includes/settings.php';
-include './sources/main.functions.php';
-
-require_once './sources/SplClassLoader.php';
-
-// connect to the server
-$db = new SplClassLoader('Database\Core', './includes/libraries');
-$db->register();
-$db = new Database\Core\DbCore($server, $user, $pass, $database, $pre);
-$db->connect();
-
-$rows = $db->fetchAllArray("SELECT id, pw FROM ".$pre."items WHERE perso = '0'");
-foreach ($rows as $reccord) {
-	$pw = decrypt($reccord['pw']);
-	if (!empty($pw) && strlen($pw) > 30 && isutf8($pw)) {
-
-		$key = substr($pw, 0, 15);
-		$pw = substr($pw,30);
-
-		$pw = $key . $pw;
-
-		$pw = encrypt($pw);
-
-		$db->queryUpdate(
-			'items',
-			array(
-			    'pw' => $pw
-			),
-			"id='".$reccord['id']."'"
-		);
-	}
-}
-
-?>
\ No newline at end of file
diff --git a/roles.php b/roles.php
index e7875726..1897a6f4 100644
--- a/roles.php
+++ b/roles.php
@@ -10,14 +10,26 @@
  * This library is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
 
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
+if (
+    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
+    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
+    !isset($_SESSION['key']) || empty($_SESSION['key'])
+){
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], curPage())) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    include 'error.php';
+    exit();
+}
+
 //load help
 require_once $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'_admin_help.php';
 
 //Get full list of groups
 $arr_groups = array();
diff --git a/sources/admin.queries.php b/sources/admin.queries.php
index 91869e0e..d9a677c2 100644
--- a/sources/admin.queries.php
+++ b/sources/admin.queries.php
@@ -13,14 +13,26 @@
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
 
 require_once('sessions.php');
 session_start();
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || !isset($_SESSION['key']) || empty($_SESSION['key'])) {
+if (
+    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
+    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
+    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
+{
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_settings")) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    include 'error.php';
+    exit();
+}
+
 include $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
 include $_SESSION['settings']['cpassman_dir'].'/includes/settings.php';
 include $_SESSION['settings']['cpassman_dir'].'/includes/include.php';
 header("Content-type: text/html; charset=utf-8");
 header("Cache-Control: no-cache, no-store, must-revalidate");
@@ -116,11 +128,18 @@ switch ($_POST['type']) {
                ),
                 "id='".$record['id']."'"
             );
 
             //if folder doesn't exist then create it
-            $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."nested_tree WHERE title = '".$record['id']."' AND parent_id = 0");
+            //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."nested_tree WHERE title = '".$record['id']."' AND parent_id = 0");
+            $data = $db->queryCount(
+                "nested_tree",
+                array(
+                    "title" => $record['id'],
+                    "parent_id" => 0
+                )
+            );
             if ($data[0] == 0) {
                 //If not exist then add it
                 $db->queryInsert(
                     "nested_tree",
                     array(
@@ -192,11 +211,18 @@ switch ($_POST['type']) {
             "SELECT id
             FROM ".$pre."items
             ORDER BY id ASC"
         );
         foreach ($rows as $item) {
-            $row = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."log_items WHERE id_item=".$item['id']." AND action = 'at_creation'");
+            //$row = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."log_items WHERE id_item=".$item['id']." AND action = 'at_creation'");
+            $row = $db->queryCount(
+                "log_items",
+                array(
+                    "id_item" => $item['id'],
+                    "action" => "at_creation"
+                )
+            );
             if ($row[0] == 0) {
                 $db->query("DELETE FROM ".$pre."items WHERE id = ".$item['id']);
                 $db->query("DELETE FROM ".$pre."categories_items WHERE item_id = ".$item['id']);
                 $db->query("DELETE FROM ".$pre."log_items WHERE id_item = ".$item['id']);
                 $nbItemsDeleted++;
@@ -368,11 +394,18 @@ switch ($_POST['type']) {
             "SELECT id
             FROM ".$pre."items
             ORDER BY id ASC"
         );
         foreach ($rows as $item) {
-            $row = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."log_items WHERE id_item=".$item['id']." AND action = 'at_creation'");
+            //$row = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."log_items WHERE id_item=".$item['id']." AND action = 'at_creation'");
+            $row = $db->queryCount(
+                "log_items",
+                array(
+                    "id_item" => $item['id'],
+                    "action" => "at_creation"
+                )
+            );
             if ($row[0] == 0) {
                 //Create new at_creation entry
                 $rowTmp = $db->queryFirst("SELECT date FROM ".$pre."log_items WHERE id_item=".$item['id']." ORDER BY date ASC");
                 $db->queryInsert(
                     'log_items',
@@ -617,11 +650,18 @@ switch ($_POST['type']) {
         $numOfItemsChanged = 0;
         // go for all Items and get their PW
         $rows = $db->fetchAllArray("SELECT id, pw FROM ".$pre."items WHERE perso = '0'");
         foreach ($rows as $reccord) {
             // check if key exists for this item
-            $row = @$db->fetchRow("SELECT COUNT(*) FROM ".$pre."keys WHERE `id`='".$reccord['id']."' AND `table` = 'items'");
+            //$row = @$db->fetchRow("SELECT COUNT(*) FROM ".$pre."keys WHERE `id`='".$reccord['id']."' AND `table` = 'items'");
+            $row = $db->queryCount(
+                "keys",
+                array(
+                    "id" => $reccord['id'],
+                    "table" => "items"
+                )
+            );
             if ($row[0] == 0) {
                 $storePrefix = false;
                 // decrypt pw
                 $pw = decrypt($reccord['pw']);
                 if (!empty($pw) && strlen($pw) > 15 && isutf8($pw)) {
diff --git a/sources/categories.queries.php b/sources/categories.queries.php
index 4971e321..eba959a9 100644
--- a/sources/categories.queries.php
+++ b/sources/categories.queries.php
@@ -10,15 +10,28 @@
  * This library is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
 
+require_once('sessions.php');
 session_start();
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || !isset($_SESSION['key']) || empty($_SESSION['key'])) {
+if (
+    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
+    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
+    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
+{
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_settings")) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    include 'error.php';
+    exit();
+}
+
 include $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
 include $_SESSION['settings']['cpassman_dir'].'/includes/settings.php';
 header("Content-type: text/html; charset==utf-8");
 include 'main.functions.php';
 require_once $_SESSION['settings']['cpassman_dir'].'/sources/SplClassLoader.php';
@@ -181,11 +194,20 @@ if (isset($_POST['type'])) {
                             'id_folder' => $folder
                            )
                     );
                     
                     // prepare a list
-                    $row = $db->fetchRow("SELECT title FROM ".$pre."nested_tree WHERE id=".$folder);
+                    //$row = $db->fetchRow("SELECT title FROM ".$pre."nested_tree WHERE id=".$folder);
+                    $row = $db->queryGetRow(
+                        "nested_tree",
+                        array(
+                            "title"
+                        ),
+                        array(
+                            "id" => intval($folder)
+                        )
+                    );
                     if (empty($list)) {
                         $list = $row[0];
                     } else {
                         $list .= " | ".$row[0];
                     }
diff --git a/sources/checks.php b/sources/checks.php
new file mode 100644
index 00000000..62efaa8c
--- /dev/null
+++ b/sources/checks.php
@@ -0,0 +1,84 @@
+<?php
+/**
+ *
+ * @file          checks.php
+ * @author        Nils Laumaillé
+ * @version       2.1.20
+ * @copyright     (c) 2009-2014 Nils Laumaillé
+ * @licensing     GNU AFFERO GPL 3.0
+ * @link		  http://www.teampass.net
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ */
+
+$pagesRights = array(
+    "user" => array(
+        "home", "items", "find", "kb", "favourites"
+    ),
+    "manager" => array(
+        "home", "items", "find", "kb", "favourites", "manage_roles", "manage_folders", "manage_views", "manage_users"
+    ),
+    "admin" => array(
+        "home", "items", "find", "kb", "favourites", "manage_roles", "manage_folders", "manage_views", "manage_users", "manage_settings", "manage_main"
+    )
+);
+
+function curPage()
+{
+    parse_str(substr($_SERVER["REQUEST_URI"], strpos($_SERVER["REQUEST_URI"], "?")+1), $result);
+    return $result['page'];
+}
+
+function checkUser($userId, $userKey, $pageVisited)
+{
+    global $pagesRights;
+
+    if (empty($userId) || empty($pageVisited) || empty($userKey)) {
+        return false;
+    }
+
+    include $_SESSION['settings']['cpassman_dir'].'/includes/settings.php';
+    require_once $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
+    require_once $_SESSION['settings']['cpassman_dir'].'/sources/SplClassLoader.php';
+
+    // Connect to mysql server
+    $db = new SplClassLoader('Database\Core', $_SESSION['settings']['cpassman_dir'].'/includes/libraries');
+    $db->register();
+    $db = new Database\Core\DbCore($server, $user, $pass, $database, $pre);
+    $db->connect();
+
+    // load user's data
+    /*$sql = "SELECT * FROM ".$pre."users WHERE id = '$userId'";
+    $row = $db->query($sql);
+    $data = $db->fetchArray($row);*/
+    $data = $db->queryGetArray(
+        "users",
+        array(
+            "login",
+            "key_tempo",
+            "admin",
+            "gestionnaire"
+        ),
+        array(
+            "id" => intval($userId)
+        )
+    );
+
+    // check if user exists and tempo key is coherant
+    if (empty($data['login']) || empty($data['key_tempo']) || $data['key_tempo'] != $userKey) {
+        return false;
+    }
+
+    // check if user is allowed to see this page
+    if (empty($data['admin']) && empty($data['gestionnaire']) && !in_array($pageVisited, $pagesRights['user'])) {
+        return false;
+    } else if (empty($data['admin']) && !empty($data['gestionnaire']) && !in_array($pageVisited, $pagesRights['manager'])) {
+        return false;
+    } else if (!empty($data['admin']) && !in_array($pageVisited, $pagesRights['admin'])) {
+        return false;
+    }
+
+    return true;
+}
\ No newline at end of file
diff --git a/sources/core.php b/sources/core.php
index 288ddda8..ddcd1109 100644
--- a/sources/core.php
+++ b/sources/core.php
@@ -143,11 +143,20 @@ if (
     exit;
 }
 
 /* CHECK IF SESSION EXISTS AND IF SESSION IS VALID */
 if (!empty($_SESSION['fin_session'])) {
-    $dataSession = $db->fetchRow("SELECT key_tempo FROM ".$pre."users WHERE id=".$_SESSION['user_id']);
+    //$dataSession = $db->fetchRow("SELECT key_tempo FROM ".$pre."users WHERE id=".$_SESSION['user_id']);
+    $dataSession = $db->queryGetRow(
+        "users",
+        array(
+            "key_tempo"
+        ),
+        array(
+            "id" => intval($_SESSION['user_id'])
+        )
+    );
 } else {
     $dataSession[0] = "";
 }
 
 if (
@@ -189,11 +198,21 @@ if (
 /* CHECK IF UPDATE IS NEEDED */
 if (
     isset($_SESSION['settings']['update_needed']) && ($_SESSION['settings']['update_needed'] != false
     || empty($_SESSION['settings']['update_needed']))
 ) {
-    $row = $db->fetchRow("SELECT valeur FROM ".$pre."misc WHERE type = 'admin' AND intitule = 'cpassman_version'");
+    //$row = $db->fetchRow("SELECT valeur FROM ".$pre."misc WHERE type = 'admin' AND intitule = 'cpassman_version'");
+    $row = $db->queryGetRow(
+        "misc",
+        array(
+            "valeur"
+        ),
+        array(
+            "type" => "admin",
+            "intitule" => "cpassman_version"
+        )
+    );
     if ($row[0] != $k['version']) {
         $_SESSION['settings']['update_needed'] = true;
     } else {
         $_SESSION['settings']['update_needed'] = false;
     }
@@ -283,13 +302,23 @@ if (
 }
 
 /* LOAD INFORMATION CONCERNING USER */
 if (isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])) {
     // query on user
-    $sql="SELECT * FROM ".$pre."users WHERE id = '".$_SESSION['user_id']."'";
-    $row = $db->query($sql);
-    $data = $db->fetchArray($row);
+    $data = $db->queryGetArray(
+        "users",
+        array(
+            "admin",
+            "gestionnaire",
+            "groupes_visibles",
+            "groupes_interdits",
+            "fonction_id"
+        ),
+        array(
+            "id" => intval($_SESSION['user_id'])
+        )
+    );
 
     //Check if user has been deleted or unlogged
     if (empty($data)) {
         // erase session table
         $_SESSION = array();
@@ -415,7 +444,7 @@ if (
         $_SESSION['temporary']['send_stats_done'] = true;   //permits to test only once by session
     }
 }
 
 /* CHECK NUMBER OF USER ONLINE */
-$queryCount = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."users WHERE timestamp >= '".(time() - 600)."'");
+$queryCount = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."users WHERE timestamp >= '".intval((time() - 600))."'");
 $_SESSION['nb_users_online'] = $queryCount[0];
\ No newline at end of file
diff --git a/sources/datatable/datatable.item_edition.php b/sources/datatable/datatable.item_edition.php
index 8372d7eb..322b3ed3 100644
--- a/sources/datatable/datatable.item_edition.php
+++ b/sources/datatable/datatable.item_edition.php
@@ -46,11 +46,11 @@ if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
 
 if (isset($_GET['iSortCol_0'])) {
     $sOrder = "ORDER BY  ";
     for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
         if ($_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true") {
-            $sOrder .= $aColumns[ intval($_GET['iSortCol_'.$i]) ]."
+            $sOrder .= $aColumns[ intval(mysql_real_escape_string($_GET['iSortCol_'.$i])) ]."
             ".mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
         }
     }
 
     $sOrder = substr_replace($sOrder, "", -2);
@@ -66,11 +66,10 @@ if (isset($_GET['iSortCol_0'])) {
 * on very large tables, and MySQL's regex functionality is very limited
 */
 if ($_GET['sSearch'] != "") {
     $sWhere = " WHERE (";
     for ($i=0; $i<count($aColumns); $i++) {
-        $sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string($_GET['sSearch'])."%' OR ";
     }
     $sWhere = substr_replace($sWhere, "", -3).") ";
 }
 
 $sql = "SELECT e.timestamp,e.item_id, e.user_id, u.login, u.name, u.lastname, i.label
diff --git a/sources/datatable/datatable.kb.php b/sources/datatable/datatable.kb.php
index e02e4e51..99f20468 100644
--- a/sources/datatable/datatable.kb.php
+++ b/sources/datatable/datatable.kb.php
@@ -37,20 +37,21 @@ $sWhere = $sOrder = $sLimit = "";
 
 /* BUILD QUERY */
 //Paging
 $sLimit = "";
 if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
-    $sLimit = "LIMIT ". $_GET['iDisplayStart'] .", ". $_GET['iDisplayLength'] ;
+    $sLimit = "LIMIT ". mysql_real_escape_string($_GET['iDisplayStart']) .", "
+            . mysql_real_escape_string($_GET['iDisplayLength']) ;
 }
 
 //Ordering
 
 if (isset($_GET['iSortCol_0'])) {
     $sOrder = "ORDER BY  ";
     for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
         if ($_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true") {
-            $sOrder .= $aColumns[ intval($_GET['iSortCol_'.$i]) ]."
+            $sOrder .= $aColumns[ intval(mysql_real_escape_string($_GET['iSortCol_'.$i])) ]."
                     ".mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
         }
     }
 
     $sOrder = substr_replace($sOrder, "", -2);
@@ -131,11 +132,20 @@ foreach ($rows as $reccord) {
         $sOutput .= '<img src=\"includes/images/direction_minus.png\" onclick=\"deleteKB(\''.$reccord['id'].'\')\" style=\"cursor:pointer;\" />';
     }
     $sOutput .= '",';
 
     //col2
-    $ret_cat = $db->fetchRow("SELECT category FROM ".$pre."kb_categories WHERE id = ".$reccord['category_id']);
+    //$ret_cat = $db->fetchRow("SELECT category FROM ".$pre."kb_categories WHERE id = ".$reccord['category_id']);
+    $ret_cat = $db->queryGetRow(
+        "kb_categories",
+        array(
+            "category"
+        ),
+        array(
+            "id" => intval($reccord['category_id'])
+        )
+    );
     $sOutput .= '"'.htmlspecialchars(stripslashes($ret_cat[0]), ENT_QUOTES).'",';
 
     //col3
     $sOutput .= '"'.htmlspecialchars(stripslashes($reccord['label']), ENT_QUOTES).'",';
     /*
@@ -145,11 +155,20 @@ foreach ($rows as $reccord) {
     } else {
         $sOutput .= '"'.substr(trim(html_entity_decode(strip_tags(str_replace(array('\n'), array(''), $reccord['description'])), ENT_NOQUOTES, $k['charset'])), 0, 50).'",';
     }
     */
     //col5
-    $ret_author = $db->fetchRow("SELECT login FROM ".$pre."users WHERE id = ".$reccord['author_id']);
+    //$ret_author = $db->fetchRow("SELECT login FROM ".$pre."users WHERE id = ".$reccord['author_id']);
+    $ret_author = $db->queryGetRow(
+        "users",
+        array(
+            "login"
+        ),
+        array(
+            "id" => intval($reccord['author_id'])
+        )
+    );
     $sOutput .= '"'.html_entity_decode($ret_author[0], ENT_NOQUOTES).'"';
 
     //Finish the line
     $sOutput .= '],';
 
diff --git a/sources/datatable/datatable.logs.php b/sources/datatable/datatable.logs.php
index 10a56276..d434466c 100644
--- a/sources/datatable/datatable.logs.php
+++ b/sources/datatable/datatable.logs.php
@@ -39,20 +39,21 @@ if (isset($_GET['action']) && $_GET['action'] == "connections") {
 
     /* BUILD QUERY */
     //Paging
     $sLimit = "";
     if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
-        $sLimit = "LIMIT ". $_GET['iDisplayStart'] .", ". $_GET['iDisplayLength'] ;
+        $sLimit = "LIMIT ". mysql_real_escape_string($_GET['iDisplayStart']) .", "
+                . mysql_real_escape_string($_GET['iDisplayLength']) ;
     }
 
     //Ordering
 
     if (isset($_GET['iSortCol_0'])) {
         $sOrder = "ORDER BY  ";
         for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
             if ($_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true") {
-                $sOrder .= $aColumns[ intval($_GET['iSortCol_'.$i]) ]."
+                $sOrder .= $aColumns[ intval(mysql_real_escape_string($_GET['iSortCol_'.$i])) ]."
                     ".mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
             }
         }
 
         $sOrder = substr_replace($sOrder, "", -2);
diff --git a/sources/datatable/datatable.users_logged.php b/sources/datatable/datatable.users_logged.php
index 4ebb031d..1e9bac40 100644
--- a/sources/datatable/datatable.users_logged.php
+++ b/sources/datatable/datatable.users_logged.php
@@ -39,20 +39,21 @@ $sOrder = $sLimit = "";
 
 /* BUILD QUERY */
 //Paging
 $sLimit = "";
 if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
-    $sLimit = "LIMIT ". $_GET['iDisplayStart'] .", ". $_GET['iDisplayLength'] ;
+    $sLimit = "LIMIT ". mysql_real_escape_string($_GET['iDisplayStart']) .", "
+            . mysql_real_escape_string($_GET['iDisplayLength']);
 }
 
 //Ordering
 
 if (isset($_GET['iSortCol_0'])) {
     $sOrder = "ORDER BY  ";
     for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
         if ($_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true") {
-            $sOrder .= $aColumns[ intval($_GET['iSortCol_'.$i]) ]."
+            $sOrder .= $aColumns[ intval(mysql_real_escape_string($_GET['iSortCol_'.$i])) ]."
             ".mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
         }
     }
 
     $sOrder = substr_replace($sOrder, "", -2);
diff --git a/sources/export.queries.php b/sources/export.queries.php
index f9150e09..1d618ef6 100644
--- a/sources/export.queries.php
+++ b/sources/export.queries.php
@@ -470,11 +470,11 @@ Enter the decryption key : <input type="password" id="saltkey" />
 
 			$encPw = GibberishAES::enc($elem['pw'], $_POST['pdf_password']);
 			fputs($outstream, '
 		<tr class="'.$lineType.'">
 		    <td>'.addslashes($elem['label']).'</td>
-			<td align="center"><span class="span_pw" id="span_'.$elem['id'].'"><a href="#" onclick="decryptme('.$elem['id'].', \''.$encPw.'\')">Decrypt </a></span><input type="hidden" id="hide_'.$elem['id'].'" value="'.$encPw.'" /></td>
+			<td align="center"><span class="span_pw" id="span_'.$elem['id'].'"><a href="#" onclick="decryptme('.$elem['id'].', \''.$encPw.'\');return false;">Decrypt </a></span><input type="hidden" id="hide_'.$elem['id'].'" value="'.$encPw.'" /></td>
 		    <td>'.$desc.'</td>
 		    <td align="center">'.$login.'</td>
 		    <td align="center">'.$rest.'</td>
 		    </tr>'
 			);
diff --git a/sources/favourites.queries.php b/sources/favourites.queries.php
index af95937e..d28b0763 100644
--- a/sources/favourites.queries.php
+++ b/sources/favourites.queries.php
@@ -32,11 +32,20 @@ $db->connect();
 if (!empty($_POST['type'])) {
     switch ($_POST['type']) {
         #CASE adding a new function
         case "del_fav":
             //Get actual favourites
-            $data = $db->fetchRow("SELECT favourites FROM ".$pre."users WHERE id = '".$_SESSION['user_id']."'");
+            //$data = $db->fetchRow("SELECT favourites FROM ".$pre."users WHERE id = '".$_SESSION['user_id']."'");
+            $data = $db->queryGetRow(
+                "users",
+                array(
+                    "favourites"
+                ),
+                array(
+                    "id" => intval($_SESSION['user_id'])
+                )
+            );
             $tmp = explode(";", $data[0]);
             $favs = "";
             $tab_favs = array();
             //redefine new list of favourites
             foreach ($tmp as $f) {
diff --git a/sources/find.queries.php b/sources/find.queries.php
index 0adc26bc..2d84e626 100644
--- a/sources/find.queries.php
+++ b/sources/find.queries.php
@@ -36,58 +36,70 @@ $aColumns = array('id', 'label', 'description', 'tags', 'id_tree', 'folder', 'lo
 //init SQL variables
 $sOrder = $sLimit = "";
 $sWhere = "id_tree IN(".implode(', ', $_SESSION['groupes_visibles']).")";    //limit search to the visible folders
 
 //Get current user "personal folder" ID
-$row = $db->fetchRow("SELECT id FROM ".$pre."nested_tree WHERE title = ".$_SESSION['user_id']);
+// $row = $db->fetchRow("SELECT id FROM ".$pre."nested_tree WHERE title = '".intval($_SESSION['user_id'])."'");
+$row = $db->queryGetRow(
+    "nested_tree",
+    array(
+        "id"
+    ),
+    array(
+        "title" => intval($_SESSION['user_id'])
+    )
+);
 
 //get list of personal folders
 $arrayPf = array();
 $listPf = "";
-$rows = $db->fetchAllArray(
-    "SELECT id FROM ".$pre."nested_tree WHERE personal_folder=1 AND NOT parent_id = ".$row[0].
-    " AND NOT title = ".$_SESSION['user_id']
-);
-foreach ($rows as $reccord) {
-    if (!in_array($reccord['id'], $arrayPf)) {
-        //build an array of personal folders ids
-        array_push($arrayPf, $reccord['id']);
-        //build also a string with those ids
-        if (empty($listPf)) {
-            $listPf = $reccord['id'];
-        } else {
-            $listPf .= ', '.$reccord['id'];
-        }
-    }
+if (empty($row[0])) {
+	$rows = $db->fetchAllArray(
+	    "SELECT id FROM ".$pre."nested_tree WHERE personal_folder=1 AND NOT parent_id = '".intval($row[0]).
+	    "' AND NOT title = '".intval($_SESSION['user_id'])."'"
+	);
+	foreach ($rows as $reccord) {
+		if (!in_array($reccord['id'], $arrayPf)) {
+			//build an array of personal folders ids
+			array_push($arrayPf, $reccord['id']);
+			//build also a string with those ids
+			if (empty($listPf)) {
+				$listPf = $reccord['id'];
+			} else {
+				$listPf .= ', '.$reccord['id'];
+			}
+		}
+	}
 }
 
+
 /* BUILD QUERY */
 //Paging
 $sLimit = "";
 if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
-    $sLimit = "LIMIT ". intval($_GET['iDisplayStart']) .", ". intval($_GET['iDisplayLength']);
+    $sLimit = "LIMIT ". intval($_GET['iDisplayStart']) .", ". intval($_GET['iDisplayLength'])."";
 }
 
 //Ordering
 if (isset($_GET['iSortCol_0'])) {
     $sOrder = "ORDER BY  ";
     for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
         if (
             $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" &&
             preg_match("#^(asc|desc)\$#i", $_GET['sSortDir_'.$i])
         ) {
-            $sOrder .= $aColumns[ intval($_GET['iSortCol_'.$i]) ]."
-            ".$_GET['sSortDir_'.$i] .", ";
+            $sOrder .= "".$aColumns[ intval($_GET['iSortCol_'.$i]) ]." "
+            .mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
         }
     }
 
     $sOrder = substr_replace($sOrder, "", -2);
     if ($sOrder == "ORDER BY") {
             $sOrder = "";
     }
 }
-
+//echo $sOrder;
 /*
  * Filtering
  * NOTE this does not match the built-in DataTables filtering which does it
  * word by word on any field. It's possible to do here, but concerned about efficiency
  * on very large tables, and MySQL's regex functionality is very limited
@@ -162,11 +174,11 @@ foreach ($rows as $reccord) {
 
     //col4
     //get restriction from ROles
     $restrictedToRole = false;
     $rTmp = mysql_query(
-        "SELECT role_id FROM ".$pre."restriction_to_roles WHERE item_id = ".$reccord['id']
+        "SELECT role_id FROM ".$pre."restriction_to_roles WHERE item_id = '".$reccord['id']."'"
     ) or die(mysql_error());
     while ($aTmp = mysql_fetch_row($rTmp)) {
         if ($aTmp[0] != "") {
             if (!in_array($aTmp[0], $_SESSION['user_roles'])) {
                 $restrictedToRole = true;
diff --git a/sources/folders.queries.php b/sources/folders.queries.php
index 0726880c..faaf2fff 100644
--- a/sources/folders.queries.php
+++ b/sources/folders.queries.php
@@ -12,14 +12,26 @@
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
 
 require_once('sessions.php');
 session_start();
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || !isset($_SESSION['key']) || empty($_SESSION['key'])) {
+if (
+    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
+    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
+    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
+{
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_folders")) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    include 'error.php';
+    exit();
+}
+
 include $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
 include $_SESSION['settings']['cpassman_dir'].'/includes/settings.php';
 header("Content-type: text/html; charset==utf-8");
 include 'main.functions.php';
 require_once $_SESSION['settings']['cpassman_dir'].'/sources/SplClassLoader.php';
@@ -84,11 +96,20 @@ if (isset($_POST['newtitle'])) {
             'parent_id' => $_POST['newparent_id']
        ),
         "id=".$id[1]
     );
     //Get the title to display it
-    $data = $db->fetchRow("SELECT title FROM ".$pre."nested_tree WHERE id = ".$_POST['newparent_id']);
+    // $data = $db->fetchRow("SELECT title FROM ".$pre."nested_tree WHERE id = ".$_POST['newparent_id']);
+    $row = $db->queryGetRow(
+        "nested_tree",
+        array(
+            "title"
+        ),
+        array(
+            "id" => $_POST['newparent_id']
+        )
+    );
     //show value
     echo ($data[0]);
     //rebuild the tree grid
     $tree = new Tree\NestedTree\NestedTree($pre.'nested_tree', 'id', 'parent_id', 'title');
     $tree->rebuild();
@@ -96,11 +117,18 @@ if (isset($_POST['newtitle'])) {
     // CASE where complexity is changed
 } elseif (isset($_POST['changer_complexite'])) {
     $id = explode('_', $_POST['id']);
 
     //Check if group exists
-    $tmp = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."misc WHERE type = 'complex' AND intitule = '".$id[1]."'");
+    //$tmp = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."misc WHERE type = 'complex' AND intitule = '".$id[1]."'");
+    $tmp = $db->queryCount(
+        "misc",
+        array(
+            "intitule" => $id[1],
+            "type" => "complex"
+        )
+    );
     if ($tmp[0] == 0) {
         //Insert into DB
         $db->queryInsert(
             'misc',
             array(
@@ -208,22 +236,37 @@ if (isset($_POST['newtitle'])) {
             }
 
             //Check if duplicate folders name are allowed
             $createNewFolder = true;
             if (isset($_SESSION['settings']['duplicate_folder']) && $_SESSION['settings']['duplicate_folder'] == 0) {
-                $data = $db->fetchRow(
-                    "SELECT COUNT(*) FROM ".$pre."nested_tree WHERE title = '".addslashes($title)."'"
+                //$data = $db->fetchRow(
+                //    "SELECT COUNT(*) FROM ".$pre."nested_tree WHERE title = '".addslashes($title)."'"
+                //);
+                $data = $db->queryCount(
+                    "nested_tree",
+                    array(
+                        "title" => addslashes($title)
+                    )
                 );
                 if ($data[0] != 0) {
                     $error = 'error_group_exist';
                     $createNewFolder = false;
                 }
             }
 
             if ($createNewFolder == true) {
                 //check if parent folder is personal
-                $data = $db->fetchRow("SELECT personal_folder FROM ".$pre."nested_tree WHERE id = '".$parentId."'");
+                // $data = $db->fetchRow("SELECT personal_folder FROM ".$pre."nested_tree WHERE id = '".$parentId."'");
+                $row = $db->queryGetRow(
+                    "nested_tree",
+                    array(
+                        "personal_folder"
+                    ),
+                    array(
+                        "id" => intval($parentId)
+                    )
+                );
                 if ($data[0] == 1) {
                     $isPersonal = 1;
                 } else {
                     $isPersonal = 0;
                 }
@@ -317,12 +360,22 @@ if (isset($_POST['newtitle'])) {
             }
 
             //Check if duplicate folders name are allowed
             $createNewFolder = true;
             if (isset($_SESSION['settings']['duplicate_folder']) && $_SESSION['settings']['duplicate_folder'] == 0) {
-                $data = $db->fetchRow(
+                /*$data = $db->fetchRow(
                     "SELECT id, title FROM ".$pre."nested_tree WHERE title = '".addslashes($title)."'"
+                );*/
+                $data = $db->queryGetRow(
+                    "nested_tree",
+                    array(
+                        "id",
+                        "title"
+                    ),
+                    array(
+                        "title" => addslashes($title)
+                    )
                 );
                 if (!empty($data[0]) && $dataReceived['id'] != $data[0] && $title != $data[1] ) {
                     echo '[ { "error" : "error_group_exist" } ]';
                     break;
                 }
@@ -365,11 +418,21 @@ if (isset($_POST['newtitle'])) {
         //CASE where to update the associated Function
         case "fonction":
             $val = explode(';', $_POST['valeur']);
             $valeur = $_POST['valeur'];
             //Check if ID already exists
-            $data = $db->fetchRow("SELECT authorized FROM ".$pre."rights WHERE tree_id = '".$val[0]."' AND fonction_id= '".$val[1]."'");
+            // $data = $db->fetchRow("SELECT authorized FROM ".$pre."rights WHERE tree_id = '".$val[0]."' AND fonction_id= '".$val[1]."'");
+            $data = $db->queryGetRow(
+                "rights",
+                array(
+                    "authorized"
+                ),
+                array(
+                    "tree_id" => intval($val[0]),
+                    "fonction_id" => intval($val[1])
+                )
+            );
             if (empty($data[0])) {
                 //Insert into DB
                 $db->queryInsert(
                     'rights',
                     array(
diff --git a/sources/import.queries.php b/sources/import.queries.php
index d391bbb5..0c82a0d7 100644
--- a/sources/import.queries.php
+++ b/sources/import.queries.php
@@ -171,11 +171,20 @@ switch ($_POST['type']) {
         if ($_POST['folder'] == $_SESSION['user_id']) {
             $personalFolder = 1;
         } else {
             $personalFolder = 0;
         }
-        $data_fld = $db->fetchRow("SELECT title FROM ".$pre."nested_tree WHERE id = '".$_POST['folder']."'");
+        // $data_fld = $db->fetchRow("SELECT title FROM ".$pre."nested_tree WHERE id = '".$_POST['folder']."'");
+        $data_fld = $db->queryGetRow(
+            "nested_tree",
+            array(
+                "title"
+            ),
+            array(
+                "id" => intval($_POST['folder'])
+            )
+        );
 
         //Prepare variables
         $listItems = htmlspecialchars_decode($dataReceived);
         $list = "";
 
@@ -611,11 +620,19 @@ switch ($_POST['type']) {
                         $fold = $folder;
                         $parent_id = $_POST['destination']; //permits to select the folder destination
                     }
 
                     //create folder - if not exists at the same level
-                    $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."nested_tree WHERE nlevel = ".($folderLevel+$startPathLevel)." AND title = \"".$fold."\" AND parent_id = ".$parent_id);
+                    //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."nested_tree WHERE nlevel = ".($folderLevel+$startPathLevel)." AND title = \"".$fold."\" AND parent_id = ".$parent_id);
+                    $data = $db->queryCount(
+                        "nested_tree",
+                        array(
+                            "nlevel" => intval($folderLevel+$startPathLevel),
+                            "title" => $fold,
+                            "parent_id" => intval(parent_id)
+                        )
+                    );
                     if ($data[0] == 0) {
                         //do query
                         $id = $db->queryInsert(
                             "nested_tree",
                             array(
@@ -652,11 +669,22 @@ switch ($_POST['type']) {
                         $text .= '- '.(($fold)).'<br />';
                         //increment number of imported folders
                         $nbFoldersImported++;
                     } else {
                         //get forlder actual ID
-                        $data = $db->fetchRow("SELECT id FROM ".$pre."nested_tree WHERE nlevel = '".($folderLevel+$startPathLevel)."' AND title = '".$fold."' AND parent_id = '".$parent_id."'");
+                        // $data = $db->fetchRow("SELECT id FROM ".$pre."nested_tree WHERE nlevel = '".($folderLevel+$startPathLevel)."' AND title = '".$fold."' AND parent_id = '".$parent_id."'");
+                        $row = $db->queryGetRow(
+                            "nested_tree",
+                            array(
+                                "id"
+                            ),
+                            array(
+                                "nlevel" => intval($folderLevel+$startPathLevel),
+                                "title" => $fold,
+                                "parent_id" => intval($parent_id)
+                            )
+                        );
                         $id = $data[0];
                     }
 
                     //store in array
                     $foldersArray[$fold] = array(
@@ -703,12 +731,18 @@ switch ($_POST['type']) {
                 $item = fgets($cacheFile, 4096);
                 $item = explode($itemsSeparator, str_replace(array("\r\n", "\n", "\r"), '', $item));
 
                 if (!empty($item[2])) {
                     //check if not exists
-                    $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."items WHERE id_tree = '".$foldersArray[$item[1]]['id']."' AND label = \"".$item[2]."\"");
-
+                    //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."items WHERE id_tree = '".$foldersArray[$item[1]]['id']."' AND label = \"".$item[2]."\"");
+                    $data = $db->queryCount(
+                        "items",
+                        array(
+                            "id_tree" => intval($foldersArray[$item[1]]['id']),
+                            "label" => $item[2]
+                        )
+                    );
                     if ($data[0] == 0) {
                         //Encryption key
                         $randomKey = generateKey();
                         $pw = $randomKey.$item[3];
 
@@ -765,11 +799,20 @@ switch ($_POST['type']) {
                         if (count($foldersArray)==0) {
                             $folderId = $_POST['destination'];
                         } else {
                             $folderId = $foldersArray[$item[1]]['id'];
                         }
-                        $data = $db->fetchRow("SELECT title FROM ".$pre."nested_tree WHERE id = '".$folderId."'");
+                        // $data = $db->fetchRow("SELECT title FROM ".$pre."nested_tree WHERE id = '".$folderId."'");
+                        $data = $db->queryGetRow(
+                            "nested_tree",
+                            array(
+                                "title"
+                            ),
+                            array(
+                                "id" => intval($folderId)
+                            )
+                        );
 
                         //Add entry to cache table
                         $db->queryInsert(
                             'cache',
                             array(
diff --git a/sources/items.queries.php b/sources/items.queries.php
index cd84d30d..23aeb299 100644
--- a/sources/items.queries.php
+++ b/sources/items.queries.php
@@ -16,10 +16,18 @@ require_once('sessions.php');
 session_start();
 if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || !isset($_SESSION['key']) || empty($_SESSION['key'])) {
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "home")) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    //include 'error.php';
+    exit();
+}
+
 /**
  * Define Timezone
  */
 if (isset($_SESSION['settings']['timezone'])) {
     date_default_timezone_set($_SESSION['settings']['timezone']);
@@ -100,11 +108,18 @@ if (isset($_POST['type'])) {
                     break;
                 }
                 // ;check if element doesn't already exist
                 $itemExists = 0;
                 $newID = "";
-                $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."items WHERE label = '".addslashes($label)."' AND inactif=0");
+                //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."items WHERE label = '".addslashes($label)."' AND inactif=0");
+                $data = $db->queryCount(
+                    "items",
+                    array(
+                        "label" => addslashes($label),
+                        "inactif" => "0"
+                    )
+                );
                 if ($data[0] != 0) {
                     $itemExists = 1;
                 } else {
                     $itemExists = 0;
                 }
@@ -489,12 +504,12 @@ if (isset($_POST['type'])) {
                             if (count($field_data)>1 && !empty($field_data[1])) {
                                 $dataTmp = $db->fetchRow(
                                     "SELECT c.title AS title, i.data AS data
                                     FROM ".$pre."categories_items AS i
                                     INNER JOIN ".$pre."categories AS c ON (i.field_id=c.id)
-                                    WHERE i.field_id = '".$field_data[0]."'
-                                    AND i.item_id=".$dataReceived['id']
+                                    WHERE i.field_id = '".intval($field_data[0])."'
+                                    AND i.item_id=".intval($dataReceived['id'])
                                 );
                                 // store Field text in DB
                                 if (count($dataTmp[0]) == 0) {
                                     // generate Key for fields
                                     $randomKeyFields = generateKey();
@@ -565,11 +580,17 @@ if (isset($_POST['type'])) {
                     }
 
                     // Update automatic deletion - Only by the creator of the Item
                     if (isset($_SESSION['settings']['enable_delete_after_consultation']) && $_SESSION['settings']['enable_delete_after_consultation'] == 1) {
                         // check if elem exists in Table. If not add it or update it.
-                        $dataTmp = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."automatic_del WHERE item_id = '".$dataReceived['id']."'");
+                        //$dataTmp = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."automatic_del WHERE item_id = '".$dataReceived['id']."'");
+                        $dataTmp = $db->queryCount(
+                            "automatic_del",
+                            array(
+                                "item_id" => $dataReceived['id']
+                            )
+                        );
                         if ($dataTmp[0] == 0) {
                             // No automatic deletion for this item
                             if (!empty($dataReceived['to_be_deleted']) || ($dataReceived['to_be_deleted'] > 0 && is_numeric($dataReceived['to_be_deleted']))) {
                                 // Automatic deletion to be added
                                 $db->queryInsert(
@@ -1022,12 +1043,26 @@ if (isset($_POST['type'])) {
         case "show_details_item":
             $arrData = array();
             // return ID
             $arrData['id'] = $_POST['id'];
             // Check if item is deleted
-            $dataDeleted = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."log_items WHERE id_item = '".$_POST['id']."' AND action = 'at_delete'");
-            $dataRestored = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."log_items WHERE id_item = '".$_POST['id']."' AND action = 'at_restored'");
+            //$dataDeleted = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."log_items WHERE id_item = '".$_POST['id']."' AND action = 'at_delete'");
+            //$dataRestored = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."log_items WHERE id_item = '".$_POST['id']."' AND action = 'at_restored'");
+            $dataDeleted = $db->queryCount(
+                "log_items",
+                array(
+                    "id_item" => $_POST['id'],
+                     "action" => "at_delete"
+                )
+            );
+            $dataRestored = $db->queryCount(
+                "log_items",
+                array(
+                    "id_item" => $_POST['id'],
+                     "action" => "at_restored"
+                )
+            );
             if ($dataDeleted[0] != 0 && $dataDeleted[0] > $dataRestored[0]) {
                 // This item is deleted => exit
                 echo prepareExchangedData(array('show_detail_option' => 2), "encode");
                 break;
             }
@@ -1382,11 +1417,11 @@ if (isset($_POST['type'])) {
         	   * Display History of the selected Item
         	*/
         case "showDetailsStep2":
         	// get Item info
         	$dataItem = $db->queryFirst(
-        	"SELECT *
+        	    "SELECT *
                 FROM ".$pre."items
                 WHERE id=".$_POST['id']
         	);
 
         	// get Item Key for decryption
@@ -1526,38 +1561,10 @@ if (isset($_POST['type'])) {
 	        	),
 	        	"encode"
         	);
         	break;
 
-            /*
-        * CASE
-        * Generate a password
-        */
-        case "pw_generate":
-            $pwgen = new SplClassLoader('Encryption\PwGen', '../includes/libraries');
-            $pwgen->register();
-            $pwgen = new Encryption\PwGen\pwgen();
-            // Set pw size
-            $pwgen->setLength($_POST['size']);
-            // Include at least one number in the password
-            $pwgen->setNumerals(($_POST['num'] == "true")? true : false);
-            // Include at least one capital letter in the password
-            $pwgen->setCapitalize(($_POST['maj'] == "true")? true : false);
-            // Include at least one symbol in the password
-            $pwgen->setSymbols(($_POST['symb'] == "true")? true : false);
-            // Complete random, hard to memorize password
-            if (isset($_POST['secure']) && $_POST['secure'] == "true") {
-                $pwgen->setSecure(true);
-                $pwgen->setSymbols(true);
-                $pwgen->setCapitalize(true);
-                $pwgen->setNumerals(true);
-            } else {
-                $pwgen->setSecure(false);
-            }
-            echo prepareExchangedData(array("key" => $pwgen->generate()), "encode");
-            break;
-
         /*
          * CASE
          * Delete an item
         */
         case "del_item":
@@ -1608,19 +1615,40 @@ if (isset($_POST['type'])) {
                 break;
             }
             // Check if duplicate folders name are allowed
             $createNewFolder = true;
             if (isset($_SESSION['settings']['duplicate_folder']) && $_SESSION['settings']['duplicate_folder'] == 0) {
-                $data = $db->fetchRow("SELECT id, title FROM ".$pre."nested_tree WHERE title = '".addslashes($title)."'");
+                // $data = $db->fetchRow("SELECT id, title FROM ".$pre."nested_tree WHERE title = '".addslashes($title)."'");
+                $data = $db->queryGetRow(
+                    "nested_tree",
+                    array(
+                        "title",
+                        "id"
+                    ),
+                    array(
+                        "title" => addslashes($title)
+                    )
+                );
                 if (!empty($data[0]) && $dataReceived['folder'] != $data[0]) {
                     echo '[ { "error" : "'.addslashes($txt['error_group_exist']).'" } ]';
                     break;
                 }
             }
             // update Folders table
-            $tmp = $db->fetchRow(
+            /*$tmp = $db->fetchRow(
                 "SELECT title, parent_id, personal_folder FROM ".$pre."nested_tree WHERE id = ".$dataReceived['folder']
+            );*/
+            $tmp = $db->queryGetRow(
+                "nested_tree",
+                array(
+                    "title",
+                    "parent_id",
+                    "personal_folder"
+                ),
+                array(
+                    "id" => intval($dataReceived['folder'])
+                )
             );
             if ( $tmp[1] != 0 || $tmp[0] != $_SESSION['user_id'] || $tmp[2] != 1 ) {
                 $db->queryUpdate(
                     "nested_tree",
                     array(
@@ -1722,12 +1750,18 @@ if (isset($_POST['type'])) {
                 array_merge($_SESSION['groupes_visibles'], @array_keys($_SESSION['list_restricted_folders_for_items']))
             )) {
             	echo prepareExchangedData(array("error" => "not_authorized"), "encode");
                 break;
             } else {
-                $data_count = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."items WHERE inactif = 0");
-                $whereArg = " AND i.id_tree=".$_POST['id'];
+                //$data_count = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."items WHERE inactif = 0");
+                $data_count = $db->queryCount(
+                    "items",
+                    array(
+                        "inactif" => "0"
+                    )
+                );
+                $whereArg = " AND i.id_tree=".intval($_POST['id']);
             }
 
             if ($data_count[0] > 0 && empty($showError)) {
                 // init variables
                 $init_personal_folder = false;
@@ -2104,20 +2138,40 @@ if (isset($_POST['type'])) {
         * Get complexity level of a group
         */
         case "recup_complex":
             if (isset($_POST['item_id']) && !empty($_POST['item_id'])) {
                 // Lock Item (if already locked), go back and warn
-                $dataTmp = $db->fetchRow("SELECT timestamp, user_id FROM ".$pre."items_edition WHERE item_id = '".$_POST['item_id']."'");//echo ">".$dataTmp[0];
+                // $dataTmp = $db->fetchRow("SELECT timestamp, user_id FROM ".$pre."items_edition WHERE item_id = '".$_POST['item_id']."'");//echo ">".$dataTmp[0];
+                $dataTmp = $db->queryGetRow(
+                    "items_edition",
+                    array(
+                        "timestamp",
+                        "user_id"
+                    ),
+                    array(
+                        "item_id" => intval($_POST['item_id'])
+                    )
+                );
 
                 // If token is taken for this Item and delay is passed then delete it.
                 if (isset($_SESSION['settings']['delay_item_edition']) &&
                     $_SESSION['settings']['delay_item_edition'] > 0 && !empty($dataTmp[0]) &&
                     round(abs(time()-$dataTmp[0]) / 60, 2) > $_SESSION['settings']['delay_item_edition']
                 ) {
                     $db->query("DELETE FROM ".$pre."items_edition WHERE item_id = '".$_POST['item_id']."'");
                     //reload the previous data
-                    $dataTmp = $db->fetchRow("SELECT timestamp, user_id FROM ".$pre."items_edition WHERE item_id = '".$_POST['item_id']."'");
+                    // $dataTmp = $db->fetchRow("SELECT timestamp, user_id FROM ".$pre."items_edition WHERE item_id = '".$_POST['item_id']."'");
+                    $dataTmp = $db->queryGetRow(
+                        "items_edition",
+                        array(
+                            "timestamp",
+                            "user_id"
+                        ),
+                        array(
+                            "item_id" => intval($_POST['item_id'])
+                        )
+                    );
                 }
 
                 // If edition by same user (and token not freed before for any reason, then update timestamp)
                 if (!empty($dataTmp[0]) && $dataTmp[1] == $_SESSION['user_id']) {
                     $db->query("UPDATE ".$pre."items_edition SET timestamp = '".time()."' WHERE user_id = '".$_SESSION['user_id']."' AND item_id = '".$_POST['item_id']."'");
@@ -2141,11 +2195,21 @@ if (isset($_POST['type'])) {
                     break;
                 }
             }
 
             // Get required Complexity for this Folder
-            $data = $db->fetchRow("SELECT valeur FROM ".$pre."misc WHERE type='complex' AND intitule = '".$_POST['groupe']."'");
+            // $data = $db->fetchRow("SELECT valeur FROM ".$pre."misc WHERE type='complex' AND intitule = '".$_POST['groupe']."'");
+            $data = $db->queryGetRow(
+                "misc",
+                array(
+                    "valeur"
+                ),
+                array(
+                    "intitule" => $_POST['groupe'],
+                    "type" => "complex"
+                )
+            );
 
             if (isset($data[0]) && (!empty($data[0]) || $data[0] == 0)) {
                 $complexity = $pwComplexity[$data[0]][1];
             } else {
                 $complexity = $txt['not_defined'];
@@ -2209,11 +2273,22 @@ if (isset($_POST['type'])) {
         * CASE
         * DELETE attached file from an item
         */
         case "delete_attached_file":
             // Get some info before deleting
-            $data = $db->fetchRow("SELECT name,id_item,file FROM ".$pre."files WHERE id = '".$_POST['file_id']."'");
+            // $data = $db->fetchRow("SELECT name,id_item,file FROM ".$pre."files WHERE id = '".$_POST['file_id']."'");
+            $data = $db->queryGetRow(
+                "files",
+                array(
+                    "name",
+                    "id_item",
+                    "file"
+                ),
+                array(
+                    "id" => intval($_POST['file_id'])
+                )
+            );
             if (!empty($data[1])) {
                 // Delete from FILES table
                 $db->query("DELETE FROM ".$pre."files WHERE id = '".$_POST['file_id']."'");
                 // Update the log
                 $db->queryInsert(
@@ -2580,11 +2655,22 @@ if (isset($_POST['type'])) {
         /*
         * CASE
         * Check if Item has been changed since loaded
         */
         case "is_item_changed":
-            $data = $db->fetchRow("SELECT date FROM ".$pre."log_items WHERE action = 'at_modification' AND id_item = '".$_POST['item_id']."' ORDER BY date DESC");
+            // $data = $db->fetchRow("SELECT date FROM ".$pre."log_items WHERE action = 'at_modification' AND id_item = '".$_POST['item_id']."' ORDER BY date DESC");
+            $data = $db->queryGetRow(
+                "log_items",
+                array(
+                    "date"
+                ),
+                array(
+                    "action" => "at_modification",
+                    "id_item" => intval($_POST['item_id'])
+                ),
+                " ORDER BY date DESC"
+            );
             // Check if it's in a personal folder. If yes, then force complexity overhead.
             if ($data[0] > $_POST['timestamp']) {
                 echo '{ "modified" : "1" }';
             } else {
                 echo '{ "modified" : "0" }';
@@ -2621,11 +2707,22 @@ if (isset($_GET['type'])) {
 * Identify if this group authorize creation of item without the complexit level reached
 */
 function recupDroitCreationSansComplexite($groupe)
 {
     global $db, $pre;
-    $data = $db->fetchRow("SELECT bloquer_creation,bloquer_modification,personal_folder FROM ".$pre."nested_tree WHERE id = '".$groupe."'");
+    // $data = $db->fetchRow("SELECT bloquer_creation,bloquer_modification,personal_folder FROM ".$pre."nested_tree WHERE id = '".$groupe."'");
+    $data = $db->queryGetRow(
+        "nested_tree",
+        array(
+            "bloquer_creation",
+            "bloquer_modification",
+            "personal_folder"
+        ),
+        array(
+            "id" => intval($groupe)
+        )
+    );
     // Check if it's in a personal folder. If yes, then force complexity overhead.
     if ($data[2] == 1) {
         return array("bloquer_modification_complexite" => 1, "bloquer_creation_complexite" => 1);
     } else {
         return array("bloquer_modification_complexite" => $data[1], "bloquer_creation_complexite" => $data[0]);
diff --git a/sources/kb.queries.php b/sources/kb.queries.php
index a954a5c3..8209faaf 100644
--- a/sources/kb.queries.php
+++ b/sources/kb.queries.php
@@ -13,16 +13,27 @@
  */
 
 require_once('sessions.php');
 session_start();
 if (
-        !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || !isset($_SESSION['key']) || empty($_SESSION['key'])
-        || !isset($_SESSION['settings']['enable_kb']) || $_SESSION['settings']['enable_kb'] != 1
-) {
+        !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 ||
+        !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) ||
+        !isset($_SESSION['key']) || empty($_SESSION['key'])
+        || !isset($_SESSION['settings']['enable_kb'])
+        || $_SESSION['settings']['enable_kb'] != 1)
+{
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "kb")) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    include 'error.php';
+    exit();
+}
+
 require_once $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
 include $_SESSION['settings']['cpassman_dir'].'/includes/settings.php';
 require_once $_SESSION['settings']['cpassman_dir'].'/includes/include.php';
 require_once $_SESSION['settings']['cpassman_dir'].'/sources/SplClassLoader.php';
 header("Content-type: text/html; charset=utf-8");
@@ -67,23 +78,37 @@ if (!empty($_POST['type'])) {
             $kb_associated_to = htmlspecialchars_decode($data_received['kb_associated_to']);
             $description = htmlspecialchars_decode($data_received['description']);
 
             //check if allowed to modify
             if (isset($id) && !empty($id)) {
-                $row = $db->query("SELECT anyone_can_modify, author_id FROM ".$pre."kb WHERE id = ".$id);
-                $ret = $db->fetchArray($row);
+                $ret = $db->queryGetArray(
+                    "kb",
+                    array(
+                        "anyone_can_modify",
+                        "author_id"
+                    ),
+                    array(
+                        "id" => intval($id)
+                    )
+                );
                 if ($ret['anyone_can_modify'] == 1 || $ret['author_id'] == $_SESSION['user_id']) {
                     $manage_kb = true;
                 } else {
                     $manage_kb = false;
                 }
             } else {
                 $manage_kb = true;
             }
             if ($manage_kb == true) {
                 //Add category if new
-                $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."kb_categories WHERE category = '".mysql_real_escape_string($category)."'");
+                //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."kb_categories WHERE category = '".mysql_real_escape_string($category)."'");
+                $data = $db->queryCount(
+                    "kb_categories",
+                    array(
+                        "category" => $category
+                    )
+                );
                 if ($data[0] == 0) {
                     $cat_id = $db->queryInsert(
                         "kb_categories",
                         array(
                             'category' => mysql_real_escape_string($category)
@@ -153,19 +178,33 @@ if (!empty($_POST['type'])) {
             // Check KEY
             if ($_POST['key'] != $_SESSION['key']) {
                 echo '[ { "error" : "key_not_conform" } ]';
                 break;
             }
-            $row = $db->query(
-                "SELECT k.id as id, k.label as label, k.description as description, k.category_id as category_id, k.author_id as author_id, k.anyone_can_modify as anyone_can_modify,
-                u.login as login, c.category as category
-                FROM ".$pre."kb as k
-                INNER JOIN ".$pre."kb_categories as c ON (c.id = k.category_id)
-                INNER JOIN ".$pre."users as u ON (u.id = k.author_id)
-                WHERE k.id = '".$_POST['id']."'"
+            $ret = $db->queryGetArray(
+                array(
+                    "kb" => "k"
+                ),
+                array(
+                    "k.id" => "id",
+                    "k.label" => "label",
+                    "k.description" => "description",
+                    "k.category_id" => "category_id",
+                    "k.author_id" => "author_id",
+                    "k.anyone_can_modify" => "anyone_can_modify",
+                    "u.login" => "login",
+                    "c.category" => "category"
+                ),
+                array(
+                    "k.id" => intval($_POST['id'])
+                ),
+                "",
+                array(
+                    "kb_categories AS c" => "(c.id = k.category_id)",
+                    "users AS u" => "(u.id = k.author_id)"
+                )
             );
-            $ret = $db->fetchArray($row);
 
             //select associated items
             $rows = $db->fetchAllArray(
                 "SELECT item_id
                 FROM ".$pre."kb_items
diff --git a/sources/logs.queries.php b/sources/logs.queries.php
index 18cd6d7b..f3cee1bc 100644
--- a/sources/logs.queries.php
+++ b/sources/logs.queries.php
@@ -12,14 +12,26 @@
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
 
 require_once('sessions.php');
 session_start();
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || !isset($_SESSION['key']) || empty($_SESSION['key'])) {
+if (
+    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
+    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
+    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
+{
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_views")) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    include 'error.php';
+    exit();
+}
+
 global $k, $settings;
 include $_SESSION['settings']['cpassman_dir'].'/includes/settings.php';
 header("Content-type: text/html; charset==utf-8");
 
 //Connect to DB
diff --git a/sources/main.functions.php b/sources/main.functions.php
index d4de7d52..023da4b1 100644
--- a/sources/main.functions.php
+++ b/sources/main.functions.php
@@ -10,10 +10,11 @@
  */
 // session_start();
 if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
     die('Hacking attempt...');
 }
+
 //define pbkdf2 iteration count
 @define('ITCOUNT', '2072');
 
 //Generate N# of random bits for use as salt
 function getBits($n)
@@ -297,11 +298,20 @@ function identifyUserRights($groupesVisiblesUser, $groupesInterditsUser, $isAdmi
         $sql = "SELECT id FROM ".$pre."nested_tree WHERE personal_folder = 1";
         if (isset($_SESSION['settings']['enable_pf_feature']) && $_SESSION['settings']['enable_pf_feature'] == 1) {
             $sql .= " AND title != '".$_SESSION['user_id']."'";
         }
         // Get ID of personal folder
-        $pf = $db->fetchRow("SELECT id FROM ".$pre."nested_tree WHERE title = '".$_SESSION['user_id']."'");
+        // $pf = $db->fetchRow("SELECT id FROM ".$pre."nested_tree WHERE title = '".$_SESSION['user_id']."'");
+        $pf = $db->queryGetRow(
+            "nested_tree",
+            array(
+                "id"
+            ),
+            array(
+                "title" => $_SESSION['user_id']
+            )
+        );
         if (!empty($pf[0])) {
             if (!in_array($pf[0], $_SESSION['groupes_visibles'])) {
                 array_push($_SESSION['groupes_visibles'], $pf[0]);
                 array_push($_SESSION['personal_visible_groups'], $pf[0]);
                 // get all descendants
@@ -431,11 +441,20 @@ function identifyUserRights($groupesVisiblesUser, $groupesInterditsUser, $isAdmi
             isset($_SESSION['settings']['enable_pf_feature']) &&
             $_SESSION['settings']['enable_pf_feature'] == 1 &&
             isset($_SESSION['personal_folder']) &&
             $_SESSION['personal_folder'] == 1
         ) {
-            $pf = $db->fetchRow("SELECT id FROM ".$pre."nested_tree WHERE title = '".$_SESSION['user_id']."'");
+        // $pf = $db->fetchRow("SELECT id FROM ".$pre."nested_tree WHERE title = '".$_SESSION['user_id']."'");
+        $pf = $db->queryGetRow(
+            "nested_tree",
+            array(
+                "id"
+            ),
+            array(
+                "title" => intval($_SESSION['user_id'])
+            )
+        );
             if (!empty($pf[0])) {
                 if (!in_array($pf[0], $listAllowedFolders)) {
                     // get all descendants
                     $ids = $tree->getDescendants($pf[0], true);
                     foreach ($ids as $id) {
@@ -558,18 +577,32 @@ function updateCacheTable($action, $id = "")
             );
         }
         // UPDATE an item
     } elseif ($action == "update_value") {
         // get new value from db
-        $sql = "SELECT label, description, id_tree, perso, restricted_to, login
+        /*$sql = "SELECT label, description, id_tree, perso, restricted_to, login
                 FROM ".$pre."items
                 WHERE id=".$id;
         $row = $db->query($sql);
-        $data = $db->fetchArray($row);
+        $data = $db->fetchArray($row);*/
+        $ret = $db->queryGetArray(
+            "items",
+            array(
+                "label",
+                "description",
+                "id_tree",
+                "perso",
+                "restricted_to",
+                "login"
+            ),
+            array(
+                "id" => intval($id)
+            )
+        );
         // Get all TAGS
         $tags = "";
-        $itemTags = $db->fetchAllArray("SELECT tag FROM ".$pre."tags WHERE item_id=".$id);
+        $itemTags = $db->fetchAllArray("SELECT tag FROM ".$pre."tags WHERE item_id=".intval($id));
         foreach ($itemTags as $itemTag) {
             if (!empty($itemTag['tag'])) {
                 $tags .= $itemTag['tag']." ";
             }
         }
@@ -598,22 +631,44 @@ function updateCacheTable($action, $id = "")
                 'restricted_to' => $data['restricted_to'],
                 'login' => $data['login'],
                 'folder' => $folder,
                 'author' => $_SESSION['user_id'],
                ),
-            "id='".$id."'"
+            "id='".intval($id)."'"
         );
         // ADD an item
     } elseif ($action == "add_value") {
         // get new value from db
-        $sql = "SELECT i.label, i.description, i.id_tree as id_tree, i.perso, i.restricted_to, i.id, i.login
+        /*$sql = "SELECT i.label, i.description, i.id_tree as id_tree, i.perso, i.restricted_to, i.id, i.login
                 FROM ".$pre."items as i
                 INNER JOIN ".$pre."log_items as l ON (l.id_item = i.id)
                 WHERE i.id=".$id."
                 AND l.action = 'at_creation'";
         $row = $db->query($sql);
-        $data = $db->fetchArray($row);
+        $data = $db->fetchArray($row);*/
+        $data = $db->queryGetArray(
+            array(
+                "items" => "i"
+            ),
+            array(
+                "i.label" => "label",
+                "i.description" => "description",
+                "i.id_tree" => id_tree,
+                "i.perso" => "perso",
+                "i.restricted_to" => "restricted_to",
+                "i.login" => "login",
+                "i.id" => "id"
+            ),
+            array(
+                "i.id" => intval($id),
+                "l.action" => "at_creation"
+            ),
+            "",
+            array(
+                "log_items as l" => "(l.id_item = i.id)"
+            )
+        );
         // Get all TAGS
         $tags = "";
         $itemTags = $db->fetchAllArray("SELECT tag FROM ".$pre."tags WHERE item_id=".$id);
         foreach ($itemTags as $itemTag) {
             if (!empty($itemTag['tag'])) {
diff --git a/sources/main.queries.php b/sources/main.queries.php
index d2bdb139..dcdcda6f 100644
--- a/sources/main.queries.php
+++ b/sources/main.queries.php
@@ -1,12 +1,12 @@
 <?php
 /**
  *
  * @file          main.queries.php
- * @author        Nils Laumaillé
+ * @author        Nils LaumaillÃ©
  * @version       2.1.19
- * @copyright     (c) 2009-2014 Nils Laumaillé
+ * @copyright     (c) 2009-2014 Nils LaumaillÃ©
  * @licensing     GNU AFFERO GPL 3.0
  * @link          http://www.teampass.net
  *
  * This library is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -142,11 +142,20 @@ switch ($_POST['type']) {
                     'qui' => $_SESSION['user_id'],
                     'field_1' => $_SESSION['user_id']
                    )
             );
             //Send email to user
-            $row = $db->fetchRow("SELECT email FROM ".$pre."users WHERE id=".$dataReceived['user_id']);
+            // $row = $db->fetchRow("SELECT email FROM ".$pre."users WHERE id=".$dataReceived['user_id']);
+            $row = $db->queryGetRow(
+                "users",
+                array(
+                    "email"
+                ),
+                array(
+                    "id" => intval($dataReceived['user_id'])
+                )
+            );
             if (!empty($row[0])) {
                 sendEmail(
                     $txt['forgot_pw_email_subject'],
                     $txt['forgot_pw_email_body'] . " " . htmlspecialchars_decode($dataReceived['new_pw']),
                     $row[0],
@@ -778,50 +787,59 @@ switch ($_POST['type']) {
         $pwgen->setCapitalize(true);
         $pwgen->setNumerals(true);
         $key = $pwgen->generate();
 
         // Get account and pw associated to email
-        $data = $db->fetchRow(
-            "SELECT COUNT(*) FROM ".$pre."users WHERE email = '".
-            mysql_real_escape_string(stripslashes(($_POST['email'])))."'"
+        $data = $db->queryCount(
+            "users",
+            array(
+                "email" => mysql_real_escape_string(stripslashes($_POST['email']))
+            )
         );
         $textMail = $txt['forgot_pw_email_body_1']." <a href=\"".
             $_SESSION['settings']['cpassman_url']."/index.php?action=password_recovery&key=".$key.
-            "&login=".$_POST['login']."\">".$_SESSION['settings']['cpassman_url'].
-            "/index.php?action=password_recovery&key=".$key."&login=".$_POST['login']."</a>.<br><br>".$txt['thku'];
-        $textMailAlt = $txt['forgot_pw_email_altbody_1']." ".$txt['at_login']." : ".$data['login']." - ".
+            "&login=".mysql_real_escape_string($_POST['login'])."\">".$_SESSION['settings']['cpassman_url'].
+            "/index.php?action=password_recovery&key=".$key."&login=".mysql_real_escape_string($_POST['login'])."</a>.<br><br>".$txt['thku'];
+        $textMailAlt = $txt['forgot_pw_email_altbody_1']." ".$txt['at_login']." : ".mysql_real_escape_string($_POST['login'])." - ".
             $txt['index_password']." : ".md5($data['pw']);
 
         if ($data[0] != 0) {
             $data = $db->fetchArray(
                 "SELECT login,pw FROM ".$pre."users WHERE email = '".
-                mysql_real_escape_string(stripslashes(($_POST['email'])))."'"
+                mysql_real_escape_string(stripslashes($_POST['email']))."'"
             );
 
             // Check if email has already a key in DB
-            $data = $db->fetchRow(
-                "SELECT COUNT(*) FROM ".$pre."misc WHERE intitule = '".
-                $_POST['login']."' AND type = 'password_recovery'"
+            //$data = $db->fetchRow(
+            //    "SELECT COUNT(*) FROM ".$pre."misc WHERE intitule = '".
+            //    mysql_real_escape_string($_POST['login'])."' AND type = 'password_recovery'"
+            //);
+            $data = $db->queryCount(
+                "misc",
+                array(
+                    "intitule" => $_POST['login'],
+                    "type" => "password_recovery"
+                )
             );
             if ($data[0] != 0) {
                 $db->queryUpdate(
                     "misc",
                     array(
                             'valeur' => $key
                     ),
                     array(
                             'type' => 'password_recovery',
-                            'intitule' => $_POST['login']
+                            'intitule' => mysql_real_escape_string($_POST['login'])
                     )
                 );
             } else {
                 // store in DB the password recovery informations
                 $db->queryInsert(
                     'misc',
                     array(
                             'type' => 'password_recovery',
-                            'intitule' => $_POST['login'],
+                            'intitule' => mysql_real_escape_string($_POST['login']),
                             'valeur' => $key
                     )
                 );
             }
 
@@ -831,16 +849,31 @@ switch ($_POST['type']) {
             echo '[{"error":"error_email" , "message":"'.$txt['forgot_my_pw_error_email_not_exist'].'"}]';
         }
         break;
     // Send to user his new pw if key is conform
     case "generate_new_password":
+        // decrypt and retreive data in JSON format
+        $dataReceived = prepareExchangedData($_POST['data'], "decode");
+        // Prepare variables
+        $login = htmlspecialchars_decode($dataReceived['login']);
+        $key = htmlspecialchars_decode($dataReceived['key']);
         // check if key is okay
-        $data = $db->fetchRow(
+        /*$data = $db->fetchRow(
             "SELECT valeur FROM ".$pre."misc WHERE intitule = '".
-            $_POST['login']."' AND type = 'password_recovery'"
+            mysql_real_escape_string($login)."' AND type = 'password_recovery'"
+        );*/
+        $data = $db->queryGetRow(
+            "misc",
+            array(
+                "valeur"
+            ),
+            array(
+                "type" => "password_recovery",
+                "intitule" => $login
+            )
         );
-        if ($_POST['key'] == $data[0]) {
+        if ($key == $data[0]) {
             //Load PWGEN
             $pwgen = new SplClassLoader('Encryption\PwGen', '../includes/libraries');
             $pwgen->register();
             $pwgen = new Encryption\PwGen\pwgen();
 
@@ -858,23 +891,23 @@ switch ($_POST['type']) {
             $db->queryUpdate(
                 "users",
                 array(
                     'pw' => $newPw
                    ),
-                "login = '".$_POST['login']."'"
+                "login = '".mysql_real_escape_string($login)."'"
             );
             // Delete recovery in DB
             $db->queryDelete(
                 "misc",
                 array(
                     'type' => 'password_recovery',
-                    'intitule' => $_POST['login'],
+                    'intitule' => mysql_real_escape_string($login),
                     'valeur' => $key
                    )
             );
             // Get email
-            $dataUser = $db->queryFirst("SELECT email FROM ".$pre."users WHERE login = '".$_POST['login']."'");
+            $dataUser = $db->queryFirst("SELECT email FROM ".$pre."users WHERE login = '".mysql_real_escape_string($login)."'");
 
             $_SESSION['validite_pw'] = false;
             // send to user
             $ret = json_decode(
                 @sendEmail(
@@ -1016,22 +1049,26 @@ switch ($_POST['type']) {
     /**
      * Change the user's language
      */
     case "change_user_language":
         if (!empty($_SESSION['user_id'])) {
+            // decrypt and retreive data in JSON format
+            $dataReceived = prepareExchangedData($_POST['data'], "decode");
+            // Prepare variables
+            $language = $dataReceived['lang'];
             // update DB
             $db->queryUpdate(
                 "users",
                 array(
-                    'user_language' => $_POST['lang']
+                    'user_language' => $language
                    ),
                 "id = ".$_SESSION['user_id']
             );
-            $_SESSION['user_language'] = $_POST['lang'];
+            $_SESSION['user_language'] = $language;
         	echo "done";
         } else {
-            $_SESSION['user_language'] = $_POST['lang'];
+            $_SESSION['user_language'] = $language;
             echo "done";
         }
         break;
     /**
      * Send emails not sent
@@ -1123,30 +1160,64 @@ switch ($_POST['type']) {
         break;
     /**
      * Generate a password generic
      */
     case "generate_a_password":
+    	if ($_POST['size'] > $_SESSION['settings']['pwd_maximum_length']) {
+    		echo prepareExchangedData(
+	    		array(
+		    		"error_msg" => "Password length is too long!",
+		    		"error" => "true"
+	    		),
+	    		"encode"
+    		);
+    		break;
+    	}
+
         //Load PWGEN
         $pwgen = new SplClassLoader('Encryption\PwGen', '../includes/libraries');
         $pwgen->register();
         $pwgen = new Encryption\PwGen\pwgen();
-        //Generate
-        $pwgen->setLength($_POST['length']);
-        $pwgen->setSecure($_POST['secure']);
-        $pwgen->setSymbols($_POST['symbols']);
-        $pwgen->setCapitalize($_POST['capitalize']);
-        $pwgen->setNumerals($_POST['numerals']);
 
-        echo Encryption\Crypt\aesctr::encrypt($pwgen->generate(), $_SESSION['key'], 256);
+    	$pwgen->setLength($_POST['size']);
+    	if (isset($_POST['secure']) && $_POST['secure'] == "true") {
+    		$pwgen->setSecure(true);
+    		$pwgen->setSymbols(true);
+    		$pwgen->setCapitalize(true);
+    		$pwgen->setNumerals(true);
+    	} else {
+    		$pwgen->setSecure(($_POST['secure'] == "true")? true : false);
+    		$pwgen->setNumerals(($_POST['numerals'] == "true")? true : false);
+    		$pwgen->setCapitalize(($_POST['capitalize'] == "true")? true : false);
+    		$pwgen->setSymbols(($_POST['symbols'] == "true")? true : false);
+    	}
+
+        echo prepareExchangedData(
+        	array(
+	        	"key" => $pwgen->generate(),
+	        	"error" => ""
+        	),
+        	"encode"
+        );
         break;
     /**
      * Check if user exists and send back if psk is set
      */
     case "check_login_exists":
-        $sql = "SELECT * FROM ".$pre."users WHERE login = '".addslashes($_POST['userId'])."'";
+        /*$sql = "SELECT * FROM ".$pre."users WHERE login = '".addslashes($_POST['userId'])."'";
         $row = $db->query($sql);
-        $data = $db->fetchArray($row);
+        $data = $db->fetchArray($row);*/
+        $data = $db->queryGetArray(
+            "users",
+            array(
+                "login",
+                "psk"
+            ),
+            array(
+                "login" => $_POST['userId']
+            )
+        );
         if (empty($data['login'])) {
             $userOk = false;
         } else {
             $userOk = true;
         }
diff --git a/sources/roles.queries.php b/sources/roles.queries.php
index 9506612f..3842d68b 100644
--- a/sources/roles.queries.php
+++ b/sources/roles.queries.php
@@ -12,14 +12,26 @@
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
 
 require_once('sessions.php');
 session_start();
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || !isset($_SESSION['key']) || empty($_SESSION['key'])) {
+if (
+    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
+    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
+    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
+{
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_roles")) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    include 'error.php';
+    exit();
+}
+
 include $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
 include $_SESSION['settings']['cpassman_dir'].'/includes/settings.php';
 header("Content-type: text/html; charset=utf-8");
 include 'main.functions.php';
 
@@ -39,11 +51,17 @@ $tree = new Tree\NestedTree\NestedTree($pre.'nested_tree', 'id', 'parent_id', 't
 if (!empty($_POST['type'])) {
     switch ($_POST['type']) {
         #CASE adding a new role
         case "add_new_role":
             //Check if role already exist : No similar roles
-            $tmp = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."roles_title WHERE title = '".mysql_real_escape_string(stripslashes($_POST['name']))."'");
+            //$tmp = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."roles_title WHERE title = '".mysql_real_escape_string(stripslashes($_POST['name']))."'");
+            $tmp = $db->queryCount(
+                "roles_title",
+                array(
+                    "title" => stripslashes($_POST['name'])
+                )
+            );
             if ($tmp[0] == 0) {
                 $role_id = $db->queryInsert(
                         'roles_title',
                         array(
                                 'title' => mysql_real_escape_string(stripslashes($_POST['name'])),
@@ -77,11 +95,18 @@ if (!empty($_POST['type'])) {
 
         //-------------------------------------------
         #CASE editing a role
         case "edit_role":
             //Check if role already exist : No similar roles
-            $tmp = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."roles_title WHERE id != '".$_POST['id']."' AND title = '".mysql_real_escape_string(stripslashes($_POST['title']))."'");
+            //$tmp = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."roles_title WHERE id != '".$_POST['id']."' AND title = '".mysql_real_escape_string(stripslashes($_POST['title']))."'");
+            $tmp = $db->queryCount(
+                "roles_title",
+                array(
+                    "title" => stripslashes($_POST['title']),
+                    "id" => intval($_POST['id'])
+                )
+            );
             if ($tmp[0] == 0) {
                 $db->queryUpdate(
                     "roles_title",
                     array(
                         'title' => $_POST['title'],
@@ -219,11 +244,18 @@ if (!empty($_POST['type'])) {
                     $texte .= '<tr><td style=\'font-size:10px; font-family:arial;\'>'.$ident.$node->title.'</td>';
 
                     foreach ($arrRoles as $role) {
                         //check if this role has access or not
                         // if not then color is red; if yes then color is green
-                        $count = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."roles_values WHERE folder_id = ".$node->id." AND role_id = ".$role);
+                        //$count = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."roles_values WHERE folder_id = ".$node->id." AND role_id = ".$role);
+                        $count = $db->queryCount(
+                            "roles_values",
+                            array(
+                                "folder_id" => intval($node->id),
+                                "role_id" => intval($role)
+                            )
+                        );
                         if ($count[0] > 0) {
                             $couleur = '#008000';
                             $allowed = 1;
                         } else {
                             $couleur = '#FF0000';
diff --git a/sources/upload/upload.attachments.php b/sources/upload/upload.attachments.php
index dcbfb7b9..e28ea875 100644
--- a/sources/upload/upload.attachments.php
+++ b/sources/upload/upload.attachments.php
@@ -12,14 +12,26 @@
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
 
 require_once('../sessions.php');
 session_start();
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
+if (
+        !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 ||
+        !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) ||
+        !isset($_SESSION['key']) || empty($_SESSION['key'])
+) {
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "items")) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    handleError('Not allowed to ...', 110);
+    exit();
+}
+
 //check for session
 if (isset($_POST['PHPSESSID'])) {
     session_id($_POST['PHPSESSID']);
 } elseif (isset($_GET['PHPSESSID'])) {
     session_id($_GET['PHPSESSID']);
diff --git a/sources/upload/upload.files.php b/sources/upload/upload.files.php
index 434cda98..7f50701e 100644
--- a/sources/upload/upload.files.php
+++ b/sources/upload/upload.files.php
@@ -12,14 +12,26 @@
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
 
 require_once('../sessions.php');
 session_start();
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
+if (
+        !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 ||
+        !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) ||
+        !isset($_SESSION['key']) || empty($_SESSION['key'])
+) {
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "items")) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    handleError('Not allowed to ...', 110);
+    exit();
+}
+
 //check for session
 if (isset($_POST['PHPSESSID'])) {
     session_id($_POST['PHPSESSID']);
 } elseif (isset($_GET['PHPSESSID'])) {
     session_id($_GET['PHPSESSID']);
diff --git a/sources/users.queries.php b/sources/users.queries.php
index 5534d7bb..f34195fd 100644
--- a/sources/users.queries.php
+++ b/sources/users.queries.php
@@ -4,19 +4,35 @@
  * @file          users.queries.php
  * @author        Nils Laumaillé
  * @version       2.1.20
  * @copyright     (c) 2009-2014 Nils Laumaillé
  * @licensing     GNU AFFERO GPL 3.0
- * @link          http://www.teampass.net
+ * @link		http://www.teampass.net
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
 
 require_once('sessions.php');
 session_start();
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || !isset($_SESSION['key']) || empty($_SESSION['key'])) {
+if (
+    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
+    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
+    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
+{
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_users")) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    include 'error.php';
+    exit();
+}
+
 include $_SESSION['settings']['cpassman_dir'].'/includes/settings.php';
 header("Content-type: text/html; charset=utf-8");
 require_once $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
 require_once $_SESSION['settings']['cpassman_dir'].'/sources/main.functions.php';
 require_once $_SESSION['settings']['cpassman_dir'].'/sources/SplClassLoader.php';
@@ -42,11 +58,20 @@ if (!empty($_POST['type'])) {
         case "groupes_visibles":
         case "groupes_interdits":
             $val = explode(';', $_POST['valeur']);
             $valeur = $_POST['valeur'];
             // Check if id folder is already stored
-            $data = $db->fetchRow("SELECT ".$_POST['type']." FROM ".$pre."users WHERE id = ".$val[0]);
+            // $data = $db->fetchRow("SELECT ".$_POST['type']." FROM ".$pre."users WHERE id = ".$val[0]);
+            $data = $db->queryGetRow(
+                "users",
+                array(
+                    $_POST['type']
+                ),
+                array(
+                    "id" => intval($val[0])
+                )
+            );
             $new_groupes = $data[0];
             if (!empty($data[0])) {
                 $groupes = explode(';', $data[0]);
                 if (in_array($val[1], $groupes)) {
                     $new_groupes = str_replace($val[1], "", $new_groupes);
@@ -72,11 +97,20 @@ if (!empty($_POST['type'])) {
          */
         case "fonction":
             $val = explode(';', $_POST['valeur']);
             $valeur = $_POST['valeur'];
             // v?rifier si l'id est d?j? pr?sent
-            $data = $db->fetchRow("SELECT fonction_id FROM ".$pre."users WHERE id = $val[0]");
+            // $data = $db->fetchRow("SELECT fonction_id FROM ".$pre."users WHERE id = $val[0]");
+            $data = $db->queryGetRow(
+                "users",
+                array(
+                    "fonction_id"
+                ),
+                array(
+                    "id" => intval($val[0])
+                )
+            );
             $new_fonctions = $data[0];
             if (!empty($data[0])) {
                 $fonctions = explode(';', $data[0]);
                 if (in_array($val[1], $fonctions)) {
                     $new_fonctions = str_replace($val[1], "", $new_fonctions);
@@ -237,11 +271,21 @@ if (!empty($_POST['type'])) {
                     array(
                         'id' => $_POST['id']
                        )
                 );
                 // delete personal folder and subfolders
-                $data = $db->fetchRow("SELECT id FROM ".$pre."nested_tree WHERE title = '".$_POST['id']."' AND personal_folder = 1");    // Get personal folder ID
+                // $data = $db->fetchRow("SELECT id FROM ".$pre."nested_tree WHERE title = '".$_POST['id']."' AND personal_folder = 1");    // Get personal folder ID
+                $data = $db->queryGetRow(
+                    "nested_tree",
+                    array(
+                        "id"
+                    ),
+                    array(
+                        "title" => intval($_POST['id']),
+                        "personal_folder" => "1"
+                    )
+                );
                 // Get through each subfolder
                 if (!empty($data[0])) {
                     $folders = $tree->getDescendants($data[0], true);
                     foreach ($folders as $folder) {
                         // delete folder
@@ -302,11 +346,20 @@ if (!empty($_POST['type'])) {
             if ($_POST['key'] != $_SESSION['key']) {
                 // error
                 echo '[ { "error" : "yes" } ]';
             }
             // Get old email
-            $data = $db->fetchRow("SELECT email FROM ".$pre."users WHERE id = '".$_POST['id']."'");
+            // $data = $db->fetchRow("SELECT email FROM ".$pre."users WHERE id = '".$_POST['id']."'");
+            $data = $db->queryGetRow(
+                "users",
+                array(
+                    "email"
+                ),
+                array(
+                    "id" => intval($_POST['id'])
+                )
+            );
 
             $db->queryUpdate(
                 "users",
                 array(
                     'email' => $_POST['newemail']
@@ -421,11 +474,20 @@ if (!empty($_POST['type'])) {
          * CHANGE USER FUNCTIONS
          */
         case "open_div_functions";
             $text = "";
             // Refresh list of existing functions
-            $data_user = $db->fetchRow("SELECT fonction_id FROM ".$pre."users WHERE id = ".$_POST['id']);
+            // $data_user = $db->fetchRow("SELECT fonction_id FROM ".$pre."users WHERE id = ".$_POST['id']);
+            $data = $db->queryGetRow(
+                "users",
+                array(
+                    "fonction_id"
+                ),
+                array(
+                    "id" => intval($_POST['id'])
+                )
+            );
             $users_functions = explode(';', $data_user[0]);
             // array of roles for actual user
             $my_functions = explode(';', $_SESSION['fonction_id']);
 
             $rows = $db->fetchAllArray("SELECT id,title,creator_id FROM ".$pre."roles_title");
@@ -482,11 +544,20 @@ if (!empty($_POST['type'])) {
          * CHANGE AUTHORIZED GROUPS
          */
         case "open_div_autgroups";
             $text = "";
             // Refresh list of existing functions
-            $data_user = $db->fetchRow("SELECT groupes_visibles FROM ".$pre."users WHERE id = ".$_POST['id']);
+            // $data_user = $db->fetchRow("SELECT groupes_visibles FROM ".$pre."users WHERE id = ".$_POST['id']);
+            $data_user = $db->queryGetRow(
+                "users",
+                array(
+                    "groupes_visibles"
+                ),
+                array(
+                    "id" => intval($_POST['id'])
+                )
+            );
             $user = explode(';', $data_user[0]);
 
             $tree_desc = $tree->getDescendants();
             foreach ($tree_desc as $t) {
                 if (in_array($t->id, $_SESSION['groupes_visibles']) && !in_array($t->id, $_SESSION['personal_visible_groups'])) {
@@ -572,11 +643,20 @@ if (!empty($_POST['type'])) {
                 exit();
             }
 
             $text = "";
             // Refresh list of existing functions
-            $data_user = $db->fetchRow("SELECT groupes_interdits FROM ".$pre."users WHERE id = ".$_POST['id']);
+            // $data_user = $db->fetchRow("SELECT groupes_interdits FROM ".$pre."users WHERE id = ".$_POST['id']);
+            $data_user = $db->queryGetRow(
+                "users",
+                array(
+                    "groupes_interdits"
+                ),
+                array(
+                    "id" => intval($_POST['id'])
+                )
+            );
             $user = explode(';', $data_user[0]);
 
             $tree_desc = $tree->getDescendants();
             foreach ($tree_desc as $t) {
                 if (in_array($t->id, $_SESSION['groupes_visibles']) && !in_array($t->id, $_SESSION['personal_visible_groups'])) {
@@ -660,18 +740,31 @@ if (!empty($_POST['type'])) {
         * Check the domain
         */
         case "check_domain":
             $return = array();
             // Check if folder exists
-            $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."nested_tree WHERE title = '".$_POST['domain']."' AND parent_id = 0");
+            //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."nested_tree WHERE title = '".$_POST['domain']."' AND parent_id = 0");
+            $data = $db->queryCount(
+                "nested_tree",
+                array(
+                    "title" => $_POST['domain'],
+                    "parent_id" => "0"
+                )
+            );
             if ($data[0] != 0) {
                 $return["folder"] = "exists";
             } else {
                 $return["folder"] = "not_exists";
             }
             // Check if role exists
-            $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."roles_title WHERE title = '".$_POST['domain']."'");
+            //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."roles_title WHERE title = '".$_POST['domain']."'");
+            $data = $db->queryCount(
+                "roles_title",
+                array(
+                    "title" => $_POST['domain']
+                )
+            );
             if ($data[0] != 0) {
                 $return["role"] = "exists";
             } else {
                 $return["role"] = "not_exists";
             }
@@ -695,11 +788,11 @@ if (!empty($_POST['type'])) {
                 $data = $db->fetchRow(
                     "SELECT COUNT(*)
                     FROM ".$pre."log_items as l
                     INNER JOIN ".$pre."items as i ON (l.id_item=i.id)
                     INNER JOIN ".$pre."users as u ON (l.id_user=u.id)
-                    WHERE l.id_user = ".$_POST['id'].$sql_filter
+                    WHERE l.id_user = ".intval($_POST['id'].$sql_filter)
                 );
                 // define query limits
                 if (isset($_POST['page']) && $_POST['page'] > 1) {
                     $start = ($_POST['nb_items_by_page'] * ($_POST['page'] - 1)) + 1;
                 } else {
@@ -709,20 +802,27 @@ if (!empty($_POST['type'])) {
                 $rows = $db->fetchAllArray(
                     "SELECT l.date as date, u.login as login, i.label as label, l.action as action
                     FROM ".$pre."log_items as l
                     INNER JOIN ".$pre."items as i ON (l.id_item=i.id)
                     INNER JOIN ".$pre."users as u ON (l.id_user=u.id)
-                    WHERE l.id_user = ".$_POST['id'].$sql_filter."
+                    WHERE l.id_user = ".intval($_POST['id'].$sql_filter)."
                     ORDER BY date DESC
-                    LIMIT $start,".$_POST['nb_items_by_page']
+                    LIMIT ".intval($start).",".intval($_POST['nb_items_by_page'])
                 );
             } else {
                 // get number of pages
-                $data = $db->fetchRow(
-                    "SELECT COUNT(*)
-                    FROM ".$pre."log_system
-                    WHERE type = 'user_mngt' AND field_1=".$_POST['id']
+                //$data = $db->fetchRow(
+                //    "SELECT COUNT(*)
+                //    FROM ".$pre."log_system
+                //    WHERE type = 'user_mngt' AND field_1=".$_POST['id']
+                //);
+                $data = $db->queryCount(
+                    "log_system",
+                    array(
+                        "type" => "user_mngt",
+                        "field_1" => $_POST['id']
+                    )
                 );
                 // define query limits
                 if (isset($_POST['page']) && $_POST['page'] > 1) {
                     $start = ($_POST['nb_items_by_page'] * ($_POST['page'] - 1)) + 1;
                 } else {
@@ -777,13 +877,13 @@ if (!empty($_POST['type'])) {
                 echo '[ { "error" : "no_sk_user" } ]';
             } elseif ($user_id == "") {
                 echo '[ { "error" : "no_user_id" } ]';
             } else {
                 // Get folder id for Admin
-                $admin_folder = $db->queryFirst("SELECT id FROM ".$pre."nested_tree WHERE title='".$_SESSION['user_id']."' AND personal_folder = 1");
+                $admin_folder = $db->queryFirst("SELECT id FROM ".$pre."nested_tree WHERE title='".intval($_SESSION['user_id'])."' AND personal_folder = 1");
                 // Get folder id for User
-                $user_folder = $db->queryFirst("SELECT id FROM ".$pre."nested_tree WHERE title='".$user_id."' AND personal_folder = 1");
+                $user_folder = $db->queryFirst("SELECT id FROM ".$pre."nested_tree WHERE title='".intval($user_id)."' AND personal_folder = 1");
                 // Get through each subfolder
                 foreach ($tree->getDescendants($admin_folder['id'], true) as $folder) {
                     // Create folder if necessary
                     if ($folder->title != $_SESSION['user_id']) {
                         // update folder
@@ -798,11 +898,11 @@ if (!empty($_POST['type'])) {
                     // Get each Items in PF
                     $rows = $db->fetchAllArray(
                         "SELECT i.pw, i.label, l.id_user
                         FROM ".$pre."items as i
                         LEFT JOIN ".$pre."log_items as l ON (l.id_item=i.id)
-                        WHERE l.action = 'at_creation' AND i.perso=1 AND i.id_tree=".$folder->id
+                        WHERE l.action = 'at_creation' AND i.perso=1 AND i.id_tree=".intval($folder->id)
                     );
                     foreach ($rows as $reccord) {
                         echo $reccord['label']." - ";
                         // Change user
                         $db->queryUpdate(
@@ -839,11 +939,11 @@ if (!empty($_POST['type'])) {
                     array(
                         'timestamp' => "",
                         'key_tempo' => "",
                         'session_end' => ""
                        ),
-                    "id = ".$_POST['user_id']
+                    "id = ".intval($_POST['user_id'])
                 );
             break;
 
         /**
         * delete the timestamp value for all users
@@ -862,11 +962,11 @@ if (!empty($_POST['type'])) {
                     array(
                         'timestamp' => "",
                         'key_tempo' => "",
                         'session_end' => ""
                        ),
-                    "id = ".$reccord['id']
+                    "id = ".intval($reccord['id'])
                 );
             }
             break;
     }
 }
diff --git a/sources/views.queries.php b/sources/views.queries.php
index 4ea32b9e..b77e0458 100644
--- a/sources/views.queries.php
+++ b/sources/views.queries.php
@@ -12,14 +12,26 @@
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
 
 require_once('sessions.php');
 session_start();
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || !isset($_SESSION['key']) || empty($_SESSION['key'])) {
+if (
+    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
+    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
+    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
+{
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_views")) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    include 'error.php';
+    exit();
+}
+
 include $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
 include $_SESSION['settings']['cpassman_dir'].'/includes/settings.php';
 include $_SESSION['settings']['cpassman_dir'].'/includes/include.php';
 header("Content-type: text/html; charset=utf-8");
 include 'main.functions.php';
@@ -369,11 +381,11 @@ switch ($_POST['type']) {
         $data = $db->fetchRow(
             "SELECT COUNT(*)
             FROM ".$pre."log_items as l
             INNER JOIN ".$pre."items as i ON (l.id_item=i.id)
             INNER JOIN ".$pre."users as u ON (l.id_user=u.id)
-            WHERE l.action = 'at_shown'".$sqlFilter
+            WHERE l.action = 'at_shown'".mysql_real_escape_string($sqlFilter)
         );
         if ($data[0] != 0) {
             $nbPages = ceil($data[0]/$nbElements);
             for ($i=1; $i<=$nbPages; $i++) {
                 $pages .= '<td onclick=\'displayLogs(\"access_logs\", '.$i.', \"'.$_POST['order'].'\")\'><span style=\'cursor:pointer;'.($_POST['page'] == $i ? 'font-weight:bold;font-size:18px;\'>'.$i:'\'>'.$i).'</span></td>';
@@ -424,11 +436,11 @@ switch ($_POST['type']) {
         $data = $db->fetchRow(
             "SELECT COUNT(*)
             FROM ".$pre."log_items as l
             INNER JOIN ".$pre."items as i ON (l.id_item=i.id)
             INNER JOIN ".$pre."users as u ON (l.id_user=u.id)
-            WHERE l.action = 'at_copy'".$sqlFilter
+            WHERE l.action = 'at_copy'".mysql_real_escape_string($sqlFilter)
         );
         if ($data[0] != 0) {
             $nbPages = ceil($data[0]/$nbElements);
             for ($i=1; $i<=$nbPages; $i++) {
                 $pages .= '<td onclick=\'displayLogs(\"copy_logs\", '.$i.', \'\')\'><span style=\'cursor:pointer;'.($_POST['page'] == $i ? 'font-weight:bold;font-size:18px;\'>'.$i:'\'>'.$i).'</span></td>';
@@ -480,11 +492,11 @@ switch ($_POST['type']) {
         $data = $db->fetchRow(
             "SELECT COUNT(*)
             FROM ".$pre."log_items as l
             INNER JOIN ".$pre."items as i ON (l.id_item=i.id)
             INNER JOIN ".$pre."users as u ON (l.id_user=u.id)
-            WHERE i.label LIKE '%".$_POST['filter']."%'"
+            WHERE i.label LIKE '%".mysql_real_escape_string($_POST['filter'])."%'"
         );
         if ($data[0] != 0) {
             $nbPages = ceil($data[0]/$nbElements);
             for ($i=1; $i<=$nbPages; $i++) {
                 $pages .= '<td onclick=\'displayLogs(\"items_logs\", '.$i.', \"\")\'><span style=\'cursor:pointer;'.($_POST['page'] == $i ? 'font-weight:bold;font-size:18px;\'>'.$i:'\'>'.$i).'</span></td>';
@@ -541,11 +553,11 @@ switch ($_POST['type']) {
         //get number of pages
         $data = $db->fetchRow(
             "SELECT COUNT(*)
             FROM ".$pre."log_system as l
             INNER JOIN ".$pre."users as u ON (l.qui=u.id)
-            WHERE l.type = 'admin_action'".$sqlFilter
+            WHERE l.type = 'admin_action'".mysql_real_escape_string($sqlFilter)
         );
         if ($data[0] != 0) {
             $nbPages = ceil($data[0]/$nbElements);
             for ($i=1; $i<=$nbPages; $i++) {
                 $pages .= '<td onclick=\'displayLogs(\"copy_logs\", '.$i.', \'\')\'><span style=\'cursor:pointer;'.($_POST['page'] == $i ? 'font-weight:bold;font-size:18px;\'>'.$i:'\'>'.$i).'</span></td>';
@@ -683,44 +695,44 @@ switch ($_POST['type']) {
         if (!empty($_POST['purgeFrom']) && !empty($_POST['purgeTo']) && !empty($_POST['logType'])
             && isset($_SESSION['user_admin']) && $_SESSION['user_admin'] == 1) {
             if ($_POST['logType'] == "items_logs") {
                 $nbElements = $db->fetchRow(
                     "SELECT COUNT(*) FROM ".$pre."log_items WHERE action='at_shown' ".
-                    "AND date BETWEEN '".strtotime($_POST['purgeFrom'])."' AND '".strtotime($_POST['purgeTo'])."'"
+                    "AND date BETWEEN '".intval(strtotime($_POST['purgeFrom']))."' AND '".intval(strtotime($_POST['purgeTo']))."'"
                 );
                 // Delete
                 $db->query(
                     "DELETE FROM ".$pre."log_items WHERE action='at_shown' AND date BETWEEN '".
                     strtotime($_POST['purgeFrom'])."' AND '".strtotime($_POST['purgeTo'])."'"
                 );
             } elseif ($_POST['logType'] == "connections_logs") {
                 $nbElements = $db->fetchRow(
                     "SELECT COUNT(*) FROM ".$pre."log_system WHERE type='user_connection' ".
-                    "AND date BETWEEN '".strtotime($_POST['purgeFrom'])."' AND '".
-                    strtotime($_POST['purgeTo'])."'"
+                    "AND date BETWEEN '".intval(strtotime($_POST['purgeFrom']))."' AND '".
+                    intval(strtotime($_POST['purgeTo']))."'"
                 );
                 // Delete
                 $db->query(
                     "DELETE FROM ".$pre."log_system WHERE type='user_connection' ".
                     "AND date BETWEEN '".strtotime($_POST['purgeFrom'])."' AND '".strtotime($_POST['purgeTo'])."'"
                 );
             } elseif ($_POST['logType'] == "errors_logs") {
                 $nbElements = $db->fetchRow(
                     "SELECT COUNT(*) FROM ".$pre."log_system WHERE type='error' ".
-                    "AND date BETWEEN '".strtotime($_POST['purgeFrom'])."' AND '".
-                    strtotime($_POST['purgeTo'])."'"
+                    "AND date BETWEEN '".intval(strtotime($_POST['purgeFrom']))."' AND '".
+                    intval(strtotime($_POST['purgeTo']))."'"
                 );
                 // Delete
                 $db->query(
                     "DELETE FROM ".$pre."log_system WHERE type='error' ".
                     "AND date BETWEEN '".strtotime($_POST['purgeFrom'])."' AND '".strtotime($_POST['purgeTo'])."'"
                 );
             } elseif ($_POST['logType'] == "copy_logs") {
                 $nbElements = $db->fetchRow(
                     "SELECT COUNT(*) FROM ".$pre."log_items WHERE action='at_copy' ".
-                    "AND date BETWEEN '".strtotime($_POST['purgeFrom'])."' AND '".
-                    strtotime($_POST['purgeTo'])."'"
+                    "AND date BETWEEN '".intval(strtotime($_POST['purgeFrom']))."' AND '".
+                    intval(strtotime($_POST['purgeTo']))."'"
                 );
                 // Delete
                 $db->query(
                     "DELETE FROM ".$pre."log_items WHERE action='at_copy' ".
                     "AND date BETWEEN '".strtotime($_POST['purgeFrom'])."' AND '".strtotime($_POST['purgeTo'])."'"
diff --git a/users.load.php b/users.load.php
index df2e63ab..157e83bb 100644
--- a/users.load.php
+++ b/users.load.php
@@ -254,16 +254,21 @@ $(function() {
                             type       : "generate_a_password",
                             length     : 8,
                             secure     : true,
                             symbols    : false,
                             capitalize : true,
-                            numerals   : true,
+                            numerals   : true
                         },
                         function(data) {
-                            var pw = htmlspecialchars_decode(aes_decrypt(data));
-                        	$("#change_user_pw_newpw_confirm, #change_user_pw_newpw").val(pw);
-                    		$("#change_user_pw_newpw").focus();
+                        	data = prepareExchangedData(data, "decode");
+                        	if (data.error == "true") {
+                        		$("#div_dialog_message_text").html(data.error_msg);
+                        		$("#div_dialog_message").dialog("open");
+                        	} else {
+                        		$("#change_user_pw_newpw_confirm, #change_user_pw_newpw").val(pw);
+                        		$("#change_user_pw_newpw").focus();
+                        	}
                     		$("#change_user_pw_wait").hide();
                         }
                    );
         	},
             "<?php echo $txt['save_button'];?>": function() {
@@ -405,24 +410,29 @@ $(function() {
 });
 
 function pwGenerate(elem)
 {
     $.post(
-        "sources/items.queries.php",
+        "sources/main.queries.php",
         {
-            type    : "pw_generate",
+            type    : "generate_a_password",
             size    : Math.floor((8-5)*Math.random()) + 6,
             num        : true,
             maj        : true,
             symb    : false,
             fixed_elem    : 1,
             elem    : elem,
             force    : false
         },
         function(data) {
-            data = $.parseJSON(data);
-            $("#"+elem).val(data.key).focus();
+        	data = prepareExchangedData(data, "decode");
+        	if (data.error == "true") {
+        		$("#div_dialog_message_text").html(data.error_msg);
+        		$("#div_dialog_message").dialog("open");
+        	} else {
+        		$("#"+elem).val(data.key).focus();
+        	}
         }
    );
 }
 
 function action_on_user(id, action)
diff --git a/users.php b/users.php
index 5229816d..01ad462c 100644
--- a/users.php
+++ b/users.php
@@ -11,14 +11,26 @@
  * This library is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
 
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
+if (
+    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
+    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
+    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
+{
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], curPage())) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    include 'error.php';
+    exit();
+}
+
 require_once $_SESSION['settings']['cpassman_dir'].'/sources/SplClassLoader.php';
 
 // Load file
 require_once 'users.load.php';
 // load help
diff --git a/views.php b/views.php
index 6f3acfbd..0fbdb3a6 100644
--- a/views.php
+++ b/views.php
@@ -10,14 +10,26 @@
  * This library is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
 
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
+if (
+    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
+    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
+    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
+{
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], curPage())) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    include 'error.php';
+    exit();
+}
+
 //Load file
 require_once 'views.load.php';
 
 // show TABS permitting to select specific actions
 echo '
diff --git a/views_database.php b/views_database.php
index 8852407e..ab61061f 100644
--- a/views_database.php
+++ b/views_database.php
@@ -1,29 +1,40 @@
 <?php
 /**
  * @file          views_database.php
- * @author        Nils Laumaillé
+ * @author        Nils LaumaillÃ©
  * @version       2.1.19
- * @copyright     (c) 2009-2014 Nils Laumaillé
+ * @copyright     (c) 2009-2014 Nils LaumaillÃ©
  * @licensing     GNU AFFERO GPL 3.0
  * @link          http://www.teampass.net
  *
  * This library is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  */
 
 require_once('sources/sessions.php');
 session_start();
-
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
+if (
+    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 ||
+    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) ||
+    !isset($_SESSION['key']) || empty($_SESSION['key']))
+{
     die('Hacking attempt...');
 }
 
+/* do checks */
+include $_SESSION['settings']['cpassman_dir'].'/includes/include.php';
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_views")) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    include 'error.php';
+    exit();
+}
+
 include $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
 include $_SESSION['settings']['cpassman_dir'].'/includes/settings.php';
-include $_SESSION['settings']['cpassman_dir'].'/includes/include.php';
 header("Content-type: text/html; charset=utf-8");
 include $_SESSION['settings']['cpassman_dir'].'/sources/main.functions.php';
 
 require_once $_SESSION['settings']['cpassman_dir'].'/sources/SplClassLoader.php';
 
diff --git a/views_logs.php b/views_logs.php
index 6f120b4e..fe8684ae 100644
--- a/views_logs.php
+++ b/views_logs.php
@@ -13,14 +13,26 @@
  */
 
 require_once('sources/sessions.php');
 session_start();
 
-if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
+if (
+    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
+    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
+    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
+{
     die('Hacking attempt...');
 }
 
+/* do checks */
+require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
+if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_views")) {
+    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
+    include 'error.php';
+    exit();
+}
+
 include $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
 include $_SESSION['settings']['cpassman_dir'].'/includes/settings.php';
 include $_SESSION['settings']['cpassman_dir'].'/includes/include.php';
 header("Content-type: text/html; charset=utf-8");
 include $_SESSION['settings']['cpassman_dir'].'/sources/main.functions.php';

Vulnerable code: if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
    $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."misc WHERE type='".$type."' AND intitule = '".$setting."'");
            $data_time = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."misc WHERE type='".$type."' AND intitule = '".$setting."_time'");
$nb_emails = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."emails WHERE status = 'not_sent' OR status = ''");
            $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."nested_tree WHERE personal_folder=0 AND id = ".$folder->id);
 * @file          datatable.users_logged.php
 * @author        Nils Laumaill�
 * @copyright     (c) 2009-2014 Nils Laumaill�
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
        $sLimit = "LIMIT ". $_GET['iDisplayStart'] .", ". $_GET['iDisplayLength'] ;
                $sOrder .= $aColumns[ intval($_GET['iSortCol_'.$i]) ]."
                        ".mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
        $data = $db->fetchRow("SELECT title FROM ".$pre."nested_tree WHERE id = ".$t->parent_id);
        $node_data = $db->fetchRow(
        echo '<tr class="ligne0" id="row_'.$t->id.'">
                        <td align="center" onclick="open_edit_folder_dialog('.$t->id.')">'.$t->id.'</td>
                        <td width="50%" onclick="open_edit_folder_dialog('.$t->id.')">
                            '.$ident.'<span id="title_'.$t->id.'">'.$t->title.'</span>
                        </td>
                        <td align="center" onclick="open_edit_folder_dialog('.$t->id.')">
                            <span id="complexite_'.$t->id.'">'.@$pwComplexity[$node_data[0]][1].'</span>
                        </td>
                        <td align="center" onclick="open_edit_folder_dialog('.$t->id.')">
                            <span id="parent_'.$t->id.'">'.$data[0].'</span>
                        </td>
                        <td align="center" onclick="open_edit_folder_dialog('.$t->id.')">
                            '.$t->nlevel.'
                        </td>
                        <td align="center" onclick="open_edit_folder_dialog('.$t->id.')">
                            <span id="renewal_'.$t->id.'">'.$node_data[1].'</span>
                        </td>
                        <td align="center">
                            <img src="includes/images/folder--minus.png" onclick="supprimer_groupe(\''.$t->id.'\')" style="cursor:pointer;" />
                        </td>';
        $data3 = $db->fetchRow("SELECT bloquer_creation,bloquer_modification FROM ".$pre."nested_tree WHERE id = ".$t->id);
                        <td align="center">
                            <input type="checkbox" id="cb_droit_'.$t->id.'" onchange="Changer_Droit_Complexite(\''.$t->id.'\',\'creation\')"', isset($data3[0]) && $data3[0] == 1 ? 'checked' : '', ' />
                        </td>
                        <td align="center">
                            <input type="checkbox" id="cb_droit_modif_'.$t->id.'" onchange="Changer_Droit_Complexite(\''.$t->id.'\',\'modification\')"', isset($data3[1]) && $data3[1] == 1 ? 'checked' : '', ' />
                        </td>
                        <td>
                            <input type="hidden"  id="parent_id_'.$t->id.'" value="'.$t->parent_id.'" />
                            <input type="hidden"  id="renewal_id_'.$t->id.'" value="'.$node_data[0].'" />
                        </td>
            $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."log_items WHERE id_item = '".$record['id']."' AND action = 'at_delete'");
$k['copyright'] = "&nbsp;&copy;&nbsp;copyright 2009-2014";
$txt['user_ga_code'] = "Send GoogleAuthenticator to user by email";
$txt['send_ga_code'] = "Google Authenticator for user";
$txt['error_no_email'] = "This user has no email set!";
$txt['error_no_user'] = "No user found!";
$txt['email_ga_subject'] = "Your Google Authenticator flash code for Teampass";
$txt['email_ga_text'] = "Hello,<br><br>Please click this <a href='#link#'>LINK</a> and flash it with GoogleAuthenticator application to get your OTP credentials for Teampass.<br /><br />Cheers";

$txt['purge_done'] = "Purge done! Number of elements deleted: ";
    public function checkCode($secret, $code, $discrepancy = 3)
        /*
       $time = floor(time() / 30);
   		*/
    	$currentTimeSlice = floor(time() / 30);

    	for ($i = -$discrepancy; $i <= $discrepancy; $i++) {
    		$calculatedCode = $this->getCode($secret, $currentTimeSlice + $i);
    		if ($calculatedCode == $code ) {
    			return true;
    		}
    	}
    }#-#fetchArray()
        
        
        } else {            
$database = "tp";
@define('SECUREPATH', 'E:/xampp/security');
require_once "E:/xampp/security/sk.php";
    $dataLanguage =
        );
            <button title="'.$txt['login_copy'].'" style="margin-bottom:5px;" id="menu_button_copy_login" class="copy_clipboard"><img src="includes/images/ui-text-field.png" id="div_copy_login" alt="" /></button>
        "sources/items.queries.php",
            type    : "pw_generate",
        	data = prepareExchangedData(data, "decode");
            $("#"+elem+"pw1").val(data.key).focus();
			$("#visible_pw").text(data.key);
        $("#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");
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
if (!isset($_SESSION['login'])) {
    break;
                $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."items WHERE inactif=0 AND id_tree = ".$node);
            $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."items WHERE inactif=0 AND id_tree = ".$folder->id);
</div>';
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1
        || $_SESSION['settings']['enable_kb'] != 1
) {
                login:    login,
                key :    key
                type    : "change_user_language",
                lang    : lang
<?php
session_start();

include './includes/settings.php';
include './sources/main.functions.php';

require_once './sources/SplClassLoader.php';

// connect to the server
$db = new SplClassLoader('Database\Core', './includes/libraries');
$db->register();
$db = new Database\Core\DbCore($server, $user, $pass, $database, $pre);
$db->connect();

$rows = $db->fetchAllArray("SELECT id, pw FROM ".$pre."items WHERE perso = '0'");
foreach ($rows as $reccord) {
	$pw = decrypt($reccord['pw']);
	if (!empty($pw) && strlen($pw) > 30 && isutf8($pw)) {

		$key = substr($pw, 0, 15);
		$pw = substr($pw,30);

		$pw = $key . $pw;

		$pw = encrypt($pw);

		$db->queryUpdate(
			'items',
			array(
			    'pw' => $pw
			),
			"id='".$reccord['id']."'"
		);
	}
}

?>
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || !isset($_SESSION['key']) || empty($_SESSION['key'])) {
            $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."nested_tree WHERE title = '".$record['id']."' AND parent_id = 0");
            $row = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."log_items WHERE id_item=".$item['id']." AND action = 'at_creation'");
            $row = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."log_items WHERE id_item=".$item['id']." AND action = 'at_creation'");
            $row = @$db->fetchRow("SELECT COUNT(*) FROM ".$pre."keys WHERE `id`='".$reccord['id']."' AND `table` = 'items'");
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || !isset($_SESSION['key']) || empty($_SESSION['key'])) {
                    $row = $db->fetchRow("SELECT title FROM ".$pre."nested_tree WHERE id=".$folder);
    $dataSession = $db->fetchRow("SELECT key_tempo FROM ".$pre."users WHERE id=".$_SESSION['user_id']);
    $row = $db->fetchRow("SELECT valeur FROM ".$pre."misc WHERE type = 'admin' AND intitule = 'cpassman_version'");
    $sql="SELECT * FROM ".$pre."users WHERE id = '".$_SESSION['user_id']."'";
    $row = $db->query($sql);
    $data = $db->fetchArray($row);
$queryCount = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."users WHERE timestamp >= '".(time() - 600)."'");
            $sOrder .= $aColumns[ intval($_GET['iSortCol_'.$i]) ]."
        $sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string($_GET['sSearch'])."%' OR ";
    $sLimit = "LIMIT ". $_GET['iDisplayStart'] .", ". $_GET['iDisplayLength'] ;
            $sOrder .= $aColumns[ intval($_GET['iSortCol_'.$i]) ]."
    $ret_cat = $db->fetchRow("SELECT category FROM ".$pre."kb_categories WHERE id = ".$reccord['category_id']);
    $ret_author = $db->fetchRow("SELECT login FROM ".$pre."users WHERE id = ".$reccord['author_id']);
        $sLimit = "LIMIT ". $_GET['iDisplayStart'] .", ". $_GET['iDisplayLength'] ;
                $sOrder .= $aColumns[ intval($_GET['iSortCol_'.$i]) ]."
    $sLimit = "LIMIT ". $_GET['iDisplayStart'] .", ". $_GET['iDisplayLength'] ;
            $sOrder .= $aColumns[ intval($_GET['iSortCol_'.$i]) ]."
			<td align="center"><span class="span_pw" id="span_'.$elem['id'].'"><a href="#" onclick="decryptme('.$elem['id'].', \''.$encPw.'\')">Decrypt </a></span><input type="hidden" id="hide_'.$elem['id'].'" value="'.$encPw.'" /></td>
            $data = $db->fetchRow("SELECT favourites FROM ".$pre."users WHERE id = '".$_SESSION['user_id']."'");
$row = $db->fetchRow("SELECT id FROM ".$pre."nested_tree WHERE title = ".$_SESSION['user_id']);
$rows = $db->fetchAllArray(
    "SELECT id FROM ".$pre."nested_tree WHERE personal_folder=1 AND NOT parent_id = ".$row[0].
    " AND NOT title = ".$_SESSION['user_id']
);
foreach ($rows as $reccord) {
    if (!in_array($reccord['id'], $arrayPf)) {
        //build an array of personal folders ids
        array_push($arrayPf, $reccord['id']);
        //build also a string with those ids
        if (empty($listPf)) {
            $listPf = $reccord['id'];
        } else {
            $listPf .= ', '.$reccord['id'];
        }
    }
    $sLimit = "LIMIT ". intval($_GET['iDisplayStart']) .", ". intval($_GET['iDisplayLength']);
            $sOrder .= $aColumns[ intval($_GET['iSortCol_'.$i]) ]."
            ".$_GET['sSortDir_'.$i] .", ";

        "SELECT role_id FROM ".$pre."restriction_to_roles WHERE item_id = ".$reccord['id']
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || !isset($_SESSION['key']) || empty($_SESSION['key'])) {
    $data = $db->fetchRow("SELECT title FROM ".$pre."nested_tree WHERE id = ".$_POST['newparent_id']);
    $tmp = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."misc WHERE type = 'complex' AND intitule = '".$id[1]."'");
                $data = $db->fetchRow(
                    "SELECT COUNT(*) FROM ".$pre."nested_tree WHERE title = '".addslashes($title)."'"
                $data = $db->fetchRow("SELECT personal_folder FROM ".$pre."nested_tree WHERE id = '".$parentId."'");
                $data = $db->fetchRow(
            $data = $db->fetchRow("SELECT authorized FROM ".$pre."rights WHERE tree_id = '".$val[0]."' AND fonction_id= '".$val[1]."'");
        $data_fld = $db->fetchRow("SELECT title FROM ".$pre."nested_tree WHERE id = '".$_POST['folder']."'");
                    $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."nested_tree WHERE nlevel = ".($folderLevel+$startPathLevel)." AND title = \"".$fold."\" AND parent_id = ".$parent_id);
                        $data = $db->fetchRow("SELECT id FROM ".$pre."nested_tree WHERE nlevel = '".($folderLevel+$startPathLevel)."' AND title = '".$fold."' AND parent_id = '".$parent_id."'");
                    $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."items WHERE id_tree = '".$foldersArray[$item[1]]['id']."' AND label = \"".$item[2]."\"");

                        $data = $db->fetchRow("SELECT title FROM ".$pre."nested_tree WHERE id = '".$folderId."'");
                $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."items WHERE label = '".addslashes($label)."' AND inactif=0");
                                    WHERE i.field_id = '".$field_data[0]."'
                                    AND i.item_id=".$dataReceived['id']
                        $dataTmp = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."automatic_del WHERE item_id = '".$dataReceived['id']."'");
            $dataDeleted = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."log_items WHERE id_item = '".$_POST['id']."' AND action = 'at_delete'");
            $dataRestored = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."log_items WHERE id_item = '".$_POST['id']."' AND action = 'at_restored'");
        	"SELECT *
            /*
        * CASE
        * Generate a password
        */
        case "pw_generate":
            $pwgen = new SplClassLoader('Encryption\PwGen', '../includes/libraries');
            $pwgen->register();
            $pwgen = new Encryption\PwGen\pwgen();
            // Set pw size
            $pwgen->setLength($_POST['size']);
            // Include at least one number in the password
            $pwgen->setNumerals(($_POST['num'] == "true")? true : false);
            // Include at least one capital letter in the password
            $pwgen->setCapitalize(($_POST['maj'] == "true")? true : false);
            // Include at least one symbol in the password
            $pwgen->setSymbols(($_POST['symb'] == "true")? true : false);
            // Complete random, hard to memorize password
            if (isset($_POST['secure']) && $_POST['secure'] == "true") {
                $pwgen->setSecure(true);
                $pwgen->setSymbols(true);
                $pwgen->setCapitalize(true);
                $pwgen->setNumerals(true);
            } else {
                $pwgen->setSecure(false);
            }
            echo prepareExchangedData(array("key" => $pwgen->generate()), "encode");
            break;

                $data = $db->fetchRow("SELECT id, title FROM ".$pre."nested_tree WHERE title = '".addslashes($title)."'");
            $tmp = $db->fetchRow(
                $data_count = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."items WHERE inactif = 0");
                $whereArg = " AND i.id_tree=".$_POST['id'];
                $dataTmp = $db->fetchRow("SELECT timestamp, user_id FROM ".$pre."items_edition WHERE item_id = '".$_POST['item_id']."'");//echo ">".$dataTmp[0];
                    $dataTmp = $db->fetchRow("SELECT timestamp, user_id FROM ".$pre."items_edition WHERE item_id = '".$_POST['item_id']."'");
            $data = $db->fetchRow("SELECT valeur FROM ".$pre."misc WHERE type='complex' AND intitule = '".$_POST['groupe']."'");
            $data = $db->fetchRow("SELECT name,id_item,file FROM ".$pre."files WHERE id = '".$_POST['file_id']."'");
            $data = $db->fetchRow("SELECT date FROM ".$pre."log_items WHERE action = 'at_modification' AND id_item = '".$_POST['item_id']."' ORDER BY date DESC");
    $data = $db->fetchRow("SELECT bloquer_creation,bloquer_modification,personal_folder FROM ".$pre."nested_tree WHERE id = '".$groupe."'");
        !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || !isset($_SESSION['key']) || empty($_SESSION['key'])
        || !isset($_SESSION['settings']['enable_kb']) || $_SESSION['settings']['enable_kb'] != 1
) {
                $row = $db->query("SELECT anyone_can_modify, author_id FROM ".$pre."kb WHERE id = ".$id);
                $ret = $db->fetchArray($row);
                $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."kb_categories WHERE category = '".mysql_real_escape_string($category)."'");
            $row = $db->query(
                "SELECT k.id as id, k.label as label, k.description as description, k.category_id as category_id, k.author_id as author_id, k.anyone_can_modify as anyone_can_modify,
                u.login as login, c.category as category
                FROM ".$pre."kb as k
                INNER JOIN ".$pre."kb_categories as c ON (c.id = k.category_id)
                INNER JOIN ".$pre."users as u ON (u.id = k.author_id)
                WHERE k.id = '".$_POST['id']."'"
            $ret = $db->fetchArray($row);
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || !isset($_SESSION['key']) || empty($_SESSION['key'])) {
        $pf = $db->fetchRow("SELECT id FROM ".$pre."nested_tree WHERE title = '".$_SESSION['user_id']."'");
            $pf = $db->fetchRow("SELECT id FROM ".$pre."nested_tree WHERE title = '".$_SESSION['user_id']."'");
        $sql = "SELECT label, description, id_tree, perso, restricted_to, login
        $data = $db->fetchArray($row);
        $itemTags = $db->fetchAllArray("SELECT tag FROM ".$pre."tags WHERE item_id=".$id);
            "id='".$id."'"
        $sql = "SELECT i.label, i.description, i.id_tree as id_tree, i.perso, i.restricted_to, i.id, i.login
        $data = $db->fetchArray($row);
 * @author        Nils Laumaillé
 * @copyright     (c) 2009-2014 Nils Laumaillé
            $row = $db->fetchRow("SELECT email FROM ".$pre."users WHERE id=".$dataReceived['user_id']);
        $data = $db->fetchRow(
            "SELECT COUNT(*) FROM ".$pre."users WHERE email = '".
            mysql_real_escape_string(stripslashes(($_POST['email'])))."'"
            "&login=".$_POST['login']."\">".$_SESSION['settings']['cpassman_url'].
            "/index.php?action=password_recovery&key=".$key."&login=".$_POST['login']."</a>.<br><br>".$txt['thku'];
        $textMailAlt = $txt['forgot_pw_email_altbody_1']." ".$txt['at_login']." : ".$data['login']." - ".
                mysql_real_escape_string(stripslashes(($_POST['email'])))."'"
            $data = $db->fetchRow(
                "SELECT COUNT(*) FROM ".$pre."misc WHERE intitule = '".
                $_POST['login']."' AND type = 'password_recovery'"
                            'intitule' => $_POST['login']
                            'intitule' => $_POST['login'],
        $data = $db->fetchRow(
            $_POST['login']."' AND type = 'password_recovery'"
        if ($_POST['key'] == $data[0]) {
                "login = '".$_POST['login']."'"
                    'intitule' => $_POST['login'],
            $dataUser = $db->queryFirst("SELECT email FROM ".$pre."users WHERE login = '".$_POST['login']."'");
                    'user_language' => $_POST['lang']
            $_SESSION['user_language'] = $_POST['lang'];
            $_SESSION['user_language'] = $_POST['lang'];
        //Generate
        $pwgen->setLength($_POST['length']);
        $pwgen->setSecure($_POST['secure']);
        $pwgen->setSymbols($_POST['symbols']);
        $pwgen->setCapitalize($_POST['capitalize']);
        $pwgen->setNumerals($_POST['numerals']);
        echo Encryption\Crypt\aesctr::encrypt($pwgen->generate(), $_SESSION['key'], 256);
        $sql = "SELECT * FROM ".$pre."users WHERE login = '".addslashes($_POST['userId'])."'";
        $data = $db->fetchArray($row);
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || !isset($_SESSION['key']) || empty($_SESSION['key'])) {
            $tmp = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."roles_title WHERE title = '".mysql_real_escape_string(stripslashes($_POST['name']))."'");
            $tmp = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."roles_title WHERE id != '".$_POST['id']."' AND title = '".mysql_real_escape_string(stripslashes($_POST['title']))."'");
                        $count = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."roles_values WHERE folder_id = ".$node->id." AND role_id = ".$role);
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
 * @link          http://www.teampass.net
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || !isset($_SESSION['key']) || empty($_SESSION['key'])) {
            $data = $db->fetchRow("SELECT ".$_POST['type']." FROM ".$pre."users WHERE id = ".$val[0]);
            $data = $db->fetchRow("SELECT fonction_id FROM ".$pre."users WHERE id = $val[0]");
                $data = $db->fetchRow("SELECT id FROM ".$pre."nested_tree WHERE title = '".$_POST['id']."' AND personal_folder = 1");    // Get personal folder ID
            $data = $db->fetchRow("SELECT email FROM ".$pre."users WHERE id = '".$_POST['id']."'");
            $data_user = $db->fetchRow("SELECT fonction_id FROM ".$pre."users WHERE id = ".$_POST['id']);
            $data_user = $db->fetchRow("SELECT groupes_visibles FROM ".$pre."users WHERE id = ".$_POST['id']);
            $data_user = $db->fetchRow("SELECT groupes_interdits FROM ".$pre."users WHERE id = ".$_POST['id']);
            $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."nested_tree WHERE title = '".$_POST['domain']."' AND parent_id = 0");
            $data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."roles_title WHERE title = '".$_POST['domain']."'");
                    WHERE l.id_user = ".$_POST['id'].$sql_filter
                    WHERE l.id_user = ".$_POST['id'].$sql_filter."
                    LIMIT $start,".$_POST['nb_items_by_page']
                $data = $db->fetchRow(
                    "SELECT COUNT(*)
                    FROM ".$pre."log_system
                    WHERE type = 'user_mngt' AND field_1=".$_POST['id']
                $admin_folder = $db->queryFirst("SELECT id FROM ".$pre."nested_tree WHERE title='".$_SESSION['user_id']."' AND personal_folder = 1");
                $user_folder = $db->queryFirst("SELECT id FROM ".$pre."nested_tree WHERE title='".$user_id."' AND personal_folder = 1");
                        WHERE l.action = 'at_creation' AND i.perso=1 AND i.id_tree=".$folder->id
                    "id = ".$_POST['user_id']
                    "id = ".$reccord['id']
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || !isset($_SESSION['key']) || empty($_SESSION['key'])) {
            WHERE l.action = 'at_shown'".$sqlFilter
            WHERE l.action = 'at_copy'".$sqlFilter
            WHERE i.label LIKE '%".$_POST['filter']."%'"
            WHERE l.type = 'admin_action'".$sqlFilter
                    "AND date BETWEEN '".strtotime($_POST['purgeFrom'])."' AND '".strtotime($_POST['purgeTo'])."'"
                    "AND date BETWEEN '".strtotime($_POST['purgeFrom'])."' AND '".
                    strtotime($_POST['purgeTo'])."'"
                    "AND date BETWEEN '".strtotime($_POST['purgeFrom'])."' AND '".
                    strtotime($_POST['purgeTo'])."'"
                    "AND date BETWEEN '".strtotime($_POST['purgeFrom'])."' AND '".
                    strtotime($_POST['purgeTo'])."'"
                            numerals   : true,
                            var pw = htmlspecialchars_decode(aes_decrypt(data));
                        	$("#change_user_pw_newpw_confirm, #change_user_pw_newpw").val(pw);
                    		$("#change_user_pw_newpw").focus();
        "sources/items.queries.php",
            type    : "pw_generate",
            data = $.parseJSON(data);
            $("#"+elem).val(data.key).focus();
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
 * @author        Nils Laumaillé
 * @copyright     (c) 2009-2014 Nils Laumaillé

if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
include $_SESSION['settings']['cpassman_dir'].'/includes/include.php';
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
Fixed code: if (
    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
{
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "users.php")) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    include 'error.php';
    exit();
}

if (
    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
{
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], curPage())) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    include 'error.php';
    exit();
}

    //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."misc WHERE type='".$type."' AND intitule = '".$setting."'");
    $data = $db->queryCount(
        "misc",
        array(
            "type" => $type,
            "intitule" => $setting
        )
    );
            //$data_time = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."misc WHERE type='".$type."' AND intitule = '".$setting."_time'");
            $data_time = $db->queryCount(
                "misc",
                array(
                    "type" => $type,
                    "intitule" => $setting."_time"
                )
            );
//$nb_emails = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."emails WHERE status = 'not_sent' OR status = ''");
$nb_emails = $db->queryCount(
    "emails",
    "status = 'not_sent' OR status = ''"
);
            //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."nested_tree WHERE personal_folder=0 AND id = ".$folder->id);
            $data = $db->queryCount(
                "nested_tree",
                array(
                    "personal_folder" => 0,
                    "id" => $folder->id
                )
            );
 #xxx - Off-line mode, link make the page scroll up
 * @file          datatable.logs.php
 * @author        Nils Laumaillé
 * @copyright     (c) 2009-2014 Nils Laumaillé
if (
    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 ||
    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
    !isset($_SESSION['key']) || empty($_SESSION['key']))
{
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_views")) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    include 'error.php';
    exit();
}

        $sLimit = "LIMIT ". mysql_real_escape_string($_GET['iDisplayStart']) .", ". mysql_real_escape_string($_GET['iDisplayLength']) ."" ;
                $sOrder .= $aColumns[ intval(mysql_real_escape_string($_GET['iSortCol_'.$i])) ]."
                        '".mysql_real_escape_string($_GET['sSortDir_'.$i]) ."', ";
    } elseif (@$_SESSION['error']['code'] == ERR_VALID_SESSION) {
        echo '
        <div class="ui-state-error ui-corner-all error" style="text-align:center;" >'.$txt['error_not_authorized'].'<br /><br /><a href="index.php" />'.$txt['home'] .'</a></div>';
if (
    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
{
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], curPage())) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    include 'error.php';
    exit();
}

if (
    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
{
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], curPage())) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    include 'error.php';
    exit();
}

        //$data = $db->fetchRow("SELECT title FROM ".$pre."nested_tree WHERE id = ".$t->parent_id);
        $data = $db->queryGetRow(
            "nested_tree",
            array(
                "title"
            ),
            array(
                "id" => intval($t->parent_id)
            )
        );
        /*$node_data = $db->fetchRow(
        );*/
        $node_data = $db->queryGetRow(
            array(
                "misc" => "m",
                "nested_tree" => "n"
            ),
            array(
                "m.valeur" => "valeur",
                "n.renewal_period" => "renewal_period"
            ),
            array(
                "m.type" => "complex",
                "m.intitule" => intval(n.id),
                "m.intitule" => intval($t->id)
            )
        echo '
                <tr class="ligne0" id="row_'.$t->id.'">
                    <td align="center" onclick="open_edit_folder_dialog('.$t->id.')">'.$t->id.'</td>
                    <td width="50%" onclick="open_edit_folder_dialog('.$t->id.')">
                        '.$ident.'<span id="title_'.$t->id.'">'.$t->title.'</span>
                    </td>
                    <td align="center" onclick="open_edit_folder_dialog('.$t->id.')">
                        <span id="complexite_'.$t->id.'">'.@$pwComplexity[$node_data[0]][1].'</span>
                    </td>
                    <td align="center" onclick="open_edit_folder_dialog('.$t->id.')">
                        <span id="parent_'.$t->id.'">'.$data[0].'</span>
                    </td>
                    <td align="center" onclick="open_edit_folder_dialog('.$t->id.')">
                        '.$t->nlevel.'
                    </td>
                    <td align="center" onclick="open_edit_folder_dialog('.$t->id.')">
                        <span id="renewal_'.$t->id.'">'.$node_data[1].'</span>
                    </td>
                    <td align="center">
                        <img src="includes/images/folder--minus.png" onclick="supprimer_groupe(\''.$t->id.'\')" style="cursor:pointer;" />
                    </td>';
        //$data3 = $db->fetchRow("SELECT bloquer_creation,bloquer_modification FROM ".$pre."nested_tree WHERE id = ".$t->id);
        $data3 = $db->queryGetRow(
            array(
                "bloquer_creation",
                "bloquer_modification"
            ),
            "nested_tree",
            array(
                "id" => intval($t->id)
            )
        );
                    <td align="center">
                        <input type="checkbox" id="cb_droit_'.$t->id.'" onchange="Changer_Droit_Complexite(\''.$t->id.'\',\'creation\')"', isset($data3[0]) && $data3[0] == 1 ? 'checked' : '', ' />
                    </td>
                    <td align="center">
                        <input type="checkbox" id="cb_droit_modif_'.$t->id.'" onchange="Changer_Droit_Complexite(\''.$t->id.'\',\'modification\')"', isset($data3[1]) && $data3[1] == 1 ? 'checked' : '', ' />
                    </td>
                    <td>
                        <input type="hidden"  id="parent_id_'.$t->id.'" value="'.$t->parent_id.'" />
                        <input type="hidden"  id="renewal_id_'.$t->id.'" value="'.$node_data[0].'" />
                    </td>
            //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."log_items WHERE id_item = '".$record['id']."' AND action = 'at_delete'");
            $data = $db->queryCount(
                "log_items",
                array(
                    "id_item" => intval($record['id']),
                    "action" => "at_delete"
                )
            );
$txt['purge_done'] = "The purge has been performed!<br />Number of elements deleted: ";
    public function checkCode($secret, $code)
        $time = floor(time() / 30);
    }#-#fetchRow()

    #-#############################################
    # desc: builds the sql query
    # param: tables, inputs, conditions, extras
    # return: string SQL query
    public function prepareData($table, $data, $where, $extra = "", $inner = "")
    {
        $q = "SELECT ";

        // data
        $d = "";
        if (is_array($data)) {
            foreach ($data as $key => $val) {
                if (is_int($key)) {
                    $d .= "`".$this->escape($val)."`, ";
                } else {
                    if (strpos($key,'.') === false) {
                        $d .= "`$key` AS $val, ";
                    } else {
                        $d .= "$key AS $val, ";
                    }
                }
            }
            $q .= substr_replace($d, "", -2);
        } else {
            $d = $data." ";
        }

        // table
        if (is_array($table)) {
            $t = "";
            $q .= " FROM ";
            foreach ($table as $key => $val) {
                $t .= "`".$this->pre.$key."` AS ".$this->escape($val).", ";
            }
            $q .= substr_replace($t, "", -2)." ";
        } else {
            $q .= " FROM `".$this->pre.$table."` ";
        }

        // inner join conditions
        if (!empty($inner)) {
            $i = "";
            foreach ($inner as $key => $val) {
                $i .= "INNER JOIN ".$this->pre.$key." ON ".$val." ";
            }
            $q .= $i;
        }

        // where
        $w = "";
        foreach ($where as $key => $val) {
            if (strtolower($val) == 'null') {
                $w .= "`$key` = NULL, ";
            } elseif (strtolower($val)=='now()') {
                $w .= "`$key` = NOW(), ";
            } else {
                if (strpos($key,'.') === false) {
                    $w .= "`$key` = '".$this->escape($val)."' AND ";
                } else {
                    $w .= "$key = '".$this->escape($val)."' AND ";
                }
            }
        }

        // compile
        return rtrim($q, ', ').' WHERE '. rtrim($w, ' AND ') . $extra .';';
    }#-#prepareData()

    #-#############################################
    # desc: fetches and return result of one line
    # param: table (no prefix), array of fields to return, array for where conditions
    # return: (array) fetched record
    public function queryGetRow($table, $data, $where, $extra = "", $inner = "")
    {
        $q =  $this->prepareData($table, $data, $where, $extra, $inner);

        $query_id = $this->query($q);

        if (isset($this->query_id)) {
            $record = mysql_fetch_row($this->query_id);
        } else {
            $this->oops("Invalid query_id: <b>$this->query_id</b>. Records could not be fetched.");
        }

        $this->freeResult($query_id);

        return $record;
    }#-#queryGetRow()

    #-#############################################
    # desc: fetches and return result of one line
    # param: table (no prefix), array of fields to return, array for where conditions
    # return: (array) fetched record
    public function queryGetArray($table, $data, $where, $extra = "", $inner = "")
    {
        $q =  $this->prepareData($table, $data, $where, $extra, $inner);

        $query_id = $this->query($q);

        if (isset($this->query_id)) {
            $record = mysql_fetch_assoc($this->query_id) or die(mysql_error()." | ".$q);
        } else {
            $this->oops("Invalid query_id: <b>$this->query_id</b>. Records could not be fetched.");
        }

        $this->freeResult($query_id);

        return $record;
    }#-#queryGetRow()

    #-#############################################
    # desc: fetches and return the number of lines
    # param: table (no prefix), array of fields to return, array for where conditions
    # return: (array) fetched record
    public function queryCount($table, $where)
    {
        $q = "SELECT COUNT(*) FROM `".$this->pre.$table."` ";

        if (is_array($where)) {
            $w = "";
            foreach ($where as $key => $val) {
                if (strtolower($val) == 'null') {
                    $w .= "`$key` = NULL, ";
                } elseif (strtolower($val)=='now()') {
                    $w .= "`$key` = NOW(), ";
                } else {
                    $w .= "`$key`='".$this->escape($val)."' AND ";
                }
            }
        } else {
            $w = $where;
        }
        $q = rtrim($q, ', ').' WHERE '. rtrim($w, ' AND ') .';';

        $query_id = $this->query($q);
        $out = mysql_fetch_row($query_id);
        $this->freeResult($query_id);

        return $out;
    }


        } else {
$database = "tpssl";
@define('SECUREPATH', 'C:/nils.laumaille/utils/xamppssl/security');
require_once "C:/nils.laumaille/utils/xamppssl/security/sk.php";

    /*$dataLanguage =
        );*/
    $dataLanguage = $db->queryGetRow(
        "misc",
        array(
            "valeur"
        ),
        array(
            "type" => "admin",
            "intitule" => "default_language"
        )
    );
            <button title="'.$txt['login_copy'].'" id="menu_button_copy_login" class="copy_clipboard"><img src="includes/images/ui-text-field.png" id="div_copy_login" alt="" /></button>
            <br />
            <button title="'.$txt['url_copy'].'" style="margin-bottom:5px;" id="menu_button_copy_url" class="copy_clipboard"><img src="includes/images/ui-toolbar-bookmark.png" id="div_copy_url" alt="" /></button>
} elseif ((!isset($_SESSION['validite_pw']) || empty($_SESSION['validite_pw']) || empty($_SESSION['user_id'])) && isset($_GET['otv']) && $_GET['otv'] == "true") {
    // case where one-shot viewer
    if (isset($_GET['session']) && !empty($_GET['session'])) {
        include 'otv.php?session='.$_GET['session'];
    } else {
        $_SESSION['error']['code'] = ERR_VALID_SESSION;
        $_SESSION['initial_url'] = substr($_SERVER["REQUEST_URI"], strpos($_SERVER["REQUEST_URI"], "index.php?"));
        include 'error.php';
    }    
        "sources/main.queries.php",
            type    : "generate_a_password",
			data = prepareExchangedData(data, "decode");
           	if (data.error == "true") {
           		$("#div_dialog_message_text").html(data.error_msg);
           		$("#div_dialog_message").dialog("open");
           	} else {
           		$("#"+elem+"pw1").val(data.key).focus();
				$("#visible_pw").text(data.key);
           	}
        $("#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_url, #menu_button_copy_link").attr("disabled","disabled");
                        // #XXX
                        if (data.url != "") {
                            var clip = new ZeroClipboard.Client();
                            clip.setText(data.url);
                            clip.addEventListener('complete', function(client, text) {
                                    $("#message_box").html("<?php echo addslashes($txt['url_copied_clipboard']);?>").show().fadeOut(1000);
                            });
                            clip.glue('menu_button_copy_url');
                        }
if (
    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
{
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], curPage())) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    //include 'error.php';
    exit();
                //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."items WHERE inactif=0 AND id_tree = ".$node);
                $data = $db->queryCount(
                    "items",
                    array(
                        "inactif" => 0,
                        "id_tree" => intval($node)
                    )
                );
            //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."items WHERE inactif=0 AND id_tree = ".$folder->id);
            $data = $db->queryCount(
                "items",
                array(
                    "inactif" => 0,
                    "id_tree" => intval($folder->id)
                )
            );
</div><br />';
if (
        !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 ||
        !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) ||
        !isset($_SESSION['key']) || empty($_SESSION['key'])
        || $_SESSION['settings']['enable_kb'] != 1)
{
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], curPage())) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    include 'error.php';
    exit();
}

        // prepare data
        data = \'{"login":"\'+sanitizeString(login)+\'" ,\'+
            \'"key":"\'+sanitizeString(key)+\'"}\';
    		    data : prepareExchangedData(data, "encode")
        data = \'{"lang":"\'+sanitizeString(lang)+\'"}\';    		        
                type : "change_user_language",
                data : prepareExchangedData(data, "encode")
if (
    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
    !isset($_SESSION['key']) || empty($_SESSION['key'])
){
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], curPage())) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    include 'error.php';
    exit();
}

if (
    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
{
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_settings")) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    include 'error.php';
    exit();
}

            //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."nested_tree WHERE title = '".$record['id']."' AND parent_id = 0");
            $data = $db->queryCount(
                "nested_tree",
                array(
                    "title" => $record['id'],
                    "parent_id" => 0
                )
            );
            //$row = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."log_items WHERE id_item=".$item['id']." AND action = 'at_creation'");
            $row = $db->queryCount(
                "log_items",
                array(
                    "id_item" => $item['id'],
                    "action" => "at_creation"
                )
            );
            //$row = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."log_items WHERE id_item=".$item['id']." AND action = 'at_creation'");
            $row = $db->queryCount(
                "log_items",
                array(
                    "id_item" => $item['id'],
                    "action" => "at_creation"
                )
            );
            //$row = @$db->fetchRow("SELECT COUNT(*) FROM ".$pre."keys WHERE `id`='".$reccord['id']."' AND `table` = 'items'");
            $row = $db->queryCount(
                "keys",
                array(
                    "id" => $reccord['id'],
                    "table" => "items"
                )
            );
require_once('sessions.php');
if (
    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
{
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_settings")) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    include 'error.php';
    exit();
}

                    //$row = $db->fetchRow("SELECT title FROM ".$pre."nested_tree WHERE id=".$folder);
                    $row = $db->queryGetRow(
                        "nested_tree",
                        array(
                            "title"
                        ),
                        array(
                            "id" => intval($folder)
                        )
                    );
<?php
/**
 *
 * @file          checks.php
 * @author        Nils Laumaillé
 * @version       2.1.20
 * @copyright     (c) 2009-2014 Nils Laumaillé
 * @licensing     GNU AFFERO GPL 3.0
 * @link		  http://www.teampass.net
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */

$pagesRights = array(
    "user" => array(
        "home", "items", "find", "kb", "favourites"
    ),
    "manager" => array(
        "home", "items", "find", "kb", "favourites", "manage_roles", "manage_folders", "manage_views", "manage_users"
    ),
    "admin" => array(
        "home", "items", "find", "kb", "favourites", "manage_roles", "manage_folders", "manage_views", "manage_users", "manage_settings", "manage_main"
    )
);

function curPage()
{
    parse_str(substr($_SERVER["REQUEST_URI"], strpos($_SERVER["REQUEST_URI"], "?")+1), $result);
    return $result['page'];
}

function checkUser($userId, $userKey, $pageVisited)
{
    global $pagesRights;

    if (empty($userId) || empty($pageVisited) || empty($userKey)) {
        return false;
    }

    include $_SESSION['settings']['cpassman_dir'].'/includes/settings.php';
    require_once $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
    require_once $_SESSION['settings']['cpassman_dir'].'/sources/SplClassLoader.php';

    // Connect to mysql server
    $db = new SplClassLoader('Database\Core', $_SESSION['settings']['cpassman_dir'].'/includes/libraries');
    $db->register();
    $db = new Database\Core\DbCore($server, $user, $pass, $database, $pre);
    $db->connect();

    // load user's data
    /*$sql = "SELECT * FROM ".$pre."users WHERE id = '$userId'";
    $row = $db->query($sql);
    $data = $db->fetchArray($row);*/
    $data = $db->queryGetArray(
        "users",
        array(
            "login",
            "key_tempo",
            "admin",
            "gestionnaire"
        ),
        array(
            "id" => intval($userId)
        )
    );

    // check if user exists and tempo key is coherant
    if (empty($data['login']) || empty($data['key_tempo']) || $data['key_tempo'] != $userKey) {
        return false;
    }

    // check if user is allowed to see this page
    if (empty($data['admin']) && empty($data['gestionnaire']) && !in_array($pageVisited, $pagesRights['user'])) {
        return false;
    } else if (empty($data['admin']) && !empty($data['gestionnaire']) && !in_array($pageVisited, $pagesRights['manager'])) {
        return false;
    } else if (!empty($data['admin']) && !in_array($pageVisited, $pagesRights['admin'])) {
        return false;
    }

    return true;
}
    //$dataSession = $db->fetchRow("SELECT key_tempo FROM ".$pre."users WHERE id=".$_SESSION['user_id']);
    $dataSession = $db->queryGetRow(
        "users",
        array(
            "key_tempo"
        ),
        array(
            "id" => intval($_SESSION['user_id'])
        )
    );
    //$row = $db->fetchRow("SELECT valeur FROM ".$pre."misc WHERE type = 'admin' AND intitule = 'cpassman_version'");
    $row = $db->queryGetRow(
        "misc",
        array(
            "valeur"
        ),
        array(
            "type" => "admin",
            "intitule" => "cpassman_version"
        )
    );
    $data = $db->queryGetArray(
        "users",
        array(
            "admin",
            "gestionnaire",
            "groupes_visibles",
            "groupes_interdits",
            "fonction_id"
        ),
        array(
            "id" => intval($_SESSION['user_id'])
        )
    );
$queryCount = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."users WHERE timestamp >= '".intval((time() - 600))."'");
            $sOrder .= $aColumns[ intval(mysql_real_escape_string($_GET['iSortCol_'.$i])) ]."
    $sLimit = "LIMIT ". mysql_real_escape_string($_GET['iDisplayStart']) .", "
            . mysql_real_escape_string($_GET['iDisplayLength']) ;
            $sOrder .= $aColumns[ intval(mysql_real_escape_string($_GET['iSortCol_'.$i])) ]."
    //$ret_cat = $db->fetchRow("SELECT category FROM ".$pre."kb_categories WHERE id = ".$reccord['category_id']);
    $ret_cat = $db->queryGetRow(
        "kb_categories",
        array(
            "category"
        ),
        array(
            "id" => intval($reccord['category_id'])
        )
    );
    //$ret_author = $db->fetchRow("SELECT login FROM ".$pre."users WHERE id = ".$reccord['author_id']);
    $ret_author = $db->queryGetRow(
        "users",
        array(
            "login"
        ),
        array(
            "id" => intval($reccord['author_id'])
        )
    );
        $sLimit = "LIMIT ". mysql_real_escape_string($_GET['iDisplayStart']) .", "
                . mysql_real_escape_string($_GET['iDisplayLength']) ;
                $sOrder .= $aColumns[ intval(mysql_real_escape_string($_GET['iSortCol_'.$i])) ]."
    $sLimit = "LIMIT ". mysql_real_escape_string($_GET['iDisplayStart']) .", "
            . mysql_real_escape_string($_GET['iDisplayLength']);
            $sOrder .= $aColumns[ intval(mysql_real_escape_string($_GET['iSortCol_'.$i])) ]."
			<td align="center"><span class="span_pw" id="span_'.$elem['id'].'"><a href="#" onclick="decryptme('.$elem['id'].', \''.$encPw.'\');return false;">Decrypt </a></span><input type="hidden" id="hide_'.$elem['id'].'" value="'.$encPw.'" /></td>
            //$data = $db->fetchRow("SELECT favourites FROM ".$pre."users WHERE id = '".$_SESSION['user_id']."'");
            $data = $db->queryGetRow(
                "users",
                array(
                    "favourites"
                ),
                array(
                    "id" => intval($_SESSION['user_id'])
                )
            );
// $row = $db->fetchRow("SELECT id FROM ".$pre."nested_tree WHERE title = '".intval($_SESSION['user_id'])."'");
$row = $db->queryGetRow(
    "nested_tree",
    array(
        "id"
    ),
    array(
        "title" => intval($_SESSION['user_id'])
    )
);
if (empty($row[0])) {
	$rows = $db->fetchAllArray(
	    "SELECT id FROM ".$pre."nested_tree WHERE personal_folder=1 AND NOT parent_id = '".intval($row[0]).
	    "' AND NOT title = '".intval($_SESSION['user_id'])."'"
	);
	foreach ($rows as $reccord) {
		if (!in_array($reccord['id'], $arrayPf)) {
			//build an array of personal folders ids
			array_push($arrayPf, $reccord['id']);
			//build also a string with those ids
			if (empty($listPf)) {
				$listPf = $reccord['id'];
			} else {
				$listPf .= ', '.$reccord['id'];
			}
		}
	}

    $sLimit = "LIMIT ". intval($_GET['iDisplayStart']) .", ". intval($_GET['iDisplayLength'])."";
            $sOrder .= "".$aColumns[ intval($_GET['iSortCol_'.$i]) ]." "
            .mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
//echo $sOrder;
        "SELECT role_id FROM ".$pre."restriction_to_roles WHERE item_id = '".$reccord['id']."'"
if (
    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
{
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_folders")) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    include 'error.php';
    exit();
}

    // $data = $db->fetchRow("SELECT title FROM ".$pre."nested_tree WHERE id = ".$_POST['newparent_id']);
    $row = $db->queryGetRow(
        "nested_tree",
        array(
            "title"
        ),
        array(
            "id" => $_POST['newparent_id']
        )
    );
    //$tmp = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."misc WHERE type = 'complex' AND intitule = '".$id[1]."'");
    $tmp = $db->queryCount(
        "misc",
        array(
            "intitule" => $id[1],
            "type" => "complex"
        )
    );
                //$data = $db->fetchRow(
                //    "SELECT COUNT(*) FROM ".$pre."nested_tree WHERE title = '".addslashes($title)."'"
                //);
                $data = $db->queryCount(
                    "nested_tree",
                    array(
                        "title" => addslashes($title)
                    )
                // $data = $db->fetchRow("SELECT personal_folder FROM ".$pre."nested_tree WHERE id = '".$parentId."'");
                $row = $db->queryGetRow(
                    "nested_tree",
                    array(
                        "personal_folder"
                    ),
                    array(
                        "id" => intval($parentId)
                    )
                );
                /*$data = $db->fetchRow(
                );*/
                $data = $db->queryGetRow(
                    "nested_tree",
                    array(
                        "id",
                        "title"
                    ),
                    array(
                        "title" => addslashes($title)
                    )
            // $data = $db->fetchRow("SELECT authorized FROM ".$pre."rights WHERE tree_id = '".$val[0]."' AND fonction_id= '".$val[1]."'");
            $data = $db->queryGetRow(
                "rights",
                array(
                    "authorized"
                ),
                array(
                    "tree_id" => intval($val[0]),
                    "fonction_id" => intval($val[1])
                )
            );
        // $data_fld = $db->fetchRow("SELECT title FROM ".$pre."nested_tree WHERE id = '".$_POST['folder']."'");
        $data_fld = $db->queryGetRow(
            "nested_tree",
            array(
                "title"
            ),
            array(
                "id" => intval($_POST['folder'])
            )
        );
                    //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."nested_tree WHERE nlevel = ".($folderLevel+$startPathLevel)." AND title = \"".$fold."\" AND parent_id = ".$parent_id);
                    $data = $db->queryCount(
                        "nested_tree",
                        array(
                            "nlevel" => intval($folderLevel+$startPathLevel),
                            "title" => $fold,
                            "parent_id" => intval(parent_id)
                        )
                    );
                        // $data = $db->fetchRow("SELECT id FROM ".$pre."nested_tree WHERE nlevel = '".($folderLevel+$startPathLevel)."' AND title = '".$fold."' AND parent_id = '".$parent_id."'");
                        $row = $db->queryGetRow(
                            "nested_tree",
                            array(
                                "id"
                            ),
                            array(
                                "nlevel" => intval($folderLevel+$startPathLevel),
                                "title" => $fold,
                                "parent_id" => intval($parent_id)
                            )
                        );
                    //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."items WHERE id_tree = '".$foldersArray[$item[1]]['id']."' AND label = \"".$item[2]."\"");
                    $data = $db->queryCount(
                        "items",
                        array(
                            "id_tree" => intval($foldersArray[$item[1]]['id']),
                            "label" => $item[2]
                        )
                    );
                        // $data = $db->fetchRow("SELECT title FROM ".$pre."nested_tree WHERE id = '".$folderId."'");
                        $data = $db->queryGetRow(
                            "nested_tree",
                            array(
                                "title"
                            ),
                            array(
                                "id" => intval($folderId)
                            )
                        );
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "home")) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    //include 'error.php';
    exit();
}

                //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."items WHERE label = '".addslashes($label)."' AND inactif=0");
                $data = $db->queryCount(
                    "items",
                    array(
                        "label" => addslashes($label),
                        "inactif" => "0"
                    )
                );
                                    WHERE i.field_id = '".intval($field_data[0])."'
                                    AND i.item_id=".intval($dataReceived['id'])
                        //$dataTmp = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."automatic_del WHERE item_id = '".$dataReceived['id']."'");
                        $dataTmp = $db->queryCount(
                            "automatic_del",
                            array(
                                "item_id" => $dataReceived['id']
                            )
                        );
            //$dataDeleted = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."log_items WHERE id_item = '".$_POST['id']."' AND action = 'at_delete'");
            //$dataRestored = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."log_items WHERE id_item = '".$_POST['id']."' AND action = 'at_restored'");
            $dataDeleted = $db->queryCount(
                "log_items",
                array(
                    "id_item" => $_POST['id'],
                     "action" => "at_delete"
                )
            );
            $dataRestored = $db->queryCount(
                "log_items",
                array(
                    "id_item" => $_POST['id'],
                     "action" => "at_restored"
                )
            );
        	    "SELECT *
                // $data = $db->fetchRow("SELECT id, title FROM ".$pre."nested_tree WHERE title = '".addslashes($title)."'");
                $data = $db->queryGetRow(
                    "nested_tree",
                    array(
                        "title",
                        "id"
                    ),
                    array(
                        "title" => addslashes($title)
                    )
                );
            /*$tmp = $db->fetchRow(
            );*/
            $tmp = $db->queryGetRow(
                "nested_tree",
                array(
                    "title",
                    "parent_id",
                    "personal_folder"
                ),
                array(
                    "id" => intval($dataReceived['folder'])
                )
                //$data_count = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."items WHERE inactif = 0");
                $data_count = $db->queryCount(
                    "items",
                    array(
                        "inactif" => "0"
                    )
                );
                $whereArg = " AND i.id_tree=".intval($_POST['id']);
                // $dataTmp = $db->fetchRow("SELECT timestamp, user_id FROM ".$pre."items_edition WHERE item_id = '".$_POST['item_id']."'");//echo ">".$dataTmp[0];
                $dataTmp = $db->queryGetRow(
                    "items_edition",
                    array(
                        "timestamp",
                        "user_id"
                    ),
                    array(
                        "item_id" => intval($_POST['item_id'])
                    )
                );
                    // $dataTmp = $db->fetchRow("SELECT timestamp, user_id FROM ".$pre."items_edition WHERE item_id = '".$_POST['item_id']."'");
                    $dataTmp = $db->queryGetRow(
                        "items_edition",
                        array(
                            "timestamp",
                            "user_id"
                        ),
                        array(
                            "item_id" => intval($_POST['item_id'])
                        )
                    );
            // $data = $db->fetchRow("SELECT valeur FROM ".$pre."misc WHERE type='complex' AND intitule = '".$_POST['groupe']."'");
            $data = $db->queryGetRow(
                "misc",
                array(
                    "valeur"
                ),
                array(
                    "intitule" => $_POST['groupe'],
                    "type" => "complex"
                )
            );
            // $data = $db->fetchRow("SELECT name,id_item,file FROM ".$pre."files WHERE id = '".$_POST['file_id']."'");
            $data = $db->queryGetRow(
                "files",
                array(
                    "name",
                    "id_item",
                    "file"
                ),
                array(
                    "id" => intval($_POST['file_id'])
                )
            );
            // $data = $db->fetchRow("SELECT date FROM ".$pre."log_items WHERE action = 'at_modification' AND id_item = '".$_POST['item_id']."' ORDER BY date DESC");
            $data = $db->queryGetRow(
                "log_items",
                array(
                    "date"
                ),
                array(
                    "action" => "at_modification",
                    "id_item" => intval($_POST['item_id'])
                ),
                " ORDER BY date DESC"
            );
    // $data = $db->fetchRow("SELECT bloquer_creation,bloquer_modification,personal_folder FROM ".$pre."nested_tree WHERE id = '".$groupe."'");
    $data = $db->queryGetRow(
        "nested_tree",
        array(
            "bloquer_creation",
            "bloquer_modification",
            "personal_folder"
        ),
        array(
            "id" => intval($groupe)
        )
    );
        !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 ||
        !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) ||
        !isset($_SESSION['key']) || empty($_SESSION['key'])
        || !isset($_SESSION['settings']['enable_kb'])
        || $_SESSION['settings']['enable_kb'] != 1)
{
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "kb")) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    include 'error.php';
    exit();
}

                $ret = $db->queryGetArray(
                    "kb",
                    array(
                        "anyone_can_modify",
                        "author_id"
                    ),
                    array(
                        "id" => intval($id)
                    )
                );
                //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."kb_categories WHERE category = '".mysql_real_escape_string($category)."'");
                $data = $db->queryCount(
                    "kb_categories",
                    array(
                        "category" => $category
                    )
                );
            $ret = $db->queryGetArray(
                array(
                    "kb" => "k"
                ),
                array(
                    "k.id" => "id",
                    "k.label" => "label",
                    "k.description" => "description",
                    "k.category_id" => "category_id",
                    "k.author_id" => "author_id",
                    "k.anyone_can_modify" => "anyone_can_modify",
                    "u.login" => "login",
                    "c.category" => "category"
                ),
                array(
                    "k.id" => intval($_POST['id'])
                ),
                "",
                array(
                    "kb_categories AS c" => "(c.id = k.category_id)",
                    "users AS u" => "(u.id = k.author_id)"
                )
if (
    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
{
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_views")) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    include 'error.php';
    exit();
}


        // $pf = $db->fetchRow("SELECT id FROM ".$pre."nested_tree WHERE title = '".$_SESSION['user_id']."'");
        $pf = $db->queryGetRow(
            "nested_tree",
            array(
                "id"
            ),
            array(
                "title" => $_SESSION['user_id']
            )
        );
        // $pf = $db->fetchRow("SELECT id FROM ".$pre."nested_tree WHERE title = '".$_SESSION['user_id']."'");
        $pf = $db->queryGetRow(
            "nested_tree",
            array(
                "id"
            ),
            array(
                "title" => intval($_SESSION['user_id'])
            )
        );
        /*$sql = "SELECT label, description, id_tree, perso, restricted_to, login
        $data = $db->fetchArray($row);*/
        $ret = $db->queryGetArray(
            "items",
            array(
                "label",
                "description",
                "id_tree",
                "perso",
                "restricted_to",
                "login"
            ),
            array(
                "id" => intval($id)
            )
        );
        $itemTags = $db->fetchAllArray("SELECT tag FROM ".$pre."tags WHERE item_id=".intval($id));
            "id='".intval($id)."'"
        /*$sql = "SELECT i.label, i.description, i.id_tree as id_tree, i.perso, i.restricted_to, i.id, i.login
        $data = $db->fetchArray($row);*/
        $data = $db->queryGetArray(
            array(
                "items" => "i"
            ),
            array(
                "i.label" => "label",
                "i.description" => "description",
                "i.id_tree" => id_tree,
                "i.perso" => "perso",
                "i.restricted_to" => "restricted_to",
                "i.login" => "login",
                "i.id" => "id"
            ),
            array(
                "i.id" => intval($id),
                "l.action" => "at_creation"
            ),
            "",
            array(
                "log_items as l" => "(l.id_item = i.id)"
            )
        );
 * @author        Nils LaumaillÃ©
 * @copyright     (c) 2009-2014 Nils LaumaillÃ©
            // $row = $db->fetchRow("SELECT email FROM ".$pre."users WHERE id=".$dataReceived['user_id']);
            $row = $db->queryGetRow(
                "users",
                array(
                    "email"
                ),
                array(
                    "id" => intval($dataReceived['user_id'])
                )
            );
        $data = $db->queryCount(
            "users",
            array(
                "email" => mysql_real_escape_string(stripslashes($_POST['email']))
            )
            "&login=".mysql_real_escape_string($_POST['login'])."\">".$_SESSION['settings']['cpassman_url'].
            "/index.php?action=password_recovery&key=".$key."&login=".mysql_real_escape_string($_POST['login'])."</a>.<br><br>".$txt['thku'];
        $textMailAlt = $txt['forgot_pw_email_altbody_1']." ".$txt['at_login']." : ".mysql_real_escape_string($_POST['login'])." - ".
                mysql_real_escape_string(stripslashes($_POST['email']))."'"
            //$data = $db->fetchRow(
            //    "SELECT COUNT(*) FROM ".$pre."misc WHERE intitule = '".
            //    mysql_real_escape_string($_POST['login'])."' AND type = 'password_recovery'"
            //);
            $data = $db->queryCount(
                "misc",
                array(
                    "intitule" => $_POST['login'],
                    "type" => "password_recovery"
                )
                            'intitule' => mysql_real_escape_string($_POST['login'])
                            'intitule' => mysql_real_escape_string($_POST['login']),
        // decrypt and retreive data in JSON format
        $dataReceived = prepareExchangedData($_POST['data'], "decode");
        // Prepare variables
        $login = htmlspecialchars_decode($dataReceived['login']);
        $key = htmlspecialchars_decode($dataReceived['key']);
        /*$data = $db->fetchRow(
            mysql_real_escape_string($login)."' AND type = 'password_recovery'"
        );*/
        $data = $db->queryGetRow(
            "misc",
            array(
                "valeur"
            ),
            array(
                "type" => "password_recovery",
                "intitule" => $login
            )
        if ($key == $data[0]) {
                "login = '".mysql_real_escape_string($login)."'"
                    'intitule' => mysql_real_escape_string($login),
            $dataUser = $db->queryFirst("SELECT email FROM ".$pre."users WHERE login = '".mysql_real_escape_string($login)."'");
            // decrypt and retreive data in JSON format
            $dataReceived = prepareExchangedData($_POST['data'], "decode");
            // Prepare variables
            $language = $dataReceived['lang'];
                    'user_language' => $language
            $_SESSION['user_language'] = $language;
            $_SESSION['user_language'] = $language;
    	if ($_POST['size'] > $_SESSION['settings']['pwd_maximum_length']) {
    		echo prepareExchangedData(
	    		array(
		    		"error_msg" => "Password length is too long!",
		    		"error" => "true"
	    		),
	    		"encode"
    		);
    		break;
    	}

    	$pwgen->setLength($_POST['size']);
    	if (isset($_POST['secure']) && $_POST['secure'] == "true") {
    		$pwgen->setSecure(true);
    		$pwgen->setSymbols(true);
    		$pwgen->setCapitalize(true);
    		$pwgen->setNumerals(true);
    	} else {
    		$pwgen->setSecure(($_POST['secure'] == "true")? true : false);
    		$pwgen->setNumerals(($_POST['numerals'] == "true")? true : false);
    		$pwgen->setCapitalize(($_POST['capitalize'] == "true")? true : false);
    		$pwgen->setSymbols(($_POST['symbols'] == "true")? true : false);
    	}

        echo prepareExchangedData(
        	array(
	        	"key" => $pwgen->generate(),
	        	"error" => ""
        	),
        	"encode"
        );
        /*$sql = "SELECT * FROM ".$pre."users WHERE login = '".addslashes($_POST['userId'])."'";
        $data = $db->fetchArray($row);*/
        $data = $db->queryGetArray(
            "users",
            array(
                "login",
                "psk"
            ),
            array(
                "login" => $_POST['userId']
            )
        );
if (
    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
{
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_roles")) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    include 'error.php';
    exit();
}

            //$tmp = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."roles_title WHERE title = '".mysql_real_escape_string(stripslashes($_POST['name']))."'");
            $tmp = $db->queryCount(
                "roles_title",
                array(
                    "title" => stripslashes($_POST['name'])
                )
            );
            //$tmp = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."roles_title WHERE id != '".$_POST['id']."' AND title = '".mysql_real_escape_string(stripslashes($_POST['title']))."'");
            $tmp = $db->queryCount(
                "roles_title",
                array(
                    "title" => stripslashes($_POST['title']),
                    "id" => intval($_POST['id'])
                )
            );
                        //$count = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."roles_values WHERE folder_id = ".$node->id." AND role_id = ".$role);
                        $count = $db->queryCount(
                            "roles_values",
                            array(
                                "folder_id" => intval($node->id),
                                "role_id" => intval($role)
                            )
                        );
if (
        !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 ||
        !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) ||
        !isset($_SESSION['key']) || empty($_SESSION['key'])
) {
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "items")) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    handleError('Not allowed to ...', 110);
    exit();
}

if (
        !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 ||
        !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) ||
        !isset($_SESSION['key']) || empty($_SESSION['key'])
) {
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "items")) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    handleError('Not allowed to ...', 110);
    exit();
}

 * @link		http://www.teampass.net
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
if (
    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
{
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_users")) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    include 'error.php';
    exit();
}

            // $data = $db->fetchRow("SELECT ".$_POST['type']." FROM ".$pre."users WHERE id = ".$val[0]);
            $data = $db->queryGetRow(
                "users",
                array(
                    $_POST['type']
                ),
                array(
                    "id" => intval($val[0])
                )
            );
            // $data = $db->fetchRow("SELECT fonction_id FROM ".$pre."users WHERE id = $val[0]");
            $data = $db->queryGetRow(
                "users",
                array(
                    "fonction_id"
                ),
                array(
                    "id" => intval($val[0])
                )
            );
                // $data = $db->fetchRow("SELECT id FROM ".$pre."nested_tree WHERE title = '".$_POST['id']."' AND personal_folder = 1");    // Get personal folder ID
                $data = $db->queryGetRow(
                    "nested_tree",
                    array(
                        "id"
                    ),
                    array(
                        "title" => intval($_POST['id']),
                        "personal_folder" => "1"
                    )
                );
            // $data = $db->fetchRow("SELECT email FROM ".$pre."users WHERE id = '".$_POST['id']."'");
            $data = $db->queryGetRow(
                "users",
                array(
                    "email"
                ),
                array(
                    "id" => intval($_POST['id'])
                )
            );
            // $data_user = $db->fetchRow("SELECT fonction_id FROM ".$pre."users WHERE id = ".$_POST['id']);
            $data = $db->queryGetRow(
                "users",
                array(
                    "fonction_id"
                ),
                array(
                    "id" => intval($_POST['id'])
                )
            );
            // $data_user = $db->fetchRow("SELECT groupes_visibles FROM ".$pre."users WHERE id = ".$_POST['id']);
            $data_user = $db->queryGetRow(
                "users",
                array(
                    "groupes_visibles"
                ),
                array(
                    "id" => intval($_POST['id'])
                )
            );
            // $data_user = $db->fetchRow("SELECT groupes_interdits FROM ".$pre."users WHERE id = ".$_POST['id']);
            $data_user = $db->queryGetRow(
                "users",
                array(
                    "groupes_interdits"
                ),
                array(
                    "id" => intval($_POST['id'])
                )
            );
            //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."nested_tree WHERE title = '".$_POST['domain']."' AND parent_id = 0");
            $data = $db->queryCount(
                "nested_tree",
                array(
                    "title" => $_POST['domain'],
                    "parent_id" => "0"
                )
            );
            //$data = $db->fetchRow("SELECT COUNT(*) FROM ".$pre."roles_title WHERE title = '".$_POST['domain']."'");
            $data = $db->queryCount(
                "roles_title",
                array(
                    "title" => $_POST['domain']
                )
            );
                    WHERE l.id_user = ".intval($_POST['id'].$sql_filter)
                    WHERE l.id_user = ".intval($_POST['id'].$sql_filter)."
                    LIMIT ".intval($start).",".intval($_POST['nb_items_by_page'])
                //$data = $db->fetchRow(
                //    "SELECT COUNT(*)
                //    FROM ".$pre."log_system
                //    WHERE type = 'user_mngt' AND field_1=".$_POST['id']
                //);
                $data = $db->queryCount(
                    "log_system",
                    array(
                        "type" => "user_mngt",
                        "field_1" => $_POST['id']
                    )
                $admin_folder = $db->queryFirst("SELECT id FROM ".$pre."nested_tree WHERE title='".intval($_SESSION['user_id'])."' AND personal_folder = 1");
                $user_folder = $db->queryFirst("SELECT id FROM ".$pre."nested_tree WHERE title='".intval($user_id)."' AND personal_folder = 1");
                        WHERE l.action = 'at_creation' AND i.perso=1 AND i.id_tree=".intval($folder->id)
                    "id = ".intval($_POST['user_id'])
                    "id = ".intval($reccord['id'])
if (
    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
{
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_views")) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    include 'error.php';
    exit();
}

            WHERE l.action = 'at_shown'".mysql_real_escape_string($sqlFilter)
            WHERE l.action = 'at_copy'".mysql_real_escape_string($sqlFilter)
            WHERE i.label LIKE '%".mysql_real_escape_string($_POST['filter'])."%'"
            WHERE l.type = 'admin_action'".mysql_real_escape_string($sqlFilter)
                    "AND date BETWEEN '".intval(strtotime($_POST['purgeFrom']))."' AND '".intval(strtotime($_POST['purgeTo']))."'"
                    "AND date BETWEEN '".intval(strtotime($_POST['purgeFrom']))."' AND '".
                    intval(strtotime($_POST['purgeTo']))."'"
                    "AND date BETWEEN '".intval(strtotime($_POST['purgeFrom']))."' AND '".
                    intval(strtotime($_POST['purgeTo']))."'"
                    "AND date BETWEEN '".intval(strtotime($_POST['purgeFrom']))."' AND '".
                    intval(strtotime($_POST['purgeTo']))."'"
                            numerals   : true
                        	data = prepareExchangedData(data, "decode");
                        	if (data.error == "true") {
                        		$("#div_dialog_message_text").html(data.error_msg);
                        		$("#div_dialog_message").dialog("open");
                        	} else {
                        		$("#change_user_pw_newpw_confirm, #change_user_pw_newpw").val(pw);
                        		$("#change_user_pw_newpw").focus();
                        	}
        "sources/main.queries.php",
            type    : "generate_a_password",
        	data = prepareExchangedData(data, "decode");
        	if (data.error == "true") {
        		$("#div_dialog_message_text").html(data.error_msg);
        		$("#div_dialog_message").dialog("open");
        	} else {
        		$("#"+elem).val(data.key).focus();
        	}
if (
    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
{
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], curPage())) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    include 'error.php';
    exit();
}

if (
    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
{
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], curPage())) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    include 'error.php';
    exit();
}

 * @author        Nils LaumaillÃ©
 * @copyright     (c) 2009-2014 Nils LaumaillÃ©
if (
    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 ||
    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) ||
    !isset($_SESSION['key']) || empty($_SESSION['key']))
{
/* do checks */
include $_SESSION['settings']['cpassman_dir'].'/includes/include.php';
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_views")) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    include 'error.php';
    exit();
}

if (
    !isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || 
    !isset($_SESSION['user_id']) || empty($_SESSION['user_id']) || 
    !isset($_SESSION['key']) || empty($_SESSION['key'])) 
{
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'].'/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_views")) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED; //not allowed page
    include 'error.php';
    exit();
}