CVE-2014-3773 (published 2014-08-07T11:13Z)

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/.

Severity: HIGH
CVSS v2 base score: 7.5 (AV:N/AC:L/Au:N/C:P/I:P/A:P)

Weakness information:
cwe_id: CWE-89
cwe_name: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
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.
extended_description: 
            
            
         
         

Fix information:
repo_url: https://github.com/nilsteampassnet/TeamPass
commit_details: repo_url: https://github.com/nilsteampassnet/TeamPass
author: nils@teampass.net
author_date: 2014-05-03 08:06:26+02:00
msg: Security/API (beta) improvements
repository: repo_url: https://github.com/nilsteampassnet/TeamPass
repo_name: nilsteampassnet/TeamPass
description: Collaborative Passwords Manager
repo_language: PHP
owner: nilsteampassnet
file_changes: filename: admin.php
change_type: ModificationType.MODIFY
diff: @@ -42,8 +42,6 @@ echo '
             <h3>Some instructions</h3>
             <span class="ui-icon ui-icon-wrench" style="float: left; margin-right: .3em;">&nbsp;</span>
                 Access to <a target="_blank" href="http://www.teampass.net" style="font-weight:bold;font-style:italic;">TeamPass website</a><br />
-            <span class="ui-icon ui-icon-wrench" style="float: left; margin-right: .3em;">&nbsp;</span>
-                For any kind of Help and Support, please use the <a target="_blank" href="http://www.teampass.net/forum" style="font-weight:bold;font-style:italic;">Forum</a><br />
             <span class="ui-icon ui-icon-wrench" style="float: left; margin-right: .3em;">&nbsp;</span>
                 You discovered a Bug or you have an improvement Proposal, please use the <a target="_blank" href="https://github.com/nilsteampassnet/TeamPass/issues" style="font-weight:bold;font-style:italic;">Github channel</a>. <i>If you are not sure, always use the Forum before to obtain a confirmation. This will prevent having to much open tickets at Github</i>.<br />
             <div style="text-align:center;margin-top:10px;">

programming_language: PHP
filename: admin.settings_api.php
change_type: ModificationType.MODIFY
diff: @@ -230,7 +230,7 @@ function newIPDB()
 
 function ip_update(id, value, ip)
 {
-    $("#api_db_type").val("admin_action_api_save_key");
+    $("#api_db_type").val("admin_action_api_save_ip");
     $("#api_db_id").val(id);
     $("#api_db_action").val("update");
     $("#div_key").show();
@@ -261,6 +261,7 @@ $(function() {
 					$("#api_db_message").html("'.$txt['error_too_long'].'");
 					exit;
 				}
+
                 $("#div_loading").show();
                 var $this = $(this);
             	// send query

programming_language: PHP
filename: config.php
change_type: ModificationType.DELETE
diff: @@ -1,9 +0,0 @@
-<?php
-
-// Set Teampass path
-$teampass_path = "E:/xampp/htdocs/Teampass";
-// Set Teampass config file
-$teampass_config_file = $teampass_path."/includes/settings.php";
-// Set Teampass secure keys file path
-$teampass_sk_file = "/space/private/teampass/sk.php";
-?>

programming_language: unknown
filename: functions.php
change_type: ModificationType.MODIFY
diff: @@ -1,4 +1,19 @@
 <?php
+/**
+ *
+ * @file          configapi.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.
+ */
+
+$teampass_config_file = "../includes/settings.php";
 
 function teampass_api_enabled() {
 	$bdd = teampass_connect();
@@ -9,7 +24,7 @@ function teampass_api_enabled() {
 function teampass_whitelist() {
     $bdd = teampass_connect();
 	$apiip_pool = teampass_get_ips();
-	if (count($apiip_pool) > 0 && !array_search($_SERVER['REMOTE_ADDR'], $apiip_pool)) {
+	if (count($apiip_pool) > 0 && array_search($_SERVER['REMOTE_ADDR'], $apiip_pool) === false) {
 		rest_error('IPWHITELIST');
 	}
 }
@@ -169,36 +184,19 @@ function rest_get () {
 
 		if ($GLOBALS['request'][0] == "read") {
 			if($GLOBALS['request'][1] == "category") {
-				$array_category = explode(';',$GLOBALS['request'][2]);
-
-				foreach($array_category as $category) {
-					if(!preg_match_all("/^([\w\:\'\-\sàáâãäåçèéêëìíîïðòóôõöùúûüýÿ]+)$/i", $category,$result)) {
-						rest_error('CATEGORY_MALFORMED');
-					}
-				}
-
-				if(count($array_category) > 1 && count($array_category) < 5) {
-					for ($i = count($array_category); $i > 0; $i--) {
-						$slot = $i - 1;
-						if (!$slot) {
-							$category_query .= "select id from ".$GLOBALS['pre']."nested_tree where title LIKE '".$array_category[$slot]."' AND parent_id = 0";
-						} else {
-							$category_query .= "select id from ".$GLOBALS['pre']."nested_tree where title LIKE '".$array_category[$slot]."' AND parent_id = (";
-						}
-					}
-					for ($i = 1; $i < count($array_category); $i++) { $category_query .= ")"; }
-				} elseif (count($array_category) == 1) {
-					$category_query = "select id from ".$GLOBALS['pre']."nested_tree where title LIKE '".$array_category[0]."' AND parent_id = 0";
+				// get ids
+				if (strpos($GLOBALS['request'][2],",") > 0) {
+					$condition = "id_tree IN (".$GLOBALS['request'][2].")";
 				} else {
-					rest_error ('NO_CATEGORY');
+					$condition = "id_tree = '".$GLOBALS['request'][2]."'";
 				}
-				$response = $bdd->query("select id,label,login,pw from ".$GLOBALS['pre']."items where id_tree = (".$category_query.")");
+				$response = $bdd->query("select id,label,login,pw from ".$GLOBALS['pre']."items where ".$condition);
 				while ($data = $response->fetch())
 				{
 					$id = $data['id'];
 					$json[$id]['label'] = utf8_encode($data['label']);
 					$json[$id]['login'] = utf8_encode($data['login']);
-//					$json[$id]['pw'] = teampass_decrypt_pw($data['pw'],SALT,$rand_key);
+					$json[$id]['pw'] = teampass_decrypt_pw($data['pw'],SALT,$rand_key);
 				}
 			} elseif($GLOBALS['request'][1] == "item") {
 				$array_category = explode(';',$GLOBALS['request'][2]);
@@ -325,6 +323,4 @@ function teampass_decrypt_pw($encrypted, $salt, $rand_key, $itcount = 2072)
     $encrypted = substr($encrypted, 0, -64);
     if ($mac !== hash_hmac('sha256', $encrypted, $salt)) return null;
     return substr(rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, 'ctr', $iv), "\0\4"), strlen($rand_key));
-}
-
-?>
+}
\ No newline at end of file

programming_language: PHP
filename: index.php
change_type: ModificationType.MODIFY
diff: @@ -1,6 +1,19 @@
 <?php
+/**
+ *
+ * @file          indexapi.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.
+ */
 
-require_once('config.php');
+//require_once('config.php');
 require_once('functions.php');
 
 header('Content-Type: application/json');

programming_language: PHP
filename: include.php
change_type: ModificationType.MODIFY
diff: @@ -39,4 +39,4 @@ $mngPages = array(
     'manage_views' => 'views.php',
     'manage_main' => 'admin.php',
     'manage_settings' => 'admin.settings.php'
-);
+);
\ No newline at end of file

programming_language: PHP
filename: items.load.php
change_type: ModificationType.MODIFY
diff: @@ -2617,6 +2617,7 @@ function prepareOneTimeView()
         function(data) {
             //check if format error
             if (data[0].error == "") {
+				$("#div_dialog_message").dialog({minHeight:500,minWidth:750});
                 $("#div_dialog_message").dialog('open');
                 $("#div_dialog_message_text").html(data[0].url);
             } else {

programming_language: JavaScript
filename: items.php
change_type: ModificationType.MODIFY
diff: @@ -96,13 +96,13 @@ echo '
 <input type="hidden" id="pf_selected" />';
 // Hidden objects for Item search
 if (isset($_GET['group']) && isset($_GET['id'])) {
-    echo '<input type="hidden" name="open_folder" id="open_folder" value="'.$_GET['group'].'" />';
-    echo '<input type="hidden" name="open_id" id="open_id" value="'.$_GET['id'].'" />';
-    echo '<input type="hidden" name="recherche_group_pf" id="recherche_group_pf" value="', in_array($_GET['group'], $_SESSION['personal_visible_groups']) ? '1' : '', '" />';
+    echo '<input type="hidden" name="open_folder" id="open_folder" value="'.htmlspecialchars($_GET['group']).'" />';
+    echo '<input type="hidden" name="open_id" id="open_id" value="'.htmlspecialchars($_GET['id']).'" />';
+    echo '<input type="hidden" name="recherche_group_pf" id="recherche_group_pf" value="', in_array(htmlspecialchars($_GET['group']), $_SESSION['personal_visible_groups']) ? '1' : '', '" />';
 } elseif (isset($_GET['group']) && !isset($_GET['id'])) {
-    echo '<input type="hidden" name="open_folder" id="open_folder" value="'.$_GET['group'].'" />';
+    echo '<input type="hidden" name="open_folder" id="open_folder" value="'.htmlspecialchars($_GET['group']).'" />';
     echo '<input type="hidden" name="open_id" id="open_id" value="" />';
-    echo '<input type="hidden" name="recherche_group_pf" id="recherche_group_pf" value="', in_array($_GET['group'], $_SESSION['personal_visible_groups']) ? '1' : '', '" />';
+    echo '<input type="hidden" name="recherche_group_pf" id="recherche_group_pf" value="', in_array(htmlspecialchars($_GET['group']), $_SESSION['personal_visible_groups']) ? '1' : '', '" />';
 } else {
     echo '<input type="hidden" name="open_folder" id="open_folder" value="" />';
     echo '<input type="hidden" name="open_id" id="open_id" value="" />';
@@ -230,7 +230,7 @@ foreach ($folders as $folder) {
         	}
             // Prepare folder
             $folderTxt = '
-                    <li class="jstreeopen" id="li_'.$folder->id.'">';
+                    <li class="jstreeopen" id="li_'.$folder->id.'" title="ID ['.$folder->id.']">';
             if (in_array($folder->id, $_SESSION['groupes_visibles'])) {
                 $folderTxt .= '
                             <a id="fld_'.$folder->id.'" class="folder" onclick="ListerItems(\''.$folder->id.'\', \'\', 0);">'.$fldTitle.' (<span class="items_count" id="itcount_'.$folder->id.'">'.$itemsNb.'</span>';
@@ -358,7 +358,7 @@ echo '
                 <tr>
                     <td valign="top" class="td_title"><span class="ui-icon ui-icon-carat-1-e" style="float: left; margin-right: .3em;">&nbsp;</span>'.$txt['label'].' :</td>
                     <td>
-                        <input type="hidden" id="hid_label" value="', isset($dataItem) ? $dataItem['label'] : '', '" />
+                        <input type="hidden" id="hid_label" value="', isset($dataItem) ? htmlspecialchars($dataItem['label']) : '', '" />
                         <div id="id_label" style="display:inline;"></div>
                     </td>
                 </tr>';
@@ -367,7 +367,7 @@ echo '
                 <tr>
                     <td valign="top" class="td_title"><span class="ui-icon ui-icon-carat-1-e" style="float: left; margin-right: .3em;">&nbsp;</span>'.$txt['description'].' :</td>
                     <td>
-                        <div id="id_desc" style="font-style:italic;display:inline;"></div><input type="hidden" id="hid_desc" value="', isset($dataItem) ? $dataItem['description'] : '', '" />
+                        <div id="id_desc" style="font-style:italic;display:inline;"></div><input type="hidden" id="hid_desc" value="', isset($dataItem) ? htmlspecialchars($dataItem['description']) : '', '" />
                     </td>
                 </tr>';
 // Line for PW
@@ -455,7 +455,7 @@ if (isset($_SESSION['settings']['item_extra_fields']) && $_SESSION['settings']['
                     <tr class="tr_fields itemCatName_'.$itemCatName.'">
                         <td valign="top" class="td_title">&nbsp;&nbsp;<span class="ui-icon ui-icon-carat-1-e" style="float: left; margin: 0 .3em 0 15px; font-size:9px;">&nbsp;</span><i>'.$field[1].'</i> :</td>
                         <td>
-                            <div id="id_field_'.$field[0].'" style="display:inline;" class="fields_div"></div><input type="hidden" id="hid_field_'.$field[0].'" class="fields" />
+                            <div id="id_field_'.$field[0].'" style="display:inline;" class="fields_div"></div><input type="hidden" id="hid_field_'.htmlspecialchars($field[0]).'" class="fields" />
                         </td>
                     </tr>';
         }

programming_language: PHP
filename: otv.php
change_type: ModificationType.MODIFY
diff: @@ -70,6 +70,13 @@ if (
 
             // get data
             $pw = decrypt($dataItem['pw']);
+
+        	// get key for original pw
+        	$originalKey = $db->queryFirst('SELECT rand_key FROM `'.$pre.'keys` WHERE `table` LIKE "items" AND `id` ='.intval($_GET['item_id']));
+        	// unsalt previous pw
+        	$pw = substr(decrypt($dataItem['pw']), strlen($originalKey['rand_key']));
+
+
             $label = $dataItem['label'];
             $email = $dataItem['email'];
             $url = $dataItem['url'];

programming_language: PHP
filename: admin.queries.php
change_type: ModificationType.MODIFY
diff: @@ -919,6 +919,7 @@ switch ($_POST['type']) {
 				'api',
 				array(
 				    'label'     => $_POST['label'],
+					'value'     => $_POST['key'],
 				    'timestamp' => time()
 				),
 				"id='".intval($_POST['id'])."'"

programming_language: PHP
filename: datatable.item_edition.php
change_type: ModificationType.MODIFY
diff: @@ -31,6 +31,7 @@ $db->connect();
 
 //Columns name
 $aColumns = array('e.timestamp', 'u.login', 'i.label', 'u.name', 'u.lastname');
+$aSortTypes = array('ASC', 'DESC');
 
 //init SQL variables
 $sOrder = $sLimit = $sWhere = "";
@@ -39,19 +40,30 @@ $sOrder = $sLimit = $sWhere = "";
 //Paging
 $sLimit = "";
 if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
-    $sLimit = "LIMIT ". $_GET['iDisplayStart'] .", ". $_GET['iDisplayLength'] ;
+    $sLimit = "LIMIT ". filter_var($_GET['iDisplayStart'], FILTER_SANITIZE_NUMBER_INT) .", ". filter_var($_GET['iDisplayLength'], FILTER_SANITIZE_NUMBER_INT)."";
 }
 
 //Ordering
 
-if (isset($_GET['iSortCol_0'])) {
+if (isset($_GET['iSortCol_0']) && in_array($_GET['iSortCol_0'], $aSortTypes)) {
     $sOrder = "ORDER BY  ";
-    for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
+/*
+for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
         if ($_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true") {
             $sOrder .= $aColumns[ intval(mysql_real_escape_string($_GET['iSortCol_'.$i])) ]."
             ".mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
         }
     }
+*/
+	for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
+		if (
+			$_GET[ 'bSortable_'.filter_var($_GET['iSortCol_'.$i], FILTER_SANITIZE_NUMBER_INT)] == "true" &&
+			preg_match("#^(asc|desc)\$#i", $_GET['sSortDir_'.$i])
+		) {
+			$sOrder .= "".$aColumns[ filter_var($_GET['iSortCol_'.$i], FILTER_SANITIZE_NUMBER_INT) ]." "
+			.mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
+		}
+	}
 
     $sOrder = substr_replace($sOrder, "", -2);
     if ($sOrder == "ORDER BY") {

programming_language: PHP
filename: datatable.kb.php
change_type: ModificationType.MODIFY
diff: @@ -31,6 +31,7 @@ $db->connect();
 
 //Columns name
 $aColumns = array('id', 'category_id', 'label', 'description', 'author_id');
+$aSortTypes = array('ASC', 'DESC');
 
 //init SQL variables
 $sWhere = $sOrder = $sLimit = "";
@@ -39,20 +40,22 @@ $sWhere = $sOrder = $sLimit = "";
 //Paging
 $sLimit = "";
 if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
-    $sLimit = "LIMIT ". mysql_real_escape_string($_GET['iDisplayStart']) .", "
-            . mysql_real_escape_string($_GET['iDisplayLength']) ;
+    $sLimit = "LIMIT ". filter_var($_GET['iDisplayStart'], FILTER_SANITIZE_NUMBER_INT) .", ". filter_var($_GET['iDisplayLength'], FILTER_SANITIZE_NUMBER_INT)."";
 }
 
 //Ordering
 
-if (isset($_GET['iSortCol_0'])) {
+if (isset($_GET['iSortCol_0']) && in_array($_GET['iSortCol_0'], $aSortTypes)) {
     $sOrder = "ORDER BY  ";
-    for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
-        if ($_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true") {
-            $sOrder .= $aColumns[ intval(mysql_real_escape_string($_GET['iSortCol_'.$i])) ]."
-                    ".mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
-        }
-    }
+	for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
+		if (
+			$_GET[ 'bSortable_'.filter_var($_GET['iSortCol_'.$i], FILTER_SANITIZE_NUMBER_INT)] == "true" &&
+			preg_match("#^(asc|desc)\$#i", $_GET['sSortDir_'.$i])
+		) {
+			$sOrder .= "".$aColumns[ filter_var($_GET['iSortCol_'.$i], FILTER_SANITIZE_NUMBER_INT) ]." "
+			.mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
+		}
+	}
 
     $sOrder = substr_replace($sOrder, "", -2);
     if ($sOrder == "ORDER BY") {

programming_language: PHP
filename: datatable.logs.php
change_type: ModificationType.MODIFY
diff: @@ -33,6 +33,7 @@ $db->connect();
 if (isset($_GET['action']) && $_GET['action'] == "connections") {
     //Columns name
     $aColumns = array('l.date', 'l.label', 'l.qui', 'u.login');
+	$aSortTypes = array('ASC', 'DESC');
 
     //init SQL variables
     $sWhere = $sOrder = $sLimit = "";
@@ -41,20 +42,22 @@ if (isset($_GET['action']) && $_GET['action'] == "connections") {
     //Paging
     $sLimit = "";
     if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
-        $sLimit = "LIMIT ". mysql_real_escape_string($_GET['iDisplayStart']) .", "
-                . mysql_real_escape_string($_GET['iDisplayLength']) ;
+        $sLimit = "LIMIT ". filter_var($_GET['iDisplayStart'], FILTER_SANITIZE_NUMBER_INT) .", ". filter_var($_GET['iDisplayLength'], FILTER_SANITIZE_NUMBER_INT)."";
     }
 
     //Ordering
 
-    if (isset($_GET['iSortCol_0'])) {
+    if (isset($_GET['iSortCol_0']) && in_array($_GET['iSortCol_0'], $aSortTypes)) {
         $sOrder = "ORDER BY  ";
-        for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
-            if ($_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true") {
-                $sOrder .= $aColumns[ intval(mysql_real_escape_string($_GET['iSortCol_'.$i])) ]."
-                    ".mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
-            }
-        }
+    	for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
+    		if (
+    			$_GET[ 'bSortable_'.filter_var($_GET['iSortCol_'.$i], FILTER_SANITIZE_NUMBER_INT)] == "true" &&
+    			preg_match("#^(asc|desc)\$#i", $_GET['sSortDir_'.$i])
+    		) {
+    			$sOrder .= "".$aColumns[ filter_var($_GET['iSortCol_'.$i], FILTER_SANITIZE_NUMBER_INT) ]." "
+    			.mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
+    		}
+    	}
 
         $sOrder = substr_replace($sOrder, "", -2);
         if ($sOrder == "ORDER BY") {

programming_language: PHP
filename: datatable.users_logged.php
change_type: ModificationType.MODIFY
diff: @@ -33,6 +33,7 @@ $db->connect();
 
 //Columns name
 $aColumns = array('login', 'name', 'lastname', 'timestamp', 'last_connexion');
+$aSortTypes = array('ASC', 'DESC');
 
 //init SQL variables
 $sOrder = $sLimit = "";
@@ -41,20 +42,22 @@ $sOrder = $sLimit = "";
 //Paging
 $sLimit = "";
 if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
-    $sLimit = "LIMIT ". mysql_real_escape_string($_GET['iDisplayStart']) .", "
-            . mysql_real_escape_string($_GET['iDisplayLength']);
+    $sLimit = "LIMIT ". filter_var($_GET['iDisplayStart'], FILTER_SANITIZE_NUMBER_INT) .", ". filter_var($_GET['iDisplayLength'], FILTER_SANITIZE_NUMBER_INT)."";
 }
 
 //Ordering
 
-if (isset($_GET['iSortCol_0'])) {
+if (isset($_GET['iSortCol_0']) && in_array($_GET['iSortCol_0'], $aSortTypes)) {
     $sOrder = "ORDER BY  ";
-    for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
-        if ($_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true") {
-            $sOrder .= $aColumns[ intval(mysql_real_escape_string($_GET['iSortCol_'.$i])) ]."
-            ".mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
-        }
-    }
+	for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
+		if (
+			$_GET[ 'bSortable_'.filter_var($_GET['iSortCol_'.$i], FILTER_SANITIZE_NUMBER_INT)] == "true" &&
+			preg_match("#^(asc|desc)\$#i", $_GET['sSortDir_'.$i])
+		) {
+			$sOrder .= "".$aColumns[ filter_var($_GET['iSortCol_'.$i], FILTER_SANITIZE_NUMBER_INT) ]." "
+			.mysql_real_escape_string($_GET['sSortDir_'.$i]) .", ";
+		}
+	}
 
     $sOrder = substr_replace($sOrder, "", -2);
     if ($sOrder == "ORDER BY") {

programming_language: PHP
filename: find.queries.php
change_type: ModificationType.MODIFY
diff: @@ -84,7 +84,6 @@ if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
 if (isset($_GET['iSortCol_0']) && in_array($_GET['iSortCol_0'], $aSortTypes)) {
     $sOrder = "ORDER BY  ";
     for ($i=0; $i<intval($_GET['iSortingCols']); $i++) {
-
         if (
             $_GET[ 'bSortable_'.filter_var($_GET['iSortCol_'.$i], FILTER_SANITIZE_NUMBER_INT)] == "true" &&
             preg_match("#^(asc|desc)\$#i", $_GET['sSortDir_'.$i])

programming_language: PHP
filename: items.queries.php
change_type: ModificationType.MODIFY
diff: @@ -1249,7 +1249,7 @@ if (isset($_POST['type'])) {
                     $arrData['link'] = "&nbsp;<a href='".$dataItem['url']."' target='_blank'><img src='includes/images/arrow_skip.png' style='border:0px;' title='".$txt['open_url_link']."'></a>";
                 }
 
-                $arrData['description'] = preg_replace('/(?<!\\r)\\n+(?!\\r)/', '', strip_tags($dataItem['description'], $allowedTags));
+                $arrData['description'] = preg_replace('/(?<!\\r)\\n+(?!\\r)/', '', strip_tags($dataItem['description'], $k['allowedTags']));
                 $arrData['login'] = str_replace('"', '&quot;', $dataItem['login']);
                 $arrData['id_restricted_to'] = $listeRestriction;
                 $arrData['id_restricted_to_roles'] = count($listRestrictionRoles) > 0 ? implode(";", $listRestrictionRoles).";" : "";

programming_language: PHP
filename: users.queries.php
change_type: ModificationType.MODIFY
diff: @@ -373,8 +373,8 @@ if (!empty($_POST['type'])) {
                     'type' => 'user_mngt',
                     'date' => time(),
                     'label' => 'at_user_email_changed:'.$data[0],
-                    'qui' => $_SESSION['user_id'],
-                    'field_1' => $_POST['id']
+                    'qui' => intval($_SESSION['user_id']),
+                    'field_1' => intval($_POST['id'])
                    )
             );
         	echo '[{"error" : "no"}]';

programming_language: PHP
repo_url: https://github.com/nilsteampassnet/TeamPass
commit_details: repo_url: https://github.com/nilsteampassnet/TeamPass
author: nilsteampassnet
author_date: 2014-04-18 11:55:28+02:00
msg: 2.1.20
repository: repo_url: https://github.com/nilsteampassnet/TeamPass
repo_name: nilsteampassnet/TeamPass
description: Collaborative Passwords Manager
repo_language: PHP
owner: nilsteampassnet
file_changes: filename: admin.php
change_type: ModificationType.MODIFY
diff: @@ -12,10 +12,22 @@
  * 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;">';

programming_language: PHP
filename: admin.settings.php
change_type: ModificationType.MODIFY
diff: @@ -13,10 +13,22 @@
  * 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
 */
@@ -37,7 +49,14 @@ function updateSettings ($setting, $val, $type = '')
     $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",
@@ -69,7 +88,14 @@ function updateSettings ($setting, $val, $type = '')
         // 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",
@@ -1843,7 +1869,11 @@ echo '
                         </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>

programming_language: PHP
filename: admin.settings_categories.php
change_type: ModificationType.MODIFY
diff: @@ -189,7 +189,14 @@ echo '
         <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>';

programming_language: PHP
filename: changelog.md
change_type: ModificationType.MODIFY
diff: @@ -12,6 +12,7 @@
  #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"
 

programming_language: Markdown
filename: datatable.logs.php
change_type: ModificationType.MODIFY
diff: @@ -1,9 +1,9 @@
 <?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
  *
@@ -14,10 +14,22 @@
 
 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;
@@ -42,7 +54,7 @@ if (isset($_GET['action']) && $_GET['action'] == "connections") {
     //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
@@ -51,8 +63,8 @@ if (isset($_GET['action']) && $_GET['action'] == "connections") {
         $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]) ."', ";
             }
         }
 

programming_language: PHP
filename: error.php
change_type: ModificationType.MODIFY
diff: @@ -63,6 +63,9 @@ if (isset($_POST['session']) && $_POST['session'] == "expired") {
     } 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>';
     }
 }
 

programming_language: PHP
filename: find.php
change_type: ModificationType.MODIFY
diff: @@ -9,10 +9,22 @@
  * @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

programming_language: PHP
filename: folders.php
change_type: ModificationType.MODIFY
diff: @@ -13,10 +13,22 @@
  * 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*/
@@ -89,7 +101,16 @@ $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'];
         }
@@ -105,48 +126,74 @@ foreach ($tst as $t) {
             $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++;

programming_language: PHP
filename: home.php
change_type: ModificationType.MODIFY
diff: @@ -73,7 +73,14 @@ if (empty($_SESSION['last_pw_change']) || $_SESSION['validite_pw'] == false) {
         $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 />';

programming_language: PHP
filename: include.php
change_type: ModificationType.MODIFY
diff: @@ -13,7 +13,6 @@ 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";

programming_language: PHP
filename: english.php
change_type: ModificationType.MODIFY
diff: @@ -6,13 +6,6 @@ if (!isset($_SESSION['settings']['cpassman_url'])) {
     $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";
@@ -99,7 +92,7 @@ $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 (,)";

programming_language: PHP
filename: GoogleAuthenticator.php
change_type: ModificationType.MODIFY
diff: @@ -38,24 +38,14 @@ class GoogleAuthenticator
      * @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;
     }

programming_language: PHP
filename: DbCore.php
change_type: ModificationType.MODIFY
diff: @@ -167,7 +167,148 @@ class DbCore
         $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;
+    }
 
 
     #-#############################################
@@ -289,12 +430,12 @@ class DbCore
         }
 
         $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;
         }

programming_language: PHP
filename: settings.php
change_type: ModificationType.MODIFY
diff: @@ -6,10 +6,10 @@ global $server, $user, $pass, $database, $pre, $db;
 $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

programming_language: PHP
filename: index.php
change_type: ModificationType.MODIFY
diff: @@ -22,6 +22,7 @@ session_start();
 
 $_SESSION['CPM'] = 1;
 session_id();
+
 // Test if settings.file exists, if not then install
 if (!file_exists('includes/settings.php')) {
     echo '
@@ -54,11 +55,21 @@ 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";
@@ -278,7 +289,9 @@ if (isset($_SESSION['autoriser']) && $_SESSION['autoriser'] == true && isset($_G
             <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 />
@@ -443,6 +456,15 @@ if (isset($_SESSION['validite_pw']) && $_SESSION['validite_pw'] == true && !empt
     $_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 '

programming_language: PHP
filename: items.load.php
change_type: ModificationType.MODIFY
diff: @@ -339,9 +339,9 @@ function pwGenerate(elem)
     $("#"+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"),
@@ -351,9 +351,14 @@ function pwGenerate(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();
         }
    );
@@ -929,7 +934,7 @@ function AfficherDetailsItem(id, salt_key_required, expired_item, restricted, di
         $("#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;
     }
@@ -1157,6 +1162,15 @@ function AfficherDetailsItem(id, salt_key_required, expired_item, restricted, di
                             });
                             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);

programming_language: JavaScript
filename: items.php
change_type: ModificationType.MODIFY
diff: @@ -13,12 +13,20 @@
  * 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';
@@ -167,7 +175,14 @@ foreach ($folders as $folder) {
         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 (
@@ -189,7 +204,14 @@ foreach ($folders as $folder) {
                 $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
@@ -1010,6 +1032,6 @@ echo '
 echo '
 <div id="div_item_updated" style="display:none;">
     <div style="">'.$txt['item_updated_text'].'</div>
-</div>';
+</div><br />';
 
 require_once 'items.load.php';

programming_language: PHP
filename: kb.php
change_type: ModificationType.MODIFY
diff: @@ -12,13 +12,24 @@
  * 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';
 

programming_language: PHP
filename: load.php
change_type: ModificationType.MODIFY
diff: @@ -234,11 +234,13 @@ $htmlHeaders .= '
     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") {
@@ -284,11 +286,12 @@ $htmlHeaders .= '
     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") {

programming_language: PHP
filename: patch.php
change_type: ModificationType.DELETE
diff: @@ -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

programming_language: unknown
filename: roles.php
change_type: ModificationType.MODIFY
diff: @@ -12,10 +12,22 @@
  * 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';
 

programming_language: PHP
filename: admin.queries.php
change_type: ModificationType.MODIFY
diff: @@ -15,10 +15,22 @@
 
 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';
@@ -118,7 +130,14 @@ switch ($_POST['type']) {
             );
 
             //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(
@@ -194,7 +213,14 @@ switch ($_POST['type']) {
             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']);
@@ -370,7 +396,14 @@ switch ($_POST['type']) {
             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");
@@ -619,7 +652,14 @@ switch ($_POST['type']) {
         $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

programming_language: PHP
filename: categories.queries.php
change_type: ModificationType.MODIFY
diff: @@ -12,11 +12,24 @@
  * 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");
@@ -183,7 +196,16 @@ if (isset($_POST['type'])) {
                     );
                     
                     // 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 {

programming_language: PHP
filename: checks.php
change_type: ModificationType.ADD
diff: @@ -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

programming_language: PHP
filename: core.php
change_type: ModificationType.MODIFY
diff: @@ -145,7 +145,16 @@ if (
 
 /* 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] = "";
 }
@@ -191,7 +200,17 @@ 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 {
@@ -285,9 +304,19 @@ 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)) {
@@ -417,5 +446,5 @@ if (
 }
 
 /* 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

programming_language: PHP
filename: datatable.item_edition.php
change_type: ModificationType.MODIFY
diff: @@ -48,7 +48,7 @@ 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]) .", ";
         }
     }
@@ -68,7 +68,6 @@ if (isset($_GET['iSortCol_0'])) {
 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).") ";
 }

programming_language: PHP
filename: datatable.kb.php
change_type: ModificationType.MODIFY
diff: @@ -39,7 +39,8 @@ $sWhere = $sOrder = $sLimit = "";
 //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
@@ -48,7 +49,7 @@ 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]) .", ";
         }
     }
@@ -133,7 +134,16 @@ foreach ($rows as $reccord) {
     $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
@@ -147,7 +157,16 @@ foreach ($rows as $reccord) {
     }
     */
     //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

programming_language: PHP
filename: datatable.logs.php
change_type: ModificationType.MODIFY
diff: @@ -41,7 +41,8 @@ if (isset($_GET['action']) && $_GET['action'] == "connections") {
     //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
@@ -50,7 +51,7 @@ if (isset($_GET['action']) && $_GET['action'] == "connections") {
         $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]) .", ";
             }
         }

programming_language: PHP
filename: datatable.users_logged.php
change_type: ModificationType.MODIFY
diff: @@ -41,7 +41,8 @@ $sOrder = $sLimit = "";
 //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
@@ -50,7 +51,7 @@ 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]) .", ";
         }
     }

programming_language: PHP
filename: export.queries.php
change_type: ModificationType.MODIFY
diff: @@ -472,7 +472,7 @@ Enter the decryption key : <input type="password" id="saltkey" />
 			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>

programming_language: PHP
filename: favourites.queries.php
change_type: ModificationType.MODIFY
diff: @@ -34,7 +34,16 @@ if (!empty($_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();

programming_language: PHP
filename: find.queries.php
change_type: ModificationType.MODIFY
diff: @@ -38,33 +38,45 @@ $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
@@ -75,8 +87,8 @@ if (isset($_GET['iSortCol_0'])) {
             $_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]) .", ";
         }
     }
 
@@ -85,7 +97,7 @@ if (isset($_GET['iSortCol_0'])) {
             $sOrder = "";
     }
 }
-
+//echo $sOrder;
 /*
  * Filtering
  * NOTE this does not match the built-in DataTables filtering which does it
@@ -164,7 +176,7 @@ foreach ($rows as $reccord) {
     //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] != "") {

programming_language: PHP
filename: folders.queries.php
change_type: ModificationType.MODIFY
diff: @@ -14,10 +14,22 @@
 
 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");
@@ -86,7 +98,16 @@ if (isset($_POST['newtitle'])) {
         "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
@@ -98,7 +119,14 @@ if (isset($_POST['newtitle'])) {
     $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(
@@ -210,8 +238,14 @@ 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';
@@ -221,7 +255,16 @@ if (isset($_POST['newtitle'])) {
 
             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 {
@@ -319,8 +362,18 @@ 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" } ]';
@@ -367,7 +420,17 @@ if (isset($_POST['newtitle'])) {
             $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(

programming_language: PHP
filename: import.queries.php
change_type: ModificationType.MODIFY
diff: @@ -173,7 +173,16 @@ switch ($_POST['type']) {
         } 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);
@@ -613,7 +622,15 @@ switch ($_POST['type']) {
                     }
 
                     //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(
@@ -654,7 +671,18 @@ switch ($_POST['type']) {
                         $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];
                     }
 
@@ -705,8 +733,14 @@ switch ($_POST['type']) {
 
                 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();
@@ -767,7 +801,16 @@ switch ($_POST['type']) {
                         } 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(

programming_language: PHP
filename: items.queries.php
change_type: ModificationType.MODIFY
diff: @@ -18,6 +18,14 @@ if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || !isset($_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
  */
@@ -102,7 +110,14 @@ if (isset($_POST['type'])) {
                 // ;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 {
@@ -491,8 +506,8 @@ if (isset($_POST['type'])) {
                                     "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) {
@@ -567,7 +582,13 @@ 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']))) {
@@ -1024,8 +1045,22 @@ if (isset($_POST['type'])) {
             // 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");
@@ -1384,7 +1419,7 @@ if (isset($_POST['type'])) {
         case "showDetailsStep2":
         	// get Item info
         	$dataItem = $db->queryFirst(
-        	"SELECT *
+        	    "SELECT *
                 FROM ".$pre."items
                 WHERE id=".$_POST['id']
         	);
@@ -1528,34 +1563,6 @@ if (isset($_POST['type'])) {
         	);
         	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
@@ -1610,15 +1617,36 @@ if (isset($_POST['type'])) {
             // 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(
@@ -1724,8 +1752,14 @@ if (isset($_POST['type'])) {
             	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)) {
@@ -2106,7 +2140,17 @@ if (isset($_POST['type'])) {
         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']) &&
@@ -2115,7 +2159,17 @@ if (isset($_POST['type'])) {
                 ) {
                     $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)
@@ -2143,7 +2197,17 @@ if (isset($_POST['type'])) {
             }
 
             // 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];
@@ -2211,7 +2275,18 @@ if (isset($_POST['type'])) {
         */
         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']."'");
@@ -2582,7 +2657,18 @@ if (isset($_POST['type'])) {
         * 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" }';
@@ -2623,7 +2709,18 @@ if (isset($_GET['type'])) {
 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);

programming_language: PHP
filename: kb.queries.php
change_type: ModificationType.MODIFY
diff: @@ -15,12 +15,23 @@
 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';
@@ -69,8 +80,16 @@ if (!empty($_POST['type'])) {
 
             //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 {
@@ -81,7 +100,13 @@ if (!empty($_POST['type'])) {
             }
             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",
@@ -155,15 +180,29 @@ if (!empty($_POST['type'])) {
                 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(

programming_language: PHP
filename: logs.queries.php
change_type: ModificationType.MODIFY
diff: @@ -14,10 +14,22 @@
 
 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");

programming_language: PHP
filename: main.functions.php
change_type: ModificationType.MODIFY
diff: @@ -12,6 +12,7 @@
 if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1) {
     die('Hacking attempt...');
 }
+
 //define pbkdf2 iteration count
 @define('ITCOUNT', '2072');
 
@@ -299,7 +300,16 @@ function identifyUserRights($groupesVisiblesUser, $groupesInterditsUser, $isAdmi
             $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]);
@@ -433,7 +443,16 @@ function identifyUserRights($groupesVisiblesUser, $groupesInterditsUser, $isAdmi
             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
@@ -560,14 +579,28 @@ 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']." ";
@@ -600,18 +633,40 @@ function updateCacheTable($action, $id = "")
                 '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);

programming_language: PHP
filename: main.queries.php
change_type: ModificationType.MODIFY
diff: @@ -2,9 +2,9 @@
 /**
  *
  * @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
  *
@@ -144,7 +144,16 @@ switch ($_POST['type']) {
                    )
             );
             //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'],
@@ -780,27 +789,36 @@ switch ($_POST['type']) {
         $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(
@@ -810,7 +828,7 @@ switch ($_POST['type']) {
                     ),
                     array(
                             'type' => 'password_recovery',
-                            'intitule' => $_POST['login']
+                            'intitule' => mysql_real_escape_string($_POST['login'])
                     )
                 );
             } else {
@@ -819,7 +837,7 @@ switch ($_POST['type']) {
                     'misc',
                     array(
                             'type' => 'password_recovery',
-                            'intitule' => $_POST['login'],
+                            'intitule' => mysql_real_escape_string($_POST['login']),
                             'valeur' => $key
                     )
                 );
@@ -833,12 +851,27 @@ switch ($_POST['type']) {
         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();
@@ -860,19 +893,19 @@ switch ($_POST['type']) {
                 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
@@ -1018,18 +1051,22 @@ switch ($_POST['type']) {
      */
     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;
@@ -1125,26 +1162,60 @@ switch ($_POST['type']) {
      * 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 {

programming_language: PHP
filename: roles.queries.php
change_type: ModificationType.MODIFY
diff: @@ -14,10 +14,22 @@
 
 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");
@@ -41,7 +53,13 @@ if (!empty($_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',
@@ -79,7 +97,14 @@ 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",
@@ -221,7 +246,14 @@ if (!empty($_POST['type'])) {
                     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;

programming_language: PHP
filename: upload.attachments.php
change_type: ModificationType.MODIFY
diff: @@ -14,10 +14,22 @@
 
 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']);

programming_language: PHP
filename: upload.files.php
change_type: ModificationType.MODIFY
diff: @@ -14,10 +14,22 @@
 
 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']);

programming_language: PHP
filename: users.queries.php
change_type: ModificationType.MODIFY
diff: @@ -6,15 +6,31 @@
  * @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';
@@ -44,7 +60,16 @@ if (!empty($_POST['type'])) {
             $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]);
@@ -74,7 +99,16 @@ if (!empty($_POST['type'])) {
             $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]);
@@ -239,7 +273,17 @@ if (!empty($_POST['type'])) {
                        )
                 );
                 // 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);
@@ -304,7 +348,16 @@ if (!empty($_POST['type'])) {
                 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",
@@ -423,7 +476,16 @@ if (!empty($_POST['type'])) {
         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']);
@@ -484,7 +546,16 @@ if (!empty($_POST['type'])) {
         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();
@@ -574,7 +645,16 @@ if (!empty($_POST['type'])) {
 
             $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();
@@ -662,14 +742,27 @@ if (!empty($_POST['type'])) {
         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 {
@@ -697,7 +790,7 @@ if (!empty($_POST['type'])) {
                     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) {
@@ -711,16 +804,23 @@ if (!empty($_POST['type'])) {
                     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) {
@@ -779,9 +879,9 @@ if (!empty($_POST['type'])) {
                 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
@@ -800,7 +900,7 @@ if (!empty($_POST['type'])) {
                         "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']." - ";
@@ -841,7 +941,7 @@ if (!empty($_POST['type'])) {
                         'key_tempo' => "",
                         'session_end' => ""
                        ),
-                    "id = ".$_POST['user_id']
+                    "id = ".intval($_POST['user_id'])
                 );
             break;
 
@@ -864,7 +964,7 @@ if (!empty($_POST['type'])) {
                         'key_tempo' => "",
                         'session_end' => ""
                        ),
-                    "id = ".$reccord['id']
+                    "id = ".intval($reccord['id'])
                 );
             }
             break;

programming_language: PHP
filename: views.queries.php
change_type: ModificationType.MODIFY
diff: @@ -14,10 +14,22 @@
 
 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';
@@ -371,7 +383,7 @@ switch ($_POST['type']) {
             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);
@@ -426,7 +438,7 @@ switch ($_POST['type']) {
             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);
@@ -482,7 +494,7 @@ switch ($_POST['type']) {
             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);
@@ -543,7 +555,7 @@ switch ($_POST['type']) {
             "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);
@@ -685,7 +697,7 @@ switch ($_POST['type']) {
             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(
@@ -695,8 +707,8 @@ switch ($_POST['type']) {
             } 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(
@@ -706,8 +718,8 @@ switch ($_POST['type']) {
             } 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(
@@ -717,8 +729,8 @@ switch ($_POST['type']) {
             } 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(

programming_language: PHP
filename: users.load.php
change_type: ModificationType.MODIFY
diff: @@ -256,12 +256,17 @@ $(function() {
                             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();
                         }
                    );
@@ -407,9 +412,9 @@ $(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,
@@ -419,8 +424,13 @@ function pwGenerate(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();
+        	}
         }
    );
 }

programming_language: PHP
filename: users.php
change_type: ModificationType.MODIFY
diff: @@ -13,10 +13,22 @@
  * 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

programming_language: PHP
filename: views.php
change_type: ModificationType.MODIFY
diff: @@ -12,10 +12,22 @@
  * 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';
 

programming_language: PHP
filename: views_database.php
change_type: ModificationType.MODIFY
diff: @@ -1,9 +1,9 @@
 <?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
  *
@@ -14,14 +14,25 @@
 
 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';
 

programming_language: PHP
filename: views_logs.php
change_type: ModificationType.MODIFY
diff: @@ -15,10 +15,22 @@
 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';

programming_language: PHP