Przeglądaj źródła

draft: backend sql queries have been rewritten to work using parameters

Dmitriev Roman 3 miesięcy temu
rodzic
commit
1ca878a8a5

+ 23 - 17
scripts/check_dhcp_pool.pl

@@ -46,27 +46,33 @@ my $dhcp_networks = new Net::Patricia;
 
 my @subnets=get_records_sql($dbh,'SELECT * FROM subnets WHERE dhcp=1 and office=1 and vpn=0 and hotspot=0 ORDER BY ip_int_start');
 foreach my $subnet (@subnets) {
-next if (!$subnet->{gateway});
-my $subnet_name = $subnet->{subnet};
-$subnet_name=~s/\/\d+$//g;
-$dhcp_networks->add_string($subnet->{subnet},$subnet_name);
-$dhcp_conf{$subnet_name}->{first_ip}=IpToStr($subnet->{dhcp_start});
-$dhcp_conf{$subnet_name}->{last_ip}=IpToStr($subnet->{dhcp_stop});
-$dhcp_conf{$subnet_name}->{first_ip_aton}=$subnet->{dhcp_start};
-$dhcp_conf{$subnet_name}->{last_ip_aton}=$subnet->{dhcp_stop};
-$dhcp_conf{$subnet_name}->{dhcp_pool_size}=$subnet->{dhcp_stop}-$subnet->{dhcp_start};
+    next if (!$subnet->{gateway});
+    my $subnet_name = $subnet->{subnet};
+    $subnet_name=~s/\/\d+$//g;
+    $dhcp_networks->add_string($subnet->{subnet},$subnet_name);
+    $dhcp_conf{$subnet_name}->{first_ip}=IpToStr($subnet->{dhcp_start});
+    $dhcp_conf{$subnet_name}->{last_ip}=IpToStr($subnet->{dhcp_stop});
+    $dhcp_conf{$subnet_name}->{first_ip_aton}=$subnet->{dhcp_start};
+    $dhcp_conf{$subnet_name}->{last_ip_aton}=$subnet->{dhcp_stop};
+    $dhcp_conf{$subnet_name}->{dhcp_pool_size}=$subnet->{dhcp_stop}-$subnet->{dhcp_start};
 }
 
 #get userid list
-my $sSQL="SELECT id,ip,ip_int,mac,description,dns_name FROM user_auth where dhcp=1 and deleted=0 and ou_id<>$default_hotspot_ou_id and ou_id<>$default_user_ou_id ORDER by ip_int";
-my @users = get_records_sql($dbh,$sSQL);
+my $sSQL = "SELECT id, ip, ip_int, mac, description, dns_name 
+           FROM user_auth 
+           WHERE dhcp = 1 
+             AND deleted = 0 
+             AND ou_id NOT IN (?, ?)
+           ORDER BY ip_int";
+my @users = get_records_sql($dbh, $sSQL, $default_hotspot_ou_id, $default_user_ou_id);
+
 foreach my $row (@users) {
-next if (!$row);
-next if (!$dhcp_networks->match_string($row->{ip}));
-next if (!$row->{mac});
-next if (!$row->{ip});
-my $subnet_name = $dhcp_networks->match_string($row->{ip});
-if (in_array([$dhcp_conf{$subnet_name}->{first_ip_aton} .. $dhcp_conf{$subnet_name}->{last_ip_aton}],$row->{ip_int})) { $dhcp_conf{$subnet_name}->{dhcp_pool_size}--; }
+    next if (!$row);
+    next if (!$dhcp_networks->match_string($row->{ip}));
+    next if (!$row->{mac});
+    next if (!$row->{ip});
+    my $subnet_name = $dhcp_networks->match_string($row->{ip});
+    if (in_array([$dhcp_conf{$subnet_name}->{first_ip_aton} .. $dhcp_conf{$subnet_name}->{last_ip_aton}],$row->{ip_int})) { $dhcp_conf{$subnet_name}->{dhcp_pool_size}--; }
 }
 
 my @warning=();

+ 11 - 18
scripts/dhcp-log.pl

@@ -209,14 +209,11 @@ sub run {
                         $t_remote_id = $decoded_remote_id;
                         $t_remote_id .= "0" x (12 - length($t_remote_id)) if length($t_remote_id) < 12;
                         $t_remote_id = mac_splitted(isc_mac_simplify($t_remote_id));
-
                         my $devSQL = "SELECT D.id, D.device_name, D.ip, A.mac " .
                                      "FROM devices AS D, user_auth AS A " .
                                      "WHERE D.user_id = A.User_id AND D.ip = A.ip AND A.deleted = 0 " .
-                                     "AND A.mac = '$t_remote_id'";
-                        log_debug("SQL (по decoded_remote_id): $devSQL");
-                        $switch = get_record_sql($hdb, $devSQL);
-
+                                     "AND A.mac = ?";
+                        $switch = get_record_sql($hdb, $devSQL, $t_remote_id);
                         if ($switch) {
                             $remote_id = $t_remote_id;
                             $circuit_id = $decoded_circuit_id;
@@ -231,14 +228,11 @@ sub run {
                         $t_remote_id = $remote_id;
                         $t_remote_id .= "0" x (12 - length($t_remote_id)) if length($t_remote_id) < 12;
                         $t_remote_id = mac_splitted(isc_mac_simplify($t_remote_id));
-
                         my $devSQL = "SELECT D.id, D.device_name, D.ip, A.mac " .
                                      "FROM devices AS D, user_auth AS A " .
                                      "WHERE D.user_id = A.User_id AND D.ip = A.ip AND A.deleted = 0 " .
-                                     "AND A.mac = '$t_remote_id'";
-                        log_debug("SQL (по remote_id): $devSQL");
-                        $switch = get_record_sql($hdb, $devSQL);
-
+                                     "AND A.mac = ?";
+                        $switch = get_record_sql($hdb, $devSQL, $t_remote_id);
                         if ($switch) {
                             $remote_id = $t_remote_id;
                             $dhcp_record->{circuit_id} = $circuit_id;
@@ -254,9 +248,8 @@ sub run {
                             my $devSQL = "SELECT D.id, D.device_name, D.ip, A.mac " .
                                          "FROM devices AS D, user_auth AS A " .
                                          "WHERE D.user_id = A.User_id AND D.ip = A.ip AND A.deleted = 0 " .
-                                         "AND D.device_name LIKE '$id_words[0]%'";
-                            log_debug("SQL (по имени устройства из remote_id): $devSQL");
-                            $switch = get_record_sql($hdb, $devSQL);
+                                         "AND D.device_name LIKE ?";
+                            $switch = get_record_sql($hdb, $devSQL, $id_words[0] . '%');
                             if ($switch) {
                                 log_debug("Коммутатор найден по имени: " . $switch->{device_name});
                             }
@@ -270,9 +263,8 @@ sub run {
                             my $devSQL = "SELECT D.id, D.device_name, D.ip, A.mac " .
                                          "FROM devices AS D, user_auth AS A " .
                                          "WHERE D.user_id = A.User_id AND D.ip = A.ip AND A.deleted = 0 " .
-                                         "AND D.device_name LIKE '$id_words[0]%'";
-                            log_debug("SQL (по имени из circuit_id — MikroTik?): $devSQL");
-                            $switch = get_record_sql($hdb, $devSQL);
+                                         "AND D.device_name LIKE ?";
+                            $switch = get_record_sql($hdb, $devSQL, $id_words[0] . '%');
                             if ($switch) {
                                 # MikroTik часто путает remote-id и circuit-id — меняем местами
                                 ($circuit_id, $remote_id) = ($remote_id, $t_circuit_id);
@@ -289,7 +281,8 @@ sub run {
                         $t_circuit_id =~ s/[\+\-\s]+/ /g;
 
                         # Загружаем порты коммутатора
-                        my @device_ports = get_records_sql($hdb, "SELECT * FROM device_ports WHERE device_id = " . $switch->{id});
+                        my @device_ports = get_records_sql($hdb, "SELECT * FROM device_ports WHERE device_id = ?", $switch->{id});
+
                         my %device_ports_h;
                         foreach my $port_data (@device_ports) {
                             $port_data->{snmp_index} //= $port_data->{port};
@@ -321,7 +314,7 @@ sub run {
                             db_log_verbose($hdb, "DHCP $type: IP=$ip, MAC=$mac " . $switch->{device_name} . " / " . $switch_port->{ifName});
 
                             # Проверяем, существует ли уже соединение
-                            my $connection = get_records_sql($hdb, "SELECT * FROM connections WHERE auth_id = $auth_id");
+                            my $connection = get_records_sql($hdb, "SELECT * FROM connections WHERE auth_id = ?", $auth_id);
                             if (!$connection || !@{$connection}) {
                                 my $new_connection = {
                                     port_id    => $switch_port->{id},

+ 51 - 18
scripts/eye-statd.pl

@@ -758,12 +758,16 @@ undef %saved_netflow;
 #save statistics
 
 #start stat time
-my $hour_date1 = $hdb->quote(sprintf "%04d-%02d-%02d %02d:00:00",$year+1900,$month+1,$day,$hour);
+my $hour_date1 = sprintf "%04d-%02d-%02d %02d:00:00",$year+1900,$month+1,$day,$hour;
 #end hour
 ($hour,$day,$month,$year) = (localtime($last_time+3600))[2,3,4,5];
-my $hour_date2 = $hdb->quote(sprintf "%04d-%02d-%02d %02d:00:00",$year+1900,$month+1,$day,$hour);
+my $hour_date2 = sprintf "%04d-%02d-%02d %02d:00:00",$year+1900,$month+1,$day,$hour;
 
-my @batch_sql_traf=();
+my @batch_user_stats=();
+my @batch_user_stats_update=();
+my @batch_user_stats_full=();
+my @batch_auth_status=();
+my @batch_wan_stats=();
 
 #log_debug("User STATS: ".Dumper(\%user_stats));
 
@@ -776,11 +780,10 @@ foreach my $user_ip (keys %user_stats) {
     #last flow for user
     my ($sec,$min,$hour,$day,$month,$year) = (localtime($user_stats{$user_ip}{last_found}))[0,1,2,3,4,5];
     #flow time string
-    my $flow_date = $hdb->quote(sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year+1900,$month+1,$day,$hour,$min,$sec);
+    my $flow_date = sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year+1900,$month+1,$day,$hour,$min,$sec;
 
     #last found timestamp
-    my $tSQL="UPDATE user_auth SET last_found=$flow_date WHERE id='$auth_id'";
-    push (@batch_sql_traf,$tSQL);
+    push @batch_auth_status, [ $flow_date, $flow_date, $auth_id ];
 
     #per router stats
     foreach my $router_id (keys %routers_found) {
@@ -793,23 +796,33 @@ foreach my $user_ip (keys %user_stats) {
 	if (!exists $user_stats{$user_ip}{$router_id}{pkt_in})  { $user_stats{$user_ip}{$router_id}{pkt_in} = 0; }
 	if (!exists $user_stats{$user_ip}{$router_id}{pkt_out}) { $user_stats{$user_ip}{$router_id}{pkt_out} = 0; }
 	#current stats
-	my $tSQL="INSERT INTO user_stats_full (ts,auth_id,router_id,byte_in,byte_out,pkt_in,pkt_out,step) VALUES($flow_date,'$auth_id','$router_id','$user_stats{$user_ip}{$router_id}{in}','$user_stats{$user_ip}{$router_id}{out}','$user_stats{$user_ip}{$router_id}{pkt_in}','$user_stats{$user_ip}{$router_id}{pkt_out}','$timeshift')";
-	push (@batch_sql_traf,$tSQL);
+        push @batch_user_stats_full, [
+    	    $flow_date, 
+    	    $auth_id, 
+    	    $router_id, 
+    	    $user_stats{$user_ip}{$router_id}{in}, 
+    	    $user_stats{$user_ip}{$router_id}{out}, 
+    	    $user_stats{$user_ip}{$router_id}{pkt_in}, 
+    	    $user_stats{$user_ip}{$router_id}{pkt_out}, 
+    	    $timeshift ];
 	#hour stats
 	# get current stats
-	my $sql = "SELECT id, byte_in, byte_out FROM user_stats WHERE ts>=$hour_date1 AND ts<$hour_date2 AND router_id=$router_id AND auth_id=$auth_id";
-	my $hour_stat = get_record_sql($hdb,$sql);
+	my $sql = "SELECT id, byte_in, byte_out FROM user_stats WHERE ts >= ? AND ts < ? AND router_id = ? AND auth_id = ?";
+	my $hour_stat = get_record_sql($hdb, $sql, 
+	    $hour_date1,
+	    $hour_date2,
+	    $router_id,
+	    $auth_id
+	    );
 	if (!$hour_stat) {
-	    my $dSQL="INSERT INTO user_stats (ts,auth_id,router_id,byte_in,byte_out) VALUES($flow_date,'$auth_id','$router_id','$user_stats{$user_ip}{$router_id}{in}','$user_stats{$user_ip}{$router_id}{out}')";
-	    push (@batch_sql_traf,$dSQL);
+            push @batch_user_stats, [ $flow_date, $auth_id, $router_id, $user_stats{$user_ip}{$router_id}{in}, $user_stats{$user_ip}{$router_id}{out} ];
 	    next;
 	    }
 	if (!$hour_stat->{byte_in}) { $hour_stat->{byte_in}=0; }
 	if (!$hour_stat->{byte_out}) { $hour_stat->{byte_out}=0; }
 	$hour_stat->{byte_in} += $user_stats{$user_ip}{$router_id}{in};
 	$hour_stat->{byte_out} += $user_stats{$user_ip}{$router_id}{out};
-	$tSQL="UPDATE user_stats SET byte_in='".$hour_stat->{byte_in}."', byte_out='".$hour_stat->{byte_out}."' WHERE id='".$auth_id."' AND router_id='".$router_id."'";
-	push (@batch_sql_traf,$tSQL);
+        push @batch_user_stats_update, [ $hour_stat->{byte_in}, $hour_stat->{byte_out}, $auth_id, $router_id ];
 	}
     }
 
@@ -829,14 +842,34 @@ foreach my $router_id (keys %wan_stats) {
 	if (!$wan_stats{$router_id}{$int_id}{forward_out})  { $wan_stats{$router_id}{$int_id}{forward_out} = 0; }
 	#skip empty stats
         if ($wan_stats{$router_id}{$int_id}{in} + $wan_stats{$router_id}{$int_id}{out} + $wan_stats{$router_id}{$int_id}{forward_in} + $wan_stats{$router_id}{$int_id}{forward_out} ==0) { next; }
-	#current stats
-	my $tSQL="INSERT INTO wan_stats (ts,router_id,interface_id,bytes_in,bytes_out,forward_in,forward_out) VALUES($flow_date,'$router_id','$int_id','$wan_stats{$router_id}{$int_id}{in}','$wan_stats{$router_id}{$int_id}{out}','$wan_stats{$router_id}{$int_id}{forward_in}','$wan_stats{$router_id}{$int_id}{forward_out}')";
-	push (@batch_sql_traf,$tSQL);
+	#current wan stats
+	push @batch_wan_stats, [
+            $flow_date,
+            $router_id,
+            $int_id,
+            $wan_stats{$router_id}{$int_id}{in},
+            $wan_stats{$router_id}{$int_id}{out},
+            $wan_stats{$router_id}{$int_id}{forward_in},
+            $wan_stats{$router_id}{$int_id}{forward_out}
+        ];
 	}
     }
 
+my $tSQL="UPDATE user_auth SET arp_found= ?, last_found= ? WHERE id= ?";
+batch_db_sql_cached($tSQL,\@batch_auth_status);
+
+$tSQL="INSERT INTO user_stats_full (ts,auth_id,router_id,byte_in,byte_out,pkt_in,pkt_out,step) VALUES( ?, ?, ?, ?, ?, ?, ?, ?)";
+batch_db_sql_cached($tSQL,\@batch_user_stats_full);
+
+my $dSQL="INSERT INTO user_stats (ts,auth_id,router_id,byte_in,byte_out)  VALUES( ?, ?, ?, ?, ?, ?)";
+batch_db_sql_cached($tSQL,\@batch_user_stats);
+
+$tSQL="UPDATE user_stats SET byte_in= ?, byte_out= ? WHERE id= ? AND router_id= ?";
+batch_db_sql_cached($tSQL,\@batch_user_stats_update);
+
 #update statistics in DB
-batch_db_sql($hdb,\@batch_sql_traf);
+my $tSQL="INSERT INTO wan_stats (ts,router_id,interface_id,bytes_in,bytes_out,forward_in,forward_out) VALUES( ?, ?, ?, ?, ?, ?, ?)";
+batch_db_sql_cached($tSQL,\@batch_wan_stats);
 
 @batch_sql_traf = ();
 

Plik diff jest za duży
+ 402 - 560
scripts/eyelib/database.pm


+ 19 - 17
scripts/fetch_new_arp.pl

@@ -46,8 +46,8 @@ if ($config_ref{config_mode}) {
 db_log_verbose($dbh, 'Clearing empty records.');
 
 log_info($dbh, 'Clearing empty user accounts and associated devices for dynamic users and hotspot');
-my $u_sql = "SELECT * FROM user_list AS U WHERE (U.ou_id = " . $default_hotspot_ou_id . " OR U.ou_id = " . $default_user_ou_id . ") AND (SELECT COUNT(*) FROM user_auth WHERE user_auth.deleted = 0 AND user_auth.user_id = U.id) = 0";
-my @u_ref = get_records_sql($dbh, $u_sql);
+my $u_sql = "SELECT * FROM user_list AS U WHERE (U.ou_id = ? OR U.ou_id = ?) AND (SELECT COUNT(*) FROM user_auth WHERE user_auth.deleted = 0 AND user_auth.user_id = U.id) = 0";
+my @u_ref = get_records_sql($dbh, $u_sql, $default_user_ou_id, $default_hotspot_ou_id);
 foreach my $row (@u_ref) {
     db_log_info($dbh, "Remove empty dynamic user with id: $row->{id} login: $row->{login}");
     delete_user($dbh, $row->{id});
@@ -66,14 +66,17 @@ foreach my $row (@u_ref) {
 
 # Clean temporary (dynamic) user authentication records that have expired
 my $now = DateTime->now(time_zone => 'local');
-my $clear_time = $dbh->quote($now->strftime('%Y-%m-%d %H:%M:%S'));
-my $users_sql = "SELECT * FROM user_auth WHERE deleted = 0 AND dynamic = 1 AND end_life <= " . $clear_time;
-my @users_auth = get_records_sql($dbh, $users_sql);
+
+
+my $clear_time_str = $now->strftime('%Y-%m-%d %H:%M:%S');
+my $users_sql = "SELECT * FROM user_auth WHERE deleted = 0 AND dynamic = 1 AND end_life <= ?";
+my @users_auth = get_records_sql($dbh, $users_sql, $clear_time_str);
+
 if (@users_auth and scalar @users_auth) {
     foreach my $row (@users_auth) {
         delete_user_auth($dbh, $row->{id});
         db_log_info($dbh, "Removed dynamic user auth record for auth_id: $row->{'id'} by end_life time: $row->{'end_life'}", $row->{'id'});
-        my $u_count = get_count_records($dbh, 'user_auth', 'deleted = 0 AND user_id = ' . $row->{user_id});
+        my $u_count = get_count_records($dbh, 'user_auth', 'deleted = 0 AND user_id = ? ', $row->{user_id});
         if (!$u_count) {
             delete_user($dbh, $row->{'user_id'});
         }
@@ -239,9 +242,8 @@ foreach my $connection (@connections_list) {
 }
 
 # Build operational and full MAC-to-auth lookup tables
-my $auth_filter = " AND last_found >= '" . $now_day . "' ";
-my $auth_sql = "SELECT id, mac FROM user_auth WHERE mac IS NOT NULL AND deleted = 0 $auth_filter ORDER BY id ASC";
-my @auth_list = get_records_sql($dbh, $auth_sql);
+my $auth_sql = "SELECT id, mac FROM user_auth WHERE mac IS NOT NULL AND deleted = 0 AND last_found >= ? ORDER BY id ASC";
+my @auth_list = get_records_sql($dbh, $auth_sql, $now_day);
 
 my %auth_table;
 foreach my $auth (@auth_list) {
@@ -351,7 +353,7 @@ foreach my $device (@device_list) {
     next if (!$fdb);
 
     # Load device port mappings from database
-    my @device_ports = get_records_sql($dbh, "SELECT * FROM device_ports WHERE device_id = $dev_id");
+    my @device_ports = get_records_sql($dbh, "SELECT * FROM device_ports WHERE device_id = ?", $dev_id);
     foreach my $port_data (@device_ports) {
         my $fdb_port_index = $port_data->{port};
         my $port_id = $port_data->{id};
@@ -370,7 +372,7 @@ foreach my $device (@device_list) {
     # Special handling for MikroTik: skip device's own MAC addresses
     my $sw_mac;
     if ($device->{vendor_id} eq '9') {
-        my $sw_auth = get_record_sql($dbh, "SELECT mac FROM user_auth WHERE deleted = 0 AND ip = '" . $device->{ip} . "'");
+        my $sw_auth = get_record_sql($dbh, "SELECT mac FROM user_auth WHERE deleted = 0 AND ip = ?", $device->{ip});
         $sw_mac = mac_simplify($sw_auth->{mac});
         $sw_mac =~ s/.{2}$//s;  # Strip last two hex chars for prefix match
     }
@@ -400,7 +402,7 @@ foreach my $device (@device_list) {
         next if (!$port || !exists $port_index{$port} || $port_links{$port} > 0);
         my $dev_ports;
         $dev_ports->{last_mac_count} = $mac_port_count{$port};
-        update_record($dbh, 'device_ports', $dev_ports, "device_id = $dev_id AND port = $port");
+        update_record($dbh, 'device_ports', $dev_ports, "device_id = ? AND port = ?", $dev_id, $port);
     }
 
     # Process each learned MAC address
@@ -434,7 +436,7 @@ foreach my $device (@device_list) {
                         my $auth_rec;
                         $auth_rec->{last_found} = $now_str;
 	                $auth_rec->{mac_found}  = $now_str;
-                        update_record($dbh, 'user_auth', $auth_rec, "id = $auth_id");
+                        update_record($dbh, 'user_auth', $auth_rec, "id = ?", $auth_id);
                     }
                     next;
                 }
@@ -448,12 +450,12 @@ foreach my $device (@device_list) {
                 my $auth_rec;
                 $auth_rec->{last_found} = $now_str;
                 $auth_rec->{mac_found}  = $now_str;
-                update_record($dbh, 'user_auth', $auth_rec, "id = $auth_id");
+                update_record($dbh, 'user_auth', $auth_rec, "id = ?", $auth_id);
 
                 my $conn_rec;
                 $conn_rec->{port_id}   = $port_id;
                 $conn_rec->{device_id} = $dev_id;
-                update_record($dbh, 'connections', $conn_rec, "auth_id = $auth_id");
+                update_record($dbh, 'connections', $conn_rec, "auth_id = ?", $auth_id);
             } else {
                 # New connection for known user
                 $mac_history{$simple_mac}{changed} = 1;
@@ -464,7 +466,7 @@ foreach my $device (@device_list) {
                 my $auth_rec;
                 $auth_rec->{last_found} = $now_str;
                 $auth_rec->{mac_found}  = $now_str;
-                update_record($dbh, 'user_auth', $auth_rec, "id = $auth_id");
+                update_record($dbh, 'user_auth', $auth_rec, "id = ?", $auth_id);
 
                 my $conn_rec;
                 $conn_rec->{port_id}   = $port_id;
@@ -484,7 +486,7 @@ foreach my $device (@device_list) {
                 my $unknown_rec;
                 $unknown_rec->{port_id}   = $port_id;
                 $unknown_rec->{device_id} = $dev_id;
-                update_record($dbh, 'unknown_mac', $unknown_rec, "id = $unknown_table{$simple_mac}{unknown_id}");
+                update_record($dbh, 'unknown_mac', $unknown_rec, "id = ?", $unknown_table{$simple_mac}{unknown_id});
             } else {
                 # Brand new unknown MAC
                 $mac_history{$simple_mac}{changed} = 1;

+ 21 - 21
scripts/garbage.pl

@@ -125,7 +125,7 @@ if ($day == 1) {
         FROM (
             SELECT user_stats.auth_id, SUM(byte_in + byte_out) AS traf_all
             FROM user_stats
-            WHERE user_stats.ts >= $month_start AND user_stats.ts < $month_stop
+            WHERE user_stats.ts >= ? AND user_stats.ts < ?
             GROUP BY user_stats.auth_id
         ) AS V, user_auth, user_list
         WHERE V.auth_id = user_auth.id
@@ -134,7 +134,7 @@ if ($day == 1) {
         GROUP BY login
     ";
 
-    my @month_stats = get_records_sql($dbh, $month_sql);
+    my @month_stats = get_records_sql($dbh, $month_sql, $month_start, $month_stop);
     foreach my $row (@month_stats) {
         my $m_quota = $row->{uquota} * $KB * $KB;  # Convert MB to bytes
         next if ($m_quota < $row->{traf_sum});     # Skip if still over quota
@@ -146,8 +146,8 @@ if ($day == 1) {
 # Clean expired DHCP leases for dynamic users (hotspot and default OU only)
 log_info($dbh, 'Cleaning DHCP leases with overdue expiration for dynamic hosts');
 
-my $users_sql = "SELECT * FROM user_auth WHERE deleted = 0 AND (ou_id = " . $default_user_ou_id . " OR ou_id = " . $default_hotspot_ou_id . ")";
-my @users_auth = get_records_sql($dbh, $users_sql);
+my $users_sql = "SELECT * FROM user_auth WHERE deleted = 0 AND (ou_id = ? OR ou_id = ?)";
+my @users_auth = get_records_sql($dbh, $users_sql, $default_user_ou_id, $default_hotspot_ou_id);
 foreach my $row (@users_auth) {
     # Skip if IP is not in any DHCP pool
     next if (!is_dhcp_pool(\%dhcp_conf, $row->{ip_int}));
@@ -163,7 +163,7 @@ foreach my $row (@users_auth) {
             delete_user_auth($dbh, $row->{id});
 
             # Also delete parent user if no other active sessions remain
-            my $u_count = get_count_records($dbh, 'user_auth', "deleted = 0 AND user_id = " . $row->{user_id});
+            my $u_count = get_count_records($dbh, 'user_auth', "deleted = 0 AND user_id = ? ", $row->{user_id});
             if (!$u_count) {
                 delete_user($dbh, $row->{'user_id'});
                 db_log_info($dbh, "Removed dynamic user id: $row->{'user_id'} due to DHCP lease timeout");
@@ -180,7 +180,7 @@ if ($history_dhcp) {
     my $clean_date = $now - $day_dur;
     my $clean_str = $dbh->quote($clean_date->ymd("-") . " 00:00:00");
     log_info($dbh, 'Clearing outdated DHCP log records');
-    do_sql($dbh, "DELETE FROM dhcp_log WHERE ts < $clean_str");
+    do_sql($dbh, "DELETE FROM dhcp_log WHERE ts < ?",$clean_str);
     log_verbose($dbh, "Removed DHCP log entries older than $clean_str");
 }
 
@@ -190,12 +190,12 @@ if ($connections_history) {
     my $day_dur = DateTime::Duration->new(days => $connections_history);
     my $clean_date = $now - $day_dur;
     my $clean_str = $dbh->quote($clean_date->ymd("-") . " 00:00:00");
-    $users_sql = "SELECT id FROM user_auth WHERE last_found < $clean_str AND last_found > 0";
+    $users_sql = "SELECT id FROM user_auth WHERE last_found < ? AND last_found > 0";
     log_debug($dbh, $users_sql) if ($debug);
-    @users_auth = get_records_sql($dbh, $users_sql);
+    @users_auth = get_records_sql($dbh, $users_sql, $clean_str);
     foreach my $row (@users_auth) {
         log_debug($dbh, "Clearing old connection for auth_id: " . $row->{id});
-        do_sql($dbh, "DELETE FROM connections WHERE auth_id = '" . $row->{id} . "'");
+        do_sql($dbh, "DELETE FROM connections WHERE auth_id = ?", $row->{id});
     }
 }
 
@@ -218,7 +218,7 @@ foreach my $row (@conn_ref) {
 
     # If we're still on the same (port, auth) pair, this is a duplicate
     if ($old_port_id == $c_port_id && $old_auth_id == $c_auth_id) {
-        do_sql($dbh, "DELETE FROM connections WHERE id = '$c_id'");
+        do_sql($dbh, "DELETE FROM connections WHERE id = ?",$c_id);
         log_info($dbh, "Removed duplicate connection id=$c_id: port=$c_port_id auth=$c_auth_id");
     } else {
         $old_port_id = $c_port_id;
@@ -228,8 +228,8 @@ foreach my $row (@conn_ref) {
 
 # Clean empty dynamic/hotspot user accounts (no active authentications)
 log_info($dbh, 'Clearing empty user accounts and associated devices for dynamic users and hotspot');
-my $u_sql = "SELECT * FROM user_list AS U WHERE (U.ou_id = " . $default_hotspot_ou_id . " OR U.ou_id = " . $default_user_ou_id . ") AND (SELECT COUNT(*) FROM user_auth WHERE user_auth.deleted = 0 AND user_auth.user_id = U.id) = 0";
-my @u_ref = get_records_sql($dbh, $u_sql);
+my $u_sql = "SELECT * FROM user_list AS U WHERE (U.ou_id = ? OR U.ou_id = ? ) AND (SELECT COUNT(*) FROM user_auth WHERE user_auth.deleted = 0 AND user_auth.user_id = U.id) = 0";
+my @u_ref = get_records_sql($dbh, $u_sql, $default_hotspot_ou_id, $default_user_ou_id);
 foreach my $row (@u_ref) {
     db_log_info($dbh, "Removing empty dynamic user with id: $row->{id}, login: $row->{login}");
     delete_user($dbh, $row->{id});
@@ -255,7 +255,7 @@ $users_sql = "SELECT mac FROM user_auth WHERE deleted = 0";
 @users_auth = get_records_sql($dbh, $users_sql);
 foreach my $row (@users_auth) {
     next if (!$row->{mac});
-    do_sql($dbh, "DELETE FROM unknown_mac WHERE mac = '" . mac_simplify($row->{mac}) . "'");
+    do_sql($dbh, "DELETE FROM unknown_mac WHERE mac = ?", mac_simplify($row->{mac}));
 }
 
 # Clean old detailed traffic records (based on global $history setting)
@@ -264,7 +264,7 @@ if ($history) {
     my $clean_date = $now - $day_dur;
     my $clean_str = $dbh->quote($clean_date->ymd("-") . " 00:00:00");
     log_info($dbh, "Cleaning traffic detail records older than $clean_str");
-    do_sql($dbh, "DELETE FROM traffic_detail WHERE ts < $clean_str");
+    do_sql($dbh, "DELETE FROM traffic_detail WHERE ts < ?", $clean_str);
 }
 
 # Clean verbose (non-info) worklog entries
@@ -273,7 +273,7 @@ if ($history_log_day) {
     my $clean_date = $now - $day_dur;
     my $clean_str = $dbh->quote($clean_date->ymd("-") . " 00:00:00");
     log_info($dbh, "Cleaning VERBOSE worklog entries older than $clean_str");
-    do_sql($dbh, "DELETE FROM worklog WHERE level > $L_INFO AND ts < $clean_str");
+    do_sql($dbh, "DELETE FROM worklog WHERE level > ? AND ts < ?", $L_INFO, $clean_str);
 }
 
 # Clean debug-level worklog entries older than $debug_history days (hardcoded to 3)
@@ -282,7 +282,7 @@ if ($debug_history) {
     my $clean_date = $now - $day_dur;
     my $clean_str = $dbh->quote($clean_date->ymd("-") . " 00:00:00");
     log_info($dbh, "Cleaning debug worklog entries older than $clean_str");
-    do_sql($dbh, "DELETE FROM worklog WHERE level >= $L_DEBUG AND ts < $clean_str");
+    do_sql($dbh, "DELETE FROM worklog WHERE level >= ? AND ts < ?",$L_DEBUG, $clean_str);
 }
 
 # Clean old remote syslog entries
@@ -291,7 +291,7 @@ if ($history_syslog_day) {
     my $clean_date = $now - $day_dur;
     my $clean_str = $dbh->quote($clean_date->ymd("-") . " 00:00:00");
     log_info($dbh, "Cleaning syslog entries older than $clean_str");
-    do_sql($dbh, "DELETE FROM remote_syslog WHERE ts < $clean_str");
+    do_sql($dbh, "DELETE FROM remote_syslog WHERE ts < ?",$clean_str);
 }
 
 # Clean old aggregated traffic statistics
@@ -300,7 +300,7 @@ if ($history_trafstat_day) {
     my $clean_date = $now - $day_dur;
     my $clean_str = $dbh->quote($clean_date->ymd("-") . " 00:00:00");
     log_info($dbh, "Cleaning traffic statistics older than $clean_str");
-    do_sql($dbh, "DELETE FROM user_stats WHERE ts < $clean_str");
+    do_sql($dbh, "DELETE FROM user_stats WHERE ts < ?",$clean_str);
 }
 
 # Clean old per-IP full traffic statistics (if retention is configured)
@@ -310,7 +310,7 @@ if ($iptraf_history) {
     my $clean_date = $now - $day_dur;
     my $clean_str = $dbh->quote($clean_date->ymd("-") . " 00:00:00");
     log_info($dbh, "Cleaning full traffic statistics older than $clean_str");
-    do_sql($dbh, "DELETE FROM user_stats_full WHERE ts < $clean_str");
+    do_sql($dbh, "DELETE FROM user_stats_full WHERE ts < ?",$clean_str);
 }
 
 # Clean dangling user_auth records (deleted, but with no MAC — likely artifacts)
@@ -337,8 +337,8 @@ foreach my $auth (@auth_full_list) {
     $auth_table{$auth_mac} = 1;
 
     # Check if location history already exists
-    my $h_sql = "SELECT * FROM mac_history WHERE mac = '$auth_mac' ORDER BY ts";
-    my $history = get_record_sql($dbh, $h_sql);
+    my $h_sql = "SELECT * FROM mac_history WHERE mac = ? ORDER BY ts";
+    my $history = get_record_sql($dbh, $h_sql, $auth_mac);
 
     my $cur_conn = $connections{$auth->{id}};
 

+ 14 - 14
scripts/gen_nagios_config.pl

@@ -88,7 +88,7 @@ if (scalar(@netdev_list)>0) {
             }
 	if ($router->{'user_id'}) {
             #get user
-	    my $login = get_record_sql($dbh,"SELECT * FROM user_list WHERE id=".$router->{'user_id'});
+	    my $login = get_record_sql($dbh,"SELECT * FROM user_list WHERE id= ?", $router->{'user_id'});
 	    if ($login and $login->{ou_id} and $ou{$login->{ou_id}}->{nagios_dir}) { $devices{$device_id}{ou_id} = $login->{ou_id}; }
             }
         $devices{$device_id}{ou}=$ou{$devices{$device_id}{ou_id}};
@@ -99,33 +99,33 @@ if (scalar(@netdev_list)>0) {
     	    }
         $devices{$device_id}{user_id}=$router->{'user_id'};
         #get uplinks
-        my $uplink_port = get_record_sql($dbh,"SELECT * FROM device_ports WHERE uplink=1 AND device_id=".$devices{$device_id}{device_id}." AND target_port_id>0 ORDER BY port DESC");
+        my $uplink_port = get_record_sql($dbh,"SELECT * FROM device_ports WHERE uplink=1 AND device_id= ? AND target_port_id>0 ORDER BY port DESC",$devices{$device_id}{device_id});
         if ($uplink_port and $uplink_port->{target_port_id}) {
-            my $parent_uplink = get_record_sql($dbh,"SELECT * FROM device_ports WHERE id=".$uplink_port->{target_port_id}." ORDER BY id DESC");
+            my $parent_uplink = get_record_sql($dbh,"SELECT * FROM device_ports WHERE id= ? ORDER BY id DESC",$uplink_port->{target_port_id});
             if ($parent_uplink and $parent_uplink->{device_id}) {
-        	my $uplink_device = get_record_sql($dbh,"SELECT * FROM devices WHERE id=".$parent_uplink->{device_id}." AND nagios=1 AND deleted=0");
+        	my $uplink_device = get_record_sql($dbh,"SELECT * FROM devices WHERE id= ? AND nagios=1 AND deleted=0",$parent_uplink->{device_id});
         	if ($uplink_device) {
         	    $devices{$device_id}{parent}='netdev_'.$uplink_device->{'id'}; 
         	    $devices{$device_id}{parent_name}=$uplink_device->{'device_name'};
         	    }
         	}
-            my $uplink = get_record_sql($dbh,"SELECT * FROM device_ports WHERE id=".$uplink_port->{id}." ORDER BY id DESC");
+            my $uplink = get_record_sql($dbh,"SELECT * FROM device_ports WHERE id=? ORDER BY id DESC",$uplink_port->{id});
     	    $devices{$device_id}{parent_downlink}=$parent_uplink;
     	    $devices{$device_id}{uplink}=$uplink;
             }
         #downlinks
-        my @downlinks = get_records_sql($dbh,"SELECT * FROM device_ports WHERE device_id=".$devices{$device_id}{device_id}." and target_port_id>0 and uplink=0");
+        my @downlinks = get_records_sql($dbh,"SELECT * FROM device_ports WHERE device_id= ? and target_port_id>0 and uplink=0", $devices{$device_id}{device_id});
         foreach my $downlink_port (@downlinks) {
-    	    my $downlink = get_record_sql($dbh,"SELECT * FROM device_ports WHERE id=".$downlink_port->{target_port_id});
+    	    my $downlink = get_record_sql($dbh,"SELECT * FROM device_ports WHERE id= ?", $downlink_port->{target_port_id});
     	    if ($downlink) {
-    		my $downlink_device = get_record_sql($dbh,"SELECT * FROM devices WHERE id=".$downlink->{device_id});
+    		my $downlink_device = get_record_sql($dbh,"SELECT * FROM devices WHERE id= ?", $downlink->{device_id});
     		if ($downlink_device) { $downlink_port->{downlink_name}=$downlink_device->{device_name}; }
 		}
 	    #id,port,snmp_index
             push(@{$devices{$device_id}{downlinks}},$downlink_port);
     	    }
 	#custom ports
-        my @custom_ports = get_records_sql($dbh,"SELECT * FROM device_ports WHERE device_id=".$devices{$device_id}{device_id}." and target_port_id=0 and uplink=0 and nagios=1");
+        my @custom_ports = get_records_sql($dbh,"SELECT * FROM device_ports WHERE device_id= ? and target_port_id=0 and uplink=0 and nagios=1", $devices{$device_id}{device_id});
         foreach my $downlink_port (@custom_ports) {
             #id,port,snmp_index,description
 	    push(@{$devices{$device_id}{downlinks}},$downlink_port);
@@ -148,11 +148,11 @@ if (scalar(@auth_list)>0) {
         next if ($devices{$device_id});
 
 	#skip user device with few ip
-        my $auth_count = get_count_records($dbh,"user_auth","user_id=".$auth->{'user_id'}." AND deleted=0");
+        my $auth_count = get_count_records($dbh,"user_auth","user_id= ? AND deleted=0",$auth->{'user_id'});
         next if ($auth_count>1);
 
 	#skip switches and routers
-        my $auth_device = get_record_sql($dbh,"SELECT * FROM devices WHERE user_id=".$auth->{'user_id'});
+        my $auth_device = get_record_sql($dbh,"SELECT * FROM devices WHERE user_id=?",$auth->{'user_id'});
 	next if ($auth_device and $auth_device->{device_type}<=2);
 
 	#snmp parameters
@@ -162,7 +162,7 @@ if (scalar(@auth_list)>0) {
         $devices{$device_id}{ip}=$ip;
 
         #get user
-        my $login = get_record_sql($dbh,"SELECT * FROM user_list WHERE id=".$auth->{'user_id'});
+        my $login = get_record_sql($dbh,"SELECT * FROM user_list WHERE id=?",$auth->{'user_id'});
     
         $devices{$device_id}{user_login} = $login->{login};
         $devices{$device_id}{user_fio} = $login->{fio};
@@ -192,9 +192,9 @@ if (scalar(@auth_list)>0) {
         $devices{$device_id}{type}='3';
         $devices{$device_id}{user_id}=$auth->{'user_id'};
         #get uplinks
-        my $uplink_port = get_record_sql($dbh,"SELECT * FROM connections WHERE auth_id=".$auth->{'id'});
+        my $uplink_port = get_record_sql($dbh,"SELECT * FROM connections WHERE auth_id=?",$auth->{'id'});
         if ($uplink_port and $uplink_port->{port_id}) {
-            my $uplink = get_record_sql($dbh,"SELECT * FROM device_ports WHERE id=".$uplink_port->{port_id});
+            my $uplink = get_record_sql($dbh,"SELECT * FROM device_ports WHERE id=?",$uplink_port->{port_id});
             if ($uplink and $uplink->{device_id} and $devices{'netdev_'.$uplink->{'device_id'}}) {
         	$devices{$device_id}{parent}='netdev_'.$uplink->{'device_id'};
                 $devices{$device_id}{parent_port} = $uplink->{port};

+ 11 - 11
scripts/hmonitor.pl

@@ -121,23 +121,23 @@ my $login;
 my $nagios_handler;
 
 if (!$hostid or $hostid !~ /^[0-9]/) {
-    $auth = get_record_sql($hdb,"SELECT * FROM user_auth WHERE deleted=0 AND ip='".$hostip."'");
+    $auth = get_record_sql($hdb,"SELECT * FROM user_auth WHERE deleted=0 AND ip=?",$hostip);
     next if (!$auth);
     $hostid = $auth->{id};
-    $login = get_record_sql($hdb,'SELECT * FROM user_list WHERE id='.$auth->{user_id});
-    $device = get_record_sql($hdb,'SELECT * FROM devices WHERE user_id='.$auth->{user_id});
+    $login = get_record_sql($hdb,'SELECT * FROM user_list WHERE id=?',$auth->{user_id});
+    $device = get_record_sql($hdb,'SELECT * FROM devices WHERE user_id=?',$auth->{user_id});
     if ($auth->{nagios_status}) { $old_state = $auth->{nagios_status}; }
     db_log_verbose($hdb,"Manual host: $hostname [$hostip] => $hoststate, old: $old_state");
     } else {
     if ($hosttype=~/device/i) {
-        $device = get_record_sql($hdb,'SELECT * FROM devices WHERE id='.$hostid);
-        $login = get_record_sql($hdb,'SELECT * FROM user_list WHERE id='.$device->{user_id});
-        $auth = get_record_sql($hdb,'SELECT * FROM user_auth WHERE user_id='.$device->{user_id}." AND deleted=0 AND ip='".$hostip."'");
+        $device = get_record_sql($hdb,'SELECT * FROM devices WHERE id=?',$hostid);
+        $login = get_record_sql($hdb,'SELECT * FROM user_list WHERE id=?',$device->{user_id});
+        $auth = get_record_sql($hdb,'SELECT * FROM user_auth WHERE user_id=? AND deleted=0 AND ip=?',$device->{user_id},$hostip);
         if ($device->{nagios_status}) { $old_state = $device->{nagios_status}; }
         } else {
-        $auth = get_record_sql($hdb,'SELECT * FROM user_auth WHERE id='.$hostid);
-        $login = get_record_sql($hdb,'SELECT * FROM user_list WHERE id='.$auth->{user_id});
-        $device = get_record_sql($hdb,'SELECT * FROM devices WHERE user_id='.$auth->{user_id});
+        $auth = get_record_sql($hdb,'SELECT * FROM user_auth WHERE id=?',$hostid);
+        $login = get_record_sql($hdb,'SELECT * FROM user_list WHERE id=?',$auth->{user_id});
+        $device = get_record_sql($hdb,'SELECT * FROM devices WHERE user_id=?',$auth->{user_id});
         if ($auth->{nagios_status}) { $old_state = $auth->{nagios_status}; }
         }
     }
@@ -154,8 +154,8 @@ if ($hoststate ne $old_state) {
     #Change device state
     db_log_verbose($hdb,"Host changed! $hostname [$hostip] => $hoststate, old: $old_state");
     my $ip_aton=StrToIp($hostip);
-    if ($device->{id}) { do_sql($hdb,"UPDATE devices SET nagios_status='".$hoststate."' WHERE id=".$device->{id}); }
-    if ($auth->{id}) { do_sql($hdb,"UPDATE user_auth SET nagios_status='".$hoststate."' WHERE id=".$auth->{id}); }
+    if ($device->{id}) { do_sql($hdb,"UPDATE devices SET nagios_status=? WHERE id=?", $hoststate, $device->{id}); }
+    if ($auth->{id}) { do_sql($hdb,"UPDATE user_auth SET nagios_status=? WHERE id=?",$hoststate, $auth->{id}); }
     if ($hoststate=~/UP/i) {
         nagios_host_svc_enable($hostname,1);
         db_log_debug($hdb,"Enable notifications for host $hostname [$hostip] id: $hostid services");

+ 3 - 3
scripts/restart_port_snmp.pl

@@ -39,7 +39,7 @@ my $HOST_IP = $ARGV[0];
 
 my $IP_ATON=StrToIp($HOST_IP);
 
-my $auth_rec = get_record_sql($dbh,'SELECT * FROM user_auth WHERE deleted=0 and ip_int='.$IP_ATON);
+my $auth_rec = get_record_sql($dbh,'SELECT * FROM user_auth WHERE deleted=0 and ip_int=?',$IP_ATON);
 if (!$auth_rec) { db_log_error("Record with ip $HOST_IP not found! Bye."); exit; }
 
 my $auth_id = $auth_rec->{id};
@@ -54,7 +54,7 @@ my $dev_port = get_record_sql($dbh,$d_sql);
 
 if (!$dev_port) { db_log_error($dbh,"Connection for $HOST_IP not found! Bye."); exit; }
 
-my $switch = get_record_sql($dbh,'SELECT * FROM devices WHERE id='.$dev_port->{id});
+my $switch = get_record_sql($dbh,'SELECT * FROM devices WHERE id=?',$dev_port->{id});
 
 if (!$switch) { db_log_error($dbh,"Switch for $HOST_IP not found! Bye."); exit; }
 
@@ -62,7 +62,7 @@ setCommunity($switch);
 
 my $ip=$dev_port->{ip};
 my $model_id=$dev_port->{device_model_id};
-my $model_rec = get_record_sql($dbh,'SELECT model_name FROM device_models WHERE id='.$model_id);
+my $model_rec = get_record_sql($dbh,'SELECT model_name FROM device_models WHERE id=?',$model_id);
 my $model = $model_rec->{model_name};
 my $port=$dev_port->{port};
 my $vendor_id = $dev_port->{vendor_id};

+ 8 - 8
scripts/stat-sync.pl

@@ -103,7 +103,7 @@ if (!$pid) {
                 process_dhcp_request($hdb, $dhcp->{action}, $dhcp->{mac}, $dhcp->{ip}, $dhcp->{dhcp_hostname}, '', '', '')
                         unless exists $leases{$dhcp->{ip}} && $leases{$dhcp->{ip}}{'action'} ne $dhcp->{action} && time() - $leases{$dhcp->{ip}}{'last_time'} <= $mute_time;
                 $leases{$dhcp->{ip}}=$dhcp;
-                do_sql($hdb,"DELETE FROM dhcp_queue WHERE id=".$dhcp->{id});
+                do_sql($hdb,"DELETE FROM dhcp_queue WHERE id=?",$dhcp->{id});
                 }
             }
 
@@ -116,13 +116,13 @@ if (!$pid) {
             $urgent_sync=get_option($hdb,50);
             if ($urgent_sync) {
                     #clean changed for dynamic clients or hotspot
-        	    do_sql($hdb,"UPDATE user_auth SET changed=0 WHERE ou_id=".$default_user_ou_id." OR ou_id=".$default_hotspot_ou_id);
-                    do_sql($hdb,"UPDATE user_auth SET dhcp_changed=0 WHERE ou_id=".$default_user_ou_id." OR ou_id=".$default_hotspot_ou_id);
+        	    do_sql($hdb,"UPDATE user_auth SET changed=0 WHERE ou_id=? OR ou_id=?",$default_user_ou_id,$default_hotspot_ou_id);
+                    do_sql($hdb,"UPDATE user_auth SET dhcp_changed=0 WHERE ou_id=? OR ou_id=?",$default_user_ou_id,$default_hotspot_ou_id);
         	    #clean unmanagment ip changed
 	            my @all_changed = get_records_sql($hdb,"SELECT id, ip FROM user_auth WHERE changed = 1 OR dhcp_changed = 1");
         	    foreach my $row(@all_changed) {
 	        	    next if ($office_networks->match_string($row->{ip}));
-		            do_sql($hdb,"UPDATE user_auth SET changed = 0, dhcp_changed = 0  WHERE id=".$row->{id});
+		            do_sql($hdb,"UPDATE user_auth SET changed = 0, dhcp_changed = 0  WHERE id=?",$row->{id});
 		            }
                     #dhcp changed records
                     my $changed = get_record_sql($hdb,"SELECT COUNT(*) as c_count from user_auth WHERE dhcp_changed=1");
@@ -148,19 +148,19 @@ if (!$pid) {
                     foreach my $auth (@dns_changed) {
                         update_dns_record($hdb,$auth->{auth_id});
                         log_info("Clear changed dns for auth id: ".$auth->{auth_id});
-                        do_sql($hdb,"DELETE FROM dns_queue WHERE auth_id=".$auth->{auth_id});
+                        do_sql($hdb,"DELETE FROM dns_queue WHERE auth_id=?",$auth->{auth_id});
                         }
 	            }
             #clear temporary user auth records
             my $now = DateTime->now(time_zone=>'local');
             my $clear_time =$dbh->quote($now->strftime('%Y-%m-%d %H:%M:%S'));
-            my $users_sql = "SELECT * FROM user_auth WHERE deleted=0 AND dynamic=1 AND end_life<=".$clear_time;
-            my @users_auth = get_records_sql($hdb,$users_sql);
+            my $users_sql = "SELECT * FROM user_auth WHERE deleted=0 AND dynamic=1 AND end_life<=?";
+            my @users_auth = get_records_sql($hdb,$users_sql,$clear_time);
             if (@users_auth and scalar @users_auth) {
                     foreach my $row (@users_auth) {
                         delete_user_auth($hdb,$row->{id});
                         db_log_info($hdb,"Removed dynamic user auth record for auth_id: $row->{'id'} by end_life time: $row->{'end_life'}",$row->{'id'});
-                        my $u_count=get_count_records($hdb,'user_auth','deleted=0 and user_id='.$row->{user_id});
+                        my $u_count=get_count_records($hdb,'user_auth','deleted=0 and user_id=?',$row->{user_id});
                         if (!$u_count) { delete_user($hdb,$row->{'user_id'}); }
                         }
                     }

+ 9 - 8
scripts/sync_mikrotik.pl

@@ -46,7 +46,7 @@ my $all_ok = 1;
 my @gateways =();
 #select undeleted mikrotik routers only
 if ($ARGV[0]) {
-    my $router = get_record_sql($dbh,'SELECT * FROM devices WHERE (device_type=2 OR device_type=0) and protocol>=0 and (user_acl=1 or dhcp=1) and deleted=0 and vendor_id=9 and id='.$ARGV[0]);
+    my $router = get_record_sql($dbh,'SELECT * FROM devices WHERE (device_type=2 OR device_type=0) and protocol>=0 and (user_acl=1 or dhcp=1) and deleted=0 and vendor_id=9 and id=?',$ARGV[0]);
     if ($router) { push(@gateways,$router); }
     } else {
     @gateways = get_records_sql($dbh,'SELECT * FROM devices WHERE (device_type=2 OR device_type=0) and protocol>=0 and (user_acl=1 or dhcp=1) and deleted=0 and vendor_id=9');
@@ -116,7 +116,7 @@ my %hotspot_exceptions;
 my @lan_int=();
 my @wan_int=();
 
-my @l3_int = get_records_sql($dbh,'SELECT * FROM device_l3_interfaces WHERE device_id='.$gate->{'id'});
+my @l3_int = get_records_sql($dbh,'SELECT * FROM device_l3_interfaces WHERE device_id=?',$gate->{'id'});
 foreach my $l3 (@l3_int) {
 $l3->{'name'}=~s/\"//g;
 if ($l3->{'interface_type'} eq '0') { push(@lan_int,$l3->{'name'}); }
@@ -124,7 +124,7 @@ if ($l3->{'interface_type'} eq '1') { push(@wan_int,$l3->{'name'}); }
 }
 
 #формируем список подключенных к роутеру сетей
-my @gw_subnets = get_records_sql($dbh,"SELECT gateway_subnets.*,subnets.subnet FROM gateway_subnets LEFT JOIN subnets ON gateway_subnets.subnet_id = subnets.id WHERE gateway_subnets.device_id=".$gate->{'id'});
+my @gw_subnets = get_records_sql($dbh,"SELECT gateway_subnets.*,subnets.subnet FROM gateway_subnets LEFT JOIN subnets ON gateway_subnets.subnet_id = subnets.id WHERE gateway_subnets.device_id=?",$gate->{'id'});
 if (@gw_subnets and scalar @gw_subnets) {
     foreach my $gw_subnet (@gw_subnets) {
         if ($gw_subnet and $gw_subnet->{'subnet'}) {
@@ -231,7 +231,8 @@ my @auth_records=();
 foreach my $dhcp_subnet (@dhcp_subnets) {
     next if (!$dhcp_subnet);
     next if (!exists $dhcp_conf{$dhcp_subnet});
-    my @tmp1=get_records_sql($dbh,"SELECT * from user_auth WHERE dhcp=1 and ip_int>=".$dhcp_conf{$dhcp_subnet}->{first_ip_aton}." and ip_int<=".$dhcp_conf{$dhcp_subnet}->{last_ip_aton}." and deleted=0 and ou_id !=".$default_user_ou_id." and ou_id !=".$default_hotspot_ou_id." ORDER BY ip_int");
+    my $a_sql = "SELECT * from user_auth WHERE dhcp=1 and ip_int>= ? AND ip_int<= ? and deleted=0 and ou_id != ? and ou_id != ? ORDER BY ip_int");
+    my @tmp1=get_records_sql($dbh,$a_sql,$dhcp_conf{$dhcp_subnet}->{first_ip_aton},$dhcp_conf{$dhcp_subnet}->{last_ip_aton},$default_user_ou_id, $default_hotspot_ou_id);
     push(@auth_records,@tmp1);
     undef @tmp1;
 }
@@ -463,10 +464,10 @@ AND user_auth.enabled =1
 AND user_auth.blocked =0
 AND user_list.blocked =0
 AND user_list.enabled =1
-AND user_auth.ou_id <> $default_hotspot_ou_id
+AND user_auth.ou_id <> ?
 ORDER BY ip_int";
 
-my @authlist_ref = get_records_sql($dbh,$user_auth_sql);
+my @authlist_ref = get_records_sql($dbh,$user_auth_sql,$default_hotspot_ou_id);
 my %users;
 my %lists;
 my %found_users;
@@ -645,7 +646,7 @@ my $instance_name = 'Users';
 if ($filter_instance->{id}>1) {
     $instance_name = 'Users-'.$filter_instance->{name};
     #check filter instance exist at gateway
-    my $instance_ok = get_record_sql($dbh,"SELECT * FROM device_filter_instances WHERE device_id=$gate->{'id'} AND instance_id=$filter_instance->{id}");
+    my $instance_ok = get_record_sql($dbh,"SELECT * FROM device_filter_instances WHERE device_id= ? AND instance_id=?", $gate->{'id'}, $filter_instance->{id});
     #skip insatnce if not found
     if (!$instance_ok) { next; }
     }
@@ -1041,7 +1042,7 @@ $pm->wait_all_children;
 #clear changed
 if ($all_ok) {
     foreach my $row (@changes_found) {
-        do_sql($dbh,"UPDATE user_auth SET changed=0 WHERE id=".$row->{id});
+        do_sql($dbh,"UPDATE user_auth SET changed=0 WHERE id=?",$row->{id});
         }
     }
 

+ 1 - 1
scripts/sync_mikrotik_poe_monitor.pl

@@ -41,7 +41,7 @@ my $switch_ip=$device->{ip};
 
 my @cmd_list=();
 
-my @auth_list = get_records_sql($dbh,"SELECT DP.port,AU.ip,AU.dns_name FROM device_ports AS DP, user_auth as AU, connections as C WHERE DP.id=C.port_id and C.auth_id=AU.id and AU.deleted=0 and AU.nagios=1 and C.device_id=".$device->{id}."");
+my @auth_list = get_records_sql($dbh,"SELECT DP.port,AU.ip,AU.dns_name FROM device_ports AS DP, user_auth as AU, connections as C WHERE DP.id=C.port_id and C.auth_id=AU.id and AU.deleted=0 and AU.nagios=1 and C.device_id=?",$device->{id});
 
 my %work_list;
 foreach my $auth (@auth_list) {

+ 2 - 2
scripts/syslog-stat.pl

@@ -165,8 +165,8 @@ eval {
             }
 
         my $q_msg=$db->quote($message);
-        my $ssql="INSERT INTO remote_syslog(device_id,ip,message) values('".$id."','".$host_ip."',".$q_msg.")";
-        do_sql($db,$ssql);
+        my $ssql="INSERT INTO remote_syslog(device_id,ip,message) values(?,?,?)";
+        do_sql($db,$ssql,$id,$host_ip,$q_msg);
 
         foreach my $pattern (keys %warning_patterns) {
             next if (!$pattern);

+ 1 - 1
scripts/utils/backupcfg.pl

@@ -30,7 +30,7 @@ $|=1;
 my $debug = 1;
 
 if ($ARGV[0]) {
-    my $device=get_record_sql($dbh,'SELECT * FROM devices WHERE id='.$ARGV[0]);
+    my $device=get_record_sql($dbh,'SELECT * FROM devices WHERE id=?',$ARGV[0]);
     $device = netdev_set_auth($device);
     print "Backup switch $device->{device_name} ip: $device->{ip} ...";
     netdev_backup($device,$tftp_server);

+ 1 - 1
scripts/utils/bind/print-dns-zones.pl

@@ -25,7 +25,7 @@ my $named_db_path='/etc/bind/masters';
 my $DNS1=$config_ref{dns_server};
 my $DNS1_IP=$config_ref{dns_server};
 
-my $dns_server_record = get_record_sql($dbh,"SELECT id,ip,dns_name FROM user_auth WHERE deleted=0 AND ip='".$DNS1_IP."'");
+my $dns_server_record = get_record_sql($dbh,"SELECT id,ip,dns_name FROM user_auth WHERE deleted=0 AND ip=?",$DNS1_IP);
 
 if ($dns_server_record and $dns_server_record->{dns_name}) { 
     my $ns1=$dns_server_record->{dns_name};

+ 26 - 26
scripts/import-system-dev.pl → scripts/utils/import-system-dev.pl

@@ -53,49 +53,49 @@ my %vendor_migration;
 print "Import Vendors\n";
 foreach my $vendor (@user_vendors) {
 #seach exists vendor created by user
-my $vendor_exist = get_record_sql($dbh,"SELECT * FROM vendors WHERE id>=10000 and LOWER(name)='".lc(trim($vendor->{name}))."'");
+my $vendor_exist = get_record_sql($dbh,"SELECT * FROM vendors WHERE id>=10000 and LOWER(name)= ?", lc(trim($vendor->{name})));
 print "Check: $vendor->{name} id: $vendor->{id} ...";
 if ($vendor_exist) {
     if ($vendor_exist->{id} == $vendor->{id}) { print "OK\n"; next; }
     print " created by user. Switch to system pool.";
-    do_sql($dbh,"UPDATE vendors SET id=".$vendor->{id}." WHERE id=".$vendor_exist->{id});
-    do_sql($dbh,"UPDATE device_models SET vendor_id=".$vendor->{id}." WHERE vendor_id=".$vendor_exist->{id});
-    do_sql($dbh,"UPDATE devices SET vendor_id=".$vendor->{id}." WHERE vendor_id=".$vendor_exist->{id});
+    do_sql($dbh,"UPDATE vendors SET id=? WHERE id=?",$vendor->{id},$vendor_exist->{id});
+    do_sql($dbh,"UPDATE device_models SET vendor_id=? WHERE vendor_id=?",$vendor->{id}, $vendor_exist->{id});
+    do_sql($dbh,"UPDATE devices SET vendor_id=? WHERE vendor_id=?", $vendor->{id}, $vendor_exist->{id});
     print " Migrated.\n";
     next;
     }
 #check system pool
-$vendor_exist = get_record_sql($dbh,"SELECT * FROM vendors WHERE id<10000 and LOWER(name)='".lc(trim($vendor->{name}))."'");
+$vendor_exist = get_record_sql($dbh,"SELECT * FROM vendors WHERE id<10000 and LOWER(name)=?",lc(trim($vendor->{name})));
 if ($vendor_exist) {
     if ($vendor_exist->{id} == $vendor->{id}) { print "OK\n"; next ; }
     print "Warning! System vendor mismatch! ";
-    my $vendor2 = get_record_sql($dbh,"SELECT * FROM vendors WHERE id=$vendor->{id}");
+    my $vendor2 = get_record_sql($dbh,"SELECT * FROM vendors WHERE id=?",$vendor->{id});
     if ($vendor2) {
         print "Found another vendor with this id =>".$vendor2->{name};
         my $last_id = get_record_sql($dbh,"SELECT MAX(id) as last FROM vendors");
         my $new_vendor_id = $last_id->{'last'}+1;
         if ($new_vendor_id <=10000 ) { $new_vendor_id = 10001; }
         print " Move vendor $vendor2->{name} to user custom block. Run script again\n";
-        do_sql($dbh,"UPDATE vendors SET id=".$new_vendor_id." WHERE id=".$vendor2->{id});
-        do_sql($dbh,"UPDATE device_models SET vendor_id=".$new_vendor_id." WHERE vendor_id=".$vendor2->{id});
+        do_sql($dbh,"UPDATE vendors SET id=? WHERE id=?",$new_vendor_id, $vendor2->{id});
+        do_sql($dbh,"UPDATE device_models SET vendor_id=? WHERE vendor_id=?",$new_vendor_id,$vendor2->{id});
         next;
         }
-    do_sql($dbh,"UPDATE vendors SET id=".$vendor->{id}." WHERE id=".$vendor_exist->{id});
-    do_sql($dbh,"UPDATE device_models SET vendor_id=".$vendor->{id}." WHERE vendor_id=".$vendor_exist->{id});
-    do_sql($dbh,"UPDATE devices SET vendor_id=".$vendor->{id}." WHERE vendor_id=".$vendor_exist->{id});
+    do_sql($dbh,"UPDATE vendors SET id=? WHERE id=?",$vendor->{id},$vendor_exist->{id});
+    do_sql($dbh,"UPDATE device_models SET vendor_id=? WHERE vendor_id=?",$vendor->{id},$vendor_exist->{id});
+    do_sql($dbh,"UPDATE devices SET vendor_id=? WHERE vendor_id=?",$vendor->{id},$vendor_exist->{id});
     print "Fixed.\n";
     next;
     }
 #check another record with this id
-my $vendor2 = get_record_sql($dbh,"SELECT * FROM vendors WHERE id=$vendor->{id}");
+my $vendor2 = get_record_sql($dbh,"SELECT * FROM vendors WHERE id=?",$vendor->{id});
 if ($vendor2) {
     print "Found another vendor with this id =>".$vendor2->{name};
     my $last_id = get_record_sql($dbh,"SELECT MAX(id) as last FROM vendors");
     my $new_vendor_id = $last_id->{'last'}+1;
     if ($new_vendor_id <=10000 ) { $new_vendor_id = 10001; }
     print " Move vendor $vendor2->{name} to user custom block. Run script again\n";
-    do_sql($dbh,"UPDATE vendors SET id=".$new_vendor_id." WHERE id=".$vendor2->{id});
-    do_sql($dbh,"UPDATE device_models SET vendor_id=".$new_vendor_id." WHERE vendor_id=".$vendor2->{id});
+    do_sql($dbh,"UPDATE vendors SET id=? WHERE id=?",$new_vendor_id,$vendor2->{id});
+    do_sql($dbh,"UPDATE device_models SET vendor_id=? WHERE vendor_id=?",$new_vendor_id,$vendor2->{id});
     next;
     }
 insert_record($dbh,"vendors",$vendor);
@@ -108,45 +108,45 @@ print "Import devices\n";
 foreach my $device (@user_devices) {
 #seach exists device created by user
 print "Check id: $device->{id} name: $device->{model_name}..";
-my $device_exist = get_record_sql($dbh,"SELECT * FROM device_models WHERE id>=10000 AND vendor_id=".$device->{vendor_id}." AND LOWER(model_name)='".lc(trim($device->{model_name}))."'");
+my $device_exist = get_record_sql($dbh,"SELECT * FROM device_models WHERE id>=10000 AND vendor_id=? AND LOWER(model_name)=?",$device->{vendor_id},lc(trim($device->{model_name})));
 if ($device_exist) {
     if ($device_exist->{id} == $device->{id}) { print "OK\n"; next; }
-    do_sql($dbh,"UPDATE device_models SET id=".$device->{id}." WHERE id=".$device_exist->{id});
-    do_sql($dbh,"UPDATE devices SET device_model_id=".$device->{id}." WHERE device_model_id=".$device_exist->{id});
+    do_sql($dbh,"UPDATE device_models SET id=? WHERE id=?",$device->{id},$device_exist->{id});
+    do_sql($dbh,"UPDATE devices SET device_model_id=? WHERE device_model_id=?",$device->{id},$device_exist->{id});
     print "Migrated\n";
     next;
     }
 #system model table
-$device_exist = get_record_sql($dbh,"SELECT * FROM device_models WHERE id<10000 AND vendor_id=".$device->{vendor_id}." AND LOWER(model_name)='".lc(trim($device->{model_name}))."'");
+$device_exist = get_record_sql($dbh,"SELECT * FROM device_models WHERE id<10000 AND vendor_id=? AND LOWER(model_name)=?",$device->{vendor_id},lc(trim($device->{model_name})));
 if ($device_exist) {
     if ($device_exist->{id} == $device->{id}) { print "OK\n"; next; }
     print "Warning! System device model mismatch! ";
-    my $device2 = get_record_sql($dbh,"SELECT * FROM device_models WHERE id=".$device->{id});
+    my $device2 = get_record_sql($dbh,"SELECT * FROM device_models WHERE id=?",$device->{id});
     if ($device2) {
         print "Found another device model with this id =>".$device2->{model_name};
         my $last_id = get_record_sql($dbh,"SELECT MAX(id) as last FROM device_models");
         my $new_model_id = $last_id->{'last'}+1;
         if ($new_model_id <=10000 ) { $new_model_id = 10001; }
         print " Move device model $device2->{model_name} to user custom block. Run script again\n";
-        do_sql($dbh,"UPDATE device_models SET id=".$new_model_id." WHERE id=".$device2->{id});
-        do_sql($dbh,"UPDATE devices SET device_model_id=".$new_model_id." WHERE device_model_id=".$device2->{id});
+        do_sql($dbh,"UPDATE device_models SET id=? WHERE id=?",$new_model_id,$device2->{id});
+        do_sql($dbh,"UPDATE devices SET device_model_id=? WHERE device_model_id=?",$new_model_id,$device2->{id});
         next;
         }
-    do_sql($dbh,"UPDATE device_models SET id=".$device->{id}." WHERE id=".$device_exist->{id});
-    do_sql($dbh,"UPDATE devices SET device_model_id=".$device->{id}." WHERE device_model_id=".$device_exist->{id});
+    do_sql($dbh,"UPDATE device_models SET id=? WHERE id=?",$device->{id},$device_exist->{id});
+    do_sql($dbh,"UPDATE devices SET device_model_id=? WHERE device_model_id=?",$device->{id},$device_exist->{id});
     print "Migrated\n";
     next;
     }
 #check another record with this id
-my $device2 = get_record_sql($dbh,"SELECT * FROM device_models WHERE id=".$device->{id});
+my $device2 = get_record_sql($dbh,"SELECT * FROM device_models WHERE id=?",$device->{id});
 if ($device2) {
     print "Found another device model with this id =>".$device2->{model_name};
     my $last_id = get_record_sql($dbh,"SELECT MAX(id) as last FROM device_models");
     my $new_model_id = $last_id->{'last'}+1;
     if ($new_model_id <=10000 ) { $new_model_id = 10001; }
     print " Move device model $device2->{model_name} to user custom block. Run script again\n";
-    do_sql($dbh,"UPDATE device_models SET id=".$new_model_id." WHERE id=".$device2->{id});
-    do_sql($dbh,"UPDATE devices SET device_model_id=".$new_model_id." WHERE device_model_id=".$device2->{id});
+    do_sql($dbh,"UPDATE device_models SET id=? WHERE id=?",$new_model_id,$device2->{id});
+    do_sql($dbh,"UPDATE devices SET device_model_id=? WHERE device_model_id=?",$new_model_id,$device2->{id});
     next;
     }
 insert_record($dbh,"device_models",$device);

+ 86 - 80
scripts/utils/import/import_auth.pl

@@ -32,134 +32,140 @@ sub process_file {
         chomp $line;
         $line_num++;
 
-        # Пропускаем пустые строки
         next if $line =~ /^\s*$/;
 
-        # Разбиваем строку по разделителям: пробелы, табы, запятые, точки с запятой
         my @fields = split(/[\t,;]+/, $line);
 
         if ($line_num == 1) {
-            # Первая непустая строка — заголовки
             @headers = @fields;
             print "Заголовки: " . join(" | ", map { "'$_'" } @headers) . "\n\n";
             next;
         }
 
-        # Проверяем, совпадает ли количество полей с количеством заголовков
         if (@fields != @headers) {
             warn "Предупреждение: строка $line_num: количество полей (" . scalar(@fields) .
                  ") не совпадает с количеством заголовков (" . scalar(@headers) . ")\n";
-            # Дополняем или обрезаем массив, чтобы избежать ошибок
             @fields = @fields[0 .. $#headers] if @fields > @headers;
-            while (@fields < @headers) {
-                push @fields, '';
-            }
+            push @fields, ('') x (@headers - @fields);
         }
 
-        # Создаём ассоциативный массив (hash) для текущей строки
         my %row;
-        for my $i (0 .. $#headers) {
-            $row{$headers[$i]} = $fields[$i];
-        }
-
-        # Добавляем в общий результат
+        @row{@headers} = @fields;
         push @data, \%row;
     }
 
-    return @data;  # возвращаем список ссылок на хеши
+    return @data;
 }
 
-my @rows=();
-
 # === Основная логика ===
+my @rows = ();
 if (@ARGV) {
-    foreach my $filename (@ARGV) {
+    for my $filename (@ARGV) {
         open(my $fh, '<', $filename) or die "Не могу открыть файл '$filename': $!";
         print "Обработка файла: $filename\n";
-        @rows = process_file($fh);
-        close($fh);
+        push @rows, process_file($fh);
+        close $fh;
     }
 } else {
     @rows = process_file(\*STDIN);
 }
 
-foreach my $record (@rows) {
+for my $record (@rows) {
+    next unless exists $record->{ip};
 
-next if (!exists($record->{ip}));
+    my $ip = trim($record->{ip});
+    next if !$ip;
 
-my $auth_network = $office_networks->match_string($record->{ip});
-if (!$auth_network) {
-    log_error("Unknown network in request! IP: $record->{ip}");
-    next;
+    # Проверка сети
+    my $auth_network = $office_networks->match_string($ip);
+    if (!$auth_network) {
+        log_error("Unknown network in request! IP: $ip");
+        next;
     }
 
-my $search_sql = 'SELECT * FROM user_auth WHERE ip="'.$record->{ip}.'" and deleted=0 ORDER BY last_found DESC';
-$record->{ip_int}=StrToIp($record->{ip});
-if (!exists($record->{'mac'})) {
-    delete $record->{'mac'};
+    # Подготовка записи
+    my $ip_int = StrToIp($ip);
+    $record->{ip} = $ip;
+    $record->{ip_int} = $ip_int;
+
+    if (exists $record->{mac} && defined $record->{mac} && $record->{mac} ne '') {
+        $record->{mac} = mac_splitted(isc_mac_simplify($record->{mac}));
     } else {
-    $record->{mac}=mac_splitted(isc_mac_simplify($record->{mac}));
-    $search_sql = 'SELECT * FROM user_auth WHERE ip="'.$record->{ip}.'" and mac="'.$record->{mac}.'" and deleted=0 ORDER BY last_found DESC';
+        delete $record->{mac};
     }
 
-print "Импортируем:\n";
-for my $key (keys %{$record}) {
-    print "\t\t$key => $record->{$key}\n";
-}
-print "\n";
-
-if (exists $record->{dns_name}) {
+    # Обработка dns_name
+    if (exists $record->{dns_name} && defined $record->{dns_name}) {
         my $auth_dns_name = lc(trim($record->{dns_name}));
-        $auth_dns_name=~s/\./-/g;
-        $auth_dns_name=~s/\//-/g;
+        $auth_dns_name =~ s/[.\/-]+/-/g;  # заменяем . и / на -
         $record->{dns_name} = $auth_dns_name;
-        }
+    }
+
+    print "Импортируем:\n";
+    for my $key (sort keys %$record) {
+        print "\t\t$key => $record->{$key}\n";
+    }
+    print "\n";
+
+    # === Безопасный поиск записи ===
+    my $auth_record;
+    if (exists $record->{mac}) {
+        $auth_record = get_record_sql(
+            $dbh,
+            'SELECT * FROM user_auth WHERE ip = ? AND mac = ? AND deleted = 0 ORDER BY last_found DESC',
+            $ip, $record->{mac}
+        );
+    } else {
+        $auth_record = get_record_sql(
+            $dbh,
+            'SELECT * FROM user_auth WHERE ip = ? AND deleted = 0 ORDER BY last_found DESC',
+            $ip
+        );
+    }
+
+    if ($auth_record) {
+        # Обновление user_auth
+        update_record($dbh, 'user_auth', $record, 'id = ?', $auth_record->{id});
+        print "URL: <a href='$config_ref{stat_url}/admin/users/edituser.php?id=$auth_record->{user_id}'>$auth_record->{user_id}</a><br>\n";
 
-#search actual record
-my $auth_record = get_record_sql($dbh,$search_sql);
-if ($auth_record) {
-    update_record($dbh,'user_auth',$record,"id=".$auth_record->{id});
-    print "URL: <a href='".$config_ref{stat_url}."/admin/users/edituser.php?id=".$auth_record->{user_id}."'>".$auth_record->{user_id}."</a><br>\n";
-    if (exists $record->{dns_name}) {
-        my $user_info;
-        $user_info->{login}=$record->{dns_name};
-        update_record($dbh,'user_list',$user_info,"id=".$auth_record->{user_id});
-        my $device;
-        $device->{device_name}=$record->{dns_name};
-        update_record($dbh,'devices',$device,"user_id=".$auth_record->{user_id});
+        my $user_id = $auth_record->{user_id};
+
+        # Обновление user_list и devices
+        if (exists $record->{dns_name}) {
+            update_record($dbh, 'user_list', { login => $record->{dns_name} }, 'id = ?', $user_id);
+            update_record($dbh, 'devices', { device_name => $record->{dns_name} }, 'user_id = ?', $user_id);
         }
-    if (exists $record->{description}) {
-        my $user_info;
-        $user_info->{fio}=$record->{description};
-        update_record($dbh,'user_list',$user_info,"id=".$auth_record->{user_id});
+
+        if (exists $record->{description}) {
+            update_record($dbh, 'user_list', { fio => $record->{description} }, 'id = ?', $user_id);
         }
-    next;
+
+        next;
     }
 
-my $dhcp_record =  {%{$record || {}}};
-$dhcp_record->{'type'}='add';
+    # === Создание новой записи ===
+    my $dhcp_record = { %$record, type => 'add' };
+    my $res_id = resurrection_auth($dbh, $dhcp_record);
 
-my $res_id = resurrection_auth($dbh,$dhcp_record);
-if (!$res_id) {
-    db_log_error($dbh,"Error creating an ip address record for:\t\t".Dumper($dhcp_record));
-    next;
+    if (!$res_id) {
+        db_log_error($dbh, "Error creating an ip address record for:\t\t" . Dumper($dhcp_record));
+        next;
     }
-update_record($dbh,'user_auth',$record,"id=".$res_id);
-$auth_record = get_record_sql($dbh,'SELECT * FROM user_auth where id='.$res_id);
-if ($auth_record) {
-    print "URL: <a href='".$config_ref{stat_url}."/admin/users/edituser.php?id=".$auth_record->{user_id}."'>".$auth_record->{user_id}."</a><br>\n";
-    if (exists $record->{dns_name}) {
-        my $user_info;
-        $user_info->{login}=$record->{dns_name};
-        update_record($dbh,'user_list',$user_info,"id=".$auth_record->{user_id});
-        my $device;
-        $device->{device_name}=$record->{dns_name};
-        update_record($dbh,'devices',$device,"user_id=".$auth_record->{user_id});
+
+    update_record($dbh, 'user_auth', $record, 'id = ?', $res_id);
+    $auth_record = get_record_sql($dbh, 'SELECT * FROM user_auth WHERE id = ?', $res_id);
+
+    if ($auth_record) {
+        print "URL: <a href='$config_ref{stat_url}/admin/users/edituser.php?id=$auth_record->{user_id}'>$auth_record->{user_id}</a><br>\n";
+        my $user_id = $auth_record->{user_id};
+
+        if (exists $record->{dns_name}) {
+            update_record($dbh, 'user_list', { login => $record->{dns_name} }, 'id = ?', $user_id);
+            update_record($dbh, 'devices', { device_name => $record->{dns_name} }, 'user_id = ?', $user_id);
         }
-    if (exists $record->{description}) {
-        my $user_info;
-        $user_info->{fio}=$record->{description};
-        update_record($dbh,'user_list',$user_info,"id=".$auth_record->{user_id});
+
+        if (exists $record->{description}) {
+            update_record($dbh, 'user_list', { fio => $record->{description} }, 'id = ?', $user_id);
         }
     }
 }

+ 1 - 1
scripts/utils/parse_flow.pl

@@ -261,7 +261,7 @@ db_log_debug($f_dbh,"Stopped child $child_count analyze data") if ($debug);
 
 if (scalar(@detail_traffic)) {
         db_log_debug($f_dbh,"Start write traffic detail to DB. ".scalar @detail_traffic." lines count") if ($debug);
-	batch_db_sql_cached("INSERT INTO traffic_detail (auth_id,router_id,ts,proto,src_ip,dst_ip,src_port,dst_port,bytes,pkt) VALUES(?,?,?,?,?,?,?,?,?,?)",\@detail_traffic);
+	batch_db_sql_cached($f_dbh,"INSERT INTO traffic_detail (auth_id,router_id,ts,proto,src_ip,dst_ip,src_port,dst_port,bytes,pkt) VALUES(?,?,?,?,?,?,?,?,?,?)",\@detail_traffic);
         db_log_debug($f_dbh,"Write traffic detail to DB stopped") if ($debug);
 	}
 

+ 1 - 1
scripts/utils/radius/print_huntgroups.pl

@@ -34,7 +34,7 @@ my %huntgroups=(
 
 my @device_list = get_records_sql($dbh,"SELECT * FROM devices WHERE device_type<=2 ORDER BY device_name" );
 foreach my $device (sort @device_list) {
-my @auth_list = get_records_sql($dbh,"SELECT * FROM user_auth WHERE deleted=0 AND user_id=".$device->{user_id});
+my @auth_list = get_records_sql($dbh,"SELECT * FROM user_auth WHERE deleted=0 AND user_id=?",$device->{user_id});
     print "#$device->{device_name}\n";
     foreach my $auth (sort @auth_list) {
     if (exists $huntgroups{$device->{vendor_id}}) {

Niektóre pliki nie zostały wyświetlone z powodu dużej ilości zmienionych plików