Dmitriev Roman 3 месяцев назад
Родитель
Сommit
f0cb17e953

+ 0 - 4
html/admin/devices/edit_gw_instances.php

@@ -19,7 +19,6 @@ if (getPOST("s_remove") !== null) {
             delete_record($db_link, "device_filter_instances", "id = ?", [$val]);
             delete_record($db_link, "device_filter_instances", "id = ?", [$val]);
         }
         }
     }
     }
-    
     header("Location: " . $_SERVER["REQUEST_URI"]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
     exit;
 }
 }
@@ -27,17 +26,14 @@ if (getPOST("s_remove") !== null) {
 // Создание нового фильтра
 // Создание нового фильтра
 if (getPOST("s_create") !== null) {
 if (getPOST("s_create") !== null) {
     $new_instance = trim(getPOST("new_instance", null, ''));
     $new_instance = trim(getPOST("new_instance", null, ''));
-    
     if ($new_instance !== '') {
     if ($new_instance !== '') {
         $new = [
         $new = [
             'instance_id' => $new_instance,
             'instance_id' => $new_instance,
             'device_id'   => $id
             'device_id'   => $id
         ];
         ];
-        
         LOG_INFO($db_link, "Add instance id: " . $new['instance_id'] . " for gateway id: " . $id);
         LOG_INFO($db_link, "Add instance id: " . $new['instance_id'] . " for gateway id: " . $id);
         insert_record($db_link, "device_filter_instances", $new);
         insert_record($db_link, "device_filter_instances", $new);
     }
     }
-    
     header("Location: " . $_SERVER["REQUEST_URI"]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
     exit;
 }
 }

+ 26 - 13
html/admin/devices/edit_gw_subnets.php

@@ -4,28 +4,41 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . HTML_LANG . ".php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . HTML_LANG . ".php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
 
 
-$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']]);
 
 
-if (isset($_POST["s_remove"])) {
-    $s_id = $_POST["gs_id"];
-    foreach ($s_id as $key => $val) {
-        if (isset($val)) {
-            LOG_INFO($db_link, "Remove subnet from gateway id: $val ". dump_record($db_link,'gateway_subnets','id=?',[$val]));
-            delete_record($db_link, "gateway_subnets", "id=?" , [ $val ]);
+// Удаление подсетей шлюза
+if (getPOST("s_remove") !== null) {
+    $s_id = getPOST("gs_id", null, []);
+    
+    if (!empty($s_id) && is_array($s_id)) {
+        foreach ($s_id as $val) {
+            $val = trim($val);
+            if ($val === '') continue;
+            
+            LOG_INFO($db_link, "Remove subnet from gateway id: $val " . dump_record($db_link, 'gateway_subnets', 'id = ?', [$val]));
+            delete_record($db_link, "gateway_subnets", "id = ?", [(int)$val]);
         }
         }
     }
     }
+    
     header("Location: " . $_SERVER["REQUEST_URI"]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
     exit;
 }
 }
 
 
-if (isset($_POST["s_create"])) {
-    if (!empty($_POST["new_subnet"])) {
-        $new['subnet_id'] = trim($_POST["new_subnet"]);
-        $new['device_id'] = $id;
-        LOG_INFO($db_link, "Add subnet id: ".$new['subnet_id']." for gateway id: ".$id);
+// Добавление подсети к шлюзу
+if (getPOST("s_create") !== null) {
+    $new_subnet = trim(getPOST("new_subnet", null, ''));
+    
+    if ($new_subnet !== '') {
+        $new = [
+            'subnet_id' => $new_subnet,
+            'device_id' => $id
+        ];
+        
+        LOG_INFO($db_link, "Add subnet id: " . $new['subnet_id'] . " for gateway id: " . $id);
         insert_record($db_link, "gateway_subnets", $new);
         insert_record($db_link, "gateway_subnets", $new);
     }
     }
+    
     header("Location: " . $_SERVER["REQUEST_URI"]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
     exit;
 }
 }

+ 120 - 90
html/admin/devices/edit_l3int.php

@@ -1,135 +1,165 @@
 <?php
 <?php
+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");
 
 
-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]);
+$snmp = getSnmpAccess($device);
+$user_info = get_record_sql($db_link, "SELECT * FROM user_list WHERE id = ?", [$device['user_id']]);
+$int_list = getIpAdEntIfIndex($db_link, $device['ip'], $snmp);
 
 
-$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']]);
-$int_list = getIpAdEntIfIndex($db_link,$device['ip'],$snmp);
-
-if (isset($_POST["s_remove"])) {
-    $s_id = $_POST["s_id"];
-    foreach ($s_id as $key => $val) {
-        if (isset($val)) {
-            LOG_INFO($db_link, "Remove l3_interface id: $val ". dump_record($db_link,'device_l3_interfaces','id=?',[$val]));
-            delete_record($db_link, "device_l3_interfaces", "id=?", [$val]);
+// Удаление L3-интерфейсов
+if (getPOST("s_remove") !== null) {
+    $s_id = getPOST("s_id", null, []);
+    
+    if (!empty($s_id) && is_array($s_id)) {
+        foreach ($s_id as $val) {
+            $val = trim($val);
+            if ($val === '') continue;
+            
+            LOG_INFO($db_link, "Remove l3_interface id: $val " . dump_record($db_link, 'device_l3_interfaces', 'id = ?', [$val]));
+            delete_record($db_link, "device_l3_interfaces", "id = ?", [(int)$val]);
         }
         }
     }
     }
+    
     header("Location: " . $_SERVER["REQUEST_URI"]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
     exit;
 }
 }
 
 
-if (isset($_POST['s_save'])) {
-    $len = is_array($_POST['s_save']) ? count($_POST['s_save']) : 0;
-    for ($i = 0; $i < $len; $i ++) {
-        $save_id = intval($_POST['s_save'][$i]);
-        $len_all = is_array($_POST['n_id']) ? count($_POST['n_id']) : 0;
-        for ($j = 0; $j < $len_all; $j ++) {
-            if (intval($_POST['n_id'][$j]) != $save_id) { continue; }
-            $new['interface_type'] = $_POST['s_type'][$j]*1;
-            update_record($db_link, "device_l3_interfaces", "id=?", $new, [$save_id]);
+// Сохранение ОТМЕЧЕННЫХ L3-интерфейсов
+if (getPOST("s_save") !== null) {
+    $selected_ids = getPOST("s_id", null, []);      // отмеченные чекбоксы
+    $all_ids      = getPOST("n_id", null, []);      // все ID
+    $types        = getPOST("s_type", null, []);
+    
+    if (!empty($selected_ids) && is_array($selected_ids)) {
+        $selected_ids = array_map('intval', $selected_ids);
+        $selected_set = array_flip($selected_ids);
+        
+        foreach ($all_ids as $i => $id) {
+            $id = (int)$id;
+            if ($id <= 0 || !isset($selected_set[$id])) continue;
+            
+            $new = [
+                'interface_type' => (int)($types[$i] ?? 0)
+            ];
+            
+            update_record($db_link, "device_l3_interfaces", "id = ?", $new, [$id]);
         }
         }
     }
     }
+    
     header("Location: " . $_SERVER["REQUEST_URI"]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
     exit;
 }
 }
 
 
-if (isset($_POST["s_create"])) {
-    if (!empty($_POST["s_create_name"])) {
-        $new = NULL;
-        list($new['name'],$new['snmpin'],$new['interface_type']) = explode(";", trim($_POST["s_create_name"]));
-        $new['device_id'] = $id;
-        $new['name']=preg_replace('/\"/','',$new['name']);
-        LOG_INFO($db_link, "Create new l3_interface ".$new['name']);
-        insert_record($db_link, "device_l3_interfaces", $new);
+// Создание нового L3-интерфейса
+if (getPOST("s_create") !== null) {
+    $create_name = trim(getPOST("s_create_name", null, ''));
+    
+    if ($create_name !== '') {
+        $parts = explode(";", $create_name);
+        if (count($parts) >= 3) {
+            $new = [
+                'name'           => preg_replace('/"/', '', trim($parts[0])),
+                'snmpin'         => trim($parts[1]),
+                'interface_type' => (int)trim($parts[2]),
+                'device_id'      => $id
+            ];
+            
+            LOG_INFO($db_link, "Create new l3_interface " . $new['name']);
+            insert_record($db_link, "device_l3_interfaces", $new);
+        }
     }
     }
+    
     header("Location: " . $_SERVER["REQUEST_URI"]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
     exit;
 }
 }
 
 
 unset($_POST);
 unset($_POST);
 
 
-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']);
-
-?>
-<div id="contsubmenu">
-<br>
-<?php print "<form name=def action='edit_l3int.php?id=".$id."' method=post>"; ?>
-<?php print WEB_list_l3_interfaces."<b>"; print_url($device['device_name'],"/admin/devices/editdevice.php?id=$id"); ?>
-</b> <br>
-<table class="data">
-<tr align="center">
-	<td></td>
-	<td width=30><b>id</b></td>
-	<td><b><?php echo WEB_cell_name; ?></b></td>
-	<td><b><?php echo WEB_cell_type; ?></b></td>
-	<td>
-	<input type="submit" onclick="return confirm('<?php print WEB_msg_delete; ?>?')" name="s_remove" value="<?php print WEB_btn_remove; ?>">
-	</td>
-</tr>
-<?php
-
-$t_l3_interface = get_records_sql($db_link,"SELECT * FROM device_l3_interfaces WHERE device_id=? ORDER BY name", [ $id ]);
+// Автоисправление интерфейсов
+$t_l3_interface = get_records_sql($db_link, "SELECT * FROM device_l3_interfaces WHERE device_id = ? ORDER BY name", [$id]);
 
 
 $int_by_name = [];
 $int_by_name = [];
 foreach ($int_list as $row) {
 foreach ($int_list as $row) {
-    $row['name'] = preg_replace('/\"/','',$row['name']);
-    $int_by_name[$row['name']]=$row;
+    $row['name'] = preg_replace('/"/', '', $row['name']);
+    $int_by_name[$row['name']] = $row;
 }
 }
 $fixed = 0;
 $fixed = 0;
 
 
-//fixing snmp index if not exists by interface name
-foreach ( $t_l3_interface as $row ) {
-    $fix = NULL;
-    if (empty($row['snmpin']) and !empty($int_by_name[$row['name']])) {
-        $fix['snmpin']=$int_by_name[$row['name']]['index'];
-        if (!empty($fix)) {
-            update_record($db_link,'device_l3_interfaces','id=?',$fix, [ $row['id'] ]);
-            }
+// Исправление snmpin по имени
+foreach ($t_l3_interface as $row) {
+    if (empty($row['snmpin']) && !empty($int_by_name[$row['name']])) {
+        update_record($db_link, 'device_l3_interfaces', 'id = ?', ['snmpin' => $int_by_name[$row['name']]['index']], [$row['id']]);
         $fixed = 1;
         $fixed = 1;
-        }
     }
     }
+}
 
 
-//updating interface name by snmp index
-foreach ( $t_l3_interface as $row ) {
-    $fix = NULL;
-    if (!empty($int_list[$row['snmpin']]) and $int_list[$row['snmpin']]['name'] !== $row['name']) {
-        $fix['name']=$int_list[$row['snmpin']]['name'];
-        if (!empty($fix)) {
-            update_record($db_link,'device_l3_interfaces','id=?', $fix, [$row['id']]);
-            }
+// Обновление имени по snmpin
+foreach ($t_l3_interface as $row) {
+    if (!empty($int_list[$row['snmpin']]) && $int_list[$row['snmpin']]['name'] !== $row['name']) {
+        update_record($db_link, 'device_l3_interfaces', 'id = ?', ['name' => $int_list[$row['snmpin']]['name']], [$row['id']]);
         $fixed = 1;
         $fixed = 1;
-        }
     }
     }
+}
 
 
 if ($fixed) {
 if ($fixed) {
-    $t_l3_interface = get_records_sql($db_link,"SELECT * FROM device_l3_interfaces WHERE device_id=? ORDER BY name", [ $id ]);
-    }
+    $t_l3_interface = get_records_sql($db_link, "SELECT * FROM device_l3_interfaces WHERE device_id = ? ORDER BY name", [$id]);
+}
 
 
-foreach ( $t_l3_interface as $row ) {
+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']);
+?>
+<div id="contsubmenu">
+<br>
+<form name="def" action="edit_l3int.php?id=<?php echo $id; ?>" method="post">
+<?php echo WEB_list_l3_interfaces . "<b>"; print_url($device['device_name'], "/admin/devices/editdevice.php?id=$id"); ?></b> <br>
+<table class="data">
+<tr align="center">
+    <td><input type="checkbox" onClick="checkAll(this.checked);"></td>
+    <td width=30><b>id</b></td>
+    <td><b><?php echo WEB_cell_name; ?></b></td>
+    <td><b><?php echo WEB_cell_type; ?></b></td>
+    <td>
+        <!-- Кнопки управления справа -->
+        <div style="text-align: right; white-space: nowrap;">
+            <input type="submit" name="s_save" value="<?php echo WEB_btn_save; ?>">
+            <input type="submit" 
+                   onclick="return confirm('<?php echo WEB_msg_delete; ?>?')" 
+                   name="s_remove" 
+                   value="<?php echo WEB_btn_remove; ?>"
+                   style="margin-left: 8px;">
+        </div>
+    </td>
+</tr>
+<?php
+foreach ($t_l3_interface as $row) {
     print "<tr align=center>\n";
     print "<tr align=center>\n";
-    print "<td class=\"data\" style='padding:0'><input type=checkbox name=s_id[] value='{$row['id']}'></td>\n";
-    print "<td class=\"data\"><input type=\"hidden\" name='n_id[]' value='{$row['id']}'>{$row['snmpin']}</td>\n";
-    print "<td class=\"data\">".$row['name'].'/'.$int_list[$row['snmpin']]['ip']."</td>\n";
-    print "<td class=\"data\">"; print_qa_l3int_select('s_type[]',$row['interface_type']); print "</td>\n";
-    print "<td class=\"data\"><button name='s_save[]' value='{$row['id']}'>".WEB_btn_save."</button></td>\n";
+    print "<td class=\"data\" style='padding:0'><input type=\"checkbox\" name=\"s_id[]\" value=\"{$row['id']}\"></td>\n";
+    print "<td class=\"data\"><input type=\"hidden\" name=\"n_id[]\" value=\"{$row['id']}\">{$row['snmpin']}</td>\n";
+    print "<td class=\"data\">" . htmlspecialchars($row['name']) . '/' . htmlspecialchars($int_list[$row['snmpin']]['ip'] ?? '') . "</td>\n";
+    print "<td class=\"data\">";
+    print_qa_l3int_select('s_type[]', $row['interface_type']);
+    print "</td>\n";
+    print "<td class=\"data\"></td>\n";
     print "</tr>\n";
     print "</tr>\n";
-    }
+}
 ?>
 ?>
 <tr>
 <tr>
-<td colspan=4><?php print WEB_l3_interface_add; print_add_dev_interface($db_link, $id, $int_list, 's_create_name');?>
-</td>
-<td>
-<input type="submit" name="s_create" value="<?php echo WEB_btn_add; ?>">
-</td>
+    <td colspan=4>
+        <?php 
+        echo WEB_l3_interface_add; 
+        print_add_dev_interface($db_link, $id, $int_list, 's_create_name');
+        ?>
+    </td>
+    <td>
+        <input type="submit" name="s_create" value="<?php echo WEB_btn_add; ?>">
+    </td>
 </tr>
 </tr>
 </table>
 </table>
 </form>
 </form>
 <?php
 <?php
-require_once ($_SERVER['DOCUMENT_ROOT']."/inc/footer.php");
+require_once ($_SERVER['DOCUMENT_ROOT'] . "/inc/footer.php");
 ?>
 ?>

+ 112 - 122
html/admin/devices/editdevice.php

@@ -3,145 +3,135 @@ require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/auth.php");
 require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/languages/" . HTML_LANG . ".php");
 require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/languages/" . HTML_LANG . ".php");
 require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/idfilter.php");
 require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/idfilter.php");
 
 
-if (isset($_POST["editdevice"]) and isset($id)) {
-    if (isset($_POST["f_port_count"])) {
-        $sw_ports = $_POST["f_port_count"] * 1;
-    } else {
-        $sw_ports = 0;
-    }
-    $sSQL = "SELECT count(id) from device_ports WHERE device_ports.device_id=?";
-    $d_ports = get_single_field($db_link,$sSQL, [$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']]);
+
+if (getPOST("editdevice") !== null && isset($id)) {
+    // === УПРАВЛЕНИЕ ПОРТАМИ ====================================================
+    $sw_ports = (int)getPOST("f_port_count", null, 0);
+    $sSQL = "SELECT COUNT(id) FROM device_ports WHERE device_ports.device_id = ?";
+    $d_ports = (int)get_single_field($db_link, $sSQL, [$id]);
+
     if ($d_ports != $sw_ports) {
     if ($d_ports != $sw_ports) {
         LOG_DEBUG($db_link, "Device id: $id changed port count!");
         LOG_DEBUG($db_link, "Device id: $id changed port count!");
+        
         if ($sw_ports > $d_ports) {
         if ($sw_ports > $d_ports) {
             $start_port = $d_ports + 1;
             $start_port = $d_ports + 1;
             LOG_DEBUG($db_link, "Device id: $id add connection for port from $start_port to $sw_ports.");
             LOG_DEBUG($db_link, "Device id: $id add connection for port from $start_port to $sw_ports.");
             for ($port = $start_port; $port <= $sw_ports; $port++) {
             for ($port = $start_port; $port <= $sw_ports; $port++) {
-                $new['device_id'] = $id;
-                $new['snmp_index'] = $port;
-                $new['port'] = $port;
-                insert_record($db_link, "device_ports", $new);
+                insert_record($db_link, "device_ports", [
+                    'device_id'   => $id,
+                    'snmp_index'  => $port,
+                    'port'        => $port
+                ]);
             }
             }
         }
         }
+        
         if ($sw_ports < $d_ports) {
         if ($sw_ports < $d_ports) {
             LOG_DEBUG($db_link, "Device id: $id remove connection for port from $d_ports to $sw_ports");
             LOG_DEBUG($db_link, "Device id: $id remove connection for port from $d_ports to $sw_ports");
             for ($port = $d_ports; $port > $sw_ports; $port--) {
             for ($port = $d_ports; $port > $sw_ports; $port--) {
-                $port_id = get_id_record($db_link, 'device_ports', "device_id=? and port=?", [ $id, $port ]);
+                $port_id = get_id_record($db_link, 'device_ports', "device_id = ? AND port = ?", [$id, $port]);
                 if ($port_id) {
                 if ($port_id) {
-                    delete_record($db_link, "device_ports", "id=?" ,[ $port_id ]);
-                    run_sql($db_link, "DELETE FROM connections WHERE port_id=?", [ $port_id ]);
+                    delete_record($db_link, "device_ports", "id = ?", [$port_id]);
+                    delete_records($db_link, "connections", "port_id = ?", [$port_id]);
                 } else {
                 } else {
                     LOG_DEBUG($db_link, "Device id: $id port_id not found for port: $port!");
                     LOG_DEBUG($db_link, "Device id: $id port_id not found for port: $port!");
                 }
                 }
             }
             }
         }
         }
     }
     }
-    unset($new);
-    if (isset($_POST["f_ip"])) {
-        $new['ip'] = $_POST["f_ip"];
-        $new['ip_int'] = ip2long($new['ip']);
-    }
-    $cur_device = get_record_sql($db_link, "SELECT * FROM devices WHERE id=?", [ $id ]);
-    //main device info
-    if (!empty($new['ip'])) {
-        $cur_auth = get_record_sql($db_link, "SELECT * FROM user_auth WHERE deleted=0 AND ip=?",[ $new['ip'] ]);
-    }
-    if (isset($_POST["f_device_model_id"])) {
-        $new['device_model_id'] = $_POST["f_device_model_id"] * 1;
-        $new['vendor_id'] = get_device_model_vendor($db_link, $new['device_model_id']);
-    }
-    if (isset($_POST["f_port_count"])) {
-        $new['port_count'] = $sw_ports;
-    }
-    if (isset($_POST["f_devtype_id"])) {
-        $new['device_type'] = $_POST["f_devtype_id"] * 1;
-    }
-    if (isset($_POST["f_description"])) {
-        $new['description'] = $_POST["f_description"];
-    }
-    if (isset($_POST["f_SN"])) {
-        $new['SN'] = $_POST["f_SN"];
-    }
-    if (isset($_POST["f_firmware"])) {
-        $new['firmware'] = $_POST["f_firmware"];
-    }
-    //snmp
-    if (isset($_POST["f_snmp_version"])) {
-        $new['snmp_version'] = $_POST["f_snmp_version"] * 1;
-    }
-    if (isset($_POST["f_community"])) {
-        $new['community'] = substr($_POST["f_community"], 0, 50);
-    }
-    if (isset($_POST["f_snmp3_auth_proto"])) {
-        $new['snmp3_auth_proto'] = trim(substr($_POST["f_snmp3_auth_proto"], 0, 10));
-    }
-    if (isset($_POST["f_snmp3_priv_proto"])) {
-        $new['snmp3_priv_proto'] = trim(substr($_POST["f_snmp3_priv_proto"], 0, 10));
-    }
-    if (isset($_POST["f_rw_community"])) {
-        $new['rw_community'] = substr($_POST["f_rw_community"], 0, 50);
-    }
-    if (isset($_POST["f_snmp3_user_rw"])) {
-        $new['snmp3_user_rw'] = substr($_POST["f_snmp3_user_rw"], 0, 20);
-    }
-    if (isset($_POST["f_snmp3_user_ro"])) {
-        $new['snmp3_user_ro'] = substr($_POST["f_snmp3_user_ro"], 0, 20);
-    }
-    if (isset($_POST["f_snmp3_user_rw_password"])) {
-        $new['snmp3_user_rw_password'] = substr($_POST["f_snmp3_user_rw_password"], 0, 20);
-    }
-    if (isset($_POST["f_snmp3_user_ro_password"])) {
-        $new['snmp3_user_ro_password'] = substr($_POST["f_snmp3_user_ro_password"], 0, 20);
-    }
-    //acl & configuration options
-    if (isset($_POST["f_queue_enabled"])) {
-        $new['queue_enabled'] = $_POST["f_queue_enabled"] * 1;
-    }
-    if (isset($_POST["f_connected_user_only"])) {
-        $new['connected_user_only'] = $_POST["f_connected_user_only"] * 1;
-    }
-    if (isset($_POST["f_dhcp"])) {
-        $new['dhcp'] = $_POST["f_dhcp"] * 1;
-    }
-    if (isset($_POST["f_user_acl"])) {
-        $new['user_acl'] = $_POST["f_user_acl"] * 1;
-    }
-    //interfaces
-    if (isset($_POST["f_wan"])) {
-        $new['wan_int'] = $_POST["f_wan"];
-    }
-    if (isset($_POST["f_lan"])) {
-        $new['lan_int'] = $_POST["f_lan"];
-    }
-    //location
-    if (isset($_POST["f_building_id"])) {
-        $new['building_id'] = $_POST["f_building_id"] * 1;
+
+    // === ОСНОВНЫЕ ДАННЫЕ УСТРОЙСТВА ============================================
+    $new = [];
+    $cur_device = get_record_sql($db_link, "SELECT * FROM devices WHERE id = ?", [$id]);
+
+    // IP-адрес
+    $f_ip = trim(getPOST("f_ip", null, ''));
+    if ($f_ip !== '') {
+        $new['ip'] = $f_ip;
+        $new['ip_int'] = ip2long($f_ip);
+        $cur_auth = get_record_sql($db_link, "SELECT * FROM user_auth WHERE deleted = 0 AND ip = ?", [$f_ip]);
     }
     }
-    //access
-    if (isset($_POST["f_login"])) {
-        $new['login'] = $_POST["f_login"];
+
+    // Модель устройства
+    $f_device_model_id = (int)getPOST("f_device_model_id", null, 0);
+    if ($f_device_model_id > 0) {
+        $new['device_model_id'] = $f_device_model_id;
+        $new['vendor_id'] = get_device_model_vendor($db_link, $f_device_model_id);
     }
     }
-    if (!empty($_POST["f_password"])) {
-        if (!preg_match('/^\*+$/', $_POST["f_password"])) {
-            $new['password'] = crypt_string($_POST["f_password"]);
+
+    // Количество портов
+    $new['port_count'] = $sw_ports;
+
+    // Тип устройства
+    $new['device_type'] = (int)getPOST("f_devtype_id", null, 0);
+
+    // === УПРАВЛЕНИЕ ЭКЗЕМПЛЯРАМИ ФИЛЬТРОВ ======================================
+    if ($new['device_type'] == 2) {
+        // Это шлюз — должен иметь хотя бы один экземпляр
+        $instances_count = get_count_records($db_link, 'device_filter_instances', 'device_id = ?', [$id]);
+        if (empty($instances_count) || $instances_count == 0) {
+            // Создаём стандартный экземпляр (ID=1)
+            insert_record($db_link, "device_filter_instances", [
+                'instance_id' => 1,
+                'device_id'   => $id
+            ]);
+            LOG_INFO($db_link, "Added default firewall instance for gateway id: $id");
+        }
+    } else {
+        // Не шлюз — удаляем все экземпляры
+        if ($device['device_type'] == 2) {
+            $instances_count = get_count_records($db_link, 'device_filter_instances', 'device_id = ?', [$id]);
+            if (!empty($instances_count) && $instances_count > 0) {
+                delete_records($db_link, 'device_filter_instances', 'device_id = ?', [$id]);
+                LOG_INFO($db_link, "Removed firewall instances for non-gateway device id: $id");
+            }
         }
         }
     }
     }
-    if (isset($_POST["f_protocol"])) {
-        $new['protocol'] = $_POST["f_protocol"] * 1;
-    }
-    if (isset($_POST["f_control_port"])) {
-        $new['control_port'] = $_POST["f_control_port"] * 1;
-    }
-    if (isset($_POST["f_save_netflow"])) {
-        $new['netflow_save'] = $_POST["f_save_netflow"] * 1;
-    }
-    //discovery
-    if (isset($_POST["f_discovery"])) {
-        $new['discovery'] = $_POST["f_discovery"];
+
+    // === ОСТАЛЬНЫЕ ПОЛЯ =========================================================
+    $new['description']           = trim(getPOST("f_description", null, ''));
+    $new['SN']                    = trim(getPOST("f_SN", null, ''));
+    $new['firmware']              = trim(getPOST("f_firmware", null, ''));
+
+    // SNMP
+    $new['snmp_version']          = (int)getPOST("f_snmp_version", null, 0);
+    $new['community']             = substr(trim(getPOST("f_community", null, '')), 0, 50);
+    $new['snmp3_auth_proto']      = substr(trim(getPOST("f_snmp3_auth_proto", null, '')), 0, 10);
+    $new['snmp3_priv_proto']      = substr(trim(getPOST("f_snmp3_priv_proto", null, '')), 0, 10);
+    $new['rw_community']          = substr(trim(getPOST("f_rw_community", null, '')), 0, 50);
+    $new['snmp3_user_rw']         = substr(trim(getPOST("f_snmp3_user_rw", null, '')), 0, 20);
+    $new['snmp3_user_ro']         = substr(trim(getPOST("f_snmp3_user_ro", null, '')), 0, 20);
+    $new['snmp3_user_rw_password']= substr(trim(getPOST("f_snmp3_user_rw_password", null, '')), 0, 20);
+    $new['snmp3_user_ro_password']= substr(trim(getPOST("f_snmp3_user_ro_password", null, '')), 0, 20);
+
+    // ACL и настройки
+    $new['queue_enabled']         = (int)getPOST("f_queue_enabled", null, 0);
+    $new['connected_user_only']   = (int)getPOST("f_connected_user_only", null, 0);
+    $new['dhcp']                  = (int)getPOST("f_dhcp", null, 0);
+    $new['user_acl']              = (int)getPOST("f_user_acl", null, 0);
+
+    // Расположение
+    $new['building_id']           = (int)getPOST("f_building_id", null, 0);
+
+    // Доступ
+    $new['login']                 = trim(getPOST("f_login", null, ''));
+    $f_password                   = getPOST("f_password", null, '');
+    if ($f_password !== '' && !preg_match('/^\*+$/', $f_password)) {
+        $new['password'] = crypt_string($f_password);
     }
     }
-    //nagios
-    if (isset($_POST["f_nagios"])) {
-        $new['nagios'] = $_POST["f_nagios"] * 1;
+
+    $new['protocol']              = (int)getPOST("f_protocol", null, 0);
+    $new['control_port']          = (int)getPOST("f_control_port", null, 0);
+    $new['netflow_save']          = (int)getPOST("f_save_netflow", null, 0);
+
+    // Discovery
+    $new['discovery']             = trim(getPOST("f_discovery", null, 0));
+
+    // Nagios
+    $f_nagios                     = (int)getPOST("f_nagios", null, -1);
+    if ($f_nagios !== -1) {
+        $new['nagios'] = $f_nagios;
         if ($new['nagios'] == 0) {
         if ($new['nagios'] == 0) {
             $new['nagios_status'] = 'UP';
             $new['nagios_status'] = 'UP';
         }
         }
@@ -152,19 +142,19 @@ if (isset($_POST["editdevice"]) and isset($id)) {
         }
         }
     }
     }
 
 
-    if ($new['device_type'] == 0 or $new['protocol']<0) {
-        $new['queue_enabled'] = 0;
+    // === ЗАВИСИМОСТИ ПО ТИПУ УСТРОЙСТВА ========================================
+    if ($new['device_type'] == 0 || $new['protocol'] < 0) {
+        $new['queue_enabled']       = 0;
         $new['connected_user_only'] = 1;
         $new['connected_user_only'] = 1;
-        $new['user_acl'] = 0;
+        $new['user_acl']            = 0;
     }
     }
 
 
-    update_record($db_link, "devices", "id=?", $new, [ $id ]);
+    // === СОХРАНЕНИЕ =============================================================
+    update_record($db_link, "devices", "id = ?", $new, [$id]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
     exit;
 }
 }
 
 
-$device = get_record($db_link, 'devices', "id=?" ,[ $id]);
-$user_info = get_record_sql($db_link, "SELECT * FROM user_list WHERE id=?", [ $device['user_id'] ]);
 unset($_POST);
 unset($_POST);
 
 
 require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/header.php");
 require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/header.php");

+ 211 - 174
html/admin/users/editauth.php

@@ -5,44 +5,47 @@ require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/idfilter.php");
 
 
 $msg_error = "";
 $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)) {
 if (empty($old_auth_info)) {
     header("Location: /admin/");
     header("Location: /admin/");
-    }
+    exit;
+}
 
 
 $parent_id = $old_auth_info['user_id'];
 $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'];
 $parent_ou_id = $user_info['ou_id'];
 $user_enabled = $user_info['enabled'];
 $user_enabled = $user_info['enabled'];
 
 
-if (isset($_POST["editauth"]) and !$old_auth_info['deleted']) {
-    $ip = normalizeIpAddress(substr(trim($_POST["f_ip"]), 0, 18));
+// === РЕДАКТИРОВАНИЕ ЗАПИСИ АВТОРИЗАЦИИ ==========================================
+if (getPOST("editauth") !== null && !$old_auth_info['deleted']) {
+    $ip = normalizeIpAddress(substr(trim(getPOST("f_ip", null, '')), 0, 18));
+    
     if (!empty($ip)) {
     if (!empty($ip)) {
         $ip_aton = ip2long($ip);
         $ip_aton = ip2long($ip);
-        $mac = mac_dotted($_POST["f_mac"]);
-        //search mac
+        $mac = mac_dotted(getPOST("f_mac", null, ''));
+        // Проверка MAC
         $mac_exists = find_mac_in_subnet($db_link, $ip, $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=? ";
-            $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'];
+        if (!empty($mac_exists) && ($mac_exists['count'] ?? 0) >= 1 && !in_array($parent_id, $mac_exists['users_id'] ?? [])) {
+            $dup_info = get_record_sql($db_link, "SELECT * FROM user_list WHERE id = ?", [$mac_exists['users_id'][0] ?? 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;
             $_SESSION[$page_url]['msg'] = $msg_error;
             LOG_ERROR($db_link, $msg_error);
             LOG_ERROR($db_link, $msg_error);
             header("Location: " . $_SERVER["REQUEST_URI"]);
             header("Location: " . $_SERVER["REQUEST_URI"]);
             exit;
             exit;
         }
         }
-        //disable dhcp for secondary ip
-        $f_dhcp = $_POST["f_dhcp"] * 1;
-        if (!empty($mac_exists) and in_array($parent_id, $mac_exists['users_id'])) {
-            if ($parent_id != $mac_exists['users_id'][0]) {
+
+        // DHCP для вторичного IP
+        $f_dhcp = (int)getPOST("f_dhcp", null, 0);
+        if (!empty($mac_exists) && in_array($parent_id, $mac_exists['users_id'] ?? [])) {
+            if ($parent_id != ($mac_exists['users_id'][0] ?? null)) {
                 $f_dhcp = 0;
                 $f_dhcp = 0;
             }
             }
         }
         }
-        //search ip
-        $dup_ip_record = get_record_sql($db_link, "SELECT * FROM user_auth WHERE ip_int=? AND id<>? AND deleted=0", [ $ip_aton, $id ]);
+
+        // Проверка дубликата IP
+        $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)) {
         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'];
             $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;
             $_SESSION[$page_url]['msg'] = $msg_error;
             LOG_ERROR($db_link, $msg_error);
             LOG_ERROR($db_link, $msg_error);
@@ -50,126 +53,145 @@ if (isset($_POST["editauth"]) and !$old_auth_info['deleted']) {
             exit;
             exit;
         }
         }
 
 
-        $new['ip'] = $ip;
-        $new['ou_id'] = $parent_ou_id;
-        $new['ip_int'] = $ip_aton;
-        $new['mac'] = mac_dotted($_POST["f_mac"]);
-        $new['description'] = $_POST["f_description"];
-        $new['WikiName'] = $_POST["f_wiki"];
-        $f_dnsname = trim($_POST["f_dns_name"]);
-        $new['dns_ptr_only']=0;
-        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'] ]);
-        if (!empty($device)) {
-            $dev['ip'] = $ip;
-            $dev['ip_int']=$ip_aton;
-            update_record($db_link,"devices","id=?",$dev, [ $device['id'] ]);
+        $new = [
+            'ip'          => $ip,
+            'ou_id'       => $parent_ou_id,
+            'ip_int'      => $ip_aton,
+            'mac'         => $mac,
+            'description' => trim(getPOST("f_description", null, '')),
+            'WikiName'    => trim(getPOST("f_wiki", null, ''))
+        ];
+
+        $f_dnsname = trim(getPOST("f_dns_name", null, ''));
+        $f_dns_ptr_present = (getPOST("f_dns_ptr", null, null) !== null);
+        if (empty($f_dnsname)) {
+            $new['dns_ptr_only'] = 0;
+            $new['dns_name'] = '';
+            } else {
+            $new['dns_ptr_only'] = $f_dns_ptr_present ? 1 : 0;
             }
             }
+        
+        // Обновление IP в devices
+        $device = get_record_sql($db_link, "SELECT * FROM devices WHERE ip_int = ?", [$old_auth_info['ip_int']]);
+        if (!empty($device)) {
+            update_record($db_link, "devices", "id = ?", [
+                'ip'     => $ip,
+                'ip_int' => $ip_aton
+            ], [$device['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, '.');
-            $f_dnsname = preg_replace('/\.' . str_replace('.', '\.', $domain_zone) . '$/', '', $f_dnsname);
-//            $f_dnsname = preg_replace('/\.$/','',$f_dnsname);
-            $f_dnsname = preg_replace('/\s+/','-',$f_dnsname);
-//            $f_dnsname = preg_replace('/\./','-',$f_dnsname);
-            //disable change dns name when exists aliases
-            if ($dns_alias_count >0 and $f_dnsname !== $old_auth_info['dns_name']) {
-                $f_dnsname =  $old_auth_info['dns_name'];
-                } else {
+        // Обработка DNS-имени и алиасов
+        $dns_alias_count = get_count_records($db_link, 'user_auth_alias', 'auth_id = ?', [$id]);
+        if (!empty($f_dnsname) && !$new['dns_ptr_only']) {
+            $domain_zone = ltrim(get_option($db_link, 33), '.');
+            $escaped_zone = preg_quote($domain_zone, '/');
+            $f_dnsname = preg_replace('/\.' . $escaped_zone . '$/i', '', $f_dnsname);
+            $f_dnsname = preg_replace('/\s+/', '-', $f_dnsname);
+
+            if ($dns_alias_count > 0 && $f_dnsname !== $old_auth_info['dns_name']) {
+                $f_dnsname = $old_auth_info['dns_name'];
+            } else {
                 $valid_dns = checkValidHostname($f_dnsname);
                 $valid_dns = checkValidHostname($f_dnsname);
-                $uniq_dns = checkUniqHostname($db_link,$id,$f_dnsname);
-                if ($valid_dns and $uniq_dns) {
-                        $new['dns_name'] = $f_dnsname;
-                        } else {
-                        if (!$uniq_dns) {
-                            $msg_error = "DNS $f_dnsname already exists at: ".searchHostname($db_link,$id,$f_dnsname)." Discard changes!";
-                            } else {
-                            $msg_error = "DNS $f_dnsname not valid! Discard changes!";
-                            }
-                        $_SESSION[$page_url]['msg'] = $msg_error;
-                        LOG_ERROR($db_link, $msg_error);
-                        header("Location: " . $_SERVER["REQUEST_URI"]);
-                        exit;
-                        }
+                $uniq_dns = checkUniqHostname($db_link, $id, $f_dnsname);
+                if ($valid_dns && $uniq_dns) {
+                    $new['dns_name'] = $f_dnsname;
+                } else {
+                    $msg_error = !$uniq_dns 
+                        ? "DNS $f_dnsname already exists at: " . searchHostname($db_link, $id, $f_dnsname) . " Discard changes!"
+                        : "DNS $f_dnsname not valid! Discard changes!";
+                    $_SESSION[$page_url]['msg'] = $msg_error;
+                    LOG_ERROR($db_link, $msg_error);
+                    header("Location: " . $_SERVER["REQUEST_URI"]);
+                    exit;
                 }
                 }
             }
             }
+        }
 
 
-        if (empty($f_dnsname) or $new['dns_ptr_only']) {
-            //remove all dns aliases
+        // Удаление алиасов при отключении DNS
+        if (empty($f_dnsname) || $new['dns_ptr_only']) {
             $new['dns_name'] = '';
             $new['dns_name'] = '';
-            $t_user_auth_alias = get_records($db_link,'user_auth_alias',"auth_id=? ORDER BY alias", [ $id ]);
+            $t_user_auth_alias = get_records($db_link, 'user_auth_alias', "auth_id = ? ORDER BY alias", [$id]);
             if (!empty($t_user_auth_alias)) {
             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'] ]);
-                    }
+                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']]);
                 }
                 }
             }
             }
+        }
 
 
-        if ($old_auth_info['dns_ptr_only'] and !$new['dns_ptr_only']) {
-            $new['dns_name'] = ''; 
-            }
-
-        if (!empty($f_dnsname) and $new['dns_ptr_only']) {
-            $domain_zone = get_option($db_link, 33);
-            $domain_zone = ltrim($domain_zone, '.');
-            $f_dnsname = preg_replace('/\.' . str_replace('.', '\.', $domain_zone) . '$/', '', $f_dnsname);
-//            $f_dnsname = preg_replace('/\.$/','',$f_dnsname);
-            $f_dnsname = preg_replace('/\s+/','-',$f_dnsname);
-//            $f_dnsname = preg_replace('/\./','-',$f_dnsname);
+        // PTR-only режим
+        if ($old_auth_info['dns_ptr_only'] && !$new['dns_ptr_only']) {
+            $new['dns_name'] = '';
+        }
+        if (!empty($f_dnsname) && $new['dns_ptr_only']) {
+            $domain_zone = ltrim(get_option($db_link, 33), '.');
+            $escaped_zone = preg_quote($domain_zone, '/');
+            $f_dnsname = preg_replace('/\.' . $escaped_zone . '$/i', '', $f_dnsname);
+            $f_dnsname = preg_replace('/\s+/', '-', $f_dnsname);
             $new['dns_name'] = $f_dnsname;
             $new['dns_name'] = $f_dnsname;
-            }
+        }
 
 
-        $new['save_traf'] = $_POST["f_save_traf"] * 1;
-        $new['dhcp_acl'] = trim($_POST["f_acl"]);
-        $new['dhcp_option_set'] = trim($_POST["f_dhcp_option_set"]);
-        $new['dynamic'] = trim($_POST["f_dynamic"]);
-        if ($new['dynamic']) { $new['end_life'] =  trim($_POST["f_end_life"]); }
-        if (get_const('default_user_ou_id') == $parent_ou_id or get_const('default_hotspot_ou_id') == $parent_ou_id) {
-            $new['nagios_handler'] = '';
-            $new['enabled'] = 0;
-            $new['link_check'] = 0;
-            $new['nagios'] = 0;
-            $new['blocked'] = 0;
-            $new['day_quota'] = 0;
-            $new['month_quota'] = 0;
-            $new['queue_id'] = 0;
-            $new['filter_group_id'] = 0;
+        // Остальные поля
+        $new['save_traf']         = (int)getPOST("f_save_traf", null, 0);
+        $new['dhcp_acl']          = trim(getPOST("f_acl", null, ''));
+        $new['dhcp_option_set']   = trim(getPOST("f_dhcp_option_set", null, ''));
+        $new['dynamic']           = (int)(getPOST("f_dynamic", null, 0));
+        if ($new['dynamic']) {
+            $new['end_life'] = trim(getPOST("f_end_life", null, ''));
+        }
+
+        // Настройки по OU
+        if (get_const('default_user_ou_id') == $parent_ou_id || get_const('default_hotspot_ou_id') == $parent_ou_id) {
+            $new += [
+                'nagios_handler'    => '',
+                'enabled'           => 0,
+                'link_check'        => 0,
+                'nagios'            => 0,
+                'blocked'           => 0,
+                'day_quota'         => 0,
+                'month_quota'       => 0,
+                'queue_id'          => 0,
+                'filter_group_id'   => 0
+            ];
         } else {
         } else {
-            $new['nagios_handler'] = $_POST["f_handler"];
-            $new['enabled'] = get_int($_POST["f_enabled"]);
-            $new['link_check'] = get_int($_POST["f_link"]);
-            $new['nagios'] = get_int($_POST["f_nagios"]);
-            $new['dhcp'] = $f_dhcp;
-            $new['blocked'] = get_int($_POST["f_blocked"]);
-            $new['day_quota'] = get_int($_POST["f_day_q"]);
-            $new['month_quota'] = get_int($_POST["f_month_q"]);
-            $new['queue_id'] = get_int($_POST["f_queue_id"]);
-            $new['filter_group_id'] = get_int($_POST["f_group_id"]);
+            $new += [
+                'nagios_handler'    => trim(getPOST("f_handler", null, '')),
+                'enabled'           => (int)getPOST("f_enabled", null, 0),
+                'link_check'        => (int)getPOST("f_link", null, 0),
+                'nagios'            => (int)getPOST("f_nagios", null, 0),
+                'dhcp'              => $f_dhcp,
+                'blocked'           => (int)getPOST("f_blocked", null, 0),
+                'day_quota'         => (int)getPOST("f_day_q", null, 0),
+                'month_quota'       => (int)getPOST("f_month_q", null, 0),
+                'queue_id'          => (int)getPOST("f_queue_id", null, 0),
+                'filter_group_id'   => (int)getPOST("f_group_id", null, 0)
+            ];
         }
         }
+
         if ($new['nagios'] == 0) {
         if ($new['nagios'] == 0) {
             $new['nagios_status'] = 'UP';
             $new['nagios_status'] = 'UP';
-            }
-        if (!$user_enabled) { $new['enabled']=0; }
-        $changes = get_diff_rec($db_link, "user_auth", "id=?", $new, 0, [ $id ]);
+        }
+        if (!$user_enabled) {
+            $new['enabled'] = 0;
+        }
+
+        // Применение изменений
+        $changes = get_diff_rec($db_link, "user_auth", "id = ?", $new, 0, [$id]);
         if (!empty($changes)) {
         if (!empty($changes)) {
             LOG_WARNING($db_link, "Changed record for $ip! Log: " . $changes, $id);
             LOG_WARNING($db_link, "Changed record for $ip! Log: " . $changes, $id);
-            }
+        }
+
         if (is_auth_bind_changed($db_link, $id, $ip, $mac)) {
         if (is_auth_bind_changed($db_link, $id, $ip, $mac)) {
             $new_id = copy_auth($db_link, $id, $new);
             $new_id = copy_auth($db_link, $id, $new);
             if (!empty($new_id)) {
             if (!empty($new_id)) {
-                header("Location: /admin/users/editauth.php?id=" . $new_id, TRUE, 302);
-                } else {
-                header("Location: " . $_SERVER["REQUEST_URI"]);
-                }
-            exit;
+                header("Location: /admin/users/editauth.php?id=" . $new_id, true, 302);
             } else {
             } else {
-            update_record($db_link, "user_auth", "id=?", $new, [ $id ]);
+                header("Location: " . $_SERVER["REQUEST_URI"]);
             }
             }
+            exit;
+        } else {
+            update_record($db_link, "user_auth", "id = ?", $new, [$id]);
+        }
     } else {
     } else {
         $msg_error = "$msg_ip_error xxx.xxx.xxx.xxx";
         $msg_error = "$msg_ip_error xxx.xxx.xxx.xxx";
         $_SESSION[$page_url]['msg'] = $msg_error;
         $_SESSION[$page_url]['msg'] = $msg_error;
@@ -178,97 +200,109 @@ if (isset($_POST["editauth"]) and !$old_auth_info['deleted']) {
     exit;
     exit;
 }
 }
 
 
-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 ]);
+// === ПЕРЕМЕЩЕНИЕ ЗАПИСИ =========================================================
+if (getPOST("moveauth") !== null && !$old_auth_info['deleted']) {
+    $new_parent_id = (int)getPOST("f_new_parent", null, 0);
+    $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);
     $changes = apply_auth_rule($db_link, $moved_auth, $new_parent_id);
-    update_record($db_link, "user_auth", "id='$id'", $changes);
+    
+    update_record($db_link, "user_auth", "id = ?", $changes, [$id]);
     LOG_WARNING($db_link, "IP-address moved to another user! Applyed: " . hash_to_text($changes), $id);
     LOG_WARNING($db_link, "IP-address moved to another user! Applyed: " . hash_to_text($changes), $id);
-    run_sql($db_link,"DELETE FROM auth_rules WHERE user_id=".$old_auth_info["user_id"]." AND rule='".$old_auth_info["mac"]."' AND rule_type=2");
-    run_sql($db_link,"DELETE FROM auth_rules WHERE user_id=".$old_auth_info["user_id"]." AND rule='".$old_auth_info["ip"]."' AND rule_type=1");
-    LOG_INFO($db_link,"Autorules removed for user_id: ".$old_auth_info["user_id"]." login: ".$user_info["login"]." by mac and ip");
+    
+    // Удаляем старые правила
+    delete_records($db_link, "auth_rules", "user_id = ? AND rule = ? AND rule_type = 2", [$old_auth_info["user_id"], $old_auth_info["mac"]]);
+    delete_records($db_link, "auth_rules", "user_id = ? AND rule = ? AND rule_type = 1", [$old_auth_info["user_id"], $old_auth_info["ip"]]);
+    
+    LOG_INFO($db_link, "Autorules removed for user_id: " . $old_auth_info["user_id"] . " login: " . $user_info["login"] . " by mac and ip");
     header("Location: " . $_SERVER["REQUEST_URI"]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
     exit;
 }
 }
 
 
-if (isset($_POST["recovery"]) and $old_auth_info['deleted']) {
-    $ip = trim($_POST["f_ip"]);
+// === ВОССТАНОВЛЕНИЕ УДАЛЁННОЙ ЗАПИСИ ===========================================
+if (getPOST("recovery") !== null && $old_auth_info['deleted']) {
+    $ip = trim(getPOST("f_ip", null, ''));
     if (checkValidIp($ip)) {
     if (checkValidIp($ip)) {
         $ip_aton = ip2long($ip);
         $ip_aton = ip2long($ip);
-        $mac = mac_dotted($_POST["f_mac"]);
-        //search mac
+        $mac = mac_dotted(getPOST("f_mac", null, ''));
+        
+        // Проверка MAC
         $mac_exists = find_mac_in_subnet($db_link, $ip, $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=?";
-            $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'];
+        if (!empty($mac_exists) && ($mac_exists['count'] ?? 0) >= 1 && !in_array($parent_id, $mac_exists['users_id'] ?? [])) {
+            $dup_info = get_record_sql($db_link, "SELECT * FROM user_list WHERE id = ?", [$mac_exists['users_id'][0] ?? 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;
             $_SESSION[$page_url]['msg'] = $msg_error;
             LOG_ERROR($db_link, $msg_error);
             LOG_ERROR($db_link, $msg_error);
             header("Location: " . $_SERVER["REQUEST_URI"]);
             header("Location: " . $_SERVER["REQUEST_URI"]);
             exit;
             exit;
         }
         }
-        //disable dhcp for secondary ip
-        $f_dhcp = $_POST["f_dhcp"] * 1;
-        if (in_array($parent_id, $mac_exists['users_id'])) {
-            if ($parent_id != $mac_exists['users_id'][0]) {
+
+        // DHCP для вторичного IP
+        $f_dhcp = (int)getPOST("f_dhcp", null, 0);
+        if (!empty($mac_exists) && in_array($parent_id, $mac_exists['users_id'] ?? [])) {
+            if ($parent_id != ($mac_exists['users_id'][0] ?? null)) {
                 $f_dhcp = 0;
                 $f_dhcp = 0;
             }
             }
         }
         }
-        //search ip
-        $dup_ip_record = get_record_sql($db_link, "SELECT * FROM user_auth WHERE ip_int=? AND id<>? AND deleted=0", [ $ip_aton, $id ]);
+
+        // Проверка дубликата IP
+        $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)) {
         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'];
             $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;
             $_SESSION[$page_url]['msg'] = $msg_error;
             LOG_ERROR($db_link, $msg_error);
             LOG_ERROR($db_link, $msg_error);
             header("Location: " . $_SERVER["REQUEST_URI"]);
             header("Location: " . $_SERVER["REQUEST_URI"]);
             exit;
             exit;
         }
         }
-        $new['deleted'] = 0;
-        $new['dynamic'] = 0;
-        $new['dns_name']='';
 
 
-        $parent_id = $old_auth_info['user_id'];
+        $new = ['deleted' => 0, 'dynamic' => 0, 'dns_name' => ''];
 
 
-        $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)) {
         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']; }
-            if (empty($new_user_id)) { $new_user_id = new_user($db_link, $new_user_info); }
-            $new['user_id'] = $new_user_id;
+            $new_user_info = get_new_user_id($db_link, $ip, $mac, null);
+            $new_user_id = $new_user_info['user_id'] ?? null;
+            if (empty($new_user_id)) {
+                $new_user_id = new_user($db_link, $new_user_info);
             }
             }
+            $new['user_id'] = $new_user_id;
+        }
 
 
-        //save description
-        $new['description']=$old_parent['description'];
-
-        if (get_const('default_user_ou_id') == $parent_ou_id or get_const('default_hotspot_ou_id') == $parent_ou_id) {
-            $new['nagios_handler'] = '';
-            $new['enabled'] = 0;
-            $new['link_check'] = 0;
-            $new['nagios'] = 0;
-            $new['blocked'] = 0;
-            $new['day_quota'] = 0;
-            $new['month_quota'] = 0;
-            $new['queue_id'] = 0;
-            $new['filter_group_id'] = 0;
+        $new['description'] = $old_parent['description'] ?? '';
+
+        // Настройки по OU
+        if (get_const('default_user_ou_id') == $parent_ou_id || get_const('default_hotspot_ou_id') == $parent_ou_id) {
+            $new += [
+                'nagios_handler'    => '',
+                'enabled'           => 0,
+                'link_check'        => 0,
+                'nagios'            => 0,
+                'blocked'           => 0,
+                'day_quota'         => 0,
+                'month_quota'       => 0,
+                'queue_id'          => 0,
+                'filter_group_id'   => 0
+            ];
         } else {
         } else {
-            $new['nagios_handler'] = $_POST["f_handler"];
-            $new['enabled'] = get_int($_POST["f_enabled"]);
-            $new['link_check'] = get_int($_POST["f_link"]);
-            $new['nagios'] = get_int($_POST["f_nagios"]);
-            $new['dhcp'] = get_int($_POST["f_dhcp"]);
-            $new['blocked'] = get_int($_POST["f_blocked"]);
-            $new['day_quota'] = get_int($_POST["f_day_q"]);
-            $new['month_quota'] = get_int($_POST["f_month_q"]);
-            $new['queue_id'] = get_int($_POST["f_queue_id"]);
-            $new['filter_group_id'] = get_int($_POST["f_group_id"]);
+            $new += [
+                'nagios_handler'    => trim(getPOST("f_handler", null, '')),
+                'enabled'           => (int)getPOST("f_enabled", null, 0),
+                'link_check'        => (int)getPOST("f_link", null, 0),
+                'nagios'            => (int)getPOST("f_nagios", null, 0),
+                'dhcp'              => (int)getPOST("f_dhcp", null, 0),
+                'blocked'           => (int)getPOST("f_blocked", null, 0),
+                'day_quota'         => (int)getPOST("f_day_q", null, 0),
+                'month_quota'       => (int)getPOST("f_month_q", null, 0),
+                'queue_id'          => (int)getPOST("f_queue_id", null, 0),
+                'filter_group_id'   => (int)getPOST("f_group_id", null, 0)
+            ];
         }
         }
-        $changes = get_diff_rec($db_link, "user_auth", "id=?", $new, 0, [ $id ]);
+
+        $changes = get_diff_rec($db_link, "user_auth", "id = ?", $new, 0, [$id]);
         if (!empty($changes)) {
         if (!empty($changes)) {
             LOG_WARNING($db_link, "Recovered ip-address. Applyed: $changes", $id);
             LOG_WARNING($db_link, "Recovered ip-address. Applyed: $changes", $id);
         }
         }
         $new = apply_auth_rule($db_link, $new, $new['user_id']);
         $new = apply_auth_rule($db_link, $new, $new['user_id']);
-        update_record($db_link, "user_auth", "id=?", $new, [ $id ]);
+        update_record($db_link, "user_auth", "id = ?", $new, [$id]);
     } else {
     } else {
         $msg_error = "$msg_ip_error xxx.xxx.xxx.xxx/xx";
         $msg_error = "$msg_ip_error xxx.xxx.xxx.xxx/xx";
         $_SESSION[$page_url]['msg'] = $msg_error;
         $_SESSION[$page_url]['msg'] = $msg_error;
@@ -334,7 +368,7 @@ if (empty($auth_info['end_life']) or $auth_info['end_life'] == '0000-00-00 00:00
                 <td></td>
                 <td></td>
             </tr>
             </tr>
             <tr>
             <tr>
-                <td><input type="text" name="f_dns_name" size="14"  value="<?php echo $auth_info['dns_name']; ?>" pattern="^([a-zA-Z0-9-]{1,63})(\.[a-zA-Z0-9-]{1,63})*\.?$">
+                <td style="white-space: nowrap;"><input type="text" name="f_dns_name" size="14"  value="<?php echo $auth_info['dns_name']; ?>" pattern="^([a-zA-Z0-9-]{1,63})(\.[a-zA-Z0-9-]{1,63})*\.?$">
                     <input type="checkbox" id="f_dns_ptr" name="f_dns_ptr" value="1" <?php echo $f_dns_ptr; ?>> &nbsp <?php print WEB_cell_ptr_only; ?>
                     <input type="checkbox" id="f_dns_ptr" name="f_dns_ptr" value="1" <?php echo $f_dns_ptr; ?>> &nbsp <?php print WEB_cell_ptr_only; ?>
                 </td>
                 </td>
                 <td><input type="text" name="f_description" value="<?php echo $auth_info['description']; ?>"></td>
                 <td><input type="text" name="f_description" value="<?php echo $auth_info['description']; ?>"></td>
@@ -415,8 +449,11 @@ if (empty($auth_info['end_life']) or $auth_info['end_life'] == '0000-00-00 00:00
             </tr>
             </tr>
             <tr>
             <tr>
                 <td><?php print WEB_cell_temporary; ?></td>
                 <td><?php print WEB_cell_temporary; ?></td>
-                <?php if ($auth_info['dynamic']) { print "<td class='cell_red'>"; } else { print "<td>"; } ?>
-                <?php print WEB_cell_end_life; ?></td>
+                <?php if ($auth_info['dynamic']) { print "<td>"; } else { print "<td>"; } ?>
+                <div style="color: #7B1FA2;">
+                <?php print WEB_cell_end_life; ?>
+                </div>
+                </td>
                 <td></td>
                 <td></td>
                 <td></td>
                 <td></td>
                 <td></td>
                 <td></td>

+ 213 - 147
html/admin/users/edituser.php

@@ -8,240 +8,306 @@ require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/sortfilter.php");
 
 
 $msg_error = "";
 $msg_error = "";
 
 
-$sSQL = "SELECT * FROM user_list WHERE id=?";
-$user_info = get_record_sql($db_link, $sSQL, [ $id ]);
+$sSQL = "SELECT * FROM user_list WHERE id = ?";
+$user_info = get_record_sql($db_link, $sSQL, [$id]);
 
 
 if (empty($user_info)) {
 if (empty($user_info)) {
     header("Location: /admin/");
     header("Location: /admin/");
+    exit;
 }
 }
 
 
-if (isset($_POST["edituser"])) {
-    unset($new);
-    if ($_POST["f_ou"] >0) {  $new["ou_id"] = $_POST["f_ou"]; }
-    $new["filter_group_id"] = $_POST["f_filter"] * 1;
-    $new["queue_id"] = $_POST["f_queue"] * 1;
-    $user_name = trim($_POST["f_login"]);
-    if (!empty($user_name)) { $new["login"] = $user_name; }
-    $new["fio"] = trim($_POST["f_fio"]);
-    if (get_const('default_user_ou_id') == $new["ou_id"] or get_const('default_hotspot_ou_id') == $new["ou_id"]) {
-        $new["enabled"] = 0;
-        $new["blocked"] = 0;
-        $new["day_quota"] = 0;
-        $new["month_quota"] = 0;
-        $new["permanent"] = 0;
+// === РЕДАКТИРОВАНИЕ ПОЛЬЗОВАТЕЛЯ ===============================================
+if (getPOST("edituser") !== null) {
+    $new = [];
+
+    $f_ou = (int)getPOST("f_ou", null, 0);
+    if ($f_ou > 0) {
+        $new["ou_id"] = $f_ou;
+    }
+
+    $new["filter_group_id"] = (int)getPOST("f_filter", null, 0);
+    $new["queue_id"]         = (int)getPOST("f_queue", null, 0);
+    
+    $user_name = trim(getPOST("f_login", null, $user_info['login']));
+    if ($user_name !== '') {
+        $new["login"] = $user_name;
+    }
+    
+    $new["fio"] = trim(getPOST("f_fio", null, ''));
+
+    // Настройки по OU
+    if (get_const('default_user_ou_id') == ($new["ou_id"] ?? 0) || 
+        get_const('default_hotspot_ou_id') == ($new["ou_id"] ?? 0)) {
+        $new["enabled"]      = 0;
+        $new["blocked"]      = 0;
+        $new["day_quota"]    = 0;
+        $new["month_quota"]  = 0;
+        $new["permanent"]    = 0;
     } else {
     } else {
-        $new["enabled"] = get_int($_POST["f_enabled"]);
-        $new["blocked"] = get_int($_POST["f_blocked"]);
-        $new["day_quota"] = get_int(trim($_POST["f_perday"]));
-        $new["month_quota"] = get_int(trim($_POST["f_permonth"]));
-        $new["permanent"] = $_POST["f_permanent"] * 1;
+        $new["enabled"]      = (int)getPOST("f_enabled", null, 0);
+        $new["blocked"]      = (int)getPOST("f_blocked", null, 0);
+        $new["day_quota"]    = (int)trim(getPOST("f_perday", null, 0));
+        $new["month_quota"]  = (int)trim(getPOST("f_permonth", null, 0));
+        $new["permanent"]    = (int)getPOST("f_permanent", null, 0);
     }
     }
-    $changes = get_diff_rec($db_link, "user_list", "id=?", $new, 0, [ $id ]);
+
+    $changes = get_diff_rec($db_link, "user_list", "id = ?", $new, 0, [$id]);
     if (!empty($changes)) {
     if (!empty($changes)) {
-        LOG_WARNING($db_link, "Changed user id: $id login: " . $new["login"] . ". \r\nApply: $changes");
+        LOG_WARNING($db_link, "Changed user id: $id login: " . ($new["login"] ?? '') . ". \r\nApply: $changes");
     }
     }
-    update_record($db_link, "user_list", "id=?", $new, [ $id ]);
+    update_record($db_link, "user_list", "id = ?", $new, [$id]);
+
+    // Отключаем авторизацию, если пользователь выключен
     if (!$new["enabled"]) {
     if (!$new["enabled"]) {
-        update_record($db_link, 'user_auth', 'user_id = ?', [ 'enabled' => 0,'changed' => 1 ], [ $id ]);
+        update_records($db_link, 'user_auth', 'user_id = ?', ['enabled' => 0, 'changed' => 1], [$id]);
     }
     }
+
+    // Обновляем описание в user_auth
     if (!empty($new["fio"])) {
     if (!empty($new["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"] ]);
+        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"]]
+        );
     }
     }
+
     // Обновление ou_id в user_auth
     // Обновление ou_id в user_auth
-    update_records($db_link, 'user_auth', 'user_id = ? AND deleted=0', [ 'ou_id' => $new["ou_id"] ], [ $id ]);
+    update_records($db_link, 'user_auth', 'user_id = ? AND deleted = 0', ['ou_id' => $new["ou_id"]], [$id]);
+
     // Обновление device_name в devices
     // Обновление device_name в devices
-    update_record($db_link, 'devices', 'user_id = ?', [ 'device_name' => $new["login"] ], [ $id ]);
+    update_record($db_link, 'devices', 'user_id = ?', ['device_name' => $new["login"]], [$id]);
+
     header("Location: " . $_SERVER["REQUEST_URI"]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
     exit;
 }
 }
 
 
-if (isset($_POST["addMacRule"])) {
-    unset($new);
-    $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 ]);
+// === АВТОПРАВИЛА ПО MAC =========================================================
+if (getPOST("addMacRule") !== null) {
+    $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) {
     foreach ($first_auth as $row) {
-        if (!empty($row['mac'])) { add_auth_rule($db_link, $row['mac'], 2, $id); }
+        if (!empty($row['mac'])) {
+            add_auth_rule($db_link, $row['mac'], 2, $id);
         }
         }
+    }
     header("Location: " . $_SERVER["REQUEST_URI"]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
     exit;
 }
 }
 
 
-if (isset($_POST["delMacRule"])) {
-    run_sql($db_link, "DELETE FROM auth_rules WHERE user_id=? AND rule_type=2", [ $id ]);
+if (getPOST("delMacRule") !== null) {
+    delete_records($db_link, "auth_rules", "user_id = ? AND rule_type = 2", [$id]);
     LOG_INFO($db_link, "All autorules removed for id: $id login: " . $user_info["login"] . " by mac");
     LOG_INFO($db_link, "All autorules removed for id: $id login: " . $user_info["login"] . " by mac");
     header("Location: " . $_SERVER["REQUEST_URI"]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
     exit;
 }
 }
 
 
-if (isset($_POST["addIPRule"])) {
-    unset($new);
-    $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]);
+// === АВТОПРАВИЛА ПО IP ==========================================================
+if (getPOST("addIPRule") !== null) {
+    $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) {
     foreach ($first_auth as $row) {
-        if (!empty($row['ip'])) { add_auth_rule($db_link, $row['ip'], 1, $id); }
+        if (!empty($row['ip'])) {
+            add_auth_rule($db_link, $row['ip'], 1, $id);
         }
         }
+    }
     header("Location: " . $_SERVER["REQUEST_URI"]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
     exit;
 }
 }
 
 
-if (isset($_POST["delIPRule"])) {
-    run_sql($db_link, "DELETE FROM auth_rules WHERE user_id=? AND rule_type=1", [ $id ]);
+if (getPOST("delIPRule") !== null) {
+    delete_records($db_link, "auth_rules", "user_id = ? AND rule_type = 1", [$id]);
     LOG_INFO($db_link, "Removed all auto rules for id: $id login: " . $user_info["login"] . " by ip");
     LOG_INFO($db_link, "Removed all auto rules for id: $id login: " . $user_info["login"] . " by ip");
     header("Location: " . $_SERVER["REQUEST_URI"]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
     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]);
-    if (empty($device) and !empty($auth)) {
-        $new['user_id'] = $id;
-        $new['device_name'] = $user_info['login'];
-        $new['device_type'] = 5;
-        $new['ip'] = $auth['ip'];
-        $new['ip_int'] = $auth['ip_int'];
-        $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);
+// === СОЗДАНИЕ УСТРОЙСТВА ========================================================
+if (getPOST("showDevice") !== null) {
+    $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) && !empty($auth)) {
+        $new = [
+            'user_id'          => $id,
+            'device_name'      => $user_info['login'],
+            'device_type'      => 5,
+            'ip'               => $auth['ip'],
+            'ip_int'           => $auth['ip_int'],
+            '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);
         $new_id = insert_record($db_link, "devices", $new);
-        unset($_POST);
         if (!empty($new_id)) {
         if (!empty($new_id)) {
             LOG_INFO($db_link, "Created device with id: $new_id for auth_id: $id");
             LOG_INFO($db_link, "Created device with id: $new_id for auth_id: $id");
             header("Location: /admin/devices/editdevice.php?id={$new_id}");
             header("Location: /admin/devices/editdevice.php?id={$new_id}");
             exit;
             exit;
-        } else {
-            header("Location: " . $_SERVER["REQUEST_URI"]);
-            exit;
         }
         }
     }
     }
-    header("Location: /admin/devices/editdevice.php?id=" . $device['id']);
+
+    if (!empty($device['id'])) {
+        header("Location: /admin/devices/editdevice.php?id=" . $device['id']);
+    } else {
+        header("Location: " . $_SERVER["REQUEST_URI"]);
+    }
     exit;
     exit;
 }
 }
 
 
-if (isset($_POST["addauth"])) {
-    $fip = normalizeIpAddress(substr(trim($_POST["newip"]), 0, 18));
-    $fdescription = NULL;
-    $fmac = trim($_POST["newmac"]);
+// === ДОБАВЛЕНИЕ ЗАПИСИ АВТОРИЗАЦИИ ==============================================
+if (getPOST("addauth") !== null) {
+    $fip = normalizeIpAddress(substr(trim(getPOST("newip", null, '')), 0, 18));
+    $fdescription = null;
+    $fmac = trim(getPOST("newmac", null, ''));
+
     if (!empty($fmac)) {
     if (!empty($fmac)) {
         if (!checkValidMac($fmac)) {
         if (!checkValidMac($fmac)) {
-                $fdescription = $fmac;
-                $fmac=NULL;
-            } else {
+            $fdescription = $fmac;
+            $fmac = null;
+        } else {
             $fmac = mac_dotted($fmac);
             $fmac = mac_dotted($fmac);
-            }
         }
         }
+    }
+
     if (!empty($fip)) {
     if (!empty($fip)) {
-            $ip_aton = ip2long($fip);
-            $f_dhcp = 1;
-            //search mac
-            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=?";
-                    $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);
-                    header("Location: " . $_SERVER["REQUEST_URI"]);
-                    exit;
-                }
-                //disable dhcp for secondary ip
-                if (empty($mac_exists)) {
-                    $f_dhcp = 1;
-                } else {
-                    if (in_array($id, $mac_exists['users_id'])) {
-                        $f_dhcp = 0;
-                    }
-                }
-            }
-            //search ip
-            $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'] ]);
-                $msg_error = "$fip already exists. Skip creating $fip [$fmac].<br>Old user id: " . $dup_info['id'] . " login: " . $dup_info['login'];
+        $ip_aton = ip2long($fip);
+        $f_dhcp = 1;
+
+        // Проверка MAC
+        if (!empty($fmac)) {
+            $mac_exists = find_mac_in_subnet($db_link, $fip, $fmac);
+            if (!empty($mac_exists) && ($mac_exists['count'] ?? 0) >= 1 && !in_array($id, $mac_exists['users_id'] ?? [])) {
+                $dup_info = get_record_sql($db_link, "SELECT * FROM user_list WHERE id = ?", [$mac_exists['users_id'][0] ?? 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;
                 $_SESSION[$page_url]['msg'] = $msg_error;
                 LOG_ERROR($db_link, $msg_error);
                 LOG_ERROR($db_link, $msg_error);
                 header("Location: " . $_SERVER["REQUEST_URI"]);
                 header("Location: " . $_SERVER["REQUEST_URI"]);
                 exit;
                 exit;
             }
             }
-            $fid = new_auth($db_link, $fip, $fmac, $id);
-            if (!empty($fid)) {
-                $new['dhcp'] = $f_dhcp;
-                $new['created_by'] = 'manual';
-                if (!empty($fdescription)) { $new['description'] = $fdescription; }
-                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;
+
+            // DHCP для вторичного IP
+            if (!empty($mac_exists) && in_array($id, $mac_exists['users_id'] ?? [])) {
+                $f_dhcp = 0;
             }
             }
+        }
+
+        // Проверка дубликата IP
+        $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']]);
+            $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);
             header("Location: " . $_SERVER["REQUEST_URI"]);
             header("Location: " . $_SERVER["REQUEST_URI"]);
             exit;
             exit;
-        } else {
-            $msg_error = "IP-address fromat eror!";
-            $_SESSION[$page_url]['msg'] = $msg_error;
         }
         }
+
+        $fid = new_auth($db_link, $fip, $fmac, $id);
+        if (!empty($fid)) {
+            $new_auth = ['dhcp' => $f_dhcp, 'created_by' => 'manual'];
+            if (!empty($fdescription)) {
+                $new_auth['description'] = $fdescription;
+            }
+            update_record($db_link, "user_auth", "id = ?", $new_auth, [$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;
+        }
+    } else {
+        $msg_error = "IP-address format error!";
+        $_SESSION[$page_url]['msg'] = $msg_error;
+    }
+
     header("Location: " . $_SERVER["REQUEST_URI"]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
     exit;
-    }
+}
 
 
-if (isset($_POST["removeauth"])) {
-    $auth_id = $_POST["f_auth_id"];
-    foreach ($auth_id as $key => $val) {
-        if ($val) { delete_user_auth($db_link, $val); }
+// === УДАЛЕНИЕ ЗАПИСЕЙ АВТОРИЗАЦИИ ==============================================
+if (getPOST("removeauth") !== null) {
+    $auth_id = getPOST("f_auth_id", null, []);
+    if (!empty($auth_id) && is_array($auth_id)) {
+        foreach ($auth_id as $val) {
+            $val = trim($val);
+            if ($val !== '') {
+                delete_user_auth($db_link, (int)$val);
+            }
+        }
     }
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
     exit;
 }
 }
 
 
-if (isset($_POST["new_user"])) {
-    $auth_id = $_POST["f_auth_id"];
-    $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 ]);
+// === СОЗДАНИЕ НОВОГО ПОЛЬЗОВАТЕЛЯ ИЗ ЗАПИСИ АВТОРИЗАЦИИ =========================
+if (getPOST("new_user") !== null) {
+    $auth_id = getPOST("f_auth_id", null, []);
+    $save_traf = (int)get_option($db_link, 23);
+
+    if (!empty($auth_id) && is_array($auth_id)) {
+        foreach ($auth_id as $val) {
+            $val = (int)$val;
+            if ($val <= 0) continue;
+
+            $auth_info = get_record_sql($db_link, "SELECT * FROM user_auth WHERE id = ?", [$val]);
+            if (empty($auth_info)) continue;
+
             $ou_id = $user_info["ou_id"];
             $ou_id = $user_info["ou_id"];
-            $login = NULL;
+            $login = null;
+
             if (!empty($auth_info["dns_name"])) {
             if (!empty($auth_info["dns_name"])) {
                 $login = $auth_info["dns_name"];
                 $login = $auth_info["dns_name"];
-            }
-            if (empty($login) and !empty($auth_info["description"])) {
+            } elseif (!empty($auth_info["description"])) {
                 $login = transliterate($auth_info["description"]);
                 $login = transliterate($auth_info["description"]);
-            }
-            if (empty($login) and !empty($auth_info["dhcp_hostname"])) {
+            } elseif (!empty($auth_info["dhcp_hostname"])) {
                 $login = $auth_info["dhcp_hostname"];
                 $login = $auth_info["dhcp_hostname"];
-            }
-            if (empty($login) and !empty($auth_info["mac"])) {
+            } elseif (!empty($auth_info["mac"])) {
                 $login = $auth_info["mac"];
                 $login = $auth_info["mac"];
-            }
-            if (empty($login)) {
+            } else {
                 $login = $auth_info["ip"];
                 $login = $auth_info["ip"];
             }
             }
-	    $new_user = get_record_sql($db_link, "SELECT * FROM user_list WHERE LOWER(login) = LOWER(?) AND deleted = 0", [$login]);
+
+            $new_user = get_record_sql($db_link, "SELECT * FROM user_list WHERE LOWER(login) = LOWER(?) AND deleted = 0", [$login]);
             if (!empty($new_user)) {
             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=?", $auth,  [ $val ]);
+                // Перенос записи авторизации
+                $auth_update = [
+                    'user_id' => $new_user["id"],
+                    'ou_id'   => $new_user["ou_id"],
+                    'save_traf' => $save_traf
+                ];
+                $auth_update = apply_auth_rule($db_link, $auth_update, $new_user["id"]);
+                update_record($db_link, "user_auth", "id = ?", $auth_update, [$val]);
                 LOG_WARNING($db_link, "ip from id: $val moved to another user user_id: " . $new_user["id"], $val);
                 LOG_WARNING($db_link, "ip from id: $val moved to another user user_id: " . $new_user["id"], $val);
             } else {
             } else {
-                $new["login"] = $login;
-                $new["ou_id"] = $ou_id;
-                if (!empty($auth_info["description"])) { $new["fio"] = $auth_info["description"]; }
-                if (!isset($new["fio"]) and !empty($auth_info["dns_name"])) { $new["fio"] = $auth_info["dns_name"]; }
-                if (!isset($new["fio"]) and !empty($auth_info["dhcp_hostname"])) { $new["fio"] = $auth_info["dhcp_hostname"]; }
-                $new["enabled"] = $auth_info["enabled"];
-                $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=?", $auth, [ $val ]);
-                LOG_WARNING($db_link, "Create user from ip: login => $login. ip-record auth_id: $val moved to this user.", $val);
+                $new_user_data = [
+                    'login' => $login,
+                    'ou_id' => $ou_id
+                ];
+                if (!empty($auth_info["description"])) {
+                    $new_user_data["fio"] = $auth_info["description"];
+                } elseif (!empty($auth_info["dns_name"])) {
+                    $new_user_data["fio"] = $auth_info["dns_name"];
+                } elseif (!empty($auth_info["dhcp_hostname"])) {
+                    $new_user_data["fio"] = $auth_info["dhcp_hostname"];
+                }
+
+                $new_user_data["enabled"] = $auth_info["enabled"];
+                $l_id = insert_record($db_link, "user_list", $new_user_data);
+
+                if (!empty($l_id)) {
+                    $auth_update = ['user_id' => $l_id, 'save_traf' => $save_traf];
+                    update_record($db_link, "user_auth", "id = ?", $auth_update, [$val]);
+                    LOG_WARNING($db_link, "Create user from ip: login => $login. ip-record auth_id: $val moved to this user.", $val);
+                }
             }
             }
         }
         }
     }
     }
+
     header("Location: " . $_SERVER["REQUEST_URI"]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
     exit;
 }
 }

+ 39 - 25
html/admin/users/index.php

@@ -9,36 +9,50 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/sortfilter.php");
 
 
 $msg_error = "";
 $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 ]);
+if (getPOST("create") !== null) {
+    $login = trim(getPOST("newlogin", null, ''));
+    
+    if ($login !== '') {
+        // Проверка существования логина
+        $lcount = get_count_records($db_link, "user_list", "LOWER(login) = LOWER(?)", [$login]);
+        
         if ($lcount > 0) {
         if ($lcount > 0) {
-            $msg_error = WEB_cell_login." ".$login." ".$msg_exists."!";
-            unset($_POST);
+            $msg_error = WEB_cell_login . " " . $login . " " . $msg_exists . "!";
         } else {
         } else {
-            $new['login'] = $login;
-            if ($rou>0) { $new['ou_id'] = $rou; } else {
-                $row = 3; //User OU
-                $ou_exists = get_record_sql($db_link,"SELECT id FROM ou WHERE id=?", [ $rou ]);
-                if (empty($ou_exists)) { $row = $default_user_ou_id; }
-                $new['ou_id'] = $row;
+            $new = ['login' => $login];
+            // Определение OU
+            if ($rou > 0) {
+                $new['ou_id'] = $rou;
+            } else {
+                $rou = 3;
+                $ou_exists = get_record_sql($db_link, "SELECT id FROM ou WHERE id = ?", [$rou]);
+                if (empty($ou_exists)) {
+                    $new['ou_id'] = $default_user_ou_id; // по умолчанию
+                } else {
+                    $new['ou_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; }
-		if (empty($ou_info['filter_group_id'])) { $ou_info['filter_group_id'] = 0; }
-	        $new['enabled'] = $ou_info['enabled'];
-	        $new['queue_id'] = $ou_info['queue_id'];
-	        $new['filter_group_id'] = $ou_info['filter_group_id'];
-	        }
-            $lid=insert_record($db_link, "user_list", $new);
-            LOG_WARNING($db_link,"Создан новый пользователь: Login => $login");
-            header("Location: edituser.php?id=$lid");
-            exit;
+            }
+            // Наследование настроек от OU
+            $ou_info = get_record_sql($db_link, "SELECT * FROM ou WHERE id = ?", [$new['ou_id']]);
+            if (!empty($ou_info)) {
+                $new['enabled']           = isset($ou_info['enabled']) ? (int)$ou_info['enabled'] : 0;
+                $new['queue_id']          = isset($ou_info['queue_id']) ? (int)$ou_info['queue_id'] : 0;
+                $new['filter_group_id']   = isset($ou_info['filter_group_id']) ? (int)$ou_info['filter_group_id'] : 0;
+            } else {
+                // Если OU не найден — значения по умолчанию
+                $new['enabled']           = 0;
+                $new['queue_id']          = 0;
+                $new['filter_group_id']   = 0;
+            }
+            $lid = insert_record($db_link, "user_list", $new);
+            LOG_WARNING($db_link, "Создан новый пользователь: Login => $login");
+            if (!empty($lid)) {
+                header("Location: edituser.php?id=$lid");
+                exit;
+            }
         }
         }
     }
     }
+    
     header("Location: " . $_SERVER["REQUEST_URI"]);
     header("Location: " . $_SERVER["REQUEST_URI"]);
     exit;
     exit;
 }
 }