Просмотр исходного кода

we continue to transfer work from sql to parameterized queries for the frontend

Dmitriev Roman 3 месяцев назад
Родитель
Сommit
3a876bfd27
77 измененных файлов с 2032 добавлено и 1586 удалено
  1. 4 4
      html/admin/devices/index-tree-simple.php
  2. 4 4
      html/admin/devices/index-tree.php
  3. 21 7
      html/admin/devices/index.php
  4. 5 5
      html/admin/devices/mactable.php
  5. 8 8
      html/admin/devices/portmactable.php
  6. 4 4
      html/admin/devices/portsbyvlan.php
  7. 2 2
      html/admin/devices/snmpwalk.php
  8. 6 6
      html/admin/devices/switchport-conn.php
  9. 8 8
      html/admin/devices/switchport.php
  10. 13 13
      html/admin/devices/switchstatus.php
  11. 2 2
      html/admin/filters/editfilter.php
  12. 7 7
      html/admin/filters/editgroup.php
  13. 4 4
      html/admin/filters/groups.php
  14. 2 2
      html/admin/filters/index.php
  15. 5 5
      html/admin/filters/instances.php
  16. 8 8
      html/admin/groups/edit_group.php
  17. 5 5
      html/admin/groups/index.php
  18. 12 9
      html/admin/iplist/auto_rules.php
  19. 18 8
      html/admin/iplist/deleted.php
  20. 14 8
      html/admin/iplist/doubles.php
  21. 25 10
      html/admin/iplist/index.php
  22. 10 5
      html/admin/iplist/nagios.php
  23. 43 14
      html/admin/logs/authlog.php
  24. 16 7
      html/admin/logs/detaillog.php
  25. 20 10
      html/admin/logs/dhcp.php
  26. 62 22
      html/admin/logs/index.php
  27. 35 15
      html/admin/logs/ip.php
  28. 25 12
      html/admin/logs/mac.php
  29. 40 27
      html/admin/logs/syslog.php
  30. 49 14
      html/admin/logs/unknown.php
  31. 2 2
      html/admin/queues/index.php
  32. 66 23
      html/admin/reports/authday.php
  33. 56 40
      html/admin/reports/index-full.php
  34. 56 38
      html/admin/reports/index.php
  35. 72 29
      html/admin/reports/userday.php
  36. 23 8
      html/admin/reports/userdaydetail.php
  37. 56 17
      html/admin/reports/userdaydetaillog.php
  38. 110 78
      html/admin/reports/wan.php
  39. 6 6
      html/admin/users/edit_alias.php
  40. 5 5
      html/admin/users/edit_rules.php
  41. 25 25
      html/admin/users/editauth.php
  42. 30 28
      html/admin/users/edituser.php
  43. 49 15
      html/admin/users/index.php
  44. 171 166
      html/api.php
  45. 28 25
      html/inc/auth.php
  46. 18 10
      html/inc/authidfilter.php
  47. 12 8
      html/inc/buildingfilter.php
  48. 14 9
      html/inc/cidrfilter.php
  49. 12 3
      html/inc/common.php
  50. 1 1
      html/inc/datetimefilter.php
  51. 4 8
      html/inc/devmodelsfilter.php
  52. 4 8
      html/inc/devtypesfilter.php
  53. 3 8
      html/inc/dhcpfilter.php
  54. 3 8
      html/inc/dynfilter.php
  55. 3 8
      html/inc/enabledfilter.php
  56. 3 5
      html/inc/gatefilter.php
  57. 6 7
      html/inc/idfilter.php
  58. 3 8
      html/inc/iptypefilter.php
  59. 5 27
      html/inc/logfilter.php
  60. 3 20
      html/inc/loglevelfilter.php
  61. 3 24
      html/inc/oufilter.php
  62. 16 34
      html/inc/rulesfilter.php
  63. 4 8
      html/inc/search.php
  64. 18 12
      html/inc/sortfilter.php
  65. 5 8
      html/inc/subnetfilter.php
  66. 4 8
      html/inc/vendorfilter.php
  67. 127 138
      html/public/blocked.php
  68. 0 18
      html/sessions/.htaccess
  69. 132 156
      html/utils/auth_apply.php
  70. 96 18
      html/utils/auth_export.php
  71. 16 13
      html/utils/auth_remove.php
  72. 48 32
      html/utils/devices_apply.php
  73. 19 16
      html/utils/devices_remove.php
  74. 175 180
      html/utils/user_apply.php
  75. 19 13
      html/utils/user_remove.php
  76. 22 8
      install-eye.sh
  77. 2 2
      scripts/fetch_new_arp.pl

+ 4 - 4
html/admin/devices/index-tree-simple.php

@@ -40,13 +40,13 @@ foreach ($switches as $row) {
     $dev_hash[$dev_id]['type'] = $row['device_type'];
     $dev_hash[$dev_id]['model_name'] = $row['model_name'];
     $dev_hash[$dev_id]['parent_id'] = null; // инициализируем
-    $pSQL = 'SELECT * FROM device_ports WHERE uplink = 1 and device_id='.$dev_id;
-    $uplink = get_record_sql($db_link,$pSQL);
+    $pSQL = 'SELECT * FROM device_ports WHERE uplink = 1 and device_id=?';
+    $uplink = get_record_sql($db_link,$pSQL, [ $dev_id ]);
     if (empty($uplink)) { continue; }
     if (empty($uplink['target_port_id'])) { continue; }
     $dev_hash[$dev_id]['uplink'] = $uplink['port_name'];
-    $parentSQL = 'SELECT * FROM device_ports WHERE device_ports.id='.$uplink['target_port_id'];
-    $parent = get_record_sql($db_link,$parentSQL);
+    $parentSQL = 'SELECT * FROM device_ports WHERE device_ports.id=?';
+    $parent = get_record_sql($db_link,$parentSQL, [$uplink['target_port_id']]);
     // Защита от ссылки на самого себя
     if ($parent['device_id'] == $dev_id) {
         // Устройство ссылается само на себя - пропускаем эту связь

+ 4 - 4
html/admin/devices/index-tree.php

@@ -60,14 +60,14 @@ foreach ($switches as $row) {
     $dev_hash[$dev_id]['model_name'] = $row['model_name'];
     $dev_hash[$dev_id]['parent_id'] = null; // инициализируем
     
-    $pSQL = 'SELECT * FROM device_ports WHERE uplink = 1 and device_id='.$dev_id;
-    $uplink = get_record_sql($db_link,$pSQL);
+    $pSQL = 'SELECT * FROM device_ports WHERE uplink = 1 and device_id=?';
+    $uplink = get_record_sql($db_link,$pSQL, [ $dev_id ]);
     if (empty($uplink)) { continue; }
     if (empty($uplink['target_port_id'])) { continue; }
     
     $dev_hash[$dev_id]['uplink'] = $uplink['port_name'];
-    $parentSQL = 'SELECT * FROM device_ports WHERE device_ports.id='.$uplink['target_port_id'];
-    $parent = get_record_sql($db_link,$parentSQL);
+    $parentSQL = 'SELECT * FROM device_ports WHERE device_ports.id=?';
+    $parent = get_record_sql($db_link,$parentSQL, [$uplink['target_port_id']]);
     
     // Защита от ссылки на самого себя
     if ($parent['device_id'] == $dev_id) {

+ 21 - 7
html/admin/devices/index.php

@@ -19,10 +19,8 @@ if (isset($_POST["remove_device"])) {
 
 print_device_submenu($page_url);
 
-$sort_sql=" ORDER BY device_name";
-if (!empty($sort_field) and !empty($order)) { $sort_sql = " ORDER BY $sort_field $order"; }
-
 ?>
+
 <div id="cont">
 <br>
 <form name="def" action="index.php" method="post">
@@ -48,16 +46,32 @@ if (!empty($sort_field) and !empty($order)) { $sort_sql = " ORDER BY $sort_field
 </tr>
 <?php
 $filter = '';
-if ($f_building_id > 0) { $filter .= ' and building_id=' . $f_building_id; }
-if ($f_devtype_id >= 0) { $filter .= ' and device_type=' . $f_devtype_id; } else { $filter .= ' and device_type<=2'; }
-if ($f_devmodel_id > 0) { $filter .= ' and device_model_id=' . $f_devmodel_id; }
+$params=[];
+if ($f_building_id > 0) { $filter .= ' and building_id=?'; $params[]=$f_building_id; }
+if ($f_devtype_id >= 0) { $filter .= ' and device_type=?'; $params[]=$f_devtype_id; } else { $filter .= ' and device_type<=2'; }
+if ($f_devmodel_id > 0) { $filter .= ' and device_model_id=?'; $params[]= $f_devmodel_id; }
+
+#$countSQL = "SELECT COUNT(*)  FROM devices D
+#LEFT JOIN device_models DM ON D.device_model_id = DM.id
+#LEFT JOIN building B ON D.building_id = B.id
+#WHERE D.deleted = 0 $filter";
+#$count_records = get_single_field($db_link, $countSQL, $params);
+
+#$total=ceil($count_records/$displayed);
+#if ($page>$total) { $page=$total; }
+#if ($page<1) { $page=1; }
+#$start = ($page * $displayed) - $displayed;
+#print_navigation($page_url,$page,$displayed,$count_records,$total);
+
+$sort_sql=" ORDER BY device_name";
+if (!empty($sort_field) and !empty($order)) { $sort_sql = " ORDER BY $sort_field $order"; }
 
 $dSQL = 'SELECT D.*, DM.model_name, B.name AS building_name FROM devices D
 LEFT JOIN device_models DM ON D.device_model_id = DM.id
 LEFT JOIN building B ON D.building_id = B.id
 WHERE D.deleted = 0 ' . $filter . ' ' . $sort_sql;
 
-$switches = get_records_sql($db_link,$dSQL);
+$switches = get_records_sql($db_link,$dSQL, $params);
 foreach ($switches as $row) {
     print "<tr align=center>\n";
     $cl = "data";

+ 5 - 5
html/admin/devices/mactable.php

@@ -3,17 +3,17 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . HTML_LANG . ".php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
 
-$device=get_record($db_link,'devices',"id=".$id);
+$device=get_record($db_link,'devices',"id=?", [$id]);
 $snmp = getSnmpAccess($device);
-$user_info = get_record_sql($db_link,"SELECT * FROM user_list WHERE id=".$device['user_id']);
+$user_info = get_record_sql($db_link,"SELECT * FROM user_list WHERE id=?", [$device['user_id']]);
 
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
 
 print_device_submenu($page_url);
 print_editdevice_submenu($page_url,$id,$device['device_type'],$user_info['login']);
 
-$sSQL = "SELECT port, snmp_index FROM device_ports WHERE device_id=".$id;
-$ports_info = get_records_sql($db_link, $sSQL);
+$sSQL = "SELECT port, snmp_index FROM device_ports WHERE device_id=?";
+$ports_info = get_records_sql($db_link, $sSQL, [ $id ]);
 $ports_by_snmp_index=NULL;
 foreach ($ports_info as &$row) { $ports_by_snmp_index[$row["snmp_index"]]=$row["port"]; }
 
@@ -26,7 +26,7 @@ if (!apply_device_lock($db_link,$id)) {
 
 <div id="contsubmenu">
 <?php
-$ports = get_records($db_link,'device_ports',"device_id=$id AND uplink=0 ORDER BY port");
+$ports = get_records($db_link,'device_ports',"device_id=? AND uplink=0 ORDER BY port", [ $id ]);
 print "<b>".WEB_device_mac_table_show."&nbsp".$device['device_name']." (".$device['ip']."):</b>\n";
 
 $snmp_ok = 0;

+ 8 - 8
html/admin/devices/portmactable.php

@@ -4,8 +4,8 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . HTML_LANG . ".php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
 
 $port_id = $id;
-$sSQL = "SELECT DP.device_id, DP.port, DP.snmp_index, D.device_name, D.ip, D.vendor_id FROM device_ports AS DP, devices AS D WHERE D.id = DP.device_id AND DP.id=$port_id";
-$port_info = get_record_sql($db_link, $sSQL);
+$sSQL = "SELECT DP.device_id, DP.port, DP.snmp_index, D.device_name, D.ip, D.vendor_id FROM device_ports AS DP, devices AS D WHERE D.id = DP.device_id AND DP.id=?";
+$port_info = get_record_sql($db_link, $sSQL, [ $port_id ]);
 if (empty($port_info)) {
     header("Location: /admin/devices/editdevice.php?id=".$device_id);
     exit;
@@ -13,8 +13,8 @@ if (empty($port_info)) {
 
 $device_id = $port_info["device_id"];
 
-$sSQL = "SELECT port, snmp_index FROM device_ports WHERE device_id=".$device_id;
-$ports_info = get_records_sql($db_link, $sSQL);
+$sSQL = "SELECT port, snmp_index FROM device_ports WHERE device_id=?";
+$ports_info = get_records_sql($db_link, $sSQL, [$device_id]);
 if (empty($ports_info)) {
     header("Location: /admin/devices/editdevice.php?id=".$device_id);
     exit;
@@ -23,14 +23,14 @@ if (empty($ports_info)) {
 $ports_by_snmp_index=NULL;
 foreach ($ports_info as &$row) { $ports_by_snmp_index[$row["snmp_index"]]=$row["port"]; }
 
-$device=get_record($db_link,'devices',"id=".$device_id);
+$device=get_record($db_link,'devices',"id=?", [$device_id]);
 if (empty($device)) {
     header("Location: /admin/devices/index.php");
     exit;
 }
 
 $snmp = getSnmpAccess($device);
-$user_info = get_record_sql($db_link,"SELECT * FROM user_list WHERE id=".$device['user_id']);
+$user_info = get_record_sql($db_link,"SELECT * FROM user_list WHERE id=?", [$device['user_id']]);
 if (empty($user_info)) {
     header("Location: /admin/devices/index.php");
     exit;
@@ -57,7 +57,7 @@ print "<b>".$port_info['device_name']." [".$port_info['port']."] </b><br>\n";
 $sw_auth=NULL;
 $sw_mac=NULL;
 
-$sw_auth = get_record_sql($db_link,"SELECT mac FROM user_auth WHERE deleted=0 and ip='".$port_info['ip']."'");
+$sw_auth = get_record_sql($db_link,"SELECT mac FROM user_auth WHERE deleted=0 and ip=?", [ $port_info['ip'] ]);
 if (!empty($sw_auth)) {
     $sw_mac = mac_simplify($sw_auth['mac']);
     $sw_mac = preg_replace("/.{2}$/","",$sw_mac);
@@ -121,7 +121,7 @@ if (!empty($t_device)) {
     }
 }
 
-$maclist = get_records_sql($db_link, "SELECT mac,ts from unknown_mac where port_id=$port_id ORDER BY ts desc");
+$maclist = get_records_sql($db_link, "SELECT mac,ts from unknown_mac where port_id=? ORDER BY ts desc", [ $port_id ]);
 if (!empty($maclist)) {
     foreach ($maclist as $row) {
         print "<tr>";

+ 4 - 4
html/admin/devices/portsbyvlan.php

@@ -16,8 +16,8 @@ print_device_submenu($page_url);
 </form>
 
 <?php
-$countSQL="SELECT Count(*) FROM device_ports AS DP, devices AS D WHERE D.id = DP.device_id AND DP.vlan=$id";
-$count_records = get_single_field($db_link,$countSQL);
+$countSQL="SELECT Count(*) FROM device_ports AS DP, devices AS D WHERE D.id = DP.device_id AND DP.vlan=?";
+$count_records = get_single_field($db_link,$countSQL, [ $id ]);
 $total=ceil($count_records/$displayed);
 if ($page>$total) { $page=$total; }
 if ($page<1) { $page=1; }
@@ -31,8 +31,8 @@ print_navigation($page_url,$page,$displayed,$count_records,$total);
 <td><?php echo WEB_device_port_name; ?></td>
 </tr>
 <?php
-$sSQL = "SELECT DP.id, DP.port, DP.device_id, D.device_name FROM device_ports AS DP, devices AS D WHERE D.id = DP.device_id AND DP.vlan=$id";
-$ports_info = get_records_sql($db_link, $sSQL);
+$sSQL = "SELECT DP.id, DP.port, DP.device_id, D.device_name FROM device_ports AS DP, devices AS D WHERE D.id = DP.device_id AND DP.vlan=?";
+$ports_info = get_records_sql($db_link, $sSQL, [ $id ]);
 foreach ($ports_info as $row) {
     print "<tr>";
     print "<td class=\"data\"><a href=\"/admin/devices/editdevice.php?id=".$row['device_id']."\">" . $row['device_name']. "</a></td>\n";

+ 2 - 2
html/admin/devices/snmpwalk.php

@@ -3,9 +3,9 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . HTML_LANG . ".php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
 
-$device=get_record($db_link,'devices',"id=".$id);
+$device=get_record($db_link,'devices',"id=?", [ $id ]);
 $snmp = getSnmpAccess($device);
-$user_info = get_record_sql($db_link,"SELECT * FROM user_list WHERE id=".$device['user_id']);
+$user_info = get_record_sql($db_link,"SELECT * FROM user_list WHERE id=?", [ $device['user_id'] ]);
 
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
 print_device_submenu($page_url);

+ 6 - 6
html/admin/devices/switchport-conn.php

@@ -3,14 +3,14 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . HTML_LANG . ".php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
 
-$device=get_record($db_link,'devices',"id=".$id);
+$device=get_record($db_link,'devices',"id=?", [ $id ]);
 
 if (isset($_POST["remove"])) {
     $fid = $_POST["f_id"];
     foreach ($fid as $key => $val) {
         if (isset($val) and $val != 1) {
-                LOG_VERBOSE($db_link, "Remove connection id: $val ".dump_record($db_link,'connections','id='.$val));
-                delete_record($db_link, "connections", "id=" . $val);
+                LOG_VERBOSE($db_link, "Remove connection id: $val ".dump_record($db_link,'connections','id=?', [$val]));
+                delete_record($db_link, "connections", "id=?", [$val]);
             }
         }
         header("Location: " . $_SERVER["REQUEST_URI"]);
@@ -19,7 +19,7 @@ if (isset($_POST["remove"])) {
 
 unset($_POST);
 
-$user_info = get_record_sql($db_link,"SELECT * FROM user_list WHERE id=".$device['user_id']);
+$user_info = get_record_sql($db_link,"SELECT * FROM user_list WHERE id=?", [ $device['user_id'] ]);
 
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
 
@@ -43,11 +43,11 @@ print_editdevice_submenu($page_url,$id,$device['device_type'],$user_info['login'
 
 <?php
 
-$connections = get_records_sql($db_link,"SELECT C.* FROM connections as C,user_auth as A WHERE A.id=C.auth_id AND A.deleted=0 AND C.device_id=$id ORDER BY C.port_id ASC");
+$connections = get_records_sql($db_link,"SELECT C.* FROM connections as C,user_auth as A WHERE A.id=C.auth_id AND A.deleted=0 AND C.device_id=? ORDER BY C.port_id ASC", [ $id ]);
 foreach ($connections as $key => $value) {
 print "<tr align=center>\n";
 print "<td class=\"data\" style='padding:0'><input type=checkbox name=f_id[] value='{$value['id']}'></td>\n";
-$port = get_record($db_link,"device_ports","id=".$value['port_id']);
+$port = get_record($db_link,"device_ports","id=?", [$value['port_id']]);
 print "<td class=\"data\">". $port['port'] . "</a></td>\n";
 print "<td class=\"data\">";
 print_auth_detail($db_link, $value['auth_id']);

+ 8 - 8
html/admin/devices/switchport.php

@@ -5,13 +5,13 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
 
 if (isset($_POST["regensnmp"])) {
     $snmp_index = $_POST["f_snmp_start"] * 1;
-    $sSQL = "SELECT id,port from device_ports WHERE device_ports.device_id=$id ORDER BY id";
-    $flist = get_records_sql($db_link, $sSQL);
+    $sSQL = "SELECT id,port from device_ports WHERE device_ports.device_id=? ORDER BY id";
+    $flist = get_records_sql($db_link, $sSQL, [ $id ]);
     LOG_DEBUG($db_link, "Recalc snmp_index for device id: $id with start $snmp_index");
     foreach ($flist as $row) {
         $snmp = $row['port'] + $snmp_index - 1;
         $new['snmp_index'] = $snmp;
-        update_record($db_link, "device_ports", "id=".$row['id'], $new);
+        update_record($db_link, "device_ports", "id=?", $new, [$row['id']]);
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
@@ -45,7 +45,7 @@ if (isset($_POST['save'])) {
             if (intval($_POST['p_id'][$j]) != $save_id) { continue; }
             $new['port_name'] = $_POST['f_name'][$j];
             $new['snmp_index'] = $_POST['f_snmp_index'][$j]*1;
-            update_record($db_link, "device_ports", "id='{$save_id}'", $new);
+            update_record($db_link, "device_ports", "id=?", $new, [ $save_id ]);
             }
         }
     header("Location: " . $_SERVER["REQUEST_URI"]);
@@ -55,8 +55,8 @@ if (isset($_POST['save'])) {
 
 unset($_POST);
 
-$device=get_record($db_link,'devices',"id=".$id);
-$user_info = get_record_sql($db_link,"SELECT * FROM user_list WHERE id=".$device['user_id']);
+$device=get_record($db_link,'devices',"id=?", [$id]);
+$user_info = get_record_sql($db_link,"SELECT * FROM user_list WHERE id=?", [ $device['user_id'] ]);
 
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
 
@@ -87,8 +87,8 @@ print_editdevice_submenu($page_url,$id,$device['device_type'],$user_info['login'
 <td><?php echo WEB_cell_mac_count; ?></td>
 </tr>
 <?php
-$sSQL = "SELECT * FROM device_ports WHERE device_ports.device_id=$id ORDER BY port";
-$ports=get_records_sql($db_link,$sSQL);
+$sSQL = "SELECT * FROM device_ports WHERE device_ports.device_id=? ORDER BY port";
+$ports=get_records_sql($db_link,$sSQL, [ $id ]);
 foreach ($ports as $row) {
         print "<tr align=center>\n";
         $cl = "data";

+ 13 - 13
html/admin/devices/switchstatus.php

@@ -3,19 +3,19 @@ require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/auth.php");
 require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/languages/" . HTML_LANG . ".php");
 require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/idfilter.php");
 
-$device = get_record($db_link, 'devices', "id=" . $id);
+$device = get_record($db_link, 'devices', "id=?", [ $id ]);
 $snmp = getSnmpAccess($device);
-$device_model = get_record($db_link, 'device_models', "id=" . $device['device_model_id']);
+$device_model = get_record($db_link, 'device_models', "id=?", [ $device['device_model_id'] ]);
 
 if (isset($_POST["regensnmp"])) {
     $snmp_index = $_POST["f_snmp_start"] * 1;
-    $sSQL = "SELECT id,port from device_ports WHERE device_ports.device_id=$id ORDER BY id";
-    $flist = get_records_sql($db_link, $sSQL);
+    $sSQL = "SELECT id,port from device_ports WHERE device_ports.device_id=? ORDER BY id";
+    $flist = get_records_sql($db_link, $sSQL, [ $id ]);
     LOG_DEBUG($db_link, "Recalc snmp_index for device id: $id with start $snmp_index");
     foreach ($flist as $row) {
         $snmp = $row['port'] + $snmp_index - 1;
         $new['snmp_index'] = $snmp;
-        update_record($db_link, "device_ports", "id=".$row['id'], $new);
+        update_record($db_link, "device_ports", "id=?", $new, [$row['id']]);
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
@@ -25,8 +25,8 @@ if (isset($_POST['poe_on']) and $device['snmp_version'] > 0) {
     $len = is_array($_POST['poe_on']) ? count($_POST['poe_on']) : 0;
     for ($i = 0; $i < $len; $i++) {
         $port_index = intval($_POST['poe_on'][$i]);
-        $sSQL = "SELECT port from device_ports WHERE device_id=" . $id . " and snmp_index=" . $port_index;
-        $port = get_record_sql($db_link, $sSQL);
+        $sSQL = "SELECT port from device_ports WHERE device_id=? and snmp_index=?";
+        $port = get_record_sql($db_link, $sSQL, [ $id , $port_index ]);
         LOG_DEBUG($db_link, "Device id: " . $id . " enable poe at port " . $port['port'] . " snmp index " . $port_index);
         set_port_poe_state($device['vendor_id'], $port['port'], $port_index, $device['ip'], $snmp, 1);
     }
@@ -38,8 +38,8 @@ if (isset($_POST['poe_off']) and $device['snmp_version'] > 0) {
     $len = is_array($_POST['poe_off']) ? count($_POST['poe_off']) : 0;
     for ($i = 0; $i < $len; $i++) {
         $port_index = intval($_POST['poe_off'][$i]);
-        $sSQL = "SELECT port from device_ports WHERE device_id=" . $id . " and snmp_index=" . $port_index;
-        $port = get_record_sql($db_link, $sSQL);
+        $sSQL = "SELECT port from device_ports WHERE device_id=? and snmp_index=?";
+        $port = get_record_sql($db_link, $sSQL, [ $id , $port_index ]);
         LOG_DEBUG($db_link, "Device id: " . $id . " disable poe at port " . $port['port'] . " snmp index " . $port_index);
         set_port_poe_state($device['vendor_id'], $port['port'], $port_index, $device['ip'], $snmp, 0);
     }
@@ -76,7 +76,7 @@ if (!apply_device_lock($db_link, $id)) {
     exit;
 }
 
-$user_info = get_record_sql($db_link, "SELECT * FROM user_list WHERE id=" . $device['user_id']);
+$user_info = get_record_sql($db_link, "SELECT * FROM user_list WHERE id=?", [ $device['user_id'] ]);
 
 require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/header.php");
 
@@ -134,8 +134,8 @@ print_editdevice_submenu($page_url, $id, $device['device_type'], $user_info['log
         }
         print "<td>" . WEB_device_port_control . "</td>\n";
         print "</tr>\n";
-        $sSQL = "SELECT * FROM device_ports WHERE device_ports.device_id=$id ORDER BY port";
-        $ports = get_records_sql($db_link, $sSQL);
+        $sSQL = "SELECT * FROM device_ports WHERE device_ports.device_id=? ORDER BY port";
+        $ports = get_records_sql($db_link, $sSQL, [ $id ]);
         foreach ($ports as $row) {
             print "<tr align=center>\n";
             $cl = "down";
@@ -296,7 +296,7 @@ print_editdevice_submenu($page_url, $id, $device['device_type'], $user_info['log
 
             //fix port information
             if ($snmp_ok) {
-                update_record($db_link, "device_ports", "id=" . $row['id'], $new_info);
+                update_record($db_link, "device_ports", "id=?", $new_info, [  $row['id'] ]);
             }
 
             $ifname = compact_port_name($ifname);

+ 2 - 2
html/admin/filters/editfilter.php

@@ -10,7 +10,7 @@ if (isset($_POST["editfilter"])) {
     $new['dstport'] = str_replace(':', '-', $_POST["f_dstport"]);
     $new['srcport'] = str_replace(':', '-', $_POST["f_srcport"]);
     $new['description'] = $_POST["f_description"];
-    update_record($db_link, "filter_list", "id='$id'", $new);
+    update_record($db_link, "filter_list", "id=?", $new, [ $id ]);
     unset($_POST);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
@@ -20,7 +20,7 @@ unset($_POST);
 
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
 
-$filter = get_record($db_link, 'filter_list','id='.$id);
+$filter = get_record($db_link, 'filter_list','id=?', [ $id ]);
 
 print_filters_submenu($page_url);
 

+ 7 - 7
html/admin/filters/editgroup.php

@@ -7,14 +7,14 @@ if (isset($_POST["editgroup"])) {
     $new['group_name'] = $_POST["f_group_name"];
     $new['instance_id'] = $_POST["f_instance_id"]*1;
     $new['description'] = $_POST["f_group_description"];
-    update_record($db_link, "group_list", "id='$id'", $new);
+    update_record($db_link, "group_list", "id=?", $new, [ $id ]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
 }
 
 if (isset($_POST["addfilter"])) {
     $filter_id = $_POST["newfilter"] * 1;
-    $max_record = get_record_sql($db_link, "SELECT MAX(G.rule_order) as morder FROM group_filters as G where G.group_id='$id'");
+    $max_record = get_record_sql($db_link, "SELECT MAX(G.rule_order) as morder FROM group_filters as G where G.group_id=?", [ $id ]);
     if (empty($max_record)) {
         $forder = 1;
     } else {
@@ -33,7 +33,7 @@ if (isset($_POST["removefilter"])) {
     $f_group_filter = $_POST["f_group_filter"];
     foreach ($f_group_filter as $key => $val) {
         if (!empty($val)) {
-            delete_record($db_link, "group_filters", "id=" . $val * 1);
+            delete_record($db_link, "group_filters", "id=? ", [ $val ]);
         }
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);
@@ -57,7 +57,7 @@ if (isset($_POST["updateFilters"])) {
                 $new['action'] = $_POST["f_action"][$group_filter_id] * 1;
             }
             if (!empty($new)) {
-                update_record($db_link, "group_filters", "id=" . $group_filter_id, $new);
+                update_record($db_link, "group_filters", "id=?", $new, [ $group_filter_id ]);
             }
         }
     }
@@ -67,7 +67,7 @@ if (isset($_POST["updateFilters"])) {
 
 unset($_POST);
 
-$group = get_record_sql($db_link, "SELECT * FROM group_list WHERE id=" . $id);
+$group = get_record_sql($db_link, "SELECT * FROM group_list WHERE id=?", [ $id ]);
 
 print_filters_submenu($page_url);
 
@@ -107,8 +107,8 @@ require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/header.php");
             </tr>
 
             <?php
-            $sSQL = "SELECT G.id, G.filter_id, F.name, G.rule_order, G.action, F.description FROM group_filters G, filter_list F WHERE F.id=G.filter_id and group_id=$id ORDER BY G.rule_order";
-            $flist = get_records_sql($db_link, $sSQL);
+            $sSQL = "SELECT G.id, G.filter_id, F.name, G.rule_order, G.action, F.description FROM group_filters G, filter_list F WHERE F.id=G.filter_id and group_id=? ORDER BY G.rule_order";
+            $flist = get_records_sql($db_link, $sSQL, [ $id ]);
             foreach ($flist as $row) {
                 print "<tr align=center>\n";
                 print "<td class=\"data\" style='padding:0'><input type=checkbox name=f_group_filter[] value=" . $row['id'] . "></td>\n";

+ 4 - 4
html/admin/filters/groups.php

@@ -18,9 +18,9 @@ if (isset($_POST["remove"])) {
     $fgid = $_POST["fid"];
     foreach ($fgid as $key => $val) {
         if (!empty($val)) {
-            run_sql($db_link, "UPDATE user_auth SET filter_group_id=0, changed = 1 WHERE deleted=0 AND filter_group_id=" . $val * 1);
-            run_sql($db_link, "DELETE FROM group_filters WHERE group_id=" . $val * 1);
-            delete_record($db_link, "group_list", "id=" . $val * 1);
+            run_sql($db_link, "UPDATE user_auth SET filter_group_id=0, changed = 1 WHERE deleted=0 AND filter_group_id=?", [ $val ]);
+            run_sql($db_link, "DELETE FROM group_filters WHERE group_id=? ", [ $val ]);
+            delete_record($db_link, "group_list", "id=?", [ $val ]);
         }
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);
@@ -46,7 +46,7 @@ print_filters_submenu($page_url);
             <?php
             $groups = get_records_sql($db_link, 'SELECT * FROM group_list ORDER BY id');
             foreach ($groups as $row) {
-		$filter_instance = get_record_sql($db_link,'SELECT * FROM filter_instances WHERE id='.$row["instance_id"]);
+		$filter_instance = get_record_sql($db_link,'SELECT * FROM filter_instances WHERE id=?', [ $row["instance_id"] ]);
                 print "<tr align=center>\n";
                 print "<td class=\"data\" style='padding:0'><input type=checkbox name=fid[] value=" . $row["id"] . "></td>\n";
                 print "<td class=\"data\" ><input type=\"hidden\" name=\"" . $row["id"] . "\" value=" . $row["id"] . ">" . $row["id"] . "</td>\n";

+ 2 - 2
html/admin/filters/index.php

@@ -21,8 +21,8 @@ if (isset($_POST["remove"])) {
     $fid = $_POST["fid"];
     foreach ($fid as $key => $val) {
         if ($val) {
-            run_sql($db_link, "DELETE FROM group_filters WHERE filter_id=" . $val);
-            delete_record($db_link, "filter_list", "id=$val");
+            run_sql($db_link, "DELETE FROM group_filters WHERE filter_id=?", [ $val ]);
+            delete_record($db_link, "filter_list", "id=?", [ $val ]);
         }
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);

+ 5 - 5
html/admin/filters/instances.php

@@ -12,7 +12,7 @@ if (isset($_POST['save'])) {
             $id = intval($_POST['r_id'][$j]);
             $new['name'] = trim($_POST['f_name'][$j]);
             $new['description'] = trim($_POST['f_description'][$j]);
-            update_record($db_link, "filter_instances", "id='$id'", $new);
+            update_record($db_link, "filter_instances", "id=?", $new, [ $id ]);
         }
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);
@@ -34,12 +34,12 @@ if (isset($_POST["remove"])) {
     for ($i = 0; $i < $len; $i ++) {
         $id = intval($_POST['r_id'][$i]);
         if (!empty($id) and $id>1) {
-	    $deleted_groups = get_records_sql($db_link,"SELECT * FROM group_list WHERE instance_id>1 AND instance_id=".$id);
+	    $deleted_groups = get_records_sql($db_link,"SELECT * FROM group_list WHERE instance_id>1 AND instance_id=?", [ $id ]);
 	    foreach ($deleted_groups as $d_group) {
-	        run_sql($db_link, "UPDATE user_auth SET filter_group_id=0, changed = 1 WHERE deleted=0 AND filter_group_id=" . $d_group['id']);
-		delete_record($db_link, "group_list", "id=" . $d_group['id']);
+	        run_sql($db_link, "UPDATE user_auth SET filter_group_id=0, changed = 1 WHERE deleted=0 AND filter_group_id=?", [ $d_group['id'] ]);
+		delete_record($db_link, "group_list", "id=?", [ $d_group['id'] ]);
 		}
-            delete_record($db_link, "filter_instances", "id=" . $id * 1);
+            delete_record($db_link, "filter_instances", "id=?", [$id ]);
         }
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);

+ 8 - 8
html/admin/groups/edit_group.php

@@ -19,9 +19,9 @@ if (isset($_POST['save'])) {
             $tmp_life_duration = str_replace(',', '.',$_POST['f_life_duration']*1);
             if (!empty($tmp_life_duration) and is_numeric($tmp_life_duration)) { $new['life_duration'] = $tmp_life_duration; }
             } else { $new['life_duration']=0; }
-        if ($new['default_users'] == TRUE) { run_sql($db_link,"UPDATE ou set default_users=0 WHERE id!='{$id}'"); }
-        if ($new['default_hotspot'] == TRUE) { run_sql($db_link,"UPDATE ou set default_hotspot=0 WHERE id!='{$id}'"); }
-        update_record($db_link, "ou", "id='{$id}'", $new);
+        if ($new['default_users'] == TRUE) { run_sql($db_link,"UPDATE ou set default_users=0 WHERE id!=?", [ $id ]); }
+        if ($new['default_hotspot'] == TRUE) { run_sql($db_link,"UPDATE ou set default_hotspot=0 WHERE id!=?", [ $id ]); }
+        update_record($db_link, "ou", "id=?", $new, [ $id ]);
         header("Location: " . $_SERVER["REQUEST_URI"]);
 	exit;
 	}
@@ -30,8 +30,8 @@ if (isset($_POST["s_remove"])) {
     $s_id = $_POST["s_id"];
     foreach ($s_id as $key => $val) {
         if (isset($val)) {
-            LOG_INFO($db_link, "Remove rule id: $val ".dump_record($db_link,'auth_rules','id='.$val));
-            delete_record($db_link, "auth_rules", "id=" . $val);
+            LOG_INFO($db_link, "Remove rule id: $val ".dump_record($db_link,'auth_rules','id=?', [$val]));
+            delete_record($db_link, "auth_rules", "id=?", [ $val ]);
         }
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);
@@ -48,7 +48,7 @@ if (isset($_POST['s_save'])) {
             $new['type'] = $_POST['s_type'][$j];
             $new['rule'] = trim($_POST['s_rule'][$j]);
             $new['description'] = trim($_POST['s_description'][$j]);
-            update_record($db_link, "auth_rules", "id='{$save_id}'", $new);
+            update_record($db_link, "auth_rules", "id=?", $new, [ $save_id ]);
         }
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);
@@ -84,7 +84,7 @@ fix_auth_rules($db_link);
 <td><b><?php print WEB_cell_dynamic; ?></b></td>
 </tr>
 <?php
-$ou_info = get_record_sql($db_link,'SELECT * FROM ou WHERE id='.$id);
+$ou_info = get_record_sql($db_link,'SELECT * FROM ou WHERE id=?', [$id]);
 print "<tr align=center>\n";
 print "<td colspan=2 class=\"data\"><input type=\"text\" name='f_group_name' value='{$ou_info['ou_name']}' style=\"width:95%;\"></td>\n";
 if ($ou_info['default_users']) { $cl = "up"; } else { $cl="data"; }
@@ -135,7 +135,7 @@ if (!$ou_info['dynamic']) { print "disabled"; }; print " style=\"width:35%;\" ><
     <?php print "<td><button id='s_save' name='s_save'>".WEB_btn_save."</button></td>"; ?>
 </tr>
 <?php
-$t_auth_rules = get_records($db_link,'auth_rules',"ou_id=$id ORDER BY id");
+$t_auth_rules = get_records_sql($db_link,"SELECT * FROM auth_rules WHERE ou_id=? ORDER BY id", [ $id ]);
 foreach ( $t_auth_rules as $row ) {
     print "<tr align=center>\n";
     print "<td class=\"data\" style='padding:0'><input type=checkbox name=s_id[] value='{$row['id']}'></td>\n";

+ 5 - 5
html/admin/groups/index.php

@@ -6,10 +6,10 @@ if (isset($_POST["remove"])) {
     $fid = $_POST["f_id"];
     foreach ($fid as $key => $val) {
         if (isset($val) and $val > 0) {
-            run_sql($db_link, "UPDATE user_list SET ou_id=0 WHERE ou_id=$val");
-            run_sql($db_link, "UPDATE user_auth SET ou_id=0 WHERE ou_id=$val");
-            run_sql($db_link, "DELETE FROM auth_rules WHERE ou_id=$val");
-            delete_record($db_link, "ou", "id=" . $val);
+            run_sql($db_link, "UPDATE user_list SET ou_id=0 WHERE ou_id=?", [ $val ]);
+            run_sql($db_link, "UPDATE user_auth SET ou_id=0 WHERE ou_id=?", [ $val ]);
+            run_sql($db_link, "DELETE FROM auth_rules WHERE ou_id=?", [ $val ]);
+            delete_record($db_link, "ou", "id=?", [$val]);
             }
         }
     header("Location: " . $_SERVER["REQUEST_URI"]);
@@ -44,7 +44,7 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
 </td>
 </tr>
 <?php
-$t_ou = get_records($db_link,'ou','TRUE ORDER BY ou_name');
+$t_ou = get_records_sql($db_link,'SELECT * FROM ou ORDER BY ou_name');
 foreach ($t_ou as $row) {
     print "<tr align=center>\n";
     print "<td class=\"data\" style='padding:0'><input type=checkbox name=f_id[] value='{$row['id']}'></td>\n";

+ 12 - 9
html/admin/iplist/auto_rules.php

@@ -8,7 +8,7 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/rulesfilter.php");
 if (isset($_POST["removeRule"])) {
     $r_id = $_POST["f_id"];
     foreach ($r_id as $key => $val) {
-        if ($val) { delete_record($db_link, "auth_rules", "id=".$val); }
+        if ($val) { delete_record($db_link, "auth_rules", "id=?", [$val]); }
         }
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
@@ -44,16 +44,17 @@ print_ip_submenu($page_url);
 <?php
 
 $target_filter='';
+$params=[];
 if ($rule_target>0) {
     if ($rule_target==1) { $target_filter = ' AND user_id>0'; }
     if ($rule_target==2) { $target_filter = ' AND ou_id>0'; }
     }
 
 $type_filter='';
-if ($rule_type>0) { $type_filter = ' AND type='.$rule_type; }
+if ($rule_type>0) { $type_filter = ' AND type=?'; $params[]=$rule_type; }
 
 $rule_filter='';
-if (!empty($f_rule)) { $rule_filter = ' AND rule LIKE "'.$f_rule.'%"'; }
+if (!empty($f_rule)) { $rule_filter = ' AND rule LIKE ?'; $params[]=$f_rule.'%'; }
 
 $rule_filters = '';
 if (!empty($target_filter) or !empty($type_filter) or !empty($rule_filter)) {
@@ -62,7 +63,7 @@ if (!empty($target_filter) or !empty($type_filter) or !empty($rule_filter)) {
 
 fix_auth_rules($db_link);
 $countSQL="SELECT Count(*) FROM auth_rules $rule_filters";
-$count_records = get_single_field($db_link,$countSQL);
+$count_records = get_single_field($db_link,$countSQL, $params);
 $total=ceil($count_records/$displayed);
 if ($page>$total) { $page=$total; }
 if ($page<1) { $page=1; }
@@ -70,7 +71,6 @@ $start = ($page * $displayed) - $displayed;
 print_navigation($page_url,$page,$displayed,$count_records,$total);
 ?>
 
-
 <table class="data">
 <tr align="center">
 <td><input type="checkbox" onClick="checkAll(this.checked);"></td>
@@ -81,8 +81,11 @@ print_navigation($page_url,$page,$displayed,$count_records,$total);
 <td align=right><input type="submit" onclick="return confirm('<?php echo WEB_msg_delete; ?>?')" name="removeRule" value="<?php echo WEB_btn_delete; ?>"></td>
 </tr>
 <?php
-$rulesSQL = "SELECT * FROM auth_rules $rule_filters ORDER BY id LIMIT $displayed OFFSET $start";
-$t_auth_rules = get_records_sql($db_link,$rulesSQL);
+$rulesSQL = "SELECT * FROM auth_rules $rule_filters ORDER BY id LIMIT ? OFFSET ?";
+$params[]=$displayed;
+$params[]=$start;
+
+$t_auth_rules = get_records_sql($db_link,$rulesSQL, $params);
 foreach ( $t_auth_rules as $row ) {
     print "<tr align=center>\n";
     print "<td class=\"data\" style='padding:0'><input type=checkbox name=f_id[] value=".$row["id"]." ></td>\n";
@@ -94,11 +97,11 @@ foreach ( $t_auth_rules as $row ) {
     print "<td class=\"data\">".$row['rule']."</td>\n";
     print "<td colspan=2 class=\"data\" align=left>";
     if (!empty($row['user_id'])) {
-	$user_info=get_record_sql($db_link,"SELECT * FROM user_list WHERE id=".$row['user_id']);
+	$user_info=get_record_sql($db_link,"SELECT * FROM user_list WHERE id=?", [$row['user_id']]);
 	if (!empty($user_info)) { print "User: &nbsp"; print_url($user_info['login'],'/admin/users/edituser.php?id='.$user_info['id']); }
 	}
     if (!empty($row['ou_id'])) {
-	$ou_info=get_record_sql($db_link,"SELECT * FROM ou WHERE id=".$row['ou_id']);
+	$ou_info=get_record_sql($db_link,"SELECT * FROM ou WHERE id=?", [ $row['ou_id'] ]);
 	if (!empty($ou_info)) { print "Group: &nbsp"; print_url($ou_info['ou_name'],'/admin/groups/edit_group.php?id='.$ou_info['id']); }
 	}
     print "</td>";

+ 18 - 8
html/admin/iplist/deleted.php

@@ -18,21 +18,27 @@ if (!isset($f_description)) { $f_description=''; }
 $_SESSION[$page_url]['description']=$f_description;
 
 $sort_table = 'user_auth';
-
 $sort_url = "<a href=deleted.php?";
 
+$params=[];
 if ($rsubnet == 0) { $subnet_filter = ''; } else {
     $subnet_range = get_subnet_range($db_link,$rsubnet);
-    $subnet_filter = " and user_auth.ip_int>=".$subnet_range['start']." and user_auth.ip_int<=".$subnet_range['stop'];
+    $subnet_filter = " and user_auth.ip_int>=? and user_auth.ip_int<=?";
+    $params[]=$subnet_range['start'];
+    $params[]=$subnet_range['stop'];
     }
 
 $ip_list_filter = $subnet_filter;
 
 $ip_where = '';
 if (!empty($f_description)) {
-    if (checkValidIp($f_description)) { $ip_where = " and ip_int=inet_aton('" . $f_description . "') "; }
-    if (checkValidMac($f_description)) { $ip_where = " and mac='" . mac_dotted($f_description) . "'  "; }
-    if (empty($ip_where)) { $ip_where=" and (user_auth.description LIKE '$f_description' OR user_auth.dhcp_hostname LIKE '$f_description')"; }
+    if (checkValidIp($f_description)) { $ip_where = " and ip=?"; $params[]=$f_description; }
+    if (checkValidMac($f_description)) { $ip_where = " and mac=?"; $params[]= mac_dotted($f_description); }
+    if (empty($ip_where)) { 
+	$ip_where=" and (user_auth.description LIKE ? OR user_auth.dhcp_hostname LIKE ?)"; 
+	$params[]=$f_description;
+	$params[]=$f_description;
+	}
     $ip_list_filter = $ip_where;
     } 
 
@@ -51,7 +57,7 @@ print_ip_submenu($page_url);
 
 <?php
 $countSQL="SELECT Count(*) FROM user_auth WHERE user_auth.deleted = 1 $ip_list_filter";
-$count_records = get_single_field($db_link,$countSQL);
+$count_records = get_single_field($db_link,$countSQL, $params);
 $total=ceil($count_records/$displayed);
 if ($page>$total) { $page=$total; }
 if ($page<1) { $page=1; }
@@ -76,8 +82,12 @@ $sSQL = "SELECT
 user_auth.id, user_auth.ip, user_auth.mac, user_auth.description, user_auth.dns_name, user_auth.dhcp_hostname, 
 user_auth.dhcp_time, user_auth.last_found, user_auth.ts, user_auth.changed_time
 FROM user_auth WHERE user_auth.deleted = 1 $ip_list_filter
-ORDER BY $sort_table.$sort_field $order LIMIT $displayed OFFSET $start";
-$users = get_records_sql($db_link,$sSQL);
+ORDER BY $sort_table.$sort_field $order LIMIT ? OFFSET ?";
+
+$params[]=$displayed;
+$params[]=$start;
+
+$users = get_records_sql($db_link,$sSQL, $params);
 foreach ($users as $user) {
     if (empty($user['last_found']) or $user['last_found'] === '0000-00-00 00:00:00') { $user['last_found'] = ''; }
     if (empty($user['ts']) or $user['ts'] === '0000-00-00 00:00:00') { $user['ts'] = ''; }

+ 14 - 8
html/admin/iplist/doubles.php

@@ -14,10 +14,14 @@ if (isset($_POST["removeauth"])) {
     }
 
 print_ip_submenu($page_url);
-
+$params=[];
 if (empty($rcidr)) { $cidr_filter = ''; } else {
     $cidr_range = cidrToRange($rcidr);
-    if (!empty($cidr_range)) { $cidr_filter = " AND (U.ip_int>=".ip2long($cidr_range[0])." AND U.ip_int<=".ip2long($cidr_range[1]).")"; }
+    if (!empty($cidr_range)) { 
+	$cidr_filter = " AND (U.ip_int>=? AND U.ip_int<=?)"; 
+	$params[]=ip2long($cidr_range[0]);
+	$params[]=ip2long($cidr_range[1]);
+	}
     }
 
 ?>
@@ -40,8 +44,9 @@ if (empty($rcidr)) { $cidr_filter = ''; } else {
     <td align=right><input type="submit" onclick="return confirm('<?php echo WEB_msg_delete; ?>?')" name="removeauth" value="<?php echo WEB_btn_delete; ?>"></td>
 </tr>
 <?php
-$sSQL = "SELECT U.id, U.ip, U.mac, U.arp_found, S.subnet as net FROM user_auth U, subnets S WHERE (U.mac IS NOT NULL AND U.mac<>'') AND (U.ip_int BETWEEN S.ip_int_start AND S.ip_int_stop) $cidr_filter AND S.office=1 AND U.deleted=0 ORDER BY net,mac,arp_found";
-$users = get_records_sql($db_link,$sSQL);
+$sSQL = "SELECT U.id, U.ip, U.mac, U.arp_found, S.subnet as net FROM user_auth U, subnets S WHERE (U.mac IS NOT NULL AND U.mac<>'') 
+AND (U.ip_int BETWEEN S.ip_int_start AND S.ip_int_stop) $cidr_filter AND S.office=1 AND U.deleted=0 ORDER BY net,mac,arp_found";
+$users = get_records_sql($db_link,$sSQL, $params);
 $f_subnet=NULL;
 $f_mac=NULL;
 $f_id=NULL;
@@ -63,12 +68,13 @@ foreach ($users as $row) {
         //если первая запись не выводилась - выводим на печать
         if (!isset($printed[$f_id])) {
             //считаем сколько у нас дублей
-            $dSQL = "SELECT  U.id, U.ip, U.mac, U.arp_found FROM user_auth U WHERE U.mac='".$f_mac."' $cidr_filter AND U.deleted=0";
-            $doubles = get_records_sql($db_link,$dSQL);
+            $dSQL = "SELECT  U.id, U.ip, U.mac, U.arp_found FROM user_auth U WHERE $cidr_filter AND U.deleted=0 AND U.mac=?";
+            $params[]= $f_mac;
+            $doubles = get_records_sql($db_link,$dSQL, $params);
             $f_count = count($doubles);
 
             $f_index++;
-            $user = get_record_sql($db_link,"SELECT * FROM user_auth WHERE id=".$f_id);
+            $user = get_record_sql($db_link,"SELECT * FROM user_auth WHERE id=?", [$f_id]);
             if (empty($user['arp_found']) or $user['arp_found'] === '0000-00-00 00:00:00') { $user['arp_found'] = ''; }
             if (empty($user['ts']) or $user['ts'] === '0000-00-00 00:00:00') { $user['ts'] = ''; }
             if (empty($user['changed_time']) or $user['changed_time'] === '0000-00-00 00:00:00') { $user['changed_time'] = ''; }
@@ -94,7 +100,7 @@ foreach ($users as $row) {
         //проверяем текущую запись
         if (!isset($printed[$row['id']])) {
             $f_index++;
-            $user = get_record_sql($db_link,"SELECT * FROM user_auth WHERE id=".$row['id']);
+            $user = get_record_sql($db_link,"SELECT * FROM user_auth WHERE id=?", [$row['id']]);
             if (empty($user['arp_found']) or $user['arp_found'] === '0000-00-00 00:00:00') { $user['arp_found'] = ''; }
             if (empty($user['ts']) or $user['ts'] === '0000-00-00 00:00:00') { $user['ts'] = ''; }
             if (empty($user['changed_time']) or $user['changed_time'] === '0000-00-00 00:00:00') { $user['changed_time'] = ''; }

+ 25 - 10
html/admin/iplist/index.php

@@ -19,13 +19,17 @@ if ($sort_field == 'login') { $sort_table = 'user_list'; }
 if ($sort_field == 'fio') { $sort_table = 'user_list'; }
 if ($sort_field == 'ou_name') { $sort_table = 'ou'; }
 
+$params=[];
+
 $sort_url = "<a href=index.php?ou=" . $rou;
 
-if ($rou == 0) { $ou_filter = ''; } else { $ou_filter = " and user_list.ou_id=$rou "; }
+if ($rou == 0) { $ou_filter = ''; } else { $ou_filter = " and user_list.ou_id=?"; $params[]=$rou; }
 
 if (empty($rcidr)) { $cidr_filter = ''; } else {
     $cidr_range = cidrToRange($rcidr);
-    if (!empty($cidr_range)) { $cidr_filter = " and user_auth.ip_int>=".ip2long($cidr_range[0])." and user_auth.ip_int<=".ip2long($cidr_range[1]); }
+    if (!empty($cidr_range)) { $cidr_filter = " and user_auth.ip_int>=? and user_auth.ip_int<=?"; }
+    $params[]=ip2long($cidr_range[0]);
+    $params[]=ip2long($cidr_range[1]);
     }
 
 $enabled_filter='';
@@ -67,12 +71,20 @@ $ip_where = '';
 if (!empty($f_search_str)) {
     $f_ip = normalizeIpAddress($f_search_str);
     if (!empty($f_ip)) { 
-        $ip_where = " and ip_int=inet_aton('" . $f_ip . "') ";
+        $ip_where = " and ip=?";
+        $params[]= $f_ip;
         $f_search_str = $f_ip;
         } else {
-        if (checkValidMac($f_search_str)) { $ip_where =" and mac='" . mac_dotted($f_search_str) ."'"; }
-            else {
-            $ip_where =" and (mac like '" . mac_dotted($f_search) . "%' or login like '".$f_search."%' or description like '".$f_search."%' or dns_name like '".$f_search."%' or dhcp_hostname like '".$f_search."%')"; 
+        if (checkValidMac($f_search_str)) { 
+    	    $ip_where =" and mac=?"; 
+    	    $params[]= mac_dotted($f_search_str);
+    	    } else {
+            $ip_where =" and (mac like ? or login like ? or description like ? or dns_name like ? or dhcp_hostname like ?)"; 
+            $params[]=mac_dotted($f_search);
+            $parmas[]=$f_search.'%';
+            $params[]=$f_search.'%';
+            $params[]=$f_search.'%';
+            $params[]=$f_search.'%';
             }
         }
     }
@@ -188,7 +200,7 @@ LEFT JOIN ou
 ON ou.id=user_list.ou_id
 WHERE user_auth.deleted =0 $ip_list_filter";
 
-$count_records = get_single_field($db_link,$countSQL);
+$count_records = get_single_field($db_link,$countSQL, $params);
 $total=ceil($count_records/$displayed);
 if ($page>$total) { $page=$total; }
 if ($page<1) { $page=1; }
@@ -223,9 +235,12 @@ ON user_auth.user_id = user_list.id
 LEFT JOIN ou
 ON ou.id=user_list.ou_id
 WHERE user_auth.deleted =0 $ip_list_filter
-ORDER BY $sort_table.$sort_field $order LIMIT $displayed OFFSET $start";
+ORDER BY $sort_table.$sort_field $order LIMIT ? OFFSET ?";
+
+$params[]=$displayed;
+$params[]=$start;
 
-$users = get_records_sql($db_link,$sSQL);
+$users = get_records_sql($db_link,$sSQL, $params);
 foreach ($users as $user) {
     if ($user['dhcp_time'] == '0000-00-00 00:00:00') {
         $dhcp_str = '';
@@ -252,7 +267,7 @@ foreach ($users as $user) {
         print "<td class=\"$cl\" width=200 >".$user['description']."</td>\n";
     }
 
-    $aliases = get_records_sql($db_link, 'SELECT * FROM user_auth_alias WHERE auth_id='.$user['id']);
+    $aliases = get_records_sql($db_link, 'SELECT * FROM user_auth_alias WHERE auth_id=?', [$user['id']]);
     $dns_display = $user['dns_name'];
     if ($user["dns_ptr_only"]) { $dns_display.='&nbsp(ptr)'; }
     if (!empty($aliases)) {

+ 10 - 5
html/admin/iplist/nagios.php

@@ -16,11 +16,14 @@ if ($sort_field == 'fio') { $sort_table = 'user_list'; }
 
 $sort_url = "<a href=nagios.php?ou=" . $rou; 
 
-if ($rou == 0) { $ou_filter = ''; } else { $ou_filter = " and user_list.ou_id=$rou "; }
+$params=[];
+if ($rou == 0) { $ou_filter = ''; } else { $ou_filter = " and user_list.ou_id=?"; $params[]=$rou; }
 
 if ($rsubnet == 0) { $subnet_filter = ''; } else {
     $subnet_range = get_subnet_range($db_link,$rsubnet);
-    if (!empty($subnet_range)) { $subnet_filter = " and user_auth.ip_int>=".$subnet_range['start']." and user_auth.ip_int<=".$subnet_range['stop']; }
+    if (!empty($subnet_range)) { $subnet_filter = " and user_auth.ip_int>=? and user_auth.ip_int<=?"; }
+    $params[]=$subnet_range['start'];
+    $params[]=$subnet_range['stop'];
     }
 
 $enabled_filter='';
@@ -68,7 +71,7 @@ print_ip_submenu($page_url);
 
 <?php
 $countSQL="SELECT Count(*) FROM user_auth, user_list WHERE user_auth.user_id = user_list.id AND user_auth.deleted =0 $ip_list_filter";
-$count_records = get_single_field($db_link,$countSQL);
+$count_records = get_single_field($db_link,$countSQL, $params);
 $total=ceil($count_records/$displayed);
 if ($page>$total) { $page=$total; }
 if ($page<1) { $page=1; }
@@ -97,9 +100,11 @@ print_navigation($page_url,$page,$displayed,$count_records,$total);
 
 $sSQL = "SELECT user_auth.*, user_list.login FROM user_auth, user_list
 WHERE user_auth.user_id = user_list.id AND user_auth.deleted =0 $ip_list_filter
-ORDER BY $sort_table.$sort_field $order LIMIT $displayed OFFSET $start";
+ORDER BY $sort_table.$sort_field $order LIMIT ? OFFSET ?";
+$params[]=$displayed;
+$params[]=$start;
 
-$users = get_records_sql($db_link,$sSQL);
+$users = get_records_sql($db_link,$sSQL, $params);
 foreach ($users as $user) {
     if ($user['dhcp_time'] == '0000-00-00 00:00:00') {
         $dhcp_str = '';

+ 43 - 14
html/admin/logs/authlog.php

@@ -21,25 +21,57 @@ if (!isset($auth_id)) { header('Location: /admin/logs/index.php', true, 301); ex
 </form>
 
 <?php
-$log_filter ='';
+$params = [$date1, $date2];
+$log_filter_parts = [];
+// Уровень логирования
+if ($display_log_level == L_ERROR) {
+    $log_filter_parts[] = "level = ?";
+    $params[] = L_ERROR;
+} elseif ($display_log_level == L_WARNING) {
+    $log_filter_parts[] = "level <= ?";
+    $params[] = L_WARNING;
+} elseif ($display_log_level == L_INFO) {
+    $log_filter_parts[] = "level <= ?";
+    $params[] = L_INFO;
+} elseif ($display_log_level == L_VERBOSE) {
+    $log_filter_parts[] = "level <= ?";
+    $params[] = L_VERBOSE;
+}
+// L_DEBUG — ничего не добавляем (все уровни)
+
+$log_filter_parts[] = "auth_id = ?";
+$params[] = $auth_id;
+
+if (!empty($fcustomer)) {
+    $log_filter_parts[] = "customer LIKE ?";
+    $params[] = '%' . $fcustomer . '%';
+}
+if (!empty($fmessage)) {
+    $log_filter_parts[] = "message LIKE ?";
+    $params[] = '%' . $fmessage . '%';
+}
 
-if ($display_log_level == L_ERROR) { $log_filter = " and level=". L_ERROR." "; }
-if ($display_log_level == L_WARNING) { $log_filter = " and level<=".L_WARNING." "; }
-if ($display_log_level == L_INFO) { $log_filter = " and level<=".L_INFO." "; }
-if ($display_log_level == L_VERBOSE) { $log_filter = " and level<=".L_VERBOSE." "; }
-if ($display_log_level == L_DEBUG) { $log_filter = ""; }
+// Собираем фильтр
+$log_filter = !empty($log_filter_parts) ? ' AND ' . implode(' AND ', $log_filter_parts) : '';
 
-if (!empty($log_filter)) { $log_filter = $log_filter." and auth_id=".$auth_id; } else { $log_filter = " and auth_id=".$auth_id; }
-if (!empty($fcustomer)) { $log_filter = $log_filter." and customer LIKE '%".$fcustomer."%'"; }
-if (!empty($fmessage)) { $log_filter = $log_filter." and message LIKE '%".$fmessage."%'"; }
+$countSQL = "SELECT COUNT(*) FROM worklog WHERE ts >= ? AND ts < ?" . $log_filter;
+$count_records = get_single_field($db_link, $countSQL, $params);
 
-$countSQL="SELECT Count(*) FROM worklog WHERE ts>='$date1' AND ts<'$date2' $log_filter";
-$count_records = get_single_field($db_link,$countSQL);
 $total=ceil($count_records/$displayed);
 if ($page>$total) { $page=$total; }
 if ($page<1) { $page=1; }
 $start = ($page * $displayed) - $displayed; 
 print_navigation($page_url,$page,$displayed,$count_records,$total);
+#speedup paging
+$sSQL = "SELECT ts,customer,message,level FROM worklog as S JOIN (SELECT id FROM worklog WHERE ts>=? AND ts<? $log_filter 
+ORDER BY id DESC 
+LIMIT $displayed OFFSET $start) AS I ON S.id = I.id";
+
+$params[]=$displayed;
+$params[]=$start;
+
+$userlog = get_records_sql($db_link, $sSQL, $params);
+
 ?>
 <br>
 <table class="data" width="90%">
@@ -50,9 +82,6 @@ print_navigation($page_url,$page,$displayed,$count_records,$total);
 		<td class="data"><b><?php echo WEB_log_event; ?></b></td>
 	</tr>
 <?php
-#speedup paging
-$sSQL = "SELECT ts,customer,message,level FROM worklog as S JOIN (SELECT id FROM worklog WHERE ts>='$date1' AND ts<'$date2' $log_filter ORDER BY id DESC LIMIT $displayed OFFSET $start) AS I ON S.id = I.id";
-$userlog = get_records_sql($db_link, $sSQL);
 foreach ($userlog as $row) {
     print "<tr align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
     print "<td class=\"data\">" . $row['ts'] . "</td>\n";

+ 16 - 7
html/admin/logs/detaillog.php

@@ -16,10 +16,13 @@ if (empty($f_ip)) { $f_ip = '127.0.0.1'; }
 $_SESSION[$page_url]['ip']=$f_ip;
 
 $ip_where = '';
+$params=[];
 
 if (!empty($f_ip)) {
     if (checkValidIp($f_ip)) {
-        $ip_where = " (src_ip=inet_aton('" . $f_ip . "') or dst_ip=inet_aton('" . $f_ip . "')) AND "; 
+        $ip_where = " (src_ip=? or dst_ip=?) AND "; 
+        $params[]=ip2long($f_ip);
+        $params[]=ip2long($f_ip);
         }
     }
 
@@ -57,10 +60,13 @@ $sort_url = "<a href='detaillog.php?date_start=\"".$date1.'"&date_stop="'.$date2
 if (!empty($f_ip)) { $sort_url .='&f_ip="'.$f_ip.'"'; }
 
 $gateway_filter='';
-if (!empty($rgateway) and $rgateway>0) { $gateway_filter="(router_id=$rgateway) AND"; }
+if (!empty($rgateway) and $rgateway>0) { $gateway_filter="(router_id=?) AND"; $params[]=$rgateway; }
 
-$countSQL="SELECT Count(*) FROM traffic_detail as A WHERE $gateway_filter $ip_where ts>='$date1' AND ts<'$date2'";
-$count_records = get_single_field($db_link,$countSQL);
+$countSQL="SELECT Count(*) FROM traffic_detail as A WHERE $gateway_filter $ip_where ts>=? AND ts<?";
+$params[]=$date1;
+$params[]=$date2;
+
+$count_records = get_single_field($db_link,$countSQL, $params);
 $total=ceil($count_records/$displayed);
 if ($page>$total) { $page=$total; }
 if ($page<1) { $page=1; }
@@ -88,9 +94,12 @@ $gateway_list = get_gateways($db_link);
 </tr>
 <?php
 $fsql = "SELECT A.id, A.auth_id, A.ts, A.router_id, A.proto, A.src_ip, A.src_port, A.dst_ip, A.dst_port, A.bytes, A.pkt FROM traffic_detail as A JOIN (SELECT id FROM traffic_detail 
-        WHERE $gateway_filter $ip_where ts>='$date1' AND ts<'$date2'
-        ORDER BY ts ASC LIMIT $displayed OFFSET $start) as T ON A.id = T.id ORDER BY $sort_table.$sort_field $order";
-$userdata = get_records_sql($db_link, $fsql);
+        WHERE $gateway_filter $ip_where ts>=? AND ts<?
+        ORDER BY ts ASC LIMIT ? OFFSET ?) as T ON A.id = T.id ORDER BY $sort_table.$sort_field $order";
+$params[]=$displayed;
+$params[]=$start;
+
+$userdata = get_records_sql($db_link, $fsql, $params);
 foreach ($userdata as $row) {
     print "<tr align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
     print "<td class=\"data\">" . $row['id'] . "</td>\n";

+ 20 - 10
html/admin/logs/dhcp.php

@@ -18,20 +18,28 @@ $_SESSION[$page_url]['f_dhcp']=$f_dhcp;
 $_SESSION[$page_url]['ip']=$f_ip;
 
 $dhcp_where = '';
-if ($f_dhcp != 'all') { $dhcp_where = " and action='$f_dhcp' "; }
+$params=[ $date1, $date2 ];
+if ($f_dhcp != 'all') { $dhcp_where = " and action=?"; $params[]=$f_dhcp; }
 
 if (empty($rcidr)) { $cidr_filter = ''; } else {
     $cidr_range = cidrToRange($rcidr);
-    if (!empty($cidr_range)) { $cidr_filter = " and (ip_int>=".ip2long($cidr_range[0])." and ip_int<=".ip2long($cidr_range[1]).")"; }
+    if (!empty($cidr_range)) { $cidr_filter = " and (ip_int>=? and ip_int<=?)"; }
+    $params[]=ip2long($cidr_range[0]);
+    $params[]=ip2long($cidr_range[1]);
     }
 
 if (!empty($f_ip)) {
     if (checkValidIp($f_ip)) { 
-        $dhcp_where = " and ip_int=inet_aton('" . $f_ip . "') "; 
+        $dhcp_where = " and ip_int=?"; 
+        $params[]=ip2long($f_ip);
         } else {
         if (checkValidMac($f_ip)) { 
-            $dhcp_where = " and mac='" . mac_dotted($f_ip) . "'  "; 
-            } else { $dhcp_where = " and dhcp_hostname like '".$f_ip."%'"; }
+            $dhcp_where = " and mac=?";
+            $params[]= mac_dotted($f_ip);
+            } else { 
+    	    $dhcp_where = " and dhcp_hostname like ?";
+    	    $params[]=$f_ip.'%';
+    	    }
         }
     }
 
@@ -39,7 +47,6 @@ $dhcp_where .= $cidr_filter;
 
 print_log_submenu($page_url);
 
-
 ?>
 
 <div id="cont">
@@ -56,8 +63,8 @@ print_log_submenu($page_url);
 </form>
 
 <?php
-$countSQL="SELECT Count(*) FROM dhcp_log WHERE ts>='$date1' AND ts<'$date2' $dhcp_where";
-$count_records = get_single_field($db_link,$countSQL);
+$countSQL="SELECT Count(*) FROM dhcp_log WHERE ts>=? AND ts<? $dhcp_where";
+$count_records = get_single_field($db_link,$countSQL, $params);
 $total=ceil($count_records/$displayed);
 if ($page>$total) { $page=$total; }
 if ($page<1) { $page=1; }
@@ -77,8 +84,11 @@ print_navigation($page_url,$page,$displayed,$count_records,$total);
 <?php
 
 #speedup dhcp log paging
-$sSQL = "SELECT * FROM dhcp_log as D JOIN (SELECT id FROM dhcp_log WHERE ts>='$date1' and ts<'$date2' $dhcp_where ORDER BY id DESC LIMIT $displayed OFFSET $start) AS I ON D.id = I.id";
-$userlog = get_records_sql($db_link, $sSQL);
+$sSQL = "SELECT * FROM dhcp_log as D JOIN (SELECT id FROM dhcp_log WHERE ts>=? and ts<? $dhcp_where ORDER BY id DESC LIMIT ? OFFSET ?) AS I ON D.id = I.id";
+$params[]=$displayed;
+$params[]=$start;
+
+$userlog = get_records_sql($db_link, $sSQL, $params);
 
 foreach ($userlog as $row) {
     if ($row['action'] == "old") { $row['action'] = WEB_log_dhcp_old.": "; }

+ 62 - 22
html/admin/logs/index.php

@@ -27,28 +27,69 @@ print_log_submenu($page_url);
 </form>
 
 <?php
-$log_filter ='';
-
-if ($display_log_level == L_ERROR) { $log_filter = " and level=". L_ERROR." "; }
-if ($display_log_level == L_WARNING) { $log_filter = " and level<=".L_WARNING." "; }
-if ($display_log_level == L_INFO) { $log_filter = " and level<=".L_INFO." "; }
-if ($display_log_level == L_VERBOSE) { $log_filter = " and level<=".L_VERBOSE." "; }
-if ($display_log_level == L_DEBUG) { $log_filter = ""; }
-
-if (!empty($fcustomer)) { $log_filter = $log_filter." and customer LIKE '".$fcustomer."'"; }
-if (!empty($fmessage)) { $log_filter = $log_filter." and message LIKE '".$fmessage."'"; }
-if (!empty($fuser_ip)) { $log_filter = $log_filter." and ip LIKE '".$fuser_ip."'"; }
-
-$countSQL="SELECT Count(*) FROM worklog WHERE ts>='$date1' AND ts<'$date2' $log_filter";
-$count_records = get_single_field($db_link,$countSQL);
-$total=ceil($count_records/$displayed);
-if ($page>$total) { $page=$total; }
-if ($page<1) { $page=1; }
-$start = ($page * $displayed) - $displayed; 
-print_navigation($page_url,$page,$displayed,$count_records,$total);
+// === 1. Формируем базовые параметры и условия ===
+$params = [$date1, $date2];
+$conditions = [];
+
+// Уровень логирования
+if ($display_log_level == L_ERROR) {
+    $conditions[] = "level = ?";
+    $params[] = L_ERROR;
+} elseif ($display_log_level == L_WARNING) {
+    $conditions[] = "level <= ?";
+    $params[] = L_WARNING;
+} elseif ($display_log_level == L_INFO) {
+    $conditions[] = "level <= ?";
+    $params[] = L_INFO;
+} elseif ($display_log_level == L_VERBOSE) {
+    $conditions[] = "level <= ?";
+    $params[] = L_VERBOSE;
+}
+// L_DEBUG: не добавляем условие (показываем всё)
+
+// Остальные фильтры — ВСЕ через параметры!
+if (!empty($fcustomer)) {
+    $conditions[] = "customer LIKE ?";
+    $params[] = '%' . $fcustomer . '%';
+}
+if (!empty($fmessage)) {
+    $conditions[] = "message LIKE ?";
+    $params[] = '%' . $fmessage . '%';
+}
+if (!empty($fuser_ip)) {
+    $conditions[] = "ip LIKE ?";
+    $params[] = '%' . $fuser_ip . '%';
+}
+
+// Собираем WHERE-часть
+$whereClause = !empty($conditions) ? ' AND ' . implode(' AND ', $conditions) : '';
+
+// === 2. Подсчёт общего количества записей ===
+$countSQL = "SELECT COUNT(*) FROM worklog WHERE ts >= ? AND ts < ?" . $whereClause;
+$count_records = (int)get_single_field($db_link, $countSQL, $params);
+
+// === 3. Пагинация ===
+$total = ceil($count_records / $displayed);
+$page = max(1, min($page, $total)); // корректное ограничение страницы
+$start = ($page - 1) * $displayed;   // исправлено: OFFSET должен быть (page-1)*limit
+
+print_navigation($page_url, $page, $displayed, $count_records, $total);
+
+// === 4. Запрос данных с пагинацией ===
+// Добавляем LIMIT и OFFSET как параметры (приводим к int!)
+$limit = (int)$displayed;
+$offset = (int)$start;
+
+$dataParams = array_merge($params, [$limit, $offset]);
+
+$sSQL = "
+    SELECT * FROM worklog 
+    WHERE ts >= ? AND ts < ?" . $whereClause . "
+    ORDER BY ts DESC 
+    LIMIT ? OFFSET ?
+";
 
-#speedup paging
-$sSQL = "SELECT * FROM (SELECT * FROM worklog WHERE ts>='$date1' AND ts<'$date2' $log_filter ) AS W ORDER BY ts DESC LIMIT $displayed OFFSET $start";
+$userlog = get_records_sql($db_link, $sSQL, $dataParams);
 
 ?>
 <br>
@@ -63,7 +104,6 @@ $sSQL = "SELECT * FROM (SELECT * FROM worklog WHERE ts>='$date1' AND ts<'$date2'
 </tr>
 
 <?php
-$userlog = get_records_sql($db_link, $sSQL);
 
 foreach ($userlog as $row) {
     print "<tr align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";

+ 35 - 15
html/admin/logs/ip.php

@@ -13,11 +13,6 @@ $_SESSION[$page_url]['ip']=$f_ip;
 
 print_log_submenu($page_url);
 
-$ip_where = '';
-if (!empty($f_ip)) {
-    if (checkValidIp($f_ip)) { $ip_where = " and ip_int=inet_aton('" . $f_ip . "') "; }
-    if (checkValidMac($f_ip)) { $ip_where = " and mac='" . mac_dotted($f_ip) . "'  "; }
-    }
 ?>
 
 <div id="cont">
@@ -31,13 +26,41 @@ if (!empty($f_ip)) {
 </form>
 
 <?php
-$countSQL="SELECT Count(*) FROM user_auth WHERE ts>='$date1' AND ts<'$date2' $ip_where";
-$count_records = get_single_field($db_link,$countSQL);
-$total=ceil($count_records/$displayed);
-if ($page>$total) { $page=$total; }
-if ($page<1) { $page=1; }
-$start = ($page * $displayed) - $displayed; 
-print_navigation($page_url,$page,$displayed,$count_records,$total);
+$params = [$date1, $date2];
+$conditions = [];
+
+if (!empty($f_ip)) {
+    if (checkValidIp($f_ip)) {
+        $ip_long = sprintf('%u', ip2long($f_ip));
+        $conditions[] = "ip_int = ?";
+        $params[] = $ip_long;
+    } elseif (checkValidMac($f_ip)) {
+        $conditions[] = "mac = ?";
+        $params[] = mac_dotted($f_ip);
+    }
+}
+
+$whereClause = !empty($conditions) ? ' AND ' . implode(' AND ', $conditions) : '';
+
+$countSQL = "SELECT COUNT(*) FROM user_auth WHERE ts >= ? AND ts < ?" . $whereClause;
+$count_records = (int)get_single_field($db_link, $countSQL, $params);
+$total = ceil($count_records / $displayed);
+$page = max(1, min($page, $total));
+$start = ($page - 1) * $displayed;
+
+print_navigation($page_url, $page, $displayed, $count_records, $total);
+
+$dataParams = array_merge($params, [$displayed, $start]);
+
+$sSQL = "
+    SELECT * FROM user_auth 
+    WHERE ts >= ? AND ts < ?" . $whereClause . "
+    ORDER BY id DESC 
+    LIMIT ? OFFSET ?
+";
+
+$iplog = get_records_sql($db_link, $sSQL, $dataParams);
+
 ?>
 <br>
 <table class="data">
@@ -53,9 +76,6 @@ print_navigation($page_url,$page,$displayed,$count_records,$total);
 
 <?php
 
-$sSQL = "SELECT * FROM user_auth WHERE ts>='$date1' AND ts<'$date2' $ip_where ORDER BY id DESC LIMIT $displayed OFFSET $start";
-
-$iplog = get_records_sql($db_link, $sSQL);
 foreach ($iplog as $row) {
     print "<tr align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
     print "<td class=\"data\">" . $row['id'] . "</td>\n";

+ 25 - 12
html/admin/logs/mac.php

@@ -12,8 +12,6 @@ if (!isset($f_mac)) { $f_mac=''; }
 
 $_SESSION[$page_url]['mac']=$f_mac;
 
-$mac_where = '';
-if (!empty($f_mac)) { $mac_where = " and mac='$f_mac' "; }
 
 print_log_submenu($page_url);
 ?>
@@ -27,14 +25,32 @@ print_log_submenu($page_url);
 </form>
 
 <?php
-$countSQL="SELECT Count(*) FROM mac_history WHERE ts>='$date1' AND ts<'$date2' $mac_where ORDER BY id DESC";
-$count_records = get_single_field($db_link,$countSQL);
-$total=ceil($count_records/$displayed);
-if ($page>$total) { $page=$total; }
-if ($page<1) { $page=1; }
-$start = ($page * $displayed) - $displayed; 
-print_navigation($page_url,$page,$displayed,$count_records,$total);
+$params = [$date1, $date2];
+$conditions = [];
+if (!empty($f_mac)) {
+    $conditions[] = "mac = ?";
+    $params[] = $f_mac;
+}
+$whereClause = !empty($conditions) ? ' AND ' . implode(' AND ', $conditions) : '';
+$countSQL = "SELECT COUNT(*) FROM mac_history WHERE ts >= ? AND ts < ?" . $whereClause;
+$count_records = (int)get_single_field($db_link, $countSQL, $params);
+$total = ceil($count_records / $displayed);
+$page = max(1, min($page, $total));
+$start = ($page - 1) * $displayed;
+print_navigation($page_url, $page, $displayed, $count_records, $total);
+
+$dataParams = array_merge($params, [$displayed, $start]);
+
+$sSQL = "
+    SELECT * FROM mac_history 
+    WHERE ts >= ? AND ts < ?" . $whereClause . "
+    ORDER BY ts DESC 
+    LIMIT ? OFFSET ?
+";
+
+$maclog = get_records_sql($db_link, $sSQL, $dataParams);
 ?>
+
 <br>
 <table class="data" width="850">
 <tr align="center">
@@ -46,9 +62,6 @@ print_navigation($page_url,$page,$displayed,$count_records,$total);
 
 <?php
 
-$sSQL = "SELECT * FROM mac_history WHERE ts>='$date1' AND ts<'$date2' $mac_where ORDER BY ts DESC LIMIT $displayed OFFSET $start";
-$maclog = get_records_sql($db_link, $sSQL);
-
 foreach ($maclog as $row) {
     print "<tr align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
     print "<td class=\"data\">" . $row['ts'] . "</td>\n";

+ 40 - 27
html/admin/logs/syslog.php

@@ -15,19 +15,49 @@ $_SESSION[$page_url]['device_show']=$f_id;
 
 print_log_submenu($page_url);
 
-$log_filter = "";
-
-if ($f_id>0) {
-    $dev_ips=get_device_ips($db_link,$f_id);
-    $log_filter=' and ip IN (';
-    foreach ($dev_ips as $index => $ip) {
-	$log_filter=$log_filter."'".$ip."',";
-        }
-    $log_filter = preg_replace('/\,$/', '',$log_filter);
-    $log_filter = $log_filter .")";
+$params = [$date1, $date2];
+$conditions = [];
+// === Фильтр по IP (через IN с параметрами) ===
+if ($f_id > 0) {
+    $dev_ips = get_device_ips($db_link, $f_id);
+    if (!empty($dev_ips)) {
+        // Создаём плейсхолдеры: ?, ?, ?
+        $placeholders = str_repeat('?,', count($dev_ips) - 1) . '?';
+        $conditions[] = "ip IN ($placeholders)";
+        $params = array_merge($params, $dev_ips);
     }
+}
+
+if (!empty($fmessage)) {
+    $conditions[] = "message LIKE ?";
+    $params[] = '%' . $fmessage . '%';
+}
+
+$whereClause = !empty($conditions) ? ' AND ' . implode(' AND ', $conditions) : '';
+
+$countSQL = "SELECT COUNT(*) FROM remote_syslog WHERE ts >= ? AND ts < ?" . $whereClause;
+$count_records = (int)get_single_field($db_link, $countSQL, $params);
+$total = ceil($count_records / $displayed);
+$page = max(1, min($page, $total));
+$start = ($page - 1) * $displayed;
+
+print_navigation($page_url, $page, $displayed, $count_records, $total);
+
+$limit = (int)$displayed;
+$offset = (int)$start;
+
+$dataParams = array_merge($params, [$limit, $offset]);
+
+$sSQL = "
+    SELECT * FROM remote_syslog 
+    WHERE ts >= ? AND ts < ?" . $whereClause . "
+    ORDER BY ts DESC 
+    LIMIT ? OFFSET ?
+";
 
+$syslog = get_records_sql($db_link, $sSQL, $dataParams);
 ?>
+
 <div id="cont">
 <br>
 <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
@@ -38,21 +68,6 @@ if ($f_id>0) {
 <?php echo WEB_log_filter_event; ?>:<input name="message" value="<?php echo $fmessage; ?>" />
 </form>
 
-<?php
-
-if (!empty($fmessage)) { $log_filter .= " AND message LIKE '%" . addslashes($fmessage) . "%'"; }
-
-$countSQL="SELECT Count(*) FROM remote_syslog WHERE ts>='$date1' AND ts<'$date2' $log_filter";
-$count_records = get_single_field($db_link,$countSQL);
-$total=ceil($count_records/$displayed);
-if ($page>$total) { $page=$total; }
-if ($page<1) { $page=1; }
-$start = ($page * $displayed) - $displayed; 
-print_navigation($page_url,$page,$displayed,$count_records,$total);
-#speedup pageing
-$sSQL = "SELECT * FROM (SELECT * FROM remote_syslog WHERE ts>='$date1' AND ts<'$date2' $log_filter) as R ORDER BY ts DESC LIMIT $displayed OFFSET $start";
-?>
-
 <br>
 <table class="data" width="90%">
 		<tr align="center">
@@ -63,8 +78,6 @@ $sSQL = "SELECT * FROM (SELECT * FROM remote_syslog WHERE ts>='$date1' AND ts<'$
 
 <?php
 
-
-$syslog = get_records_sql($db_link, $sSQL);
 if (!empty($syslog)) {
     foreach ($syslog as $row) {
         print "<tr align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";

+ 49 - 14
html/admin/logs/unknown.php

@@ -11,8 +11,55 @@ if (!isset($f_id)) { $f_id=0; }
 
 $_SESSION[$page_url]['device_show']=$f_id;
 print_log_submenu($page_url);
-$where_dev = "";
-if ($f_id > 0) { $where_dev = " and D.id=$f_id "; }
+
+$params = [$date1, $date2];
+$conditions = [];
+
+// === 2. Условие по устройству ===
+if ($f_id > 0) {
+    $conditions[] = "D.id = ?";
+    $params[] = (int)$f_id; // приведение к int для безопасности
+}
+
+$whereClause = !empty($conditions) ? ' AND ' . implode(' AND ', $conditions) : '';
+
+$countSQL = "
+    SELECT COUNT(*)
+    FROM unknown_mac AS U
+    JOIN devices AS D ON U.device_id = D.id
+    JOIN device_ports AS DP ON U.port_id = DP.id
+    WHERE D.device_type <= 2
+      AND U.ts >= ?
+      AND U.ts < ?
+      $whereClause
+";
+
+$count_records = (int)get_single_field($db_link, $countSQL, $params);
+$total = ceil($count_records / $displayed);
+$page = max(1, min($page, $total));
+$start = ($page - 1) * $displayed;
+
+print_navigation($page_url, $page, $displayed, $count_records, $total);
+
+$limit = (int)$displayed;
+$offset = (int)$start;
+
+$dataParams = array_merge($params, [$limit, $offset]);
+
+$sSQL = "
+    SELECT U.mac, U.ts, DP.port, D.device_name
+    FROM unknown_mac AS U
+    JOIN devices AS D ON U.device_id = D.id
+    JOIN device_ports AS DP ON U.port_id = DP.id
+    WHERE D.device_type <= 2
+      AND U.ts >= ?
+      AND U.ts < ?
+      $whereClause
+    ORDER BY U.mac
+    LIMIT ? OFFSET ?
+";
+
+$maclog = get_records_sql($db_link, $sSQL, $dataParams);
 ?>
 
 <div id="cont">
@@ -24,15 +71,6 @@ if ($f_id > 0) { $where_dev = " and D.id=$f_id "; }
 <input type="submit" value="<?php echo WEB_btn_show; ?>">
 </form>
 
-<?php
-$countSQL="SELECT Count(*) FROM unknown_mac AS U, devices AS D, device_ports AS DP  WHERE D.device_type<=2 and U.device_id = D.id  AND U.port_id = DP.id AND U.ts>='$date1' AND U.ts<'$date2' $where_dev";
-$count_records = get_single_field($db_link,$countSQL);
-$total=ceil($count_records/$displayed);
-if ($page>$total) { $page=$total; }
-if ($page<1) { $page=1; }
-$start = ($page * $displayed) - $displayed; 
-print_navigation($page_url,$page,$displayed,$count_records,$total);
-?>
 <br>
 <table class="data" width="750">
 <tr align="center">
@@ -42,9 +80,6 @@ print_navigation($page_url,$page,$displayed,$count_records,$total);
 	<td class="data"><b><?php echo WEB_cell_last_found; ?></b></td>
 </tr>
 <?php
-
-$sSQL = "SELECT U.mac, U.ts, DP.port, D.device_name FROM unknown_mac AS U, devices AS D, device_ports AS DP  WHERE D.device_type<=2 and U.device_id = D.id  AND U.port_id = DP.id AND U.ts>='$date1' AND U.ts<'$date2' $where_dev ORDER BY U.mac LIMIT $displayed OFFSET $start";
-$maclog = get_records_sql($db_link, $sSQL);
 foreach ($maclog as $row) {
     print "<tr align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
     print "<td class=\"data\">" . $row['device_name'] . "</td>\n";

+ 2 - 2
html/admin/queues/index.php

@@ -9,7 +9,7 @@ if (isset($_POST['save'])) {
         $new['queue_name'] = trim($_POST['f_queue_name'][$i]);
         $new['Download'] = $_POST['f_down'][$i] * 1;
         $new['Upload'] = $_POST['f_up'][$i] * 1;
-        update_record($db_link, "queue_list", "id='{$id}'", $new);
+        update_record($db_link, "queue_list", "id=?", $new, [ $id ]);
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
@@ -41,7 +41,7 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
 	<td><input type="submit" onclick="return confirm('<?php echo WEB_msg_delete; ?>?')" name="remove" value="<?php echo WEB_btn_delete; ?>"></td>
 </tr>
 <?php
-$t_queue=get_records($db_link, "queue_list",'TRUE ORDER BY id');
+$t_queue=get_records_sql($db_link, "SELECT * FROM queue_list ORDER BY id");
 foreach ($t_queue as $row) {
     print "<tr align=center>\n";
     print "<td class=\"data\" style='padding:0'><input type=checkbox name=f_id[] value='{$row['id']}'></td>\n";

+ 66 - 23
html/admin/reports/authday.php

@@ -6,8 +6,8 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/datetimefilter.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/oufilter.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/gatefilter.php");
-$auth=get_record_sql($db_link,'SELECT * FROM user_auth WHERE id='.$id);
-$user=get_record_sql($db_link,'SELECT * FROM user_list WHERE id='.$auth['user_id']);
+$auth=get_record_sql($db_link,'SELECT * FROM user_auth WHERE id=?', [$id]);
+$user=get_record_sql($db_link,'SELECT * FROM user_list WHERE id=?', [ $auth['user_id']]);
 
 ?>
 <div id="cont">
@@ -36,36 +36,79 @@ print WEB_report_traffic_for_ip."&nbsp<a href=../users/editauth.php?id=$id>".$au
 </tr>
 <?php
 
-$gateway_list = get_gateways($db_link);
-$gateway_filter='';
-if (!empty($rgateway) and $rgateway>0) { $gateway_filter="(router_id=$rgateway) AND"; }
+// === 1. Определяем тип СУБД ===
+$db_type = $db_link->getAttribute(PDO::ATTR_DRIVER_NAME);
 
-print "<tr align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
-print "<td class=\"data\" colspan=2>".$auth['description']."</td>\n";
-print "<td class=\"data\" colspan=2><a href=/admin/reports/userdaydetail.php?id=$id&date_start=$date1&date_stop=$date2>TOP 10</a></td>\n";
-print "<td class=\"data\" colspan=2><a href=/admin/reports/userdaydetaillog.php?id=$id&date_start=$date1&date_stop=$date2>".WEB_report_detail."</a></td>\n";
-print "</tr>\n";
+// === 2. Выбираем формат даты для каждой СУБД ===
+if ($days_shift <= 1) {
+    $mysql_format = '%Y-%m-%d %H';
+    $pg_format    = 'YYYY-MM-DD HH24';
+} elseif ($days_shift <= 30) {
+    $mysql_format = '%Y-%m-%d';
+    $pg_format    = 'YYYY-MM-DD';
+} elseif ($days_shift <= 730) {
+    $mysql_format = '%Y-%m';
+    $pg_format    = 'YYYY-MM';
+} else {
+    $mysql_format = '%Y';
+    $pg_format    = 'YYYY';
+}
+
+// === 3. Базовые параметры (все значения — через параметры!) ===
+$params = [$date1, $date2, (int)$id];
+
+// === 4. Дополнительное условие по router_id (если нужно) ===
+$router_condition = '';
+if (!empty($rgateway) && $rgateway > 0) {
+    $router_condition = ' AND router_id = ?';
+    $params[] = (int)$rgateway;
+}
 
-$display_date_format='%Y-%m-%d %H';
+// === 5. Формируем запрос в зависимости от СУБД ===
+if ($db_type === 'mysql') {
+    $sSQL = "
+        SELECT 
+            router_id,
+            DATE_FORMAT(ts, '$mysql_format') AS tHour,
+            SUM(byte_in) AS byte_in_sum,
+            SUM(byte_out) AS byte_out_sum,
+            MAX(ROUND(pkt_in / step)) AS pkt_in_max,
+            MAX(ROUND(pkt_out / step)) AS pkt_out_max
+        FROM user_stats_full
+        WHERE ts >= ? AND ts < ? AND auth_id = ?$router_condition
+        GROUP BY DATE_FORMAT(ts, '$mysql_format'), router_id
+        ORDER BY tHour" . ($rgateway > 0 ? '' : ', router_id');
 
-if ($days_shift <=1) { $display_date_format='%Y-%m-%d %H'; }
-if ($days_shift >1 and $days_shift <=30) { $display_date_format='%Y-%m-%d'; }
-if ($days_shift >30 and $days_shift <=730) { $display_date_format='%Y-%m'; }
-if ($days_shift >730) { $display_date_format='%Y'; }
+} elseif ($db_type === 'pgsql') {
+    $sSQL = "
+        SELECT 
+            router_id,
+            TO_CHAR(ts, '$pg_format') AS tHour,
+            SUM(byte_in) AS byte_in_sum,
+            SUM(byte_out) AS byte_out_sum,
+            MAX(ROUND(pkt_in / step)) AS pkt_in_max,
+            MAX(ROUND(pkt_out / step)) AS pkt_out_max
+        FROM user_stats_full
+        WHERE ts >= ? AND ts < ? AND auth_id = ?$router_condition
+        GROUP BY TO_CHAR(ts, '$pg_format'), router_id
+        ORDER BY tHour" . ($rgateway > 0 ? '' : ', router_id');
 
-$sSQL = "SELECT router_id, DATE_FORMAT(ts,'$display_date_format') as tHour, 
-         SUM(byte_in) as byte_in_sum, SUM(byte_out) as byte_out_sum,
-         MAX(ROUND(pkt_in/step)) as pkt_in_max, MAX(ROUND(pkt_out/step)) as pkt_out_max
-         FROM user_stats_full WHERE ts>='$date1' AND ts<'$date2' AND auth_id=$id";
-if ($rgateway == 0) {
-    $sSQL = $sSQL . " GROUP BY DATE_FORMAT(ts,'$display_date_format'),router_id ORDER BY tHour,router_id";
 } else {
-    $sSQL = $sSQL . " AND router_id=$rgateway GROUP BY DATE_FORMAT(ts,'$display_date_format'),router_id ORDER BY tHour";
+    throw new RuntimeException("Unsupported database driver: $db_type");
 }
 
-$userdata = get_records_sql($db_link, $sSQL);
+// === 6. Выполняем запрос ===
+$userdata = get_records_sql($db_link, $sSQL, $params);
+
 $sum_in = 0;
 $sum_out = 0;
+
+print "<tr align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
+print "<td class=\"data\" colspan=2>".$auth['description']."</td>\n";
+print "<td class=\"data\" colspan=2><a href=/admin/reports/userdaydetail.php?id=$id&date_start=$date1&date_stop=$date2>TOP 10</a></td>\n";
+print "<td class=\"data\" colspan=2><a href=/admin/reports/userdaydetaillog.php?id=$id&date_start=$date1&date_stop=$date2>".WEB_report_detail."</a></td>\n";
+print "</tr>\n";
+
 foreach ($userdata as $row) {
     print "<tr align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
     print "<td class=\"data\">" . $gateway_list[$row['router_id']] . "</td>\n";

+ 56 - 40
html/admin/reports/index-full.php

@@ -24,52 +24,70 @@ print_reports_submenu($page_url);
 
 <?php
 
-$traffic_stat_table = 'user_stats_full';
-if ($days_shift >= $config["traffic_ipstat_history"]) { $traffic_stat_table = 'user_stats'; }
-
-$sort_sql=" ORDER BY tin DESC";
-
-if (!empty($sort_field) and !empty($order)) { $sort_sql = " ORDER BY $sort_field $order"; }
-
-$gateway_list = get_gateways($db_link);
-
-$sql_params=[];
-
-$trafSQL = "SELECT user_auth.id, ".$traffic_stat_table.".router_id,
-SUM( byte_in ) AS tin, SUM( byte_out ) AS tout, MAX(ROUND(pkt_in/step)) as pin, MAX(ROUND(pkt_out/step)) as pout 
-FROM ".$traffic_stat_table.",user_auth,user_list WHERE user_list.id=user_auth.user_id 
-AND ".$traffic_stat_table.".auth_id = user_auth.id 
-AND ".$traffic_stat_table.".ts>= ? AND ".$traffic_stat_table.".ts< ?";
-
-array_push($sql_params,$date1);
-array_push($sql_params,$date2);
-
+// === 1. Выбор таблицы статистики ===
+$traffic_stat_table = ($days_shift >= ($config["traffic_ipstat_history"] ?? 30)) 
+    ? 'user_stats' 
+    : 'user_stats_full';
+
+// === 2. Безопасная сортировка ===
+$allowed_sort_fields = ['tin', 'tout', 'pin', 'pout', 'id', 'router_id'];
+$allowed_orders = ['ASC', 'DESC'];
+
+$sort_field = in_array($sort_field, $allowed_sort_fields, true) ? $sort_field : 'tin';
+$order = in_array(strtoupper($order), $allowed_orders, true) ? strtoupper($order) : 'DESC';
+
+$sort_sql = " ORDER BY $sort_field $order";
+
+// === 3. Базовые параметры ===
+$sql_params = [$date1, $date2];
+
+// === 4. Формируем запрос ===
+$trafSQL = "
+    SELECT 
+        user_auth.id,
+        {$traffic_stat_table}.router_id,
+        SUM(byte_in) AS tin,
+        SUM(byte_out) AS tout,
+        MAX(ROUND(pkt_in / step)) AS pin,
+        MAX(ROUND(pkt_out / step)) AS pout
+    FROM {$traffic_stat_table}
+    JOIN user_auth ON {$traffic_stat_table}.auth_id = user_auth.id
+    JOIN user_list ON user_list.id = user_auth.user_id
+    WHERE {$traffic_stat_table}.ts >= ?
+      AND {$traffic_stat_table}.ts < ?
+";
+
+// === 5. Дополнительные условия ===
 if ($rou !== 0) {
-    $trafSQL = $trafSQL . " AND user_list.ou_id=?";
-    array_push($sql_params,$rou);
+    $trafSQL .= " AND user_list.ou_id = ?";
+    $sql_params[] = (int)$rou;
 }
-
-if ($rgateway >0) {
-    $trafSQL = $trafSQL . " AND ".$traffic_stat_table.".router_id= ?";
-    array_push($sql_params,$rgateway);
+if ($rgateway > 0) {
+    $trafSQL .= " AND {$traffic_stat_table}.router_id = ?";
+    $sql_params[] = (int)$rgateway;
 }
 
-$trafSQL = $trafSQL . " GROUP by user_auth.id,".$traffic_stat_table.".router_id";
+// === 6. GROUP BY (корректный для текущего SELECT) ===
+$trafSQL .= " GROUP BY user_auth.id, {$traffic_stat_table}.router_id";
 
-$countSQL = "SELECT Count(*) FROM ($trafSQL) A";
-$count_records = get_single_field($db_link,$countSQL,$sql_params);
+// === 7. Подсчёт записей ===
+$countSQL = "SELECT COUNT(*) FROM ($trafSQL) AS subquery";
+$count_records = (int)get_single_field($db_link, $countSQL, $sql_params);
 
-$total=ceil($count_records/$displayed);
-if ($page>$total) { $page=$total; }
-if ($page<1) { $page=1; }
-$start = ($page * $displayed) - $displayed;
+// === 8. Пагинация ===
+$total = ceil($count_records / $displayed);
+$page = max(1, min($page, $total));
+$start = ($page - 1) * $displayed; // исправлено
 
-#set sort
-$trafSQL=$trafSQL ." $sort_sql LIMIT ? OFFSET ?";
-array_push($sql_params,$displayed);
-array_push($sql_params,$start);
+print_navigation($page_url, $page, $displayed, $count_records, $total);
 
-print_navigation($page_url,$page,$displayed,$count_records,$total);
+// === 9. Добавляем сортировку, LIMIT, OFFSET ===
+$trafSQL .= $sort_sql . " LIMIT ? OFFSET ?";
+$sql_params[] = (int)$displayed;
+$sql_params[] = (int)$start;
+
+// === 10. Выполняем запрос ===
+$traf = get_records_sql($db_link, $trafSQL, $sql_params);
 
 print "<br><br>\n";
 print "<table class=\"data\" cellspacing=\"1\" cellpadding=\"4\">\n";
@@ -86,8 +104,6 @@ print "</tr>\n";
 $total_in = 0;
 $total_out = 0;
 
-$traf = get_records_sql($db_link, $trafSQL, $sql_params);
-
 foreach ($traf as $row) {
     if ($row['tin'] + $row['tout'] == 0) { continue; }
     $total_in += $row['tin'];

+ 56 - 38
html/admin/reports/index.php

@@ -24,51 +24,70 @@ print_reports_submenu($page_url);
 
 <?php
 
-$traffic_stat_table = 'user_stats_full';
-if ($days_shift >= $config["traffic_ipstat_history"]) { $traffic_stat_table = 'user_stats'; }
-
-$sort_sql=" ORDER BY tin DESC";
-
-if (!empty($sort_field) and !empty($order)) { $sort_sql = " ORDER BY $sort_field $order"; }
-
-$gateway_list = get_gateways($db_link);
-
-$sql_params=[];
-
-$trafSQL = "SELECT user_auth.user_id,".$traffic_stat_table.".router_id,
-SUM( byte_in ) AS tin, SUM( byte_out ) AS tout, MAX(ROUND(pkt_in/step)) as pin, MAX(ROUND(pkt_out/step)) as pout 
-FROM ".$traffic_stat_table.",user_auth,user_list WHERE user_list.id=user_auth.user_id 
-AND ".$traffic_stat_table.".auth_id = user_auth.id 
-AND ".$traffic_stat_table.".ts>= ? AND ".$traffic_stat_table.".ts< ?";
-
-array_push($sql_params,$date1);
-array_push($sql_params,$date2);
+// === 1. Выбор таблицы ===
+$traffic_stat_table = ($days_shift >= ($config["traffic_ipstat_history"] ?? 30))
+    ? 'user_stats'
+    : 'user_stats_full';
+
+// === 2. Безопасная сортировка  ===
+$allowed_sort = ['tin', 'tout', 'pin', 'pout', 'user_id', 'router_id'];
+$allowed_order = ['ASC', 'DESC'];
+
+$sort_field = in_array($sort_field, $allowed_sort, true) ? $sort_field : 'tin';
+$order = in_array(strtoupper($order), $allowed_order, true) ? strtoupper($order) : 'DESC';
+$sort_sql = " ORDER BY $sort_field $order";
+
+// === 3. Базовые параметры ===
+$sql_params = [$date1, $date2];
+
+// === 4. Формируем запрос  ===
+$trafSQL = "
+    SELECT 
+        user_auth.user_id,
+        {$traffic_stat_table}.router_id,
+        SUM(byte_in) AS tin,
+        SUM(byte_out) AS tout,
+        MAX(ROUND(pkt_in / step)) AS pin,
+        MAX(ROUND(pkt_out / step)) AS pout
+    FROM {$traffic_stat_table}, user_auth, user_list
+    WHERE 
+        user_list.id = user_auth.user_id
+        AND {$traffic_stat_table}.auth_id = user_auth.id
+        AND {$traffic_stat_table}.ts >= ?
+        AND {$traffic_stat_table}.ts < ?
+";
+
+// === 5. Дополнительные условия ===
 if ($rou !== 0) {
-    $trafSQL = $trafSQL . " AND user_list.ou_id=?";
-    array_push($sql_params,$rou);
+    $trafSQL .= " AND user_list.ou_id = ?";
+    $sql_params[] = (int)$rou;
 }
-
-if ($rgateway >0) {
-    $trafSQL = $trafSQL . " AND ".$traffic_stat_table.".router_id= ?";
-    array_push($sql_params,$rgateway);
+if ($rgateway > 0) {
+    $trafSQL .= " AND {$traffic_stat_table}.router_id = ?";
+    $sql_params[] = (int)$rgateway;
 }
 
-$trafSQL = $trafSQL . "  GROUP by user_auth.user_id,".$traffic_stat_table.".router_id";
+// === 6. GROUP BY  ===
+$trafSQL .= " GROUP BY user_auth.user_id, {$traffic_stat_table}.router_id";
 
-$countSQL = "SELECT Count(*) FROM ($trafSQL) A";
-$count_records = get_single_field($db_link,$countSQL,$sql_params);
+// === 7. Подсчёт записей ===
+$countSQL = "SELECT COUNT(*) FROM ($trafSQL) AS subquery";
+$count_records = (int)get_single_field($db_link, $countSQL, $sql_params);
 
-$total=ceil($count_records/$displayed);
-if ($page>$total) { $page=$total; }
-if ($page<1) { $page=1; }
-$start = ($page * $displayed) - $displayed;
+// === 8. Пагинация ===
+$total = ceil($count_records / $displayed);
+$page = max(1, min($page, $total));
+$start = ($page - 1) * $displayed;
 
-#set sort
-$trafSQL=$trafSQL ." $sort_sql LIMIT ? OFFSET ?";
-array_push($sql_params,$displayed);
-array_push($sql_params,$start);
+print_navigation($page_url, $page, $displayed, $count_records, $total);
 
-print_navigation($page_url,$page,$displayed,$count_records,$total);
+// === 9. Добавляем сортировку + пагинацию ===
+$trafSQL .= $sort_sql . " LIMIT ? OFFSET ?";
+$sql_params[] = (int)$displayed;
+$sql_params[] = (int)$start;
+
+// === 10. Выполняем запрос ===
+$traf = get_records_sql($db_link, $trafSQL, $sql_params);
 
 print "<br><br>\n";
 print "<table class=\"data\">\n";
@@ -84,7 +103,6 @@ print "</tr>\n";
 $total_in = 0;
 $total_out = 0;
 
-$traf = get_records_sql($db_link, $trafSQL,$sql_params);
 
 foreach ($traf as $row) {
     if ($row['tin'] + $row['tout'] == 0) { continue; }

+ 72 - 29
html/admin/reports/userday.php

@@ -7,7 +7,7 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/datetimefilter.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/oufilter.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/gatefilter.php");
 
-$user=get_record_sql($db_link,'SELECT * FROM user_list WHERE id='.$id);
+$user=get_record_sql($db_link,'SELECT * FROM user_list WHERE id=?', [ $id ]);
 
 ?>
 
@@ -32,28 +32,38 @@ $user=get_record_sql($db_link,'SELECT * FROM user_list WHERE id='.$id);
 </tr>
 
 <?php
-$gateway_list = get_gateways($db_link);
 
-$gateway_filter='';
-if (!empty($rgateway) and $rgateway>0) { $gateway_filter="(user_stats.router_id=$rgateway) AND"; }
+$gateway_list = get_gateways($db_link);
 
-$sSQL = "SELECT id,ip,description FROM user_auth WHERE (user_auth.user_id=$id) ORDER BY IP";
-$usersip = get_records_sql($db_link, $sSQL);
+$sSQL = "SELECT id,ip,description FROM user_auth WHERE (user_auth.user_id=?) ORDER BY IP";
+$usersip = get_records_sql($db_link, $sSQL, [ $id ]);
 
 $ipcount = 0;
 $itog_in = 0;
 $itog_out = 0;
 
+// Определяем тип СУБД один раз (лучше вынести выше, но для примера — здесь)
+$db_type = $db_link->getAttribute(PDO::ATTR_DRIVER_NAME);
+
 foreach ($usersip as $row) {
-    $fid = $row["id"];
+    $fid = (int)$row["id"];
     $fip = $row["ip"];
     $fcomm = $row["description"];
 
-    $sSQL = "SELECT SUM(byte_in)+SUM(byte_out) as t_sum FROM user_stats 
-    WHERE $gateway_filter user_stats.ts>='$date1' AND user_stats.ts<'$date2'AND auth_id=$fid";
+    $params = [$date1, $date2];
+    $conditions = ["user_stats.ts >= ?", "user_stats.ts < ?"];
+    
+    if (!empty($rgateway) && $rgateway > 0) {
+        $conditions[] = "user_stats.router_id = ?";
+        $params[] = (int)$rgateway;
+    }
+    $conditions[] = "auth_id = ?";
+    $params[] = $fid;
 
-    $day_summary = get_record_sql($db_link, $sSQL);
-    if (!empty($day_summary)) { $summ = $day_summary['t_sum']; } else { $summ = 0; }
+    $whereClause = implode(' AND ', $conditions);
+    $sSQL = "SELECT SUM(byte_in) + SUM(byte_out) AS t_sum FROM user_stats WHERE $whereClause";
+    $day_summary = get_record_sql($db_link, $sSQL, $params);
+    $summ = !empty($day_summary) ? (float)($day_summary['t_sum'] ?? 0) : 0;
 
     if ($summ > 0) {
         $ipcount++;
@@ -64,30 +74,63 @@ foreach ($usersip as $row) {
         print "<td class=\"data\" ><a href=/admin/reports/userdaydetaillog.php?id=$fid&date_start=$date1&date_stop=$date2>".WEB_report_detail."</a></td>\n";
         print "</tr>\n";
 
-        $display_date_format='%Y-%m-%d %H';
-        if ($days_shift <=1) { $display_date_format='%Y-%m-%d %H'; }
-        if ($days_shift >1 and $days_shift <=30) { $display_date_format='%Y-%m-%d'; }
-        if ($days_shift >30 and $days_shift <=730) { $display_date_format='%Y-%m'; }
-        if ($days_shift >730) { $display_date_format='%Y'; }
-
-        $sSQL = "SELECT user_stats.router_id, DATE_FORMAT(user_stats.ts,'$display_date_format') as tHour,
-                SUM(byte_in) as byte_in_sum, SUM(byte_out) as byte_out_sum 
-                FROM user_stats 
-                WHERE user_stats.ts>='$date1' AND user_stats.ts<'$date2' and auth_id=$fid";
-        if ($rgateway == 0) {
-            $sSQL = $sSQL . " GROUP BY DATE_FORMAT(user_stats.ts,'$display_date_format'),user_stats.router_id 
-            ORDER BY tHour,user_stats.router_id";
+        // === 2. Формат даты в зависимости от СУБД ===
+        if ($days_shift <= 1) {
+            $mysql_format = '%Y-%m-%d %H';
+            $pg_format    = 'YYYY-MM-DD HH24';
+        } elseif ($days_shift <= 30) {
+            $mysql_format = '%Y-%m-%d';
+            $pg_format    = 'YYYY-MM-DD';
+        } elseif ($days_shift <= 730) {
+            $mysql_format = '%Y-%m';
+            $pg_format    = 'YYYY-MM';
         } else {
-            $sSQL = $sSQL . " and user_stats.router_id=$rgateway 
-            GROUP BY DATE_FORMAT(user_stats.ts,'$display_date_format'),user_stats.router_id 
-            ORDER BY tHour";
+            $mysql_format = '%Y';
+            $pg_format    = 'YYYY';
         }
 
-        $userdata = get_records_sql($db_link, $sSQL);
+        // === 3. Параметры для детального запроса ===
+        $detail_params = [$date1, $date2, $fid];
+        $detail_conditions = "user_stats.ts >= ? AND user_stats.ts < ? AND auth_id = ?";
+
+        if ($rgateway > 0) {
+            $detail_conditions .= " AND user_stats.router_id = ?";
+            $detail_params[] = (int)$rgateway;
+        }
+
+        // === 4. Запрос в зависимости от СУБД ===
+        if ($db_type === 'mysql') {
+            $date_expr = "DATE_FORMAT(user_stats.ts, '$mysql_format')";
+            $sSQL = "
+                SELECT 
+                    user_stats.router_id,
+                    $date_expr AS tHour,
+                    SUM(byte_in) AS byte_in_sum,
+                    SUM(byte_out) AS byte_out_sum
+                FROM user_stats
+                WHERE $detail_conditions
+                GROUP BY $date_expr, user_stats.router_id
+                ORDER BY tHour" . ($rgateway > 0 ? '' : ', user_stats.router_id');
+        } elseif ($db_type === 'pgsql') {
+            $date_expr = "TO_CHAR(user_stats.ts, '$pg_format')";
+            $sSQL = "
+                SELECT 
+                    user_stats.router_id,
+                    $date_expr AS tHour,
+                    SUM(byte_in) AS byte_in_sum,
+                    SUM(byte_out) AS byte_out_sum
+                FROM user_stats
+                WHERE $detail_conditions
+                GROUP BY $date_expr, user_stats.router_id
+                ORDER BY tHour" . ($rgateway > 0 ? '' : ', user_stats.router_id');
+        } else {
+            throw new Exception("Unsupported DB: $db_type");
+        }
+
+        $userdata = get_records_sql($db_link, $sSQL, $detail_params);
 
         $sum_in = 0;
         $sum_out = 0;
-
         foreach ($userdata as $userrow) {
             print "<tr align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
             print "<td class=\"data\"> </td>\n";

+ 23 - 8
html/admin/reports/userdaydetail.php

@@ -46,15 +46,30 @@ DNS:&nbsp <input type=checkbox name=dns value="1" <?php print $dns_checked; ?>>
 <td class="data" width=80><b><?php echo WEB_bytes; ?></b></td>
 </tr>
 <?php
-$ip_aton = ip2long($fip);
-
-$gateway_filter='';
-if (!empty($rgateway) and $rgateway>0) { $gateway_filter="(router_id=$rgateway) AND"; }
+// Беззнаковое представление IP
+$ip_long = sprintf('%u', ip2long($fip));
+$params = [$date1, $date2, (int)$id, $ip_long];
+$conditions = [
+    "ts >= ?",
+    "ts < ?",
+    "auth_id = ?",
+    "dst_ip = ?"
+];
+if (!empty($rgateway) && $rgateway > 0) {
+    $conditions[] = "router_id = ?";
+    $params[] = (int)$rgateway;
+}
+$where = implode(' AND ', $conditions);
+$fsql = "
+    SELECT proto, src_ip, src_port, SUM(bytes) AS tin
+    FROM traffic_detail
+    WHERE $where
+    GROUP BY src_ip, src_port, proto
+    ORDER BY tin DESC
+    LIMIT 10
+";
 
-$fsql = "SELECT A.proto, A.src_ip, A.src_port, SUM(A.bytes) as tin FROM traffic_detail A
-            WHERE $gateway_filter (auth_id='$id') and  ts>='$date1' and ts<'$date2' and (A.dst_ip='$ip_aton')
-            GROUP BY A.src_ip, A.src_port, A.proto ORDER BY tin DESC LIMIT 10 OFFSET 0";
-$userdata = get_records_sql($db_link, $fsql);
+$userdata = get_records_sql($db_link, $fsql, $params);
 foreach ($userdata as $row) {
     print "<tr align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
     $proto_name = getprotobynumber($row['proto']);

+ 56 - 17
html/admin/reports/userdaydetaillog.php

@@ -17,7 +17,7 @@ if ($rdns) { $dns_checked='checked="checked"'; }
 
 $dns_cache=NULL;
 
-$usersip = get_record_sql($db_link, "SELECT ip,user_id,description FROM user_auth WHERE user_auth.id=$id");
+$usersip = get_record_sql($db_link, "SELECT ip,user_id,description FROM user_auth WHERE user_auth.id=?", [ $id ]);
 if (empty($usersip)) {
     header("location: /admin/reports/index-full.php");
     exit;
@@ -47,18 +47,61 @@ DNS:&nbsp <input type=checkbox name=dns value="1" <?php print $dns_checked; ?>>
 <?php
 $sort_url = "<a href='userdaydetaillog.php?id=".$id.'&date_start="'.$date1.'"&date_stop="'.$date2.'"';
 
-$gateway_filter='';
-if (!empty($rgateway) and $rgateway>0) { $gateway_filter="(router_id=$rgateway) AND"; }
-if (!empty($search)) { $gateway_filter.=' (src_ip='.ip2long($search).' OR dst_ip='.ip2long($search).') AND'; }
-
-$countSQL="SELECT Count(*) FROM traffic_detail as A WHERE $gateway_filter (auth_id='$id') and ts>='$date1' and ts<'$date2'";
-$count_records = get_single_field($db_link,$countSQL);
-$total=ceil($count_records/$displayed);
-if ($page>$total) { $page=$total; }
-if ($page<1) { $page=1; }
-$start = ($page * $displayed) - $displayed;
-print_navigation($page_url,$page,$displayed,$count_records,$total);
-$gateway_list = get_gateways($db_link);
+// === 1. Валидация и подготовка параметров ===
+$params = [$date1, $date2, (int)$id];
+$conditions = ["ts >= ?", "ts < ?", "auth_id = ?"];
+
+// Фильтр по gateway
+if (!empty($rgateway) && $rgateway > 0) {
+    $conditions[] = "router_id = ?";
+    $params[] = (int)$rgateway;
+}
+
+// Фильтр по IP (если search — валидный IPv4)
+if (!empty($search) && filter_var($search, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
+    $ip_long = sprintf('%u', ip2long($search)); // беззнаковое число
+    $conditions[] = "(src_ip = ? OR dst_ip = ?)";
+    $params[] = $ip_long;
+    $params[] = $ip_long;
+}
+
+$whereClause = implode(' AND ', $conditions);
+
+// === 2. Подсчёт записей ===
+$countSQL = "SELECT COUNT(*) FROM traffic_detail WHERE $whereClause";
+$count_records = (int)get_single_field($db_link, $countSQL, $params);
+
+// === 3. Пагинация ===
+$total = ceil($count_records / $displayed);
+$page = max(1, min($page, $total));
+$start = ($page - 1) * $displayed;
+
+print_navigation($page_url, $page, $displayed, $count_records, $total);
+
+// === 4. Безопасная сортировка (БЕЛЫЙ СПИСОК!) ===
+$allowed_sort_fields = ['ts', 'proto', 'src_ip', 'dst_ip', 'bytes', 'pkt'];
+$allowed_order = ['ASC', 'DESC'];
+
+$sort_field = in_array($sort_field, $allowed_sort_fields, true) ? $sort_field : 'ts';
+$order = in_array(strtoupper($order), $allowed_order, true) ? strtoupper($order) : 'ASC';
+
+// === 5. Запрос данных с пагинацией ===
+$limit = (int)$displayed;
+$offset = (int)$start;
+
+$dataParams = array_merge($params, [$limit, $offset]);
+
+// Используем прямой запрос (без подзапроса — он не нужен для пагинации по id)
+$fsql = "
+    SELECT id, ts, router_id, proto, src_ip, src_port, dst_ip, dst_port, bytes, pkt
+    FROM traffic_detail
+    WHERE $whereClause
+    ORDER BY $sort_field $order
+    LIMIT ? OFFSET ?
+";
+
+$userdata = get_records_sql($db_link, $fsql, $dataParams);
+
 ?>
 
 <br>
@@ -77,10 +120,6 @@ $gateway_list = get_gateways($db_link);
 <td class="data" width=80><b><?php $url = $sort_url.'&sort=pkt&order='.$new_order."'>".WEB_pkts."</a>"; print $url; ?></b></td>
 </tr>
 <?php
-$fsql = "SELECT A.id, A.ts, A.router_id, A.proto, A.src_ip, A.src_port, A.dst_ip, A.dst_port, A.bytes, A.pkt FROM traffic_detail as A JOIN (SELECT id FROM traffic_detail 
-        WHERE $gateway_filter (auth_id='$id') and  ts>='$date1' and ts<'$date2'
-        ORDER BY ts ASC LIMIT $displayed OFFSET $start) as T ON A.id = T.id ORDER BY $sort_table.$sort_field $order";
-$userdata = get_records_sql($db_link, $fsql);
 foreach ($userdata as $row) {
     print "<tr align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
     print "<td class=\"data\">" . $row['ts'] . "</td>\n";

+ 110 - 78
html/admin/reports/wan.php

@@ -7,91 +7,123 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/gatefilter.php");
 
 print_reports_submenu($page_url);
 
-function print_gateway_statistics($db,$device_id,$device_name,$date1,$date2) {
-
-$start_time = new DateTimeImmutable($date1);
-$stop_time = new DateTimeImmutable($date2);
-$interval = $stop_time->diff($start_time,true);
-
-$delta = $interval->format("%a");
-
-$l3_interfaces = get_wan_interfaces($db,$device_id);
+function print_gateway_statistics($db, $device_id, $device_name, $date1, $date2) {
+    $start_time = new DateTimeImmutable($date1);
+    $stop_time = new DateTimeImmutable($date2);
+    $interval = $stop_time->diff($start_time, true);
+    $delta = (int)$interval->format("%a");
+
+    // === Определяем СУБД ===
+    $db_type = $db->getAttribute(PDO::ATTR_DRIVER_NAME);
+
+    // === Формат даты в зависимости от СУБД и периода ===
+    if ($delta == 1) {
+        $mysql_format = '%Y-%m-%d %H:00:00';
+        $pg_format    = 'YYYY-MM-DD HH24:00:00';
+    } elseif ($delta > 1 && $delta <= 31) {
+        $mysql_format = '%Y-%m-%d';
+        $pg_format    = 'YYYY-MM-DD';
+    } else {
+        $mysql_format = '%Y-%m';
+        $pg_format    = 'YYYY-MM';
+    }
 
-#for day - show hour statistics
-$dt_template = '%Y-%m-%d %H:00:00';
-if ($delta == 1) { $dt_template = '%Y-%m-%d %H:00:00'; } 
-    elseif ($delta >1 and $delta<=31) { $dt_template = '%Y-%m-%d'; }
-        elseif ($delta >31) { $dt_template = '%Y-%m'; }
+    $l3_interfaces = get_wan_interfaces($db, $device_id);
+
+    $global_int_in = $global_int_out = $global_int_f_in = $global_int_f_out = 0;
+
+    echo "<tr><td class=\"info\" colspan=\"5\"><b>" . htmlspecialchars($device_name, ENT_QUOTES, 'UTF-8') . "</b></td></tr>\n";
+
+    foreach ($l3_interfaces as $row) {
+        $name = htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8');
+        $desc = !empty($row['description']) 
+            ? ' (' . htmlspecialchars($row['description'], ENT_QUOTES, 'UTF-8') . ')' 
+            : '';
+
+        echo "<tr><td class=\"data\" colspan=\"5\"><b>{$name}{$desc}</b></td></tr>\n";
+        echo "<tr class=\"info\">\n";
+        echo "<td>" . WEB_date . "</td>\n";
+        echo "<td>" . WEB_title_input . "</td>\n";
+        echo "<td>" . WEB_title_output . "</td>\n";
+        echo "<td>" . WEB_title_forward_input . "</td>\n";
+        echo "<td>" . WEB_title_forward_output . "</td>\n";
+        echo "</tr>\n";
+
+        // === Параметризованный запрос ===
+        $params = [$device_id, $row['snmpin'], $date1, $date2];
+
+        if ($db_type === 'mysql') {
+            $date_expr = "DATE_FORMAT(ts, '$mysql_format')";
+            $sql = "
+                SELECT 
+                    $date_expr AS dt,
+                    SUM(bytes_in) AS byte_in,
+                    SUM(bytes_out) AS byte_out,
+                    SUM(forward_in) AS byte_f_in,
+                    SUM(forward_out) AS byte_f_out
+                FROM wan_stats
+                WHERE router_id = ? AND interface_id = ? AND ts >= ? AND ts < ?
+                GROUP BY $date_expr
+                ORDER BY dt";
+        } elseif ($db_type === 'pgsql') {
+            $date_expr = "TO_CHAR(ts, '$pg_format')";
+            $sql = "
+                SELECT 
+                    $date_expr AS dt,
+                    SUM(bytes_in) AS byte_in,
+                    SUM(bytes_out) AS byte_out,
+                    SUM(forward_in) AS byte_f_in,
+                    SUM(forward_out) AS byte_f_out
+                FROM wan_stats
+                WHERE router_id = ? AND interface_id = ? AND ts >= ? AND ts < ?
+                GROUP BY $date_expr
+                ORDER BY dt";
+        } else {
+            throw new Exception("Unsupported DB: $db_type");
+        }
 
+        $int_statistics = get_records_sql($db, $sql, $params);
 
-$global_int_in = 0;
-$global_int_out = 0;
-$global_int_f_in = 0;
-$global_int_f_out = 0;
+        $int_in = $int_out = $int_f_in = $int_f_out = 0;
 
-print "<tr ><td class=\"info\" colspan=5><b>".$device_name."</b></td></tr>\n";
+        foreach ($int_statistics as $stat) {
+            echo "<tr align=\"center\" class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
+            echo "<td class=\"data\">" . htmlspecialchars($stat['dt'], ENT_QUOTES, 'UTF-8') . "</td>\n";
+            echo "<td class=\"data\">" . fbytes($stat['byte_in']) . "</td>\n";
+            echo "<td class=\"data\">" . fbytes($stat['byte_out']) . "</td>\n";
+            echo "<td class=\"data\">" . fbytes($stat['byte_f_in']) . "</td>\n";
+            echo "<td class=\"data\">" . fbytes($stat['byte_f_out']) . "</td>\n";
+            echo "</tr>\n";
 
-foreach ($l3_interfaces as $row) {
-    if (!empty($row['description'])) {
-        print "<tr ><td class=\"data\" colspan=5><b>".$row['name']." (".$row['description'].")</b></td></tr>\n";
-        } else {
-        print "<tr ><td class=\"data\" colspan=5><b>".$row['name']."</b></td></tr>\n";
-        }
-    print "<tr class=\"info\">\n";
-    print "<td >".WEB_date."</td>\n";
-    print "<td >".WEB_title_input."</td>\n";
-    print "<td >".WEB_title_output."</td>\n";
-    print "<td >".WEB_title_forward_input."</td>\n";
-    print "<td >".WEB_title_forward_output."</td>\n";
-    print "</tr>\n";
-
-    $trafSQL="SELECT DATE_FORMAT(ts, '".$dt_template."'  ) AS dt,SUM(bytes_in) as byte_in,SUM(bytes_out) as byte_out, SUM(forward_in) as byte_f_in,SUM(forward_out) as byte_f_out FROM wan_stats ";
-    $trafSQL .=" WHERE router_id='".$device_id."' AND interface_id='".$row['snmpin']."' AND time>='$date1' AND time<'$date2'";
-    $trafSQL .=" GROUP BY DATE_FORMAT(ts, '".$dt_template."' ) ORDER BY dt;";
-
-    $int_statistics = get_records_sql($db,$trafSQL);
-
-    $int_in = 0;
-    $int_out = 0;
-    $int_f_in = 0;
-    $int_f_out = 0;
-    foreach ($int_statistics as $stat) {
-        print "<tr align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
-        print "<td class=\"data\">".$stat['dt']."</td>\n";
-        print "<td class=\"data\">".fbytes($stat['byte_in'])."</td>\n";
-        print "<td class=\"data\">".fbytes($stat['byte_out'])."</td>\n";
-        print "<td class=\"data\">".fbytes($stat['byte_f_in'])."</td>\n";
-        print "<td class=\"data\">".fbytes($stat['byte_f_out'])."</td>\n";
-        print "</tr>\n";
-        $int_in +=$stat['byte_in'];
-        $int_out +=$stat['byte_out'];
-        $int_f_in +=$stat['byte_f_in'];
-        $int_f_out +=$stat['byte_f_out'];
+            $int_in += $stat['byte_in'];
+            $int_out += $stat['byte_out'];
+            $int_f_in += $stat['byte_f_in'];
+            $int_f_out += $stat['byte_f_out'];
         }
-    print "<tr align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
-    print "<td class=\"data\"><b>".WEB_title_itog."</b></td>\n";
-    print "<td class=\"data\">".fbytes($int_in)."</td>\n";
-    print "<td class=\"data\">".fbytes($int_out)."</td>\n";
-    print "<td class=\"data\">".fbytes($int_f_in)."</td>\n";
-    print "<td class=\"data\">".fbytes($int_f_out)."</td>\n";
-    print "</tr>\n";
-
-    $global_int_in += $int_in;
-    $global_int_out += $int_out;
-    $global_int_f_in += $int_f_in;
-    $global_int_f_out += $int_f_out;
-    }
 
-print "<tr align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
-print "<td class=\"data\" colspan=5><b>".WEB_title_itog."</b></td></tr>\n";
-print "<tr align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
-print "<td class=\"data\"></td>\n";
-print "<td class=\"data\">".fbytes($global_int_in)."</td>\n";
-print "<td class=\"data\">".fbytes($global_int_out)."</td>\n";
-print "<td class=\"data\">".fbytes($global_int_f_in)."</td>\n";
-print "<td class=\"data\">".fbytes($global_int_f_out)."</td>\n";
-print "</tr>\n";
+        echo "<tr align=\"center\" class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
+        echo "<td class=\"data\"><b>" . WEB_title_itog . "</b></td>\n";
+        echo "<td class=\"data\">" . fbytes($int_in) . "</td>\n";
+        echo "<td class=\"data\">" . fbytes($int_out) . "</td>\n";
+        echo "<td class=\"data\">" . fbytes($int_f_in) . "</td>\n";
+        echo "<td class=\"data\">" . fbytes($int_f_out) . "</td>\n";
+        echo "</tr>\n";
+
+        $global_int_in += $int_in;
+        $global_int_out += $int_out;
+        $global_int_f_in += $int_f_in;
+        $global_int_f_out += $int_f_out;
+    }
 
+    echo "<tr align=\"center\" class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
+    echo "<td class=\"data\" colspan=\"5\"><b>" . WEB_title_itog . "</b></td></tr>\n";
+    echo "<tr align=\"center\" class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
+    echo "<td class=\"data\"></td>\n";
+    echo "<td class=\"data\">" . fbytes($global_int_in) . "</td>\n";
+    echo "<td class=\"data\">" . fbytes($global_int_out) . "</td>\n";
+    echo "<td class=\"data\">" . fbytes($global_int_f_in) . "</td>\n";
+    echo "<td class=\"data\">" . fbytes($global_int_f_out) . "</td>\n";
+    echo "</tr>\n";
 }
 
 ?>
@@ -115,7 +147,7 @@ if ($rgateway==0) {
         print_gateway_statistics($db_link,$key,$val,$date1,$date2);
         }
     } else {
-        $router = get_record_sql($db_link,"SELECT device_name FROM devices WHERE id='".$rgateway."'");
+        $router = get_record_sql($db_link,"SELECT device_name FROM devices WHERE id=?", [ $rgateway ]);
         print_gateway_statistics($db_link,$rgateway,$router['device_name'],$date1,$date2);
     }
 

+ 6 - 6
html/admin/users/edit_alias.php

@@ -6,8 +6,8 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
 
 $msg_error = "";
 
-$sSQL = "SELECT * FROM user_auth WHERE id=$id";
-$auth_info = get_record_sql($db_link, $sSQL);
+$sSQL = "SELECT * FROM user_auth WHERE id=?";
+$auth_info = get_record_sql($db_link, $sSQL, [ $id ]);
 
 if (empty($auth_info['dns_name']) or $auth_info['deleted']) {
     header("Location: /admin/users/editauth.php?id=".$id);
@@ -20,8 +20,8 @@ if (isset($_POST["s_remove"])) {
     $s_id = $_POST["s_id"];
     foreach ($s_id as $key => $val) {
         if (isset($val)) {
-            LOG_INFO($db_link, "Remove alias id: $val ".dump_record($db_link,'user_auth_alias','id='.$val));
-            delete_record($db_link, "user_auth_alias", "id=" . $val);
+            LOG_INFO($db_link, "Remove alias id: $val ".dump_record($db_link,'user_auth_alias','id=?', [ $val ]));
+            delete_record($db_link, "user_auth_alias", "id=?", [ $val ]);
         }
     }
     header("Location: " . $page_url);
@@ -47,7 +47,7 @@ if (isset($_POST['s_save'])) {
             if (empty($f_dnsname) or !checkValidHostname($f_dnsname) or !checkUniqHostname($db_link,$id,$f_dnsname)) { continue; }
             $new['alias'] = $f_dnsname;
             $new['description'] = trim($_POST['s_description'][$j]);
-            update_record($db_link, "user_auth_alias", "id='{$save_id}'", $new);
+            update_record($db_link, "user_auth_alias", "id=?", $new, [ $save_id ]);
         }
     }
     header("Location: " . $page_url);
@@ -111,7 +111,7 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
 	<td><input type="submit" onclick="return confirm('<?php echo WEB_msg_delete; ?>?')" name="s_remove" value="<?php echo WEB_btn_delete; ?>"></td>
 </tr>
 <?php
-$t_user_auth_alias = get_records($db_link,'user_auth_alias',"auth_id=$id ORDER BY alias");
+$t_user_auth_alias = get_records_sql($db_link,"SELECT * FROM user_auth_alias WHERE auth_id=? ORDER BY alias", [ $id ]);
 if (!empty($t_user_auth_alias)) {
 foreach ( $t_user_auth_alias as $row ) {
     print "<tr align=center>\n";

+ 5 - 5
html/admin/users/edit_rules.php

@@ -6,15 +6,15 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
 
 $msg_error = "";
 
-$sSQL = "SELECT * FROM user_list WHERE id=$id";
-$auth_info = get_record_sql($db_link, $sSQL);
+$sSQL = "SELECT * FROM user_list WHERE id=?";
+$auth_info = get_record_sql($db_link, $sSQL, [ $id ]);
 
 if (isset($_POST["s_remove"])) {
     $s_id = $_POST["s_id"];
     foreach ($s_id as $key => $val) {
         if (isset($val)) {
-            LOG_INFO($db_link, "Remove rule id: $val ".dump_record($db_link,'auth_rules','id='.$val));
-            delete_record($db_link, "auth_rules", "id=" . $val);
+            LOG_INFO($db_link, "Remove rule id: $val ".dump_record($db_link,'auth_rules','id=?', [ $val ]));
+            delete_record($db_link, "auth_rules", "id=?" , [ $val ]);
         }
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);
@@ -74,7 +74,7 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
     <td><input type="submit" onclick="return confirm('<?php echo WEB_msg_delete; ?>?')" name="s_remove" value="<?php echo WEB_btn_delete; ?>"></td>
 </tr>
 <?php
-$t_auth_rules = get_records($db_link,'auth_rules',"user_id=$id ORDER BY id");
+$t_auth_rules = get_records_sql($db_link,"SELECT * FROM auth_rules WHERE user_id=? ORDER BY id", [ $id ]);
 foreach ( $t_auth_rules as $row ) {
     print "<tr align=center>\n";
     print "<td class=\"data\" style='padding:0'><input type=checkbox name=s_id[] value='{$row['id']}'></td>\n";

+ 25 - 25
html/admin/users/editauth.php

@@ -5,14 +5,14 @@ require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/idfilter.php");
 
 $msg_error = "";
 
-$old_auth_info = get_record_sql($db_link, "SELECT * FROM user_auth WHERE id=" . $id);
+$old_auth_info = get_record_sql($db_link, "SELECT * FROM user_auth WHERE id=?", [ $id ]);
 if (empty($old_auth_info)) {
     header("Location: /admin/");
     }
 
 $parent_id = $old_auth_info['user_id'];
 
-$user_info = get_record_sql($db_link, "SELECT * FROM user_list WHERE id=" . $parent_id);
+$user_info = get_record_sql($db_link, "SELECT * FROM user_list WHERE id=?", [ $parent_id ]);
 $parent_ou_id = $user_info['ou_id'];
 $user_enabled = $user_info['enabled'];
 
@@ -24,8 +24,8 @@ if (isset($_POST["editauth"]) and !$old_auth_info['deleted']) {
         //search mac
         $mac_exists = find_mac_in_subnet($db_link, $ip, $mac);
         if (isset($mac_exists) and $mac_exists['count'] >= 1 and !in_array($parent_id, $mac_exists['users_id'])) {
-            $dup_sql = "SELECT * FROM user_list WHERE id=" . $mac_exists['users_id']['0'];
-            $dup_info = get_record_sql($db_link, $dup_sql);
+            $dup_sql = "SELECT * FROM user_list WHERE id=? ";
+            $dup_info = get_record_sql($db_link, $dup_sql, [  $mac_exists['users_id']['0'] ]);
             $msg_error = "Mac already exists at another user in this subnet! Skip creating $ip [$mac].<br>Old user id: " . $dup_info['id'] . " login: " . $dup_info['login'];
             $_SESSION[$page_url]['msg'] = $msg_error;
             LOG_ERROR($db_link, $msg_error);
@@ -40,9 +40,9 @@ if (isset($_POST["editauth"]) and !$old_auth_info['deleted']) {
             }
         }
         //search ip
-        $dup_ip_record = get_record_sql($db_link, "SELECT * FROM user_auth WHERE ip_int=$ip_aton AND id<>$id AND deleted=0");
+        $dup_ip_record = get_record_sql($db_link, "SELECT * FROM user_auth WHERE ip_int=? AND id<>? AND deleted=0", [ $ip_aton, $id ]);
         if (!empty($dup_ip_record)) {
-            $dup_info = get_record_sql($db_link, "SELECT * FROM user_list WHERE id=" . $dup_ip_record['user_id']);
+            $dup_info = get_record_sql($db_link, "SELECT * FROM user_list WHERE id=?", [ $dup_ip_record['user_id'] ]);
             $msg_error = "$ip already exists. Skip creating $ip [$mac].<br>Old user id: " . $dup_info['id'] . " login: " . $dup_info['login'];
             $_SESSION[$page_url]['msg'] = $msg_error;
             LOG_ERROR($db_link, $msg_error);
@@ -61,14 +61,14 @@ if (isset($_POST["editauth"]) and !$old_auth_info['deleted']) {
         if (isset($_POST["f_dns_ptr"]) or !empty($f_dns_name)) { $new['dns_ptr_only']=1; }
 
         //update device managment ip
-        $device = get_record_sql($db_link,"SELECT * FROM devices WHERE ip_int=".$old_auth_info['ip_int']);
+        $device = get_record_sql($db_link,"SELECT * FROM devices WHERE ip_int=? ", [ $old_auth_info['ip_int'] ]);
         if (!empty($device)) {
             $dev['ip'] = $ip;
             $dev['ip_int']=$ip_aton;
-            update_record($db_link,"devices","id=".$device['id'],$dev);
+            update_record($db_link,"devices","id=?",$dev, [ $device['id'] ]);
             }
 
-        $dns_alias_count = get_count_records($db_link,'user_auth_alias','auth_id='.$id);
+        $dns_alias_count = get_count_records($db_link,'user_auth_alias','auth_id=?', [ $id ]);
         if (!empty($f_dnsname) and !$new['dns_ptr_only']) {
             $domain_zone = get_option($db_link, 33);
             $domain_zone = ltrim($domain_zone, '.');
@@ -101,11 +101,11 @@ if (isset($_POST["editauth"]) and !$old_auth_info['deleted']) {
         if (empty($f_dnsname) or $new['dns_ptr_only']) {
             //remove all dns aliases
             $new['dns_name'] = '';
-            $t_user_auth_alias = get_records($db_link,'user_auth_alias',"auth_id=$id ORDER BY alias");
+            $t_user_auth_alias = get_records($db_link,'user_auth_alias',"auth_id=? ORDER BY alias", [ $id ]);
             if (!empty($t_user_auth_alias)) {
                 foreach ( $t_user_auth_alias as $row ) {
-                    LOG_INFO($db_link, "Remove alias id: ".$row['id']." for auth_id: $id :: ".dump_record($db_link,'user_auth_alias','id='.$row['id']));
-                    delete_record($db_link,'user_auth_alias','id='.$row['id']);
+                    LOG_INFO($db_link, "Remove alias id: ".$row['id']." for auth_id: $id :: ".dump_record($db_link,'user_auth_alias','id=?', [ $row['id'] ]));
+                    delete_record($db_link,'user_auth_alias','id=?', [ $row['id'] ]);
                     }
                 }
             }
@@ -155,7 +155,7 @@ if (isset($_POST["editauth"]) and !$old_auth_info['deleted']) {
             $new['nagios_status'] = 'UP';
             }
         if (!$user_enabled) { $new['enabled']=0; }
-        $changes = get_diff_rec($db_link, "user_auth", "id='$id'", $new, 0);
+        $changes = get_diff_rec($db_link, "user_auth", "id=?", $new, 0, [ $id ]);
         if (!empty($changes)) {
             LOG_WARNING($db_link, "Changed record for $ip! Log: " . $changes, $id);
             }
@@ -168,7 +168,7 @@ if (isset($_POST["editauth"]) and !$old_auth_info['deleted']) {
                 }
             exit;
             } else {
-            update_record($db_link, "user_auth", "id='$id'", $new);
+            update_record($db_link, "user_auth", "id=?", $new, [ $id ]);
             }
     } else {
         $msg_error = "$msg_ip_error xxx.xxx.xxx.xxx";
@@ -180,7 +180,7 @@ if (isset($_POST["editauth"]) and !$old_auth_info['deleted']) {
 
 if (isset($_POST["moveauth"]) and !$old_auth_info['deleted']) {
     $new_parent_id = $_POST["f_new_parent"] * 1;
-    $moved_auth = get_record_sql($db_link,"SELECT description FROM user_auth WHERE id=".$id);
+    $moved_auth = get_record_sql($db_link,"SELECT description FROM user_auth WHERE id=?", [ $id ]);
     $changes = apply_auth_rule($db_link, $moved_auth, $new_parent_id);
     update_record($db_link, "user_auth", "id='$id'", $changes);
     LOG_WARNING($db_link, "IP-address moved to another user! Applyed: " . hash_to_text($changes), $id);
@@ -199,8 +199,8 @@ if (isset($_POST["recovery"]) and $old_auth_info['deleted']) {
         //search mac
         $mac_exists = find_mac_in_subnet($db_link, $ip, $mac);
         if (isset($mac_exists) and $mac_exists['count'] >= 1 and !in_array($parent_id, $mac_exists['users_id'])) {
-            $dup_sql = "SELECT * FROM user_list WHERE id=" . $mac_exists['users_id']['0'];
-            $dup_info = get_record_sql($db_link, $dup_sql);
+            $dup_sql = "SELECT * FROM user_list WHERE id=?";
+            $dup_info = get_record_sql($db_link, $dup_sql, [ $mac_exists['users_id']['0'] ]);
             $msg_error = "Mac already exists at another user in this subnet! Skip creating $ip [$mac].<br>Old user id: " . $dup_info['id'] . " login: " . $dup_info['login'];
             $_SESSION[$page_url]['msg'] = $msg_error;
             LOG_ERROR($db_link, $msg_error);
@@ -215,9 +215,9 @@ if (isset($_POST["recovery"]) and $old_auth_info['deleted']) {
             }
         }
         //search ip
-        $dup_ip_record = get_record_sql($db_link, "SELECT * FROM user_auth WHERE ip_int=$ip_aton AND id<>$id AND deleted=0");
+        $dup_ip_record = get_record_sql($db_link, "SELECT * FROM user_auth WHERE ip_int=? AND id<>? AND deleted=0", [ $ip_aton, $id ]);
         if (!empty($dup_ip_record)) {
-            $dup_info = get_record_sql($db_link, "SELECT * FROM user_list WHERE id=" . $dup_ip_record['user_id']);
+            $dup_info = get_record_sql($db_link, "SELECT * FROM user_list WHERE id=?", [ $dup_ip_record['user_id'] ]);
             $msg_error = "$ip already exists. Skip creating $ip [$mac].<br>Old user id: " . $dup_info['id'] . " login: " . $dup_info['login'];
             $_SESSION[$page_url]['msg'] = $msg_error;
             LOG_ERROR($db_link, $msg_error);
@@ -230,7 +230,7 @@ if (isset($_POST["recovery"]) and $old_auth_info['deleted']) {
 
         $parent_id = $old_auth_info['user_id'];
 
-        $old_parent = get_record_sql($db_link, "SELECT * FROM user_list WHERE id=".$parent_id);
+        $old_parent = get_record_sql($db_link, "SELECT * FROM user_list WHERE id=? ", [ $parent_id ]);
         if (empty($old_parent)) {
             $new_user_info = get_new_user_id($db_link, $ip, $mac, NULL);
             if ($new_user_info['user_id']) { $new_user_id = $new_user_info['user_id']; }
@@ -263,12 +263,12 @@ if (isset($_POST["recovery"]) and $old_auth_info['deleted']) {
             $new['queue_id'] = get_int($_POST["f_queue_id"]);
             $new['filter_group_id'] = get_int($_POST["f_group_id"]);
         }
-        $changes = get_diff_rec($db_link, "user_auth", "id='$id'", $new, 0);
+        $changes = get_diff_rec($db_link, "user_auth", "id=?", $new, 0, [ $id ]);
         if (!empty($changes)) {
             LOG_WARNING($db_link, "Recovered ip-address. Applyed: $changes", $id);
         }
         $new = apply_auth_rule($db_link, $new, $new['user_id']);
-        update_record($db_link, "user_auth", "id='$id'", $new);
+        update_record($db_link, "user_auth", "id=?", $new, [ $id ]);
     } else {
         $msg_error = "$msg_ip_error xxx.xxx.xxx.xxx/xx";
         $_SESSION[$page_url]['msg'] = $msg_error;
@@ -281,9 +281,9 @@ unset($_POST);
 
 require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/header.php");
 
-$sSQL = "SELECT * FROM user_auth WHERE id=$id";
-$auth_info = get_record_sql($db_link, $sSQL);
-$device = get_record_sql($db_link, "SELECT * FROM devices WHERE user_id=" . $auth_info['user_id']);
+$sSQL = "SELECT * FROM user_auth WHERE id=?";
+$auth_info = get_record_sql($db_link, $sSQL, [ $id ]);
+$device = get_record_sql($db_link, "SELECT * FROM devices WHERE user_id=?", [ $auth_info['user_id'] ]);
 
 $parent_name = get_login($db_link, $auth_info['user_id']);
 if (empty($parent_name)) { $parent_name=$auth_info['user_id']; }

+ 30 - 28
html/admin/users/edituser.php

@@ -8,8 +8,8 @@ require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/sortfilter.php");
 
 $msg_error = "";
 
-$sSQL = "SELECT * FROM user_list WHERE id=$id";
-$user_info = get_record_sql($db_link, $sSQL);
+$sSQL = "SELECT * FROM user_list WHERE id=?";
+$user_info = get_record_sql($db_link, $sSQL, [ $id ]);
 
 if (empty($user_info)) {
     header("Location: /admin/");
@@ -36,26 +36,28 @@ if (isset($_POST["edituser"])) {
         $new["month_quota"] = get_int(trim($_POST["f_permonth"]));
         $new["permanent"] = $_POST["f_permanent"] * 1;
     }
-    $changes = get_diff_rec($db_link, "user_list", "id='$id'", $new, 0);
+    $changes = get_diff_rec($db_link, "user_list", "id=?", $new, 0, [ $id ]);
     if (!empty($changes)) {
         LOG_WARNING($db_link, "Changed user id: $id login: " . $new["login"] . ". \r\nApply: $changes");
     }
-    update_record($db_link, "user_list", "id='$id'", $new);
+    update_record($db_link, "user_list", "id=?", $new, [ $id ]);
     if (!$new["enabled"]) {
-        run_sql($db_link, "UPDATE user_auth SET enabled=0, changed=1 WHERE user_id=" . $id);
+        update_record($db_link, 'user_auth', 'user_id = ?', [ 'enabled' => 0,'changed' => 1 ], [ $id ]);
     }
     if (!empty($new["fio"])) {
-        run_sql($db_link, "UPDATE user_auth SET description='" . db_escape($db_link, $new["fio"]) . "' WHERE user_id=" . $id . " AND deleted=0 AND (description IS NULL or description='' or description='" . $user_info["fio"] . "')");
+	update_records($db_link,'user_auth',"user_id=? AND deleted=0 AND (description IS NULL or description='' or description=?)", [ 'description'=> $new["fio"] ], [ $id, $user_info["fio"] ]);
     }
-    run_sql($db_link, "UPDATE user_auth SET ou_id=" . $new["ou_id"] . " WHERE user_id=" . $id);
-    run_sql($db_link, "UPDATE devices SET device_name='" . $new["login"] . "' WHERE user_id=" . $id);
+    // Обновление ou_id в user_auth
+    update_records($db_link, 'user_auth', 'user_id = ? AND deleted=0', [ 'ou_id' => $new["ou_id"] ], [ $id ]);
+    // Обновление device_name в devices
+    update_record($db_link, 'devices', 'user_id = ?', [ 'device_name' => $new["login"] ], [ $id ]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
 }
 
 if (isset($_POST["addMacRule"])) {
     unset($new);
-    $first_auth = get_records_sql($db_link, "SELECT mac FROM user_auth WHERE user_id=" . $id . " AND deleted=0 AND LENGTH(mac)>0 ORDER BY id");
+    $first_auth = get_records_sql($db_link, "SELECT mac FROM user_auth WHERE user_id=? AND deleted=0 AND LENGTH(mac)>0 ORDER BY id", [ $id ]);
     foreach ($first_auth as $row) {
         if (!empty($row['mac'])) { add_auth_rule($db_link, $row['mac'], 2, $id); }
         }
@@ -64,7 +66,7 @@ if (isset($_POST["addMacRule"])) {
 }
 
 if (isset($_POST["delMacRule"])) {
-    run_sql($db_link, "DELETE FROM auth_rules WHERE user_id=" . $id . " AND type=2");
+    run_sql($db_link, "DELETE FROM auth_rules WHERE user_id=? AND type=2", [ $id ]);
     LOG_INFO($db_link, "All autorules removed for id: $id login: " . $user_info["login"] . " by mac");
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
@@ -72,7 +74,7 @@ if (isset($_POST["delMacRule"])) {
 
 if (isset($_POST["addIPRule"])) {
     unset($new);
-    $first_auth = get_records_sql($db_link, "SELECT ip FROM user_auth WHERE user_id=" . $id . " AND deleted=0 AND LENGTH(ip)>0 ORDER BY id");
+    $first_auth = get_records_sql($db_link, "SELECT ip FROM user_auth WHERE user_id = ? AND deleted = 0 AND ip IS NOT NULL ORDER BY id", [$id]);
     foreach ($first_auth as $row) {
         if (!empty($row['ip'])) { add_auth_rule($db_link, $row['ip'], 1, $id); }
         }
@@ -81,15 +83,15 @@ if (isset($_POST["addIPRule"])) {
 }
 
 if (isset($_POST["delIPRule"])) {
-    run_sql($db_link, "DELETE FROM auth_rules WHERE user_id=" . $id . " AND type=1");
+    run_sql($db_link, "DELETE FROM auth_rules WHERE user_id=? AND type=1", [ $id ]);
     LOG_INFO($db_link, "Removed all auto rules for id: $id login: " . $user_info["login"] . " by ip");
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
 }
 
 if (isset($_POST["showDevice"])) {
-    $device = get_record_sql($db_link, "SELECT * FROM devices WHERE user_id=" . $id);
-    $auth = get_record_sql($db_link, "SELECT * FROM user_auth WHERE user_id=" . $id);
+    $device = get_record_sql($db_link, "SELECT * FROM devices WHERE user_id=?", [$id]);
+    $auth = get_record_sql($db_link, "SELECT * FROM user_auth WHERE user_id=?", [$id]);
     if (empty($device) and !empty($auth)) {
         $new['user_id'] = $id;
         $new['device_name'] = $user_info['login'];
@@ -137,8 +139,8 @@ if (isset($_POST["addauth"])) {
             if (!empty($fmac) and !empty($fip)) {
                 $mac_exists = find_mac_in_subnet($db_link, $fip, $fmac);
                 if (!empty($mac_exists) and $mac_exists['count'] >= 1 and !in_array($id, $mac_exists['users_id'])) {
-                    $dup_sql = "SELECT * FROM user_list WHERE id=" . $mac_exists['users_id']['0'];
-                    $dup_info = get_record_sql($db_link, $dup_sql);
+                    $dup_sql = "SELECT * FROM user_list WHERE id=?";
+                    $dup_info = get_record_sql($db_link, $dup_sql, [ $mac_exists['users_id']['0'] ]);
                     $msg_error = "Mac already exists at another user in this subnet! Skip creating $fip [$fmac].<br>Old user id: " . $dup_info['id'] . " login: " . $dup_info['login'];
                     $_SESSION[$page_url]['msg'] = $msg_error;
                     LOG_ERROR($db_link, $msg_error);
@@ -155,9 +157,9 @@ if (isset($_POST["addauth"])) {
                 }
             }
             //search ip
-            $dup_ip_record = get_record_sql($db_link, "SELECT * FROM user_auth WHERE ip_int=$ip_aton AND user_id<>" . $id . " AND deleted=0");
+            $dup_ip_record = get_record_sql($db_link, "SELECT * FROM user_auth WHERE ip_int=? AND user_id<>? AND deleted=0", [ $ip_aton, $id ]);
             if (!empty($dup_ip_record)) {
-                $dup_info = get_record_sql($db_link, "SELECT * FROM user_list WHERE id=" . $dup_ip_record['user_id']);
+                $dup_info = get_record_sql($db_link, "SELECT * FROM user_list WHERE id=?", [ $dup_ip_record['user_id'] ]);
                 $msg_error = "$fip already exists. Skip creating $fip [$fmac].<br>Old user id: " . $dup_info['id'] . " login: " . $dup_info['login'];
                 $_SESSION[$page_url]['msg'] = $msg_error;
                 LOG_ERROR($db_link, $msg_error);
@@ -169,7 +171,7 @@ if (isset($_POST["addauth"])) {
                 $new['dhcp'] = $f_dhcp;
                 $new['created_by'] = 'manual';
                 if (!empty($fdescription)) { $new['description'] = $fdescription; }
-                update_record($db_link, "user_auth", "id=" . $fid, $new);
+                update_record($db_link, "user_auth", "id=?", $new, [ $fid ]);
                 LOG_WARNING($db_link, "Add ip for login: " . $user_info["login"] . ": ip => $fip, mac => $fmac", $fid);
                 header("Location: /admin/users/editauth.php?id=" . $fid);
                 exit;
@@ -198,7 +200,7 @@ if (isset($_POST["new_user"])) {
     $save_traf = get_option($db_link, 23) * 1;
     foreach ($auth_id as $key => $val) {
         if ($val) {
-            $auth_info = get_record_sql($db_link, "SELECT * FROM user_auth WHERE id=$val");
+            $auth_info = get_record_sql($db_link, "SELECT * FROM user_auth WHERE id=?", [ $val ]);
             $ou_id = $user_info["ou_id"];
             $login = NULL;
             if (!empty($auth_info["dns_name"])) {
@@ -216,14 +218,14 @@ if (isset($_POST["new_user"])) {
             if (empty($login)) {
                 $login = $auth_info["ip"];
             }
-            $new_user = get_record_sql($db_link, "SELECT * FROM user_list WHERE LOWER(login)=LOWER('$login') and deleted=0");
+	    $new_user = get_record_sql($db_link, "SELECT * FROM user_list WHERE LOWER(login) = LOWER(?) AND deleted = 0", [$login]);
             if (!empty($new_user)) {
                 // move auth
                 $auth["user_id"] = $new_user["id"];
                 $auth["ou_id"] = $new_user["ou_id"];
                 $auth["save_traf"] = $save_traf;
                 $auth = apply_auth_rule($db_link, $auth, $l_id);
-                update_record($db_link, "user_auth", "id='" . $val . "'", $auth);
+                update_record($db_link, "user_auth", "id=?", $auth,  [ $val ]);
                 LOG_WARNING($db_link, "ip from id: $val moved to another user user_id: " . $new_user["id"], $val);
             } else {
                 $new["login"] = $login;
@@ -235,7 +237,7 @@ if (isset($_POST["new_user"])) {
                 $l_id = insert_record($db_link, "user_list", $new);
                 $auth["user_id"] = $l_id;
                 $auth["save_traf"] = $save_traf;
-                update_record($db_link, "user_auth", "id='" . $val . "'", $auth);
+                update_record($db_link, "user_auth", "id=?", $auth, [ $val ]);
                 LOG_WARNING($db_link, "Create user from ip: login => $login. ip-record auth_id: $val moved to this user.", $val);
             }
         }
@@ -302,19 +304,19 @@ require_once($_SERVER["DOCUMENT_ROOT"] . "/inc/header.php");
                 print "<td>";
                 print_url(WEB_user_rule_list, "/admin/users/edit_rules.php?id=$id");
                 print "</td>";
-                $rule_count = get_count_records($db_link, "auth_rules", "user_id=" . $id);
+                $rule_count = get_count_records($db_link, "auth_rules", "user_id=?", [ $id ]);
                 print "<td > Count: " . $rule_count . "</td>";
-                $first_auth = get_record_sql($db_link, "SELECT id FROM user_auth WHERE user_id=" . $id . " AND deleted=0 ORDER BY id");
+                $first_auth = get_record_sql($db_link, "SELECT id FROM user_auth WHERE user_id=? AND deleted=0 ORDER BY id", [ $id ]);
                 if (!empty($first_auth)) {
                     //mac
-                    $mac_rule_count = get_count_records($db_link, "auth_rules", "user_id=" . $id . " AND type=2");
+                    $mac_rule_count = get_count_records($db_link, "auth_rules", "user_id=? AND type=2", [ $id ]);
                     if (!empty($mac_rule_count)) {
                         print "<td><input type=\"submit\" name=\"delMacRule\" value=" . WEB_btn_mac_del . " ></td>";
                     } else {
                         print "<td><input type=\"submit\" name=\"addMacRule\" value=" . WEB_btn_mac_add . " ></td>";
                     }
                     //ip
-                    $ip_rule_count = get_count_records($db_link, "auth_rules", "user_id=" . $id . " AND type=1");
+                    $ip_rule_count = get_count_records($db_link, "auth_rules", "user_id=? AND type=1", [ $id ]);
                     if (!empty($ip_rule_count)) {
                         print "<td><input type=\"submit\" name=\"delIPRule\" value=" . WEB_btn_ip_del . " ></td>";
                     } else {
@@ -373,7 +375,7 @@ require_once($_SERVER["DOCUMENT_ROOT"] . "/inc/header.php");
 
             <?php
 
-            $flist = get_records($db_link, 'user_auth', "user_id=" . $id . " and deleted=0 ORDER BY $sort_table.$sort_field $order");
+            $flist = get_records($db_link, 'user_auth', "user_id=? and deleted=0 ORDER BY $sort_table.$sort_field $order", [ $id ]);
             if (!empty($flist)) {
                 foreach ($flist as $row) {
                     $dhcp_str = '';

+ 49 - 15
html/admin/users/index.php

@@ -12,14 +12,14 @@ $msg_error = "";
 if (isset($_POST["create"])) {
     $login = trim($_POST["newlogin"]);
     if (!empty($login)) {
-        $lcount = get_count_records($db_link,"user_list","LOWER(login)=LOWER('$login')");
+        $lcount = get_count_records($db_link,"user_list","LOWER(login)=LOWER(?)", [ $login ]);
         if ($lcount > 0) {
             $msg_error = WEB_cell_login." ".$login." ".$msg_exists."!";
             unset($_POST);
         } else {
             $new['login'] = $login;
             $new['ou_id'] = $rou;
-            $ou_info = get_record_sql($db_link,"SELECT * FROM ou WHERE id=".$rou);
+            $ou_info = get_record_sql($db_link,"SELECT * FROM ou WHERE id=?", [ $rou ]);
 	    if (!empty($ou_info)) {
 		if (empty($ou_info['enabled'])) { $ou_info['enabled'] = 0; }
 		if (empty($ou_info['queue_id'])) { $ou_info['queue_id'] = 0; }
@@ -100,20 +100,55 @@ if ($msg_error) {
 
 <?php
 
-$sort_table = 'U';
 $sort_url = "<a href=/admin/users/index.php?";
 
-if ($rou == 0) { $filter = "U.ou_id=O.id and U.deleted=0"; } else { $filter = "U.ou_id=O.id and U.deleted=0 and U.ou_id=$rou"; }
+// === 1. Базовые условия ===
+$params = [];
+$conditions = ["U.deleted = 0", "U.ou_id = O.id"];
 
-$countSQL = "SELECT Count(*) FROM user_list U, ou O WHERE $filter";
-$count_records = get_single_field($db_link,$countSQL);
-$total=ceil($count_records/$displayed);
-if ($page>$total) { $page=$total; }
-if ($page<1) { $page=1; }
-$start = ($page * $displayed) - $displayed;
-print_navigation($page_url,$page,$displayed,$count_records,$total);
+if ($rou != 0) {
+    $conditions[] = "U.ou_id = ?";
+    $params[] = (int)$rou;
+}
+
+$whereClause = implode(' AND ', $conditions);
+
+// === 2. Безопасная сортировка (БЕЛЫЙ СПИСОК!) ===
+$allowed_sort_fields = ['id', 'login', 'fio', 'ou_name', 'enabled', 'day_quota', 'month_quota', 'blocked', 'permanent'];
+$allowed_order = ['ASC', 'DESC'];
+
+$sort_field = in_array($sort_field, $allowed_sort_fields, true) ? $sort_field : 'id';
+$order = in_array(strtoupper($order), $allowed_order, true) ? strtoupper($order) : 'ASC';
+
+// === 3. Подсчёт записей ===
+$countSQL = "SELECT COUNT(*) FROM user_list U JOIN ou O ON U.ou_id = O.id WHERE $whereClause";
+$count_records = (int)get_single_field($db_link, $countSQL, $params);
+
+// === 4. Пагинация ===
+$total = ceil($count_records / $displayed);
+$page = max(1, min($page, $total));
+$start = ($page - 1) * $displayed;
+
+print_navigation($page_url, $page, $displayed, $count_records, $total);
+
+// === 5. Запрос данных ===
+$limit = (int)$displayed;
+$offset = (int)$start;
+
+$dataParams = array_merge($params, [$limit, $offset]);
+
+$sSQL = "
+    SELECT 
+        U.id, U.login, U.fio, O.ou_name, U.enabled, 
+        U.day_quota, U.month_quota, U.blocked, U.permanent
+    FROM user_list U
+    JOIN ou O ON U.ou_id = O.id
+    WHERE $whereClause
+    ORDER BY U.$sort_field $order
+    LIMIT ? OFFSET ?
+";
 
-$sSQL = "SELECT U.id, U.login, U.fio, O.ou_name, U.enabled, U.day_quota, U.month_quota, U.blocked, U.permanent FROM user_list U, ou O WHERE $filter ORDER BY $sort_table.$sort_field $order LIMIT $displayed OFFSET $start";
+$users = get_records_sql($db_link, $sSQL, $dataParams);
 
 ?>
 
@@ -134,10 +169,9 @@ $sSQL = "SELECT U.id, U.login, U.fio, O.ou_name, U.enabled, U.day_quota, U.month
 </tr>
 <?php
 
-$users = get_records_sql($db_link, $sSQL);
 
 foreach ($users as $row) {
-    $auth_customs = get_count_records($db_link,"user_auth","user_id=".$row['id']." AND deleted=0 AND enabled <>'".$row['enabled']."'");
+    $auth_customs = get_count_records($db_link,"user_auth","user_id=? AND deleted=0 AND enabled <>?", [ $row['id'],$row['enabled'] ] );
     $cl = "data";
     if (! $row['enabled']) {
         $cl = "off";
@@ -159,7 +193,7 @@ foreach ($users as $row) {
     if (empty($row['login'])) { $row['login']=$row['id']; }
     print "<td class=\"$cl\" align=left><a href=edituser.php?id=".$row['id'].">" . $row['login'] . "</a></td>\n";
     print "<td class=\"$cl\">".$row['fio']."</td>\n";
-    $rules_count = get_count_records($db_link,"auth_rules","user_id=".$row['id']);
+    $rules_count = get_count_records($db_link,"auth_rules","user_id=?", [$row['id']]);
     print "<td class=\"$cl\">".$rules_count."</td>\n";
     print "<td class=\"$cl\">".$row['ou_name']."</td>\n";
     print "<td class=\"$cl\">".get_qa($row['enabled']) . "</td>\n";

+ 171 - 166
html/api.php

@@ -1,184 +1,189 @@
 <?php
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.php");
 
-$action='';
-$ip='';
-$mac='';
-$rec_id='';
-$ip_aton=NULL;
-$f_subnet='';
-
-//MODE
-if (!empty($_GET['get'])) { $action = 'get_'.$_GET['get']; }
-if (!empty($_GET['send'])) { $action = 'send_'.$_GET['send']; }
-if (!empty($_POST['get'])) { $action = 'get_'.$_POST['get']; }
-if (!empty($_POST['send'])) { $action = 'send_'.$_POST['send']; }
-
-//GET
-if (!empty($_GET['ip'])) { $ip = $_GET['ip']; }
-if (!empty($_GET['mac'])) { $mac = mac_dotted(trim($_GET['mac'])); }
-if (!empty($_GET['id'])) { $rec_id = $_GET['id']; }
-if (!empty($_GET['subnet'])) { $f_subnet = $_GET['subnet']; }
-
-//POST
-if (!empty($_POST['ip'])) { $ip = $_POST['ip']; }
-if (!empty($_POST['mac'])) { $mac = mac_dotted($_POST['mac']); }
-if (!empty($_POST['id'])) { $rec_id = $_POST['id']; }
-if (!empty($_POST['subnet'])) { $f_subnet = $_POST['subnet']; }
+// Определяем page_url для сессии (можно использовать константу или путь)
+$page_url = 'api';
+
+// Получаем параметры через безопасные функции
+$action_get  = getParam('get',    $page_url);
+$action_send = getParam('send',   $page_url);
+$ip          = getParam('ip',     $page_url, '', FILTER_VALIDATE_IP, ['flags' => FILTER_FLAG_IPV4]);
+$mac_raw     = getParam('mac',    $page_url, '');
+$rec_id      = getParam('id',     $page_url, null, FILTER_VALIDATE_INT);
+$f_subnet    = getParam('subnet', $page_url, '');
+
+// Обработка MAC-адреса
+$mac = !empty($mac_raw) ? mac_dotted(trim($mac_raw)) : '';
+
+// Определяем действие
+$action = '';
+if (!empty($action_get))  { $action = 'get_' . $action_get; }
+if (!empty($action_send)) { $action = 'send_' . $action_send; }
+
+// Дополнительные параметры для send_dhcp
+$dhcp_hostname = getParam('hostname', $page_url, '');
+$faction_raw   = getParam('action', $page_url, 1, FILTER_VALIDATE_INT);
 
 if (!empty($action)) {
 
-      if (!empty($ip) and checkValidIp($ip))  { $ip_aton=ip2long($ip); }
-
-      //return user auth record
-      //api.php?login=<LOGIN>&api_key=<API_KEY>&get=user_auth&{mac=<MAC>|ip=<IP>}
-      if ($action ==='get_user_auth') {
-          $result=[];
-          $sql='';
-          LOG_VERBOSE($db_link,"API: Get User Auth record with ip: $ip mac: $mac id: $rec_id");
-          if (!empty($mac) and !empty($ip_aton)) { 
-                $sql="SELECT * FROM user_auth WHERE ip_int=".$ip_aton." AND mac='".$mac."' AND deleted=0"; 
-              } else {
-              if (!empty($ip_aton)) { $sql = "SELECT * FROM user_auth WHERE ip_int=".$ip_aton." AND deleted=0"; }
-              if (!empty($mac)) { $sql="SELECT * FROM user_auth WHERE mac='".$mac."' AND deleted=0"; }
-              }
-          if (!empty($rec_id)) { $sql="SELECT * FROM user_auth WHERE id=".$rec_id; }
-          if (!empty($sql)) {
-              $result=get_record_sql($db_link,$sql);
-              if (!empty($result)) {
-                  LOG_VERBOSE($db_link,"API: Record found.");
-                  try {
-                    $json = json_encode($result, JSON_THROW_ON_ERROR);
-                    header('Content-Type: application/json');
-                    echo $json;
-                    }
-                  catch (JsonException $exception) {
-                    LOG_ERROR($db_link,"API: Error decoding JSON. Error: ".$exception->getMessage());
-                    exit($exception->getMessage());
-                  }
-                } else {
-                  LOG_VERBOSE($db_link,"API: Not found.");
-                }
-             } else {
-              LOG_VERBOSE($db_link,"API: not enough parameters");
-             }
-          }
-
-      //return user records
-      //api.php?login=<LOGIN>&api_key=<API_KEY>&get=user&id=<ID>
-      if ($action ==='get_user') {
-          $result=[];
-          $sql='';
-          LOG_VERBOSE($db_link,"API: Get User record with id: $rec_id");
-          if (!empty($rec_id)) {
-                $sql="SELECT * FROM user_list WHERE id=$rec_id";
-                $result=get_record_sql($db_link,$sql);
-                if (!empty($result)) {
-                    LOG_VERBOSE($db_link,"API: User record found.");
-                    $sql="SELECT * FROM user_auth WHERE deleted=0 AND user_id=".$rec_id;
-                    $result_auth=get_records_sql($db_link,$sql);
-                    try {
-                        if (!empty($result_auth)) { $result["auth"]=$result_auth; } else { $result["auth"]=''; }
-                        $json_user = json_encode($result, JSON_THROW_ON_ERROR);
-                        header('Content-Type: application/json');
-                        echo $json_user;
-                        }
-                    catch (JsonException $exception) {
-                        LOG_ERROR($db_link,"API: Error decoding JSON. Error: ".$exception->getMessage());
-                        exit($exception->getMessage());
-                      }
-                } else {
-                  LOG_VERBOSE($db_link,"API: User not found.");
-                }
-             } else {
-              LOG_VERBOSE($db_link,"API: not enough parameters");
-             }
-          }
-
-      //return all records for dhcp server
-      //api.php?login=<LOGIN>&api_key=<API_KEY>&get=dhcp_all
-      if ($action ==='get_dhcp_all') {
-            $result=[];
-            LOG_VERBOSE($db_link,"API: Get all dhcp records");
-            $sql = "SELECT ua.id, ua.ip, ua.ip_int, ua.mac, ua.description, ua.dns_name, ua.dhcp_option_set, ua.dhcp_acl, ua.ou_id, SUBSTRING_INDEX(s.subnet, '/', 1) AS subnet_base 
-                FROM  user_auth ua JOIN subnets s ON ua.ip_int BETWEEN s.ip_int_start AND s.ip_int_stop
-                WHERE ua.dhcp = 1 AND ua.deleted = 0 AND s.dhcp = 1 ORDER BY ua.ip_int";
-            $result = get_records_sql($db_link, $sql);
-            if (!empty($result)) {
-                    LOG_VERBOSE($db_link, "API: " . count($result) . " records found.");
-                    try {
-                        header('Content-Type: application/json');
-                        echo json_encode($result, JSON_THROW_ON_ERROR);
-                    } catch (JsonException $exception) {
-                        LOG_ERROR($db_link, "API: JSON encoding error: " . $exception->getMessage());
-                        exit("JSON error");
-                        }
-                    } else {
-                        LOG_VERBOSE($db_link, "API: No records found.");
-                        header('Content-Type: application/json');
-                        echo json_encode([]);
-                    }
+    // Преобразуем IP в BIGINT (если валиден)
+    $ip_aton = null;
+    if ($ip) {
+        $ip_aton = sprintf('%u', ip2long($ip));
+    }
+
+    // === get_user_auth ===
+    if ($action === 'get_user_auth') {
+        LOG_VERBOSE($db_link, "API: Get User Auth record with ip: $ip mac: $mac id: $rec_id");
+        
+        $result = null;
+        $sql = "";
+        $params = [];
+
+        if ($rec_id > 0) {
+            $sql = "SELECT * FROM user_auth WHERE id = ?";
+            $params = [$rec_id];
+        } elseif ($ip_aton !== null && !empty($mac)) {
+            $sql = "SELECT * FROM user_auth WHERE ip_int = ? AND mac = ? AND deleted = 0";
+            $params = [$ip_aton, $mac];
+        } elseif ($ip_aton !== null) {
+            $sql = "SELECT * FROM user_auth WHERE ip_int = ? AND deleted = 0";
+            $params = [$ip_aton];
+        } elseif (!empty($mac)) {
+            $sql = "SELECT * FROM user_auth WHERE mac = ? AND deleted = 0";
+            $params = [$mac];
+        }
+
+        if ($sql) {
+            $result = get_record_sql($db_link, $sql, $params);
+            if ($result) {
+                LOG_VERBOSE($db_link, "API: Record found.");
+                header('Content-Type: application/json; charset=utf-8');
+                echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
+            } else {
+                LOG_VERBOSE($db_link, "API: Not found.");
+                http_response_code(404);
+                echo json_encode(['error' => 'Not found']);
             }
+        } else {
+            LOG_VERBOSE($db_link, "API: not enough parameters");
+            http_response_code(400);
+            echo json_encode(['error' => 'Missing parameters']);
+        }
+    }
 
-      //return all record in subnet for dhcp-server
-      //api.php?login=<LOGIN>&api_key=<API_KEY>&get=dhcp_subnet&subnet=<SUBNET>
-      if ($action ==='get_dhcp_subnet' and !empty($f_subnet)) {
-            $result=[];
-            $f_subnet = trim($f_subnet, "'");
-            LOG_VERBOSE($db_link,"API: Get dhcp records for subnet ".$f_subnet);
-            $sql = "SELECT ua.id, ua.ip, ua.ip_int, ua.mac, ua.description, ua.dns_name, ua.dhcp_option_set, ua.dhcp_acl, ua.ou_id, SUBSTRING_INDEX(s.subnet, '/', 1) AS subnet_base 
-                FROM  user_auth ua JOIN subnets s ON ua.ip_int BETWEEN s.ip_int_start AND s.ip_int_stop
-                WHERE ua.dhcp = 1 AND ua.deleted = 0 AND s.dhcp = 1 AND SUBSTRING_INDEX(s.subnet, '/', 1) = '".$f_subnet."' ORDER BY ua.ip_int";
-            $result = get_records_sql($db_link, $sql);
-            if (!empty($result)) {
-                    LOG_VERBOSE($db_link, "API: " . count($result) . " records found.");
-                    try {
-                        header('Content-Type: application/json');
-                        echo json_encode($result, JSON_THROW_ON_ERROR);
-                    } catch (JsonException $exception) {
-                        LOG_ERROR($db_link, "API: JSON encoding error: " . $exception->getMessage());
-                        exit("JSON error");
-                        }
-                    } else {
-                        LOG_VERBOSE($db_link, "API: No records found.");
-                        header('Content-Type: application/json');
-                        echo json_encode([]);
-                    }
+    // === get_user ===
+    if ($action === 'get_user') {
+        LOG_VERBOSE($db_link, "API: Get User record with id: $rec_id");
+        
+        if ($rec_id > 0) {
+            $user = get_record_sql($db_link, "SELECT * FROM user_list WHERE id = ?", [$rec_id]);
+            if ($user) {
+                $auth_records = get_records_sql($db_link, 
+                    "SELECT * FROM user_auth WHERE deleted = 0 AND user_id = ?", 
+                    [$rec_id]
+                );
+                $user['auth'] = $auth_records ?: [];
+                
+                LOG_VERBOSE($db_link, "API: User record found.");
+                header('Content-Type: application/json; charset=utf-8');
+                echo json_encode($user, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
+            } else {
+                LOG_VERBOSE($db_link, "API: User not found.");
+                http_response_code(404);
+                echo json_encode(['error' => 'User not found']);
             }
+        } else {
+            LOG_VERBOSE($db_link, "API: not enough parameters");
+            http_response_code(400);
+            echo json_encode(['error' => 'Missing user ID']);
+        }
+    }
 
-      //add dhcp log record
-      //api.php?login=<LOGIN>&api_key=<API_KEY>&send=dhcp&mac=<MAC>&ip=<IP>&action=<0|1>[&hostname=<HOSTNAME>]
-      if ($action ==='send_dhcp') {
-          if (!empty($ip) and !empty($mac)) {
-              $dhcp_hostname = '';
-              if (!empty($_GET["hostname"])) { $dhcp_hostname = trim($_GET["hostname"]); }
-              if (!empty($_POST["hostname"])) { $dhcp_hostname = trim($_POST["hostname"]); }
-              $faction = $_GET["action"] * 1;
-              $dhcp_action = 'add';
-              if ($faction == 1) { $dhcp_action = 'add'; }
-              if ($faction == 0) { $dhcp_action = 'del'; }
-              LOG_VERBOSE($db_link, "API: external dhcp request for $ip [$mac] $dhcp_action");
-              if (checkValidIp($ip) and is_our_network($db_link, $ip)) {
-                    $new['action']=$dhcp_action;
-                    $new['mac']=$mac;
-                    $new['ip']=$ip;
-                    $new['dhcp_hostname']=$dhcp_hostname;
-                    insert_record($db_link,"dhcp_queue",$new);
-                    } else { LOG_ERROR($db_link, "$ip - wrong network!"); }
-              }
-          }
-      } else {
-        LOG_WARNING($db_link,"API: Unknown request");
-      }
+    // === get_dhcp_all ===
+    if ($action === 'get_dhcp_all') {
+        LOG_VERBOSE($db_link, "API: Get all dhcp records");
+        $result = get_records_sql($db_link, "
+            SELECT 
+                ua.id, ua.ip, ua.ip_int, ua.mac, ua.description, 
+                ua.dns_name, ua.dhcp_option_set, ua.dhcp_acl, ua.ou_id,
+                SUBSTRING_INDEX(s.subnet, '/', 1) AS subnet_base 
+            FROM user_auth ua 
+            JOIN subnets s ON ua.ip_int BETWEEN s.ip_int_start AND s.ip_int_stop
+            WHERE ua.dhcp = 1 AND ua.deleted = 0 AND s.dhcp = 1 
+            ORDER BY ua.ip_int
+        ");
+        
+        LOG_VERBOSE($db_link, "API: " . count($result) . " records found.");
+        header('Content-Type: application/json; charset=utf-8');
+        echo json_encode($result ?: [], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
+    }
+
+    // === get_dhcp_subnet ===
+    if ($action === 'get_dhcp_subnet' && !empty($f_subnet)) {
+        // Валидация подсети как IPv4-адреса
+        if (!filter_var($f_subnet, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
+            http_response_code(400);
+            echo json_encode(['error' => 'Invalid subnet format']);
+            exit;
+        }
+        
+        LOG_VERBOSE($db_link, "API: Get dhcp records for subnet " . $f_subnet);
+        $result = get_records_sql($db_link, "
+            SELECT 
+                ua.id, ua.ip, ua.ip_int, ua.mac, ua.description, 
+                ua.dns_name, ua.dhcp_option_set, ua.dhcp_acl, ua.ou_id,
+                SUBSTRING_INDEX(s.subnet, '/', 1) AS subnet_base 
+            FROM user_auth ua 
+            JOIN subnets s ON ua.ip_int BETWEEN s.ip_int_start AND s.ip_int_stop
+            WHERE ua.dhcp = 1 AND ua.deleted = 0 AND s.dhcp = 1 
+              AND SUBSTRING_INDEX(s.subnet, '/', 1) = ?
+            ORDER BY ua.ip_int
+        ", [$f_subnet]);
+
+        LOG_VERBOSE($db_link, "API: " . count($result) . " records found.");
+        header('Content-Type: application/json; charset=utf-8');
+        echo json_encode($result ?: [], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
+    }
+
+    // === send_dhcp ===
+    if ($action === 'send_dhcp') {
+        if ($ip && $mac) {
+            $faction = $faction_raw !== null ? (int)$faction_raw : 1;
+            $dhcp_action = ($faction === 0) ? 'del' : 'add';
+
+            LOG_VERBOSE($db_link, "API: external dhcp request for $ip [$mac] $dhcp_action");
+            
+            if (is_our_network($db_link, $ip)) {
+                insert_record($db_link, "dhcp_queue", [
+                    'action' => $dhcp_action,
+                    'mac' => $mac,
+                    'ip' => $ip,
+                    'dhcp_hostname' => $dhcp_hostname
+                ]);
+                http_response_code(201);
+                echo json_encode(['status' => 'queued']);
+            } else {
+                LOG_ERROR($db_link, "$ip - wrong network!");
+                http_response_code(400);
+                echo json_encode(['error' => 'IP not in allowed network']);
+            }
+        } else {
+            http_response_code(400);
+            echo json_encode(['error' => 'Missing IP or MAC']);
+        }
+    }
+} else {
+    LOG_WARNING($db_link, "API: Unknown request");
+    http_response_code(400);
+    echo json_encode(['error' => 'Unknown action']);
+}
 
 ob_end_flush();
 
-// Легкая очистка сессии без установки кук
+// Очистка сессии
 if (session_status() === PHP_SESSION_ACTIVE) {
     $_SESSION = [];
     session_destroy();
 }
-
-unset($_GET);
-unset($_POST);
 ?>

+ 28 - 25
html/inc/auth.php

@@ -9,38 +9,41 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.utils.php");
 
 login($db_link);
 
-$start_array = explode(" ",$start_time);
+$start_array = explode(" ", $start_time);
 $start_time = $start_array[1] + $start_array[0];
 
-$page_full_url=$_SERVER['PHP_SELF'];
+$page_full_url = $_SERVER['PHP_SELF'];
 $page_url_array = explode('?', $page_full_url);
 
-$page_url=$_SERVER["REQUEST_URI"];
+// Определяем базовый URL страницы
+$page_url = !empty($page_url_array[0]) ? $page_url_array[0] : $_SERVER["REQUEST_URI"];
+$page_url_args = !empty($page_url_array[1]) ? $page_url_array[1] : '';
 
-if (!empty($page_url_array[0])) { $page_url = $page_url_array[0]; }
-if (!empty($page_url_array[1])) { $page_url_args = $page_url_array[1]; } else { $page_url_args=''; }
+// Получаем параметры через безопасные функции
+$id = getParam('id', $page_url);
 
-if (!empty($_GET['id'])) { $id = $_GET["id"]; }
-if (!empty($_POST['id'])) { $id = $_POST["id"]; }
-if (!empty($id) and !empty($page_url)) { $page_url = $page_url.'?id='.$id; }
+if (!empty($id) && !empty($page_url)) {
+    $page_url = $page_url . '?id=' . urlencode($id);
+}
 
 if (empty($page_url)) {
-    header("Location: ".DEFAULT_PAGE);
+    header("Location: " . DEFAULT_PAGE);
     exit;
-    }
-
-if (isset($_GET['page'])){ $page = $_GET['page']; }
-if (isset($_POST['page'])){ $page = $_POST['page']; }
-if (!isset($page) and isset($_SESSION[$page_url]['page'])) { $page=$_SESSION[$page_url]['page']; }
-if (!isset($page)) { $page=1; }
-
-if (!isset($default_displayed)) { $default_displayed=50; }
-
-if (isset($_POST['rows'])) { $displayed=$_POST['rows']; }
-if (!isset($displayed) and isset($_SESSION[$page_url]['rows'])) { $displayed=$_SESSION[$page_url]['rows']; }
-if (!isset($displayed)) { $displayed=$default_displayed; }
-
-$_SESSION[$page_url]['page']=$page;
-$_SESSION[$page_url]['rows']=$displayed;
-
+}
+
+// Получаем номер страницы
+$page = getParam('page', $page_url, 1, FILTER_VALIDATE_INT);
+if ($page < 1) $page = 1;
+
+// Получаем количество строк на странице
+$default_displayed = 50;
+$displayed = getPOST('rows', $page_url, null, FILTER_VALIDATE_INT);
+if ($displayed === null) {
+    $displayed = $_SESSION[$page_url]['rows'] ?? $default_displayed;
+}
+if ($displayed < 1) $displayed = $default_displayed;
+
+// Сохраняем в сессии
+$_SESSION[$page_url]['page'] = $page;
+$_SESSION[$page_url]['rows'] = $displayed;
 ?>

+ 18 - 10
html/inc/authidfilter.php

@@ -1,12 +1,20 @@
 <?php
-if (! defined("CONFIG")) die("Not defined");
-
-if (isset($_GET['auth_id'])) { $auth_id = $_GET["auth_id"] * 1; }
-if (isset($_POST['auth_id'])) { $auth_id = $_POST["auth_id"] * 1; }
-if (!isset($auth_id)) {
-    if (isset($_SESSION[$page_url]['auth_id'])) { $auth_id = $_SESSION[$page_url]['auth_id']*1; }
-    }
-if (!isset($auth_id) and isset($default_auth_id)) { $auth_id=$default_auth_id; }
-if (!isset($auth_id)) { header("Location: /admin/index.php"); }
-$_SESSION[$page_url]['auth_id']=$auth_id;
+if (!defined("CONFIG")) die("Not defined");
+
+// Получаем auth_id из GET, POST или сессии, с валидацией как целого числа
+$auth_id = getParam('auth_id', $page_url, null, FILTER_VALIDATE_INT);
+
+// Если не получили из запроса/сессии, пробуем использовать значение по умолчанию
+if ($auth_id === null && isset($default_auth_id)) {
+    $auth_id = (int)$default_auth_id;
+}
+
+// Если всё ещё нет auth_id - редирект
+if ($auth_id === null || $auth_id <= 0) {
+    header("Location: /admin/index.php");
+    exit;
+}
+
+// Сохраняем в сессии
+$_SESSION[$page_url]['auth_id'] = $auth_id;
 ?>

+ 12 - 8
html/inc/buildingfilter.php

@@ -1,10 +1,14 @@
 <?php
-if (! defined("CONFIG")) die("Not defined");
-if (isset($_POST['building_id']) or isset($_GET['building_id'])) {
-    if (isset($_GET['building_id'])) { $f_building_id = $_GET['building_id']*1; }
-    if (isset($_POST['building_id'])) { $f_building_id = $_POST['building_id']*1; }
-    } else {
-    if (isset($_SESSION[$page_url]['building_id'])) { $f_building_id=$_SESSION[$page_url]['building_id']; } else { $f_building_id = 0; }
-    }
-$_SESSION[$page_url]['building_id']=$f_building_id;
+if (!defined("CONFIG")) die("Not defined");
+
+// Получаем building_id с валидацией как целого числа
+$f_building_id = getParam('building_id', $page_url, 0, FILTER_VALIDATE_INT);
+
+// Гарантируем, что значение неотрицательное
+if ($f_building_id < 0) {
+    $f_building_id = 0;
+}
+
+// Сохраняем в сессии
+$_SESSION[$page_url]['building_id'] = $f_building_id;
 ?>

+ 14 - 9
html/inc/cidrfilter.php

@@ -1,11 +1,16 @@
 <?php
-if (! defined("CONFIG")) die("Not defined");
-
-if (!isset($default_cidr)) { $default_cidr = ''; }
-if (isset($_GET['cidr'])) { $rcidr = $_GET["cidr"]; }
-if (isset($_POST['cidr'])) { $rcidr = $_POST["cidr"]; }
-if (! isset($rcidr)) {
-    if (isset($_SESSION[$page_url]['cidr'])) { $rcidr=$_SESSION[$page_url]['cidr']; } else { $rcidr = $default_cidr; }
-    }
-$_SESSION[$page_url]['cidr']=$rcidr;
+if (!defined("CONFIG")) die("Not defined");
+
+$default_cidr = $default_cidr ?? '';
+
+// Получаем raw-значение без фильтрации
+$rcidr_raw = getParam('cidr', $page_url, $default_cidr);
+
+// Заменяем русскую "ю" и "Ю" на точку (на случай переключённой раскладки)
+$rcidr_normalized = str_replace(['ю', 'Ю'], '.', $rcidr_raw);
+
+// Обрезаем пробелы
+$rcidr = trim($rcidr_normalized);
+
+$_SESSION[$page_url]['cidr'] = $rcidr;
 ?>

+ 12 - 3
html/inc/common.php

@@ -90,13 +90,22 @@ FILTER_FLAG_ENCODE_AMP       // Кодирует амперсанд (&)
 */
 
 function getParam($name, $page_url, $default = null, $filter = FILTER_DEFAULT, $options = []) {
-    $value = filter_input(INPUT_POST, $name, $filter, $options) ?? filter_input(INPUT_GET, $name, $filter, $options);
-    return $value !== null ? $value : ($_SESSION[$page_url][$name] ?? $default);
+    $value = filter_input(INPUT_POST, $name, $filter, $options) ?? 
+             filter_input(INPUT_GET, $name, $filter, $options);
+    // Если filter_input вернул false — это ошибка валидации, считаем как отсутствие значения
+    if ($value === false || $value === null) {
+        return $_SESSION[$page_url][$name] ?? $default;
+    }
+    return $value;
 }
 
 function getPOST($name, $page_url, $default = null, $filter = FILTER_DEFAULT, $options = []) {
     $value = filter_input(INPUT_POST, $name, $filter, $options);
-    return $value !== null ? $value : ($_SESSION[$page_url][$name] ?? $default);
+    // Если filter_input вернул false — это ошибка валидации
+    if ($value === false || $value === null) {
+        return $_SESSION[$page_url][$name] ?? $default;
+    }
+    return $value;
 }
 
 function intval_or_zero($v): int {

+ 1 - 1
html/inc/datetimefilter.php

@@ -4,7 +4,7 @@ if (!defined("CONFIG")) die("Not defined");
 
 $date_shift = getParam('date_shift', $page_url, 'h');
 $date_start = getParam('date_start', $page_url, '');
-$date_stop = getParam('date_stop', $page_url, ''); // Исправлено: было 'date_start'
+$date_stop = getParam('date_stop', $page_url, '');
 
 // Инициализация переменных
 $datetime_start = null;

+ 4 - 8
html/inc/devmodelsfilter.php

@@ -1,10 +1,6 @@
 <?php
-if (! defined("CONFIG")) die("Not defined");
-if (isset($_POST['devmodels']) or isset($_GET['devmodels'])) {
-    if (isset($_GET['devmodels'])) { $f_devmodel_id = $_GET['devmodels']*1; }
-    if (isset($_POST['devmodels'])) { $f_devmodel_id = $_POST['devmodels']*1; }
-    } else {
-    if (isset($_SESSION[$page_url]['devmodels'])) { $f_devmodel_id=$_SESSION[$page_url]['devmodels']; } else { $f_devmodel_id = -1; }
-    }
-$_SESSION[$page_url]['devmodels']=$f_devmodel_id;
+if (!defined("CONFIG")) die("Not defined");
+
+$f_devmodel_id = getParam('devmodels', $page_url, -1, FILTER_VALIDATE_INT);
+$_SESSION[$page_url]['devmodels'] = (int)$f_devmodel_id;
 ?>

+ 4 - 8
html/inc/devtypesfilter.php

@@ -1,10 +1,6 @@
 <?php
-if (! defined("CONFIG")) die("Not defined");
-if (isset($_POST['devtypes']) or isset($_GET['devtypes'])) {
-    if (isset($_GET['devtypes'])) { $f_devtype_id = $_GET['devtypes']*1; }
-    if (isset($_POST['devtypes'])) { $f_devtype_id = $_POST['devtypes']*1; }
-    } else {
-    if (isset($_SESSION[$page_url]['devtypes'])) { $f_devtype_id=$_SESSION[$page_url]['devtypes']; } else { $f_devtype_id = -1; }
-    }
-$_SESSION[$page_url]['devtypes']=$f_devtype_id;
+if (!defined("CONFIG")) die("Not defined");
+
+$f_devtype_id = getParam('devtypes', $page_url, -1, FILTER_VALIDATE_INT);
+$_SESSION[$page_url]['devtypes'] = (int)$f_devtype_id;
 ?>

+ 3 - 8
html/inc/dhcpfilter.php

@@ -1,11 +1,6 @@
 <?php
-if (! defined("CONFIG")) die("Not defined");
+if (!defined("CONFIG")) die("Not defined");
 
-if (isset($_GET['dhcp_enabled'])) { $dhcp_enabled = $_GET["dhcp_enabled"] * 1; }
-if (isset($_POST['dhcp_enabled'])) { $dhcp_enabled = $_POST["dhcp_enabled"] * 1; }
-if (!isset($dhcp_enabled)) {
-    if (isset($_SESSION[$page_url]['dhcp_enabled'])) { $dhcp_enabled = $_SESSION[$page_url]['dhcp_enabled']*1; }
-    }
-if (!isset($dhcp_enabled)) { $dhcp_enabled = 0; }
-$_SESSION[$page_url]['dhcp_enabled']=$dhcp_enabled;
+$dhcp_enabled = getParam('dhcp_enabled', $page_url, 0, FILTER_VALIDATE_INT);
+$_SESSION[$page_url]['dhcp_enabled'] = (int)$dhcp_enabled;
 ?>

+ 3 - 8
html/inc/dynfilter.php

@@ -1,11 +1,6 @@
 <?php
-if (! defined("CONFIG")) die("Not defined");
+if (!defined("CONFIG")) die("Not defined");
 
-if (isset($_GET['dynamic_enabled'])) { $dynamic_enabled = $_GET["dynamic_enabled"] * 1; }
-if (isset($_POST['dynamic_enabled'])) { $dynamic_enabled = $_POST["dynamic_enabled"] * 1; }
-if (!isset($dynamic_enabled)) {
-    if (isset($_SESSION[$page_url]['dynamic_enabled'])) { $dynamic_enabled = $_SESSION[$page_url]['dynamic_enabled']*1; }
-    }
-if (!isset($dynamic_enabled)) { $dynamic_enabled = 0; }
-$_SESSION[$page_url]['dynamic_enabled']=$dynamic_enabled;
+$dynamic_enabled = getParam('dynamic_enabled', $page_url, 0, FILTER_VALIDATE_INT);
+$_SESSION[$page_url]['dynamic_enabled'] = (int)$dynamic_enabled;
 ?>

+ 3 - 8
html/inc/enabledfilter.php

@@ -1,11 +1,6 @@
 <?php
-if (! defined("CONFIG")) die("Not defined");
+if (!defined("CONFIG")) die("Not defined");
 
-if (isset($_GET['enabled'])) { $enabled = $_GET["enabled"] * 1; }
-if (isset($_POST['enabled'])) { $enabled = $_POST["enabled"] * 1; }
-if (!isset($enabled)) {
-    if (isset($_SESSION[$page_url]['enabled'])) { $enabled = $_SESSION[$page_url]['enabled']*1; }
-    }
-if (!isset($enabled)) { $enabled = 0; }
-$_SESSION[$page_url]['enabled']=$enabled;
+$enabled = getParam('enabled', $page_url, 0, FILTER_VALIDATE_INT);
+$_SESSION[$page_url]['enabled'] = (int)$enabled;
 ?>

+ 3 - 5
html/inc/gatefilter.php

@@ -1,8 +1,6 @@
 <?php
-if (! defined("CONFIG")) die("Not defined");
+if (!defined("CONFIG")) die("Not defined");
 
-if (isset($_POST['gateway'])) { $rgateway = $_POST["gateway"] * 1; } else {
-    if (isset($_SESSION[$page_url]['gateway'])) { $rgateway = $_SESSION[$page_url]['gateway']; } else { $rgateway = 0; }
-    }
-$_SESSION[$page_url]['gateway']=$rgateway;
+$rgateway = getPOST('gateway', $page_url, 0, FILTER_VALIDATE_INT);
+$_SESSION[$page_url]['gateway'] = (int)$rgateway;
 ?>

+ 6 - 7
html/inc/idfilter.php

@@ -1,15 +1,14 @@
 <?php
-if (! defined("CONFIG")) die("Not defined");
+if (!defined("CONFIG")) die("Not defined");
 
-if (empty($id) and !empty($_SESSION[$page_url]['id'])) { $id = $_SESSION[$page_url]['id']; }
-
-if (empty($id) and !empty($default_id)) { $id=$default_id; }
+// Получаем id из GET/POST, если не задан — из сессии, если нет — из $default_id
+$id = getParam('id', $page_url, $default_id ?? null);
 
+// Если всё ещё пусто — редирект
 if (empty($id)) {
     header("Location: /admin/index.php");
     exit;
-    }
-
-$_SESSION[$page_url]['id']=$id;
+}
 
+$_SESSION[$page_url]['id'] = $id;
 ?>

+ 3 - 8
html/inc/iptypefilter.php

@@ -1,11 +1,6 @@
 <?php
-if (! defined("CONFIG")) die("Not defined");
+if (!defined("CONFIG")) die("Not defined");
 
-if (isset($_GET['ip_type'])) { $ip_type = $_GET["ip_type"] * 1; }
-if (isset($_POST['ip_type'])) { $ip_type = $_POST["ip_type"] * 1; }
-if (!isset($ip_type)) {
-    if (isset($_SESSION[$page_url]['ip_type'])) { $ip_type = $_SESSION[$page_url]['ip_type']*1; }
-    }
-if (!isset($ip_type)) { $ip_type = 0; }
-$_SESSION[$page_url]['ip_type']=$ip_type;
+$ip_type = getParam('ip_type', $page_url, 0, FILTER_VALIDATE_INT);
+$_SESSION[$page_url]['ip_type'] = (int)$ip_type;
 ?>

+ 5 - 27
html/inc/logfilter.php

@@ -1,31 +1,9 @@
 <?php
-if (! defined("CONFIG")) die("Not defined");
-if (isset($_POST['customer']) or isset($_GET['customer'])) {
-    if (isset($_GET['customer'])) { $fcustomer = $_GET['customer']; }
-    if (isset($_POST['customer'])) { $fcustomer = $_POST['customer']; }
-    } else {
-    if (isset($_SESSION[$page_url]['customer'])) { $fcustomer=$_SESSION[$page_url]['customer']; } else { $fcustomer = ''; }
-    }
-if (isset($_POST['customer']) or isset($_GET['customer'])) {
-    if (isset($_GET['customer'])) { $fcustomer = $_GET['customer']; }
-    if (isset($_POST['customer'])) { $fcustomer = $_POST['customer']; }
-    } else {
-    if (isset($_SESSION[$page_url]['customer'])) { $fcustomer=$_SESSION[$page_url]['customer']; } else { $fcustomer = ''; }
-    }
+if (!defined("CONFIG")) die("Not defined");
 
-if (isset($_POST['message']) or isset($_GET['message'])) {
-    if (isset($_GET['message'])) { $fmessage = $_GET['message']; }
-    if (isset($_POST['message'])) { $fmessage = $_POST['message']; }
-    } else {
-    if (isset($_SESSION[$page_url]['message'])) { $fmessage=$_SESSION[$page_url]['message']; } else { $fmessage = ''; }
-    }
-if (isset($_POST['message']) or isset($_GET['message'])) {
-    if (isset($_GET['message'])) { $fmessage = $_GET['message']; }
-    if (isset($_POST['message'])) { $fmessage = $_POST['message']; }
-    } else {
-    if (isset($_SESSION[$page_url]['message'])) { $fmessage=$_SESSION[$page_url]['message']; } else { $fmessage = ''; }
-    }
+$fcustomer = getParam('customer', $page_url, '');
+$fmessage  = getParam('message',  $page_url, '');
 
-$_SESSION[$page_url]['customer']=$fcustomer;
-$_SESSION[$page_url]['message']=$fmessage;
+$_SESSION[$page_url]['customer'] = $fcustomer;
+$_SESSION[$page_url]['message']  = $fmessage;
 ?>

+ 3 - 20
html/inc/loglevelfilter.php

@@ -1,23 +1,6 @@
 <?php
 if (!defined("CONFIG")) die("Not defined");
 
-if (isset($_POST['display_log_level']) or isset($_GET['display_log_level'])) {
-    if (isset($_GET['display_log_level'])) {
-        $display_log_level = $_GET['display_log_level'] * 1;
-    }
-    if (isset($_POST['display_log_level'])) {
-        $display_log_level = $_POST['display_log_level'] * 1;
-    }
-} else {
-    if (isset($_SESSION[$page_url]['display_log_level'])) {
-        $display_log_level = $_SESSION[$page_url]['display_log_level'];
-    } else {
-        $display_log_level = 1;
-    }
-}
-
-if (!isset($display_log_level)) {
-    $display_log_level = 1;
-}
-
-$_SESSION[$page_url]['display_log_level'] = $display_log_level;
+$display_log_level = getParam('display_log_level', $page_url, 1, FILTER_VALIDATE_INT);
+$_SESSION[$page_url]['display_log_level'] = (int)$display_log_level;
+?>

+ 3 - 24
html/inc/oufilter.php

@@ -3,29 +3,8 @@ if (!defined("CONFIG")) {
     die("Not defined");
 }
 
-// значение по умолчанию
 $default_ou = isset($default_ou) ? (int)$default_ou : 0;
 
-// Проверяем источники в порядке приоритета
-$rou = null;
-
-// 1. GET (самый высокий приоритет)
-if (!empty($_GET['ou'])) {
-    $rou = (int)$_GET['ou'];
-}
-// 2. POST (ниже приоритетом)
-elseif (!empty($_POST['ou'])) {
-    $rou = (int)$_POST['ou'];
-}
-// 3. SESSION (если есть)
-elseif (!empty($_SESSION[$page_url]['ou'])) {
-    $rou = (int)$_SESSION[$page_url]['ou'];
-}
-// 4. Значение по умолчанию
-else {
-    $rou = $default_ou;
-}
-
-// Сохраняем в сессию
-$_SESSION[$page_url]['ou'] = $rou;
-?>
+$rou = getParam('ou', $page_url, $default_ou, FILTER_VALIDATE_INT);
+$_SESSION[$page_url]['ou'] = (int)$rou;
+?>

+ 16 - 34
html/inc/rulesfilter.php

@@ -1,36 +1,18 @@
 <?php
-if (! defined("CONFIG")) die("Not defined");
-
-//rule type
-if (isset($_GET['rule_type'])) { $rule_type = $_GET["rule_type"] * 1; }
-if (isset($_POST['rule_type'])) { $rule_type = $_POST["rule_type"] * 1; }
-if (!isset($rule_type)) {
-    if (isset($_SESSION[$page_url]['rule_type'])) { $rule_type = $_SESSION[$page_url]['rule_type']*1; }
-    }
-if (!isset($rule_type)) { $rule_type = 0; }
-$_SESSION[$page_url]['rule_type']=$rule_type;
-
-//rule target
-if (isset($_GET['rule_target'])) { $rule_target = $_GET["rule_target"] * 1; }
-if (isset($_POST['rule_target'])) { $rule_target = $_POST["rule_target"] * 1; }
-if (!isset($rule_target)) {
-    if (isset($_SESSION[$page_url]['rule_target'])) { $rule_target = $_SESSION[$page_url]['rule_target']*1; }
-    }
-if (!isset($rule_target)) { $rule_target = 0; }
-$_SESSION[$page_url]['rule_target']=$rule_target;
-
-//search string
-if (isset($_GET['f_rule'])) { $f_rule = htmlspecialchars(trim($_GET["f_rule"]), ENT_QUOTES, 'UTF-8'); }
-if (isset($_POST['f_rule'])) { $f_rule = htmlspecialchars(trim($_POST["f_rule"]), ENT_QUOTES, 'UTF-8'); }
-
-if (!isset($f_rule)) {
-    if (isset($_SESSION[$page_url]['f_rule'])) { $f_rule = $_SESSION[$page_url]['f_rule']; }
-    }
-
-if (!isset($f_rule)) { $f_rule = ''; }
-
-$f_rule = str_replace('%', '', $f_rule);
-
-$_SESSION[$page_url]['f_rule']=$f_rule;
-
+if (!defined("CONFIG")) die("Not defined");
+
+// rule_type — целое число
+$rule_type = getParam('rule_type', $page_url, 0, FILTER_VALIDATE_INT);
+$_SESSION[$page_url]['rule_type'] = (int)$rule_type;
+
+// rule_target — целое число  
+$rule_target = getParam('rule_target', $page_url, 0, FILTER_VALIDATE_INT);
+$_SESSION[$page_url]['rule_target'] = (int)$rule_target;
+
+// search string — строка с очисткой
+$f_rule = getParam('f_rule', $page_url, '');
+$f_rule = trim($f_rule);
+$f_rule = htmlspecialchars($f_rule, ENT_QUOTES, 'UTF-8');
+$f_rule = str_replace('%', '', $f_rule); // удаляем % для безопасности в LIKE-запросах
+$_SESSION[$page_url]['f_rule'] = $f_rule;
 ?>

+ 4 - 8
html/inc/search.php

@@ -1,11 +1,7 @@
 <?php
-if (! defined("CONFIG")) die("Not defined");
+if (!defined("CONFIG")) die("Not defined");
 
-if (isset($_GET['search'])) { $search = trim($_GET["search"]); }
-if (isset($_POST['search'])) { $search = trim($_POST["search"]); }
-if (!isset($search)) {
-    if (isset($_SESSION[$page_url]['search'])) { $search = $_SESSION[$page_url]['search']; }
-    }
-if (!isset($search)) { $search = ''; }
-$_SESSION[$page_url]['search']=$search;
+$search = getParam('search', $page_url, '');
+$search = trim($search);
+$_SESSION[$page_url]['search'] = $search;
 ?>

+ 18 - 12
html/inc/sortfilter.php

@@ -1,19 +1,25 @@
 <?php
-if (! defined("CONFIG")) die("Not defined");
+if (!defined("CONFIG")) die("Not defined");
 
-if (!isset($default_sort)) { $default_sort=''; }
-if (!isset($default_order)) { $default_order='ASC'; }
+$default_sort  = $default_sort  ?? '';
+$default_order = $default_order ?? 'ASC';
 
-if (isset($_GET['sort'])) { $sort_field = $_GET["sort"]; } else {
-    if (isset($_SESSION[$page_url]['sort_field'])) { $sort_field=$_SESSION[$page_url]['sort_field']; } else { $sort_field = $default_sort; }
-    }
+// Получаем параметры
+$sort_field = getParam('sort', $page_url, $default_sort);
+$order      = strtoupper(getParam('order', $page_url, $default_order));
 
-if (isset($_GET['order'])) { $order = strtoupper($_GET["order"]); } else {
-    if (isset($_SESSION[$page_url]['order'])) { $order=strtoupper($_SESSION[$page_url]['order']); } else { $order = $default_order; }
-    }
+// Валидация: sort_field должно быть одним словом (буквы, цифры, подчёркивания, дефисы)
+if (!preg_match('/^[a-zA-Z0-9_-]+$/', $sort_field)) {
+    $sort_field = $default_sort;
+}
 
-if (strtoupper($order) === 'ASC') { $new_order = 'DESC'; } else { $new_order = 'ASC'; }
+// Валидация: order только ASC или DESC
+if ($order !== 'ASC' && $order !== 'DESC') {
+    $order = $default_order;
+}
 
-$_SESSION[$page_url]['order']=$order;
-$_SESSION[$page_url]['sort_field']=$sort_field;
+$new_order = ($order === 'ASC') ? 'DESC' : 'ASC';
+
+$_SESSION[$page_url]['sort_field'] = $sort_field;
+$_SESSION[$page_url]['order']      = $order;
 ?>

+ 5 - 8
html/inc/subnetfilter.php

@@ -1,11 +1,8 @@
 <?php
-if (! defined("CONFIG")) die("Not defined");
+if (!defined("CONFIG")) die("Not defined");
 
-if (!isset($default_subnet)) { $default_subnet = 0; }
-if (isset($_GET['subnet'])) { $rsubnet = $_GET["subnet"] * 1; }
-if (isset($_POST['subnet'])) { $rsubnet = $_POST["subnet"] * 1; }
-if (! isset($rsubnet)) {
-    if (isset($_SESSION[$page_url]['subnet'])) { $rsubnet=$_SESSION[$page_url]['subnet']; } else { $rsubnet = $default_subnet; }
-    }
-$_SESSION[$page_url]['subnet']=$rsubnet;
+$default_subnet = $default_subnet ?? 0;
+
+$rsubnet = getParam('subnet', $page_url, $default_subnet, FILTER_VALIDATE_INT);
+$_SESSION[$page_url]['subnet'] = (int)$rsubnet;
 ?>

+ 4 - 8
html/inc/vendorfilter.php

@@ -1,10 +1,6 @@
 <?php
-if (! defined("CONFIG")) die("Not defined");
-if (isset($_POST['vendor_select']) or isset($_GET['vendor_select'])) {
-    if (isset($_GET['vendor_select'])) { $f_vendor_select = $_GET['vendor_select']*1; }
-    if (isset($_POST['vendor_select'])) { $f_vendor_select = $_POST['vendor_select']*1; }
-    } else {
-    if (isset($_SESSION[$page_url]['vendor_select'])) { $f_vendor_select=$_SESSION[$page_url]['vendor_select']; } else { $f_vendor_select = 0; }
-    }
-$_SESSION[$page_url]['vendor_select']=$f_vendor_select;
+if (!defined("CONFIG")) die("Not defined");
+
+$f_vendor_select = getParam('vendor_select', $page_url, 0, FILTER_VALIDATE_INT);
+$_SESSION[$page_url]['vendor_select'] = (int)$f_vendor_select;
 ?>

+ 127 - 138
html/public/blocked.php

@@ -7,154 +7,143 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/common.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . HTML_LANG . ".php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header_public.php");
 
-if (! isset($auth_ip)) { $auth_ip = get_user_ip(); }
-if (! isset($auth_ip)) { print "Error detecting user!!!"; }
-
-/* month */
-$pmdate_start = DateTime::createFromFormat("Y-m-d",date("Y-m-1"));
-$date1m = $pmdate_start->format('Y-m-d');
-$pmdate_stop = DateTime::createFromFormat("Y-m-d",date("Y-m-d"));
-$pmdate_stop->modify('+1 day');
-$date2m = $pmdate_stop->format('Y-m-d');
-
-/* day */
-$pdate_start = DateTime::createFromFormat("Y-m-d",date("Y-m-d"));
-$date1 = $pdate_start->format('Y-m-d');
-$pdate_start->modify('+1 day');
-$date2 = $pdate_start->format('Y-m-d');
+// === 1. Безопасное получение IP ===
+$auth_ip = get_user_ip();
+if (!$auth_ip || !filter_var($auth_ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
+    die("<font color=red><b>Invalid IP detected!</b></font>");
+}
+
+// === 2. Преобразуем IP в BIGINT (беззнаковый) ===
+$ip_long = sprintf('%u', ip2long($auth_ip));
+
+// === 3. Находим авторизацию и пользователя за один JOIN ===
+$sql = "
+    SELECT 
+        ua.*, ul.*
+    FROM user_auth ua
+    JOIN user_list ul ON ua.user_id = ul.id
+    WHERE ua.ip_int = ? AND ua.deleted = 0 AND ul.deleted = 0
+";
+$record = get_record_sql($db_link, $sql, [$ip_long]);
+
+if (!$record) {
+    die("<font color=red><b>" . WEB_cell_ip . "&nbsp;" . htmlspecialchars($auth_ip, ENT_QUOTES) . "&nbsp; - " . WEB_unknown . "!</b></font>");
+}
+
+// === 4. Подготавливаем данные ===
+$id = $record['id'];
+$user_id = $record['user_id'];
+
+$KB = get_const('KB') ? 1024 : 1000;
+
+// Квоты пользователя
+$user_month_quota = ($record['month_quota'] ?? 0) * $KB * $KB;
+$user_day_quota   = ($record['day_quota']   ?? 0) * $KB * $KB;
+
+// Квоты IP (auth)
+$auth_month_quota = ($record['auth_month_quota'] ?? $record['month_quota'] ?? 0) * $KB * $KB;
+$auth_day_quota   = ($record['auth_day_quota']   ?? $record['day_quota']   ?? 0) * $KB * $KB;
+
+// === 5. Получаем трафик за день и месяц за 2 запроса (без циклов!) ===
+$params_day = [$date1, $date2, $user_id];
+$params_month = [$date1m, $date2m, $user_id];
+
+// Трафик по всем auth этого пользователя
+$day_traffic = get_record_sql($db_link, "
+    SELECT 
+        SUM(CASE WHEN ua.id = ? THEN us.byte_in ELSE 0 END) AS auth_in,
+        SUM(CASE WHEN ua.id = ? THEN us.byte_out ELSE 0 END) AS auth_out,
+        SUM(us.byte_in) AS user_in,
+        SUM(us.byte_out) AS user_out
+    FROM user_stats us
+    JOIN user_auth ua ON us.auth_id = ua.id
+    WHERE us.ts >= ? AND us.ts < ? AND ua.user_id = ? AND ua.deleted = 0
+", [$id, $id, $date1, $date2, $user_id]);
+
+$month_traffic = get_record_sql($db_link, "
+    SELECT 
+        SUM(CASE WHEN ua.id = ? THEN us.byte_in ELSE 0 END) AS auth_in,
+        SUM(CASE WHEN ua.id = ? THEN us.byte_out ELSE 0 END) AS auth_out,
+        SUM(us.byte_in) AS user_in,
+        SUM(us.byte_out) AS user_out
+    FROM user_stats us
+    JOIN user_auth ua ON us.auth_id = ua.id
+    WHERE us.ts >= ? AND us.ts < ? AND ua.user_id = ? AND ua.deleted = 0
+", [$id, $id, $date1m, $date2m, $user_id]);
+
+$day_auth_sum_in   = $day_traffic['auth_in']   ?? 0;
+$day_auth_sum_out  = $day_traffic['auth_out']  ?? 0;
+$day_user_sum_in   = $day_traffic['user_in']   ?? 0;
+$day_user_sum_out  = $day_traffic['user_out']  ?? 0;
+
+$month_auth_sum_in  = $month_traffic['auth_in']  ?? 0;
+$month_auth_sum_out = $month_traffic['auth_out'] ?? 0;
+$month_user_sum_in  = $month_traffic['user_in']  ?? 0;
+$month_user_sum_out = $month_traffic['user_out'] ?? 0;
 
 ?>
 
 <div id="cont">
-
-<?php
-$ip_aton = ip2long($auth_ip);
-if (! $ip_aton) { $ip_aton = 0; }
-
-$sSQL = "SELECT * FROM user_auth WHERE ip_int='".$ip_aton."' and deleted = 0";
-$auth = get_record_sql($db_link,$sSQL);
-if (! isset($auth) or empty($auth)) { print "<font color=red><b>".WEB_cell_ip."&nbsp". $auth_ip ."&nbsp - ".WEB_unknown."!</b><br></font>"; die; }
-
-$id = $auth['id'];
-$user_id = $auth['user_id'];
-
-$uSQL = "SELECT * FROM user_list WHERE id='".$user_id."'";
-$user = get_record_sql($db_link,$uSQL);
-
-if (! isset($user) or empty($user)) { print "<font color=red><b>".WEB_cell_ip."&nbsp". $auth_ip .WEB_user_deleted."</b><br></font>"; die; }
-
-if (empty($user['month_quota'])) { $user['month_quota']=0; }
-if (empty($user['day_quota'])) { $user['day_quota']=0; }
-if (empty($auth['month_quota'])) { $auth['month_quota']=0; }
-if (empty($auth['day_quota'])) { $auth['day_quota']=0; }
-
-$KB = get_const('KB');
-if ($KB) { $KB = 1024; } else { $KB = 1000; }
-$user['month_quota'] = $user['month_quota'] * $KB * $KB;
-$user['day_quota'] = $user['day_quota'] * $KB * $KB;
-$auth['month_quota'] = $auth['month_quota'] * $KB * $KB;
-$auth['day_quota'] = $auth['day_quota'] * $KB * $KB;
-
-?>
 <table>
 <tr>
-<td><b><?php echo WEB_msg_now; ?></b></td><td><?php print GetNowTimeString(); ?></td></tr>
+    <td><b><?php echo WEB_msg_now; ?></b></td>
+    <td><?php print GetNowTimeString(); ?></td>
+</tr>
 <tr>
-<td><b><?php echo WEB_cell_login; ?></b></td> <td><?php print $user['login']; ?></td>
-</tr><tr>
-<td><b><?php echo WEB_cell_fio; ?></b></td> <td><?php print $user['fio']; ?></td>
-</tr><tr>
-<td> <?php echo WEB_msg_access_login; ?> </td> <td><b><?php 
-if ($user['enabled'] and !$user['blocked']) { print WEB_msg_enabled; }
-if (!$user['enabled']) { print "<font color=red>".WEB_msg_disabled."</font> &nbsp"; }
-if ($user['blocked']) { print "<font colot=red>".WEB_msg_traffic_blocked."</font>"; }
-?></b>
-</td></tr>
+    <td><b><?php echo WEB_cell_login; ?></b></td>
+    <td><?php print htmlspecialchars($record['login'], ENT_QUOTES); ?></td>
+</tr>
+<tr>
+    <td><b><?php echo WEB_cell_fio; ?></b></td>
+    <td><?php print htmlspecialchars($record['fio'], ENT_QUOTES); ?></td>
+</tr>
 <tr>
-<td> <?php echo WEB_msg_access_ip; ?> </td> <td><b><?php 
-if ($user['enabled'] and !$user['blocked'] and !$auth['blocked'] and $auth['enabled']) { print WEB_msg_enabled; }
-if (!$user['enabled'] or !$auth['enabled']) { print "<font color=red>".WEB_msg_disabled."</font> &nbsp"; }
-if ($auth['blocked']) { print "<font color=red>".WEB_msg_traffic_blocked."</font>"; }
-?></b>
-</td>
+    <td><?php echo WEB_msg_access_login; ?></td>
+    <td><b>
+    <?php if ($record['enabled'] && !$record['blocked']): ?>
+        <?php echo WEB_msg_enabled; ?>
+    <?php else: ?>
+        <?php if (!$record['enabled']): ?>
+            <font color="red"><?php echo WEB_msg_disabled; ?></font>&nbsp;
+        <?php endif; ?>
+        <?php if ($record['blocked']): ?>
+            <font color="red"><?php echo WEB_msg_traffic_blocked; ?></font>
+        <?php endif; ?>
+    <?php endif; ?>
+    </b></td>
 </tr>
-<tr><td><?php echo WEB_cell_filter; ?></td><td><?php print get_group($db_link, $auth["filter_group_id"]); ?> </td></tr>
-<tr><td><?php echo WEB_cell_shaper; ?></td><td><?php print get_queue($db_link, $auth["queue_id"]); ?></td></tr>
-<tr><td><?php echo WEB_cell_login_quote_month; ?> </td><td><?php print fbytes($user['month_quota']); ?> </td></tr>
-<tr><td><?php echo WEB_cell_login_quote_day; ?> </td><td><?php print fbytes($user['day_quota']); ?> </td></tr>
-<tr><td><?php echo WEB_cell_ip_quote_month; ?> </td><td><?php print fbytes($auth['month_quota']); ?> </td></tr>
-<tr><td><?php echo WEB_cell_ip_quote_day;?> </td><td><?php print fbytes($auth['day_quota']); ?> </td></tr>
+<!-- Аналогично для IP-статуса -->
+<tr>
+    <td><?php echo WEB_msg_access_ip; ?></td>
+    <td><b>
+    <?php if ($record['enabled'] && !$record['blocked'] && $record['auth_enabled'] /*?*/): ?>
+        <?php echo WEB_msg_enabled; ?>
+    <?php else: ?>
+        <?php if (!$record['enabled'] /* или auth_enabled */): ?>
+            <font color="red"><?php echo WEB_msg_disabled; ?></font>&nbsp;
+        <?php endif; ?>
+        <?php if ($record['auth_blocked'] /*?*/): ?>
+            <font color="red"><?php echo WEB_msg_traffic_blocked; ?></font>
+        <?php endif; ?>
+    <?php endif; ?>
+    </b></td>
+</tr>
+<tr><td><?php echo WEB_cell_filter; ?></td><td><?php print get_group($db_link, $record["filter_group_id"]); ?> </td></tr>
+<tr><td><?php echo WEB_cell_shaper; ?></td><td><?php print get_queue($db_link, $record["queue_id"]); ?></td></tr>
+<tr><td><?php echo WEB_cell_login_quote_month; ?> </td><td><?php print fbytes($user_month_quota); ?> </td></tr>
+<tr><td><?php echo WEB_cell_login_quote_day; ?> </td><td><?php print fbytes($user_day_quota); ?> </td></tr>
+<tr><td><?php echo WEB_cell_ip_quote_month; ?> </td><td><?php print fbytes($auth_month_quota); ?> </td></tr>
+<tr><td><?php echo WEB_cell_ip_quote_day; ?> </td><td><?php print fbytes($auth_day_quota); ?> </td></tr>
+
+<!-- Трафик -->
+<tr class='data'><td><b><?php echo WEB_traffic_stats . " " . WEB_cell_ip; ?></b></td><td><?php echo htmlspecialchars($auth_ip, ENT_QUOTES); ?></td></tr>
+<tr class='data'><td><?php echo WEB_public_day_traffic; ?></td><td><?php echo fbytes($day_auth_sum_in) . " / " . fbytes($day_auth_sum_out); ?></td></tr>
+<tr class='data'><td><?php echo WEB_public_month_traffic; ?></td><td><?php echo fbytes($month_auth_sum_in) . " / " . fbytes($month_auth_sum_out); ?></td></tr>
+<tr class='data'><td><b><?php echo WEB_traffic_stats . " " . WEB_cell_login; ?></b></td><td><?php echo htmlspecialchars($record['login'], ENT_QUOTES); ?></td></tr>
+<tr class='data'><td><?php echo WEB_public_day_traffic; ?></td><td><?php echo fbytes($day_user_sum_in) . " / " . fbytes($day_user_sum_out); ?></td></tr>
+<tr class='data'><td><?php echo WEB_public_month_traffic; ?></td><td><?php echo fbytes($month_user_sum_in) . " / " . fbytes($month_user_sum_out); ?></td></tr>
+</table>
 
 <?php
-
-####### day
-$sSQL = "SELECT SUM(byte_in) as tin, SUM(byte_out) as tout FROM user_stats WHERE ts>='".$date1."' AND ts<'".$date2."' AND auth_id='".$id."'";
-$day_auth_itog = get_record_sql($db_link,$sSQL);
-
-$day_auth_sum_in=0;
-$day_auth_sum_in=0;
-
-if (!empty($day_auth_itog)) {
-    if (empty($day_auth_itog['tin'])) { $day_auth_itog['tin']=0; }
-    if (empty($day_auth_itog['tout'])) { $day_auth_itog['tout']=0; }
-    $day_auth_sum_in=$day_auth_itog['tin'];
-    $day_auth_sum_out=$day_auth_itog['tout'];
-    }
-
-$day_user_sum_in=0;
-$day_user_sum_out=0;
-
-$auth_list = get_records_sql($db_link,"SELECT id FROM user_auth WHERE user_id='".$user_id."' AND deleted=0");
-
-if (!empty($auth_list)) {
-    foreach ($auth_list as $row) {
-        $auth_itog2 = get_record_sql($db_link,"SELECT SUM(byte_in) as tin, SUM(byte_out) as tout FROM user_stats WHERE ts>='".$date1."' AND ts<'".$date2."' AND auth_id='".$row['id']."'");
-        if (!empty($auth_itog2)) { 
-                if (empty($auth_itog2['tin'])) { $auth_itog2['tin']=0; }
-                if (empty($auth_itog2['tout'])) { $auth_itog2['tout']=0; }
-                $day_user_sum_in+=$auth_itog2['tin'];
-                $day_user_sum_out+=$auth_itog2['tout'];
-                }
-        }
-    }
-
-#### month
-$sSQL = "SELECT SUM(byte_in) as tin, SUM(byte_out) as tout FROM user_stats WHERE ts>='".$date1m."' AND ts<'".$date2m."' AND auth_id='".$id."'";
-$month_auth_itog = get_record_sql($db_link,$sSQL);
-
-$month_auth_sum_in=0;
-$month_auth_sum_in=0;
-
-if (!empty($month_auth_itog)) {
-    if (empty($month_auth_itog['tin'])) { $month_auth_itog['tin']=0; }
-    if (empty($month_auth_itog['tout'])) { $month_auth_itog['tout']=0; }
-    $month_auth_sum_in=$month_auth_itog['tin'];
-    $month_auth_sum_out=$month_auth_itog['tout'];
-    }
-
-$month_user_sum_in=0;
-$month_user_sum_out=0;
-
-if (!empty($auth_list)) {
-    foreach ($auth_list as $row) {
-        $auth_itog2 = get_record_sql($db_link,"SELECT SUM(byte_in) as tin, SUM(byte_out) as tout FROM user_stats WHERE ts>='".$date1m."' AND ts<'".$date2m."' AND auth_id='".$row['id']."'");
-        if (!empty($auth_itog2)) {
-                if (empty($auth_itog2['tin'])) { $auth_itog2['tin']=0; }
-                if (empty($auth_itog2['tout'])) { $auth_itog2['tout']=0; }
-                $month_user_sum_in+=$auth_itog2['tin'];
-                $month_user_sum_out+=$auth_itog2['tout'];
-                }
-        }
-    }
-
-#### print
-print "<tr class='data'><td><b>".WEB_traffic_stats." ".WEB_cell_ip."</b></td><td>$auth_ip</td></tr>\n";
-print "<tr class='data'><td>".WEB_public_day_traffic."</td><td>" . fbytes($day_auth_sum_in)." / ".fbytes($day_auth_sum_out). "</td></tr>\n";
-print "<tr class='data'><td>".WEB_public_month_traffic."</td><td>" . fbytes($month_auth_sum_in)." / ".fbytes($month_auth_sum_out). "</td></tr>\n";
-print "<tr class='data'><td><b>".WEB_traffic_stats." ".WEB_cell_login."</b></td><td>".$user['login']."</td></tr>\n";
-print "<tr class='data'><td>".WEB_public_day_traffic."</td><td>" . fbytes($day_user_sum_in)." / ".fbytes($day_user_sum_out). "</td></tr>\n";
-print "<tr class='data'><td>".WEB_public_month_traffic."</td><td>" . fbytes($month_user_sum_in)." / ".fbytes($month_user_sum_out). "</td></tr>\n";
-print "</table>\n";
-
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/footer.php");
 ?>

+ 0 - 18
html/sessions/.htaccess

@@ -1,18 +0,0 @@
-<IfModule mod_version.c>
-	<IfVersion < 2.4>
-		Order Deny,Allow
-		Deny from All
-	</IfVersion>
-	<IfVersion >= 2.4>
-		Require all denied
-	</IfVersion>
-</IfModule>
-<IfModule !mod_version.c>
-	<IfModule !mod_authz_core.c>
-		Order Deny,Allow
-		Deny from All
-	</IfModule>
-	<IfModule mod_authz_core.c>
-		Require all denied
-	</IfModule>
-</IfModule>

+ 132 - 156
html/utils/auth_apply.php

@@ -4,187 +4,163 @@ require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/languages/" . HTML_LANG . ".php")
 
 if (!defined("CONFIG")) die("Not defined");
 
-if (isset($_POST["ApplyForAll"])) {
+// Определяем page_url для сессии (можно использовать текущий скрипт)
+$page_url = basename($_SERVER['SCRIPT_NAME'], '.php');
+
+if (getPOST("ApplyForAll", $page_url)) {
+
+    // Получаем массив ID авторизаций
+    $auth_id = getPOST("fid", $page_url, []);
+
+    // Получаем и валидируем все параметры через getPOST
+    $a_ou_id = (int)getPOST("a_new_ou", $page_url, 0);
+    $a_enabled = (int)getPOST("a_enabled", $page_url, 0);
+    $a_dhcp = (int)getPOST("a_dhcp", $page_url, 0);
+    $a_dhcp_acl = trim(getPOST("a_dhcp_acl", $page_url, ''));
+    $a_dhcp_option_set = trim(getPOST("a_dhcp_option_set", $page_url, ''));
+    $a_queue = (int)getPOST("a_queue_id", $page_url, 0);
+    $a_group = (int)getPOST("a_group_id", $page_url, 0);
+    $a_traf = (int)getPOST("a_traf", $page_url, 0);
+    $a_bind_mac = (int)getPOST("a_bind_mac", $page_url, 0);
+    $a_bind_ip = (int)getPOST("a_bind_ip", $page_url, 0);
+    $n_enabled = (int)getPOST("n_enabled", $page_url, 0);
+    $n_link = (int)getPOST("n_link", $page_url, 0);
+    $n_handler = getPOST("n_handler", $page_url, '');
 
-    $auth_id = $_POST["fid"];
-
-    if (empty($_POST["a_new_ou"])) {
-        $_POST["a_new_ou"] = 0;
-    }
-    if (empty($_POST["a_enabled"])) {
-        $_POST["a_enabled"] = 0;
-    }
-    if (empty($_POST["a_dhcp"])) {
-        $_POST["a_dhcp"] = 0;
-    }
-    if (empty($_POST["a_queue_id"])) {
-        $_POST["a_queue_id"] = 0;
-    }
-    if (empty($_POST["a_group_id"])) {
-        $_POST["a_group_id"] = 0;
-    }
-    if (empty($_POST["a_traf"])) {
-        $_POST["a_traf"] = 0;
-    }
-
-    if (empty($_POST["n_enabled"])) {
-        $_POST["n_enabled"] = 0;
-    }
-
-    if (empty($_POST["n_link"])) {
-        $_POST["n_link"] = 0;
-    }
+    $msg = "Massive User change!";
+    LOG_WARNING($db_link, $msg);
 
-    if (empty($_POST["a_bind_mac"])) {
-        $_POST["a_bind_mac"] = 0;
-    }
+    $all_ok = true;
 
-    if (empty($_POST["a_bind_ip"])) {
-        $_POST["a_bind_ip"] = 0;
-    }
+    foreach ($auth_id as $val) {
+        if (!$val = (int)$val) continue;
 
-    $a_ou_id    = $_POST["a_new_ou"] * 1;
-    $a_enabled  = $_POST["a_enabled"] * 1;
-    $a_dhcp     = $_POST["a_dhcp"] * 1;
-    $a_dhcp_acl = trim($_POST["a_dhcp_acl"]);
-    $a_dhcp_option_set = trim($_POST["a_dhcp_option_set"]);
-    $a_queue    = $_POST["a_queue_id"] * 1;
-    $a_group    = $_POST["a_group_id"] * 1;
-    $a_traf     = $_POST["a_traf"] * 1;
+        // Получаем текущую авторизацию и пользователя
+        $cur_auth = get_record_sql($db_link, "SELECT * FROM user_auth WHERE id = ?", [$val]);
+        if (!$cur_auth) continue;
 
-    $a_bind_mac = $_POST["a_bind_mac"]*1;
-    $a_bind_ip  = $_POST["a_bind_ip"]*1;
+        $user_info = get_record_sql($db_link, "SELECT * FROM user_list WHERE id = ?", [(int)$cur_auth["user_id"]]);
 
-    $n_enabled = $_POST["n_enabled"] * 1;
-    $n_link    = $_POST["n_link"] * 1;
-    $n_handler = $_POST["n_handler"];
+        // Формируем данные для обновления auth
+        $auth_updates = [];
 
-    $msg = "Massive User change!";
-    LOG_WARNING($db_link, $msg);
+        if (getPOST("e_enabled", $page_url) !== null && $user_info) {
+            $auth_updates['enabled'] = (int)($user_info["enabled"] * $a_enabled);
+        }
+        if (getPOST("e_group_id", $page_url) !== null) {
+            $auth_updates['filter_group_id'] = $a_group;
+        }
+        if (getPOST("e_queue_id", $page_url) !== null) {
+            $auth_updates['queue_id'] = $a_queue;
+        }
+        if (getPOST("e_dhcp", $page_url) !== null) {
+            $auth_updates['dhcp'] = $a_dhcp;
+        }
+        if (getPOST("e_dhcp_acl", $page_url) !== null) {
+            $auth_updates['dhcp_acl'] = $a_dhcp_acl;
+        }
+        if (getPOST("e_dhcp_option_set", $page_url) !== null) {
+            $auth_updates['dhcp_option_set'] = $a_dhcp_option_set;
+        }
+        if (getPOST("e_traf", $page_url) !== null) {
+            $auth_updates['save_traf'] = $a_traf;
+        }
+        if (getPOST("e_nag_enabled", $page_url) !== null) {
+            $auth_updates['nagios'] = $n_enabled;
+        }
+        if (getPOST("e_nag_link", $page_url) !== null) {
+            $auth_updates['link_check'] = $n_link;
+        }
+        if (getPOST("e_nag_handler", $page_url) !== null) {
+            $auth_updates['nagios_handler'] = $n_handler;
+        }
 
-    $all_ok = 1;
-    foreach ($auth_id as $key => $val) {
-        if ($val) {
-            unset($auth);
-            //check user state
-            $cur_auth = get_record_sql($db_link, "SELECT * FROM user_auth WHERE id=" . $val);
-            if (!empty($cur_auth)) { $user_info = get_record_sql($db_link, "SELECT * FROM user_list WHERE id=" . $cur_auth["user_id"]); }
+        // Обновляем запись в user_auth
+        if (!empty($auth_updates)) {
+            $ret = update_record($db_link, "user_auth", "id = ?", $auth_updates, [$val]);
+            if (!$ret) $all_ok = false;
+        }
 
+        // Изменение группы пользователя
+        if (getPOST("e_new_ou", $page_url) !== null && $a_ou_id && $user_info) {
+            $user_updates = ['ou_id' => $a_ou_id];
+            $auth_updates_for_all = ['ou_id' => $a_ou_id];
 
-            if (isset($_POST["e_enabled"])) {
-                if (!empty($user_info)) { $a_enabled = $user_info["enabled"] * $a_enabled; }
-                $auth['enabled'] = $a_enabled;
-            }
-            if (isset($_POST["e_group_id"])) {
-                $auth['filter_group_id'] = $a_group;
-            }
-            if (isset($_POST["e_queue_id"])) {
-                $auth['queue_id'] = $a_queue;
-            }
-            if (isset($_POST["e_dhcp"])) {
-                $auth['dhcp'] = $a_dhcp;
-            }
-            if (isset($_POST["e_dhcp_acl"])) {
-                $auth['dhcp_acl'] = $a_dhcp_acl;
-            }
-            if (isset($_POST["e_dhcp_option_set"])) {
-                $auth['dhcp_option_set'] = $a_dhcp_option_set;
-            }
-            if (isset($_POST["e_traf"])) {
-                $auth['save_traf'] = $a_traf;
-            }
-            //nagios
-            if (isset($_POST["e_nag_enabled"])) {
-                $auth['nagios'] = $n_enabled;
-            }
-            if (isset($_POST["e_nag_link"])) {
-                $auth['link_check'] = $n_link;
-            }
-            if (isset($_POST["e_nag_handler"])) {
-                $auth['nagios_handler'] = $n_handler;
-            }
+            $log_msg = "For user id: " . $cur_auth['user_id'] . " login: " . ($user_info['login'] ?? '') . " set: ou_id = " . $a_ou_id;
+            LOG_INFO($db_link, $log_msg);
 
-            if (!empty($auth)) {
-                $ret = update_record($db_link, "user_auth", "id='" . $val . "'", $auth);
-                if (!$ret) { $all_ok = 0; }
-            }
+            // Обновляем user_list
+            $ret = update_record($db_link, "user_list", "id = ?", $user_updates, [(int)$cur_auth['user_id']]);
+            if (!$ret) $all_ok = false;
 
-            //change user group
-            if (isset($_POST["e_new_ou"]) and !empty($a_ou_id) and !empty($user_info)) {
-                $user['ou_id'] = $a_ou_id;
-                $u_auth['ou_id'] = $a_ou_id;
-                //change user group
-                $msg = " For user id: " . $cur_auth['user_id'] . " login: " . $user_info['login'] . " set: ou_id = ".$a_ou_id;
-                LOG_INFO($db_link,$msg);
-                $ret = update_record($db_link, "user_list", "id='" . $cur_auth['user_id'] . "'", $user);
-                if (!$ret) { $all_ok = 0; }
-                //change user ip
-                $auth_list = get_records_sql($db_link, "SELECT * FROM user_auth WHERE user_id=" . $cur_auth['user_id']);
-                if (!empty($auth_list)) {
-                        foreach ($auth_list as $row) {
-                            if (empty($row)) { continue; }
-                            $ret = update_record($db_link, "user_auth", "id='" . $row["id"] . "'", $u_auth);
-                            if (!$ret) { $all_ok = 0; }
-                            }
-                        }
-                unset($user);
-                }
+            // Обновляем все записи user_auth для этого пользователя
+            $ret = update_records($db_link, "user_auth", "user_id = ?", $auth_updates_for_all, [(int)$cur_auth['user_id']]);
+            if (!$ret) $all_ok = false;
+        }
 
-            //bind mac rule
-            if (isset($_POST["e_bind_mac"])) {
-                $first_auth = get_record_sql($db_link,"SELECT user_id,mac FROM user_auth WHERE id=".$val);
-                if (!empty($first_auth) and !empty($first_auth['mac'])) {
-                    if ($a_bind_mac) {
-                            $auth_rules_user = get_record_sql($db_link,"SELECT * FROM auth_rules WHERE user_id=".$first_auth['user_id']." AND type=2");
-                            $auth_rules_mac = get_record_sql($db_link,"SELECT * FROM auth_rules WHERE rule='".$first_auth['mac']."' AND type=2");
-                            if (empty($auth_rules_user) and empty($auth_rules_mac)) {
-                                $new['user_id']=$first_auth['user_id'];
-                                $new['type']=2;
-                                $new['rule']=$first_auth['mac'];
-                                insert_record($db_link,"auth_rules",$new);
-                                LOG_INFO($db_link,"Created auto rule for user_id: ".$first_auth['user_id']." and mac ".$first_auth['mac']);
-                                } else {
-                                LOG_INFO($db_link,"Auto rule for user_id: ".$first_auth['user_id']." and mac ".$first_auth['mac']." already exists");
-                                }
-                            } else {
-                                run_sql($db_link,"DELETE FROM auth_rules WHERE user_id=".$first_auth['user_id']." AND type=2");
-                                LOG_INFO($db_link,"Remove auto rule for user_id: ".$first_auth['user_id']." and mac ".$first_auth['mac']);
-                            }
+        // Правило привязки MAC
+        if (getPOST("e_bind_mac", $page_url) !== null) {
+            $first_auth = get_record_sql($db_link, "SELECT user_id, mac FROM user_auth WHERE id = ?", [$val]);
+            
+            if ($first_auth && !empty($first_auth['mac'])) {
+                if ($a_bind_mac) {
+                    $user_rule = get_record_sql($db_link, "SELECT * FROM auth_rules WHERE user_id = ? AND type = 2", [(int)$first_auth['user_id']]);
+                    $mac_rule = get_record_sql($db_link, "SELECT * FROM auth_rules WHERE rule = ? AND type = 2", [$first_auth['mac']]);
+                    
+                    if (!$user_rule && !$mac_rule) {
+                        $new_rule = [
+                            'user_id' => (int)$first_auth['user_id'],
+                            'type' => 2,
+                            'rule' => $first_auth['mac']
+                        ];
+                        insert_record($db_link, "auth_rules", $new_rule);
+                        LOG_INFO($db_link, "Created auto rule for user_id: " . $first_auth['user_id'] . " and mac " . $first_auth['mac']);
                     } else {
-                        LOG_ERROR($db_link,"Auto rule for user_id: ".$first_auth['user_id']." not created. Record not found or empty mac.");
+                        LOG_INFO($db_link, "Auto rule for user_id: " . $first_auth['user_id'] . " and mac " . $first_auth['mac'] . " already exists");
                     }
+                } else {
+                    run_sql($db_link, "DELETE FROM auth_rules WHERE user_id = ? AND type = 2", [(int)$first_auth['user_id']]);
+                    LOG_INFO($db_link, "Remove auto rule for user_id: " . $first_auth['user_id'] . " and mac " . $first_auth['mac']);
+                }
+            } else {
+                LOG_ERROR($db_link, "Auto rule for user_id: " . ($first_auth['user_id'] ?? 'N/A') . " not created. Record not found or empty mac.");
             }
+        }
 
-            //bind ip rule
-            if (isset($_POST["e_bind_ip"])) {
-                $first_auth = get_record_sql($db_link,"SELECT user_id,ip FROM user_auth WHERE id=".$val);
-                if (!empty($first_auth) and !empty($first_auth['ip'])) {
-                    if ($a_bind_ip) {
-                            $auth_rules_user = get_record_sql($db_link,"SELECT * FROM auth_rules WHERE user_id=".$first_auth['user_id']." AND type=1");
-                            $auth_rules_ip = get_record_sql($db_link,"SELECT * FROM auth_rules WHERE rule='".$first_auth['ip']."' AND type=1");
-                            if (empty($auth_rules_user) and empty($auth_rules_ip)) {
-                                $new['user_id']=$first_auth['user_id'];
-                                $new['type']=1;
-                                $new['rule']=$first_auth['ip'];
-                                insert_record($db_link,"auth_rules",$new);
-                                LOG_INFO($db_link,"Created auto rule for user_id: ".$first_auth['user_id']." and ip ".$first_auth['ip']);
-                                } else {
-                                LOG_INFO($db_link,"Auto rule for user_id: ".$first_auth['user_id']." and ip ".$first_auth['ip']." already exists");
-                                }
-                            } else {
-                                run_sql($db_link,"DELETE FROM auth_rules WHERE user_id=".$first_auth['user_id']." AND type=1");
-                                LOG_INFO($db_link,"Remove auto rule for user_id: ".$first_auth['user_id']." and ip ".$first_auth['ip']);
-                            }
+        // Правило привязки IP
+        if (getPOST("e_bind_ip", $page_url) !== null) {
+            $first_auth = get_record_sql($db_link, "SELECT user_id, ip FROM user_auth WHERE id = ?", [$val]);
+            
+            if ($first_auth && !empty($first_auth['ip'])) {
+                if ($a_bind_ip) {
+                    $user_rule = get_record_sql($db_link, "SELECT * FROM auth_rules WHERE user_id = ? AND type = 1", [(int)$first_auth['user_id']]);
+                    $ip_rule = get_record_sql($db_link, "SELECT * FROM auth_rules WHERE rule = ? AND type = 1", [$first_auth['ip']]);
+                    
+                    if (!$user_rule && !$ip_rule) {
+                        $new_rule = [
+                            'user_id' => (int)$first_auth['user_id'],
+                            'type' => 1,
+                            'rule' => $first_auth['ip']
+                        ];
+                        insert_record($db_link, "auth_rules", $new_rule);
+                        LOG_INFO($db_link, "Created auto rule for user_id: " . $first_auth['user_id'] . " and ip " . $first_auth['ip']);
                     } else {
-                        LOG_ERROR($db_link,"Auto rule for user_id: ".$first_auth['user_id']." not created. Record not found or empty ip.");
+                        LOG_INFO($db_link, "Auto rule for user_id: " . $first_auth['user_id'] . " and ip " . $first_auth['ip'] . " already exists");
                     }
+                } else {
+                    run_sql($db_link, "DELETE FROM auth_rules WHERE user_id = ? AND type = 1", [(int)$first_auth['user_id']]);
+                    LOG_INFO($db_link, "Remove auto rule for user_id: " . $first_auth['user_id'] . " and ip " . $first_auth['ip']);
+                }
+            } else {
+                LOG_ERROR($db_link, "Auto rule for user_id: " . ($first_auth['user_id'] ?? 'N/A') . " not created. Record not found or empty ip.");
             }
-
         }
     }
+
     if ($all_ok) {
         print "Success!";
     } else {
         print "Fail!";
     }
 }
+?>

+ 96 - 18
html/utils/auth_export.php

@@ -5,26 +5,104 @@ require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/languages/" . HTML_LANG . ".php")
 if (!defined("CONFIG")) die("Not defined");
 
 if (isset($_POST["ExportAuth"])) {
-    print "login;ip;mac;description;dns name;last_found;connected\n";
-    if (isset($_POST["a_selected"]) and $_POST["a_selected"] * 1) {
-        //export selected only
-        $auth_id = $_POST["fid"];
-        foreach ($auth_id as $key => $val) {
-            if ($val) {
-                $sSQL = "SELECT user_list.login, user_auth.ip, user_auth.mac, user_auth.description, user_auth.dns_name, user_auth.last_found FROM user_auth, user_list WHERE user_auth.user_id = user_list.id AND user_auth.id = " . $val;
-                $record = get_record_sql($db_link, $sSQL);
-                print $record['login'] . ';' . $record['ip'] . ';' . $record['mac'] . ';' . $record['description'] . ';' . $record['dns_name'] . ';' . $record['last_found'] . ';' . get_connection_string($db_link, $val)."\n";
+    // Устанавливаем правильный Content-Type для CSV
+    header('Content-Type: text/csv; charset=utf-8');
+    header('Content-Disposition: attachment; filename="auth_export.csv"');
+
+    $out = fopen('php://output', 'w');
+    fputcsv($out, ['login', 'ip', 'mac', 'description', 'dns name', 'last_found', 'connected'], ';');
+
+    if (!empty($_POST["a_selected"]) && (int)$_POST["a_selected"]) {
+        // Export selected only
+        $auth_ids = $_POST["fid"] ?? [];
+        $valid_ids = [];
+
+        // Фильтруем и приводим к целым числам
+        foreach ($auth_ids as $id) {
+            if ($id = (int)$id) {
+                $valid_ids[] = $id;
+            }
+        }
+
+        if (!empty($valid_ids)) {
+            // Создаем плейсхолдеры для IN
+            $placeholders = str_repeat('?,', count($valid_ids) - 1) . '?';
+            $sql = "
+                SELECT 
+                    ul.login, 
+                    ua.ip, 
+                    ua.mac, 
+                    ua.description, 
+                    ua.dns_name, 
+                    ua.last_found,
+                    ua.id
+                FROM user_auth ua
+                JOIN user_list ul ON ua.user_id = ul.id
+                WHERE ua.id IN ($placeholders)
+            ";
+            $records = get_records_sql($db_link, $sql, $valid_ids);
+            
+            foreach ($records as $record) {
+                fputcsv($out, [
+                    $record['login'],
+                    $record['ip'],
+                    $record['mac'],
+                    $record['description'],
+                    $record['dns_name'],
+                    $record['last_found'],
+                    get_connection_string($db_link, $record['id'])
+                ], ';');
             }
         }
     } else {
-        //export all
-        $ip_filter = '';
-        $sort = 'user_auth.ip_int';
-        if (!empty($_POST["ip-filter"])) { $ip_filter = $_POST['ip-filter']; }
-        if (!empty($_POST["ip-sort"])) { $sort = $_POST['ip-sort']; }
-        $sSQL = "SELECT user_auth.*, user_list.login, user_list.enabled as UEnabled, user_list.blocked as UBlocked FROM user_auth, user_list WHERE user_auth.user_id = user_list.id AND user_auth.deleted = 0 $ip_filter ORDER BY $sort";
-        $auth_table = get_records_sql($db_link, $sSQL);
-        foreach ($auth_table as $record) {
-            print $record['login'] . ';' . $record['ip'] . ';' . $record['mac'] . ';' . $record['description'] . ';' . $record['dns_name'] . ';' . $record['last_found'] .';' . get_connection_string($db_link, $record['id']). "\n";
+        // Export all
+        $conditions = ["ua.deleted = 0"];
+        $params = [];
+        
+        // Фильтр по IP (если передан как часть WHERE условия)
+        // Безопасная сортировка - белый список разрешенных полей
+        $allowed_sort_fields = [
+            'user_auth.ip_int', 'ua.ip_int',
+            'user_auth.ip', 'ua.ip',
+            'user_auth.mac', 'ua.mac',
+            'user_list.login', 'ul.login',
+            'ua.last_found'
+        ];
+        
+        $sort_field = 'ua.ip_int';
+        if (!empty($_POST["ip-sort"]) && in_array($_POST["ip-sort"], $allowed_sort_fields, true)) {
+            $sort_field = $_POST["ip-sort"];
+        }
+
+        $sql = "
+            SELECT 
+                ua.*, 
+                ul.login, 
+                ul.enabled as UEnabled, 
+                ul.blocked as UBlocked,
+                ua.id
+            FROM user_auth ua
+            JOIN user_list ul ON ua.user_id = ul.id
+            WHERE " . implode(' AND ', $conditions) . "
+            ORDER BY $sort_field
+        ";
+        
+        $records = get_records_sql($db_link, $sql, $params);
+        
+        foreach ($records as $record) {
+            fputcsv($out, [
+                $record['login'],
+                $record['ip'],
+                $record['mac'],
+                $record['description'],
+                $record['dns_name'],
+                $record['last_found'],
+                get_connection_string($db_link, $record['id'])
+            ], ';');
         }
+    }
+    
+    fclose($out);
+    exit;
 }
+?>

+ 16 - 13
html/utils/auth_remove.php

@@ -4,20 +4,23 @@ require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/languages/" . HTML_LANG . ".php")
 
 if (!defined("CONFIG")) die("Not defined");
 
-if (isset($_POST["RemoveAuth"]) and (isset($_POST["f_deleted"]))) {
-    if ($_POST["f_deleted"] * 1) {
-        $auth_id = $_POST["fid"];
-        $all_ok = 1;
-        foreach ($auth_id as $key => $val) {
-            if ($val) {
-                $changes = delete_user_auth($db_link,$val);
-                if (empty($changes)) { $all_ok = 0; }
-                }
+if (isset($_POST["RemoveAuth"]) && !empty($_POST["f_deleted"])) {
+    $auth_id = $_POST["fid"] ?? [];
+    $all_ok = true;
+
+    foreach ($auth_id as $val) {
+        if ($val = (int)$val) { // Приводим к int и проверяем, что не 0
+            $changes = delete_user_auth($db_link, $val);
+            if (empty($changes)) {
+                $all_ok = false;
             }
-        if ($all_ok) {
-            print "Success!";
-        } else {
-            print "Fail!";
         }
     }
+
+    if ($all_ok) {
+        print "Success!";
+    } else {
+        print "Fail!";
+    }
 }
+?>

+ 48 - 32
html/utils/devices_apply.php

@@ -4,51 +4,67 @@ require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/languages/" . HTML_LANG . ".php")
 
 if (!defined("CONFIG")) die("Not defined");
 
-if (isset($_POST["ApplyForAll"])) {
+// Определяем page_url для сессии
+$page_url = basename($_SERVER['SCRIPT_NAME'], '.php');
 
-    $dev_id = $_POST["fid"];
+if (getPOST("ApplyForAll", $page_url)) {
 
-    if (empty($_POST["a_dev_type"])) { $_POST["a_dev_type"] = 0; }
-    if (empty($_POST["a_device_model_id"])) { $_POST["a_device_model_id"] = 0; }
-    if (empty($_POST["a_building_id"])) { $_POST["a_building_id"] = 0; }
-    if (empty($_POST["a_snmp_version"])) { $_POST["a_snmp_version"] = 0; }
-    if (empty($_POST["a_ro_community"])) { $_POST["a_ro_community"] = 'public'; }
-    if (empty($_POST["a_rw_community"])) { $_POST["a_rw_community"] = 'private'; }
+    // Получаем массив ID устройств
+    $dev_id = getPOST("fid", $page_url, []);
 
-    $a_dev_type = $_POST["a_dev_type"];
-    $a_device_model_id = $_POST["a_device_model_id"];
-    $a_building_id = $_POST["a_building_id"];
-    $a_snmp_version = $_POST["a_snmp_version"];
-    $a_ro_community = $_POST["a_ro_community"];
-    $a_rw_community = $_POST["a_rw_community"];
+    // Получаем и валидируем параметры через getPOST
+    $a_dev_type = (int)getPOST("a_dev_type", $page_url, 0);
+    $a_device_model_id = (int)getPOST("a_device_model_id", $page_url, 0);
+    $a_building_id = (int)getPOST("a_building_id", $page_url, 0);
+    $a_snmp_version = (int)getPOST("a_snmp_version", $page_url, 0);
+    $a_ro_community = trim(getPOST("a_ro_community", $page_url, 'public'));
+    $a_rw_community = trim(getPOST("a_rw_community", $page_url, 'private'));
 
     $msg = "Massive change devices!";
     LOG_WARNING($db_link, $msg);
 
-    $all_ok = 1;
-    foreach ($dev_id as $key => $val) {
-        if (!empty($val)) {
-            unset($device);
-            if (isset($_POST["e_set_type"])) { $device['device_type'] = $a_dev_type; }
-            if (isset($_POST["e_set_model"])) { 
-                $device['device_model_id'] = $a_device_model_id;
-                $device['vendor_id'] = get_device_model_vendor($db_link,$a_device_model_id);
-                }
-            //snmp
-            if (isset($_POST["e_set_snmp_version"])) { $device['snmp_version'] = $a_snmp_version * 1; }
-            if (isset($_POST["e_set_ro_community"])) { $device['community'] = $a_ro_community; }
-            if (isset($_POST["e_set_rw_community"])) { $device['rw_community'] = $a_rw_community; }
-            //location
-            if (isset($_POST["e_set_building"])) { $device['building_id'] = $a_building_id * 1; }
-            if (!empty($device)) {
-                $ret = update_record($db_link, "devices", "id='" . $val . "'", $device);
-                if (!$ret) { $all_ok = 0; }
+    $all_ok = true;
+
+    foreach ($dev_id as $val) {
+        if (!$val = (int)$val) { // Пропускаем неправильные ID
+            continue;
+        }
+
+        $device = [];
+
+        if (getPOST("e_set_type", $page_url) !== null) {
+            $device['device_type'] = $a_dev_type;
+        }
+        if (getPOST("e_set_model", $page_url) !== null) {
+            $device['device_model_id'] = $a_device_model_id;
+            $device['vendor_id'] = get_device_model_vendor($db_link, $a_device_model_id);
+        }
+        if (getPOST("e_set_snmp_version", $page_url) !== null) {
+            $device['snmp_version'] = $a_snmp_version;
+        }
+        if (getPOST("e_set_ro_community", $page_url) !== null) {
+            $device['community'] = $a_ro_community;
+        }
+        if (getPOST("e_set_rw_community", $page_url) !== null) {
+            $device['rw_community'] = $a_rw_community;
+        }
+        if (getPOST("e_set_building", $page_url) !== null) {
+            $device['building_id'] = $a_building_id;
+        }
+
+        if (!empty($device)) {
+            // 🔒 Безопасный вызов: параметризованное условие
+            $ret = update_record($db_link, "devices", "id = ?", $device, [$val]);
+            if (!$ret) {
+                $all_ok = false;
             }
         }
     }
+
     if ($all_ok) {
         print "Success!";
     } else {
         print "Fail!";
     }
 }
+?>

+ 19 - 16
html/utils/devices_remove.php

@@ -4,20 +4,23 @@ require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/languages/" . HTML_LANG . ".php")
 
 if (!defined("CONFIG")) die("Not defined");
 
-if (isset($_POST["RemoveDevice"]) and (isset($_POST["f_deleted"]))) {
-	if ($_POST["f_deleted"] * 1) {
-		$all_ok = 1;
-		$dev_ids = $_POST["fid"];
-		foreach ($dev_ids as $key => $val) {
-		    if ($val) {
-                            $changes = delete_device($db_link,$val);
-                            if (empty($changes)) { $all_ok = 0; }
-                        }
-                }
-		if ($all_ok) {
-			print "Success!";
-		} else {
-			print "Fail!";
-		}
-	}
+if (isset($_POST["RemoveDevice"]) && !empty($_POST["f_deleted"])) {
+    $dev_ids = $_POST["fid"] ?? [];
+    $all_ok = true;
+
+    foreach ($dev_ids as $val) {
+        if ($val = (int)$val) { // Приводим к целому числу и проверяем, что не 0
+            $changes = delete_device($db_link, $val);
+            if (empty($changes)) {
+                $all_ok = false;
+            }
+        }
+    }
+
+    if ($all_ok) {
+        print "Success!";
+    } else {
+        print "Fail!";
+    }
 }
+?>

+ 175 - 180
html/utils/user_apply.php

@@ -4,210 +4,205 @@ require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/languages/" . HTML_LANG . ".php")
 
 if (!defined("CONFIG")) die("Not defined");
 
-if (isset($_POST["ApplyForAll"])) {
-
-    $auth_id = $_POST["fid"];
-
-    if (empty($_POST["a_enabled"])) {
-        $_POST["a_enabled"] = 0;
-    }
-    if (empty($_POST["a_dhcp"])) {
-        $_POST["a_dhcp"] = 0;
-    }
-    if (empty($_POST["a_queue_id"])) {
-        $_POST["a_queue_id"] = 0;
-    }
-    if (empty($_POST["a_group_id"])) {
-        $_POST["a_group_id"] = 0;
-    }
-    if (empty($_POST["a_traf"])) {
-        $_POST["a_traf"] = 0;
-    }
-
-    if (empty($_POST["a_day_q"])) {
-        $_POST["a_day_q"] = 0;
-    }
-    if (empty($_POST["a_month_q"])) {
-        $_POST["a_month_q"] = 0;
-    }
-    if (empty($_POST["a_new_ou"])) {
-        $_POST["a_new_ou"] = 0;
-    }
-
-    if (empty($_POST["a_bind_mac"])) {
-        $_POST["a_bind_mac"] = 0;
-    }
-
-    if (empty($_POST["a_bind_ip"])) {
-        $_POST["a_bind_ip"] = 0;
-    }
-
-    if (empty($_POST["a_create_netdev"])) {
-        $_POST["a_create_netdev"] = 0;
-    }
-
-    if (empty($_POST["a_permanent"])) {
-        $_POST["a_permanent"] = 0;
-    }
-
-    if (isset($_POST["a_enabled"]))             {     $a_enabled         = $_POST["a_enabled"] * 1; }
-    if (isset($_POST["a_dhcp"]))                {     $a_dhcp            = $_POST["a_dhcp"] * 1; }
-    if (isset($_POST["a_dhcp_acl"]))            {     $a_dhcp_acl        = trim($_POST["a_dhcp_acl"]); }
-    if (isset($_POST["a_dhcp_option_set"]))     {     $a_dhcp_option_set = trim($_POST["a_dhcp_option_set"]); }
-    if (isset($_POST["a_queue_id"]))            {     $a_queue           = $_POST["a_queue_id"] * 1; }
-    if (isset($_POST["a_group_id"]))            {     $a_group           = $_POST["a_group_id"] * 1; }
-    if (isset($_POST["a_traf"]))                {     $a_traf            = $_POST["a_traf"] * 1; }
-    if (isset($_POST["a_day_q"]))               {     $a_day             = $_POST["a_day_q"] * 1; }
-    if (isset($_POST["a_month_q"]))             {     $a_month           = $_POST["a_month_q"] * 1; }
-    if (isset($_POST["a_new_ou"]))              {     $a_ou_id           = $_POST["a_new_ou"] * 1; }
-    if (isset($_POST["a_permanent"]))           {     $a_permanent       = $_POST["a_permanent"] * 1; }
-
-    if (isset($_POST["a_bind_mac"]))            {     $a_bind_mac        = $_POST["a_bind_mac"] * 1; }
-    if (isset($_POST["a_bind_ip"]))             {     $a_bind_ip         = $_POST["a_bind_ip"] * 1; }
-    if (isset($_POST["a_create_netdev"]))       {     $a_create_netdev   = $_POST["a_create_netdev"] * 1; }
+// Определяем page_url для сессии
+$page_url = basename($_SERVER['SCRIPT_NAME'], '.php');
+
+if (getPOST("ApplyForAll", $page_url)) {
+
+    // === Безопасное получение и приведение параметров через getPOST ===
+    $auth_id = getPOST("fid", $page_url, []);
+
+    $a_enabled = (int)getPOST("a_enabled", $page_url, 0);
+    $a_dhcp = (int)getPOST("a_dhcp", $page_url, 0);
+    $a_queue = (int)getPOST("a_queue_id", $page_url, 0);
+    $a_group = (int)getPOST("a_group_id", $page_url, 0);
+    $a_traf = (int)getPOST("a_traf", $page_url, 0);
+    $a_day = (int)getPOST("a_day_q", $page_url, 0);
+    $a_month = (int)getPOST("a_month_q", $page_url, 0);
+    $a_ou_id = (int)getPOST("a_new_ou", $page_url, 0);
+    $a_permanent = (int)getPOST("a_permanent", $page_url, 0);
+    $a_bind_mac = (int)getPOST("a_bind_mac", $page_url, 0);
+    $a_bind_ip = (int)getPOST("a_bind_ip", $page_url, 0);
+    $a_create_netdev = (int)getPOST("a_create_netdev", $page_url, 0);
+    $a_dhcp_acl = trim(getPOST("a_dhcp_acl", $page_url, ''));
+    $a_dhcp_option_set = trim(getPOST("a_dhcp_option_set", $page_url, ''));
 
     $msg = "Massive User change!";
     LOG_WARNING($db_link, $msg);
 
-    $all_ok = 1;
-    foreach ($auth_id as $key => $val) {
-        if ($val) {
-            unset($auth);
-            unset($user);
-            if (isset($_POST["e_enabled"])) {
-                $auth['enabled'] = $a_enabled;
-                $user['enabled'] = $a_enabled;
-            }
-            if (isset($_POST["e_group_id"])) {
-                $auth['filter_group_id'] = $a_group;
-            }
-            if (isset($_POST["e_queue_id"])) {
-                $auth['queue_id'] = $a_queue;
-            }
-            if (isset($_POST["e_dhcp"])) {
-                $auth['dhcp'] = $a_dhcp;
-            }
-            if (isset($_POST["e_dhcp_acl"])) {
-                $auth['dhcp_acl'] = $a_dhcp_acl;
-            }
-            if (isset($_POST["e_dhcp_option_set"])) {
-                $auth['dhcp_option_set'] = $a_dhcp_option_set;
-            }
-            if (isset($_POST["e_traf"])) {
-                $auth['save_traf'] = $a_traf;
-            }
-            if (isset($_POST["e_day_q"])) {
-                $user['day_quota'] = $a_day;
-            }
-            if (isset($_POST["e_month_q"])) {
-                $user['month_quota'] = $a_month;
-            }
-            if (isset($_POST["e_new_ou"])) {
-                $user['ou_id'] = $a_ou_id;
-                $auth['ou_id'] = $a_ou_id;
-            }
+    $all_ok = true;
 
-            if (isset($_POST["e_permanent"])) {
-                $user['permanent'] = $a_permanent;
-            }
+    foreach ($auth_id as $user_id_raw) {
+        $user_id = (int)$user_id_raw;
+        if (!$user_id) continue;
 
-            $login = get_record($db_link, "user_list", "id='$val'");
-            $msg .= " For all ip user id: " . $val . " login: " . $login['login'] . " set: ";
-            $msg .= get_diff_rec($db_link, "user_list", "id='$val'", $user, 1);
+        $auth_updates = [];
+        $user_updates = [];
 
-            if (!empty($user)) { 
-                $ret = update_record($db_link, "user_list", "id='" . $val . "'", $user);
-                if (!$ret) { $all_ok = 0; }
-                }
+        if (getPOST("e_enabled", $page_url) !== null) {
+            $auth_updates['enabled'] = $a_enabled;
+            $user_updates['enabled'] = $a_enabled;
+        }
+        if (getPOST("e_group_id", $page_url) !== null) {
+            $auth_updates['filter_group_id'] = $a_group;
+        }
+        if (getPOST("e_queue_id", $page_url) !== null) {
+            $auth_updates['queue_id'] = $a_queue;
+        }
+        if (getPOST("e_dhcp", $page_url) !== null) {
+            $auth_updates['dhcp'] = $a_dhcp;
+        }
+        if (getPOST("e_dhcp_acl", $page_url) !== null) {
+            $auth_updates['dhcp_acl'] = $a_dhcp_acl;
+        }
+        if (getPOST("e_dhcp_option_set", $page_url) !== null) {
+            $auth_updates['dhcp_option_set'] = $a_dhcp_option_set;
+        }
+        if (getPOST("e_traf", $page_url) !== null) {
+            $auth_updates['save_traf'] = $a_traf;
+        }
+        if (getPOST("e_day_q", $page_url) !== null) {
+            $user_updates['day_quota'] = $a_day;
+        }
+        if (getPOST("e_month_q", $page_url) !== null) {
+            $user_updates['month_quota'] = $a_month;
+        }
+        if (getPOST("e_new_ou", $page_url) !== null) {
+            $user_updates['ou_id'] = $a_ou_id;
+            $auth_updates['ou_id'] = $a_ou_id;
+        }
+        if (getPOST("e_permanent", $page_url) !== null) {
+            $user_updates['permanent'] = $a_permanent;
+        }
 
-            $auth_list = get_records_sql($db_link, "SELECT id, mac, ip FROM user_auth WHERE deleted=0 AND user_id=" . $val);
-            $b_mac = '';
-            $b_ip = '';
-            if (!empty($auth_list)) {
-                foreach ($auth_list as $row) {
-                    if (empty($row)) { continue; }
-                    if (empty($b_mac) and !empty($row["mac"])) { $b_mac = $row["mac"]; }
-                    if (empty($b_ip) and !empty($row["ip"])) { $b_ip = $row["ip"]; }
-                    if (!empty($auth)) {
-                        $ret = update_record($db_link, "user_auth", "id='" . $row["id"] . "'", $auth);
-                        if (!$ret) { $all_ok = 0; }
-                    }
-                }
+        // === Обновление user_list ===
+        if (!empty($user_updates)) {
+            $login_record = get_record($db_link, "user_list", "id = ?", [$user_id]);
+            if ($login_record) {
+                $msg .= " For all ip user id: " . $user_id . " login: " . ($login_record['login'] ?? '') . " set: ";
+                $msg .= get_diff_rec($db_link, "user_list", "id = ?", $user_updates, 1, [$user_id]);
+                $ret = update_record($db_link, "user_list", "id = ?", $user_updates, [$user_id]);
+                if (!$ret) $all_ok = false;
             }
+        }
 
-            //bind mac rule
-            if (isset($_POST["e_bind_mac"])) {
-                if ($a_bind_mac) {
-                    if (!empty($b_mac)) {
-                        $auth_rules_user = get_record_sql($db_link, "SELECT * FROM auth_rules WHERE user_id=" . $val . " AND type=2");
-                        $auth_rules_mac = get_record_sql($db_link, "SELECT * FROM auth_rules WHERE rule='" . $b_mac . "' AND type=2");
-                        if (empty($auth_rules_user) and empty($auth_rules_mac)) {
-                                $new['user_id'] = $val;
-                                $new['type'] = 2;
-                                $new['rule'] = $b_mac;
-                                insert_record($db_link, "auth_rules", $new);
-                                LOG_INFO($db_link, "Created auto rule for user_id: " . $val . " and mac " . $b_mac);
-                            } else {
-                                LOG_INFO($db_link, "Auto rule for user_id: " . $val . " and mac " . $mac . " already exists");
-                            }
-                        }
-                    } else {
-                        run_sql($db_link, "DELETE FROM auth_rules WHERE user_id=" . $val . " AND type=2");
-                        LOG_INFO($db_link, "Remove auto rule for user_id: " . $val . " and mac " . $b_mac);
+        // === Получаем все активные auth записи пользователя ===
+        $auth_list = get_records_sql($db_link,
+            "SELECT id, mac, ip FROM user_auth WHERE deleted = 0 AND user_id = ?",
+            [$user_id]
+        );
+
+        $b_mac = '';
+        $b_ip = '';
+
+        // === Обновляем каждую auth запись ===
+        if (!empty($auth_list)) {
+            foreach ($auth_list as $row) {
+                if (empty($row['id'])) continue;
+                
+                if (empty($b_mac) && !empty($row['mac'])) $b_mac = $row['mac'];
+                if (empty($b_ip) && !empty($row['ip'])) $b_ip = $row['ip'];
+
+                if (!empty($auth_updates)) {
+                    $ret = update_record($db_link, "user_auth", "id = ?", $auth_updates, [(int)$row['id']]);
+                    if (!$ret) $all_ok = false;
                 }
             }
+        }
 
-            //bind ip rule
-            if (isset($_POST["e_bind_ip"])) {
-                if ($a_bind_ip) {
-                    if (!empty($b_ip)) {
-                        $auth_rules_user = get_record_sql($db_link, "SELECT * FROM auth_rules WHERE user_id=" . $val . " AND type=1");
-                        $auth_rules_ip = get_record_sql($db_link, "SELECT * FROM auth_rules WHERE rule='" . $b_ip . "' AND type=1");
-                        if (empty($auth_rules_user) and empty($auth_rules_ip)) {
-                                $new['user_id'] = $val;
-                                $new['type'] = 1;
-                                $new['rule'] = $b_ip;
-                                insert_record($db_link, "auth_rules", $new);
-                                LOG_INFO($db_link, "Created auto rule for user_id: " . $val . " and ip " . $b_ip);
-                            } else {
-                                LOG_INFO($db_link, "Auto rule for user_id: " . $val . " and ip " . $ip . " already exists");
-                            }
-                        }
-                    } else {
-                        run_sql($db_link, "DELETE FROM auth_rules WHERE user_id=" . $val . " AND type=1");
-                        LOG_INFO($db_link, "Remove auto rule for user_id: " . $val . " and ip " . $b_ip);
+        // === Правило привязки MAC ===
+        if (getPOST("e_bind_mac", $page_url) !== null) {
+            if ($a_bind_mac && $b_mac) {
+                $user_rule = get_record_sql($db_link,
+                    "SELECT * FROM auth_rules WHERE user_id = ? AND type = 2",
+                    [$user_id]
+                );
+                $mac_rule = get_record_sql($db_link,
+                    "SELECT * FROM auth_rules WHERE rule = ? AND type = 2",
+                    [$b_mac]
+                );
+
+                if (!$user_rule && !$mac_rule) {
+                    insert_record($db_link, "auth_rules", [
+                        'user_id' => $user_id,
+                        'type' => 2,
+                        'rule' => $b_mac
+                    ]);
+                    LOG_INFO($db_link, "Created auto rule for user_id: $user_id and mac $b_mac");
+                } else {
+                    LOG_INFO($db_link, "Auto rule for user_id: $user_id and mac $b_mac already exists");
                 }
+            } else {
+                run_sql($db_link, "DELETE FROM auth_rules WHERE user_id = ? AND type = 2", [$user_id]);
+                LOG_INFO($db_link, "Remove auto rule for user_id: $user_id and mac $b_mac");
             }
+        }
 
-            //create network devices
-            if (isset($_POST["e_create_netdev"])) {
-                if ($a_create_netdev) {
-                    if (!empty($b_ip)) {
-                        $device = get_record_sql($db_link,"SELECT * FROM devices WHERE user_id=".$val);
-                        $auth = get_record_sql($db_link,"SELECT * FROM user_auth WHERE user_id=".$val." ORDER BY last_found DESC");
-                        if (empty($device) and !empty($auth)) {
-                            $new['user_id']=$val;
-                            $new['device_name'] = $login['login'];
-                            $new['device_type'] = 5;
-                            $new['ip']=$auth['ip'];
-                            $new['community'] = get_const('snmp_default_community');
-                            $new['snmp_version'] = get_const('snmp_default_version');
-                            $new['login'] = get_option($db_link,28);
-                            $new['password'] = get_option($db_link,29);
-                            //default ssh
-                            $new['protocol'] = 0;
-                            $new['control_port'] = get_option($db_link,30);
-                            $new_id=insert_record($db_link, "devices", $new);
-                        }
-                    }
+        // === Правило привязки IP ===
+        if (getPOST("e_bind_ip", $page_url) !== null) {
+            if ($a_bind_ip && $b_ip) {
+                $user_rule = get_record_sql($db_link,
+                    "SELECT * FROM auth_rules WHERE user_id = ? AND type = 1",
+                    [$user_id]
+                );
+                $ip_rule = get_record_sql($db_link,
+                    "SELECT * FROM auth_rules WHERE rule = ? AND type = 1",
+                    [$b_ip]
+                );
+
+                if (!$user_rule && !$ip_rule) {
+                    insert_record($db_link, "auth_rules", [
+                        'user_id' => $user_id,
+                        'type' => 1,
+                        'rule' => $b_ip
+                    ]);
+                    LOG_INFO($db_link, "Created auto rule for user_id: $user_id and ip $b_ip");
+                } else {
+                    LOG_INFO($db_link, "Auto rule for user_id: $user_id and ip $b_ip already exists");
                 }
+            } else {
+                run_sql($db_link, "DELETE FROM auth_rules WHERE user_id = ? AND type = 1", [$user_id]);
+                LOG_INFO($db_link, "Remove auto rule for user_id: $user_id and ip $b_ip");
             }
+        }
 
+        // === Создание сетевого устройства ===
+        if (getPOST("e_create_netdev", $page_url) !== null && $a_create_netdev && $b_ip) {
+            $existing_device = get_record_sql($db_link,
+                "SELECT * FROM devices WHERE user_id = ?",
+                [$user_id]
+            );
+            
+            if (!$existing_device) {
+                $latest_auth = get_record_sql($db_link,
+                    "SELECT * FROM user_auth WHERE user_id = ? ORDER BY last_found DESC",
+                    [$user_id]
+                );
+                
+                if ($latest_auth) {
+                    $new_device = [
+                        'user_id' => $user_id,
+                        'device_name' => $login_record['login'] ?? 'user_' . $user_id,
+                        'device_type' => 5,
+                        'ip' => $latest_auth['ip'],
+                        'community' => get_const('snmp_default_community'),
+                        'snmp_version' => get_const('snmp_default_version'),
+                        'login' => get_option($db_link, 28),
+                        'password' => get_option($db_link, 29),
+                        'protocol' => 0,
+                        'control_port' => get_option($db_link, 30)
+                    ];
+                    
+                    $new_id = insert_record($db_link, "devices", $new_device);
+                }
+            }
         }
     }
+
     if ($all_ok) {
         print "Success!";
     } else {
         print "Fail!";
     }
 }
+?>

+ 19 - 13
html/utils/user_remove.php

@@ -4,17 +4,23 @@ require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/languages/" . HTML_LANG . ".php")
 
 if (!defined("CONFIG")) die("Not defined");
 
-if (isset($_POST["RemoveUser"]) and (isset($_POST["f_deleted"]))) {
-	if ($_POST["f_deleted"] * 1) {
-		$fid = $_POST["fid"];
-		$all_ok = 1;
-		foreach ($fid as $key => $val) {
-			if ($val) { delete_user($db_link,$val); }
-		}
-		if ($all_ok) {
-			print "Success!";
-		} else {
-			print "Fail!";
-		}
-	}
+if (isset($_POST["RemoveUser"]) && !empty($_POST["f_deleted"])) {
+    $fid = $_POST["fid"] ?? [];
+    $all_ok = true;
+
+    foreach ($fid as $val) {
+        if ($val = (int)$val) {
+            $result = delete_user($db_link, $val);
+            if (!$result) {
+                $all_ok = false;
+            }
+        }
+    }
+
+    if ($all_ok) {
+        print "Success!";
+    } else {
+        print "Fail!";
+    }
 }
+?>

+ 22 - 8
install-eye.sh

@@ -271,7 +271,7 @@ install_deps_altlinux() {
 
     # === Сетевой бэкенд (если нужен) ===
     if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "backend" ]]; then
-        apt-get install -y fping dnsmasq syslog-ng syslog-ng-journal
+        apt-get install -y fping
 
         # Общие Perl-модули (независимо от СУБД)
         apt-get install -y perl \
@@ -326,6 +326,7 @@ install_deps_debian() {
             php-bcmath php-intl php-mbstring php-snmp php-zip php-mail \
             php-date php-db
 
+
         if [[ "$DB_TYPE" == "postgresql" ]]; then
             apt-get install -y php-pgsql
         else
@@ -335,7 +336,7 @@ install_deps_debian() {
 
     # === Сетевой бэкенд (если нужен) ===
     if [[ "$INSTALL_TYPE" == "full" || "$INSTALL_TYPE" == "backend" ]]; then
-        apt-get install -y fping dnsmasq syslog-ng
+        apt-get install -y fping
 
         # Perl и обязательные модули (имена корректны для Ubuntu 24.04)
         apt-get install -y perl \
@@ -1156,7 +1157,8 @@ setup_apache_php() {
     print_step "Configuring Apache and PHP"
 
     # Determine PHP version
-    PHP_VERSION=$(php -v 2>/dev/null | head -n1 | grep -oP '\d+\.\d+' || echo "8.1")
+    PHP_VERSION=$(php -v 2>/dev/null | head -n1 | grep -oP '\d+\.\d+' || echo "8.2")
+    echo "Версия PHP: $PHP_VERSION"
 
     # Configure PHP for all distributions
     if [[ "$OS_FAMILY" == "alt" ]]; then
@@ -1265,12 +1267,12 @@ setup_cron_logrotate() {
     fi
 
     # Logrotate
-    if [[ -f "/opt/Eye/docs/logrotate/dnsmasq" ]]; then
-        cp /opt/Eye/docs/logrotate/dnsmasq /etc/logrotate.d/dnsmasq-eye
+    if [ -f /etc/dnsmasq.conf ] && [ -f "/opt/Eye/docs/logrotate/dnsmasq" ]; then
+	cp /opt/Eye/docs/logrotate/dnsmasq /etc/logrotate.d/dnsmasq-eye
     fi
 
-    if [[ -f "/opt/Eye/docs/logrotate/scripts" ]]; then
-        cp /opt/Eye/docs/logrotate/scripts /etc/logrotate.d/eye-scripts
+    if [ -e /opt/Eye/scripts ] && [ -f "/opt/Eye/docs/logrotate/scripts" ]; then
+	cp /opt/Eye/docs/logrotate/scripts /etc/logrotate.d/eye-scripts
     fi
 
     print_info "Cron and logrotate configuration completed"
@@ -1287,6 +1289,12 @@ setup_dhcp_server() {
         return 0
     fi
 
+    if [[ "$OS_FAMILY" == "debian" ]]; then
+	apt install dnsmasq -y
+	else
+	apt-get install dnsmasq -y
+	fi
+
     # Backup configuration
     if [[ -f "/etc/dnsmasq.conf" ]]; then
         cp /etc/dnsmasq.conf /etc/dnsmasq.conf.backup
@@ -1324,6 +1332,12 @@ setup_syslog() {
         return 0
     fi
 
+    if [[ "$OS_FAMILY" == "debian" ]]; then
+	apt install syslog-ng -y
+	else
+	apt-get install syslog-ng syslog-ng-journal -y
+	fi
+
     # Create backup of main config
     if [[ -f "/etc/syslog-ng/syslog-ng.conf" ]]; then
         cp /etc/syslog-ng/syslog-ng.conf /etc/syslog-ng/syslog-ng.conf.backup
@@ -1530,7 +1544,7 @@ show_final_instructions() {
     echo "  Distribution:     $OS_NAME"
     echo "  Version:          $OS_VERSION"
     echo "  Database:         $DB_TYPE"
-    echo "  Language:         $EYE_LANG"  # <-- Добавлено
+    echo "  Language:         $EYE_LANG"
     echo "  User:             eye"
     echo "  Directory:        /opt/Eye"
     echo ""

+ 2 - 2
scripts/fetch_new_arp.pl

@@ -507,7 +507,7 @@ foreach my $mac (keys %mac_history) {
     next if (!$mac || !$mac_history{$mac}->{changed});
     my $h_dev_id  = $mac_history{$mac}->{dev_id}  || '';
     my $h_port_id = $mac_history{$mac}->{port_id} || '';
-    my $h_ip      = $mac_history{$mac}->{ip}      || '';
+    my $h_ip      = $mac_history{$mac}->{ip};
     my $h_auth_id = $mac_history{$mac}->{auth_id} || 0;
     next if (!$h_dev_id);
 
@@ -515,7 +515,7 @@ foreach my $mac (keys %mac_history) {
     $history_rec->{device_id} = $h_dev_id;
     $history_rec->{port_id}   = $h_port_id;
     $history_rec->{mac}       = $mac;
-    $history_rec->{ip}        = $h_ip;
+    $history_rec->{ip}        = $h_ip if ($h_ip);
     $history_rec->{auth_id}   = $h_auth_id;
     insert_record($dbh, 'mac_history', $history_rec);
 }