Explorar el Código

upload last release

Dmitriev Roman hace 5 años
padre
commit
90c1600411
Se han modificado 100 ficheros con 2369 adiciones y 3450 borrados
  1. 0 39
      docs/addons/cfg/config
  2. 45 0
      docs/addons/import_ip.pl
  3. 1 0
      docs/addons/iplist.txt
  4. 2 2
      docs/addons/print-dns-zones.pl
  5. 19 0
      docs/cron/stat
  6. 3 4
      docs/dhcpd/dhcp-hook.sh
  7. 0 276
      docs/dhcpd/dhcp-log.pl
  8. 2 2
      docs/dhcpd/print-dhcpd.pl
  9. 1 2
      docs/fix_net.pl
  10. 117 119
      docs/iptables/parse_ulog.pl
  11. 14 10
      docs/iptables/sync_iptables.pl
  12. 9 0
      docs/logrotate/dnsmasq
  13. 9 0
      docs/logrotate/iptraf-ng
  14. 15 0
      docs/logrotate/scripts
  15. 351 0
      docs/mysql/stat_extra.sql
  16. 20 0
      docs/mysql/stat_table_Customers.sql
  17. 65 0
      docs/mysql/stat_table_Filter_list.sql
  18. 71 0
      docs/mysql/stat_table_Group_filters.sql
  19. 23 0
      docs/mysql/stat_table_Group_list.sql
  20. 33 0
      docs/mysql/stat_table_OU.sql
  21. 26 0
      docs/mysql/stat_table_Queue_list.sql
  22. 19 0
      docs/mysql/stat_table_Traffic_detail.sql
  23. 14 0
      docs/mysql/stat_table_Unknown_mac.sql
  24. 41 0
      docs/mysql/stat_table_User_auth.sql
  25. 14 0
      docs/mysql/stat_table_User_auth_alias.sql
  26. 31 0
      docs/mysql/stat_table_User_list.sql
  27. 15 0
      docs/mysql/stat_table_User_stats.sql
  28. 19 0
      docs/mysql/stat_table_building.sql
  29. 21 0
      docs/mysql/stat_table_config.sql
  30. 61 0
      docs/mysql/stat_table_config_options.sql
  31. 13 0
      docs/mysql/stat_table_connections.sql
  32. 21 0
      docs/mysql/stat_table_device_ports.sql
  33. 39 0
      docs/mysql/stat_table_devices.sql
  34. 16 0
      docs/mysql/stat_table_dhcp_log.sql
  35. 16 0
      docs/mysql/stat_table_mac_history.sql
  36. 2 1036
      docs/mysql/stat_table_mac_vendors.sql
  37. 14 0
      docs/mysql/stat_table_remote_syslog.sql
  38. 36 0
      docs/mysql/stat_table_subnets.sql
  39. 15 0
      docs/mysql/stat_table_syslog.sql
  40. 14 0
      docs/mysql/stat_table_variables.sql
  41. 33 0
      docs/mysql/stat_table_vendors.sql
  42. 0 95
      docs/nagios/Rstat/mfi.pm
  43. 0 411
      docs/nagios/Rstat/nagios.pm
  44. 0 192
      docs/nagios/gen_nagios_config.pl
  45. 0 124
      docs/nagios/getcfg.pl
  46. 0 167
      docs/nagios/hoststate-monitor.pl
  47. 0 129
      docs/nagios/restart_port_snmp.pl
  48. 0 80
      docs/nagios/scan_ipcam.pl
  49. 2 1
      docs/systemd/dhcp-log.service
  50. 0 12
      docs/systemd/dnsmasq-log.service
  51. 11 0
      docs/systemd/dnsmasq.service
  52. 0 8
      docs/updates/20210129/patch-db-mysql-email-alert.sql
  53. 0 3
      docs/updates/20210208/db-patch-mysql-time.sql
  54. 0 63
      docs/updates/20210217/db-patch-alias.sql
  55. 0 47
      docs/updates/20210217/migrate-alias.pl
  56. 18 10
      html/admin/customers/control-options.php
  57. 6 4
      html/admin/customers/control-subnets-usage.php
  58. 57 55
      html/admin/customers/control-subnets.php
  59. 7 0
      html/admin/customers/control.php
  60. 3 3
      html/admin/customers/editcustom.php
  61. 1 1
      html/admin/customers/index.php
  62. 3 3
      html/admin/devices/building.php
  63. 1 1
      html/admin/devices/deleted.php
  64. 85 0
      html/admin/devices/edit_l3int.php
  65. 5 5
      html/admin/devices/editport.php
  66. 83 126
      html/admin/devices/editswitches.php
  67. 29 24
      html/admin/devices/index.php
  68. 4 4
      html/admin/devices/mactable.php
  69. 1 1
      html/admin/devices/portmactable.php
  70. 1 1
      html/admin/devices/portsbyvlan.php
  71. 5 5
      html/admin/devices/switchport-conn.php
  72. 5 5
      html/admin/devices/switchport.php
  73. 29 29
      html/admin/devices/switchstatus.php
  74. 7 7
      html/admin/filters/editfilter.php
  75. 7 7
      html/admin/filters/editgroup.php
  76. 3 4
      html/admin/filters/groups.php
  77. 5 6
      html/admin/filters/index.php
  78. 3 3
      html/admin/groups/index.php
  79. 1 1
      html/admin/index.php
  80. 2 2
      html/admin/iplist/deleted.php
  81. 104 0
      html/admin/iplist/doubles.php
  82. 2 2
      html/admin/iplist/index.php
  83. 8 13
      html/admin/logout.html
  84. 2 2
      html/admin/logs/authlog.php
  85. 5 2
      html/admin/logs/dhcp.php
  86. 2 2
      html/admin/logs/index.php
  87. 2 2
      html/admin/logs/ip.php
  88. 7 7
      html/admin/logs/mac.php
  89. 16 10
      html/admin/logs/syslog.php
  90. 2 2
      html/admin/logs/unknown.php
  91. 4 4
      html/admin/queues/index.php
  92. 93 0
      html/admin/reports/authday.php
  93. 116 0
      html/admin/reports/index-full.php
  94. 39 63
      html/admin/reports/index.php
  95. 35 21
      html/admin/reports/userday.php
  96. 23 66
      html/admin/reports/userdaydetail.php
  97. 105 0
      html/admin/reports/userdaydetaillog.php
  98. 40 27
      html/admin/users/add_dhcp.php
  99. 5 5
      html/admin/users/edit_alias.php
  100. 95 93
      html/admin/users/editauth.php

+ 0 - 39
docs/addons/cfg/config

@@ -15,7 +15,6 @@ DBSERVER=localhost
 DBUSER=rstat
 DBNAME=stat
 DBPASS=password
-TRAF_HOST=localhost
 
 #login for windows AD
 domain_auth=ORG\dhcp%password
@@ -38,41 +37,3 @@ group=root
 #switch access
 sw_login=admin
 sw_password=password
-
-############### SMS Config ################
-
-use_smsd=1
-smsaero_wait=120
-smsd_group=smstools
-smsd_user=smstools
-
-################ KANNEL ####################
-
-kannel_base_url=http://localhost:13003/cgi-bin
-kannel_dlr_url=http://127.0.0.1/dlr.php
-kannel_login=login
-kannel_password=password
-kannel_spool=/var/spool/kannel/dlr
-
-############### SMSAERO ###################
-
-smsaero_base_url=https://gate.smsaero.ru
-smsaero_login=login
-smsaero_md5pass=md5hash
-sms_spool_dir=/var/spool/smsaero
-
-#подпись
-sms_from=ORG
-
-#цифровой канал=1
-smsaero_digital=0
-
-#type=1 - оплаченная буквенная подпись для всех операторов связи
-#type=2 - бесплатная буквенная подпись для всех операторов, кроме МТС
-#type=3 - бесплатная буквенная подпись для всех операторов (+0,15 рублей к тарифу Прямого канала)
-#type=4 - инфоподпись для всех операторов
-smsaero_type=2
-
-############### SMSD #######################
-
-smsd_spool_dir=/var/spool/sms

+ 45 - 0
docs/addons/import_ip.pl

@@ -0,0 +1,45 @@
+#!/usr/bin/perl
+
+#
+# Copyright (C) Roman Dmitiriev, rnd@rajven.ru
+#
+
+use FindBin '$Bin';
+use lib "$Bin/";
+use Data::Dumper;
+use Rstat::config;
+use Rstat::main;
+use Rstat::mysql;
+use Rstat::net_utils;
+use strict;
+use warnings;
+use Getopt::Long;
+use Proc::Daemon;
+use Cwd;
+use IO::Socket::UNIX qw( SOCK_STREAM );
+use Net::Netmask;
+use File::Spec::Functions;
+use File::Copy qw(move);
+use Text::Iconv;
+
+my $iplist_file = "iplist.txt";
+open(IPLIST,$iplist_file) || die("Error open $iplist_file: $!");
+while (my $logline = <IPLIST>) {
+next unless defined $logline;
+chomp($logline);
+my ($ip,$mac,$comment) = split (/\;/, $logline);
+my $auth_network = $office_networks->match_string($ip);
+if (!$auth_network) {
+    log_error("Unknown network in dhcp request! IP: $ip");
+    next;
+    }
+log_info("Check for new auth...");
+my $auth_id=resurrection_auth($dbh,$ip,$mac,'add');
+if ($comment) {
+    my $auth;
+    $auth->{comments}=$comment;
+    update_record($dbh,'User_auth',$auth,'id='.$auth_id);
+    }
+}
+close IPLIST;
+exit;

+ 1 - 0
docs/addons/iplist.txt

@@ -0,0 +1 @@
+192.168.50.220;80:5E:C0:0B:17:6E;Yarlink W60B

+ 2 - 2
docs/addons/print-dns-zones.pl

@@ -27,7 +27,7 @@ my $DNS1=$ns1.'.'.$domain_name;
 my $named_conf=$named_root.'/etc/named.dynamic';
 
 # user auth list
-my @authlist_ref = get_custom_records($dbh,"SELECT id,ip,dns_name FROM User_auth WHERE `ip_int`>0 AND `deleted`=0 ORDER BY ip_int");
+my @authlist_ref = get_records_sql($dbh,"SELECT id,ip,dns_name FROM User_auth WHERE `ip_int`>0 AND `deleted`=0 ORDER BY ip_int");
 
 my %zones;
 
@@ -52,7 +52,7 @@ if ($dns_name) {
     $zones{$domain_name}{$default_name}=$ip;
     }
 
-my @dns_names=get_custom_records($dbh,"SELECT * FROM User_auth_alias WHERE auth_id=$row->{id} ORDER BY alias");
+my @dns_names=get_records_sql($dbh,"SELECT * FROM User_auth_alias WHERE auth_id=$row->{id} ORDER BY alias");
 foreach my $alias (@dns_names) {
         my $dns = $alias->{alias};
         $dns =~s/_/-/g;

+ 19 - 0
docs/cron/stat

@@ -0,0 +1,19 @@
+#under root
+
+#active scan network (with fping subnets before analyze)
+20 10,13,19 * * * root /usr/local/scripts/fetch_new_arp.pl 1
+
+#reconfigure nagios
+#16 * * * * root /etc/nagios/restart_nagios >/dev/null
+
+#refresh dnsmasq(dhcpd) dhcp server config's
+02 * * * * root /usr/local/scripts/update-dnsmasq
+
+#scan network
+09 * * * * root /usr/local/scripts/fetch_new_arp.pl
+
+#garbage trash
+01 0 * * * root /usr/local/scripts/garbage.pl
+
+#sync mikrotik cfg (need for update dhcp hostname)
+03 * * * * root /usr/local/scripts/sync_mikrotik.pl

+ 3 - 4
docs/dhcpd/dhcp-hook.sh

@@ -1,8 +1,7 @@
 #!/bin/bash
 
-pipe='/var/lib/dhcpd/dhcpd.log'
-
-#TYPE;IP;MAC;HOSTNAME
-echo "$1;$2;$3;$4" >>${pipe}
+time=$(date +%s)
+#TYPE;MAC;IP;HOSTNAME
+echo "$1;$3;$2;$4;${time}" >>/var/spool/dhcp-log.socket &
 
 exit

+ 0 - 276
docs/dhcpd/dhcp-log.pl

@@ -1,276 +0,0 @@
-#!/usr/bin/perl
-
-#
-# Copyright (C) Roman Dmitiriev, rnd@rajven.ru
-#
-
-use FindBin '$Bin';
-use lib "$Bin/";
-use Data::Dumper;
-use Rstat::config;
-use Rstat::main;
-use Rstat::mysql;
-use Rstat::net_utils;
-use strict;
-use warnings;
-use Getopt::Long;
-use Proc::Daemon;
-use Cwd;
-use Net::Netmask;
-use File::Spec::Functions;
-use File::Copy qw(move);
-use Text::Iconv;
-
-my $pf = '/var/run/dhcp-log.pid';
-my $log='/var/lib/dhcpd/dhcpd.log';
-
-my $daemon = Proc::Daemon->new(
-        pid_file => $pf,
-        work_dir => $HOME_DIR
-);
-
-# are you running?  Returns 0 if not.
-my $pid = $daemon->Status($pf);
-
-my $daemonize = 1;
-
-GetOptions(
-    'daemon!' => \$daemonize,
-    "help"    => \&usage,
-    "reload"  => \&reload,
-    "restart" => \&restart,
-    "start"   => \&run,
-    "status"  => \&status,
-    "stop"    => \&stop
-) or &usage;
-
-exit(0);
-
-sub stop {
-        if ($pid) {
-                print "Stopping pid $pid...";
-                if ($daemon->Kill_Daemon($pf)) {
-                        print "Successfully stopped.\n";
-                } else {
-                        print "Could not find $pid.  Was it running?\n";
-                }
-         } else {
-                print "Not running, nothing to stop.\n";
-         }
-}
-
-sub status {
-        if ($pid) {
-                print "Running with pid $pid.\n";
-        } else {
-                print "Not running.\n";
-        }
-}
-
-sub run {
-if (!$pid) {
-    print "Starting...";
-    if ($daemonize) {
-        # when Init happens, everything under it runs in the child process.
-        # this is important when dealing with file handles, due to the fact
-        # Proc::Daemon shuts down all open file handles when Init happens.
-        # Keep this in mind when laying out your program, particularly if
-        # you use filehandles.
-        $daemon->Init;
-        }
-
-    setpriority(0,0,19);
-
-    my $converter = Text::Iconv->new("cp866", "utf8");
-
-
-    while (1) {
-        eval {
-        # Create new database handle. If we can't connect, die()
-        system('touch "'.$log.'"');
-        my $hdb = DBI->connect("dbi:mysql:database=$DBNAME;host=$DBHOST","$DBUSER","$DBPASS");
-        if ( !defined $hdb ) { die "Cannot connect to mySQL server: $DBI::errstr\n"; }
-
-        open(DHCP, "tail -n 0 -F $log |") || die "$log not found!";
-        while (my $logline = <DHCP>) {
-            next unless defined $logline;
-            chomp($logline);
-            log_info("GET CLIENT REQUEST: $logline");
-            my ($type,$ip,$mac,$hostname) = split (/\;/, $logline);
-            next if (!$type);
-            next if ($type!~/(old|add|del)/i);
-
-	    if (time()-$last_refresh_config>=60) { init_option($hdb); }
-
-	    my $client_hostname='UNDEFINED';
-            if ($hostname and $hostname!~/undef/i) { $client_hostname=$hostname; }
-
-            my $auth_network = $office_networks->match_string($ip);
-	    if (!$auth_network) {
-		log_error("Unknown network in dhcp request! IP: $ip");
-		next;
-		}
-
-            my $utf_client_hostname = $converter->convert($client_hostname);
-            $mac=mac_splitted(isc_mac_simplify($mac));
-
-            log_debug(uc($type).">>");
-            log_debug("MAC:      ".$mac);
-            log_debug("IP:       ".$ip);
-            log_debug("HOSTNAME: ".$client_hostname);
-            log_debug("UTF8 HOSTNAME: ".$utf_client_hostname);
-            log_debug("END GET");
-
-            my $ip_aton=StrToIp($ip);
-            $mac=mac_splitted($mac);
-            if ($type eq 'add') {
-                log_info("Check for new auth...");
-                resurrection_auth($hdb,$ip,$mac,$type);
-                }
-
-            my $auth_record = get_custom_record($hdb,'SELECT * FROM User_auth WHERE ip="'.$ip.'" and mac="'.$mac.'" and deleted=0 ORDER BY last_found DESC');
-            my $auth_id = $auth_record->{id};
-
-	    my $ad_zone = get_option($hdb,33);
-	    my $ad_dns = get_option($hdb,3);
-	    $update_hostname_from_dhcp = get_option($hdb,46) || 0;
-	    my $subnets_dhcp = get_subnets_ref($hdb);
-	    my $enable_ad_dns_update = ($ad_zone and $ad_dns and $update_hostname_from_dhcp);
-
-            log_debug("Subnet: $auth_network");
-            log_debug("DNS update flags - zone: $ad_zone dns: $ad_dns config: $update_hostname_from_dhcp subnet: $subnets_dhcp->{$auth_network}->{dhcp_update_hostname}");
-
-            my $maybe_update_dns=(($type=~/add/i or $type=~/old/i) and $utf_client_hostname and $utf_client_hostname !~/UNDEFINED/i and $enable_ad_dns_update and $subnets_dhcp->{$auth_network}->{dhcp_update_hostname});
-
-            if ($maybe_update_dns) {
-                log_debug("DNS update enabled.");
-		#update dns block
-	        my $fqdn_static;
-	        if ($auth_record->{dns_name}) {
-	                $fqdn_static=lc($auth_record->{dns_name});
-        		if ($fqdn_static!~/$ad_zone$/i) {
-        		    $fqdn_static=~s/\.$//;
-        		    $fqdn_static=lc($fqdn_static.'.'.$ad_zone);
-        		    }
-        		}
-        	my $fqdn=lc(trim($utf_client_hostname));
-        	if ($fqdn!~/$ad_zone$/i) {
-        		$fqdn=~s/\.$//;
-        		$fqdn=lc($fqdn.'.'.$ad_zone);
-        		}
-                db_log_debug($hdb,"FOUND Auth_id: $auth_id dns_name: $fqdn_static dhcp_hostname: $fqdn");
-                #check exists static dns name
-                my $static_exists = 0;
-                my $dynamic_exists = 0;
-                my $static_ok = 0;
-                my $dynamic_ok = 0;
-                my $static_ref;
-                my $dynamic_ref;
-                if ($fqdn_static ne '') {
-                        my @dns_record=ResolveNames($fqdn_static);
-                        $static_exists = (scalar @dns_record>0);
-                        if ($static_exists) {
-                            $static_ref = join(' ',@dns_record);
-                            foreach my $dns_a (@dns_record) {
-                                if ($dns_a=~/^$ip$/) { $static_ok = $dns_a; }
-                                }
-                            }
-                        } else { $static_ok = 1; }
-                if ($fqdn ne '') {
-                        my @dns_record=ResolveNames($fqdn);
-                        $dynamic_exists = (scalar @dns_record>0);
-                        if ($dynamic_exists) {
-                            $dynamic_ref = join(' ',@dns_record);
-                            foreach my $dns_a (@dns_record) {
-                                if ($dns_a=~/^$ip$/) { $dynamic_ok = $dns_a; }
-                                }
-                            }
-                        }
-		if ($fqdn_static ne '') {
-		        if (!$static_ok) {
-		            db_log_info($hdb,"Static record mismatch! Expected $fqdn_static => $ip, recivied: $static_ref"); 
-                            if (!$static_exists) {
-				db_log_info($hdb,"Static dns hostname defined but not found. Create it ($fqdn_static => $ip)!");
-				update_ad_hostname($fqdn_static,$ip,$ad_zone,$ad_dns);
-				}
-		            } else { db_log_debug($hdb,"Static record for $fqdn_static [$static_ok] correct."); }
-		        }
-		if ($fqdn ne '' and $dynamic_ok ne '') { db_log_debug($hdb,"Dynamic record for $fqdn [$dynamic_ok] correct. No changes required."); }
-		if ($fqdn ne '' and !$dynamic_ok) {
-		        #log only to file!!!
-			log_error($hdb,"Dynamic record mismatch! Expected: $fqdn => $ip, recivied: $dynamic_ref. Checking the status.");
-		        #check exists hostname
-			my $another_hostname_exists = 0;
-			my $hostname_filter = ' LOWER(dns_name)="'.lc($utf_client_hostname).'"';
-			if ($fqdn_static ne '' and $fqdn !~/$fqdn_static/) { $hostname_filter = $hostname_filter . ' or LOWER(dns_name)="'.lc($auth_record->{dns_name}).'"'; }
-			#check exists another records with some static hostname
-    	        	my $name_record = get_custom_record($hdb,'SELECT * FROM User_auth WHERE id<>'.$auth_id.' and deleted=0 and ('.$hostname_filter.') ORDER BY last_found DESC');
-        		if ($name_record->{id}) { $another_hostname_exists = 1; }
-			if (!$another_hostname_exists) {
-			    if ($fqdn_static and $fqdn_static ne '') {
-	        		    if ($fqdn_static!~/$fqdn/) {
-				        db_log_info($hdb,"Hostname from dhcp request $fqdn differs from static dns hostanme $fqdn_static. Ignore dynamic binding!");
-#				        update_ad_hostname($fqdn,$ip,$ad_zone,$ad_dns);
-                                        }
-				    } else {
-				    db_log_info($hdb,"Static dns hostname not defined. Create dns record by dhcp request. $fqdn => $ip");
-				    update_ad_hostname($fqdn,$ip,$ad_zone,$ad_dns);
-				    }
-			    } else {
-			    db_log_error($hdb,"Found another record with some hostname id: $name_record->{id} ip: $name_record->{ip} hostname: $name_record->{dns_hostname}. Skip update.");
-			    }
-			}
-                #end update dns block
-            	} else {
-            	db_log_debug($hdb,"FOUND Auth_id: $auth_id");
-            	}
-
-            if ($type=~/add/i and $utf_client_hostname and $utf_client_hostname !~/UNDEFINED/i) {
-        	my $auth_rec;
-        	$auth_rec->{dhcp_hostname} = $utf_client_hostname;
-                update_record($hdb,'User_auth',$auth_rec,"id=$auth_id");
-                }
-
-            if ($hotspot_networks->match_string($ip) and $ignore_hotspot_dhcp_log) { next; }
-
-            if ($ignore_update_dhcp_event and $type=~/old/i) { next; }
-
-            if ($type=~/(old|del)/i) {
-                        my $auth_rec;
-                        $auth_rec->{dhcp_action}=$type;
-                        $auth_rec->{dhcp_time}=GetNowTime();
-                        update_record($hdb,'User_auth',$auth_rec,"id=$auth_id");
-                        }
-
-	    my $dhcp_log;
-	    $dhcp_log->{auth_id} = $auth_id;
-	    $dhcp_log->{ip} = $ip;
-	    $dhcp_log->{ip_int} = $ip_aton;
-	    $dhcp_log->{mac} = $mac;
-	    $dhcp_log->{action} = $type;
-	    insert_record($hdb,'dhcp_log',$dhcp_log);
-
-            }
-
-	close DHCP;
-        };
-        if ($@) { log_error("Exception found: $@"); }
-        }
-    } else {
-        print "Already Running with pid $pid\n";
-    }
-}
-
-sub usage {
-    print "usage: dhcp-log.pl (start|stop|status|restart)\n";
-    exit(0);
-}
-
-sub reload {
-    print "reload process not implemented.\n";
-}
-
-sub restart {
-    stop;
-    run;
-}

+ 2 - 2
docs/dhcpd/print-dhcpd.pl

@@ -33,7 +33,7 @@ if ($address=~/inet\s+(.*)\s+brd/i) {
     }
 }
 
-my @subnets=get_custom_records($dbh,'SELECT * FROM subnets WHERE dhcp=1 and office=1 and vpn=0 and hotspot=0 ORDER BY ip_int_start');
+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});
 $dhcp_networks->add_string($subnet->{subnet});
@@ -61,7 +61,7 @@ if (! -d "$new_dir" ) { mkpath($new_dir); }
 #get userid list
 my $sSQL="SELECT id,ip,ip_int,mac,comments FROM User_auth where dhcp=1 and deleted=0 and user_id<>$hotspot_user_id and user_id<>$default_user_id ORDER by ip_int";
 
-my @users = get_custom_records($dbh,$sSQL);
+my @users = get_records_sql($dbh,$sSQL);
 
 foreach my $row (@users) {
 next if (!$row);

+ 1 - 2
docs/fix_net.pl

@@ -38,8 +38,7 @@ my $net=GetDhcpRange($ip);
 print "Auth id: $id Found network: $ip\n";
 print "NETWORK: $net->{network}\nBROADCAST: $net->{broadcast}\nMASK: $net->{mask}\n";
 my $ip_aton=StrToIp($net->{network});
-my $ip_aton_end=StrToIp($net->{broadcast});
-push(@batch_sql,"Update User_auth set ip_int=".$ip_aton.", ip_int_end=".$ip_aton_end." where id=".$id);
+push(@batch_sql,"Update User_auth set ip_int=".$ip_aton." where id=".$id);
 }
 
 

+ 117 - 119
docs/iptables/parse_ulog.pl

@@ -4,9 +4,6 @@
 # Copyright (C) Roman Dmitiriev, rnd@rajven.ru
 #
 
-#-A FORWARD -j ULOG --ulog-prefix "FORWARD" --ulog-cprange 48 --ulog-qthreshold 50
-#-A FORWARD -j USERS
-
 use FindBin '$Bin';
 use lib "$Bin/";
 use strict;
@@ -23,22 +20,37 @@ use Rstat::mysql;
 
 setpriority(0,0,19);
 
+
 my $router_id;
-my %fields=('device_name'=>'1', 'id'=>'1');
-my $gate = get_record($dbh,'devices',\%fields,"deleted=0 and internet_gateway=1 and vendor_id=19 and device_name='".$HOSTNAME."'");
-if (!$gate) { exit 0; }
-my $router_name=$gate->{device_name};
-$router_id = $gate->{id};
+if (scalar @ARGV>1) { $router_id=shift(@ARGV); } else { $router_id=$ARGV[0]; }
+
+if (!$router_id) {
+    db_log_error($dbh,"Router id not defined! Bye...");
+    exit 110;
+    }
+
+my $timeshift = get_option($dbh,55)*60;
 
-db_log_debug($dbh,"Import traffic from router id: $router_id start") if ($debug);
+db_log_debug($dbh,"Import traffic from router id: $router_id start. Timestep $timeshift sec.") if ($debug);
+
+my %stats;
+$stats{pkt}{all}=0;
+$stats{pkt}{user}=0;
+$stats{pkt}{user_in}=0;
+$stats{pkt}{user_out}=0;
+$stats{pkt}{free}=0;
+$stats{pkt}{unknown}=0;
+
+$stats{line}{all}=0;
+$stats{line}{user}=0;
+$stats{line}{free}=0;
+$stats{line}{unknown}=0;
 
 # net objects
 my $users = new Net::Patricia;
 
 InitSubnets();
 
-my $dbt = init_traf_db();
-
 #get userid list
 my $user_auth_list = $dbh->prepare( "SELECT id,ip,user_id,save_traf FROM User_auth where deleted=0 ORDER by user_id,ip" );
 if ( !defined $user_auth_list ) { die "Cannot prepare statement: $DBI::errstr\n"; }
@@ -51,16 +63,16 @@ $user_auth_list->finish();
 
 my %user_stats;
 
-print "\nUser auth ip:\n" if ($debug);
 foreach my $row (@$authlist_ref) {
 $users->add_string($row->[1],$row->[0]);
-print "ip: $row->[1] auth_id: $row->[0]\n" if ($debug);
 $user_stats{$row->[0]}{net}=$row->[1];
 $user_stats{$row->[0]}{id}=$row->[0];
 $user_stats{$row->[0]}{user_id}=$row->[2];
 $user_stats{$row->[0]}{save_traf}=$row->[3];
 $user_stats{$row->[0]}{in}=0;
 $user_stats{$row->[0]}{out}=0;
+$user_stats{$row->[0]}{pkt_in}=0;
+$user_stats{$row->[0]}{pkt_out}=0;
 }
 
 my $last_time = localtime();
@@ -75,38 +87,33 @@ my @batch_sql_traf=();
 open(FH,"-");
 
 while (my $line=<FH>) {
+$stats{line}{all}++;
 #1555573194.980;17   ;     77.243.0.12;   172.20.178.71;    53; 43432;       1;     134;     2;     1
 $line=~s/\s+//g;
+
 my ($l_time,$l_proto,$l_src_ip,$l_src_port,$l_dst_ip,$l_dst_port,$l_packets,$l_bytes,$l_input,$l_output,$l_prefix) = split(/ /,$line);
+$stats{pkt}{all}+=$l_packets;
 
-next if (!$l_time);
-next if ($l_src_ip eq '0.0.0.0');
-next if ($l_dst_ip eq '0.0.0.0');
-next if ($l_src_ip eq '255.255.255.255');
-next if ($l_dst_ip eq '255.255.255.255');
-next if ($l_prefix !~ /FORWARD/i);
-next if ($Special_Nets->match_string($l_src_ip) or $Special_Nets->match_string($l_dst_ip));
+if (!$l_time) { $stats{line}{illegal}++; $stats{pkt}{illegal}+=$l_packets; next; }
+if ($l_src_ip eq '0.0.0.0') { $stats{line}{illegal}++; $stats{pkt}{illegal}+=$l_packets; next; }
+if ($l_dst_ip eq '0.0.0.0') { $stats{line}{illegal}++; $stats{pkt}{illegal}+=$l_packets; next; }
+if ($l_src_ip eq '255.255.255.255') { $stats{line}{illegal}++; $stats{pkt}{illegal}+=$l_packets; next; }
+if ($l_dst_ip eq '255.255.255.255') { $stats{line}{illegal}++; $stats{pkt}{illegal}+=$l_packets; next; }
+if ($Special_Nets->match_string($l_src_ip) or $Special_Nets->match_string($l_dst_ip)) { $stats{line}{illegal}++; $stats{pkt}{illegal}+=$l_packets; next; }
 
 #unknown networks
-if (!$office_networks->match_string($l_src_ip) and !$office_networks->match_string($l_dst_ip)) {
-    print "Unknown packet! src: $l_src_ip dst: $l_dst_ip \n";
-    next;
-    }
+if (!$office_networks->match_string($l_src_ip) and !$office_networks->match_string($l_dst_ip)) { $stats{line}{illegal}++; $stats{pkt}{illegal}+=$l_packets; next; }
 
 #local forward
-if ($office_networks->match_string($l_src_ip) and $office_networks->match_string($l_dst_ip)) { next; }
+if ($office_networks->match_string($l_src_ip) and $office_networks->match_string($l_dst_ip)) { $stats{line}{free}++; $stats{line}{free}+=$l_packets; next; }
 
 #free forward
-if ($office_networks->match_string($l_src_ip) and $free_networks->match_string($l_dst_ip)) { next; }
-if ($free_networks->match_string($l_src_ip) and $office_networks->match_string($l_dst_ip)) { next; }
-
-print "Flow: $line\n"  if ($debug);
+if ($office_networks->match_string($l_src_ip) and $free_networks->match_string($l_dst_ip)) { $stats{line}{free}++; $stats{line}{free}+=$l_packets; next; }
+if ($free_networks->match_string($l_src_ip) and $office_networks->match_string($l_dst_ip)) { $stats{line}{free}++; $stats{line}{free}+=$l_packets; next; }
 
 my $l_src_ip_aton=StrToIp($l_src_ip);
 my $l_dst_ip_aton=StrToIp($l_dst_ip);
 
-if ($l_time ne $l_time+0) { $l_time=time-600; }
-
 $last_time = $l_time;
 my ($sec,$min,$hour,$day,$month,$year,$zone) = (localtime($l_time))[0,1,2,3,4,5];
 $month++;
@@ -126,31 +133,48 @@ if ($office_networks->match_string($l_src_ip)) {
         $user_stats{$out_user}{out} += $l_bytes;
         $user_stats{$out_user}{dbtime} = $minute_date;
         $user_stats{$out_user}{htime} = $hour_date;
-        print "OUT: $out_user + $l_bytes sum: $user_stats{$out_user}{out}\n"  if ($debug);
+        $user_stats{$out_user}{pkt_out} +=$l_packets;
         $user_found = 1;
+        $stats{line}{user}++;
+        $stats{pkt}{user_out}+=$l_packets;
         if ($save_detail and $user_stats{$out_user}{save_traf}) {
-            my $dSQL="INSERT INTO Traffic_detail (auth_id,router_id,timestamp,proto,src_ip,dst_ip,src_port,dst_port,bytes) VALUES($out_user,$router_id,$dbtime,'$l_proto',$l_src_ip_aton,$l_dst_ip_aton,'$l_src_port','$l_dst_port','$l_bytes')";
+            my $dSQL="INSERT INTO Traffic_detail (auth_id,router_id,timestamp,proto,src_ip,dst_ip,src_port,dst_port,bytes,pkt) VALUES($out_user,$router_id,$dbtime,'$l_proto',$l_src_ip_aton,$l_dst_ip_aton,'$l_src_port','$l_dst_port','$l_bytes','$l_packets')";
             push (@batch_sql_traf,$dSQL);
             }
         }
     }
+
 if ($office_networks->match_string($l_dst_ip)) {
     my $in_user = $users->match_string($l_dst_ip);
     if ($in_user) {
         $user_stats{$in_user}{in} += $l_bytes;
         $user_stats{$in_user}{dbtime} = $minute_date;
         $user_stats{$in_user}{htime} = $hour_date;
-        print "IN: $in_user + $l_bytes sum: $user_stats{$in_user}{in}\n"  if ($debug);
+        $user_stats{$in_user}{pkt_in} +=$l_packets;
+        $stats{line}{user}++;
+        $stats{pkt}{user_in}+=$l_packets;
         $user_found = 1;
         if ($save_detail and $user_stats{$in_user}{save_traf}) {
-            my $dSQL="INSERT INTO Traffic_detail (auth_id,router_id,timestamp,proto,src_ip,dst_ip,src_port,dst_port,bytes) VALUES($in_user,$router_id,$dbtime,'$l_proto',$l_src_ip_aton,$l_dst_ip_aton,'$l_src_port','$l_dst_port','$l_bytes')";
+            my $dSQL="INSERT INTO Traffic_detail (auth_id,router_id,timestamp,proto,src_ip,dst_ip,src_port,dst_port,bytes,pkt) VALUES($in_user,$router_id,$dbtime,'$l_proto',$l_src_ip_aton,$l_dst_ip_aton,'$l_src_port','$l_dst_port','$l_bytes','$l_packets')";
             push (@batch_sql_traf,$dSQL);
             }
         }
     }
 
-next if ($users->match_string($l_src_ip) or $users->match_string($l_dst_ip));
-next if (!$add_unknown_user);
+if (scalar(@batch_sql_traf)>10000) {
+    $dbh->{AutoCommit} = 0;
+    my $f_sth;
+    foreach my $sSQL(@batch_sql_traf) {
+        $f_sth = $dbh->prepare($sSQL);
+        $f_sth->execute;
+        }
+    $f_sth->finish;
+    $dbh->{AutoCommit} = 1;
+    @batch_sql_traf=();
+    }
+
+if ($users->match_string($l_src_ip) or $users->match_string($l_dst_ip)) { next; }
+if (!$add_unknown_user) { $stats{line}{illegal}++; $stats{pkt}{illegal}+=$l_packets; next; }
 
 # find user ip
 my $user_ip;
@@ -161,49 +185,31 @@ undef $user_ip;
 if (!$office_networks->match_string($l_dst_ip) and $office_networks->match_string($l_src_ip)) { $user_ip = $l_src_ip; }
 
 #skip unknown packet
-if (!$user_ip) { next; }
+if (!$user_ip) { $stats{line}{illegal}++; $stats{pkt}{illegal}+=$l_packets; next; }
+
+$stats{line}{user}++;
 
 $user_ip_aton=StrToIp($user_ip);
 
-db_log_warning($dbh,"New ip $user_ip added by netflow!");
+#new user
+my $auth_id=new_auth($dbh,$user_ip);
+next if (!$auth_id);
 
-#default user
-my $new_user_id=get_new_user_id($dbh,$user_ip);
+db_log_warning($dbh,"New ip $user_ip added by netflow!");
 
-my $insert_auth;
-$insert_auth->{ip}=$user_ip;
-$insert_auth->{ip_int}=$user_ip_aton;
-$insert_auth->{ip_int_end}=$user_ip_aton;
-$insert_auth->{user_id}=$new_user_id;
-$insert_auth->{enabled}="0";
-$insert_auth->{deleted}="0";
-$insert_auth->{save_traf}="$save_detail";
-insert_record($dbh,'User_auth',$insert_auth);
+my $new_user = get_record_sql($dbh,"SELECT * FROM User_auth WHERE id=$auth_id");
 
-my $sSQL="SELECT id,ip,user_id FROM User_auth where ip_int=\"$user_ip_aton\" and deleted=0";
-my $get_user_auth = $dbh->prepare($sSQL);
-if ( !defined $get_user_auth ) { die "Cannot prepare statement: $DBI::errstr\n"; }
-$get_user_auth->execute;
+$users->add_string($user_ip,$auth_id);
+$user_stats{$auth_id}{net}=$user_ip;
+$user_stats{$auth_id}{user_id}=$new_user->{user_id};
+$user_stats{$auth_id}{id}=$auth_id;
+$user_stats{$auth_id}{in}=0;
+$user_stats{$auth_id}{out}=0;
+$user_stats{$auth_id}{pkt_in}=0;
+$user_stats{$auth_id}{pkt_out}=0;
 
-# user auth list
-my $new_user = $get_user_auth->fetchall_arrayref();
-$get_user_auth->finish();
-
-my $auth_id;
-foreach my $row (@$new_user) {
-        next if (!$row->[0]);
-        $auth_id = $row->[0];
-        $users->add_string($user_ip,$auth_id);
-        $user_stats{$auth_id}{net}=$user_ip;
-        $user_stats{$auth_id}{user_id}=$row->[2];
-        $user_stats{$auth_id}{id}=$auth_id;
-        $user_stats{$auth_id}{in}=0;
-        $user_stats{$auth_id}{out}=0;
-        db_log_info($dbh,"Added user_auth id: $auth_id ip: $user_ip user_id: $row->[2]");
-        last;
-        }
+db_log_info($dbh,"Added user_auth id: $auth_id ip: $user_ip user_id: $new_user->{user_id}");
 
-print "ERROR add user_auth!\n" if (!$users->match_string($user_ip));
 if ($auth_id) {
         if ($save_detail) {
             my $dSQL="INSERT INTO Traffic_detail (auth_id,router_id,timestamp,proto,src_ip,dst_ip,src_port,dst_port,bytes) VALUES($auth_id,$router_id,$dbtime,'$l_proto',$l_src_ip_aton,$l_dst_ip_aton,'$l_src_port','$l_dst_port','$l_bytes')";
@@ -211,9 +217,11 @@ if ($auth_id) {
             }
         if ($l_src_ip eq $user_ip) {
             $user_stats{$auth_id}{out} += $l_bytes;
+            $user_stats{$auth_id}{pkt_out} += $l_bytes;
             }
         if ($l_dst_ip eq $user_ip) {
             $user_stats{$auth_id}{in} += $l_bytes;
+            $user_stats{$auth_id}{pkt_in} += $l_bytes;
             }
         $user_stats{$auth_id}{dbtime} = $minute_date;
         $user_stats{$auth_id}{htime} = $hour_date;
@@ -223,73 +231,63 @@ if ($auth_id) {
         }
 }
 
+#start hour
 my ($min,$hour,$day,$month,$year) = (localtime($last_time))[1,2,3,4,5];
-$month ++;
-$year += 1900;
-
-######## user statistics
+my $hour_date1 = $dbh->quote(sprintf "%04d-%02d-%02d %02d:00:00",$year+1900,$month+1,$day,$hour);
+my $flow_date = $dbh->quote(sprintf "%04d-%02d-%02d %02d:%02d:00",$year+1900,$month+1,$day,$hour,$min);
 
-print "Update traffic table...\n"  if ($debug);
+#end hour
+($min,$hour,$day,$month,$year) = (localtime($last_time+3600))[1,2,3,4,5];
+my $hour_date2 = $dbh->quote(sprintf "%04d-%02d-%02d %02d:00:00",$year+1900,$month+1,$day,$hour);
 
 # update database
 foreach my $row (keys %user_stats) {
-next if ($user_stats{$row}{in} + $user_stats{$row}{out} <= 0);
-# insert row
-my $statSQL="INSERT INTO User_traffic (timestamp,auth_id,router_id,byte_in,byte_out,byte_proxy) VALUES($user_stats{$row}{dbtime},$user_stats{$row}{id},$router_id,$user_stats{$row}{in},$user_stats{$row}{out},'0')";
-print "$statSQL\n"  if ($debug);
-push (@batch_sql_traf,$statSQL);
-}
+next if (!$user_stats{$row}{htime});
 
-### hour stats
-print "Update hourly stats table...\n"  if ($debug);
+#current stats
 
-# get current stats
-my $sql = "Select auth_id, SUM(byte_in),SUM(byte_out) from User_stats WHERE ((YEAR(timestamp)=$year) and (MONTH(timestamp)=$month) and (DAY(timestamp)=$day) and (HOUR(timestamp)=$hour) and router_id=$router_id) Group by auth_id order by auth_id";
-my $fth = $dbt->prepare($sql);
-$fth->execute;
+my $tSQL="INSERT INTO User_stats_full (timestamp,auth_id,router_id,byte_in,byte_out,pkt_in,pkt_out,step) VALUES($flow_date,'$user_stats{$row}{id}','$router_id','$user_stats{$row}{in}','$user_stats{$row}{out}','$user_stats{$row}{pkt_in}','$user_stats{$row}{pkt_out}','$timeshift')";
+push (@batch_sql_traf,$tSQL);
 
-my $hour_stats=$fth->fetchall_arrayref();
-$fth->finish;
+#hour stats
 
-# update database
-foreach my $row (keys %user_stats) {
-next if (!$user_stats{$row}{htime});
-my $found = 0;
-### find current statistics
-foreach my $row2 (@$hour_stats) {
-    my ($f_s,$f_id,$f_in,$f_out) = @$row2;
-    if ($user_stats{$row}{id} eq $f_id) {
-        $f_in += $user_stats{$row}{in};
-        $f_out += $user_stats{$row}{out};
-        $found = 1;
-        my $ssql="UPDATE User_stats set byte_in='$f_in', byte_out='$f_out' WHERE (id=$f_s and router_id=$router_id)";
-        my $res = $dbt->do($ssql);
-        unless ($res) {
-            my $dSQL="INSERT INTO User_stats (timestamp,auth_id,router_id,byte_in,byte_out) VALUES($user_stats{$row}{htime},'$user_stats{$row}{id}','$router_id','$f_in','$f_out')";
-            push (@batch_sql_traf,$dSQL);
-            }
-        last;
-        }
+# get current stats
+my $sql = "SELECT id, byte_in, byte_out FROM User_stats
+WHERE `timestamp`>=$hour_date1 AND `timestamp`<$hour_date2 AND router_id=$router_id AND auth_id=$user_stats{$row}{id}";
+my $hour_stat = get_record_sql($dbh,$sql);
+if (!$hour_stat) {
+    my $dSQL="INSERT INTO User_stats (timestamp,auth_id,router_id,byte_in,byte_out,pkt_in,pkt_out) VALUES($user_stats{$row}{htime},'$user_stats{$row}{id}','$router_id','$user_stats{$row}{in}','$user_stats{$row}{out}','$user_stats{$row}{pkt_in}','$user_stats{$row}{pkt_out}')";
+    push (@batch_sql_traf,$dSQL);
+    next;
     }
-next if ($found);
-my $dSQL="INSERT INTO User_stats (timestamp,auth_id,router_id,byte_in,byte_out) VALUES($user_stats{$row}{htime},'$user_stats{$row}{id}','$router_id','$user_stats{$row}{in}','$user_stats{$row}{out}')";
-push (@batch_sql_traf,$dSQL);
+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{$row}{in};
+$hour_stat->{byte_out} += $user_stats{$row}{out};
+my $ssql="UPDATE User_stats SET byte_in='".$hour_stat->{byte_in}."', byte_out='".$hour_stat->{byte_out}."' WHERE id=".$hour_stat->{id};
+my $res = $dbh->do($ssql);
 }
 
-$dbt->{AutoCommit} = 0;
+$dbh->{AutoCommit} = 0;
 my $sth;
 foreach my $sSQL(@batch_sql_traf) {
-$sth = $dbt->prepare($sSQL);
+$sth = $dbh->prepare($sSQL);
 $sth->execute;
 }
 $sth->finish;
-$dbt->{AutoCommit} = 1;
+$dbh->{AutoCommit} = 1;
 
 db_log_debug($dbh,"Import traffic from router id: $router_id stop") if ($debug);
 
-$dbt->disconnect;
-$dbh->disconnect;
+db_log_verbose($dbh,"Recalc quotes started");
+recalc_quotes($dbh,$router_id);
+db_log_verbose($dbh,"Recalc quotes stopped");
 
-print "Done\n"  if ($debug);
+db_log_verbose($dbh,"router id: $router_id stop Traffic statistics, lines: all => $stats{line}{all}, user=> $stats{line}{user}, free => $stats{line}{free}, illegal=> $stats{line}{illegal}");
+db_log_verbose($dbh,sprintf("router id: %d stop Traffic speed, line/s: all => %.2f, user=> %.2f, free => %.2f, unknown=> %.2f", $router_id, $stats{line}{all}/$timeshift, $stats{line}{user}/$timeshift, $stats{line}{free}/$timeshift, $stats{line}{illegal}/$timeshift));
+db_log_verbose($dbh,"router id: $router_id stop Traffic statistics, pkt: all => $stats{pkt}{all}, user_in=> $stats{pkt}{user_in}, user_in=> $stats{pkt}{user_out}, free => $stats{pkt}{free}, illegal=> $stats{pkt}{illegal}");
+db_log_verbose($dbh,sprintf("router id: %d stop Traffic speed, pkt/s: all => %.2f, user_in=> %.2f, user_out=> %.2f, free => %.2f, unknown=> %.2f", $router_id, $stats{pkt}{all}/$timeshift, $stats{pkt}{user_in}/$timeshift, $stats{pkt}{user_out}/$timeshift, $stats{pkt}{free}/$timeshift, $stats{pkt}{illegal}/$timeshift));
+
+$dbh->disconnect;
 
 exit 0;

+ 14 - 10
docs/iptables/sync_iptables.pl

@@ -26,23 +26,27 @@ use open ":encoding(utf8)";
 
 $|=1;
 
-my %fields=('device_name'=>'1', 'wan_int'=>'1', 'lan_int'=>'1', 'queue_enabled'=>'1', 'connected_user_only'=>'1');
-
-my $gate = get_record($dbh,'devices',\%fields,"deleted=0 and internet_gateway=1 and vendor_id=19 and device_name='".$HOSTNAME."'");
+my $gate = get_record_sql($dbh,"SELECT * FROM devices WHERE device_type=2 and user_acl=1 and deleted=0 and vendor_id=19 and device_name='".$HOSTNAME."'");
 
 if (!$gate) { exit 0; }
 
 my $router_name=$gate->{device_name};
-my $wan_dev = $gate->{wan_int};
-my $lan_dev = $gate->{lan_int};
+my $router_ip=$gate->{ip};
 my $shaper_enabled = $gate->{queue_enabled};
 my $connected_users_only = $gate->{connected_user_only};
 
+my @lan_int=();
+my @wan_int=();
+
+my @l3_int = get_records_sql($dbh,'SELECT * FROM device_l3_interfaces WHERE device_id='.$gate->{'id'});
+foreach my $l3 (@l3_int) {
+    if ($l3->{'interface_type'} eq '0') { push(@lan_int,$l3->{'name'}); }
+    if ($l3->{'interface_type'} eq '1') { push(@wan_int,$l3->{'name'}); }
+}
+
 my $connected_users = new Net::Patricia;
 
 if ($connected_users_only) {
-    #lan interfaces
-    my @lan_int=split(/;/,$lan_dev);
     foreach my $int (@lan_int) {
     $int=trim($int);
     next if (!$int);
@@ -74,7 +78,7 @@ ORDER BY ip_int";
 
 my %users;
 
-my @authlist_ref = get_custom_records($dbh,$user_auth_sql);
+my @authlist_ref = get_records_sql($dbh,$user_auth_sql);
 
 #print Dumper(\@authlist_ref);
 foreach my $row (@authlist_ref) {
@@ -85,7 +89,7 @@ $users{'group_'.$row->{filter_group_id}}->{ips}{$row->{ip}}=1;
 }
 
 #get filters
-my @filter_list = get_custom_records($dbh,"SELECT id,name,proto,dst,dstport,action FROM Filter_list where type=0");
+my @filter_list = get_records_sql($dbh,"SELECT id,name,proto,dst,dstport,action FROM Filter_list where type=0");
 my %filters;
 foreach my $row (@filter_list) {
 $filters{$row->{id}}->{id}=$row->{id};
@@ -96,7 +100,7 @@ $filters{$row->{id}}->{action}=$row->{action};
 }
 
 #get groups
-my @group_list = get_custom_records($dbh,"SELECT group_id,filter_id,Group_filters.order FROM Group_filters ORDER BY Group_filters.group_id,Group_filters.order" );
+my @group_list = get_records_sql($dbh,"SELECT group_id,filter_id,Group_filters.order FROM Group_filters ORDER BY Group_filters.group_id,Group_filters.order" );
 my %group_filters;
 my %lists;
 my $index=0;

+ 9 - 0
docs/logrotate/dnsmasq

@@ -0,0 +1,9 @@
+/var/log/dnsmasq.log {
+    missingok
+    notifempty
+    copytruncate
+    sharedscripts
+    postrotate
+        /usr/bin/systemctl restart dnsmasq.service > /dev/null 2>&1 || true
+    endscript
+}

+ 9 - 0
docs/logrotate/iptraf-ng

@@ -0,0 +1,9 @@
+# Logrotate file for iptraf
+/var/log/iptraf-ng/*.log {
+	compress
+	delaycompress
+	missingok
+	notifempty
+	rotate 4
+	create 0600 root root
+}

+ 15 - 0
docs/logrotate/scripts

@@ -0,0 +1,15 @@
+/var/log/scripts/*.log {
+        rotate 7
+        missingok
+        notifempty
+        compress
+        copytruncate
+}
+
+/var/log/remote/messages.log {
+    rotate 7
+    missingok
+    notifempty
+    compress
+    copytruncate
+}

+ 351 - 0
docs/mysql/stat_extra.sql

@@ -0,0 +1,351 @@
+
+--
+-- Индексы сохранённых таблиц
+--
+
+--
+-- Индексы таблицы `building`
+--
+ALTER TABLE `building`
+  ADD PRIMARY KEY (`id`);
+
+--
+-- Индексы таблицы `config`
+--
+ALTER TABLE `config`
+  ADD PRIMARY KEY (`id`),
+  ADD KEY `option` (`option_id`);
+
+--
+-- Индексы таблицы `config_options`
+--
+ALTER TABLE `config_options`
+  ADD PRIMARY KEY (`id`);
+
+--
+-- Индексы таблицы `connections`
+--
+ALTER TABLE `connections`
+  ADD PRIMARY KEY (`id`),
+  ADD KEY `auth_id` (`auth_id`),
+  ADD KEY `device_id` (`device_id`,`port_id`);
+
+--
+-- Индексы таблицы `Customers`
+--
+ALTER TABLE `Customers`
+  ADD PRIMARY KEY (`id`);
+
+--
+-- Индексы таблицы `devices`
+--
+ALTER TABLE `devices`
+  ADD PRIMARY KEY (`id`),
+  ADD KEY `device_model_id` (`device_model`),
+  ADD KEY `ip` (`ip`);
+
+--
+-- Индексы таблицы `device_ports`
+--
+ALTER TABLE `device_ports`
+  ADD PRIMARY KEY (`id`),
+  ADD KEY `device_id` (`device_id`),
+  ADD KEY `port` (`port`),
+  ADD KEY `target_port_id` (`target_port_id`);
+
+--
+-- Индексы таблицы `dhcp_log`
+--
+ALTER TABLE `dhcp_log`
+  ADD PRIMARY KEY (`id`),
+  ADD KEY `timestamp` (`timestamp`);
+
+--
+-- Индексы таблицы `Filter_list`
+--
+ALTER TABLE `Filter_list`
+  ADD PRIMARY KEY (`id`),
+  ADD KEY `Name` (`name`);
+
+--
+-- Индексы таблицы `Group_filters`
+--
+ALTER TABLE `Group_filters`
+  ADD PRIMARY KEY (`id`),
+  ADD KEY `GroupId` (`group_id`,`filter_id`);
+
+--
+-- Индексы таблицы `Group_list`
+--
+ALTER TABLE `Group_list`
+  ADD PRIMARY KEY (`id`);
+
+--
+-- Индексы таблицы `mac_history`
+--
+ALTER TABLE `mac_history`
+  ADD PRIMARY KEY (`id`),
+  ADD KEY `mac` (`mac`,`timestamp`),
+  ADD KEY `ip` (`ip`,`timestamp`);
+
+--
+-- Индексы таблицы `mac_vendors`
+--
+ALTER TABLE `mac_vendors`
+  ADD PRIMARY KEY (`id`),
+  ADD UNIQUE KEY `oui` (`oui`);
+
+--
+-- Индексы таблицы `OU`
+--
+ALTER TABLE `OU`
+  ADD PRIMARY KEY (`id`);
+
+--
+-- Индексы таблицы `Queue_list`
+--
+ALTER TABLE `Queue_list`
+  ADD PRIMARY KEY (`id`),
+  ADD UNIQUE KEY `id` (`id`);
+
+--
+-- Индексы таблицы `remote_syslog`
+--
+ALTER TABLE `remote_syslog`
+  ADD PRIMARY KEY (`id`),
+  ADD KEY `date` (`date`,`device_id`,`ip`);
+ALTER TABLE `remote_syslog` ADD FULLTEXT KEY `message` (`message`);
+
+--
+-- Индексы таблицы `subnets`
+--
+ALTER TABLE `subnets`
+  ADD PRIMARY KEY (`id`),
+  ADD KEY `ip_int_start` (`ip_int_start`,`ip_int_stop`),
+  ADD KEY `dhcp` (`dhcp`,`office`,`hotspot`,`static`);
+
+--
+-- Индексы таблицы `syslog`
+--
+ALTER TABLE `syslog`
+  ADD PRIMARY KEY (`id`),
+  ADD KEY `timestamp` (`timestamp`,`auth_id`,`customer`,`level`);
+ALTER TABLE `syslog` ADD FULLTEXT KEY `message` (`message`);
+ALTER TABLE `syslog` ADD FULLTEXT KEY `customer` (`customer`);
+
+--
+-- Индексы таблицы `Traffic_detail`
+--
+ALTER TABLE `Traffic_detail`
+  ADD PRIMARY KEY (`id`),
+  ADD KEY `src` (`auth_id`,`timestamp`,`router_id`,`src_ip`),
+  ADD KEY `dst` (`auth_id`,`timestamp`,`router_id`,`dst_ip`);
+
+--
+-- Индексы таблицы `Unknown_mac`
+--
+ALTER TABLE `Unknown_mac`
+  ADD PRIMARY KEY (`id`),
+  ADD KEY `mac` (`mac`,`timestamp`);
+
+--
+-- Индексы таблицы `User_auth`
+--
+ALTER TABLE `User_auth`
+  ADD PRIMARY KEY (`id`),
+  ADD KEY `auth_index` (`id`,`user_id`,`ip_int`,`mac`,`ip`,`deleted`);
+
+--
+-- Индексы таблицы `User_auth_alias`
+--
+ALTER TABLE `User_auth_alias`
+  ADD PRIMARY KEY (`id`),
+  ADD KEY `auth_id` (`auth_id`);
+
+--
+-- Индексы таблицы `User_list`
+--
+ALTER TABLE `User_list`
+  ADD PRIMARY KEY (`id`),
+  ADD KEY `users` (`id`,`ou_id`,`enabled`,`blocked`,`deleted`);
+
+--
+-- Индексы таблицы `User_stats`
+--
+ALTER TABLE `User_stats`
+  ADD PRIMARY KEY (`id`),
+  ADD KEY `timestamp` (`timestamp`,`auth_id`,`router_id`);
+
+--
+-- Индексы таблицы `variables`
+--
+ALTER TABLE `variables`
+  ADD PRIMARY KEY (`id`),
+  ADD UNIQUE KEY `name` (`name`),
+  ADD KEY `clear_time` (`clear_time`,`created`);
+
+--
+-- Индексы таблицы `vendors`
+--
+ALTER TABLE `vendors`
+  ADD PRIMARY KEY (`id`);
+
+--
+-- AUTO_INCREMENT для сохранённых таблиц
+--
+
+--
+-- AUTO_INCREMENT для таблицы `building`
+--
+ALTER TABLE `building`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
+
+--
+-- AUTO_INCREMENT для таблицы `config`
+--
+ALTER TABLE `config`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=109;
+
+--
+-- AUTO_INCREMENT для таблицы `config_options`
+--
+ALTER TABLE `config_options`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=56;
+
+--
+-- AUTO_INCREMENT для таблицы `connections`
+--
+ALTER TABLE `connections`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
+
+--
+-- AUTO_INCREMENT для таблицы `Customers`
+--
+ALTER TABLE `Customers`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
+
+--
+-- AUTO_INCREMENT для таблицы `devices`
+--
+ALTER TABLE `devices`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
+
+--
+-- AUTO_INCREMENT для таблицы `device_ports`
+--
+ALTER TABLE `device_ports`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
+
+--
+-- AUTO_INCREMENT для таблицы `dhcp_log`
+--
+ALTER TABLE `dhcp_log`
+  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
+
+--
+-- AUTO_INCREMENT для таблицы `Filter_list`
+--
+ALTER TABLE `Filter_list`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=105;
+
+--
+-- AUTO_INCREMENT для таблицы `Group_filters`
+--
+ALTER TABLE `Group_filters`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=220;
+
+--
+-- AUTO_INCREMENT для таблицы `Group_list`
+--
+ALTER TABLE `Group_list`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
+
+--
+-- AUTO_INCREMENT для таблицы `mac_history`
+--
+ALTER TABLE `mac_history`
+  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
+
+--
+-- AUTO_INCREMENT для таблицы `mac_vendors`
+--
+ALTER TABLE `mac_vendors`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=38949;
+
+--
+-- AUTO_INCREMENT для таблицы `OU`
+--
+ALTER TABLE `OU`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24;
+
+--
+-- AUTO_INCREMENT для таблицы `Queue_list`
+--
+ALTER TABLE `Queue_list`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
+
+--
+-- AUTO_INCREMENT для таблицы `remote_syslog`
+--
+ALTER TABLE `remote_syslog`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
+
+--
+-- AUTO_INCREMENT для таблицы `subnets`
+--
+ALTER TABLE `subnets`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23;
+
+--
+-- AUTO_INCREMENT для таблицы `syslog`
+--
+ALTER TABLE `syslog`
+  MODIFY `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT;
+
+--
+-- AUTO_INCREMENT для таблицы `Traffic_detail`
+--
+ALTER TABLE `Traffic_detail`
+  MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT;
+
+--
+-- AUTO_INCREMENT для таблицы `Unknown_mac`
+--
+ALTER TABLE `Unknown_mac`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
+
+--
+-- AUTO_INCREMENT для таблицы `User_auth`
+--
+ALTER TABLE `User_auth`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5888;
+
+--
+-- AUTO_INCREMENT для таблицы `User_auth_alias`
+--
+ALTER TABLE `User_auth_alias`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
+
+--
+-- AUTO_INCREMENT для таблицы `User_list`
+--
+ALTER TABLE `User_list`
+  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1951;
+
+--
+-- AUTO_INCREMENT для таблицы `User_stats`
+--
+ALTER TABLE `User_stats`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
+
+--
+-- AUTO_INCREMENT для таблицы `variables`
+--
+ALTER TABLE `variables`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
+
+--
+-- AUTO_INCREMENT для таблицы `vendors`
+--
+ALTER TABLE `vendors`
+  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20;

+ 20 - 0
docs/mysql/stat_table_Customers.sql

@@ -0,0 +1,20 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `Customers`
+--
+
+CREATE TABLE `Customers` (
+  `id` int(11) NOT NULL,
+  `Login` varchar(20) DEFAULT 'NULL',
+  `Pwd` varchar(32) DEFAULT 'NULL',
+  `readonly` tinyint(1) NOT NULL DEFAULT 0
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Дамп данных таблицы `Customers`
+--
+
+INSERT INTO `Customers` (`id`, `Login`, `Pwd`, `readonly`) VALUES
+(1, 'roman', '7a4415568f11d805b6eef1adb2b0af59', 0);

+ 65 - 0
docs/mysql/stat_table_Filter_list.sql

@@ -0,0 +1,65 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `Filter_list`
+--
+
+CREATE TABLE `Filter_list` (
+  `id` int(11) NOT NULL,
+  `name` varchar(20) NOT NULL DEFAULT '',
+  `proto` varchar(10) DEFAULT NULL,
+  `dst` text DEFAULT NULL,
+  `dstport` varchar(20) DEFAULT NULL,
+  `action` int(11) NOT NULL DEFAULT 0,
+  `type` int(10) UNSIGNED NOT NULL DEFAULT 0
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Дамп данных таблицы `Filter_list`
+--
+
+INSERT INTO `Filter_list` (`id`, `name`, `proto`, `dst`, `dstport`, `action`, `type`) VALUES
+(1, 'pop3', 'tcp', '0/0', '110', 1, 0),
+(3, 'http', 'tcp', '0/0', '80', 1, 0),
+(4, 'https', 'tcp', '0/0', '443', 1, 0),
+(5, 'icq', 'tcp', '0/0', '5190', 1, 0),
+(6, 'jabber', 'tcp', '0/0', '5222', 1, 0),
+(9, 'allow_all', 'all', '0/0', '0', 1, 0),
+(10, 'icmp', 'icmp', '0/0', '0', 1, 0),
+(11, 'ftp', 'tcp', '0/0', '20-21', 1, 0),
+(14, 'radmin', 'tcp', '0/0', '4899', 1, 0),
+(15, 'telnet', 'tcp', '0/0', '23', 1, 0),
+(16, 'ssh', 'tcp', '0/0', '22', 1, 0),
+(23, 'webmoney', 'tcp', '0/0', '2802', 1, 0),
+(24, 'skype', 'udp', '0/0', '39082', 1, 0),
+(26, 'bank zenit', 'tcp', '0/0', '1352', 1, 0),
+(28, 'smtp', 'tcp', '0/0', '25', 1, 0),
+(32, 'tsclient', 'tcp', '0/0', '3389', 1, 0),
+(34, 'sberbank', 'udp', '0/0', '87', 1, 0),
+(40, 'ntp', 'udp', '0/0', '123', 1, 0),
+(44, 'vnc', 'tcp', '0/0', '5800-5900', 1, 0),
+(55, 'unprivileged tcp', 'tcp', '0/0', '1024-65500', 1, 0),
+(76, 'ipsec', 'udp', '0/0', '500', 1, 0),
+(77, 'isakmp', 'udp', '0/0', '4500', 1, 0),
+(79, 'pop3s', 'tcp', '0/0', '995', 1, 0),
+(80, 'smtps', 'tcp', '0/0', '465,587', 1, 0),
+(81, 'imap', 'tcp', '0/0', '143', 1, 0),
+(82, 'imaps', 'tcp', '0/0', '993', 1, 0),
+(83, 'unprivileged udp', 'udp', '0/0', '1024-65000', 1, 0),
+(84, 'pptp', 'tcp', '0/0', '1723', 1, 0),
+(85, 'openvpn-udp', 'udp', '0/0', '1194', 1, 0),
+(88, 'pos-server', 'tcp', '0/0', '21101', 1, 0),
+(89, 'ofdp.platformaofd.ru', 'all', '185.170.204.91', '0', 1, 0),
+(90, 'dns_udp', 'udp', '0/0', '53', 1, 0),
+(91, 'dns_tcp', 'tcp', '0/0', '53', 1, 0),
+(92, 'sber-online', 'tcp', '0/0', '4477', 1, 0),
+(93, 'devline.tv', 'tcp', '0/0', '843', 1, 0),
+(94, 'squid', 'tcp', '0/0', '3128', 1, 0),
+(95, 'fe.ls.tv.ttk.ru', 'all', '37.18.127.6', '0', 1, 0),
+(96, 'cvs', 'tcp', '0/0', '5000-5012', 1, 0),
+(97, 'devline', 'tcp', '0/0', '9780-9786,9877', 1, 0),
+(98, 'atomsbt-lk', 'tcp', '0/0', '9080', 1, 0),
+(99, 'raif-tcp-1403-1405', 'tcp', '0/0', '1403-1405', 1, 0),
+(101, 'snmp', 'udp', '0/0', '161', 1, 0),
+(104, 'sberbank2', 'tcp', '0/0', '9443', 1, 0);

+ 71 - 0
docs/mysql/stat_table_Group_filters.sql

@@ -0,0 +1,71 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `Group_filters`
+--
+
+CREATE TABLE `Group_filters` (
+  `id` int(11) NOT NULL,
+  `group_id` int(11) NOT NULL DEFAULT 0,
+  `filter_id` int(11) NOT NULL DEFAULT 0,
+  `order` int(11) NOT NULL DEFAULT 0
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Дамп данных таблицы `Group_filters`
+--
+
+INSERT INTO `Group_filters` (`id`, `group_id`, `filter_id`, `order`) VALUES
+(1, 1, 9, 0),
+(2, 2, 1, 1),
+(5, 2, 4, 9),
+(6, 2, 5, 8),
+(7, 2, 6, 7),
+(10, 2, 10, 6),
+(13, 2, 11, 5),
+(147, 2, 67, 0),
+(148, 2, 68, 0),
+(149, 2, 69, 0),
+(152, 1, 67, 0),
+(153, 1, 68, 0),
+(154, 1, 69, 0),
+(166, 2, 3, 10),
+(172, 0, 78, 1),
+(173, 2, 81, 11),
+(174, 2, 82, 12),
+(175, 2, 80, 13),
+(176, 2, 79, 14),
+(179, 3, 11, 1),
+(180, 3, 4, 2),
+(181, 3, 10, 3),
+(182, 3, 5, 4),
+(183, 3, 81, 5),
+(184, 3, 82, 6),
+(185, 3, 6, 7),
+(186, 3, 40, 8),
+(187, 3, 1, 9),
+(188, 3, 79, 10),
+(190, 3, 80, 12),
+(191, 3, 15, 13),
+(192, 3, 55, 14),
+(193, 3, 83, 15),
+(194, 3, 3, 16),
+(195, 3, 16, 17),
+(198, 5, 90, 1),
+(199, 5, 88, 2),
+(200, 5, 89, 3),
+(201, 5, 3, 4),
+(202, 2, 90, 15),
+(204, 3, 91, 18),
+(205, 3, 90, 19),
+(206, 2, 92, 16),
+(207, 2, 93, 17),
+(208, 2, 40, 18),
+(209, 2, 95, 19),
+(210, 2, 96, 20),
+(211, 2, 97, 21),
+(212, 2, 98, 22),
+(213, 5, 4, 5),
+(214, 5, 99, 6),
+(219, 2, 104, 23);

+ 23 - 0
docs/mysql/stat_table_Group_list.sql

@@ -0,0 +1,23 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `Group_list`
+--
+
+CREATE TABLE `Group_list` (
+  `id` int(11) NOT NULL,
+  `group_name` varchar(30) NOT NULL DEFAULT ''
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Дамп данных таблицы `Group_list`
+--
+
+INSERT INTO `Group_list` (`id`, `group_name`) VALUES
+(0, 'default'),
+(1, 'Allow all'),
+(2, 'Users'),
+(3, 'Support'),
+(4, 'VOIP'),
+(5, 'POS');

+ 33 - 0
docs/mysql/stat_table_OU.sql

@@ -0,0 +1,33 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `OU`
+--
+
+CREATE TABLE `OU` (
+  `id` int(11) NOT NULL,
+  `ou_name` varchar(40) DEFAULT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Дамп данных таблицы `OU`
+--
+
+INSERT INTO `OU` (`id`, `ou_name`) VALUES
+(0, 'Все'),
+(1, 'Сервера'),
+(2, 'Администраторы'),
+(3, 'Пользователи'),
+(4, 'VOIP'),
+(5, 'IPCAM'),
+(6, 'Принтеры'),
+(7, 'Свичи'),
+(8, 'UPS'),
+(9, 'Охрана'),
+(10, 'Роутеры'),
+(11, 'IPTV'),
+(12, 'WiFi AP'),
+(13, 'Техподдержка'),
+(14, 'POS-терминалы'),
+(23, 'WiFi');

+ 26 - 0
docs/mysql/stat_table_Queue_list.sql

@@ -0,0 +1,26 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `Queue_list`
+--
+
+CREATE TABLE `Queue_list` (
+  `id` int(11) NOT NULL,
+  `queue_name` varchar(20) NOT NULL,
+  `Download` int(11) NOT NULL DEFAULT 0,
+  `Upload` int(11) NOT NULL DEFAULT 0
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Дамп данных таблицы `Queue_list`
+--
+
+INSERT INTO `Queue_list` (`id`, `queue_name`, `Download`, `Upload`) VALUES
+(0, 'unlimited', 0, 0),
+(1, '2M/2M', 2048, 2048),
+(2, '10M/10M', 10240, 10240),
+(3, '100M/100M', 102400, 102400),
+(4, '50M/50M', 50000, 50000),
+(5, '20M/20M', 20480, 20480),
+(6, '200M/200M', 212400, 212400);

+ 19 - 0
docs/mysql/stat_table_Traffic_detail.sql

@@ -0,0 +1,19 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `Traffic_detail`
+--
+
+CREATE TABLE `Traffic_detail` (
+  `id` bigint(20) NOT NULL,
+  `auth_id` int(11) DEFAULT NULL,
+  `router_id` int(11) NOT NULL DEFAULT 0,
+  `timestamp` timestamp NULL DEFAULT NULL,
+  `proto` int(11) DEFAULT NULL,
+  `src_ip` int(10) UNSIGNED NOT NULL,
+  `dst_ip` int(10) UNSIGNED NOT NULL,
+  `src_port` smallint(5) UNSIGNED NOT NULL,
+  `dst_port` smallint(5) UNSIGNED NOT NULL,
+  `bytes` bigint(20) NOT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;

+ 14 - 0
docs/mysql/stat_table_Unknown_mac.sql

@@ -0,0 +1,14 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `Unknown_mac`
+--
+
+CREATE TABLE `Unknown_mac` (
+  `id` int(11) NOT NULL,
+  `mac` varchar(12) DEFAULT NULL,
+  `port_id` int(11) DEFAULT NULL,
+  `device_id` int(11) DEFAULT NULL,
+  `timestamp` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;

+ 41 - 0
docs/mysql/stat_table_User_auth.sql

@@ -0,0 +1,41 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `User_auth`
+--
+
+CREATE TABLE `User_auth` (
+  `id` int(11) NOT NULL,
+  `user_id` int(11) NOT NULL DEFAULT 0,
+  `ip` varchar(18) NOT NULL DEFAULT '',
+  `ip_int` int(10) UNSIGNED NOT NULL DEFAULT 0,
+  `ip_int_end` int(10) UNSIGNED NOT NULL DEFAULT 0,
+  `save_traf` tinyint(1) NOT NULL DEFAULT 0,
+  `enabled` tinyint(1) NOT NULL DEFAULT 0,
+  `dhcp` tinyint(1) NOT NULL DEFAULT 1,
+  `filter_group_id` tinyint(1) NOT NULL DEFAULT 0,
+  `deleted` tinyint(4) NOT NULL DEFAULT 0,
+  `comments` varchar(50) NOT NULL DEFAULT '',
+  `dns_name` varchar(60) NOT NULL DEFAULT '',
+  `dhcp_acl` text DEFAULT NULL,
+  `queue_id` int(11) NOT NULL DEFAULT 0,
+  `mac` varchar(20) NOT NULL DEFAULT '',
+  `dhcp_action` varchar(10) NOT NULL DEFAULT '',
+  `dhcp_time` datetime NOT NULL DEFAULT current_timestamp(),
+  `dhcp_hostname` varchar(60) DEFAULT NULL,
+  `last_found` datetime NOT NULL DEFAULT current_timestamp(),
+  `blocked` tinyint(1) NOT NULL DEFAULT 0,
+  `day_quota` int(11) NOT NULL DEFAULT 0,
+  `month_quota` int(11) NOT NULL DEFAULT 0,
+  `timestamp` timestamp NOT NULL DEFAULT current_timestamp(),
+  `clientid` varchar(50) NOT NULL DEFAULT '',
+  `nagios` tinyint(1) NOT NULL DEFAULT 0,
+  `nagios_status` varchar(10) NOT NULL DEFAULT '',
+  `host_model` varchar(50) NOT NULL DEFAULT '',
+  `nagios_handler` varchar(50) NOT NULL DEFAULT '',
+  `link_check` tinyint(1) NOT NULL DEFAULT 0,
+  `changed` tinyint(1) NOT NULL DEFAULT 0,
+  `changed_time` datetime NOT NULL DEFAULT current_timestamp()
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+

+ 14 - 0
docs/mysql/stat_table_User_auth_alias.sql

@@ -0,0 +1,14 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `User_auth_alias`
+--
+
+CREATE TABLE `User_auth_alias` (
+  `id` int(11) NOT NULL,
+  `auth_id` int(11) NOT NULL,
+  `alias` varchar(100) DEFAULT NULL,
+  `description` varchar(100) DEFAULT NULL,
+  `timestamp` timestamp NOT NULL DEFAULT current_timestamp()
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;

+ 31 - 0
docs/mysql/stat_table_User_list.sql

@@ -0,0 +1,31 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `User_list`
+--
+
+CREATE TABLE `User_list` (
+  `id` int(10) UNSIGNED NOT NULL,
+  `timestamp` timestamp NOT NULL DEFAULT current_timestamp(),
+  `login` varchar(40) NOT NULL DEFAULT '',
+  `fio` varchar(60) NOT NULL DEFAULT '',
+  `enabled` tinyint(1) NOT NULL DEFAULT 1,
+  `blocked` tinyint(1) NOT NULL DEFAULT 0,
+  `deleted` tinyint(1) NOT NULL DEFAULT 0,
+  `ou_id` int(11) NOT NULL DEFAULT 0,
+  `filter_group_id` int(11) NOT NULL DEFAULT 0,
+  `queue_id` int(11) NOT NULL DEFAULT 0,
+  `day_quota` int(11) NOT NULL DEFAULT 0,
+  `month_quota` int(11) NOT NULL DEFAULT 0,
+  `default_subnet` varchar(20) DEFAULT NULL,
+  `hostname_rule` varchar(70) DEFAULT NULL,
+  `mac_rule` varchar(70) DEFAULT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Дамп данных таблицы `User_list`
+--
+
+INSERT INTO `User_list` (`id`, `login`, `fio`, `enabled`, `blocked`, `deleted`, `ou_id`, `filter_group_id`, `queue_id`, `day_quota`, `month_quota`, `default_subnet`, `hostname_rule`, `mac_rule`) VALUES
+(1, 'default', '', 0, 0, 0, 3, 2, 0, 0, 0, NULL, NULL, NULL);

+ 15 - 0
docs/mysql/stat_table_User_stats.sql

@@ -0,0 +1,15 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `User_stats`
+--
+
+CREATE TABLE `User_stats` (
+  `id` int(11) NOT NULL,
+  `router_id` int(11) DEFAULT 0,
+  `auth_id` int(11) NOT NULL DEFAULT 0,
+  `timestamp` datetime NOT NULL DEFAULT current_timestamp(),
+  `byte_in` int(11) NOT NULL DEFAULT 0,
+  `byte_out` int(11) NOT NULL DEFAULT 0
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;

+ 19 - 0
docs/mysql/stat_table_building.sql

@@ -0,0 +1,19 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `building`
+--
+
+CREATE TABLE `building` (
+  `id` int(11) NOT NULL,
+  `name` varchar(50) NOT NULL,
+  `comment` text DEFAULT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Дамп данных таблицы `building`
+--
+
+INSERT INTO `building` (`id`, `name`, `comment`) VALUES
+(1, 'Earth', 'Somewhere');

+ 21 - 0
docs/mysql/stat_table_config.sql

@@ -0,0 +1,21 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `config`
+--
+
+CREATE TABLE `config` (
+  `id` int(11) NOT NULL,
+  `option_id` int(11) DEFAULT NULL,
+  `value` text DEFAULT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Дамп данных таблицы `config`
+--
+
+INSERT INTO `config` (`id`, `option_id`, `value`) VALUES
+(1, 1, '1024'),
+(2, 22, '1'),
+(3, 17, '1');

+ 61 - 0
docs/mysql/stat_table_config_options.sql

@@ -0,0 +1,61 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `config_options`
+--
+
+CREATE TABLE `config_options` (
+  `id` int(11) NOT NULL,
+  `option_name` varchar(50) NOT NULL,
+  `description` text DEFAULT NULL,
+  `uniq` tinyint(1) NOT NULL DEFAULT 1,
+  `type` varchar(10) NOT NULL,
+  `default_value` text DEFAULT NULL,
+  `min_value` int(11) NOT NULL DEFAULT 0,
+  `max_value` int(11) NOT NULL DEFAULT 0
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Дамп данных таблицы `config_options`
+--
+
+INSERT INTO `config_options` (`id`, `option_name`, `description`, `uniq`, `type`, `default_value`, `min_value`, `max_value`) VALUES
+(1, 'KB', 'Число байт в килобайте', 1, 'int', '1024', 1000, 1024),
+(3, 'dns server', 'ip-адрес DNS-сервера', 1, 'text', '127.0.0.1', 0, 0),
+(5, 'dhcp server', 'ip-адрес DHCP-сервера', 1, 'text', '127.0.0.1', 0, 0),
+(9, 'default snmp version', 'Версия snmp по умолчанию. В настоящий момент поддерживаются 1 и 2. Поддержка версии 3 в разработке.', 1, 'int', '2', 1, 3),
+(11, 'default snmp community', 'Read snmp community по умолчанию', 1, 'text', 'public', 0, 0),
+(17, 'mac discavery', 'Выполнять опрос mac-таблицы коммутаторов при сканировании сети. Если опция отключена будет нельзя сопоставить ip-адрес порту коммутатора', 1, 'bool', '1', 0, 0),
+(19, 'arp discavery', 'Выполнять сканирование arp-таблицы роутеров при сканировании сети. Если опция отключена сопоставление mac-адреса ip-адресу будет возможно только из логов dhcp-сервера.', 1, 'bool', '1', 0, 0),
+(20, 'default user id', 'Id записи пользователя, в которую помещаются все вновь создаваемые при сканировании ip-адреса. Здесь же создаются записи для адресов, которые выдаёт dhcp-сервер', 1, 'int', '1', 0, 0),
+(21, 'admin email', 'E-mail администратора', 1, 'text', 'root', 0, 0),
+(22, 'add user from netflow', 'Создавать ли новые записи для неизвестных адресов из анализа трафика netflow. Обычно выключается, поскольку может создавать много фэйковых адресов - например при пинге подсети, когда пакеты идут на все, даже не существующие адреса. Имеет смысл включать только на маршрутизаторах во внешние сети.', 1, 'bool', '0', 0, 0),
+(23, 'save traffic detail', 'Сохранять ли детализацию трафика из netflow по ip-адресам пользователей', 1, 'bool', '1', 0, 0),
+(26, 'history detail traffic', 'Глубина хранения детализации в сутках. Установка значения больше 3-7 дней приведёт к разрастанию базы данных и увеличит время отображения детализации в интерфейсе администратора', 1, 'int', '3', 1, 7),
+(27, 'history dhcp lease', 'Глубина хранения аренды dhcp-сервера', 1, 'int', '1', 0, 0),
+(28, 'router_login', 'Логин для входа на маршрутизаторы Mikrotik для управления dhcp-сервером и контролем доступа', 1, 'text', 'admin', 0, 0),
+(29, 'router_password', 'Пароль для входа на маршрутизаторы Mikrotik для управления dhcp-сервером и контролем доступа', 1, 'text', 'admin', 0, 0),
+(30, 'router_port', 'Порт telnet маршрутизатора', 1, 'int', '23', 23, 0),
+(32, 'org name', 'Название организации', 1, 'text', 'ORG', 0, 0),
+(33, 'office domain', 'Домен организации', 1, 'text', 'local', 0, 0),
+(34, 'debug', 'Включить отладку', 1, 'bool', '0', 0, 0),
+(35, 'connections history, days', 'Время хранения истории мест подключения ip-адресов', 1, 'int', '90', 1, 365),
+(37, 'refresh access lists', 'Расположение скрипта управления контролем доступа для роутеров Mikrotik', 1, 'text', '/usr/local/scripts/sync_user_list.pl', 0, 0),
+(38, 'regenerate dhcp cconfig', 'Расположение скрипта управления конфигурацией dhcp-серверами', 1, 'text', '/usr/local/scripts/update-dnsmasq', 0, 0),
+(39, 'regenerate dns cconfig', 'Расположение скрипта управления dns-сервером', 1, 'text', '/usr/local/scripts/update-dns', 0, 0),
+(40, 'regenerate nagios cconfig', 'Расположение скрипта конфигурирования Nagios', 1, 'text', '/etc/nagios/restart_nagios', 0, 0),
+(41, 'discavery network', 'Расположение скрипта сканирования сети', 1, 'text', '/usr/local/scripts/fetch_new_arp.pl', 0, 0),
+(43, 'hotspot_user_id', 'Id запись юзера, в которой создаются ip-адреса, выдаваемые хот-спотом. По умолчанию, используется та же запись, что и для обычных пользователей, но лучше завести отдельную учётку, чтобы не мешать временные записи и постоянные записи компьютеров организации', 1, 'int', '1', 1, 0),
+(44, 'Ignore hotspot dhcp log', 'Не писать лог событий dhcp-сервера хотспота. Имеет смысл вклчючать, поскольку время аренды в хот-споте как правило маленькое и в записях хот-спота становятся незаметны логи обычных пользователей', 1, 'bool', '1', 0, 0),
+(45, 'ignore update dhcp event', 'Не писать события обновления ip-адреса dhcp-сервера. ', 1, 'bool', '0', 0, 0),
+(46, 'update hostname from dhcp', 'Обновлять имя хоста в DNS при получении адреса по DHCP', 1, 'bool', '0', 0, 0),
+(47, 'history worklog', 'Глубина хранения логов работы в интерфейсе администратора', 1, 'int', '90', 30, 1095),
+(48, 'history syslog', 'Глубина хранения логов работы syslog-сервера', 1, 'int', '90', 30, 1095),
+(49, 'history traffic stats', 'Глубина хранения статистики трафика юзеров', 1, 'int', '365', 30, 0),
+(50, 'urgent sync access', 'Немедленное изменение списков доступа на роутере после правки записи пользователя', 1, 'bool', '0', 0, 0),
+(51, 'Email_alert', 'Отправлять e-mail сообщения для уровней сообщений WARNING & ERROR', 1, 'bool', '1', 0, 0),
+(52, 'Sender email', 'E-mail адрес, с которого рассылается почта', 1, 'text', 'root', 0, 0),
+(53, 'log level', 'Каждый уровень включает в себя предыдущий:\r\n0 - ERROR - писать только ошибки\r\n1 - WARNING - писать предупреждения\r\n2 - INFO - писать информационные сообщения\r\n3 - VERBOSE - писать подробную информацию о выполняемых операциях', 1, 'int', '2', 0, 3),
+(54, 'enable_quotes', 'Включить обработку квот по трафику', 1, 'bool', '0', 0, 0),
+(55, 'netflow_step', 'Интервал сброса данных из коллектора netflow, минуты', 1, 'int', '10', 1, 60);

+ 13 - 0
docs/mysql/stat_table_connections.sql

@@ -0,0 +1,13 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `connections`
+--
+
+CREATE TABLE `connections` (
+  `id` int(11) NOT NULL,
+  `device_id` int(11) NOT NULL,
+  `port_id` int(11) NOT NULL,
+  `auth_id` int(11) NOT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;

+ 21 - 0
docs/mysql/stat_table_device_ports.sql

@@ -0,0 +1,21 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `device_ports`
+--
+
+CREATE TABLE `device_ports` (
+  `id` int(11) NOT NULL,
+  `device_id` int(11) DEFAULT NULL,
+  `snmp_index` int(11) DEFAULT NULL,
+  `port` int(11) DEFAULT NULL,
+  `comment` varchar(50) DEFAULT NULL,
+  `target_port_id` int(11) NOT NULL DEFAULT 0,
+  `auth_id` int(11) DEFAULT NULL,
+  `last_mac_count` int(11) DEFAULT 0,
+  `uplink` tinyint(1) NOT NULL DEFAULT 0,
+  `nagios` tinyint(1) NOT NULL DEFAULT 0,
+  `skip` tinyint(1) NOT NULL DEFAULT 0,
+  `vlan` int(11) NOT NULL DEFAULT 1
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;

+ 39 - 0
docs/mysql/stat_table_devices.sql

@@ -0,0 +1,39 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `devices`
+--
+
+CREATE TABLE `devices` (
+  `id` int(11) NOT NULL,
+  `device_model` varchar(50) DEFAULT NULL,
+  `vendor_id` int(11) NOT NULL DEFAULT 1,
+  `device_name` varchar(50) DEFAULT NULL,
+  `building_id` int(11) NOT NULL DEFAULT 1,
+  `ip` varchar(15) DEFAULT NULL,
+  `mac` varchar(20) DEFAULT NULL,
+  `port_count` int(11) NOT NULL DEFAULT 0,
+  `wan_int` text DEFAULT NULL,
+  `lan_int` text DEFAULT NULL,
+  `comment` text DEFAULT NULL,
+  `snmp_version` tinyint(4) NOT NULL DEFAULT 0,
+  `snmp3_user_rw` varchar(20) DEFAULT NULL,
+  `snmp3_user_rw_password` varchar(20) DEFAULT NULL,
+  `snmp3_user_ro` varchar(20) DEFAULT NULL,
+  `snmp3_user_ro_password` varchar(20) DEFAULT NULL,
+  `community` varchar(50) NOT NULL DEFAULT 'public',
+  `rw_community` varchar(50) NOT NULL DEFAULT 'private',
+  `fdb_snmp_index` tinyint(1) NOT NULL DEFAULT 0,
+  `discovery` tinyint(1) NOT NULL DEFAULT 1,
+  `is_router` tinyint(1) NOT NULL DEFAULT 0,
+  `internet_gateway` tinyint(1) NOT NULL DEFAULT 0,
+  `dhcp` tinyint(1) NOT NULL DEFAULT 0,
+  `nagios` tinyint(1) NOT NULL DEFAULT 0,
+  `active` tinyint(1) NOT NULL DEFAULT 1,
+  `nagios_status` varchar(10) NOT NULL DEFAULT 'UP',
+  `queue_enabled` tinyint(1) NOT NULL DEFAULT 0,
+  `connected_user_only` tinyint(1) NOT NULL DEFAULT 1,
+  `user_id` int(11) DEFAULT NULL,
+  `deleted` tinyint(1) NOT NULL DEFAULT 0
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;

+ 16 - 0
docs/mysql/stat_table_dhcp_log.sql

@@ -0,0 +1,16 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `dhcp_log`
+--
+
+CREATE TABLE `dhcp_log` (
+  `id` int(10) UNSIGNED NOT NULL,
+  `mac` varchar(17) NOT NULL,
+  `ip_int` int(10) UNSIGNED NOT NULL,
+  `ip` varchar(15) NOT NULL,
+  `action` varchar(10) NOT NULL,
+  `timestamp` timestamp NOT NULL DEFAULT current_timestamp(),
+  `auth_id` int(11) NOT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;

+ 16 - 0
docs/mysql/stat_table_mac_history.sql

@@ -0,0 +1,16 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `mac_history`
+--
+
+CREATE TABLE `mac_history` (
+  `id` int(10) UNSIGNED NOT NULL,
+  `mac` varchar(12) DEFAULT NULL,
+  `timestamp` timestamp NOT NULL DEFAULT current_timestamp(),
+  `device_id` int(11) DEFAULT NULL,
+  `port_id` int(11) DEFAULT NULL,
+  `ip` varchar(16) NOT NULL DEFAULT '',
+  `auth_id` int(11) DEFAULT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;

+ 2 - 1036
docs/mysql/db-mysql.sql → docs/mysql/stat_table_mac_vendors.sql

@@ -1,396 +1,8 @@
-SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
-SET AUTOCOMMIT = 0;
-START TRANSACTION;
-SET time_zone = "+00:00";
-
-
-/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
-/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
-/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
-/*!40101 SET NAMES utf8mb4 */;
-
-CREATE TABLE `building` (
-  `id` int(11) NOT NULL,
-  `name` varchar(50) NOT NULL,
-  `comment` text DEFAULT NULL
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
---
--- Dumping data for table `building`
---
-
-INSERT INTO `building` (`id`, `name`, `comment`) VALUES
-(1, 'Earth', 'Somewhere');
 
 -- --------------------------------------------------------
 
 --
--- Table structure for table `config`
---
-
-CREATE TABLE `config` (
-  `id` int(11) NOT NULL,
-  `option_id` int(11) DEFAULT NULL,
-  `value` text DEFAULT NULL
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
---
--- Dumping data for table `config`
---
-
-INSERT INTO `config` (`id`, `option_id`, `value`) VALUES
-(1, 1, '1024'),
-(77, 41, '/usr/local/scripts/fetch_new_arp.pl'),
-(78, 37, '/usr/local/scripts/sync_mikrotik.pl');
-
--- --------------------------------------------------------
-
---
--- Table structure for table `config_options`
---
-
-CREATE TABLE `config_options` (
-  `id` int(11) NOT NULL,
-  `option_name` varchar(50) NOT NULL,
-  `description` text DEFAULT NULL,
-  `uniq` tinyint(1) NOT NULL DEFAULT 1,
-  `type` varchar(10) NOT NULL,
-  `default_value` text DEFAULT NULL
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
---
--- Dumping data for table `config_options`
---
-
-INSERT INTO `config_options` (`id`, `option_name`, `description`, `uniq`, `type`, `default_value`) VALUES
-(1, 'KB', 'Число байт в килобайте', 1, 'int', '1024'),
-(3, 'dns server', 'ip-адрес DNS-сервера', 1, 'text', '127.0.0.1'),
-(5, 'dhcp server', 'ip-адрес DHCP-сервера', 1, 'text', '127.0.0.1'),
-(9, 'default snmp version', 'Версия snmp по умолчанию. В настоящий момент поддерживаются 1 и 2. Поддержка версии 3 в разработке.', 1, 'int', '2'),
-(11, 'default snmp community', 'Read snmp community по умолчанию', 1, 'text', 'public'),
-(17, 'mac discavery', 'Выполнять опрос mac-таблицы коммутаторов при сканировании сети. Если опция отключена будет нельзя сопоставить ip-адрес порту коммутатора', 1, 'bool', '1'),
-(19, 'arp discavery', 'Выполнять сканирование arp-таблицы роутеров при сканировании сети. Если опция отключена сопоставление mac-адреса ip-адресу будет возможно только из логов dhcp-сервера.', 1, 'bool', '1'),
-(20, 'default user id', 'Id записи пользователя, в которую помещаются все вновь создаваемые при сканировании ip-адреса. Здесь же создаются записи для адресов, которые выдаёт dhcp-сервер', 1, 'int', '1'),
-(21, 'admin email', 'E-mail администратора', 1, 'text', 'root'),
-(22, 'add user from netflow', 'Создавать ли новые записи для неизвестных адресов из анализа трафика netflow. Обычно выключается, поскольку может создавать много фэйковых адресов - например при пинге подсети, когда пакеты идут на все, даже не существующие адреса. Имеет смысл включать только на маршрутизаторах во внешние сети.', 1, 'bool', '0'),
-(23, 'save traffic detail', 'Сохранять ли детализацию трафика из netflow по ip-адресам пользователей', 1, 'bool', '1'),
-(26, 'history detail traffic', 'Глубина хранения детализации в сутках. Установка значения больше 3-7 дней приведёт к разрастанию базы данных и увеличит время отображения детализации в интерфейсе администратора', 1, 'int', '3'),
-(27, 'history dhcp lease', 'Глубина хранения аренды dhcp-сервера', 1, 'int', '1'),
-(28, 'router_login', 'Логин для входа на маршрутизаторы Mikrotik для управления dhcp-сервером и контролем доступа', 1, 'text', 'admin'),
-(29, 'router_password', 'Пароль для входа на маршрутизаторы Mikrotik для управления dhcp-сервером и контролем доступа', 1, 'text', 'admin'),
-(30, 'router_port', 'Порт telnet маршрутизатора', 1, 'int', '23'),
-(32, 'org name', 'Название организации', 1, 'text', 'ORG'),
-(33, 'office domain', 'Домен организации', 1, 'text', 'local'),
-(34, 'debug', 'Включить отладку', 1, 'bool', '0'),
-(35, 'connections history, days', 'Время хранения истории мест подключения ip-адресов', 1, 'int', '90'),
-(36, 'clear user auth', 'Удалять ли старые записи ip-адресов в динмамическом пуле (у юзера default)', 1, 'bool', '0'),
-(37, 'refresh access lists', 'Расположение скрипта управления контролем доступа для роутеров Mikrotik', 1, 'text', '/usr/local/scripts/sync_user_list.pl'),
-(38, 'regenerate dhcp cconfig', 'Расположение скрипта управления конфигурацией dhcp-серверами', 1, 'text', '/usr/local/scripts/update-dnsmasq'),
-(39, 'regenerate dns cconfig', 'Расположение скрипта управления dns-сервером', 1, 'text', '/usr/local/scripts/update-dns'),
-(40, 'regenerate nagios cconfig', 'Расположение скрипта конфигурирования Nagios', 1, 'text', '/etc/nagios/restart_nagios'),
-(41, 'discavery network', 'Расположение скрипта сканирования сети', 1, 'text', '/usr/local/scripts/fetch_new_arp.pl'),
-(43, 'hotspot_user_id', 'Id запись юзера, в которой создаются ip-адреса, выдаваемые хот-спотом. По умолчанию, используется та же запись, что и для обычных пользователей, но лучше завести отдельную учётку, чтобы не мешать временные записи и постоянные записи компьютеров организации', 1, 'int', '1'),
-(44, 'Ignore hotspot dhcp log', 'Не писать лог событий dhcp-сервера хотспота. Имеет смысл вклчючать, поскольку время аренды в хот-споте как правило маленькое и в записях хот-спота становятся незаметны логи обычных пользователей', 1, 'bool', '1'),
-(45, 'ignore update dhcp event', 'Не писать события обновления ip-адреса dhcp-сервера. ', 1, 'bool', '0'),
-(46, 'update hostname from dhcp', 'Обновлять имя хоста в DNS при получении адреса по DHCP', 1, 'bool', '0'),
-(47, 'history worklog', 'Глубина хранения логов работы в интерфейсе администратора', 1, 'int', '90'),
-(48, 'history syslog', 'Глубина хранения логов работы syslog-сервера', 1, 'int', '90'),
-(49, 'history traffic stats', 'Глубина хранения статистики трафика юзеров', 1, 'int', '365'),
-(50, 'urgent sync access', 'Немедленное изменение списков доступа на роутере после правки записи пользователя', 1, 'bool', '0'),
-(51, 'Email_alert', 'Отправлять e-mail сообщения для уровней сообщений WARNING & ERROR', 1, 'bool', '1'),
-(52, 'Sender email', 'E-mail адрес, с которого рассылается почта', 1, 'text', 'root'),
-(53, 'log level', 'Каждый уровень включает в себя предыдущий:\r\n0 - ERROR - писать только ошибки\r\n1 - WARNING - писать предупреждения\r\n2 - INFO - писать информационные сообщения\r\n3 - VERBOSE - писать подробную информацию о выполняемых операциях', 1, 'int', '2');
-
--- --------------------------------------------------------
-
---
--- Table structure for table `connections`
---
-
-CREATE TABLE `connections` (
-  `id` int(11) NOT NULL,
-  `device_id` int(11) NOT NULL,
-  `port_id` int(11) NOT NULL,
-  `auth_id` int(11) NOT NULL
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
--- --------------------------------------------------------
-
---
--- Table structure for table `Customers`
---
-
-CREATE TABLE `Customers` (
-  `id` int(11) NOT NULL,
-  `Login` varchar(20) DEFAULT 'NULL',
-  `Pwd` varchar(32) DEFAULT 'NULL',
-  `readonly` tinyint(1) NOT NULL DEFAULT 0
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
---
--- Dumping data for table `Customers`
---
-
-INSERT INTO `Customers` (`id`, `Login`, `Pwd`, `readonly`) VALUES
-(1, 'roman', '7a4415568f11d805b6eef1adb2b0af59', 0);
-
--- --------------------------------------------------------
-
---
--- Table structure for table `devices`
---
-
-CREATE TABLE `devices` (
-  `id` int(11) NOT NULL,
-  `device_model` varchar(50) DEFAULT NULL,
-  `vendor_id` int(11) NOT NULL DEFAULT 1,
-  `device_name` varchar(50) DEFAULT NULL,
-  `building_id` int(11) NOT NULL DEFAULT 1,
-  `ip` varchar(15) DEFAULT NULL,
-  `mac` varchar(20) DEFAULT NULL,
-  `port_count` int(11) NOT NULL DEFAULT 0,
-  `wan_int` text DEFAULT NULL,
-  `lan_int` text DEFAULT NULL,
-  `comment` text DEFAULT NULL,
-  `snmp_version` tinyint(4) NOT NULL DEFAULT 0,
-  `snmp3_user_rw` varchar(20) DEFAULT NULL,
-  `snmp3_user_rw_password` varchar(20) DEFAULT NULL,
-  `snmp3_user_ro` varchar(20) DEFAULT NULL,
-  `snmp3_user_ro_password` varchar(20) DEFAULT NULL,
-  `community` varchar(50) NOT NULL DEFAULT 'public',
-  `rw_community` varchar(50) NOT NULL DEFAULT 'private',
-  `fdb_snmp_index` tinyint(1) NOT NULL DEFAULT 0,
-  `discovery` tinyint(1) NOT NULL DEFAULT 1,
-  `is_router` tinyint(1) NOT NULL DEFAULT 0,
-  `internet_gateway` tinyint(1) NOT NULL DEFAULT 0,
-  `dhcp` tinyint(1) NOT NULL DEFAULT 0,
-  `nagios` tinyint(1) NOT NULL DEFAULT 0,
-  `active` tinyint(1) NOT NULL DEFAULT 1,
-  `nagios_status` varchar(10) NOT NULL DEFAULT 'UP',
-  `queue_enabled` tinyint(1) NOT NULL DEFAULT 0,
-  `connected_user_only` tinyint(1) NOT NULL DEFAULT 1,
-  `user_id` int(11) DEFAULT NULL,
-  `deleted` tinyint(1) NOT NULL DEFAULT 0
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
--- --------------------------------------------------------
-
---
--- Table structure for table `device_ports`
---
-
-CREATE TABLE `device_ports` (
-  `id` int(11) NOT NULL,
-  `device_id` int(11) DEFAULT NULL,
-  `snmp_index` int(11) DEFAULT NULL,
-  `port` int(11) DEFAULT NULL,
-  `comment` varchar(50) DEFAULT NULL,
-  `target_port_id` int(11) NOT NULL DEFAULT 0,
-  `auth_id` int(11) DEFAULT NULL,
-  `last_mac_count` int(11) DEFAULT 0,
-  `uplink` tinyint(1) NOT NULL DEFAULT 0,
-  `nagios` tinyint(1) NOT NULL DEFAULT 0,
-  `skip` tinyint(1) NOT NULL DEFAULT 0,
-  `vlan` int(11) NOT NULL DEFAULT 1
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
--- --------------------------------------------------------
-
---
--- Table structure for table `dhcp_log`
---
-
-CREATE TABLE `dhcp_log` (
-  `id` int(10) UNSIGNED NOT NULL,
-  `mac` varchar(17) NOT NULL,
-  `ip_int` int(10) UNSIGNED NOT NULL,
-  `ip` varchar(15) NOT NULL,
-  `action` varchar(10) NOT NULL,
-  `timestamp` timestamp NOT NULL DEFAULT current_timestamp(),
-  `auth_id` int(11) NOT NULL
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
--- --------------------------------------------------------
-
---
--- Table structure for table `Filter_list`
---
-
-CREATE TABLE `Filter_list` (
-  `id` int(11) NOT NULL,
-  `name` varchar(20) NOT NULL DEFAULT '',
-  `proto` varchar(10) DEFAULT NULL,
-  `dst` text DEFAULT NULL,
-  `dstport` varchar(20) DEFAULT NULL,
-  `action` int(11) NOT NULL DEFAULT 0,
-  `type` int(10) UNSIGNED NOT NULL DEFAULT 0
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
---
--- Dumping data for table `Filter_list`
---
-
-INSERT INTO `Filter_list` (`id`, `name`, `proto`, `dst`, `dstport`, `action`, `type`) VALUES
-(1, 'pop3', 'tcp', '0/0', '110', 1, 0),
-(3, 'http', 'tcp', '0/0', '80', 1, 0),
-(4, 'https', 'tcp', '0/0', '443', 1, 0),
-(5, 'icq', 'tcp', '0/0', '5190', 1, 0),
-(6, 'jabber', 'tcp', '0/0', '5222', 1, 0),
-(9, 'allow_all', 'all', '0/0', '0', 1, 0),
-(10, 'icmp', 'icmp', '0/0', '0', 1, 0),
-(11, 'ftp', 'tcp', '0/0', '20-21', 1, 0),
-(14, 'radmin', 'tcp', '0/0', '4899', 1, 0),
-(15, 'telnet', 'tcp', '0/0', '23', 1, 0),
-(16, 'ssh', 'tcp', '0/0', '22', 1, 0),
-(23, 'webmoney', 'tcp', '0/0', '2802', 1, 0),
-(24, 'skype', 'udp', '0/0', '39082', 1, 0),
-(26, 'bank zenit', 'tcp', '0/0', '1352', 1, 0),
-(28, 'smtp', 'tcp', '0/0', '25', 1, 0),
-(32, 'tsclient', 'tcp', '0/0', '3389', 1, 0),
-(34, 'sberbank', 'udp', '0/0', '87', 1, 0),
-(40, 'ntp', 'udp', '0/0', '123', 1, 0),
-(44, 'vnc', 'tcp', '0/0', '5800-5900', 1, 0),
-(55, 'unprivileged tcp', 'tcp', '0/0', '1024-65500', 1, 0),
-(76, 'ipsec', 'udp', '0/0', '500', 1, 0),
-(77, 'isakmp', 'udp', '0/0', '4500', 1, 0),
-(79, 'pop3s', 'tcp', '0/0', '995', 1, 0),
-(80, 'smtps', 'tcp', '0/0', '465,587', 1, 0),
-(81, 'imap', 'tcp', '0/0', '143', 1, 0),
-(82, 'imaps', 'tcp', '0/0', '993', 1, 0),
-(83, 'unprivileged udp', 'udp', '0/0', '1024-65000', 1, 0),
-(84, 'pptp', 'tcp', '0/0', '1723', 1, 0),
-(85, 'openvpn-udp', 'udp', '0/0', '1194', 1, 0),
-(88, 'pos-server', 'tcp', '0/0', '21101', 1, 0),
-(89, 'ofdp.platformaofd.ru', 'all', '185.170.204.91', '0', 1, 0),
-(90, 'dns_udp', 'udp', '0/0', '53', 1, 0),
-(91, 'dns_tcp', 'tcp', '0/0', '53', 1, 0),
-(92, 'sber-online', 'tcp', '0/0', '4477', 1, 0),
-(93, 'devline.tv', 'tcp', '0/0', '843', 1, 0),
-(94, 'squid', 'tcp', '0/0', '3128', 1, 0),
-(95, 'fe.ls.tv.ttk.ru', 'all', '37.18.127.6', '0', 1, 0),
-(96, 'cvs', 'tcp', '0/0', '5000-5012', 1, 0),
-(97, 'devline', 'tcp', '0/0', '9780-9786,9877', 1, 0),
-(98, 'atomsbt-lk', 'tcp', '0/0', '9080', 1, 0),
-(99, 'raif-tcp-1403-1405', 'tcp', '0/0', '1403-1405', 1, 0),
-(101, 'snmp', 'udp', '0/0', '161', 1, 0),
-(104, 'sberbank2', 'tcp', '0/0', '9443', 1, 0);
-
--- --------------------------------------------------------
-
---
--- Table structure for table `Group_filters`
---
-
-CREATE TABLE `Group_filters` (
-  `id` int(11) NOT NULL,
-  `group_id` int(11) NOT NULL DEFAULT 0,
-  `filter_id` int(11) NOT NULL DEFAULT 0,
-  `order` int(11) NOT NULL DEFAULT 0
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
---
--- Dumping data for table `Group_filters`
---
-
-INSERT INTO `Group_filters` (`id`, `group_id`, `filter_id`, `order`) VALUES
-(1, 1, 9, 0),
-(2, 2, 1, 1),
-(5, 2, 4, 9),
-(6, 2, 5, 8),
-(7, 2, 6, 7),
-(10, 2, 10, 6),
-(13, 2, 11, 5),
-(147, 2, 67, 0),
-(148, 2, 68, 0),
-(149, 2, 69, 0),
-(152, 1, 67, 0),
-(153, 1, 68, 0),
-(154, 1, 69, 0),
-(166, 2, 3, 10),
-(172, 0, 78, 1),
-(173, 2, 81, 11),
-(174, 2, 82, 12),
-(175, 2, 80, 13),
-(176, 2, 79, 14),
-(179, 3, 11, 1),
-(180, 3, 4, 2),
-(181, 3, 10, 3),
-(182, 3, 5, 4),
-(183, 3, 81, 5),
-(184, 3, 82, 6),
-(185, 3, 6, 7),
-(186, 3, 40, 8),
-(187, 3, 1, 9),
-(188, 3, 79, 10),
-(190, 3, 80, 12),
-(191, 3, 15, 13),
-(192, 3, 55, 14),
-(193, 3, 83, 15),
-(194, 3, 3, 16),
-(195, 3, 16, 17),
-(198, 5, 90, 1),
-(199, 5, 88, 2),
-(200, 5, 89, 3),
-(201, 5, 3, 4),
-(202, 2, 90, 15),
-(204, 3, 91, 18),
-(205, 3, 90, 19),
-(206, 2, 92, 16),
-(207, 2, 93, 17),
-(208, 2, 40, 18),
-(209, 2, 95, 19),
-(210, 2, 96, 20),
-(211, 2, 97, 21),
-(212, 2, 98, 22),
-(213, 5, 4, 5),
-(214, 5, 99, 6),
-(215, 6, 86, 1),
-(216, 6, 87, 2),
-(219, 2, 104, 23);
-
--- --------------------------------------------------------
-
---
--- Table structure for table `Group_list`
---
-
-CREATE TABLE `Group_list` (
-  `id` int(11) NOT NULL,
-  `group_name` varchar(30) NOT NULL DEFAULT ''
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
---
--- Dumping data for table `Group_list`
---
-
-INSERT INTO `Group_list` (`id`, `group_name`) VALUES
-(0, 'default'),
-(1, 'Allow all'),
-(2, 'Users'),
-(3, 'Support'),
-(4, 'VOIP'),
-(5, 'POS');
-
--- --------------------------------------------------------
-
---
--- Table structure for table `mac_history`
---
-
-CREATE TABLE `mac_history` (
-  `id` int(10) UNSIGNED NOT NULL,
-  `mac` varchar(12) DEFAULT NULL,
-  `timestamp` timestamp NOT NULL DEFAULT current_timestamp(),
-  `device_id` int(11) DEFAULT NULL,
-  `port_id` int(11) DEFAULT NULL,
-  `ip` varchar(16) NOT NULL DEFAULT '',
-  `auth_id` int(11) DEFAULT NULL
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
--- --------------------------------------------------------
-
---
--- Table structure for table `mac_vendors`
+-- Структура таблицы `mac_vendors`
 --
 
 CREATE TABLE `mac_vendors` (
@@ -406,7 +18,7 @@ CREATE TABLE `mac_vendors` (
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
 --
--- Dumping data for table `mac_vendors`
+-- Дамп данных таблицы `mac_vendors`
 --
 
 INSERT INTO `mac_vendors` (`id`, `oui`, `isprivate`, `companyName`, `companyAddress`, `countryCode`, `assignmentBlockSize`, `dateCreated`, `dateUpdated`) VALUES
@@ -39467,649 +39079,3 @@ INSERT INTO `mac_vendors` (`id`, `oui`, `isprivate`, `companyName`, `companyAddr
 (38946, '0050c2b88', 0, 'Gigatronik Köln GmbH', 'Ruth-Hallensleben-Straße 4 Köln 50739 DE', 'DE', 'IAB', '2010-05-15', '2015-08-29'),
 (38947, '0050c2cf5', 0, 'Gogo BA', '303 S. Technology Dr. Broomfield CO 80021 US', 'US', 'IAB', '2010-08-19', '2017-03-25'),
 (38948, 'b00ad5', 0, 'zte Corp', '12/F.,zte R&D building ,kejinan Road,Shenzhen,P.R.China shenzhen guangdong 518057 CN', 'CN', 'MA-L', '2019-11-13', '2019-11-13');
-
--- --------------------------------------------------------
-
---
--- Table structure for table `OU`
---
-
-CREATE TABLE `OU` (
-  `id` int(11) NOT NULL,
-  `ou_name` varchar(40) DEFAULT NULL
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
---
--- Dumping data for table `OU`
---
-
-INSERT INTO `OU` (`id`, `ou_name`) VALUES
-(0, 'Все'),
-(1, 'Сервера'),
-(2, 'Администраторы'),
-(3, 'Пользователи'),
-(4, 'VOIP'),
-(5, 'IPCAM'),
-(6, 'Принтеры'),
-(7, 'Свичи'),
-(8, 'UPS'),
-(9, 'Охрана'),
-(10, 'Роутеры'),
-(11, 'IPTV'),
-(12, 'WiFi AP'),
-(14, 'POS-терминалы');
-
--- --------------------------------------------------------
-
---
--- Table structure for table `Queue_list`
---
-
-CREATE TABLE `Queue_list` (
-  `id` int(11) NOT NULL,
-  `queue_name` varchar(20) NOT NULL,
-  `Download` int(11) NOT NULL DEFAULT 0,
-  `Upload` int(11) NOT NULL DEFAULT 0
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
---
--- Dumping data for table `Queue_list`
---
-
-INSERT INTO `Queue_list` (`id`, `queue_name`, `Download`, `Upload`) VALUES
-(0, 'unlimited', 0, 0),
-(1, '2M/2M', 2048, 2048),
-(2, '10M/10M', 10240, 10240),
-(3, '100M/100M', 102400, 102400),
-(4, '50M/50M', 50000, 50000),
-(5, '20M/20M', 20480, 20480);
-
--- --------------------------------------------------------
-
---
--- Table structure for table `remote_syslog`
---
-
-CREATE TABLE `remote_syslog` (
-  `id` int(11) NOT NULL,
-  `date` timestamp NOT NULL DEFAULT current_timestamp(),
-  `device_id` int(11) NOT NULL,
-  `ip` varchar(15) NOT NULL,
-  `message` text NOT NULL
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
--- --------------------------------------------------------
-
---
--- Table structure for table `subnets`
---
-
-CREATE TABLE `subnets` (
-  `id` int(11) NOT NULL,
-  `subnet` varchar(18) DEFAULT NULL,
-  `ip_int_start` bigint(20) NOT NULL,
-  `ip_int_stop` bigint(20) NOT NULL,
-  `dhcp_start` bigint(20) NOT NULL DEFAULT 0,
-  `dhcp_stop` bigint(20) NOT NULL DEFAULT 0,
-  `dhcp_lease_time` int(11) NOT NULL DEFAULT 480,
-  `gateway` bigint(20) NOT NULL DEFAULT 0,
-  `office` tinyint(1) NOT NULL DEFAULT 1,
-  `hotspot` tinyint(1) NOT NULL DEFAULT 0,
-  `vpn` tinyint(1) NOT NULL DEFAULT 0,
-  `free` tinyint(1) NOT NULL DEFAULT 0,
-  `dhcp` tinyint(1) NOT NULL DEFAULT 1,
-  `static` tinyint(1) NOT NULL DEFAULT 0,
-  `dhcp_update_hostname` tinyint(1) NOT NULL DEFAULT 0,
-  `discovery` tinyint(1) NOT NULL DEFAULT 1,
-  `comment` text CHARACTER SET utf8 DEFAULT NULL
-) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-
---
--- Dumping data for table `subnets`
---
-
-INSERT INTO `subnets` (`id`, `subnet`, `ip_int_start`, `ip_int_stop`, `dhcp_start`, `dhcp_stop`, `dhcp_lease_time`, `gateway`, `office`, `hotspot`, `vpn`, `free`, `dhcp`, `static`, `dhcp_update_hostname`, `discovery`, `comment`) VALUES
-(1, '192.168.0.0/16', 3232235520, 3232301055, 0, 0, 480, 0, 0, 0, 0, 1, 0, 0, 0, 0, 'Не считать трафик'),
-(2, '10.0.0.0/8', 167772160, 184549375, 0, 0, 480, 0, 0, 0, 0, 1, 0, 0, 0, 0, 'Не считать трафик'),
-(3, '172.16.0.0/12', 2886729728, 2887778303, 0, 0, 480, 0, 0, 0, 0, 1, 0, 0, 0, 0, 'Не считать трафик'),
-(4, '192.168.2.0/24', 3232236032, 3232236287, 3232236132, 3232236182, 480, 3232236033, 1, 0, 0, 0, 1, 0, 0, 1, 'Офис');
-
--- --------------------------------------------------------
-
---
--- Table structure for table `syslog`
---
-
-CREATE TABLE `syslog` (
-  `id` int(11) UNSIGNED NOT NULL,
-  `timestamp` timestamp NOT NULL DEFAULT current_timestamp(),
-  `auth_id` int(11) NOT NULL DEFAULT 0,
-  `customer` varchar(50) NOT NULL DEFAULT 'system',
-  `message` text NOT NULL,
-  `level` int(11) NOT NULL DEFAULT 1
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
--- --------------------------------------------------------
-
---
--- Table structure for table `Traffic_detail`
---
-
-CREATE TABLE `Traffic_detail` (
-  `id` bigint(20) NOT NULL,
-  `auth_id` int(11) DEFAULT NULL,
-  `router_id` int(11) NOT NULL DEFAULT 0,
-  `timestamp` timestamp NULL DEFAULT NULL,
-  `proto` int(11) DEFAULT NULL,
-  `src_ip` int(10) UNSIGNED NOT NULL,
-  `dst_ip` int(10) UNSIGNED NOT NULL,
-  `src_port` smallint(5) UNSIGNED NOT NULL,
-  `dst_port` smallint(5) UNSIGNED NOT NULL,
-  `bytes` bigint(20) NOT NULL
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
--- --------------------------------------------------------
-
---
--- Table structure for table `Unknown_mac`
---
-
-CREATE TABLE `Unknown_mac` (
-  `id` int(11) NOT NULL,
-  `mac` varchar(12) DEFAULT NULL,
-  `port_id` int(11) DEFAULT NULL,
-  `device_id` int(11) DEFAULT NULL,
-  `timestamp` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
--- --------------------------------------------------------
-
---
--- Table structure for table `User_auth`
---
-
-CREATE TABLE `User_auth` (
-  `id` int(11) NOT NULL,
-  `user_id` int(11) NOT NULL DEFAULT 0,
-  `ip` varchar(18) NOT NULL DEFAULT '',
-  `ip_int` int(10) UNSIGNED NOT NULL DEFAULT 0,
-  `ip_int_end` int(10) UNSIGNED NOT NULL DEFAULT 0,
-  `save_traf` tinyint(1) NOT NULL DEFAULT 0,
-  `enabled` tinyint(1) NOT NULL DEFAULT 0,
-  `dhcp` tinyint(1) NOT NULL DEFAULT 1,
-  `filter_group_id` tinyint(1) NOT NULL DEFAULT 0,
-  `deleted` tinyint(4) NOT NULL DEFAULT 0,
-  `comments` varchar(50) NOT NULL DEFAULT '',
-  `dns_name` varchar(60) NOT NULL DEFAULT '',
-  `dhcp_acl` text DEFAULT NULL,
-  `queue_id` int(11) NOT NULL DEFAULT 0,
-  `mac` varchar(20) NOT NULL DEFAULT '',
-  `dhcp_action` varchar(10) NOT NULL DEFAULT '',
-  `dhcp_time` datetime NOT NULL DEFAULT current_timestamp(),
-  `dhcp_hostname` varchar(60) DEFAULT NULL,
-  `last_found` datetime NOT NULL DEFAULT current_timestamp(),
-  `blocked` tinyint(1) NOT NULL DEFAULT 0,
-  `day_quota` int(11) NOT NULL DEFAULT 0,
-  `month_quota` int(11) NOT NULL DEFAULT 0,
-  `timestamp` timestamp NOT NULL DEFAULT current_timestamp(),
-  `clientid` varchar(50) NOT NULL DEFAULT '',
-  `nagios` tinyint(1) NOT NULL DEFAULT 0,
-  `nagios_status` varchar(10) NOT NULL DEFAULT '',
-  `host_model` varchar(50) NOT NULL DEFAULT '',
-  `nagios_handler` varchar(50) NOT NULL DEFAULT '',
-  `link_check` tinyint(1) NOT NULL DEFAULT 0,
-  `changed` tinyint(1) NOT NULL DEFAULT 0,
-  `changed_time` datetime NOT NULL DEFAULT current_timestamp()
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
-
--- --------------------------------------------------------
-
---
--- Table structure for table `User_list`
---
-
-CREATE TABLE `User_list` (
-  `id` int(10) UNSIGNED NOT NULL,
-  `timestamp` timestamp NOT NULL DEFAULT current_timestamp(),
-  `login` varchar(40) NOT NULL DEFAULT '',
-  `fio` varchar(60) NOT NULL DEFAULT '',
-  `enabled` tinyint(1) NOT NULL DEFAULT 1,
-  `blocked` tinyint(1) NOT NULL DEFAULT 0,
-  `deleted` tinyint(1) NOT NULL DEFAULT 0,
-  `ou_id` int(11) NOT NULL DEFAULT 0,
-  `filter_group_id` int(11) NOT NULL DEFAULT 0,
-  `queue_id` int(11) NOT NULL DEFAULT 0,
-  `day_quota` int(11) NOT NULL DEFAULT 0,
-  `month_quota` int(11) NOT NULL DEFAULT 0,
-  `default_subnet` varchar(20) DEFAULT NULL
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
---
--- Dumping data for table `User_list`
---
-
-INSERT INTO `User_list` (`id`, `timestamp`, `login`, `fio`, `enabled`, `blocked`, `deleted`, `ou_id`, `filter_group_id`, `queue_id`, `day_quota`, `month_quota`, `default_subnet`) VALUES
-(1, '2017-11-02 10:54:36', 'default', '', 0, 0, 0, 3, 2, 0, 0, 0, NULL);
-
--- --------------------------------------------------------
-
---
--- Table structure for table `User_stats`
---
-
-CREATE TABLE `User_stats` (
-  `id` int(11) NOT NULL,
-  `router_id` int(11) DEFAULT 0,
-  `auth_id` int(11) NOT NULL DEFAULT 0,
-  `timestamp` datetime NOT NULL DEFAULT current_timestamp(),
-  `byte_in` int(11) NOT NULL DEFAULT 0,
-  `byte_out` int(11) NOT NULL DEFAULT 0
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
--- --------------------------------------------------------
-
---
--- Table structure for table `User_traffic`
---
-
-CREATE TABLE `User_traffic` (
-  `auth_id` int(11) NOT NULL DEFAULT 0,
-  `router_id` int(11) NOT NULL DEFAULT 0,
-  `timestamp` datetime NOT NULL,
-  `byte_in` bigint(20) NOT NULL DEFAULT 0,
-  `byte_out` bigint(20) NOT NULL DEFAULT 0,
-  `byte_proxy` bigint(20) NOT NULL DEFAULT 0
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
--- --------------------------------------------------------
-
---
--- Table structure for table `vendors`
---
-
-CREATE TABLE `vendors` (
-  `id` int(11) NOT NULL,
-  `name` varchar(40) NOT NULL
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
---
--- Dumping data for table `vendors`
---
-
-INSERT INTO `vendors` (`id`, `name`) VALUES
-(1, 'Unknown'),
-(2, 'Eltex'),
-(3, 'Huawei'),
-(4, 'Zyxel'),
-(5, 'Raisecom'),
-(6, 'SNR'),
-(7, 'Dlink'),
-(8, 'Allied Telesis'),
-(9, 'Mikrotik'),
-(10, 'NetGear'),
-(11, 'Ubiquiti'),
-(15, 'HP'),
-(16, 'Cisco'),
-(17, 'Maipu'),
-(18, 'Asus'),
-(19, 'Linux');
-
---
--- Indexes for dumped tables
---
-
---
--- Indexes for table `building`
---
-ALTER TABLE `building`
-  ADD PRIMARY KEY (`id`);
-
---
--- Indexes for table `config`
---
-ALTER TABLE `config`
-  ADD PRIMARY KEY (`id`),
-  ADD KEY `option` (`option_id`);
-
---
--- Indexes for table `config_options`
---
-ALTER TABLE `config_options`
-  ADD PRIMARY KEY (`id`);
-
---
--- Indexes for table `connections`
---
-ALTER TABLE `connections`
-  ADD PRIMARY KEY (`id`),
-  ADD KEY `device_id` (`device_id`,`port_id`,`auth_id`);
-
---
--- Indexes for table `Customers`
---
-ALTER TABLE `Customers`
-  ADD PRIMARY KEY (`id`);
-
---
--- Indexes for table `devices`
---
-ALTER TABLE `devices`
-  ADD PRIMARY KEY (`id`),
-  ADD UNIQUE KEY `id` (`id`),
-  ADD KEY `device_model_id` (`device_model`),
-  ADD KEY `ip` (`ip`);
-
---
--- Indexes for table `device_ports`
---
-ALTER TABLE `device_ports`
-  ADD PRIMARY KEY (`id`),
-  ADD UNIQUE KEY `id` (`id`),
-  ADD KEY `device_id` (`device_id`),
-  ADD KEY `port` (`port`),
-  ADD KEY `target_port_id` (`target_port_id`);
-
---
--- Indexes for table `dhcp_log`
---
-ALTER TABLE `dhcp_log`
-  ADD PRIMARY KEY (`id`),
-  ADD KEY `timestamp` (`timestamp`),
-  ADD KEY `ip1` (`ip`);
-
---
--- Indexes for table `Filter_list`
---
-ALTER TABLE `Filter_list`
-  ADD PRIMARY KEY (`id`),
-  ADD KEY `Name` (`name`);
-
---
--- Indexes for table `Group_filters`
---
-ALTER TABLE `Group_filters`
-  ADD PRIMARY KEY (`id`),
-  ADD KEY `GroupId` (`group_id`,`filter_id`);
-
---
--- Indexes for table `Group_list`
---
-ALTER TABLE `Group_list`
-  ADD PRIMARY KEY (`id`);
-
---
--- Indexes for table `mac_history`
---
-ALTER TABLE `mac_history`
-  ADD PRIMARY KEY (`id`),
-  ADD KEY `mac` (`mac`),
-  ADD KEY `timestamp` (`timestamp`),
-  ADD KEY `ip` (`ip`);
-
---
--- Indexes for table `mac_vendors`
---
-ALTER TABLE `mac_vendors`
-  ADD PRIMARY KEY (`id`),
-  ADD UNIQUE KEY `oui` (`oui`);
-
---
--- Indexes for table `OU`
---
-ALTER TABLE `OU`
-  ADD PRIMARY KEY (`id`);
-
---
--- Indexes for table `Queue_list`
---
-ALTER TABLE `Queue_list`
-  ADD PRIMARY KEY (`id`),
-  ADD UNIQUE KEY `id` (`id`);
-
---
--- Indexes for table `remote_syslog`
---
-ALTER TABLE `remote_syslog`
-  ADD PRIMARY KEY (`id`),
-  ADD KEY `date_host` (`ip`,`date`),
-  ADD KEY `ip` (`ip`),
-  ADD KEY `date` (`date`);
-
---
--- Indexes for table `subnets`
---
-ALTER TABLE `subnets`
-  ADD PRIMARY KEY (`id`),
-  ADD KEY `static` (`static`);
-
---
--- Indexes for table `syslog`
---
-ALTER TABLE `syslog`
-  ADD PRIMARY KEY (`id`),
-  ADD KEY `timestamp` (`timestamp`),
-  ADD KEY `customer` (`customer`),
-  ADD KEY `level` (`level`),
-  ADD KEY `auth_idx` (`auth_id`);
-
---
--- Indexes for table `Traffic_detail`
---
-ALTER TABLE `Traffic_detail`
-  ADD PRIMARY KEY (`id`),
-  ADD KEY `auth_id` (`auth_id`),
-  ADD KEY `timestamp` (`timestamp`),
-  ADD KEY `src_ip` (`src_ip`),
-  ADD KEY `dst_ip` (`dst_ip`),
-  ADD KEY `router_id` (`router_id`);
-
---
--- Indexes for table `Unknown_mac`
---
-ALTER TABLE `Unknown_mac`
-  ADD PRIMARY KEY (`id`),
-  ADD KEY `timestamp` (`timestamp`);
-
---
--- Indexes for table `User_auth`
---
-ALTER TABLE `User_auth`
-  ADD PRIMARY KEY (`id`),
-  ADD UNIQUE KEY `id` (`id`),
-  ADD KEY `ip` (`ip`),
-  ADD KEY `ip_int` (`ip_int`),
-  ADD KEY `user_id` (`user_id`),
-  ADD KEY `enabled` (`enabled`),
-  ADD KEY `dhcp_action` (`dhcp_action`,`dhcp_time`),
-  ADD KEY `last_found` (`last_found`),
-  ADD KEY `ip_int_end` (`ip_int_end`),
-  ADD KEY `changed` (`changed`),
-  ADD KEY `changed_time` (`changed_time`);
-
---
--- Indexes for table `User_list`
---
-ALTER TABLE `User_list`
-  ADD PRIMARY KEY (`id`),
-  ADD KEY `login` (`login`);
-
---
--- Indexes for table `User_stats`
---
-ALTER TABLE `User_stats`
-  ADD PRIMARY KEY (`id`),
-  ADD KEY `Index_2` (`auth_id`),
-  ADD KEY `Index_3` (`auth_id`,`timestamp`),
-  ADD KEY `router_id` (`router_id`),
-  ADD KEY `timestamp` (`timestamp`),
-  ADD KEY `router_id_2` (`router_id`,`auth_id`,`timestamp`);
-
---
--- Indexes for table `User_traffic`
---
-ALTER TABLE `User_traffic`
-  ADD KEY `Index_1` (`auth_id`),
-  ADD KEY `Index_2` (`timestamp`),
-  ADD KEY `Index_3` (`auth_id`,`timestamp`),
-  ADD KEY `router_id` (`router_id`),
-  ADD KEY `auth_id` (`auth_id`,`router_id`,`timestamp`);
-
---
--- Indexes for table `vendors`
---
-ALTER TABLE `vendors`
-  ADD PRIMARY KEY (`id`);
-
---
--- AUTO_INCREMENT for dumped tables
---
-
---
--- AUTO_INCREMENT for table `building`
---
-ALTER TABLE `building`
-  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
-
---
--- AUTO_INCREMENT for table `config`
---
-ALTER TABLE `config`
-  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=103;
-
---
--- AUTO_INCREMENT for table `config_options`
---
-ALTER TABLE `config_options`
-  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=54;
-
---
--- AUTO_INCREMENT for table `connections`
---
-ALTER TABLE `connections`
-  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
-
---
--- AUTO_INCREMENT for table `Customers`
---
-ALTER TABLE `Customers`
-  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
-
---
--- AUTO_INCREMENT for table `devices`
---
-ALTER TABLE `devices`
-  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
-
---
--- AUTO_INCREMENT for table `device_ports`
---
-ALTER TABLE `device_ports`
-  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
-
---
--- AUTO_INCREMENT for table `dhcp_log`
---
-ALTER TABLE `dhcp_log`
-  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
-
---
--- AUTO_INCREMENT for table `Filter_list`
---
-ALTER TABLE `Filter_list`
-  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=105;
-
---
--- AUTO_INCREMENT for table `Group_filters`
---
-ALTER TABLE `Group_filters`
-  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=220;
-
---
--- AUTO_INCREMENT for table `Group_list`
---
-ALTER TABLE `Group_list`
-  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
-
---
--- AUTO_INCREMENT for table `mac_history`
---
-ALTER TABLE `mac_history`
-  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
-
---
--- AUTO_INCREMENT for table `mac_vendors`
---
-ALTER TABLE `mac_vendors`
-  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=38949;
-
---
--- AUTO_INCREMENT for table `OU`
---
-ALTER TABLE `OU`
-  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24;
-
---
--- AUTO_INCREMENT for table `Queue_list`
---
-ALTER TABLE `Queue_list`
-  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
-
---
--- AUTO_INCREMENT for table `remote_syslog`
---
-ALTER TABLE `remote_syslog`
-  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
-
---
--- AUTO_INCREMENT for table `subnets`
---
-ALTER TABLE `subnets`
-  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;
-
---
--- AUTO_INCREMENT for table `syslog`
---
-ALTER TABLE `syslog`
-  MODIFY `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT;
-
---
--- AUTO_INCREMENT for table `Traffic_detail`
---
-ALTER TABLE `Traffic_detail`
-  MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT;
-
---
--- AUTO_INCREMENT for table `Unknown_mac`
---
-ALTER TABLE `Unknown_mac`
-  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
-
---
--- AUTO_INCREMENT for table `User_auth`
---
-ALTER TABLE `User_auth`
-  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5815;
-
---
--- AUTO_INCREMENT for table `User_list`
---
-ALTER TABLE `User_list`
-  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1939;
-
---
--- AUTO_INCREMENT for table `User_stats`
---
-ALTER TABLE `User_stats`
-  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
-
---
--- AUTO_INCREMENT for table `vendors`
---
-ALTER TABLE `vendors`
-  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20;
-COMMIT;
-
-/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
-/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
-/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

+ 14 - 0
docs/mysql/stat_table_remote_syslog.sql

@@ -0,0 +1,14 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `remote_syslog`
+--
+
+CREATE TABLE `remote_syslog` (
+  `id` int(11) NOT NULL,
+  `date` timestamp NOT NULL DEFAULT current_timestamp(),
+  `device_id` int(11) NOT NULL,
+  `ip` varchar(15) NOT NULL,
+  `message` text NOT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;

+ 36 - 0
docs/mysql/stat_table_subnets.sql

@@ -0,0 +1,36 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `subnets`
+--
+
+CREATE TABLE `subnets` (
+  `id` int(11) NOT NULL,
+  `subnet` varchar(18) DEFAULT NULL,
+  `ip_int_start` bigint(20) NOT NULL,
+  `ip_int_stop` bigint(20) NOT NULL,
+  `dhcp_start` bigint(20) NOT NULL DEFAULT 0,
+  `dhcp_stop` bigint(20) NOT NULL DEFAULT 0,
+  `dhcp_lease_time` int(11) NOT NULL DEFAULT 480,
+  `gateway` bigint(20) NOT NULL DEFAULT 0,
+  `office` tinyint(1) NOT NULL DEFAULT 1,
+  `hotspot` tinyint(1) NOT NULL DEFAULT 0,
+  `vpn` tinyint(1) NOT NULL DEFAULT 0,
+  `free` tinyint(1) NOT NULL DEFAULT 0,
+  `dhcp` tinyint(1) NOT NULL DEFAULT 1,
+  `static` tinyint(1) NOT NULL DEFAULT 0,
+  `dhcp_update_hostname` tinyint(1) NOT NULL DEFAULT 0,
+  `discovery` tinyint(1) NOT NULL DEFAULT 1,
+  `comment` text CHARACTER SET utf8 DEFAULT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=latin1;
+
+--
+-- Дамп данных таблицы `subnets`
+--
+
+INSERT INTO `subnets` (`id`, `subnet`, `ip_int_start`, `ip_int_stop`, `dhcp_start`, `dhcp_stop`, `dhcp_lease_time`, `gateway`, `office`, `hotspot`, `vpn`, `free`, `dhcp`, `static`, `dhcp_update_hostname`, `discovery`, `comment`) VALUES
+(1, '192.168.2.0/24', 3232236032, 3232236287, 3232236132, 3232236182, 480, 3232236033, 1, 0, 0, 0, 1, 0, 0, 1, 'Офис'),
+(2, '192.168.0.0/16', 3232235520, 3232301055, 0, 0, 480, 0, 0, 0, 0, 1, 0, 0, 0, 0, 'Не считать трафик'),
+(3, '10.0.0.0/8', 167772160, 184549375, 0, 0, 480, 0, 0, 0, 0, 1, 0, 0, 0, 0, 'Не считать трафик'),
+(4, '172.16.0.0/12', 2886729728, 2887778303, 0, 0, 480, 0, 0, 0, 0, 1, 0, 0, 0, 0, 'Не считать трафик');

+ 15 - 0
docs/mysql/stat_table_syslog.sql

@@ -0,0 +1,15 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `syslog`
+--
+
+CREATE TABLE `syslog` (
+  `id` int(11) UNSIGNED NOT NULL,
+  `timestamp` timestamp NOT NULL DEFAULT current_timestamp(),
+  `auth_id` int(11) NOT NULL DEFAULT 0,
+  `customer` varchar(50) NOT NULL DEFAULT 'system',
+  `message` text NOT NULL,
+  `level` int(11) NOT NULL DEFAULT 1
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;

+ 14 - 0
docs/mysql/stat_table_variables.sql

@@ -0,0 +1,14 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `variables`
+--
+
+CREATE TABLE `variables` (
+  `id` int(11) NOT NULL,
+  `name` varchar(30) NOT NULL,
+  `value` varchar(255) DEFAULT NULL,
+  `clear_time` timestamp NOT NULL DEFAULT current_timestamp(),
+  `created` timestamp NOT NULL DEFAULT current_timestamp()
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;

+ 33 - 0
docs/mysql/stat_table_vendors.sql

@@ -0,0 +1,33 @@
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `vendors`
+--
+
+CREATE TABLE `vendors` (
+  `id` int(11) NOT NULL,
+  `name` varchar(40) NOT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Дамп данных таблицы `vendors`
+--
+
+INSERT INTO `vendors` (`id`, `name`) VALUES
+(1, 'Unknown'),
+(2, 'Eltex'),
+(3, 'Huawei'),
+(4, 'Zyxel'),
+(5, 'Raisecom'),
+(6, 'SNR'),
+(7, 'Dlink'),
+(8, 'Allied Telesis'),
+(9, 'Mikrotik'),
+(10, 'NetGear'),
+(11, 'Ubiquiti'),
+(15, 'HP'),
+(16, 'Cisco'),
+(17, 'Maipu'),
+(18, 'Asus'),
+(19, 'Linux');

+ 0 - 95
docs/nagios/Rstat/mfi.pm

@@ -1,95 +0,0 @@
-package Rstat::mfi;
-
-#use v5.28;
-use utf8;
-use open ":encoding(utf8)";
-
-use strict;
-use English;
-use FindBin '$Bin';
-use lib "$Bin";
-use base 'Exporter';
-use vars qw(@EXPORT @ISA);
-use Rstat::config;
-use Rstat::main;
-use Rstat::cmd;
-use Net::Telnet;
-use Data::Dumper;
-
-@ISA = qw(Exporter);
-@EXPORT = qw(
-get_mfi_config
-);
-
-BEGIN
-{
-
-sub get_mfi_config {
-
-my $ip = shift;
-my $login = 'admin';
-my $password = 'werkraft';
-my $result;
-
-my $ROUTER_PROMPT   = qr/[-\w]+\#.$/;
-
-eval {
-my $t = new Net::Telnet (Timeout => 30, Port => 23, Prompt =>"/$ROUTER_PROMPT/");
-#MFI02dc9fdb144bd3 login: admin
-#Password:
-#MF.v2.1.11#
-$t->open($ip);
-$t->waitfor('/login\:/');
-$t->print($login);
-$t->waitfor('/Password\:/');
-$t->print($password);
-$t->waitfor('/[#>\?]/');
-my @mca_status=log_cmd($t,'cat /etc/board.info');
-sleep(1);
-my @tmp = log_cmd($t,'grep 1 /proc/analog/enabled*');
-push(@mca_status,@tmp);
-sleep(1);
-@tmp = log_cmd($t,'cat /etc/persistent/cfg/config_file');
-$t->close();
-
-push(@mca_status,@tmp);
-
-@tmp = grep (/board.name/,@mca_status);
-my $board_type;
-if ($tmp[0]=~/=(.*)/) {
-    $board_type = $1 if ($1);
-    }
-
-return if (!$board_type);
-return if (!($board_type=~/mPort/i));
-
-my $sens_list;
-@tmp = grep (/enabled/,@mca_status);
-
-foreach my $sens (@tmp) {
-next if (!$sens);
-my $sens_id;
-my $index;
-if ($sens=~/enabled(\d):1/) {
-    $index = $1;
-    $sens_id = $index - 1;
-    }
-next if(!defined $sens_id);
-my @sens_info = grep (/AI.$sens_id.label/,@mca_status);
-my $sens_name = $sens_info[0];
-next if (!$sens_name);
-if ($sens_name=~/label=(.*)/) { $sens_name=$1; } else { undef $sens_name; }
-next if (!$sens_name);
-my $type = 'temp';
-if ($sens_name=~/HUM/i) { $type = 'hum'; }
-$result->{$sens_name}->{'name'}=$sens_name;
-$result->{$sens_name}->{'type'}=$type;
-$result->{$sens_name}->{'index'}=$index;
-}
-};
-
-return $result;
-}
-
-1;
-}

+ 0 - 411
docs/nagios/Rstat/nagios.pm

@@ -1,411 +0,0 @@
-package Rstat::nagios;
-
-#use v5.28;
-use utf8;
-use open ":encoding(utf8)";
-
-use strict;
-use English;
-use FindBin '$Bin';
-use lib "$Bin";
-use base 'Exporter';
-use vars qw(@EXPORT @ISA);
-use Rstat::config;
-use Rstat::main;
-use Rstat::mfi;
-use Time::Local;
-use Data::Dumper;
-
-@ISA = qw(Exporter);
-@EXPORT = qw(
-$nag_cmd
-nagios_send_command
-nagios_host_svc_disable
-nagios_host_svc_enable
-print_nagios_cfg
-);
-
-BEGIN
-{
-
-our $nag_cmd = "/var/spool/nagios/cmd/nagios.cmd";
-
-#---------------------------------------------------------------------------------
-
-sub nagios_send_command {
-my $command = shift;
-next if (!$command);
-if (!-e $nag_cmd) { die("Command socket $nag_cmd not found!"); }
-log_info("Send command: $command to $nag_cmd");
-open(FH, ">> $nag_cmd");
-print FH "$command\n";
-close(FH);
-}
-
-#---------------------------------------------------------------------------------
-
-sub nagios_host_svc_disable {
-my $hostname = shift;
-my $full = shift || 0;
-my $utime = timelocal(localtime());
-my $cmd = "[$utime] DISABLE_HOST_SVC_CHECKS;$hostname";
-#dont run!!!
-#check nagios option work?
-#nagios_send_command($cmd);
-if ($full) {
-    $cmd = "[$utime] DISABLE_ALL_NOTIFICATIONS_BEYOND_HOST;$hostname";
-    nagios_send_command($cmd);
-    }
-$cmd = "[$utime] DISABLE_HOST_SVC_NOTIFICATIONS;$hostname";
-nagios_send_command($cmd);
-}
-
-#---------------------------------------------------------------------------------
-
-sub nagios_host_svc_enable {
-my $hostname = shift;
-my $full = shift || 0;
-my $utime = timelocal(localtime());
-my $cmd = "[$utime] ENABLE_HOST_SVC_CHECKS;$hostname";
-nagios_send_command($cmd);
-if ($full) {
-    $cmd = "[$utime] ENABLE_ALL_NOTIFICATIONS_BEYOND_HOST;$hostname";
-    nagios_send_command($cmd);
-    }
-$cmd = "[$utime] ENABLE_HOST_SVC_NOTIFICATIONS;$hostname";
-nagios_send_command($cmd);
-}
-
-#---------------------------------------------------------------------------------
-
-sub read_host_template {
-my $device = shift;
-my $template_file = shift;
-my $result;
-my @custom_cfg=();
-if (-e $template_file) { @custom_cfg = read_file($template_file);  }
-if (@custom_cfg and scalar(@custom_cfg)) {
-    foreach my $row (@custom_cfg) {
-	next if (!$row);
-        $row=~s/\%HOSTNAME\%/$device->{name}/;
-        $row=~s/\%HOST\%/$device->{name}/;
-	$row=~s/\%HOSTIP\%/$device->{ip}/;
-        push(@{$result->{template}},$row);
-	if ($row=~/\s+service_description\s+(.*)$/i) { $result->{services}->{$1}=1; }
-	}
-    }
-return $result;
-}
-
-sub print_single_host {
-my $device = shift;
-my $ping_enable = shift || 0;
-my $group = 'any';
-my $template = 'generic-host';
-
-my $default_service="local-service";
-
-if ($device->{ou_id} ~~ [4,5,6,8,9,12,15,22,23,24,25,26,27]) {
-    #12 - WiFi AP
-    if ($device->{ou_id} eq 12 ) { $group = 'ap'; $template='ap'; }
-    #4 - VOIP
-    if ($device->{ou_id} eq 4 ) { $group = 'voip'; $template='voip'; }
-    #23 - IPAD
-    if ($device->{ou_id} eq 23 ) { $group = 'KW-GLOBAL/ipads'; $template='ipads'; }
-    #5 - IPCAM
-    if ($device->{ou_id} eq 5 ) { $group = 'videocam'; $template='ip-cam'; }
-    #26 - LAMPS
-    if ($device->{ou_id} eq 26 ) { $group = 'KW-GLOBAL/lamps'; $template='lamps'; }
-    #6 - Printers
-    if ($device->{ou_id} eq 6 ) { $group = 'printers'; $template='printers'; $default_service='printer-service'; }
-    #27 - PROJECTORS
-    if ($device->{ou_id} eq 27 ) { $group = 'KW-GLOBAL/proj'; $template='proj'; }
-    #22 - SGVR
-    if ($device->{ou_id} eq 22 ) { $group = 'KW-GLOBAL/sgvr'; $template='sgvr'; }
-    #24 - SPAV
-    if ($device->{ou_id} eq 24 ) { $group = 'KW-GLOBAL/spav'; $template='ipads2'; }
-    #25 - STE
-    if ($device->{ou_id} eq 25 ) { $group = 'KW-GLOBAL/sensors'; $template='ste'; }
-    #8 - UPS
-    if ($device->{ou_id} eq 8 ) { $group = 'ups'; $template='ups'; }
-    #9 - Охрана
-    if ($device->{ou_id} eq 9 ) { $group = 'security'; $template='security'; }
-    #15 - mfi
-    if ($device->{ou_id} eq 15 ) { $group = 'mfi'; $template='mfi'; }
-    }
-
-my $cfg_file = "/etc/nagios/".$group."/".$device->{name}.".cfg";
-open(FH, "> $cfg_file");
-print(FH "define host{\n");
-print(FH "       use                     $template\n");
-print(FH "       host_name               $device->{name}\n");
-print(FH "       alias                   $device->{name}\n");
-print(FH "       address                 $device->{ip}\n");
-print(FH "       _ID			 $device->{auth_id}\n"); 
-print(FH "       _TYPE			 user\n"); 
-if ($device->{device_model}) {
-	print(FH "       notes		$device->{device_model}\n"); 
-	}
-if ($device->{parent_name}) {
-        print(FH "       parents                    $device->{parent_name}\n");
-        }
-print(FH "       notes_url       http://stat.lan.local/admin/users/editauth.php?id=$device->{auth_id}\n");
-print(FH "       }\n\n");
-
-if ($ping_enable) {
-	print(FH "define service{\n");
-	print(FH "       use                    ping-service\n");
-	print(FH "       host_name              $device->{name}\n");
-	print(FH "       service_description    ping $device->{name}\n");
-	print(FH "       check_command          check_ping_icmp!100.0,20%!500.0,60%\n");
-	print(FH "       }\n");
-	print(FH "\n");
-    }
-if ($device->{parent_name} and $device->{link_check} and $device->{parent_snmp_version}) {
-        print(FH "define service{\n");
-        print(FH "       use                        $default_service\n");
-        print(FH "       host_name                  $device->{parent_name}\n");
-        print(FH "       service_description port $device->{parent_port} - $device->{name}\n");
-        print(FH "       check_command              check_ifoperstatus!$device->{parent_port_snmp_index}!$device->{parent_community}\n");
-        print(FH "       }\n");
-        print(FH "\n");
-        #src
-        print(FH "define service{\n");
-        print(FH "       use                        service-snmp-crc\n");
-        print(FH "       host_name                  $device->{parent_name}\n");
-        print(FH "       service_description port $device->{parent_port} - $device->{name} CRC Errors\n");
-        print(FH "       check_command              check_snmp_switch_crc!$device->{parent_community}!$device->{parent_port_snmp_index}\n");
-        print(FH "       }\n\n");
-    }
-close(FH);
-return $cfg_file;
-}
-#---------------------------------------------------------------------------------
-
-sub print_nagios_cfg {
-
-my $device = shift;
-return if (!$device);
-my $device_id = $device->{device_id};
-my $custom_cfg;
-my $device_custom_cfg = "/etc/nagios/custom-cfg/".$device->{name}.".cfg";
-if (-e $device_custom_cfg) { $custom_cfg = read_host_template($device,$device_custom_cfg); }
-$device_custom_cfg = "/etc/nagios/custom-cfg/".$device_id.".cfg";
-if (-e $device_custom_cfg) { $custom_cfg = read_host_template($device,$device_custom_cfg); }
-
-my $default_service="local-service";
-
-#switch | router
-if ($device->{type} ~~ [1,2]) {
-    my $cfg_file = "/etc/nagios/switches/".$device->{name}.".cfg";
-    my $device_template = 'switches';
-    if ($device->{type} eq 1) {  $cfg_file = "/etc/nagios/routers/".$device->{name}.".cfg"; $device_template='routers'; }
-    open(FH, "> $cfg_file");
-    print(FH "define  host {\n");
-    print(FH "       use                     $device_template\n");
-    print(FH "       host_name               $device->{name}\n");
-    print(FH "       alias                   $device->{name}\n");
-    print(FH "       address                 $device->{ip}\n");
-    print(FH "       _ID                 $device->{device_id}\n");
-    print(FH "       _TYPE                 device\n");
-    if ($device->{device_model}) {
-	print(FH "       notes		$device->{device_model}\n"); 
-	}
-    if ($device->{parent_name}) {
-        print(FH "       parents                    $device->{parent_name}\n");
-        }
-    print(FH "       notes_url       http://stat.lan.local/admin/devices/editswitches.php?id=$device->{device_id}\n");
-    print(FH "       }\n\n");
-    #ping
-    print(FH "define service{\n");
-    print(FH "        use                             ping-service         ; Name of service template to use\n");
-    print(FH "        host_name                       $device->{name}\n");
-    print(FH "        service_description             ping $device->{name}\n");
-    print(FH "        check_command                   check_ping_icmp!100.0,20%!500.0,60%\n");
-    print(FH "        }\n");
-    #uptime
-    if ($device->{snmp_version}) {
-        print(FH "define service{\n");
-	print(FH "        use                             $default_service\n");
-        print(FH "        host_name                       $device->{name}\n");
-	print(FH "        service_description             Uptime\n");
-        print(FH "        check_command                   check_snmp_uptime!$device->{community}!161!$device->{snmp_version}\n");
-	print(FH "        }\n");
-        print(FH "\n");
-        #uplink
-        if (exists $device->{uplink}) {
-	    print(FH "define service{\n");
-    	    print(FH "       use                        service-snmp-crc\n");
-            print(FH "       host_name                  $device->{name}\n");
-            my $port_description = $device->{parent_name};
-            my $conn = $device->{uplink};
-            print(FH "       service_description port $conn->{port} - $port_description CRC Errors\n");
-            print(FH "       check_command              check_snmp_switch_crc!$device->{community}!$conn->{snmp_index}\n");
-            print(FH "       }\n\n");
-    	    }
-	foreach my $conn (@{$device->{downlinks}}) {
-	    #id,port,snmp_index,comment
-	    print(FH "define service{\n");
-    	    print(FH "       use                        $default_service\n");
-            print(FH "       host_name                  $device->{name}\n");
-            my $port_description=translit($conn->{comment});
-            if ($conn->{target_port_id}) { $port_description = $conn->{downlink_name}; }
-            print(FH "       service_description port $conn->{port} - $port_description \n");
-            print(FH "       check_command              check_ifoperstatus!$conn->{snmp_index}!$device->{community}\n");
-            print(FH "       }\n\n");
-            #src
-	    print(FH "define service{\n");
-    	    print(FH "       use                        service-snmp-crc\n");
-            print(FH "       host_name                  $device->{name}\n");
-            my $port_description=translit($conn->{comment});
-            if ($conn->{target_port_id}) { $port_description = $conn->{downlink_name}; }
-            print(FH "       service_description port $conn->{port} - $port_description CRC Errors\n");
-            print(FH "       check_command              check_snmp_switch_crc!$device->{community}!$conn->{snmp_index}\n");
-            print(FH "       }\n\n");
-            #band
-	    print(FH "define service{\n");
-    	    print(FH "       use                        service-snmp-bandwidth\n");
-            print(FH "       host_name                  $device->{name}\n");
-            my $port_description=translit($conn->{comment});
-            if ($conn->{target_port_id}) { $port_description = $conn->{downlink_name}; }
-            print(FH "       service_description port $conn->{port} - $port_description bandwidth usage\n");
-            print(FH "       check_command              check_snmp_bandwidth!$device->{community}!$conn->{snmp_index}\n");
-            print(FH "       }\n\n");
-	    }
-	}
-    }
-#auth record
-if ($device->{type} eq 3) {
-    my $add_ping = 1;
-    if ($device->{ou_id} ~~ [5,22,23,24]) { $add_ping = 0; }
-    my $cfg_file = print_single_host($device,$add_ping);
-    open(FH, ">> $cfg_file");
-    #IPAD
-    if ($device->{ou_id} eq 23) {
-        print(FH "define service{\n");
-        print(FH "       use                    ipad-service\n");
-        print(FH "       host_name              $device->{name}\n");
-        print(FH "       service_description    ping $device->{name}\n");
-        print(FH "       check_command          check_ping_icmp!1000.0,20%!5000.0,60%\n");
-        print(FH "       }\n");
-        }
-    #IPCAM
-    if ($device->{ou_id} eq 5) {
-        print(FH "define service {\n");
-	print(FH "       use                     $default_service\n");
-        print(FH "       host_name               $device->{name}\n");
-	print(FH "       service_description     Snmp Model\n");
-        print(FH "       contact_groups          admins\n");
-	print(FH "       check_command           check_snmp_hikvision\n");
-        print(FH "       }\n");
-	print(FH "\n");
-	}
-    #Printers
-    if ($device->{ou_id} eq 6) {
-	my $printer_cfg;
-	if ($device->{device_model}=~/^OKI\s+/i) { $printer_cfg = read_host_template($device,'/etc/nagios/gen_template/oki.cfg'); }
-	if ($device->{device_model}=~/^HP\s+/i) { $printer_cfg = read_host_template($device,'/etc/nagios/gen_template/hp.cfg'); }
-	if ($device->{device_model}=~/^Panasonic\s+/i) { $printer_cfg = read_host_template($device,'/etc/nagios/gen_template/panasonic.cfg'); }
-	if ($device->{device_model}=~/^Epson\s+/i) { $printer_cfg = read_host_template($device,'/etc/nagios/gen_template/epson.cfg'); }
-	if ($printer_cfg->{template}) {
-	    my @printer_cfg = @{$printer_cfg->{template}};
-	    if (@printer_cfg and scalar(@printer_cfg)) {
-		foreach my $row (@printer_cfg) {
-		    next if (!$row);
-    		    print(FH $row."\n");
-		    }
-		}
-	    }
-	}
-    # PROJECTORS
-    if ($device->{ou_id} eq 27) {
-        print(FH "define service{\n");
-	print(FH "       use                             proj-service\n");
-        print(FH "       host_name                       $device->{name}\n");
-	print(FH "       service_description             Status\n");
-        print(FH "       check_command                   check_projector_simple\n");
-        print(FH "       }\n");
-	print(FH "\n");
-	}
-    #SGVR
-    if ($device->{ou_id} eq 22) {
-        print(FH "define service{\n");
-        print(FH "       use                    fast-check-mute-service\n");
-    #    print(FH "       use                   ipad-service\n");
-        print(FH "       host_name              $device->{name}\n");
-        print(FH "       service_description    ping $device->{name}\n");
-        print(FH "       check_command          check_ping_icmp!1000.0,20%!5000.0,60%\n");
-        print(FH "       }\n");
-        }
-    # SPAV
-    if ($device->{ou_id} eq 24) {
-        print(FH "define service{\n");
-    #    print(FH "       use                   fast-check-service\n");
-        print(FH "       use                    ipad-service\n");
-        print(FH "       host_name              $device->{name}\n");
-        print(FH "       service_description    ping $device->{name}\n");
-        print(FH "       check_command          check_ping_icmp!1000.0,20%!5000.0,60%\n");
-        print(FH "       }\n");
-        }
-    # STE
-    if ($device->{ou_id} eq 25) {
-	my @sensors = split(/\|/,$device->{device_model});
-	my $s_count =0;
-	foreach my $sens (@sensors) {
-	    $s_count++;
-	    my $s_id = 214+$s_count;
-	    $sens=~s/_/ /g;
-	    print(FH "define service{\n");
-	    print(FH "       use                        ste-service\n");
-	    print(FH "       host_name                  $device->{name}\n");
-	    print(FH "       service_description        $sens\n");
-	    print(FH "       check_command           check_ste-hwg!public!$s_id\n");
-	    print(FH "       }\n");
-	    print(FH "\n");
-	    }
-	}
-    # UPS
-    if ($device->{ou_id} eq 8) {
-	my $ups_cfg = read_host_template($device,'/etc/nagios/gen_template/ups.cfg');
-	if ($ups_cfg->{template}) {
-	    my @ups_cfg = @{$ups_cfg->{template}};
-	    if (@ups_cfg and scalar(@ups_cfg)) {
-		foreach my $row (@ups_cfg) {
-		    next if (!$row);
-    		    print(FH $row."\n");
-		    }
-		}
-	    }
-	}
-    # MFI
-    if ($device->{ou_id} eq 15) {
-	my $sensors = get_mfi_config($device->{ip});
-	if ($sensors) {
-	    foreach my $sensor (keys %$sensors) {
-		print(FH "define service{\n");
-		print(FH "       use                       mfi-service\n");
-	        print(FH "       host_name                 $device->{name}\n");
-		print(FH "       service_description       $sensor\n");
-		print(FH "       check_command             check_mfi!$sensors->{$sensor}->{index}!$sensors->{$sensor}->{type}\n");
-		print(FH "       }\n");
-		}
-	    }
-	}
-    }
-
-if ($custom_cfg->{template}) {
-    my @custom_cfg = @{$custom_cfg->{template}};
-    if (@custom_cfg and scalar(@custom_cfg)) {
-	foreach my $row (@custom_cfg) {
-	    next if (!$row);
-            print(FH $row."\n");
-	    }
-	}
-    }
-close(FH);
-}
-
-#---------------------------------------------------------------------------------
-
-1;
-}

+ 0 - 192
docs/nagios/gen_nagios_config.pl

@@ -1,192 +0,0 @@
-#!/usr/bin/perl
-
-use FindBin '$Bin';
-use lib "$Bin";
-use DBI;
-use File::Basename;
-use File::Find;
-use File::stat qw(:FIELDS);
-use File::Spec::Functions;
-use Sys::Hostname;
-use DirHandle;
-use Time::localtime;
-use Fcntl;
-use Tie::File;
-use Data::Dumper;
-use Net::Ping;
-use Rstat::config;
-use Rstat::main;
-use Rstat::nagios;
-use Rstat::mysql;
-
-my @cfg_dirs = (
-'/etc/nagios/switches',
-'/etc/nagios/routers',
-'/etc/nagios/ap',
-'/etc/nagios/voip',
-'/etc/nagios/KW-GLOBAL/ipads',
-'/etc/nagios/videocam',
-'/etc/nagios/KW-GLOBAL/lamps',
-'/etc/nagios/printers',
-'/etc/nagios/KW-GLOBAL/proj',
-'/etc/nagios/KW-GLOBAL/sgvr',
-'/etc/nagios/KW-GLOBAL/spav',
-'/etc/nagios/KW-GLOBAL/sensors',
-'/etc/nagios/ups',
-'/etc/nagios/security',
-'/etc/nagios/mfi',
-'/etc/nagios/any'
-);
-
-my %devices;
-my %auths;
-
-my %dependency;
-
-my @netdev_list=get_custom_records($dbh,'SELECT * FROM devices WHERE deleted=0 and nagios=1');
-
-##################################### Netdevices analyze ################################################
-if (scalar(@netdev_list)>0) {
-    foreach my $router (@netdev_list) {
-        next if (!$router);
-        my $ip = $router->{'ip'};
-        $ip =~s/\/\d+$//g;
-        my $device_id = 'netdev_'.$router->{'id'};
-        $devices{$device_id}{ip}=$ip;
-        $devices{$device_id}{community}=$router->{'community'};
-        $devices{$device_id}{name} = $router->{'device_name'};
-        $devices{$device_id}{device_model} = $router->{'device_model'};
-        $devices{$device_id}{device_id} = $router->{'id'};
-        $devices{$device_id}{snmp_version} = $router->{'snmp_version'};
-        if ($devices{$device_id}{snmp_version} eq '2') { $devices{$device_id}{snmp_version}='2c'; }
-        $devices{$device_id}{vendor_id} = $router->{'vendor_id'};
-        if ($router->{'is_router'}) { $devices{$device_id}{type}='1'; } else { $devices{$device_id}{type}='2'; }
-        $devices{$device_id}{rw_community}=$router->{'rw_community'};
-        $devices{$device_id}{fdb_snmp_index}=$router->{'fdb_snmp_index'};
-        $devices{$device_id}{user_id}=$router->{'user_id'};
-        #get uplinks
-        my $uplink_port = get_custom_record($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");
-        if ($uplink_port and $uplink_port->{target_port_id}) {
-            my $parent_uplink = get_custom_record($dbh,"SELECT * FROM device_ports WHERE id=".$uplink_port->{target_port_id}." ORDER BY id DESC");
-            if ($parent_uplink and $parent_uplink->{device_id}) {
-        	my $uplink_device = get_custom_record($dbh,"SELECT * FROM devices WHERE id=".$parent_uplink->{device_id}." AND nagios=1 AND deleted=0");
-        	if ($uplink_device) {
-        	    $devices{$device_id}{parent}='netdev_'.$uplink_device->{'id'}; 
-        	    $devices{$device_id}{parent_name}=$uplink_device->{'device_name'};
-        	    }
-        	}
-            my $uplink = get_custom_record($dbh,"SELECT * FROM device_ports WHERE id=".$uplink_port->{id}." ORDER BY id DESC");
-    	    $devices{$device_id}{parent_downlink}=$parent_uplink;
-    	    $devices{$device_id}{uplink}=$uplink;
-            }
-        #downlinks
-        my @downlinks = get_custom_records($dbh,"SELECT * FROM device_ports WHERE device_id=".$devices{$device_id}{device_id}." and target_port_id>0 and uplink=0");
-        foreach my $downlink_port (@downlinks) {
-    	    my $downlink = get_custom_record($dbh,"SELECT * FROM device_ports WHERE id=".$downlink_port->{target_port_id});
-    	    if ($downlink) {
-    		my $downlink_device = get_custom_record($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_custom_records($dbh,"SELECT * FROM device_ports WHERE device_id=".$devices{$device_id}{device_id}." and target_port_id=0 and uplink=0 and nagios=1");
-        foreach my $downlink_port (@custom_ports) {
-            #id,port,snmp_index,comment
-	    push(@{$devices{$device_id}{downlinks}},$downlink_port);
-    	    }
-        }
-    }
-
-my @auth_list=get_custom_records($dbh,'SELECT * FROM User_auth WHERE deleted=0 and nagios=1');
-
-##################################### User auth analyze ################################################
-
-if (scalar(@auth_list)>0) {
-    foreach my $auth (@auth_list) {
-        next if (!$auth);
-        my $ip = $auth->{'ip'};
-        $ip =~s/\/\d+$//g;
-        #skip doubles
-        my $device_id = 'auth_'.$auth->{'id'};
-        next if ($devices{$device_id});
-        $devices{$device_id}{ip}=$ip;
-        #get user
-        my $login = get_custom_record($dbh,"SELECT * FROM User_list WHERE id=".$auth->{'user_id'});
-        $devices{$device_id}{user_login} = $login->{login};
-        $devices{$device_id}{user_fio} = $login->{fio};
-	if ($login and $login->{ou_id}) { $devices{$device_id}{ou_id} = $login->{ou_id}; } else { $devices{$device_id}{ou_id} = 0; }
-	#name
-        if ($auth->{dns_name}) { $devices{$device_id}{name} = $auth->{dns_name}; }
-        if (!$devices{$device_id}{name} and $auth->{dhcp_hostname}) { $devices{$device_id}{name} = $auth->{dhcp_hostname}; }
-        if (!$devices{$device_id}{name}) {
-    	    if ($auth->{comments}) {
-    		$devices{$device_id}{name} = translit($auth->{comments});
-    		$devices{$device_id}{name}=~s/\(/-/g;
-    		$devices{$device_id}{name}=~s/\)/-/g;
-    		$devices{$device_id}{name}=~s/--/-/g;
-    		} else {
-    		$devices{$device_id}{name} = $login->{login}."_".$auth->{id};
-    		}
-    	    }
-        $devices{$device_id}{device_model} = $auth->{'host_model'};
-        $devices{$device_id}{auth_id} = $auth->{'id'};
-        $devices{$device_id}{nagios_handler} = $auth->{'nagios_handler'};
-        $devices{$device_id}{link_check} = $auth->{'link_check'};
-        $devices{$device_id}{type}='3';
-        $devices{$device_id}{user_id}=$auth->{'user_id'};
-        #get uplinks
-        my $uplink_port = get_custom_record($dbh,"SELECT * FROM connections WHERE auth_id=".$auth->{'id'});
-        if ($uplink_port and $uplink_port->{port_id}) {
-            my $uplink = get_custom_record($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};
-	        $devices{$device_id}{parent_port_snmp_index} = $uplink->{snmp_index};
-        	$devices{$device_id}{parent_name}=$devices{$devices{$device_id}{parent}}->{'name'};
-        	$devices{$device_id}{parent_snmp_version}=$devices{$devices{$device_id}{parent}}->{'snmp_version'};
-        	$devices{$device_id}{parent_community}=$devices{$devices{$device_id}{parent}}->{'community'};
-        	}
-            }
-        }
-    }
-
-foreach my $dir (@cfg_dirs) {
-    mkdir $dir unless (-d $dir);
-    unlink glob "$dir/*.cfg";
-}
-
-##################################### Switches config ################################################
-
-foreach my $device_id (keys %devices) {
-my $device = $devices{$device_id};
-next if (!$device->{ip});
-if ($device->{parent_name}) { push(@{$dependency{$device->{parent_name}}},$device->{name}); }
-print_nagios_cfg($device);
-}
-
-####################### Dependency ###########################
-
-open(FH,">","/etc/nagios/dependency/dep_hosts.cfg");
-foreach my $device_name (keys %dependency) {
-my @dep_list=@{$dependency{$device_name}};
-if (@dep_list and scalar(@dep_list)) {
-    my $dep_hosts;
-    foreach my $dep_host (@dep_list) {
-	next if (!$dep_host);
-	$dep_hosts = $dep_hosts.",".$dep_host;
-	}
-    next if (!$dep_hosts);
-    $dep_hosts=~s/^,//;
-    print(FH "define hostdependency {\n");
-    print(FH "       host_name			$device_name\n");
-    print(FH "       dependent_host_name	$dep_hosts\n");
-    print(FH "       execution_failure_criteria      n,u\n");
-    print(FH "       notification_failure_criteria   d,u\n");
-    print(FH "       }\n");
-    }
-}
-close(FH);
-
-exit

+ 0 - 124
docs/nagios/getcfg.pl

@@ -1,124 +0,0 @@
-#!/usr/bin/perl -w
-
-#
-# Copyright (C) Roman Dmitiriev, rnd@rajven.ru
-#
-
-use FindBin '$Bin';
-use lib "$Bin";
-use strict;
-use Time::Local;
-use FileHandle;
-use Data::Dumper;
-use Rstat::config;
-use Rstat::main;
-use Rstat::mysql;
-use Rstat::alliedtelesys;
-use Rstat::huawei;
-use Net::SSH::Expect;
-use Rstat::net_utils;
-
-$|=1;
-
-my $debug = 0;
-my %switches;
-
-my $tftp_server="192.168.11.107";
-
-sub backup_allied610 {
-my $ip = shift;
-my $name = shift || $ip;
-my $debug = shift;
-return "Fail!" if (!$ip);
-return "Fail!" if (!ping($ip));
-my $rest_cmd="sh run";
-eval {
-my $t = login_610($ip,$debug);
-telnet_string($t,$rest_cmd);
-};
-if ($@) { return "Fail!"; } else { return "OK!"; }
-}
-
-sub backup_allied8000 {
-my $ip = shift;
-my $name = shift || $ip;
-my $debug = shift;
-return "Fail!" if (!$ip);
-return "Fail!" if (!ping($ip));
-my $rest_cmd="copy running-config tftp://$tftp_server/$name.cfg";
-eval {
-my $t = login_8000($ip,$debug);
-telnet_string($t,$rest_cmd);
-};
-if ($@) { return "Fail!"; } else { return "OK!"; }
-}
-
-sub backup_allied8100 {
-my $ip = shift;
-my $name = shift || $ip;
-my $debug = shift;
-return "Fail!" if (!$ip);
-return "Fail!" if (!ping($ip));
-my $rest_cmd="copy flash tftp $tftp_server boot.cfg";
-eval {
-my $t = login_8100($ip,$debug);
-telnet_string($t,$rest_cmd);
-};
-if ($@) { return "Fail!"; } else { return "OK!"; }
-}
-
-sub backup_huawei {
-my $ip = shift;
-my $name = shift || $ip;
-my $debug = shift;
-return "Fail!" if (!$ip);
-return "Fail!" if (!ping($ip));
-eval {
-my $ssh = login_huawei($ip,'admin',$sw_password,$debug);
-huawei_run_cmd($ssh,"tftp $tftp_server put vrpcfg.zip $name.zip");
-$ssh->close if ($ssh);
-};
-if ($@) { return "Fail!"; } else { return "OK!"; }
-}
-
-sub backup_sw {
-my $sw_ip = shift;
-return if (!$sw_ip);
-print "Backup switch $switches{$sw_ip}->{name} [$sw_ip]: ";
-my $ret = "Skip!";
-if ($switches{$sw_ip}->{type}=~/huawei/i) { $ret = backup_huawei($sw_ip,$switches{$sw_ip}->{name},$debug); }
-if ($switches{$sw_ip}->{type}=~/allied8000/i) { $ret = backup_allied8000($sw_ip,$switches{$sw_ip}->{name},$debug); }
-if ($switches{$sw_ip}->{type}=~/allied8100/i) { 
-    $ret = backup_allied8100($sw_ip,$switches{$sw_ip}->{name},$debug); 
-    if ($ret) { rename "/var/lib/tftpboot/boot.cfg","/var/lib/tftpboot/$switches{$sw_ip}->{name}".".cfg"; }
-    }
-if ($switches{$sw_ip}->{type}=~/allied610/i) { $ret = backup_allied610($sw_ip,$switches{$sw_ip}->{name},$debug); }
-print "$ret\n";
-}
-
-$debug=1;
-
-my @ret=get_custom_records($dbh,'Select device_name as name, device_model as model, vendor_id, ip from devices where deleted=0 and (vendor_id=3 or vendor_id=8)');
-foreach my $dev (@ret) {
-$switches{$dev->{ip}}{ip}=$dev->{ip};
-$switches{$dev->{ip}}{model}=$dev->{model};
-$switches{$dev->{ip}}{name}=$dev->{name};
-if ($dev->{vendor_id}==3) { $switches{$dev->{ip}}{type}='huawei'; }
-if ($dev->{vendor_id}==8) {
-    if ($dev->{model}=~/8100/) { $switches{$dev->{ip}}{type}='allied8100'; }
-    if ($dev->{model}=~/8000/) { $switches{$dev->{ip}}{type}='allied8000'; }
-    if ($dev->{model}=~/x610/) { $switches{$dev->{ip}}{type}='allied610'; }
-    if ($dev->{model}=~/x210/) { $switches{$dev->{ip}}{type}='allied610'; }
-    }
-}
-
-if ($ARGV[0]) {
-    backup_sw($ARGV[0]);
-    } else {
-    foreach my $sw_ip (sort keys %switches) { 
-	next if (!exists $switches{$sw_ip}{type});
-	backup_sw($sw_ip); 
-	}
-    }
-
-exit 0;

+ 0 - 167
docs/nagios/hoststate-monitor.pl

@@ -1,167 +0,0 @@
-#!/usr/bin/perl
-
-#
-# Copyright (C) Roman Dmitiriev, rnd@rajven.ru
-#
-
-use FindBin '$Bin';
-use lib "$Bin";
-use strict;
-use Time::Local;
-use FileHandle;
-use Rstat::config;
-use Rstat::mysql;
-use Rstat::main;
-use Rstat::nagios;
-use Data::Dumper;
-use Time::Local;
-use Date::Parse;
-use Getopt::Long;
-use Proc::Daemon;
-use Cwd;
-
-my $pf = '/var/run/nagios/hoststate-monitor.pid';
-my $log = '/var/log/nagios/logs/hoststate.log';
-
-my $daemon = Proc::Daemon->new(
-        pid_file => $pf,
-        work_dir => $HOME_DIR
-);
-
-# are you running?  Returns 0 if not.
-my $pid = $daemon->Status($pf);
-
-my $daemonize = 1;
-
-GetOptions(
-    'daemon!' => \$daemonize,
-    "help"    => \&usage,
-    "reload"  => \&reload,
-    "restart" => \&restart,
-    "start"   => \&run,
-    "status"  => \&status,
-    "stop"    => \&stop
-) or &usage;
-
-exit(0);
-
-sub stop {
-        if ($pid) {
-                print "Stopping pid $pid...";
-                if ($daemon->Kill_Daemon($pf)) {
-                        print "Successfully stopped.\n";
-                } else {
-                        print "Could not find $pid.  Was it running?\n";
-                }
-         } else {
-                print "Not running, nothing to stop.\n";
-         }
-}
-
-sub status {
-        if ($pid) {
-                print "Running with pid $pid.\n";
-        } else {
-                print "Not running.\n";
-        }
-}
-
-sub run {
-if (!$pid) {
-    print "Starting...";
-    if ($daemonize) {
-        # when Init happens, everything under it runs in the child process.
-        # this is important when dealing with file handles, due to the fact
-        # Proc::Daemon shuts down all open file handles when Init happens.
-        # Keep this in mind when laying out your program, particularly if
-        # you use filehandles.
-        $daemon->Init;
-        }
-
-setpriority(0,0,19);
-
-while(1) {
-eval {
-if (!-e $log) { sleep(30); }
-open(hoststate, "tail -n 0 -F $log |") || die "$log not found!";
-
-my $hdb = init_db();
-
-while (my $logline = <hoststate>) {
-
-next unless defined $logline;
-chomp($logline);
-
-#db_log_debug($hdb,"Host event RAW: $logline");
-
-my ($date,$hoststate,$hoststatetype,$hostname,$hostip,$hostid,$hosttype,$svc_control)= split (/\|/, $logline);
-
-#db_log_debug($hdb,"Host event:  $date,$hoststate,$hoststatetype,$hostname,$hostip,$hostid,$hosttype,$svc_control");
-next if (!$hostid);
-
-if (time()-$last_refresh_config>=60) { init_option($hdb); }
-
-if (!$svc_control) { $svc_control=0; }
-
-if ($hoststate=~/UNREACHABLE/i) { $hoststate='DOWN'; }
-
-my $old_state = 'HARDDOWN';
-my $device = get_custom_record($hdb,'SELECT nagios_status,nagios_handler FROM User_auth WHERE id='.$hostid);
-if ($hosttype=~/device/i) { $device = get_custom_record($hdb,'SELECT nagios_status FROM devices WHERE id='.$hostid); }
-if ($device->{nagios_status}) { $old_state = $device->{nagios_status}; }
-
-db_log_debug($hdb,"Get old for $hostname [$hostip] id: $hostid type: $hosttype => state: $old_state");
-if ($hoststate eq "DOWN") { $hoststate=$hoststatetype.$hoststate; }
-db_log_debug($hdb,"Now for $hostname [$hostip] id: $hostid type: $hosttype => state: $hoststate");
-
-if ($hoststate !~ /$old_state/i) {
-    #disable child
-    my $full_action = ($svc_control eq 2);
-    #Change device state
-    db_log_debug($hdb,"Host changed! $hostname [$hostip] => $hoststate, old: $old_state");
-    my $ip_aton=StrToIp($hostip);
-    if ($hosttype=~/device/i) {
-	    do_sql($hdb,'UPDATE devices SET nagios_status="'.$hoststate.'" WHERE id='.$hostid);
-	    do_sql($hdb,'UPDATE User_auth SET nagios_status="'.$hoststate.'" WHERE deleted=0 AND ip_int='.$ip_aton);
-	    } else {
-	    do_sql($hdb,'UPDATE User_auth SET nagios_status="'.$hoststate.'" WHERE id='.$hostid);
-	    }
-    if ($hoststate=~/UP/i) { nagios_host_svc_enable($hostname,1); }
-    if ($hoststate=~/SOFTDOWN/i) { if ($svc_control) { nagios_host_svc_disable($hostname,$full_action); } }
-    if ($hoststate=~/HARDDOWN/i) {
-	if ($svc_control) { nagios_host_svc_disable($hostname,$full_action); }
-	if ($device->{nagios_handler}) {
-	    db_log_info($hdb,"Event handler $device->{nagios_handler} for $hostname [$hostip] => $hoststate found!");
-	    if ($device->{nagios_handler}=~/restart-port/i) {
-		    my $run_cmd = "/usr/local/scripts/restart_port_snmp.pl $hostip & ";
-    		    db_log_info($hdb,"Nagios eventhandler restart-port started for ip: $hostip");
-		    db_log_info($hdb,"Run handler: $run_cmd");
-		    system($run_cmd);
-		    }
-	    }
-	}
-    }
-}
-close(hoststate);
-};
-if ($@) { log_error("Exception found: $@"); }
-sleep(30);
-}
-    } else {
-        log_error("Already Running with pid $pid");
-    }
-}
-
-sub usage {
-    print "usage: hoststate-monitor.pl (start|stop|status|restart)\n";
-    exit(0);
-}
-
-sub reload {
-    print "reload process not implemented.\n";
-}
-
-sub restart {
-    stop;
-    run;
-}

+ 0 - 129
docs/nagios/restart_port_snmp.pl

@@ -1,129 +0,0 @@
-#!/usr/bin/perl
-
-#
-# Copyright (C) Roman Dmitiriev, rnd@rajven.ru
-#
-
-use FindBin '$Bin';
-use lib "$Bin/";
-use strict;
-use Time::Local;
-use FileHandle;
-use Data::Dumper;
-use Rstat::config;
-use Rstat::main;
-use Rstat::net_utils;
-use Rstat::mysql;
-use Rstat::snmp;
-use Net::SNMP qw(:snmp);
-
-my $pethPsePortAdminEnable ='.1.3.6.1.2.1.105.1.1.1.3.1.';
-
-my $huawei_poe_oid         ='.1.3.6.1.4.1.2011.5.25.195.3.1.3.';
-my $allied_poe_oid         ='.1.3.6.1.2.1.105.1.1.1.3.1.';
-my $hp_poe_oid             ='.1.3.6.1.2.1.105.1.1.1.3.1.';
-my $netgear_poe_oid        ='.1.3.6.1.4.1.4526.11.15.1.1.1.6.1.';
-my $mikrotik_poe_oid       ='.1.3.6.1.4.1.14988.1.1.15.1.1.3.';
-
-my $admin_status_oid       ='.1.3.6.1.2.1.2.2.1.7.';
-
-#wait for up interface
-my $sleep_time = 15;
-
-$|=1;
-
-exit if (!$ARGV[0]);
-
-my $HOST_IP = $ARGV[0];
-
-my $IP_ATON=StrToIp($HOST_IP);
-
-my $auth_id = get_id_record($dbh,'User_auth',"deleted=0 and ip_int='".$IP_ATON."'");
-if (!$auth_id) { db_log_error("Record with ip $HOST_IP not found! Bye."); exit; }
-
-my $ip;
-my $model;
-my $port;
-my $snmp_index;
-my $community;
-my $snmp_version;
-
-my $d_sql="SELECT D.ip, D.device_name, D.vendor_id, D.device_model, DP.port, DP.snmp_index, D.rw_community, D.snmp_version  FROM devices AS D, device_ports AS DP, connections AS C WHERE D.snmp_version>0 and D.id = DP.device_id AND DP.id = C.port_id AND C.auth_id=$auth_id AND DP.uplink=0";
-
-my $dev_port = get_custom_record($dbh,$d_sql);
-
-if (!$dev_port) { db_log_error($dbh,"Connection for $HOST_IP not found! Bye."); exit; }
-
-my $ip=$dev_port->{ip};
-my $model=$dev_port->{device_model};
-my $port=$dev_port->{port};
-my $vendor_id = $dev_port->{vendor_id};
-my $snmp_index=$dev_port->{snmp_index};
-my $community=$dev_port->{rw_community};
-my $snmp_version=$dev_port->{snmp_version};
-my $device_name = $dev_port->{device_name};
-
-db_log_warning($dbh,"Restart $HOST_IP at $device_name ($model $ip) [$port] request found. Try.");
-
-my $poe_oid;
-my $admin_oid;
-
-my $poe_enabled_value = 1;
-my $poe_disabled_value = 2;
-
-my $ret;
-
-#################### PORT STATE ###################
-
-#default
-$admin_oid=$admin_status_oid.$port;
-
-##################### POE #########################
-
-#default
-$poe_oid=$pethPsePortAdminEnable.$snmp_index;
-
-#Huawei
-if ($vendor_id eq 3) {
-    $poe_oid=$huawei_poe_oid.$snmp_index;
-    }
-
-#NetGear
-if ($vendor_id eq 10) {
-    $poe_oid=$netgear_poe_oid.$snmp_index;
-    }
-
-##################### Action ########################
-
-db_log_debug($dbh,"POE oid: $poe_oid");
-db_log_debug($dbh,"Admin oid: $admin_oid");
-
-if ($poe_oid) {
-    $ret=snmp_set_int($ip,$poe_oid,$poe_disabled_value,$community,161,$snmp_version);
-    db_log_info($dbh,"Try disable POE at port $port.");
-    db_log_debug($dbh,"Send to oid: $poe_oid value: $poe_disabled_value");
-    }
-
-if ($admin_oid) {
-    $ret=snmp_set_int($ip,$admin_oid,$poe_disabled_value,$community,161,$snmp_version); 
-    db_log_info($dbh,"Try shutdown port $port.");
-    db_log_debug($dbh,"Send to oid: $admin_oid value: $poe_disabled_value");
-    }
-
-sleep($sleep_time);
-
-if ($admin_oid) {
-    $ret=snmp_set_int($ip,$admin_oid,$poe_enabled_value,$community,161,$snmp_version);
-    db_log_info($dbh,"Enable POE at port $port.");
-    db_log_debug($dbh,"Send to oid: $admin_oid value: $poe_enabled_value");
-    }
-
-if ($poe_oid) {
-    $ret=snmp_set_int($ip,$poe_oid,$poe_enabled_value,$community,161,$snmp_version); 
-    db_log_info($dbh,"Up port $port.");
-    db_log_debug($dbh,"Send to oid: $poe_oid value: $poe_enabled_value");
-    }
-
-db_log_info($dbh,'Done!');
-
-exit;

+ 0 - 80
docs/nagios/scan_ipcam.pl

@@ -1,80 +0,0 @@
-#!/usr/bin/perl
-
-use FindBin '$Bin';
-use lib "$Bin";
-use DBI;
-use File::Basename;
-use File::Find;
-use File::stat qw(:FIELDS);
-use File::Spec::Functions;
-use Sys::Hostname;
-use DirHandle;
-use Time::localtime;
-use Fcntl;
-use Tie::File;
-use Data::Dumper;
-use Net::Ping;
-use Net::SNMP qw(ticks_to_time TRANSLATE_NONE);
-use Rstat::config;
-use Rstat::main;
-use Rstat::mysql;
-
-my %hik_snmp_oids=(
-'.1.3.6.1.4.1.39165.1.1.0'=>'Model',
-'.1.3.6.1.4.1.39165.1.3.0'=>'Firmware',
-'.1.3.6.1.4.1.39165.1.5.0'=>'Number',
-'.1.3.6.1.4.1.39165.1.6.0'=>'Vendor',
-);
-
-my @hik_oids=();
-foreach my $oid (keys %hik_snmp_oids) {
-push (@hik_oids,$oid);
-}
-
-sub scan_ipcam {
-
-my $ip = shift;
-my $community = shift;
-my $result ='';
-
-#eval {
-my ($session, $error) = Net::SNMP->session(
-   -hostname  => $ip,
-   -community => $community,
-   -port      => 161,
-   -version   => '2'
-);
-
-$session->translate(TRANSLATE_NONE);
-my $ret = $session->get_request( -varbindlist => [@hik_oids] );
-$result = 'ip: '.$ip;
-foreach my $oid (keys %hik_snmp_oids) {
-    $result = $result." ".$hik_snmp_oids{$oid}.": ".$ret->{$oid};
-    }
-$result = trim($result);
-#};
-return $result;
-}
-
-my @auth_list=get_custom_records($dbh,'SELECT * FROM User_auth WHERE deleted=0');
-
-##################################### User auth analyze ################################################
-
-if (scalar(@auth_list)>0) {
-    foreach my $auth (@auth_list) {
-        next if (!$auth);
-        my $ip = $auth->{'ip'};
-        $ip =~s/\/\d+$//g;
-        $devices{$device_id}{ip}=$ip;
-        #get user
-        my $login = get_custom_record($dbh,"SELECT * FROM User_list WHERE id=".$auth->{'user_id'});
-        next if ($login->{ou_id} ne 5);
-        $devices{$device_id}{device_model} = $auth->{'host_model'};
-        $devices{$device_id}{dns_name} = $auth->{'dns_name'};
-        $devices{$device_id}{auth_id} = $auth->{'id'};
-	my $snmp_info = scan_ipcam($auth->{ip},'public');
-	if ($snmp_info) { print $snmp_info."\n"; }
-        }
-    }
-
-exit;

+ 2 - 1
docs/systemd/dhcp-log.service

@@ -1,6 +1,7 @@
 [Unit]
 Description=Write dhcp events to Rstat
-After=syslog.target mariadb.service dhcpd.service
+After=syslog.target mariadb.service dnsmasq.service dhcpd.service
+PartOf=dnsmasq.service
 
 [Service]
 Type=forking

+ 0 - 12
docs/systemd/dnsmasq-log.service

@@ -1,12 +0,0 @@
-[Unit]
-Description=Write dhcp events to Rstat
-After=syslog.target mariadb.service dnsmasq.service
-
-[Service]
-Type=forking
-ExecStart=/usr/local/scripts/dnsmasq-log.pl --start
-Restart=always
-PIDFile=/var/run/dnsmasq-log.pid
-
-[Install]
-WantedBy=multi-user.target

+ 11 - 0
docs/systemd/dnsmasq.service

@@ -0,0 +1,11 @@
+[Unit]
+Description=DNS caching server
+After=network.target
+
+[Service]
+ExecStartPre=/bin/mkfifo /var/spool/dhcp-log.socket
+ExecStopPost=/bin/rm -f /var/spool/dhcp-log.socket
+ExecStart=/usr/sbin/dnsmasq -k
+
+[Install]
+WantedBy=multi-user.target

+ 0 - 8
docs/updates/20210129/patch-db-mysql-email-alert.sql

@@ -1,8 +0,0 @@
-INSERT INTO `config_options` (`id`, `option_name`, `description`, `uniq`, `type`, `default_value`) VALUES ('51', 'Email_alert', 'Отправлять e-mail сообщения для уровней сообщений WARNING & ERROR', '1', 'bool', '1');
-INSERT INTO `config_options` (`id`, `option_name`, `description`, `uniq`, `type`, `default_value`) VALUES ('52', 'Sender email', 'E-mail адрес, с которого рассылается почта', '1', 'text', 'root');
-INSERT INTO `config_options` (`id`, `option_name`, `description`, `uniq`, `type`, `default_value`) VALUES ('53', 'log level', 'Каждый уровень включает в себя предыдущий:\r\n0 - ERROR - писать только ошибки\r\n1 - WARNING - писать предупреждения\r\n2 - INFO - писать информационные сообщения\r\n3 - VERBOSE - писать подробную информацию о выполняемых операциях', '1', 'int', '2');
-
-UPDATE syslog set level = 255 WHERE level=2;
-UPDATE syslog set level = 2 WHERE level=1;
-UPDATE syslog set level = 1 WHERE level=0;
-UPDATE syslog set level = 0 WHERE level=3;

+ 0 - 3
docs/updates/20210208/db-patch-mysql-time.sql

@@ -1,3 +0,0 @@
-ALTER TABLE `User_auth` ADD `changed_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER `changed`, ADD INDEX `changed_time` (`changed_time`);
-UPDATE User_auth set changed_time=last_found;
-

+ 0 - 63
docs/updates/20210217/db-patch-alias.sql

@@ -1,63 +0,0 @@
--- phpMyAdmin SQL Dump
--- version 4.9.0.1
--- https://www.phpmyadmin.net/
---
--- Хост: localhost
--- Время создания: Фев 17 2021 г., 08:59
--- Версия сервера: 10.3.27-MariaDB
--- Версия PHP: 7.3.25
-
-SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
-SET AUTOCOMMIT = 0;
-START TRANSACTION;
-SET time_zone = "+00:00";
-
-
-/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
-/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
-/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
-/*!40101 SET NAMES utf8mb4 */;
-
---
--- База данных: `stat`
---
-
--- --------------------------------------------------------
-
---
--- Структура таблицы `User_auth_alias`
---
-
-CREATE TABLE `User_auth_alias` (
-  `id` int(11) NOT NULL,
-  `auth_id` int(11) NOT NULL,
-  `alias` varchar(100) DEFAULT NULL,
-  `description` varchar(100) DEFAULT NULL,
-  `timestamp` timestamp NOT NULL DEFAULT current_timestamp()
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
---
--- Индексы сохранённых таблиц
---
-
---
--- Индексы таблицы `User_auth_alias`
---
-ALTER TABLE `User_auth_alias`
-  ADD PRIMARY KEY (`id`),
-  ADD KEY `auth_id` (`auth_id`);
-
---
--- AUTO_INCREMENT для сохранённых таблиц
---
-
---
--- AUTO_INCREMENT для таблицы `User_auth_alias`
---
-ALTER TABLE `User_auth_alias`
-  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
-COMMIT;
-
-/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
-/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
-/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

+ 0 - 47
docs/updates/20210217/migrate-alias.pl

@@ -1,47 +0,0 @@
-#!/usr/bin/perl
-
-#
-# Copyright (C) Roman Dmitiriev, rnd@rajven.ru
-#
-
-use FindBin '$Bin';
-use lib "$Bin/";
-use strict;
-use DBI;
-use Time::Local;
-use Net::Patricia;
-use NetAddr::IP;
-use Data::Dumper;
-use Rstat::config;
-use Rstat::main;
-use Rstat::mysql;
-use Rstat::net_utils;
-use File::Basename;
-use File::Path;
-
-print "Start migration: ";
-#get userid list
-my $sSQL="SELECT id,ip,ip_int,mac,comments,dns_name FROM User_auth where deleted=0 ORDER by ip_int";
-my @users = get_custom_records($dbh,$sSQL);
-foreach my $row (@users) {
-next if (!$row);
-next if (!$row->{ip});
-next if (!$row->{dns_name} or $row->{dns_name}!~/;/);
-my @aliases=split(/;/,$row->{dns_name});
-my $auth;
-$auth->{dns_name}=trim($aliases[0]);
-foreach my $alias (@aliases) {
-    next if ($auth->{dns_name} eq $alias);
-    my $new_alias;
-    $new_alias->{auth_id}=$row->{id};
-    $new_alias->{alias}=trim($alias);
-    $new_alias->{description}=trim($alias);
-    insert_record($dbh,'User_auth_alias',$new_alias);
-    }
-update_record($dbh,'User_auth',$auth,"id=$row->{id}");
-print ".";
-}
-
-print "\n";
-
-exit 0;

+ 18 - 10
html/admin/customers/control-options.php

@@ -5,12 +5,14 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . $language . ".php");
 
 if (isset($_POST["remove"])) {
     $fid = $_POST["f_id"];
-    while (list ($key, $val) = @each($fid)) {
-        if (isset($val) and $val != 1) {
-            LOG_INFO($db_link, "Remove config option id: $val");
-            delete_record($db_link, "config", "id=" . $val);
+    if (!empty($fid)) {
+        while (list ($key, $val) = @each($fid)) {
+            if (isset($val) and $val != 1) {
+                LOG_INFO($db_link, "Remove config option id: $val");
+                delete_record($db_link, "config", "id=" . $val);
+                }
+            }
         }
-    }
     header("Location: " . $_SERVER["REQUEST_URI"]);
 }
 
@@ -23,7 +25,7 @@ if (isset($_POST['save'])) {
             if (intval($_POST['id'][$j]) != $save_id) { continue; }
             $value = $_POST['f_config_value'][$j];
             if (isset($value) and $value!=='********') {
-                $new[value] = $value;
+                $new['value'] = $value;
                 update_record($db_link, "config", "id='{$save_id}'", $new);
             }
         }
@@ -34,10 +36,11 @@ if (isset($_POST['save'])) {
 if (isset($_POST["create"])) {
     $new_option = $_POST["f_new_option"];
     if (isset($new_option)) {
-        $new[option_id] = $new_option;
+        $new['option_id'] = $new_option;
+        $new['value'] = get_option($db_link,$new_option);
         LOG_INFO($db_link, "Add config option $new_option");
         insert_record($db_link, "config", $new);
-    }
+        }
     header("Location: " . $_SERVER["REQUEST_URI"]);
 }
 
@@ -61,8 +64,9 @@ print_control_submenu($page_url);
 <td width=350><b>Комментарий</b></td>
 <td width=100><input type="submit" name="remove" value="Удалить"></td>
 </tr>
+
 <?
-$t_config = mysqli_query($db_link, "select config.id,option_id,option_name,value,type,description from config,config_options where config.option_id=config_options.id order by option_name");
+$t_config = mysqli_query($db_link, "select config.id,option_id,option_name,value,type,description,min_value,max_value from config,config_options where config.option_id=config_options.id order by option_name");
 while ($row = mysqli_fetch_array($t_config)) {
     print "<tr align=center>\n";
     print "<td class=\"data\" style='padding:0'><input type=checkbox name=f_id[] value='{$row['id']}'></td>\n";
@@ -77,7 +81,11 @@ while ($row = mysqli_fetch_array($t_config)) {
         set_option($db_link, $row['option_id'], $option_value);
     }
     if ($type == 'int') {
-        print "<input type=\"number\" name='f_config_value[]' value='$option_value'>";
+        $min = '';
+        $max = '';
+        if (!empty($row['min_value']) or $row['min_value']==0) { $min="min=".$row['min_value']; }
+        if (!empty($row['max_value'])) { $max="max=".$row['max_value']; }
+        print "<input type=\"number\" name='f_config_value[]' value='$option_value' $min $max>";
     }
     if ($type == 'text') {
         print "<input type=\"text\" name='f_config_value[]' value='$option_value' size=30>";

+ 6 - 4
html/admin/customers/control-subnets-usage.php

@@ -29,6 +29,7 @@ print "<td><b>Зомби dhcp<br>(> $zombi_days дней)</b></td>";
 </tr>
 <?
 $t_subnets = get_records($db_link,'subnets','office=1 ORDER BY ip_int_start');
+if (!empty($t_subnets)) {
 foreach ( $t_subnets as $row ) {
     print "<tr align=center>\n";
     $cl="data";
@@ -36,24 +37,25 @@ foreach ( $t_subnets as $row ) {
     $all_ips = $row['ip_int_stop']-$row['ip_int_start']-3;
     print "<td class=\"$cl\">".$all_ips."</td>\n";
 #used
-    $used_all = get_count_records($db_link,'User_auth','deleted=0 and ip_int>='.$row['ip_int_start'].' and ip_int_end<='.$row['ip_int_stop']);
+    $used_all = get_count_records($db_link,'User_auth','deleted=0 and ip_int>='.$row['ip_int_start'].' and ip_int<='.$row['ip_int_stop']);
     print "<td class=\"$cl\">".$used_all."</td>\n";
     $free_all = $all_ips - $used_all;
     print "<td class=\"$cl\">".$free_all."</td>\n";
     $dhcp_pool = $row['dhcp_stop']-$row['dhcp_start']+1;
     print "<td class=\"$cl\">".$dhcp_pool."</td>\n";
 #used pool
-    $used_dhcp = get_count_records($db_link,'User_auth','deleted=0 and ip_int>='.$row['dhcp_start'].' and ip_int_end<='.$row['dhcp_stop']);
+    $used_dhcp = get_count_records($db_link,'User_auth','deleted=0 and ip_int>='.$row['dhcp_start'].' and ip_int<='.$row['dhcp_stop']);
     print "<td class=\"$cl\">".$used_dhcp."</td>\n";
     $free_dhcp = $dhcp_pool - $used_dhcp;
     print "<td class=\"$cl\">".$free_dhcp."</td>\n";
     $free_static = $free_all -  $free_dhcp;
     print "<td class=\"$cl\">".$free_static."</td>\n";
-    $zombi = get_count_records($db_link,'User_auth','deleted=0 and ip_int>='.$row['ip_int_start'].' and ip_int_end<='.$row['ip_int_stop'].' and last_found<=(NOW() - INTERVAL '.$zombi_days.' DAY)');
+    $zombi = get_count_records($db_link,'User_auth','deleted=0 and ip_int>='.$row['ip_int_start'].' and ip_int<='.$row['ip_int_stop'].' and last_found<=(NOW() - INTERVAL '.$zombi_days.' DAY)');
     print "<td class=\"$cl\">".$zombi."</td>\n";
-    $zombi = get_count_records($db_link,'User_auth','deleted=0 and ip_int>='.$row['dhcp_start'].' and ip_int_end<='.$row['dhcp_stop'].' and last_found<=(NOW() - INTERVAL '.$zombi_days.' DAY)');
+    $zombi = get_count_records($db_link,'User_auth','deleted=0 and ip_int>='.$row['dhcp_start'].' and ip_int<='.$row['dhcp_stop'].' and last_found<=(NOW() - INTERVAL '.$zombi_days.' DAY)');
     print "<td class=\"$cl\">".$zombi."</td>\n";
     print "</tr>\n";
+    }
 }
 ?>
 </table>

+ 57 - 55
html/admin/customers/control-subnets.php

@@ -5,12 +5,14 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . $language . ".php");
 
 if (isset($_POST["s_remove"])) {
     $s_id = $_POST["s_id"];
-    while (list ($key, $val) = @each($s_id)) {
-        if (isset($val)) {
-            LOG_INFO($db_link, "Remove subnet id: $val");
-            delete_record($db_link, "subnets", "id=" . $val);
+    if (!empty($s_id)) {
+        while (list ($key, $val) = @each($s_id)) {
+            if (isset($val)) {
+                LOG_INFO($db_link, "Remove subnet id: $val");
+                delete_record($db_link, "subnets", "id=" . $val);
+                }
+            }
         }
-    }
     header("Location: " . $_SERVER["REQUEST_URI"]);
 }
 
@@ -21,65 +23,65 @@ if (isset($_POST['s_save'])) {
         $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[subnet] = trim($_POST['s_subnet'][$j]);
-            $new[office] = $_POST['s_office'][$j]*1;
-            $new[hotspot] = $_POST['s_hotspot'][$j]*1;
-            $new[vpn] = $_POST['s_vpn'][$j]*1;
-            $new[free] = $_POST['s_free'][$j]*1;
-            $new[dhcp] = $_POST['s_dhcp'][$j]*1;
-            $new[dhcp_lease_time] = $_POST['s_lease_time'][$j]*1;
+            $new['subnet'] = trim($_POST['s_subnet'][$j]);
+            $new['office'] = $_POST['s_office'][$j]*1;
+            $new['hotspot'] = $_POST['s_hotspot'][$j]*1;
+            $new['vpn'] = $_POST['s_vpn'][$j]*1;
+            $new['free'] = $_POST['s_free'][$j]*1;
+            $new['dhcp'] = $_POST['s_dhcp'][$j]*1;
+            $new['dhcp_lease_time'] = $_POST['s_lease_time'][$j]*1;
             $new['static'] = $_POST['s_static'][$j]*1;
-            $new[discovery] = $_POST['s_discovery'][$j]*1;
-            $new[dhcp_update_hostname] = $_POST['s_dhcp_update'][$j]*1;
-            $new[comment] = trim($_POST['s_comment'][$j]);
-            $range = cidrToRange($new[subnet]);
+            $new['discovery'] = $_POST['s_discovery'][$j]*1;
+            $new['dhcp_update_hostname'] = $_POST['s_dhcp_update'][$j]*1;
+            $new['comment'] = trim($_POST['s_comment'][$j]);
+            $range = cidrToRange($new['subnet']);
 	    $first_user_ip = $range[0];
 	    $last_user_ip = $range[1];
             $cidr = $range[2][1];
 	    if (isset($cidr) and $cidr <= 32) {
-	        $new[subnet] = $first_user_ip . '/' . $cidr;
+	        $new['subnet'] = $first_user_ip . '/' . $cidr;
 		} else {
-	        $new[subnet] = '';
+	        $new['subnet'] = '';
 		}
-            $new[ip_int_start] = ip2long($first_user_ip);
-	    $new[ip_int_stop] = ip2long($last_user_ip);
-            $new[dhcp_start] = ip2long(trim($_POST['s_dhcp_start'][$j]));
-            $new[dhcp_stop] = ip2long(trim($_POST['s_dhcp_stop'][$j]));
+            $new['ip_int_start'] = ip2long($first_user_ip);
+	    $new['ip_int_stop'] = ip2long($last_user_ip);
+            $new['dhcp_start'] = ip2long(trim($_POST['s_dhcp_start'][$j]));
+            $new['dhcp_stop'] = ip2long(trim($_POST['s_dhcp_stop'][$j]));
             $dhcp_fail=0;
-            if (!isset($new[dhcp_start]) or $new[dhcp_start]==0) { $dhcp_fail=1; }
-            if (!isset($new[dhcp_stop]) or $new[dhcp_stop]==0) { $dhcp_fail=1; }
-            if (!$dhcp_fail and ($new[dhcp_start]-$new[ip_int_stop] >= 0)) { $dhcp_fail=1; }
-            if (!$dhcp_fail and ($new[dhcp_start]-$new[ip_int_start] <= 0)) { $dhcp_fail=1; }
-            if (!$dhcp_fail and ($new[dhcp_stop]-$new[ip_int_stop]>=0)) { $dhcp_fail=1; }
-            if (!$dhcp_fail and ($new[dhcp_stop]-$new[ip_int_start]<=0)) { $dhcp_fail=1; }
-            if (!$dhcp_fail and ($new[dhcp_start]-$new[dhcp_stop]>=0)) { $dhcp_fail=1; }
+            if (!isset($new['dhcp_start']) or $new['dhcp_start']==0) { $dhcp_fail=1; }
+            if (!isset($new['dhcp_stop']) or $new['dhcp_stop']==0) { $dhcp_fail=1; }
+            if (!$dhcp_fail and ($new['dhcp_start']-$new['ip_int_stop'] >= 0)) { $dhcp_fail=1; }
+            if (!$dhcp_fail and ($new['dhcp_start']-$new['ip_int_start'] <= 0)) { $dhcp_fail=1; }
+            if (!$dhcp_fail and ($new['dhcp_stop']-$new['ip_int_stop']>=0)) { $dhcp_fail=1; }
+            if (!$dhcp_fail and ($new['dhcp_stop']-$new['ip_int_start']<=0)) { $dhcp_fail=1; }
+            if (!$dhcp_fail and ($new['dhcp_start']-$new['dhcp_stop']>=0)) { $dhcp_fail=1; }
             if ($dhcp_fail) {
-        	$new[dhcp_start]=ip2long($range[3]);
-        	$new[dhcp_stop]=ip2long($range[4]);
+        	$new['dhcp_start']=ip2long($range[3]);
+        	$new['dhcp_stop']=ip2long($range[4]);
         	}
 	    $gateway = ip2long(trim($_POST['s_gateway'][$j]));
 	    if (!isset($gateway)) { $gateway=$range[5]; }
-	    $new[gateway]=$gateway;
-	    if ($new[hotspot]) {
-        	$new[dhcp_update_hostname] = 0;
-        	$new[discovery] = 0;
-        	$new[vpn] = 0;
+	    $new['gateway']=$gateway;
+	    if ($new['hotspot']) {
+        	$new['dhcp_update_hostname'] = 0;
+        	$new['discovery'] = 0;
+        	$new['vpn'] = 0;
 		}
-	    if ($new[vpn]) {
-        	$new[discovery] = 0;
-        	$new[dhcp] = 0;
+	    if ($new['vpn']) {
+        	$new['discovery'] = 0;
+        	$new['dhcp'] = 0;
 		}
-	    if ($new[office]) {
-        	$new[free] = 0;
+	    if ($new['office']) {
+        	$new['free'] = 0;
         	}
-            if (!$new[office]) {
-        	$new[discovery] = 0;
-        	$new[dhcp] = 0;
+            if (!$new['office']) {
+        	$new['discovery'] = 0;
+        	$new['dhcp'] = 0;
         	$new['static'] = 0;
-        	$new[dhcp_update_hostname] = 0;
-        	$new[gateway] = 0;
-        	$new[dhcp_start] = 0;
-        	$new[dhcp_stop] = 0;
+        	$new['dhcp_update_hostname'] = 0;
+        	$new['gateway'] = 0;
+        	$new['dhcp_start'] = 0;
+        	$new['dhcp_stop'] = 0;
         	}
             update_record($db_link, "subnets", "id='{$save_id}'", $new);
         }
@@ -90,8 +92,8 @@ if (isset($_POST['s_save'])) {
 if (isset($_POST["s_create"])) {
     $new_subnet = $_POST["s_create_subnet"];
     if (isset($new_subnet)) {
-        $new[subnet] = trim($new_subnet);
-        $range = cidrToRange($new[subnet]);
+        $new['subnet'] = trim($new_subnet);
+        $range = cidrToRange($new['subnet']);
         $first_user_ip = $range[0];
         $last_user_ip = $range[1];
         $cidr = $range[2][1];
@@ -100,11 +102,11 @@ if (isset($_POST["s_create"])) {
         } else {
             $ip = $first_user_ip;
         }
-        $new[ip_int_start] = ip2long($first_user_ip);
-        $new[ip_int_stop] = ip2long($last_user_ip);
-    	$new[dhcp_start] = ip2long($range[3]);
-    	$new[dhcp_stop] = ip2long($range[4]);
-    	$new[gateway] = ip2long($range[5]);
+        $new['ip_int_start'] = ip2long($first_user_ip);
+        $new['ip_int_stop'] = ip2long($last_user_ip);
+    	$new['dhcp_start'] = ip2long($range[3]);
+    	$new['dhcp_stop'] = ip2long($range[4]);
+    	$new['gateway'] = ip2long($range[5]);
         LOG_INFO($db_link, "Create new subnet $new_subnet");
         insert_record($db_link, "subnets", $new);
     }

+ 7 - 0
html/admin/customers/control.php

@@ -68,6 +68,12 @@ if (isset($_POST["s_remove"])) {
     header("Location: " . $_SERVER["REQUEST_URI"]);
 }
 
+if (isset($_POST["clean_cache"])) {
+    LOG_INFO($db_link, "Clean dns cache");
+    run_sql($db_link,"DELETE FROM dns_cache");
+    header("Location: " . $_SERVER["REQUEST_URI"]);
+}
+
 unset($_POST);
 
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
@@ -102,6 +108,7 @@ print_control_submenu($page_url);
             print "<tr><td  align=right>Включить запись трафика у всех&nbsp<input type=submit name='save_traf_all' value='Выполнить'></td></tr>";
             print "<tr><td  align=right>Выключить запись трафика у всех&nbsp<input type=submit name='not_save_traf_all' value='Выполнить'></td></tr>";
         }
+        print "<tr><td  align=right>Сбросить кэш&nbsp<input type=submit name='clean_cache' value='Выполнить'></td></tr>";
 ?>
 <tr>
 <td align=right><a href="ipcam.php">Управление портами</a></td>

+ 3 - 3
html/admin/customers/editcustom.php

@@ -6,11 +6,11 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
 $msg_error = "";
 
 if (isset($_POST["edituser"])) {
-    $new[Login] = substr(trim($_POST["login"]), 0, 20);
+    $new['Login'] = substr(trim($_POST["login"]), 0, 20);
     if (isset($_POST["pass"]) and (strlen(trim($_POST["pass"])) > 0)) {
-        $new[Pwd] = md5($_POST["pass"]);
+        $new['Pwd'] = md5($_POST["pass"]);
     }
-    $new[readonly] = $_POST["f_ro"] * 1;
+    $new['readonly'] = $_POST["f_ro"] * 1;
     update_record($db_link, "Customers", "id='$id'", $new);
     unset($_POST["pass"]);
     header("Location: " . $_SERVER["REQUEST_URI"]);

+ 1 - 1
html/admin/customers/index.php

@@ -13,7 +13,7 @@ if (isset($_POST["create"])) {
             LOG_INFO($db_link, $msg_error);
             unset($_POST);
         } else {
-            $new[login] = $login;
+            $new['Login'] = $login;
             insert_record($db_link, "Customers", $new);
             list ($id) = mysqli_fetch_array(mysqli_query($db_link, "Select id from Customers where Login='$login' order by id DESC"));
             LOG_INFO($db_link, "Создание нового менеджера login: $login");

+ 3 - 3
html/admin/devices/building.php

@@ -28,8 +28,8 @@ if (isset($_POST['save'])) {
             $value = $_POST['f_building_name'][$j];
             $value_comment = $_POST['f_building_comment'][$j];
             if (isset($value)) {
-                $new[name] = $value;
-                $new[comment] = $value_comment;
+                $new['name'] = $value;
+                $new['comment'] = $value_comment;
                 LOG_INFO($db_link,"Изменяем расположение id='{$save_id}': name=".$value." comment=".$value_comment);
                 update_record($db_link, "building", "id='{$save_id}'", $new);
             }
@@ -41,7 +41,7 @@ if (isset($_POST['save'])) {
 if (isset($_POST["create"])) {
     $building_name = $_POST["new_building"];
     if (isset($building_name)) {
-        $new[name] = $building_name;
+        $new['name'] = $building_name;
         LOG_INFO($db_link,'Добавляем расположение $building_name');
         insert_record($db_link, "building", $new);
     }

+ 1 - 1
html/admin/devices/deleted.php

@@ -19,7 +19,7 @@ $switches = get_records($db_link,'devices','deleted=1 ORDER BY ip');
 foreach ($switches as $row) {
     print "<tr align=center>\n";
     $cl = "data";
-    if ($fdeleted) { $cl = "shutdown"; } else {
+    if ($row['deleted']) { $cl = "shutdown"; } else {
         if (isset($fnagios)) {
     	    if ($fnagios = 'DOWN') { $cl = 'down'; }
             if ($fnagios = 'UP') { $cl = 'up'; }

+ 85 - 0
html/admin/devices/edit_l3int.php

@@ -0,0 +1,85 @@
+<?php
+
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . $language . ".php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
+
+$sSQL = "SELECT * FROM devices WHERE id=$id";
+$device_info = get_record_sql($db_link, $sSQL);
+
+if (isset($_POST["s_remove"])) {
+    $s_id = $_POST["s_id"];
+    while (list ($key, $val) = @each($s_id)) {
+        if (isset($val)) {
+            LOG_INFO($db_link, "Remove l3_interface id: $val");
+            delete_record($db_link, "device_l3_interfaces", "id=" . $val);
+        }
+    }
+    header("Location: " . $_SERVER["REQUEST_URI"]);
+}
+
+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['name'] = trim($_POST['s_name'][$j]);
+            $new['interface_type'] = $_POST['s_type'][$j]*1;
+            update_record($db_link, "device_l3_interfaces", "id='{$save_id}'", $new);
+        }
+    }
+    header("Location: " . $_SERVER["REQUEST_URI"]);
+}
+
+if (isset($_POST["s_create"])) {
+    if (!empty($_POST["s_create_name"])) {
+        $new['name'] = trim($_POST["s_create_name"]);
+        $new['device_id'] = $id;
+        $new['interface_type'] = 0;
+        LOG_INFO($db_link, "Create new l3_interface ".$new['name']." as local");
+        insert_record($db_link, "device_l3_interfaces", $new);
+    }
+    header("Location: " . $_SERVER["REQUEST_URI"]);
+}
+
+unset($_POST);
+
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
+
+?>
+<div id="cont">
+<br>
+<form name="def" action="edit_l3int.php" method="post">
+<b>Список L3 интерфейсов <?php print_url($device_info['device_name'],"/admin/devices/editswitches.php?id=$id"); ?></b> <br>
+<table class="data">
+<tr align="center">
+	<td></td>
+	<td width=30><b>id</b></td>
+	<td><b>Название</b></td>
+	<td><b>Тип</b></td>
+	<td><input type="submit" name="s_remove" value="Удалить"></td>
+</tr>
+<?
+$t_l3_interface = get_records($db_link,'device_l3_interfaces',"device_id=$id ORDER BY name");
+foreach ( $t_l3_interface as $row ) {
+    print "<tr align=center>\n";
+    print "<td class=\"data\" style='padding:0'><input type=checkbox name=s_id[] value='{$row['id']}'></td>\n";
+    print "<td class=\"data\"><input type=\"hidden\" name='n_id[]' value='{$row['id']}'>{$row['id']}</td>\n";
+    print "<td class=\"data\"><input type=\"text\" name='s_name[]' value='{$row['name']}'></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']}'>Сохранить</button></td>\n";
+    print "</tr>\n";
+    }
+?>
+<tr>
+<td colspan=4>Добавить интерфейс :<?php print "<input type=\"text\" name='s_create_name' value=''";?>
+</td>
+<td><input type="submit" name="s_create" value="Добавить"></td>
+</tr>
+</table>
+</form>
+<?php
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/footer.php");
+?>

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

@@ -4,11 +4,11 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . $language . ".php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
 
 if (isset($_POST["editport"])) {
-    $new[snmp_index] = $_POST["f_snmp"] * 1;
-    $new[uplink] = $_POST["f_uplink"] * 1;
-    $new[nagios] = $_POST["f_nagios"] * 1;
-    $new[skip] = $_POST["f_skip"] * 1;
-    $new[comment] = $_POST["f_comment"];
+    $new['snmp_index'] = $_POST["f_snmp"] * 1;
+    $new['uplink'] = $_POST["f_uplink"] * 1;
+    $new['nagios'] = $_POST["f_nagios"] * 1;
+    $new['skip'] = $_POST["f_skip"] * 1;
+    $new['comment'] = $_POST["f_comment"];
     update_record($db_link, "device_ports", "id='$id'", $new);
 
     $target_id = $_POST["f_target_port"];

+ 83 - 126
html/admin/devices/editswitches.php

@@ -18,9 +18,9 @@ if (isset($_POST["editswitches"]) and isset($id)) {
             $start_port = $d_ports + 1;
             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 ++) {
-                $new[device_id] = $id;
-                $new[snmp_index] = $port;
-                $new[port] = $port;
+                $new['device_id'] = $id;
+                $new['snmp_index'] = $port;
+                $new['port'] = $port;
                 insert_record($db_link, "device_ports", $new);
             }
         }
@@ -38,52 +38,46 @@ if (isset($_POST["editswitches"]) and isset($id)) {
         }
     }
     unset($new);
-    $new[device_name] = substr($_POST["f_device_name"], 0, 50);
-    $new[device_model] = substr($_POST["f_device_model"], 0, 50);
-    $new[comment] = $_POST["f_comment"];
-    $new[ip] = substr($_POST["f_ip"], 0, 15);
-    $new[mac] = mac_dotted($_POST["f_mac"]);
-    $new[snmp_version] = $_POST["f_snmp_version"] * 1;
-    $new[community] = substr($_POST["f_community"], 0, 50);
-    $new[rw_community] = substr($_POST["f_rw_community"], 0, 50);
-    $new[queue_enabled] = $_POST["f_queue_enabled"] * 1;
-    $new[connected_user_only] = $_POST["f_connected_user_only"] * 1;
-    $new[snmp3_user_rw] = substr($_POST["f_snmp3_user_rw"], 0, 20);
-    $new[snmp3_user_ro] = substr($_POST["f_snmp3_user_ro"], 0, 20);
-    $new[snmp3_user_rw_password] = substr($_POST["f_snmp3_user_rw_password"], 0, 20);
-    $new[snmp3_user_ro_password] = substr($_POST["f_snmp3_user_ro_password"], 0, 20);
-    $new[fdb_snmp_index] = $_POST["f_fdb_snmp"];
-    $new[discovery] = $_POST["f_discovery"];
-    $new[dhcp] = $_POST["f_dhcp"] * 1;
-    $new[internet_gateway] = $_POST["f_gateway"] * 1;
-    $new[wan_int] = $_POST["f_wan"];
-    $new[lan_int] = $_POST["f_lan"];
-    $new[building_id] = $_POST["f_building_id"] * 1;
-    $new[user_id] = $_POST["f_user_id"] * 1;
-    if ($new[internet_gateway]) {
-        $new[is_router] = 1;
-    } else {
-        $new[is_router] = $_POST["f_router"];
-    }
-    $new[nagios] = $_POST["f_nagios"] * 1;
-    if (! $new[nagios]) {
-        $new[nagios_status] = 'UP';
-    }
-    $new[vendor_id] = $_POST["f_vendor_id"] * 1;
-    $new[port_count] = $sw_ports;
+    if (isset($_POST["f_device_name"])) { $new['device_name'] = substr($_POST["f_device_name"], 0, 50); }
+    if (isset($_POST["f_device_model"])) { $new['device_model'] = substr($_POST["f_device_model"], 0, 50); }
+    if (isset($_POST["f_devtype_id"])) { $new['device_type'] = $_POST["f_devtype_id"]*1; }
+    if (isset($_POST["f_comment"])) { $new['comment'] = $_POST["f_comment"]; }
+    if (isset($_POST["f_SN"])) { $new['SN'] = $_POST["f_SN"]; }
+    if (isset($_POST["f_ip"])) { $new['ip'] = substr($_POST["f_ip"], 0, 15); }
+    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_rw_community"])) { $new['rw_community'] = substr($_POST["f_rw_community"], 0, 50); }
+    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_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); }
+    if (isset($_POST["f_fdb_snmp"])) { $new['fdb_snmp_index'] = $_POST["f_fdb_snmp"]; }
+    if (isset($_POST["f_discovery"])) { $new['discovery'] = $_POST["f_discovery"]; }
+    if (isset($_POST["f_dhcp"])) { $new['dhcp'] = $_POST["f_dhcp"] * 1; }
+    if (isset($_POST["f_user_acl"])) { $new['user_acl'] = $_POST["user_acl"] * 1; }
+    if (isset($_POST["f_wan"])) { $new['wan_int'] = $_POST["f_wan"]; }
+    if (isset($_POST["f_lan"])) { $new['lan_int'] = $_POST["f_lan"]; }
+    if (isset($_POST["f_building_id"])) { $new['building_id'] = $_POST["f_building_id"] * 1; }
+    if (isset($_POST["f_user_id"])) { $new['user_id'] = $_POST["f_user_id"] * 1; }
+    if (isset($_POST["f_nagios"])) { $new['nagios'] = $_POST["f_nagios"] * 1; }
+    if (empty($new['nagios'])) { $new['nagios_status'] = 'UP'; }
+    if (isset($_POST["f_vendor_id"])) { $new['vendor_id'] = $_POST["f_vendor_id"] * 1; }
+    if (isset($_POST["f_port_count"])) { $new['port_count'] = $sw_ports; }
     update_record($db_link, "devices", "id='$id'", $new);
     header("Location: " . $_SERVER["REQUEST_URI"]);
 }
 
 if (isset($_POST["undelete"]) and isset($id)) {
     unset($new);
-    $new[deleted] = 0;
+    $new['deleted'] = 0;
     LOG_INFO($db_link, "Recovery deleted device id: $id");
     update_record($db_link, "devices", "id='$id'", $new);
     header("Location: " . $_SERVER["REQUEST_URI"]);
 }
 
-$switch=get_record($db_link,'devices',"id=".$id);
+$device=get_record($db_link,'devices',"id=".$id);
 
 unset($_POST);
 
@@ -97,64 +91,48 @@ print_editdevice_submenu($page_url,$id);
 <tr>
 <td>Название</td>
 <td>IP</td>
-<td>Mac</td>
+<td>Тип</td>
 <td>Портов</td>
-<td>Расположен</td>
 </tr>
 <?php
 print "<tr>\n";
-print "<td class=\"data\"><input type=\"text\" name='f_device_name' value='$switch[device_name]'></td>\n";
-print "<td class=\"data\"><input type=\"text\" name='f_ip' value='$switch[ip]'></td>\n";
-print "<td class=\"data\"><input type=\"text\" name='f_mac' value='$switch[mac]'></td>\n";
-print "<td class=\"data\"><input type=\"text\" name='f_port_count' value=$switch[port_count] size=5></td>\n";
-print "<td class=\"data\">";
-print_building_select($db_link, 'f_building_id', $switch[building_id]);
-print "</td>\n";
+print "<td class=\"data\"><input type=\"text\" name='f_device_name' value='".$device['device_name']."'></td>\n";
+print "<td class=\"data\"><input type=\"text\" name='f_ip' value='".$device['ip']."'></td>\n";
+print "<td class=\"data\">"; print_devtype_select($db_link,'f_devtype_id',$device['device_type']); print "</td>\n";
+print "<td class=\"data\"><input type=\"text\" name='f_port_count' value='".$device['port_count']."' size=5></td>\n";
 print "</tr>\n";
 ?>
 </tr>
 <td>Вендор</td>
 <td>Модель</td>
-<td colspan=3>Комментарий</td>
-</tr>
+<td colspan=2>SN</td>
+
 <?php
 print "<tr>\n";
-print "<td class=\"data\">";
-print_vendor_select($db_link, 'f_vendor_id', $switch[vendor_id]);
-print "</td>\n";
-print "<td class=\"data\"><input type=\"text\" name='f_device_model' value='$switch[device_model]'></td>\n";
-print "<td class=\"data\" colspan=3><input type=\"text\" size=70 name='f_comment' value='$switch[comment]'></td>\n";
+print "<td class=\"data\">"; print_vendor_select($db_link, 'f_vendor_id', $device['vendor_id']); print "</td>\n";
+print "<td class=\"data\"><input type=\"text\" name='f_device_model' value='".$device['device_model']."'></td>\n";
+print "<td class=\"data\" colspan=2><input type=\"text\" size=50 name='f_SN' value='".$device['SN']."'></td>\n";
 print "</tr>\n";
-?>
-<tr>
-<td>Шлюз в интернет</td>
-<td>Роутер</td>
-<td>DHCP-Server</td>
-<td>Шейперы</td>
-<td>Только connected юзеры</td>
-</tr>
-<?php
-print "<td class=\"data\">";
-print_qa_select('f_gateway', $switch[internet_gateway]);
-print "</td>\n";
-print "<td class=\"data\">";
-print_qa_select('f_router', $switch[is_router]);
-print "</td>\n";
-print "<td class=\"data\">";
-print_qa_select('f_dhcp', $switch[dhcp]);
-print "</td>\n";
-print "<td class=\"data\">";
-print_qa_select('f_queue_enabled', $switch[queue_enabled]);
-print "</td>\n";
-print "<td class=\"data\">";
-print_qa_select('f_connected_user_only', $switch[connected_user_only]);
-print "</td></tr>\n";
-if ($switch[is_router] or $switch[internet_gateway] or $switch[dhcp]) {
-    print "<tr><td colspan=2>WAN интерфейс</td><td colspan=2>LAN интерфейсы</td><td></td></tr>";
+
+print "<tr><td>Расположен</td><td colspan=2>Комментарий</td>";
+if (isset($device['user_id']) and $device['user_id']>0) { print "<td align=right><a href=/admin/users/edituser.php?id=".$device['user_id'].">Auth user</a><td>\n"; } else { print "<td>Auth user<td>"; }
+print "</tr><tr>";
+print "<td class=\"data\">"; print_building_select($db_link, 'f_building_id', $device['building_id']); print "</td>\n";
+print "<td class=\"data\" colspan=2><input type=\"text\" size=50 name='f_comment' value='".$device['comment']."'></td>\n";
+print "<td class=\"data\">"; print_login_select($db_link,'f_user_id', $device['user_id']); print "</td>\n";
+print "</tr>";
+
+if ($device['device_type']==2) {
+    print "<tr><td>Управление доступом</td><td>DHCP-Server</td><td>Шейперы</td><td>Только connected юзеры</td>";
+    print "<tr>";
+    print "<td class=\"data\">"; print_qa_select('f_user_acl', $device['user_acl']); print "</td>\n"; 
+    print "<td class=\"data\">"; print_qa_select('f_dhcp', $device['dhcp']); print "</td>\n";
+    print "<td class=\"data\">"; print_qa_select('f_queue_enabled', $device['queue_enabled']); print "</td>\n";
+    print "<td class=\"data\">"; print_qa_select('f_connected_user_only', $device['connected_user_only']); print "</td>\n";
+    print "</tr>\n";
+    print "<tr><td colspan=4>"; print_url("Список интерфейсов","/admin/devices/edit_l3int.php?id=$id"); print "</td></tr>";
     print "<tr>\n";
-    print "<td colspan=2 class=\"data\"><input type=\"text\" size=50 name='f_wan' value=$switch[wan_int]></td>\n";
-    print "<td colspan=2 class=\"data\"><input type=\"text\" size=50 name='f_lan' value=$switch[lan_int]></td>\n";
-    print "<td class=\"data\"></td>\n";
+    print "<td colspan=4 class=\"data\">"; print get_l3_interfaces($db_link,$device['id']); print "</td>\n";
     print "<tr>\n";
     }
 ?>
@@ -164,65 +142,44 @@ if ($switch[is_router] or $switch[internet_gateway] or $switch[dhcp]) {
 <td>Discovery</td>
 <td>Nagios</td>
 <td>
-<?php
-if (isset($switch[user_id]) and $switch[user_id]>0) { print "<a href=/admin/users/edituser.php?id=$switch[user_id]>Auth user</a>\n"; } else { print "Auth user"; }
-?>
 </td>
-</tr>
 <?php
-print "<td class=\"data\">";
-print_snmp_select('f_snmp_version', $switch[snmp_version]);
-print "</td>\n";
-print "<td class=\"data\">";
-print_qa_select('f_fdb_snmp', $switch[fdb_snmp_index]);
-print "</td>\n";
-print "<td class=\"data\">";
-print_qa_select('f_discovery', $switch[discovery]);
-print "</td>\n";
-print "<td class=\"data\">";
-print_qa_select('f_nagios', $switch[nagios]);
-print "</td>\n";
-print "<td class=\"data\">";
-print_login_select($db_link,'f_user_id', $switch[user_id]);
-print "</td>\n";
+print "<tr>\n";
+print "<td class=\"data\">"; print_snmp_select('f_snmp_version', $device['snmp_version']); print "</td>\n";
+print "<td class=\"data\">"; print_qa_select('f_fdb_snmp', $device['fdb_snmp_index']); print "</td>\n";
+print "<td class=\"data\">"; print_qa_select('f_discovery', $device['discovery']); print "</td>\n";
+print "<td class=\"data\">"; print_qa_select('f_nagios', $device['nagios']); print "</td>\n";
 print "</tr>\n";
+
+if ($device['snmp_version'] ==3) {
+    print "<tr><td>Snmpv3 RO user</td><td>Snmpv3 RW user</td><td>Snmpv3 RO password</td><td>Snmpv3 RW password</td><td></td>";
+    print "</tr><tr>";
+    print "<td class=\"data\"><input type=\"text\" name='f_snmp3_user_ro' value=".$device['snmp3_user_ro']."></td>\n";
+    print "<td class=\"data\"><input type=\"text\" name='f_snmp3_user_rw' value=".$device['snmp3_user_rw']."></td>\n";
+    print "<td class=\"data\"><input type=\"text\" name='f_snmp3_user_ro_password' value=".$device['snmp3_user_ro_password']."></td>\n";
+    print "<td class=\"data\"><input type=\"text\" name='f_snmp3_user_rw_password' value=".$device['snmp3_user_rw_password']."></td>\n";
+    print "<td></td></tr>\n";
+    }
 ?>
 <tr>
-<td>Snmpv3 RO user</td>
-<td>Snmpv3 RW user</td>
 <td>Snmp RO Community</td>
 <td>Snmp RW Community</td>
-<?php
-print "<td><button name=\"port_walk\" onclick=\"window.open('snmpwalk.php?id=" . $id . "')\">Port Walk</button>";
-?>
-<tr>
-<?php
-print "<td class=\"data\"><input type=\"text\" name='f_snmp3_user_ro' value=$switch[snmp3_user_ro]></td>\n";
-print "<td class=\"data\"><input type=\"text\" name='f_snmp3_user_rw' value=$switch[snmp3_user_rw]></td>\n";
-print "<td class=\"data\"><input type=\"text\" name='f_community' value=$switch[community]></td>\n";
-print "<td class=\"data\"><input type=\"text\" name='f_rw_community' value=$switch[rw_community]></td>\n";
-print "<td><button name=\"port_walk\" onclick=\"window.open('mactable.php?id=" . $id . "')\">Mac table</button></td>\n";
-print "</tr>\n";
-?>
-<tr>
-<td>Snmpv3 RO password</td>
-<td>Snmpv3 RW password</td>
 <td></td>
 <td></td>
 </tr>
 <?php
 print "<tr>\n";
-print "<td class=\"data\"><input type=\"text\" name='f_snmp3_user_ro_password' value=$switch[snmp3_user_ro_password]></td>\n";
-print "<td class=\"data\"><input type=\"text\" name='f_snmp3_user_rw_password' value=$switch[snmp3_user_rw_password]></td>\n";
-print "<td colspan=2>";
-if ($switch[deleted]) { print "<input type=\"submit\" name=\"undelete\" value=\"Воскресить\">"; }
-print "</td>\n";
-print "<td><input type=\"submit\" name=\"editswitches\" value=\"Сохранить\"></td>\n";
+print "<td class=\"data\"><input type=\"text\" name='f_community' value=".$device['community']."></td>\n";
+print "<td class=\"data\"><input type=\"text\" name='f_rw_community' value=".$device['rw_community']."></td>\n";
+print "<td><button name=\"port_walk\" onclick=\"window.open('mactable.php?id=" . $id . "')\">Mac table</button>\n";
+print "<button name=\"port_walk\" onclick=\"window.open('snmpwalk.php?id=" . $id . "')\">Port Walk</button>";
+print "<td align=right>";
+if ($device['deleted']) { print "<input type=\"submit\" name=\"undelete\" value=\"Воскресить\">"; }
+print "<input type=\"submit\" name=\"editswitches\" value=\"Сохранить\"></td>\n";
 print "</tr>\n";
 print "</table>\n";
 ?>
 </form>
-
 <?
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/footer.small.php");
 ?>

+ 29 - 24
html/admin/devices/index.php

@@ -1,30 +1,26 @@
 <?php
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . $language . ".php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/devtypesfilter.php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/buildingfilter.php");
+$default_sort='device_name';
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/sortfilter.php");
 
 if (isset($_POST["create"])) {
     $fname = $_POST["newswitches"];
     if ($fname) {
         global $snmp_default_version;
         global $snmp_default_community;
-        $new[device_name] = $fname;
-        $new[community] = $snmp_default_community;
-        $new[snmp_version] = $snmp_default_version;
-        insert_record($db_link, "devices", $new);
-        $sSQL = "Select id from devices where device_name='$fname' order by id DESC";
-        list ($new_id) = mysqli_fetch_array(mysqli_query($db_link, $sSQL));
+        $new['device_name'] = $fname;
+        $new['community'] = $snmp_default_community;
+        $new['snmp_version'] = $snmp_default_version;
+        $new_id=insert_record($db_link, "devices", $new);
         LOG_INFO($db_link, "Created new device device_name=$fname");
         unset($_POST);
         header("location: editswitches.php?id=$new_id");
     }
 }
 
-if (isset($_POST["building_id"])) {
-    $f_building_id = $_POST["building_id"] * 1;
-} else {
-    $f_building_id = 0;
-}
-
 if (isset($_POST["remove"])) {
     $fid = $_POST["fid"];
     while (list ($key, $val) = @each($fid)) {
@@ -33,7 +29,7 @@ if (isset($_POST["remove"])) {
             unbind_ports($db_link, $val);
             delete_record($db_link, "connections", "device_id=$val");
             delete_record($db_link, "device_ports", "device_id=$val");
-            $new[deleted] = 1;
+            $new['deleted'] = 1;
             update_record($db_link, "devices", "id='$val'", $new);
         }
     }
@@ -42,32 +38,41 @@ if (isset($_POST["remove"])) {
 unset($_POST);
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
 print_device_submenu($page_url);
+
+$sort_sql=" ORDER BY device_name";
+if (!empty($sort_field) and !empty($order)) { $sort_sql = " ORDER BY $sort_field $order"; }
+
 ?>
 <div id="cont">
 <br>
 <form name="def" action="index.php" method="post">
 <table class="data">
 <tr class="info" align="center">
-<td class="info" colspan=5>Показать оборудование из</td>
-<td class="info" colspan=5> <?php  print_building_select($db_link, "building_id", $f_building_id); ?> <input type="submit" name="apply" value="Apply"></td>
+<td class="info" colspan=3 > Тип оборудования: </td>
+<td class="info" colspan=2 > <?php  print_devtypes_select($db_link, "devtypes", $f_devtype_id); ?>
+<td class="info" >Показать оборудование из</td>
+<td class="info" > <?php  print_building_select($db_link, "building_id", $f_building_id); ?></td>
+<td class="info" colspan=3> <input type="submit" name="apply" value="Apply"></td>
 </tr>
 <tr align="center">
 <td><input type="checkbox" onClick="checkAll(this.checked);"></td>
-<td><b>id</b></td>
-<td><b>Название</b></td>
-<td><b>IP</b></td>
-<td><b>Модель</b></td>
-<td><b>Расположен</b></td>
+<td><b><a href=index.php?sort=id&order=<?php print $new_order; ?>>id</a></b></td>
+<td><b><a href=index.php?sort=device_type&order=<?php print $new_order; ?>>Тип</a></b></td>
+<td><b><a href=index.php?sort=device_name&order=<?php print $new_order; ?>>Название</a></b></td>
+<td><b><a href=index.php?sort=ip&order=<?php print $new_order; ?>>IP</a></b></td>
+<td><b><a href=index.php?sort=device_model&order=<?php print $new_order; ?>>Модель</a></b></td>
+<td><b><a href=index.php?sort=building_id&order=<?php print $new_order; ?>>Расположен</a></b></td>
 <td><b>Портов</b></td>
 <td><b>Nagios</b></td>
-<td><b>Router</b></td>
 <td><b>Discavery</b></td>
 </tr>
 <?
 $filter = '';
-if ($f_building_id > 0) { $filter = ' and building_id=' . $f_building_id; }
+if ($f_building_id > 0) { $filter .= ' and building_id=' . $f_building_id; }
+if ($f_devtype_id > 0) { $filter .= ' and device_type=' . $f_devtype_id; }
 
-$switches = get_records($db_link,'devices','deleted=0 '.$filter.' ORDER BY ip');
+$dSQL = 'SELECT * FROM devices WHERE deleted=0 '.$filter.' '.$sort_sql;
+$switches = get_records_sql($db_link,$dSQL);
 foreach ($switches as $row) {
     print "<tr align=center>\n";
     $cl = "data";
@@ -77,6 +82,7 @@ foreach ($switches as $row) {
     }
     print "<td class=\"$cl\" style='padding:0'><input type=checkbox name=fid[] value=".$row['id']."></td>\n";
     print "<td class=\"$cl\"><input type=hidden name=\"id\" value=".$row['id'].">".$row['id']."</td>\n";
+    print "<td class=\"$cl\">".get_devtype_name($db_link,$row['device_type'])."</td>\n";
     print "<td class=\"$cl\" align=left><a href=editswitches.php?id=".$row['id'].">" . $row['device_name'] . "</a></td>\n";
     if (isset($row['user_id']) and $row['user_id']>0) {
         print "<td class=\"$cl\"><a href=/admin/users/edituser.php?id=".$row['user_id'].">".$row['ip']."</a></td>\n";
@@ -87,7 +93,6 @@ foreach ($switches as $row) {
     print "<td class=\"$cl\">" . get_building($db_link, $row['building_id']) . "(" . $row['comment'] . ")</td>\n";
     print "<td class=\"$cl\">".$row['port_count']."</td>\n";
     print "<td class=\"$cl\">" . get_qa($row['nagios']) . "</td>\n";
-    print "<td class=\"$cl\">" . get_qa($row['is_router']) . "</td>\n";
     print "<td class=\"$cl\">" . get_qa($row['discovery']) . "</td>\n";
 }
 ?>

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

@@ -15,8 +15,8 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
 <?php
 $dev = get_record($db_link,'devices',"id=$id");
 $ports = get_records($db_link,'device_ports',"device_id=$id AND uplink=0 ORDER BY port");
-print "<b>Список маков активных на свиче $dev[device_name] ($dev[ip]):</b>\n";
-$fdb = get_fdb_table($dev[ip], $dev[community], $dev[snmp_version]);
+print "<b>Список маков активных на свиче ".$dev['device_name']." (".$dev['ip']."):</b>\n";
+$fdb = get_fdb_table($dev['ip'], $dev['community'], $dev['snmp_version']);
 print "<table class=\"data\" cellspacing=\"1\" cellpadding=\"4\">\n";
 print "<tr>";
 print "<td>Port</td>\n";
@@ -25,11 +25,11 @@ print "<td>Mac</td>\n";
 print "</tr>";
 foreach ($ports as $port) {
     foreach ($fdb as $a_mac => $a_port) {
-	if ($a_port == $port[port]) {
+	if ($a_port == $port['port']) {
 		print "<tr>";
 		print "<td class=\"data\">" . $a_port . "</td>\n";
 	        $auth = get_auth_by_mac($db_link, dec_to_hex($a_mac));
-                print "<td class=\"data\">" .$auth[auth] . "</td><td class=\"data\">". $auth[mac]."</td>\n";
+                print "<td class=\"data\">" .$auth['auth'] . "</td><td class=\"data\">". $auth['mac']."</td>\n";
 		print "</tr>";
 		}
     }

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

@@ -30,7 +30,7 @@ if ($f_snmp_index > 0) {
     foreach ($fdb as $a_mac => $a_port) {
         print "<tr>";
         $auth = get_auth_by_mac($db_link, dec_to_hex($a_mac));
-        print "<td class=\"data\">" .$auth[auth] . "</td><td class=\"data\">". $auth[mac]."</td>\n";
+        print "<td class=\"data\">" .$auth['auth'] . "</td><td class=\"data\">". $auth['mac']."</td>\n";
         print "</tr>";
     }
     print "</table>\n";

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

@@ -1,9 +1,9 @@
 <?php
+$default_displayed=100;
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . $language . ".php");
 $default_id=1;
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
-$default_displayed=100;
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
 print_device_submenu($page_url);
 ?>

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

@@ -23,10 +23,10 @@ print_editdevice_submenu($page_url,$id);
 
 ?>
 <div id="cont">
-<form name="def" action="switchport-conn.php?id=<? echo $id; ?>" method="post">
+<form name="def" action="switchport-conn.php?id=<?php echo $id; ?>" method="post">
 <br>
 
-<?php print "<b>Список соединений на портах $switch[device_name] - $switch[ip]</b><br>\n"; ?>
+<?php print "<b>Список соединений на портах ".$switch['device_name']." - ".$switch['ip']."</b><br>\n"; ?>
 
 <table class="data">
 <tr>
@@ -42,10 +42,10 @@ $connections = get_records($db_link,"connections","device_id=$id ORDER BY port_i
 foreach ($connections as $key => $value) {
 print "<tr align=center>\n";
 print "<td class=\"data\" style='padding:0'><input type=checkbox name=f_id[] value='{$value['id']}'></td>\n";
-$port = get_record($db_link,"device_ports","id=$value[port_id]");
-print "<td class=\"data\">". $port[port] . "</a></td>\n";
+$port = get_record($db_link,"device_ports","id=".$value['port_id']);
+print "<td class=\"data\">". $port['port'] . "</a></td>\n";
 print "<td class=\"data\">";
-print_auth_detail($db_link, $value[auth_id]);
+print_auth_detail($db_link, $value['auth_id']);
 print "</td>\n";
 print "<td class=\"data\"></td>\n";
 print "</tr>";

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

@@ -10,7 +10,7 @@ if (isset($_POST["regensnmp"])) {
     LOG_DEBUG($db_link, "Recalc snmp_index for device id: $id with start $snmp_index");
     while (list ($port_id, $port) = mysqli_fetch_array($flist)) {
         $snmp = $port + $snmp_index - 1;
-        $new[snmp_index] = $snmp;
+        $new['snmp_index'] = $snmp;
         update_record($db_link, "device_ports", "id='$port_id'", $new);
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);
@@ -29,7 +29,7 @@ print_editdevice_submenu($page_url,$id);
 
 <?php
 print "<br>\n";
-print "<b>Список портов $switch[device_name] - $switch[ip]</b><br>\n";
+print "<b>Список портов ".$switch['device_name']." - ".$switch['ip']."</b><br>\n";
 
 print "<table class=\"data\" cellspacing=\"1\" cellpadding=\"4\">\n";
 print "<tr>\n";
@@ -68,7 +68,7 @@ if ($d_uplink) { $cl="info"; }
         print "<td class=\"$cl\">" . $d_vlan . "</td>\n";
 
         global $torrus_url;
-        $cacti_url = get_cacti_graph($switch[ip], $d_snmp);
+        $cacti_url = get_cacti_graph($switch['ip'], $d_snmp);
         if (! isset($torrus_url) and (! isset($cacti_url))) {
                 print "<td class=\"$cl\"></td>\n";
         	} else {
@@ -80,11 +80,11 @@ if ($d_uplink) { $cl="info"; }
 	            $normed_ifname = trim(str_replace(".", "_", $normed_ifname));
 	            $normed_ifname = trim(str_replace(" ", "_", $normed_ifname));
         	    $pattern = '/cisco/i';
-        	    preg_match($pattern, $switch[device_model], $matches);
+        	    preg_match($pattern, $switch['device_model'], $matches);
         	    if (isset($matches[0])) {
                 	$normed_ifname = trim(str_replace("Gi", "GigabitEthernet", $normed_ifname));
         		}
-                    $t_url = str_replace("HOST_IP", $switch[ip], $torrus_url);
+                    $t_url = str_replace("HOST_IP", $switch['ip'], $torrus_url);
 	            $t_url = str_replace("IF_NAME", $normed_ifname, $t_url);
 	            $snmp_url = "<a href=\"$t_url\">Статистика</a>";
         	    }

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

@@ -5,42 +5,42 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
 
 $switch=get_record($db_link,'devices',"id=".$id);
 
-if (isset($_POST['poe_on']) and $switch[snmp_version]>0) {
+if (isset($_POST['poe_on']) and $switch['snmp_version']>0) {
     $len = is_array($_POST['poe_on']) ? count($_POST['poe_on']) : 0;
     for ($i = 0; $i < $len; $i ++) {
         $port_index = intval($_POST['poe_on'][$i]);
         LOG_DEBUG($db_link, "Device id: $id enable poe at port snmp index $port_index");
-        set_port_poe_state($switch[vendor_id], $port_index, $switch[ip], $switch[rw_community], $switch[snmp_version], 1);
+        set_port_poe_state($switch['vendor_id'], $port_index, $switch['ip'], $switch['rw_community'], $switch['snmp_version'], 1);
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);
 }
 
-if (isset($_POST['poe_off']) and $switch[snmp_version]>0) {
+if (isset($_POST['poe_off']) and $switch['snmp_version']>0) {
     $len = is_array($_POST['poe_off']) ? count($_POST['poe_off']) : 0;
     for ($i = 0; $i < $len; $i ++) {
         $port_index = intval($_POST['poe_off'][$i]);
         LOG_DEBUG($db_link, "Device id: $id disable poe at port snmp index $port_index");
-        set_port_poe_state($switch[vendor_id], $port_index, $switch[ip], $switch[rw_community], $switch[snmp_version], 0);
+        set_port_poe_state($switch['vendor_id'], $port_index, $switch['ip'], $switch['rw_community'], $switch['snmp_version'], 0);
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);
 }
 
-if (isset($_POST['port_on']) and $switch[snmp_version]>0) {
+if (isset($_POST['port_on']) and $switch['snmp_version']>0) {
     $len = is_array($_POST['port_on']) ? count($_POST['port_on']) : 0;
     for ($i = 0; $i < $len; $i ++) {
         $port_index = intval($_POST['port_on'][$i]);
         LOG_DEBUG($db_link, "Device id: $id enable port with snmp index $port_index");
-        set_port_state($switch[vendor_id], $port_index, $switch[ip], $switch[rw_community], $switch[snmp_version], 1);
+        set_port_state($switch['vendor_id'], $port_index, $switch['ip'], $switch['rw_community'], $switch['snmp_version'], 1);
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);
 }
 
-if (isset($_POST['port_off']) and $switch[snmp_version]>0) {
+if (isset($_POST['port_off']) and $switch['snmp_version']>0) {
     $len = is_array($_POST['port_off']) ? count($_POST['port_off']) : 0;
     for ($i = 0; $i < $len; $i ++) {
         $port_index = intval($_POST['port_off'][$i]);
         LOG_DEBUG($db_link, "Device id: $id disable port with snmp index $port_index");
-        set_port_state($switch[vendor_id], $port_index, $switch[ip], $switch[rw_community], $switch[snmp_version], 0);
+        set_port_state($switch['vendor_id'], $port_index, $switch['ip'], $switch['rw_community'], $switch['snmp_version'], 0);
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);
 }
@@ -56,17 +56,17 @@ print_editdevice_submenu($page_url,$id);
 
 <?php
 print "<br>\n";
-print "<b>Состояние портов $switch[device_name] - $switch[ip]</b><br>\n";
+print "<b>Состояние портов ".$switch['device_name']." - ".$switch['ip']."</b><br>\n";
 
-if ($switch[snmp_version]>0) {
-        $snmp_ok = check_snmp_access($switch[ip], $switch[community], $switch[snmp_version]);
+if ($switch['snmp_version']>0) {
+        $snmp_ok = check_snmp_access($switch['ip'], $switch['community'], $switch['snmp_version']);
 	if ($snmp_ok) {
 	    global $cisco_modules;
-            if ($switch[snmp_version] == 2) {
-	        $modules_oids = snmp2_real_walk($switch[ip], $switch[community], $cisco_modules);
+            if ($switch['snmp_version'] == 2) {
+	        $modules_oids = snmp2_real_walk($switch['ip'], $switch['community'], $cisco_modules);
 	    }
             if ($switch[snmp_version] == 1) {
-	        $modules_oids = snmpreal_walk($switch[ip], $switch[community], $cisco_modules);
+	        $modules_oids = snmpreal_walk($switch['ip'], $switch['community'], $cisco_modules);
 	    }
 	}
     } else { $snmp_ok = 0; }
@@ -97,8 +97,8 @@ if ($switch[snmp_version]>0) {
     while (list ($d_id, $d_snmp, $d_port, $d_comment, $d_target_id, $d_mac_count, $d_uplink, $d_nagios, $d_skip, $d_vlan) = mysqli_fetch_array($flist)) {
         print "<tr align=center>\n";
         $cl = "up";
-        if (isset($switch[ip]) and ($switch[ip] != '') and $snmp_ok) {
-            $port_state_detail = get_port_state_detail($d_snmp, $switch[ip], $switch[community], $switch[snmp_version], $switch[fdb_snmp_index]);
+        if (isset($switch['ip']) and ($switch['ip'] != '') and $snmp_ok) {
+            $port_state_detail = get_port_state_detail($d_snmp, $switch['ip'], $switch['community'], $switch['snmp_version'], $switch['fdb_snmp_index']);
             list ($poper, $padmin, $pspeed, $perrors) = explode(';', $port_state_detail);
             if (preg_match('/up/i', $poper)) {
                 $cl = "up";
@@ -128,13 +128,13 @@ if ($switch[snmp_version]>0) {
         print "<td class=\"$cl\">" . $d_comment . "</td>\n";
         if ($snmp_ok) {
             if ($switch[fdb_snmp_index]) {
-                $vlan = get_port_vlan($d_snmp, $switch[ip], $switch[community], $switch[snmp_version], $switch[fdb_snmp_index]);
+                $vlan = get_port_vlan($d_snmp, $switch['ip'], $switch['community'], $switch['snmp_version'], $switch['fdb_snmp_index']);
             } else {
-                $vlan = get_port_vlan($d_port, $switch[ip], $switch[community], $switch[snmp_version], $switch[fdb_snmp_index]);
+                $vlan = get_port_vlan($d_port, $switch['ip'], $switch['community'], $switch['snmp_version'], $switch['fdb_snmp_index']);
             }
-            $ifname = get_snmp_ifname($switch[ip], $switch[community], $switch[snmp_version], $d_snmp);
-            $sfp_status = get_sfp_status($switch[vendor_id], $d_snmp, $switch[ip], $switch[community], $switch[snmp_version], $modules_oids);
-            $poe_status = get_port_poe_state($switch[vendor_id], $d_snmp, $switch[ip], $switch[community], $switch[snmp_version]);
+            $ifname = get_snmp_ifname($switch['ip'], $switch['community'], $switch['snmp_version'], $d_snmp);
+            $sfp_status = get_sfp_status($switch['vendor_id'], $d_snmp, $switch['ip'], $switch['community'], $switch['snmp_version'], $modules_oids);
+            $poe_status = get_port_poe_state($switch['vendor_id'], $d_snmp, $switch['ip'], $switch['community'], $switch['snmp_version']);
             if (!isset($vlan)) { $vlan = $d_vlan; }
             print "<td class=\"$cl\">" . $vlan . "</td>\n";
             $speed = "0";
@@ -173,7 +173,7 @@ if ($switch[snmp_version]>0) {
             }
             print "<td class=\"$cl_error\">" . $perrors . "</td>\n";
             global $torrus_url;
-            $cacti_url = get_cacti_graph($switch[ip], $d_snmp);
+            $cacti_url = get_cacti_graph($switch['ip'], $d_snmp);
             if (! isset($torrus_url) and (! isset($cacti_url))) {
                 print "<td class=\"$cl\">" . $ifname . "</td>\n";
             } else {
@@ -185,11 +185,11 @@ if ($switch[snmp_version]>0) {
                     $normed_ifname = trim(str_replace(".", "_", $normed_ifname));
                     $normed_ifname = trim(str_replace(" ", "_", $normed_ifname));
                     $pattern = '/cisco/i';
-                    preg_match($pattern, $switch[device_model], $matches);
+                    preg_match($pattern, $switch['device_model'], $matches);
                     if (isset($matches[0])) {
                         $normed_ifname = trim(str_replace("Gi", "GigabitEthernet", $normed_ifname));
                     }
-                    $t_url = str_replace("HOST_IP", $switch[ip], $torrus_url);
+                    $t_url = str_replace("HOST_IP", $switch['ip'], $torrus_url);
                     $t_url = str_replace("IF_NAME", $normed_ifname, $t_url);
                     $snmp_url = "<a href=\"$t_url\">" . $ifname . "</a>";
                 }
@@ -198,7 +198,7 @@ if ($switch[snmp_version]>0) {
             print "<td class=\"$cl\">" . $sfp_status;
             if (isset($poe_status)) {
                 if ($poe_status == 1) {
-                    $port_poe_detail = get_port_poe_detail($switch[vendor_id], $d_snmp, $switch[ip], $switch[community], $switch[snmp_version]);
+                    $port_poe_detail = get_port_poe_detail($switch['vendor_id'], $d_snmp, $switch['ip'], $switch['community'], $switch['snmp_version']);
                     print "POE:On " . $port_poe_detail;
                 }
                 if ($poe_status == 2) {
@@ -206,9 +206,9 @@ if ($switch[snmp_version]>0) {
                 }
             }
             print "</td>\n";
-            if (isset($poe_status) and ! $d_skip and ! $switch[is_router]) {
+            if (isset($poe_status) and ! $d_skip and ! $switch['is_router']) {
                 print "<td class=\"data\">";
-                if ($switch[vendor_id] != 9) {
+                if ($switch['vendor_id'] != 9) {
                     if ($poe_status == 2) {
                         print "<button name='poe_on[]' value='{$d_snmp}'>POE On</button>";
                 	}
@@ -222,9 +222,9 @@ if ($switch[snmp_version]>0) {
         	} else {
         	print "<td>Not supported</td>\n";
         	}
-            if (isset($padmin) and ! $d_uplink and ! $d_skip and ! $switch[is_router]) {
+            if (isset($padmin) and ! $d_uplink and ! $d_skip and ! $switch['is_router']) {
                 print "<td class=\"data\">";
-                if ($switch[vendor_id] != 9) {
+                if ($switch['vendor_id'] != 9) {
                     if (preg_match('/down/i', $padmin)) {
                         print "<button name='port_on[]' value='{$d_snmp}'>Enable port</button>";
                 	}

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

@@ -4,11 +4,11 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . $language . ".php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
 
 if (isset($_POST["editfilter"])) {
-    $new[name] = $_POST["f_name"];
-    $new[dst] = $_POST["f_dst"];
-    $new[proto] = $_POST["f_proto"];
-    $new[dstport] = str_replace(':', '-', $_POST["f_dstport"]);
-    $new[action] = $_POST["f_action"] * 1;
+    $new['name'] = $_POST["f_name"];
+    $new['dst'] = $_POST["f_dst"];
+    $new['proto'] = $_POST["f_proto"];
+    $new['dstport'] = str_replace(':', '-', $_POST["f_dstport"]);
+    $new['action'] = $_POST["f_action"] * 1;
     update_record($db_link, "Filter_list", "id='$id'", $new);
     unset($_POST);
     header("location: index.php");
@@ -32,7 +32,7 @@ if (isset($filter['type']) and $filter['type'] == 0) {
     print "<td ><b>Порт</b></td>";
     print "<td ><b>Действие</b></td>";
 
-    print "</tr><td align=left><input type=text name=f_name value=".$filter['Name']."></td>";
+    print "</tr><td align=left><input type=text name=f_name value=".$filter['name']."></td>";
     print "<td ><input type=text name=f_proto value=".$filter['proto']."></td>";
     print "<td ><input type=text name=f_dst value=".$filter['dst']."></td>";
     print "<td ><input type=text name=f_dstport value=".$filter['dstport']."></td>";
@@ -47,7 +47,7 @@ if (isset($filter['type']) and $filter['type'] == 0) {
     print "<td ><b>Адрес назначения</b></td>";
     print "<td ><b>Действие</b></td></tr>";
 
-    print "<td align=left><input type=text name=f_name value=".$filter['Name']."></td>";
+    print "<td align=left><input type=text name=f_name value=".$filter['name']."></td>";
     print "<td ><input type=text name=f_dst value=".$filter['dst']."></td>";
     print_action_select('f_action', $filter['action']);
     print "<tr><td colspan=2><input type=submit name=editfilter value=Сохранить></td>";

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

@@ -4,7 +4,7 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . $language . ".php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
 
 if (isset($_POST["editgroup"])) {
-    $new[group_name] = substr($_POST["f_group_name"], 0, 30);
+    $new['group_name'] = substr($_POST["f_group_name"], 0, 30);
     update_record($db_link, "Group_list", "id='$id'", $new);
     header("location: index.php");
 }
@@ -13,9 +13,9 @@ if (isset($_POST["addfilter"])) {
     $filter_id = $_POST["newfilter"] * 1;
     list ($forder) = mysqli_fetch_array(mysqli_query($db_link, "SELECT MAX(GF.order) FROM Group_filters GF where group_id='$id'"));
     $forder ++;
-    $new[group_id] = $id;
-    $new[filter_id] = $filter_id;
-    $new[order] = $forder;
+    $new['group_id'] = $id;
+    $new['filter_id'] = $filter_id;
+    $new['order'] = $forder;
     insert_record($db_link, "Group_filters", $new);
     header("Location: " . $_SERVER["REQUEST_URI"]);
 }
@@ -36,7 +36,7 @@ if (isset($_POST["saveorder"])) {
         LOG_DEBUG($db_link, "Resort filter rules for group id: $id");
         while (list ($key, $val) = @each($ford)) {
             $gid = $fgid[$key];
-            $new[order] = $val;
+            $new['order'] = $val;
             update_record($db_link, "Group_filters", "id=" . $gid, $new);
         }
     }
@@ -70,13 +70,13 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
 </tr>
 
 <?php
-$sSQL = "SELECT G.id, G.filter_id, F.Name, G.order FROM Group_filters G, Filter_list F WHERE F.id=G.filter_id and group_id=$id Order by G.order";
+$sSQL = "SELECT G.id, G.filter_id, F.name, G.order FROM Group_filters G, Filter_list F WHERE F.id=G.filter_id and group_id=$id Order by G.order";
 $flist = get_records_sql($db_link,$sSQL);
 foreach ($flist as $row) {
     print "<tr align=center>\n";
     print "<td class=\"data\" style='padding:0'><input type=checkbox name=fgid[] value=".$row['id']."></td>\n";
     print "<td class=\"data\" align=left><input type=text name=ford[] value=".$row['order']." size=4 ></td>\n";
-    print "<td class=\"data\" align=left><a href=editfilter.php?id=".$row['filter_id'].">" . $row['Name'] . "</a></td>\n";
+    print "<td class=\"data\" align=left><a href=editfilter.php?id=".$row['filter_id'].">" . $row['name'] . "</a></td>\n";
     print "<td class=\"data\"></td>\n";
     print "</tr>";
 }

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

@@ -5,10 +5,9 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . $language . ".php");
 if (isset($_POST["create"])) {
     $fname = $_POST["newgroup"];
     if ($fname) {
-        $new[group_name] = $fname;
-        insert_record($db_link, "Group_list", $new);
-        list ($new_id) = mysqli_fetch_array(mysqli_query($db_link, "Select id from Group_list where group_name='$fname' order by id DESC"));
-        header("location: editgroup.php?id=$new_id[0]");
+        $new['group_name'] = $fname;
+        $new_id=insert_record($db_link, "Group_list", $new);
+        header("location: editgroup.php?id=$new_id");
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);
 }

+ 5 - 6
html/admin/filters/index.php

@@ -9,10 +9,9 @@ if (isset($_POST["create"])) {
         $ftype = $_POST["filter_type"] * 1;
 	}
     if (isset($fname)) {
-        $new[Name] = $fname;
-        $new[type] = $ftype;
-        insert_record($db_link, "Filter_list", $new);
-        $new_id=get_record_field($db_link,'Filter_list','id',"Name='".$fname."' and type=".$ftype." ORDER BY id DESC");
+        $new['name'] = $fname;
+        $new['type'] = $ftype;
+        $new_id=insert_record($db_link, "Filter_list", $new);
         header("Location: editfilter.php?id=$new_id");
 	}
     }
@@ -45,12 +44,12 @@ print_filters_submenu($page_url);
 		<td><b>Действие</b></td>
 	</tr>
 <?
-$filters = get_records($db_link,'Filter_list','TRUE ORDER BY Name');
+$filters = get_records($db_link,'Filter_list','TRUE ORDER BY name');
 foreach ($filters as $row) {
     print "<tr align=center>\n";
     print "<td class=\"data\" style='padding:0'><input type=checkbox name=fid[] value=".$row['id']."></td>\n";
     print "<td class=\"data\" ><input type=hidden name=\"id\" value=".$row['id'].">".$row['id']."</td>\n";
-    print "<td class=\"data\" align=left><a href=editfilter.php?id=".$row['id'].">" . $row['Name'] . "</a></td>\n";
+    print "<td class=\"data\" align=left><a href=editfilter.php?id=".$row['id'].">" . $row['name'] . "</a></td>\n";
     if ($row['type'] == 0) {
         print "<td class=\"data\">IP фильтр</td>\n";
         print "<td class=\"data\">".$row['proto']."</td>\n";

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

@@ -6,7 +6,7 @@ if (isset($_POST["remove"])) {
     $fid = $_POST["f_id"];
     while (list ($key, $val) = @each($fid)) {
         if (isset($val) and $val > 0) {
-            $new[ou_id] = 0;
+            $new['ou_id'] = 0;
             update_record($db_link, "User_list", "ou_id=" . $val, $new);
             delete_record($db_link, "OU", "id=" . $val);
         }
@@ -28,7 +28,7 @@ if (isset($_POST['save'])) {
             }
             $value = $_POST['f_group_name'][$j];
             if (isset($value)) {
-                $new[ou_name] = $value;
+                $new['ou_name'] = $value;
                 update_record($db_link, "OU", "id='{$save_id}'", $new);
             }
         }
@@ -39,7 +39,7 @@ if (isset($_POST['save'])) {
 if (isset($_POST["create"])) {
     $ou_name = $_POST["new_ou"];
     if (isset($ou_name)) {
-        $new[ou_name] = $ou_name;
+        $new['ou_name'] = $ou_name;
         insert_record($db_link, "OU", $new);
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);

+ 1 - 1
html/admin/index.php

@@ -1,3 +1,3 @@
 <?php
-header("location: /admin/iplist/index.php");
+header("location: /admin/reports/index-full.php");
 ?>

+ 2 - 2
html/admin/iplist/deleted.php

@@ -1,7 +1,7 @@
 <?php
+$default_displayed = 500;
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . $language . ".php");
-$default_displayed = 500;
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
 $default_sort='ip_int';
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/oufilter.php");
@@ -28,7 +28,7 @@ if (!empty($f_comment)) { $comment_filter=" and (User_auth.comments LIKE '$f_com
 
 if ($rsubnet == 0) { $subnet_filter = ''; } else {
     $subnet_range = get_subnet_range($db_link,$rsubnet);
-    $subnet_filter = " and User_auth.ip_int>=$subnet_range[start] and User_auth.ip_int<=$subnet_range[stop] ";
+    $subnet_filter = " and User_auth.ip_int>=".$subnet_range['start']." and User_auth.ip_int<=".$subnet_range['stop'];
     }
 
 $ip_list_filter = $subnet_filter.$comment_filter;

+ 104 - 0
html/admin/iplist/doubles.php

@@ -0,0 +1,104 @@
+<?php
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . $language . ".php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
+
+if (isset($_POST["removeauth"])) {
+    $auth_id = $_POST["f_auth_id"];
+    while (list ($key, $val) = @each($auth_id)) {
+        if ($val) {
+                delete_record($db_link, 'connections', "auth_id=" . $val);
+                delete_record($db_link, 'User_auth_alias', "auth_id=" . $val);
+                $auth["deleted"] = 1;
+                $changes = get_diff_rec($db_link,"User_auth","id='$val'", '', 0);
+                if (!empty($changes)) { LOG_WARNING($db_link,"Удалён адрес доступа: \r\n $changes"); }
+                update_record($db_link, "User_auth", "id=" . $val, $auth);
+                delete_record($db_link, "connections", "auth_id=" . $val);
+                }
+            }
+    header("Location: " . $_SERVER["REQUEST_URI"]);
+    }
+
+print_ip_submenu($page_url);
+?>
+<div id="cont">
+<br>
+<form name="def" action="doubles.php" method="post">
+<table class="data">
+<tr>
+    <td class="data"><input type="checkbox" onClick="checkAll(this.checked);"></td>
+    <td align=Center><?php print $cell_login; ?></td>
+    <td align=Center><?php print $cell_ip; ?></td>
+    <td align=Center><?php print $cell_mac ; ?></td>
+    <td align=Center><?php print $cell_comment; ?></td>
+    <td align=Center><?php print $cell_dns_name; ?></td>
+    <td align=Center>Создан</td>
+    <td align=Center>Работал</td>
+    <td align=right><input type="submit" name="removeauth" value="Удалить выделенных"></td>
+</tr>
+<?php
+$sSQL = "SELECT U.id, U.ip, U.mac, S.subnet as net FROM User_auth U, subnets S WHERE (U.mac IS NOT NULL AND U.mac<>'') AND (U.ip_int BETWEEN S.ip_int_start AND S.ip_int_stop) AND S.office=1 AND deleted=0 ORDER BY net,mac,ip";
+$users = get_records_sql($db_link,$sSQL);
+$f_subnet=NULL;
+$f_mac=NULL;
+$f_id=NULL;
+$printed = NULL;
+foreach ($users as $row) {
+    if (empty($f_subnet)) { $f_subnet = $row['net']; $f_mac=$row['mac']; $f_id=$row['id']; continue; }
+    if ($row['net'] === $f_subnet and $row['mac']===$f_mac) {
+        if (!isset($printed[$f_id])) {
+            $user = get_record_sql($db_link,"SELECT * FROM User_auth WHERE id=".$f_id);
+            if (empty($user['last_found']) or $user['last_found'] === '0000-00-00 00:00:00') { $user['last_found'] = ''; }
+            if (empty($user['timestamp']) or $user['timestamp'] === '0000-00-00 00:00:00') { $user['timestamp'] = ''; }
+            if (empty($user['changed_time']) or $user['changed_time'] === '0000-00-00 00:00:00') { $user['changed_time'] = ''; }
+            print "<tr align=center>\n";
+            $cl = "data";
+            print "<td class=\"data\" style='padding:0'><input type=checkbox name=f_auth_id[] value=".$user["id"]." ></td>\n";
+            print "<td class=\"$cl\" ><a href=/admin/users/edituser.php?id=".$user['user_id'].">" . get_login($db_link,$user['user_id']) . "</a></td>\n";
+            print "<td class=\"$cl\" ><a href=/admin/users/editauth.php?id=".$user['id'].">" . $user['ip'] . "</a></td>\n";
+            print "<td class=\"$cl\" >" . expand_mac($db_link,$user['mac']) . "</td>\n";
+            if (isset($user['dhcp_hostname']) and strlen($user['dhcp_hostname']) > 0) {
+                print "<td class=\"$cl\" >".$user['comments']." [" . $user['dhcp_hostname'] . "]</td>\n";
+                } else {
+                print "<td class=\"$cl\" >".$user['comments']."</td>\n";
+                }
+            print "<td class=\"$cl\" >".$user['dns_name']."</td>\n";
+            print "<td class=\"$cl\" >".$user['timestamp']."</td>\n";
+            print "<td class=\"$cl\" >".$user['last_found']."</td>\n";
+            print "</tr>\n";
+            $printed[$f_id] = 1;
+            }
+        if (!isset($printed[$row['id']])) {
+            $user = get_record_sql($db_link,"SELECT * FROM User_auth WHERE id=".$row['id']);
+            if (empty($user['last_found']) or $user['last_found'] === '0000-00-00 00:00:00') { $user['last_found'] = ''; }
+            if (empty($user['timestamp']) or $user['timestamp'] === '0000-00-00 00:00:00') { $user['timestamp'] = ''; }
+            if (empty($user['changed_time']) or $user['changed_time'] === '0000-00-00 00:00:00') { $user['changed_time'] = ''; }
+            print "<tr align=center>\n";
+            $cl = "data";
+            print "<td class=\"data\" style='padding:0'><input type=checkbox name=f_auth_id[] value=".$user["id"]." ></td>\n";
+            print "<td class=\"$cl\" ><a href=/admin/users/edituser.php?id=".$user['user_id'].">" . get_login($db_link,$user['user_id']) . "</a></td>\n";
+            print "<td class=\"$cl\" ><a href=/admin/users/editauth.php?id=".$user['id'].">" . $user['ip'] . "</a></td>\n";
+            print "<td class=\"$cl\" >" . expand_mac($db_link,$user['mac']) . "</td>\n";
+            if (isset($user['dhcp_hostname']) and strlen($user['dhcp_hostname']) > 0) {
+                print "<td class=\"$cl\" >".$user['comments']." [" . $user['dhcp_hostname'] . "]</td>\n";
+                } else {
+                print "<td class=\"$cl\" >".$user['comments']."</td>\n";
+                }
+            print "<td class=\"$cl\" >".$user['dns_name']."</td>\n";
+            print "<td class=\"$cl\" >".$user['timestamp']."</td>\n";
+            print "<td class=\"$cl\" >".$user['last_found']."</td>\n";
+            print "</tr>\n";
+            $printed[$row['id']] = 1;
+            }
+        }
+    $f_subnet = $row['net'];
+    $f_mac=$row['mac'];
+    $f_id=$row['id'];
+    }
+print "</table>\n";
+?>
+</form>
+<br>
+<?php
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/footer.php");
+?>

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

@@ -1,7 +1,7 @@
 <?php
+$default_displayed=500;
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . $language . ".php");
-$default_displayed = 500;
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
 $default_sort='ip_int';
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/oufilter.php");
@@ -21,7 +21,7 @@ if ($rou == 0) { $ou_filter = ''; } else { $ou_filter = " and User_list.ou_id=$r
 
 if ($rsubnet == 0) { $subnet_filter = ''; } else {
     $subnet_range = get_subnet_range($db_link,$rsubnet);
-    $subnet_filter = " and User_auth.ip_int>=$subnet_range[start] and User_auth.ip_int<=$subnet_range[stop] ";
+    if (!empty($subnet_range)) { $subnet_filter = " and User_auth.ip_int>=".$subnet_range['start']." and User_auth.ip_int<=".$subnet_range['stop']; }
     }
 
 $enabled_filter='';

+ 8 - 13
html/admin/logout.html

@@ -1,6 +1,7 @@
 <!DOCTYPE html>
 <head>
 <meta http-equiv="Content-Type" content="text/html;" />
+<link rel="stylesheet" type="text/css" href="/white.css">
 <meta charset="utf-8" />
 <title>Выход</title>
 
@@ -42,18 +43,12 @@ return xmlhttp;
 
 </head>
 <body>
-	<table>
-		<tr>
-			<td align="center" valign="middle">
-				<p>
-					<font size="+1">Чао.</font>
-				</p>
-				<p>
-					<font size="+1"><a href="/admin/">Войти</a></font>
-				</p>
-				<p>&nbsp;</p>*
-			</td>
-		</tr>
-	</table>
+<div align=center>
+<table>
+<tr>
+<td align="center" valign="middle"><p><font size="+1">Welcome</font></p><p><font size="+1"><a href="/admin/">Войти</a></font></p><p>&nbsp;</p>*</td>
+</tr>
+</table>
+</div>
 </body>
 </html>

+ 2 - 2
html/admin/logs/authlog.php

@@ -38,7 +38,7 @@ if (isset($log_filter)) { $log_filter = $log_filter." and auth_id=".$auth_id; }
 if (isset($fcustomer)) { $log_filter = $log_filter." and customer LIKE '%".$fcustomer."%'"; }
 if (isset($fmessage)) { $log_filter = $log_filter." and message LIKE '%".$fmessage."%'"; }
 
-$countSQL="SELECT Count(*) FROM syslog WHERE date(timestamp)>='$date1' AND date(timestamp)<'$date2' $log_filter";
+$countSQL="SELECT Count(*) FROM syslog WHERE `timestamp`>='$date1' AND `timestamp`<'$date2' $log_filter";
 $res = mysqli_query($db_link, $countSQL);
 $count_records = mysqli_fetch_array($res);
 
@@ -58,7 +58,7 @@ print_navigation($page_url,$page,$displayed,$count_records[0],$total);
 	</tr>
 <?php
 #speedup paging
-$sSQL = "SELECT timestamp,customer,message,level FROM syslog as S JOIN (SELECT id FROM syslog WHERE date(timestamp)>='$date1' AND date(timestamp)<'$date2' $log_filter ORDER BY id DESC LIMIT $start,$displayed) AS I ON S.id = I.id";
+$sSQL = "SELECT timestamp,customer,message,level FROM syslog as S JOIN (SELECT id FROM syslog WHERE `timestamp`>='$date1' AND `timestamp`<'$date2' $log_filter ORDER BY id DESC LIMIT $start,$displayed) AS I ON S.id = I.id";
 $userlog = get_records_sql($db_link, $sSQL);
 foreach ($userlog as $row) {
     print "<tr align=center align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";

+ 5 - 2
html/admin/logs/dhcp.php

@@ -14,6 +14,8 @@ $_SESSION[$page_url]['f_dhcp']=$f_dhcp;
 $dhcp_where = '';
 if ($f_dhcp != 'all') { $dhcp_where = " and action='$f_dhcp' "; }
 print_log_submenu($page_url);
+
+
 ?>
 
 <div id="cont">
@@ -27,7 +29,7 @@ print_log_submenu($page_url);
 </form>
 
 <?php
-$countSQL="SELECT Count(*) FROM dhcp_log WHERE date(timestamp)>='$date1' AND date(timestamp)<'$date2' $dhcp_where";
+$countSQL="SELECT Count(*) FROM dhcp_log WHERE `timestamp`>='$date1' AND `timestamp`<'$date2' $dhcp_where";
 $res = mysqli_query($db_link, $countSQL);
 $count_records = mysqli_fetch_array($res);
 $total=ceil($count_records[0]/$displayed);
@@ -46,8 +48,9 @@ print_navigation($page_url,$page,$displayed,$count_records[0],$total);
 </tr>
 
 <?php
+
 #speedup dhcp log paging
-$sSQL = "SELECT timestamp,mac,ip,action,auth_id FROM dhcp_log as D JOIN (SELECT id FROM dhcp_log WHERE date(timestamp)>='$date1' and date(timestamp)<'$date2' $dhcp_where ORDER BY timestamp DESC LIMIT $start,$displayed) AS I ON D.id = I.id";
+$sSQL = "SELECT `timestamp`,mac,ip,action,auth_id FROM dhcp_log as D JOIN (SELECT id FROM dhcp_log WHERE `timestamp`>='$date1' and `timestamp`<'$date2' $dhcp_where ORDER BY `timestamp` DESC LIMIT $start,$displayed) AS I ON D.id = I.id";
 $userlog = get_records_sql($db_link, $sSQL);
 
 foreach ($userlog as $row) {

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

@@ -37,7 +37,7 @@ if ($log_level === $L_DEBUG) { $log_filter = ""; }
 if (isset($fcustomer)) { $log_filter = $log_filter." and customer LIKE '%".$fcustomer."%'"; }
 if (isset($fmessage)) { $log_filter = $log_filter." and message LIKE '%".$fmessage."%'"; }
 
-$countSQL="SELECT Count(*) FROM syslog WHERE date(timestamp)>='$date1' AND date(timestamp)<'$date2' $log_filter";
+$countSQL="SELECT Count(*) FROM syslog WHERE `timestamp`>='$date1' AND `timestamp`<'$date2' $log_filter";
 $res = mysqli_query($db_link, $countSQL);
 $count_records = mysqli_fetch_array($res);
 
@@ -57,7 +57,7 @@ print_navigation($page_url,$page,$displayed,$count_records[0],$total);
 			</tr>
 <?php
 #speedup paging
-$sSQL = "SELECT timestamp,customer,message,level FROM syslog as S JOIN (SELECT id FROM syslog WHERE date(timestamp)>='$date1' AND date(timestamp)<'$date2' $log_filter ORDER BY id DESC LIMIT $start,$displayed) AS I ON S.id = I.id";
+$sSQL = "SELECT `timestamp`,customer,message,level FROM syslog as S JOIN (SELECT id FROM syslog WHERE `timestamp`>='$date1' AND `timestamp`<'$date2' $log_filter ORDER BY id DESC LIMIT $start,$displayed) AS I ON S.id = I.id";
 $userlog = get_records_sql($db_link, $sSQL);
 foreach ($userlog as $row) {
     print "<tr align=center align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";

+ 2 - 2
html/admin/logs/ip.php

@@ -28,7 +28,7 @@ if (isset($f_ip) and $f_ip != '') { $ip_where = " and ip_int=inet_aton('" . $f_i
 </form>
 
 <?php
-$countSQL="SELECT Count(*) FROM User_auth WHERE date(timestamp)>='$date1' AND date(timestamp)<'$date2' $ip_where";
+$countSQL="SELECT Count(*) FROM User_auth WHERE `timestamp`>='$date1' AND `timestamp`<'$date2' $ip_where";
 $res = mysqli_query($db_link, $countSQL);
 $count_records = mysqli_fetch_array($res);
 $total=ceil($count_records[0]/$displayed);
@@ -51,7 +51,7 @@ print_navigation($page_url,$page,$displayed,$count_records[0],$total);
 
 <?php
 
-$sSQL = "SELECT timestamp,mac,ip,dns_name,dhcp_hostname,id,last_found FROM User_auth WHERE date(timestamp)>='$date1' AND date(timestamp)<'$date2' $ip_where ORDER BY timestamp DESC LIMIT $start,$displayed";
+$sSQL = "SELECT timestamp,mac,ip,dns_name,dhcp_hostname,id,last_found FROM User_auth WHERE `timestamp`>='$date1' AND `timestamp`<'$date2' $ip_where ORDER BY timestamp DESC LIMIT $start,$displayed";
 $iplog = get_records_sql($db_link, $sSQL);
 foreach ($iplog as $row) {
     print "<tr align=center align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";

+ 7 - 7
html/admin/logs/mac.php

@@ -19,15 +19,15 @@ print_log_submenu($page_url);
 <div id="cont">
 <br>
 <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
-	Начало:&nbsp<input type="date" name="date_start" value="<?php echo $date1; ?>" />
-  Конец:&nbsp<input type="date"	name="date_stop" value="<?php echo $date2; ?>" />
-  Mac:&nbsp<input	type="text" name="mac" value="<?php echo $f_mac; ?>" />
-  Отображать:<?php print_row_at_pages('rows',$displayed); ?>
-  <input type="submit" value="OK">
+Начало:&nbsp<input type="date" name="date_start" value="<?php echo $date1; ?>" />
+Конец:&nbsp<input type="date"	name="date_stop" value="<?php echo $date2; ?>" />
+Mac:&nbsp<input type="text" name="mac" value="<?php echo $f_mac; ?>" />
+Отображать:<?php print_row_at_pages('rows',$displayed); ?>
+<input type="submit" value="OK">
 </form>
 
 <?php
-$countSQL="SELECT Count(*) FROM mac_history WHERE date(timestamp)>='$date1' AND date(timestamp)<'$date2' $mac_where";
+$countSQL="SELECT Count(*) FROM mac_history WHERE `timestamp`>='$date1' AND `timestamp`<'$date2' $mac_where";
 $res = mysqli_query($db_link, $countSQL);
 $count_records = mysqli_fetch_array($res);
 
@@ -47,7 +47,7 @@ print_navigation($page_url,$page,$displayed,$count_records[0],$total);
 	</tr>
 <?php
 
-$sSQL = "SELECT timestamp,mac,ip,device_id,port_id,auth_id FROM mac_history WHERE date(timestamp)>='$date1' AND date(timestamp)<'$date2' $mac_where ORDER BY timestamp DESC LIMIT $start,$displayed";
+$sSQL = "SELECT * FROM mac_history WHERE `timestamp`>='$date1' AND `timestamp`<'$date2' $mac_where ORDER BY `timestamp` DESC LIMIT $start,$displayed";
 $maclog = get_records_sql($db_link, $sSQL);
 
 foreach ($maclog as $row) {

+ 16 - 10
html/admin/logs/syslog.php

@@ -45,7 +45,7 @@ if (isset($fmessage)) {
     if (isset($log_filter)) { $log_filter = $log_filter." and message LIKE '%".$fmessage."%'"; } else { $log_filter = " message LIKE '%".$fmessage."%'"; }
     }
 
-$countSQL="SELECT Count(*) FROM `remote_syslog` WHERE date(`date`)>='$date1' AND date(`date`)<'$date2' $log_filter";
+$countSQL="SELECT Count(*) FROM `remote_syslog` WHERE `date`>='$date1' AND `date`<'$date2' $log_filter";
 $res = mysqli_query($db_link, $countSQL);
 $count_records = mysqli_fetch_array($res);
 $total=ceil($count_records[0]/$displayed);
@@ -66,16 +66,22 @@ print_navigation($page_url,$page,$displayed,$count_records[0],$total);
 <?php
 
 #speedup pageing
-$sSQL = "SELECT `date`, `ip`, `message` FROM `remote_syslog` as R JOIN (SELECT id FROM `remote_syslog` WHERE date(`date`)>='$date1' AND date(`date`)<'$date2' $log_filter
- ORDER BY `id` DESC LIMIT $start,$displayed) as I ON R.id = I.id";
+$sSQL = "SELECT 
+`date`, `ip`, `message` 
+FROM `remote_syslog` as R 
+JOIN 
+(SELECT id FROM `remote_syslog` WHERE `date`>='$date1' AND `date`<'$date2' $log_filter ORDER BY `id` DESC LIMIT $start,$displayed) as I 
+ON R.id = I.id";
 $syslog = get_records_sql($db_link, $sSQL);
-foreach ($syslog as $row) {
-    print "<tr align=center align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
-    print "<td class=\"data\">" . $row['date'] . "</td>\n";
-    print "<td class=\"data\">" . $row['ip'] . "</td>\n";
-    print "<td class=\"data\">" . $row['message'] . "</td>\n";
-    print "</tr>\n";
-}
+if (!empty($syslog)) {
+    foreach ($syslog as $row) {
+        print "<tr align=center align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
+        print "<td class=\"data\">" . $row['date'] . "</td>\n";
+        print "<td class=\"data\">" . $row['ip'] . "</td>\n";
+        print "<td class=\"data\">" . $row['message'] . "</td>\n";
+        print "</tr>\n";
+        }
+    }
 print "</table>\n";
 print_navigation($page_url,$page,$displayed,$count_records[0],$total);
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/footer.php");

+ 2 - 2
html/admin/logs/unknown.php

@@ -26,7 +26,7 @@ if ($f_id > 0) { $where_dev = " and D.id=$f_id "; }
 </form>
 
 <?php
-$countSQL="SELECT Count(*) FROM Unknown_mac AS U, devices AS D, device_ports AS DP  WHERE U.device_id = D.id  AND U.port_id = DP.id AND date(U.timestamp)>='$date1' AND date(U.timestamp)<'$date2' $where_dev";
+$countSQL="SELECT Count(*) FROM Unknown_mac AS U, devices AS D, device_ports AS DP  WHERE U.device_id = D.id  AND U.port_id = DP.id AND U.timestamp>='$date1' AND U.timestamp<'$date2' $where_dev";
 $res = mysqli_query($db_link, $countSQL);
 $count_records = mysqli_fetch_array($res);
 $total=ceil($count_records[0]/$displayed);
@@ -45,7 +45,7 @@ print_navigation($page_url,$page,$displayed,$count_records[0],$total);
 </tr>
 <?php
 
-$sSQL = "SELECT U.mac, U.timestamp, DP.port, D.device_name FROM Unknown_mac AS U, devices AS D, device_ports AS DP  WHERE U.device_id = D.id  AND U.port_id = DP.id AND date(U.timestamp)>='$date1' AND date(U.timestamp)<'$date2' $where_dev ORDER BY U.mac LIMIT $start,$displayed";
+$sSQL = "SELECT U.mac, U.timestamp, DP.port, D.device_name FROM Unknown_mac AS U, devices AS D, device_ports AS DP  WHERE U.device_id = D.id  AND U.port_id = DP.id AND U.timestamp>='$date1' AND U.timestamp<'$date2' $where_dev ORDER BY U.mac LIMIT $start,$displayed";
 $maclog = get_records_sql($db_link, $sSQL);
 foreach ($maclog as $row) {
     print "<tr align=center align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";

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

@@ -6,9 +6,9 @@ if (isset($_POST['save'])) {
     $len = is_array($_POST['id']) ? count($_POST['id']) : 0;
     for ($i = 0; $i < $len; $i ++) {
         $id = intval($_POST['id'][$i]);
-        $new[queue_name] = trim($_POST['f_queue_name'][$i]);
-        $new[Download] = $_POST['f_down'][$i] * 1;
-        $new[Upload] = $_POST['f_up'][$i] * 1;
+        $new['queue_name'] = trim($_POST['f_queue_name'][$i]);
+        $new['Download'] = $_POST['f_down'][$i] * 1;
+        $new['Upload'] = $_POST['f_up'][$i] * 1;
         update_record($db_link, "Queue_list", "id='{$id}'", $new);
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);
@@ -17,7 +17,7 @@ if (isset($_POST['save'])) {
 if (isset($_POST["create"])) {
     $queue_name = $_POST["new_queue"];
     if (isset($queue_name)) {
-        $q[queue_name] = $queue_name;
+        $q['queue_name'] = $queue_name;
         insert_record($db_link, "Queue_list", $q);
     }
     header("Location: " . $_SERVER["REQUEST_URI"]);

+ 93 - 0
html/admin/reports/authday.php

@@ -0,0 +1,93 @@
+<?php
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . $language . ".php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
+$default_date_shift='d';
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/datefilter.php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/oufilter.php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/gatefilter.php");
+$auth=get_record_sql($db_link,'SELECT * FROM User_auth WHERE id='.$id);
+$user=get_record_sql($db_link,'SELECT * FROM User_list WHERE id='.$auth['user_id']);
+
+?>
+<div id="cont">
+<b>
+<?php
+print "Трафик пользователя <a href=../users/edituser.php?id=".$auth['user_id'].">" . $user['login'] . "</a>"; 
+print " для адреса <a href=../users/editauth.php?id=$id>".$auth['ip']."</a>";
+?>
+</b>
+<br>
+<form action="<?php print $_SERVER['PHP_SELF']; ?>" method="post">
+<input type="hidden" name="id" value=<?php echo $id; ?>>
+Начало:&nbsp<input type="date" name="date_start" value="<?php print $date1; ?>" />
+Конец:&nbsp<input type="date" name="date_stop" value="<?php print $date2; ?>" />
+Шлюз:&nbsp <?php print_gateway_select($db_link, 'gateway', $rgateway); ?>
+<input type="submit" value="OK">
+</form>
+<br>
+<table class="data" width=700>
+<tr align="center">
+<td class="data"><b> Gateway </b></td>
+<td class="data"><b><?php echo userinfo10; ?></b></td>
+<td class="data"><b><?php echo userinfo7; ?></b></td>
+<td class="data"><b><?php echo userinfo8; ?></b></td>
+<td class="data"><b><?php print 'Max IN, pkt/s'; ?></b></td>
+<td class="data"><b><?php print 'Max OUT, pkt/s'; ?></b></td>
+</tr>
+<?php
+
+$gateway_list = get_gateways($db_link);
+$gateway_filter='';
+if (!empty($rgateway) and $rgateway>0) { $gateway_filter="(router_id=$rgateway) AND"; }
+
+print "<tr align=center align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
+print "<td class=\"data\" colspan=2>".$auth['comments']."</td>\n";
+print "<td class=\"data\" colspan=2><a href=/admin/reports/userdaydetail.php?id=$id&date_start=$date1&date_stop=$date2>TOP 10</a></td>\n";
+print "<td class=\"data\" colspan=2><a href=/admin/reports/userdaydetaillog.php?id=$id&date_start=$date1&date_stop=$date2>Детализация</a></td>\n";
+print "</tr>\n";
+
+$display_date_format='%Y-%m-%d %H';
+
+if ($days_shift <=1) { $display_date_format='%Y-%m-%d %H'; }
+if ($days_shift >1 and $days_shift <=30) { $display_date_format='%Y-%m-%d'; }
+if ($days_shift >30 and $days_shift <=730) { $display_date_format='%Y-%m'; }
+if ($days_shift >730) { $display_date_format='%Y'; }
+
+$sSQL = "SELECT router_id,DATE_FORMAT(`timestamp`,'$display_date_format') as tHour,SUM(`byte_in`),SUM(`byte_out`),MAX(ROUND(`pkt_in`/`step`)),MAX(ROUND(`pkt_out`/`step`))
+FROM User_stats_full WHERE `timestamp`>='$date1' AND `timestamp`<'$date2' AND auth_id=$id";
+if ($rgateway == 0) {
+        $sSQL = $sSQL . " GROUP BY DATE_FORMAT(`timestamp`,'$display_date_format'),router_id ORDER BY tHour,router_id";
+        } else {
+        $sSQL = $sSQL . " AND router_id=$rgateway GROUP BY DATE_FORMAT(`timestamp`,'$display_date_format'),router_id ORDER BY tHour";
+        }
+
+$userdata = mysqli_query($db_link, $sSQL);
+$sum_in = 0;
+$sum_out = 0;
+while (list ($u_router_id, $udata, $uin, $uout, $pin, $pout) = mysqli_fetch_array($userdata)) {
+    print "<tr align=center align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
+    print "<td class=\"data\">$gateway_list[$u_router_id]</td>\n";
+    print "<td class=\"data\">" . $udata . "</td>\n";
+    print "<td class=\"data\">" . fbytes($uin) . "</td>\n";
+    print "<td class=\"data\">" . fbytes($uout) . "</td>\n";
+    print "<td class=\"data\">" . fpkts($pin) . "</td>\n";
+    print "<td class=\"data\">" . fpkts($pout) . "</td>\n";
+    print "</tr>\n";
+    $sum_in += $uin;
+    $sum_out += $uout;
+}
+print "<tr align=center align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
+print "<td class=\"data\"><b>" . userinfo9 . "</b></td>\n";
+print "<td class=\"data\"><b> </b></td>\n";
+print "<td class=\"data\"><b>" . fbytes($sum_in) . "</b></td>\n";
+print "<td class=\"data\"><b>" . fbytes($sum_out) . "</b></td>\n";
+print "<td class=\"data\"><b></b></td>\n";
+print "<td class=\"data\"><b></b></td>\n";
+print "</tr>\n";
+?>
+</table>
+<?
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/footer.php");
+?>

+ 116 - 0
html/admin/reports/index-full.php

@@ -0,0 +1,116 @@
+<?php
+$default_displayed=100;
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . $language . ".php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
+$default_date_shift='d';
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/datefilter.php");
+$default_sort='tin';
+$default_order='DESC';
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/oufilter.php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/sortfilter.php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/gatefilter.php");
+
+print_reports_submenu($page_url);
+
+?>
+<div id="cont">
+<form action="index-full.php" method="post">
+Группа:&nbsp<?php print_ou_select($db_link,'ou',$rou); ?>
+Начало:&nbsp<input type="date" name="date_start" value="<?php echo $date1; ?>" />
+Конец:&nbsp<input type="date" name="date_stop" value="<?php echo $date2; ?>" />
+Шлюз:&nbsp<?php print_gateway_select($db_link, 'gateway', $rgateway); ?>
+Отображать:<?php print_row_at_pages('rows',$displayed); ?>
+<input type="submit" value="OK">
+</form>
+
+<?php
+
+$sort_sql=" ORDER BY tin DESC";
+
+if (!empty($sort_field) and !empty($order)) { $sort_sql = " ORDER BY $sort_field $order"; }
+
+$gateway_list = get_gateways($db_link);
+
+$trafSQL = "SELECT 
+User_list.login,User_list.ou_id,User_auth.user_id, User_auth.ip, User_stats_full.auth_id, 
+User_stats_full.router_id, SUM( byte_in ) AS tin, SUM( byte_out ) AS tout, MAX(ROUND(`pkt_in`/`step`)) as pin, MAX(ROUND(`pkt_out`/`step`)) as pout 
+FROM User_stats_full,User_auth,User_list WHERE User_list.id=User_auth.user_id 
+AND User_stats_full.auth_id = User_auth.id 
+AND User_stats_full.timestamp>='$date1' 
+AND User_stats_full.timestamp<'$date2' 
+";
+
+if ($rou !== 0) {
+    $trafSQL = $trafSQL . " AND User_list.ou_id=$rou";
+}
+
+if ($rgateway == 0) {
+    $trafSQL = $trafSQL . " GROUP by User_auth.id,User_stats_full.router_id";
+} else {
+    $trafSQL = $trafSQL . " AND User_stats_full.router_id=$rgateway GROUP by User_auth.id,User_stats_full.router_id";
+}
+
+$countSQL = "SELECT Count(*) FROM ($trafSQL) A";
+
+$res = mysqli_query($db_link, $countSQL);
+$count_records = mysqli_fetch_array($res);
+$total=ceil($count_records[0]/$displayed);
+if ($page>$total) { $page=$total; }
+if ($page<1) { $page=1; }
+$start = ($page * $displayed) - $displayed;
+
+#set sort
+$trafSQL=$trafSQL ." $sort_sql LIMIT $start,$displayed";
+
+print_navigation($page_url,$page,$displayed,$count_records[0],$total);
+
+print "<br><br>\n";
+print "<table class=\"data\" width=\"850\" cellspacing=\"1\" cellpadding=\"4\">\n";
+print "<tr align=\"center\">\n";
+print "<td ><b><a href=index-full.php?sort=login&order=$new_order>Логин</a></b></td>\n";
+print "<td ><b><a href=index-full.php?sort=ip&order=$new_order>IP</a></b></td>\n";
+print "<td ><b>Gate</b></td>\n";
+print "<td ><b><a href=index-full.php?sort=tin&order=$new_order>Входящий</a></b></td>\n";
+print "<td ><b><a href=index-full.php?sort=tout&order=$new_order>Исходящий<a></b></td>\n";
+print "<td ><b><a href=index-full.php?sort=pin&order=$new_order>Max in, pkt/s</a></b></td>\n";
+print "<td ><b><a href=index-full.php?sort=pout&order=$new_order>Max out, pkt/s<a></b></td>\n";
+print "</tr>\n";
+
+$total_in = 0;
+$total_out = 0;
+
+$traf = mysqli_query($db_link, $trafSQL);
+
+while (list ($s_login,$s_ou_id,$u_id,$s_ip,$s_auth_id, $s_router_id, $traf_day_in, $traf_day_out, $p_in, $p_out) = mysqli_fetch_array($traf)) {
+    if ($traf_day_in + $traf_day_out ==0) { continue; }
+    $total_in += $traf_day_in;
+    $total_out += $traf_day_out;
+    $s_router = $gateway_list[$s_router_id];
+    $cl = "data";
+    if ($traf_day_out > 2 * $traf_day_in) { $cl = "nb"; }
+    print "<tr align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
+    print "<td align=left class=\"$cl\">$s_login</td>\n";
+    print "<td align=left class=\"$cl\"><a href=authday.php?id=$s_auth_id&date_start=$date1&date_stop=$date2>$s_ip</a></td>\n";
+    print "<td align=left class=\"$cl\">$s_router</td>\n";
+    print "<td class=\"$cl\">" . fbytes($traf_day_in) . "</td>\n";
+    print "<td class=\"$cl\">" . fbytes($traf_day_out) . "</td>\n";
+    print "<td class=\"$cl\">" . fpkts($p_in) . "</td>\n";
+    print "<td class=\"$cl\">" . fpkts($p_out) . "</td>\n";
+    print "</tr>\n";
+}
+print "<tr align=center align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
+print "<td class=\"data\" colspan=2><b>Итого</b></td>\n";
+print "<td class=\"data\"><b></b></td>\n";
+print "<td class=\"data\"><b>" . fbytes($total_in) . "</b></td>\n";
+print "<td class=\"data\"><b>" . fbytes($total_out) . "</b></td>\n";
+print "<td class=\"data\"><b></b></td>\n";
+print "<td class=\"data\"><b></b></td>\n";
+print "</tr>\n";
+?>
+  </table>
+<?
+print_navigation($page_url,$page,$displayed,$count_records[0],$total);
+
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/footer.php");
+?>

+ 39 - 63
html/admin/reports/index.php

@@ -1,17 +1,20 @@
 <?php
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.php");
-require_once ($_SERVER['DOCUMENT_ROOT']."/inc/sqlt.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . $language . ".php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
 $default_date_shift='d';
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/datefilter.php");
-$default_sort='in';
+$default_sort='tin';
+$default_order='DESC';
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/oufilter.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/sortfilter.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/gatefilter.php");
+
+print_reports_submenu($page_url);
+
 ?>
 <div id="cont">
-<b>Трафик пользователей</b>
+
 <form action="index.php" method="post">
 Группа:&nbsp<?php print_ou_select($db_link,'ou',$rou); ?>
 Начало:&nbsp<input type="date" name="date_start" value="<?php echo $date1; ?>" />
@@ -26,82 +29,55 @@ print "<table class=\"data\" width=\"650\" cellspacing=\"1\" cellpadding=\"4\">\
 print "<tr align=\"center\">\n";
 print "<td ><b><a href=index.php?sort=login&order=$new_order>Логин</a></b></td>\n";
 print "<td ><b>Gate</b></td>\n";
-print "<td ><b><a href=index.php?sort=in&order=$new_order>Входящий</a></b></td>\n";
-print "<td ><b><a href=index.php?sort=out&order=$new_order>Исходящий<a></b></td>\n";
+print "<td ><b><a href=index.php?sort=tin&order=$new_order>Входящий</a></b></td>\n";
+print "<td ><b><a href=index.php?sort=tout&order=$new_order>Исходящий<a></b></td>\n";
 print "</tr>\n";
 
+$sort_sql=" ORDER BY tin DESC";
+
+if (!empty($sort_field) and !empty($order)) { $sort_sql = " ORDER BY $sort_field $order"; }
+
 $gateway_list = get_gateways($db_link);
 
-$trafSQL = "SELECT User_stats.auth_id, User_stats.router_id, SUM( byte_in ) AS tin, SUM( byte_out ) AS tout 
-FROM User_stats WHERE (date(User_stats.timestamp)>='$date1') AND (date(User_stats.timestamp)<'$date2') AND (byte_in>0 or byte_out>0)";
+$trafSQL = "SELECT 
+User_list.login,User_list.ou_id,User_auth.user_id, User_stats.auth_id, 
+User_stats.router_id, SUM( byte_in ) AS tin, SUM( byte_out ) AS tout 
+FROM User_stats,User_auth,User_list WHERE User_list.id=User_auth.user_id 
+AND User_stats.auth_id = User_auth.id 
+AND User_stats.timestamp>='$date1' 
+AND User_stats.timestamp<'$date2' 
+";
 
-if ($rgateway == 0) {
-    $trafSQL = $trafSQL . " GROUP by User_stats.auth_id,User_stats.router_id";
-} else {
-    $trafSQL = $trafSQL . " AND User_stats.router_id=$rgateway GROUP by User_stats.auth_id,User_stats.router_id";
+if ($rou !== 0) {
+    $trafSQL = $trafSQL . " AND User_list.ou_id=$rou";
 }
 
-$userSQL = "SELECT User_list.login as login, User_auth.user_id as user_id, User_auth.id as auth_id FROM User_list,User_auth WHERE User_list.id=User_auth.user_id";
-if ($rou == 0) {
-    $userSQL = $userSQL . " ORDER BY User_auth.id";
+if ($rgateway == 0) {
+    $trafSQL = $trafSQL . " GROUP by User_auth.user_id,User_stats.router_id";
 } else {
-    $userSQL = $userSQL . " AND User_list.ou_id=$rou ORDER BY User_auth.id";
+    $trafSQL = $trafSQL . " AND User_stats.router_id=$rgateway GROUP by User_auth.user_id,User_stats.router_id";
 }
 
-$users = mysqli_query($db_link, $userSQL);
-
-while (list ($f_login, $f_user_id, $f_auth_id) = mysqli_fetch_array($users)) {
-    $user_ref[$f_auth_id][id] = $f_user_id;
-    $user_ref[$f_auth_id][login] = $f_login;
-}
+#set sort
+$trafSQL=$trafSQL ." $sort_sql";
 
 $total_in = 0;
 $total_out = 0;
 
-unset($user_traf);
-$traf = mysqli_query($dbt_link, $trafSQL);
-
-while (list ($s_auth_id, $s_router_id, $traf_day_in, $traf_day_out) = mysqli_fetch_array($traf)) {
-    if (! isset($user_ref{$s_auth_id}{id})) { continue; }
-    if ($traf_day_in + $traf_day_out > 0) {
-        $u_id = $user_ref[$s_auth_id][id];
-        if (! isset($user_traf[$u_id][$s_router_id][in])) {
-            $user_traf[$u_id][$s_router_id][in] = 0;
-        }
-        if (! isset($user_traf[$u_id][$s_router_id][out])) {
-            $user_traf[$u_id][$s_router_id][out] = 0;
-        }
-        if (! isset($user_traf[$u_id][$s_router_id][login])) {
-            $user_traf[$u_id][$s_router_id][login] = $user_ref[$s_auth_id][login];
-        }
-        $user_traf[$u_id][$s_router_id][in] += $traf_day_in;
-        $user_traf[$u_id][$s_router_id][out] += $traf_day_out;
-        $total_in += $traf_day_in;
-        $total_out += $traf_day_out;
-    }
-}
-
-$tmp_table = "month_stats_" . $_SESSION['session_id'];
-$tSQL = "CREATE TEMPORARY TABLE $tmp_table (`id` int(11) unsigned NOT NULL,`login` varchar(50) not null,`router` varchar(50) not null, `in` bigint, `out` bigint) DEFAULT CHARSET=utf8";
-mysqli_query($db_link, $tSQL);
-foreach ($user_traf as $u_id => $user_stats) {
-    foreach ($user_stats as $s_router_id => $user_info) {
-        $tSQL = "insert into $tmp_table (`id`,`login`,`router`,`in`,`out`) values('$u_id','$user_info[login]','$gateway_list[$s_router_id]','$user_info[in]','$user_info[out]')";
-        $result = mysqli_query($db_link, $tSQL);
-    }
-}
-
-$tSQL = "Select `id`,`login`,`router`,`in`,`out` from `$tmp_table` order by `$sort_field` $order";
-$user_stats = mysqli_query($db_link, $tSQL);
+$traf = mysqli_query($db_link, $trafSQL);
 
-while (list ($s_id, $s_login, $s_router, $s_in, $s_out) = mysqli_fetch_array($user_stats)) {
+while (list ($s_login,$s_ou_id,$u_id,$s_auth_id, $s_router_id, $traf_day_in, $traf_day_out) = mysqli_fetch_array($traf)) {
+    if ($traf_day_in + $traf_day_out ==0) { continue; }
+    $total_in += $traf_day_in;
+    $total_out += $traf_day_out;
+    $s_router = $gateway_list[$s_router_id];
     $cl = "data";
-    if ($s_out > 2 * $s_in) { $cl = "nb"; }
-    print "<tr align=center align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
-    print "<td class=\"$cl\"><a href=userday.php?id=$s_id&date_start=$date1&date_stop=$date2>$s_login</a></td>\n";
-    print "<td class=\"$cl\">$s_router</td>\n";
-    print "<td class=\"$cl\">" . fbytes($s_in) . "</td>\n";
-    print "<td class=\"$cl\">" . fbytes($s_out) . "</td>\n";
+    if ($traf_day_out > 2 * $traf_day_in) { $cl = "nb"; }
+    print "<tr align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
+    print "<td align=left class=\"$cl\"><a href=userday.php?id=$u_id&date_start=$date1&date_stop=$date2>$s_login</a></td>\n";
+    print "<td align=left class=\"$cl\">$s_router</td>\n";
+    print "<td class=\"$cl\">" . fbytes($traf_day_in) . "</td>\n";
+    print "<td class=\"$cl\">" . fbytes($traf_day_out) . "</td>\n";
     print "</tr>\n";
 }
 print "<tr align=center align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";

+ 35 - 21
html/admin/reports/userday.php

@@ -1,6 +1,5 @@
 <?php
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.php");
-require_once ($_SERVER['DOCUMENT_ROOT']."/inc/sqlt.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . $language . ".php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
@@ -8,34 +7,41 @@ $default_date_shift='d';
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/datefilter.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/oufilter.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/gatefilter.php");
+
+$user=get_record_sql($db_link,'SELECT * FROM User_list WHERE id='.$id);
+
 ?>
 
 <div id="cont">
-<b><?php print "Трафик пользователя <a href=../users/edituser.php?id=$id>" . $login . "</a>"; ?></b>
+<b><?php print "Трафик пользователя <a href=../users/edituser.php?id=$id>" . $user['login'] . "</a>"; ?></b>
 <br>
-<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
-<input type="hidden" name="id" value=<? echo $id; ?>>
-Начало:&nbsp<input type="date" name="date_start" value="<?php echo $date1; ?>" />
-Конец:&nbsp<input type="date" name="date_stop" value="<?php echo $date2; ?>" />
-Шлюз:&nbsp<?php print_gateway_select($db_link, 'gateway', $rgateway); ?>
+<form action="<?php print $_SERVER['PHP_SELF']; ?>" method="post">
+<input type="hidden" name="id" value=<?php echo $id; ?>>
+Начало:&nbsp<input type="date" name="date_start" value="<?php print $date1; ?>" />
+Конец:&nbsp<input type="date" name="date_stop" value="<?php print $date2; ?>" />
+Шлюз:&nbsp <?php print_gateway_select($db_link, 'gateway', $rgateway); ?>
 <input type="submit" value="OK">
 </form>
+
 <br>
 <table class="data" width='100%'>
 <tr align="center">
-<td class="data"><b><? echo userinfo2;  ?></b></td>
+<td class="data"><b><?php echo userinfo2;  ?></b></td>
 <td class="data"><b> Gateway </b></td>
-<td class="data"><b><? echo userinfo10; ?></b></td>
-<td class="data"><b><? echo userinfo7; ?></b></td>
-<td class="data"><b><? echo userinfo8; ?></b></td>
+<td class="data"><b><?php echo userinfo10; ?></b></td>
+<td class="data"><b><?php echo userinfo7; ?></b></td>
+<td class="data"><b><?php echo userinfo8; ?></b></td>
 </tr>
 
 <?php
 $gateway_list = get_gateways($db_link);
 
-list ($login) = mysqli_fetch_array(mysqli_query($db_link, "SELECT Login FROM User_list WHERE User_list.id=$id"));
+$gateway_filter='';
+if (!empty($rgateway) and $rgateway>0) { $gateway_filter="(User_stats.router_id=$rgateway) AND"; }
+
 $sSQL = "SELECT id,ip,comments FROM User_auth WHERE (User_auth.user_id=$id) Order by IP";
 $usersip = mysqli_query($db_link, $sSQL);
+
 $ipcount = 0;
 $itog_in = 0;
 $itog_out = 0;
@@ -46,16 +52,19 @@ while ($row = mysqli_fetch_array($usersip)) {
     $fip = $row["ip"];
     $fcomm = $row["comments"];
 
-    $sSQL = "SELECT SUM(byte_in)+SUM(byte_out) from User_stats where date(User_stats.timestamp)>='$date1' and date(User_stats.timestamp)<'$date2'and auth_id=$fid";
-    $day_summary = mysqli_query($dbt_link, $sSQL);
-    list ($summ) = mysqli_fetch_array($day_summary);
+    $sSQL = "SELECT SUM(byte_in)+SUM(byte_out) as t_sum FROM User_stats 
+    WHERE $gateway_filter User_stats.timestamp>='$date1' AND User_stats.timestamp<'$date2'AND auth_id=$fid";
+
+    $day_summary = get_record_sql($db_link, $sSQL);
+    if (!empty($day_summary)) { $summ = $day_summary['t_sum']; } else { $summ = 0; }
 
     if ($summ > 0) {
         $ipcount ++;
         print "<tr align=center align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
-        print "<td class=\"data\" ><b><a href=../users/editauth.php?id=$fid>$fip</a></b></td>\n";
+        print "<td class=\"data\" ><b><a href=/admin/users/editauth.php?id=$fid>$fip</a></b></td>\n";
         print "<td class=\"data\" colspan=2>$fcomm</td>\n";
-        print "<td class=\"data\" colspan=2><a href=userdaydetail.php?id=$fid&date_start=$date1&date_stop=$date2>Детализация</a></td>\n";
+        print "<td class=\"data\" ><a href=/admin/reports/userdaydetail.php?id=$fid&date_start=$date1&date_stop=$date2>TOP 10</a></td>\n";
+        print "<td class=\"data\" ><a href=/admin/reports/userdaydetaillog.php?id=$fid&date_start=$date1&date_stop=$date2>Детализация</a></td>\n";
         print "</tr>\n";
 
 	$display_date_format='%Y-%m-%d %H';
@@ -64,14 +73,19 @@ while ($row = mysqli_fetch_array($usersip)) {
 	if ($days_shift >30 and $days_shift <=730) { $display_date_format='%Y-%m'; }
 	if ($days_shift >730) { $display_date_format='%Y'; }
 
-        $sSQL = "SELECT User_stats.router_id,DATE_FORMAT(User_stats.timestamp,'$display_date_format') as tHour,SUM(byte_in),SUM(byte_out) from User_stats where date(User_stats.timestamp)>='$date1' and  date(User_stats.timestamp)<'$date2' and auth_id=$fid";
+        $sSQL = "SELECT User_stats.router_id,DATE_FORMAT(User_stats.timestamp,'$display_date_format') as tHour,SUM(byte_in),SUM(byte_out) 
+        FROM User_stats 
+        WHERE User_stats.timestamp>='$date1' AND User_stats.timestamp<'$date2' and auth_id=$fid";
         if ($rgateway == 0) {
-            $sSQL = $sSQL . " GROUP BY DATE_FORMAT(User_stats.timestamp,'$display_date_format'),User_stats.router_id Order by tHour,User_stats.router_id";
+            $sSQL = $sSQL . " GROUP BY DATE_FORMAT(User_stats.timestamp,'$display_date_format'),User_stats.router_id 
+            ORDER BY tHour,User_stats.router_id";
         } else {
-            $sSQL = $sSQL . " and User_stats.router_id=$rgateway GROUP BY DATE_FORMAT(User_stats.timestamp,'$display_date_format'),User_stats.router_id Order by tHour";
+            $sSQL = $sSQL . " and User_stats.router_id=$rgateway 
+            GROUP BY DATE_FORMAT(User_stats.timestamp,'$display_date_format'),User_stats.router_id 
+            ORDER BY tHour";
         }
 
-        $userdata = mysqli_query($dbt_link, $sSQL);
+        $userdata = mysqli_query($db_link, $sSQL);
 
         $sum_in = 0;
         $sum_out = 0;

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

@@ -1,24 +1,32 @@
 <?php
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.php");
-require_once ($_SERVER['DOCUMENT_ROOT']."/inc/sqlt.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . $language . ".php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
 $default_date_shift='d';
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/datefilter.php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/gatefilter.php");
 
 $usersip = mysqli_query($db_link, "SELECT ip,user_id,comments FROM User_auth WHERE User_auth.id=$id");
 list ($fip, $parent, $fcomm) = mysqli_fetch_array($usersip);
+
+$rdns = 0;
+if (isset($_POST['dns'])) { $rdns=$_POST['dns']*1; }
+$_SESSION[$page_url]['dns']=$rdns;
+$dns_checked='';
+if ($rdns) { $dns_checked='checked="checked"'; }
+
+print_trafdetail_submenu($page_url,"id=$id&date_start=$date1&date_stop=$date2","<b>Детализация для <a href=/admin/users/editauth.php?id=$id>$fip</a></b> ::&nbsp");
 ?>
 
 <div id="cont">
-<?php print "<b>Детализация для <a href=../users/editauth.php?id=$id>$fip</a></b><br>\n"; ?>
 
 <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
 <input type="hidden" name="id" value=<? echo $id; ?>>
   Начало:&nbsp<input type="date" name="date_start" value="<?php echo $date1; ?>" />
   Конец:&nbsp<input type="date" name="date_stop" value="<?php echo $date2; ?>" />
-  Отображать:<?php print_row_at_pages('rows',$displayed); ?>
+  Шлюз:&nbsp <?php print_gateway_select($db_link, 'gateway', $rgateway); ?>
+  DNS:&nbsp <input type=checkbox name=dns value="1" <?php print $dns_checked; ?>>
   <input type="submit" value="OK">
 </form>
 
@@ -34,16 +42,20 @@ list ($fip, $parent, $fcomm) = mysqli_fetch_array($usersip);
 </tr>
 <?php
 $ip_aton = ip2long($fip);
+
+$gateway_filter='';
+if (!empty($rgateway) and $rgateway>0) { $gateway_filter="(router_id=$rgateway) AND"; }
+
 $fsql = "SELECT A.proto, A.src_ip, A.src_port, SUM(A.bytes) as tin FROM Traffic_detail A
-            WHERE (auth_id='$id') and  (date(`timestamp`)>='$date1' and date(`timestamp`)<'$date2') and (A.dst_ip='$ip_aton')
+            WHERE $gateway_filter (auth_id='$id') and  `timestamp`>='$date1' and `timestamp`<'$date2' and (A.dst_ip='$ip_aton')
             GROUP BY A.src_ip, A.src_port, A.proto ORDER BY tin DESC LIMIT 0,10";
-$userdata = mysqli_query($dbt_link, $fsql);
+$userdata = mysqli_query($db_link, $fsql);
 while (list ($uproto, $uip, $uport, $ubytes) = mysqli_fetch_array($userdata)) {
     print "<tr align=center align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
     print "<td class=\"data\">" . $uproto . "</td>\n";
     print "<td class=\"data\" align=left>" . long2ip($uip) . "</td>\n";
-    $ip_name = gethostbyaddr(long2ip($uip));
-    if (! isset($ip_name)) { $ip_name = '-'; }
+    $ip_name = '-';
+    if ($rdns) { $ip_name = ResolveIP($db_link,$uip); }
     print "<td class=\"data\" align=left>" . $ip_name . "</td>\n";
     print "<td class=\"data\">" . $uport . "</td>\n";
     print "<td class=\"data\" align=right>" . fbytes($ubytes) . "</td>\n";
@@ -62,15 +74,15 @@ while (list ($uproto, $uip, $uport, $ubytes) = mysqli_fetch_array($userdata)) {
 </tr>
 <?php
 $fsql = "SELECT A.proto, A.dst_ip, A.dst_port, SUM(A.bytes) as tout FROM Traffic_detail A
-        WHERE (auth_id='$id') and  (date(`timestamp`)>='$date1' and date(`timestamp`)<'$date2') and (A.src_ip='$ip_aton')
+        WHERE $gateway_filter (auth_id='$id') and  `timestamp`>='$date1' and `timestamp`<'$date2' and (A.src_ip='$ip_aton')
         GROUP BY A.dst_ip, A.dst_port, A.proto ORDER BY tout DESC LIMIT 0,10";
-$userdata = mysqli_query($dbt_link, $fsql);
+$userdata = mysqli_query($db_link, $fsql);
 while (list ($uproto, $uip, $uport, $ubytes) = mysqli_fetch_array($userdata)) {
     print "<tr align=center align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
     print "<td class=\"data\">" . $uproto . "</td>\n";
     print "<td class=\"data\" align=left>" . long2ip($uip) . "</td>\n";
-    $ip_name = gethostbyaddr(long2ip($uip));
-    if (! isset($ip_name)) { $ip_name = '-'; }
+    $ip_name = '-';
+    if ($rdns) { $ip_name = ResolveIP($db_link,$uip); }
     print "<td class=\"data\" align=left>" . $ip_name . "</td>\n";
     print "<td class=\"data\">" . $uport . "</td>\n";
     print "<td class=\"data\" align=right>" . fbytes($ubytes) . "</td>\n";
@@ -78,61 +90,6 @@ while (list ($uproto, $uip, $uport, $ubytes) = mysqli_fetch_array($userdata)) {
 }
 ?>
 </table>
-<b>Полный лог</b>
-
-<?php
-$countSQL="SELECT Count(*) FROM Traffic_detail as A WHERE (auth_id='$id') and (date(`timestamp`)>='$date1' and date(`timestamp`)<'$date2')";
-$res = mysqli_query($dbt_link, $countSQL);
-$count_records = mysqli_fetch_array($res);
-$total=ceil($count_records[0]/$displayed);
-if ($page>$total) { $page=$total; }
-if ($page<1) { $page=1; }
-$start = ($page * $displayed) - $displayed;
-print_navigation($page_url,$page,$displayed,$count_records[0],$total);
-$gateway_list = get_gateways($db_link);
-?>
-
-<br>
-<table class="data">
-<tr align="center">
-<td class="data" width=150><b>Дата</b></td>
-<td class="data" width=30><b>Роутер</b></td>
-<td class="data" width=30><b>Протокол</b></td>
-<td class="data" width=150><b>Откуда</b></td>
-<td class="data"><b>DNS</b></td>
-<td class="data" width=50><b>Порт</b></td>
-<td class="data" width=150><b>Куда</b></td>
-<td class="data"><b>DNS</b></td>
-<td class="data" width=50><b>Порт</b></td>
-<td class="data" width=80><b>Байт</b></td>
-</tr>
-<?php
-$fsql = "SELECT A.`timestamp`, A.router_id, A.proto, A.src_ip, A.src_port, A.dst_ip, A.dst_port, A.bytes FROM Traffic_detail as A JOIN (SELECT id FROM Traffic_detail 
-        WHERE (auth_id='$id') and  (date(`timestamp`)>='$date1' and date(`timestamp`)<'$date2')
-        ORDER BY `timestamp` ASC LIMIT $start,$displayed) as T ON A.id = T.id";
-$userdata = mysqli_query($dbt_link, $fsql);
-while (list ($udata, $urouter, $uproto, $sip, $sport,$dip, $dport, $ubytes) = mysqli_fetch_array($userdata)) {
-    print "<tr align=center align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
-    print "<td class=\"data\">$udata</td>\n";
-    print "<td class=\"data\">$gateway_list[$urouter]</td>\n";
-    print "<td class=\"data\">" . $uproto . "</td>\n";
-    print "<td class=\"data\" align=left>" . long2ip($sip) . "</td>\n";
-    $ip_name = gethostbyaddr(long2ip($sip));
-    if (! isset($ip_name)) { $ip_name = '-'; }
-    print "<td class=\"data\" align=left>" . $ip_name . "</td>\n";
-    print "<td class=\"data\">" .$sport . "</td>\n";
-    print "<td class=\"data\" align=left>" . long2ip($dip) . "</td>\n";
-    $ip_name = gethostbyaddr(long2ip($dip));
-    if (! isset($ip_name)) { $ip_name = '-'; }
-    print "<td class=\"data\" align=left>" . $ip_name . "</td>\n";
-    print "<td class=\"data\">" . $dport . "</td>\n";
-    print "<td class=\"data\" align=right>" . fbytes($ubytes) . "</td>\n";
-    print "</tr>\n";
-}
-?>
-</table>
-<?php print_navigation($page_url,$page,$displayed,$count_records[0],$total); ?>
-<br>
 <?php
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/footer.php");
 ?>

+ 105 - 0
html/admin/reports/userdaydetaillog.php

@@ -0,0 +1,105 @@
+<?php
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/languages/" . $language . ".php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/idfilter.php");
+$default_date_shift='h';
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/datetimefilter.php");
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/gatefilter.php");
+$default_sort='id';
+$sort_table = 'A';
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/sortfilter.php");
+$rdns = 0;
+if (isset($_POST['dns'])) { $rdns=$_POST['dns']*1; }
+$_SESSION[$page_url]['dns']=$rdns;
+$dns_checked='';
+if ($rdns) { $dns_checked='checked="checked"'; }
+
+
+$dns_cache=NULL;
+
+$usersip = mysqli_query($db_link, "SELECT ip,user_id,comments FROM User_auth WHERE User_auth.id=$id");
+list ($fip, $parent, $fcomm) = mysqli_fetch_array($usersip);
+
+print_trafdetail_submenu($page_url,"id=$id&date_start=$date1&date_stop=$date2","<b>Детализация для <a href=/admin/users/editauth.php?id=$id>$fip</a></b> ::&nbsp");
+?>
+
+<div id="cont">
+
+<form action="<?php print $page_url; ?>" method="post">
+<input type="hidden" name="id" value=<? echo $id; ?>>
+Начало:&nbsp<input type="datetime-local" name="date_start" value="<?php echo $date1; ?>" />
+Конец:&nbsp<input type="datetime-local" name="date_stop" value="<?php echo $date2; ?>" />
+Шлюз:&nbsp <?php print_gateway_select($db_link, 'gateway', $rgateway); ?>
+DNS:&nbsp <input type=checkbox name=dns value="1" <?php print $dns_checked; ?>>
+Отображать:<?php print_row_at_pages('rows',$displayed); ?>
+<input type="submit" value="OK">
+</form>
+
+<b>Полный лог</b>
+
+<?php
+$sort_url = "<a href='userdaydetaillog.php?id=".$id.'&date_start="'.$date1.'"&date_stop="'.$date2.'"';
+
+$gateway_filter='';
+if (!empty($rgateway) and $rgateway>0) { $gateway_filter="(router_id=$rgateway) AND"; }
+
+$countSQL="SELECT Count(*) FROM Traffic_detail as A WHERE $gateway_filter (auth_id='$id') and `timestamp`>='$date1' and `timestamp`<'$date2'";
+$res = mysqli_query($db_link, $countSQL);
+$count_records = mysqli_fetch_array($res);
+$total=ceil($count_records[0]/$displayed);
+if ($page>$total) { $page=$total; }
+if ($page<1) { $page=1; }
+$start = ($page * $displayed) - $displayed;
+print_navigation($page_url,$page,$displayed,$count_records[0],$total);
+$gateway_list = get_gateways($db_link);
+?>
+
+<br>
+<table class="data">
+<tr align="center">
+<td class="data" width=20><b><?php $url = $sort_url.'&sort=id&order='.$new_order."'>id</a>"; print $url; ?></b></td>
+<td class="data" width=150><b><?php $url = $sort_url.'&sort=timestamp&order='.$new_order."'>Дата</a>"; print $url; ?></b></td>
+<td class="data" width=30><b>Роутер</b></td>
+<td class="data" width=30><b>Протокол</b></td>
+<td class="data" width=150><b><?php $url = $sort_url.'&sort=src_ip&order='.$new_order."'>Откуда</a>"; print $url; ?></b></td>
+<td class="data"><b>DNS</b></td>
+<td class="data" width=50><b>Порт</b></td>
+<td class="data" width=150><b><?php $url = $sort_url.'&sort=dst_ip&order='.$new_order."'>Куда</a>"; print $url; ?></b></td>
+<td class="data"><b>DNS</b></td>
+<td class="data" width=50><b>Порт</b></td>
+<td class="data" width=80><b><?php $url = $sort_url.'&sort=bytes&order='.$new_order."'>Байт</a>"; print $url; ?></b></td>
+<td class="data" width=80><b><?php $url = $sort_url.'&sort=pkt&order='.$new_order."'>Pkt</a>"; print $url; ?></b></td>
+</tr>
+<?php
+$fsql = "SELECT A.id, A.`timestamp`, A.router_id, A.proto, A.src_ip, A.src_port, A.dst_ip, A.dst_port, A.bytes, A.pkt FROM Traffic_detail as A JOIN (SELECT id FROM Traffic_detail 
+        WHERE $gateway_filter (auth_id='$id') and  `timestamp`>='$date1' and `timestamp`<'$date2'
+        ORDER BY `timestamp` ASC LIMIT $start,$displayed) as T ON A.id = T.id ORDER BY $sort_table.$sort_field $order ";
+$userdata = mysqli_query($db_link, $fsql);
+while (list ($uid,$udata, $urouter, $uproto, $sip, $sport,$dip, $dport, $ubytes, $upkt) = mysqli_fetch_array($userdata)) {
+    print "<tr align=center align=center class=\"tr1\" onmouseover=\"className='tr2'\" onmouseout=\"className='tr1'\">\n";
+    print "<td class=\"data\">$uid</td>\n";
+    print "<td class=\"data\">$udata</td>\n";
+    print "<td class=\"data\">$gateway_list[$urouter]</td>\n";
+    print "<td class=\"data\">" . $uproto . "</td>\n";
+    print "<td class=\"data\" align=left>" . long2ip($sip) . "</td>\n";
+    $ip_name = '-';
+    if ($rdns) { $ip_name = ResolveIP($db_link,$sip); }
+    print "<td class=\"data\" align=left>" . $ip_name . "</td>\n";
+    print "<td class=\"data\">" .$sport . "</td>\n";
+    print "<td class=\"data\" align=left>" . long2ip($dip) . "</td>\n";
+    $ip_name = '-';
+    if ($rdns) { $ip_name = ResolveIP($db_link,$dip); }
+    print "<td class=\"data\" align=left>" . $ip_name . "</td>\n";
+    print "<td class=\"data\">" . $dport . "</td>\n";
+    print "<td class=\"data\" align=right>" . fbytes($ubytes) . "</td>\n";
+    print "<td class=\"data\" align=right>" . $upkt . "</td>\n";
+    print "</tr>\n";
+}
+?>
+</table>
+<?php print_navigation($page_url,$page,$displayed,$count_records[0],$total); ?>
+<br>
+<?php
+require_once ($_SERVER['DOCUMENT_ROOT']."/inc/footer.php");
+?>

+ 40 - 27
html/admin/users/add_dhcp.php

@@ -1,26 +1,21 @@
 <?php
 require_once ($_SERVER['DOCUMENT_ROOT']."/inc/qauth.php");
 
-if (isset($_GET["ip"]) and isset($_GET["mac"])) {
+if (!empty($_GET["ip"]) and !empty($_GET["mac"])) {
     $ip = $_GET["ip"];
     $mac = mac_dotted(trim($_GET["mac"]));
-    if (isset($_GET["host"])) {
-        $dhcp_hostname = trim($_GET["host"]);
-    }
+    $dhcp_hostname = NULL;
+    if (!empty($_GET["host"])) { $dhcp_hostname = trim($_GET["host"]); }
     $faction = $_GET["action"] * 1;
-    if ($faction === 1) {
-        $action = 'add';
-    }
-    if ($faction === 0) {
-        $action = 'del';
-    }
-    if (! isset($action)) {
-        $action = 'add';
-    }
+    $action = 'add';
+    if ($faction == 1) { $action = 'add'; }
+    if ($faction == 0) { $action = 'del'; }
+
     LOG_VERBOSE($db_link, "external dhcp request for $ip [$mac] $action");
     if (checkValidIp($ip) and is_our_network($db_link, $ip)) {
 	$log_dhcp = 1;
         $ip_aton = ip2long($ip);
+
 	//check hotspot
 	$hotspot_user = is_hotspot($db_link,$ip);
 	if ($hotspot_user) {
@@ -29,22 +24,40 @@ if (isset($_GET["ip"]) and isset($_GET["mac"])) {
 		if (!isset($log_dhcp_hotspot)) { $log_dhcp_hotspot = 0; }
 		$log_dhcp = !$log_dhcp_hotspot;
 		}
-	if ($faction ===0 and get_count_records($db_link, 'User_auth', "ip_int=" . $ip_aton . " and enabled=1")===0) {
-    	    LOG_VERBOSE($db_link, "dhcp action delete for unknown ip: $ip. Skip add record.");
-	    } else {
-            $aid = resurrection_auth($db_link, $ip, $mac, $action, $dhcp_hostname);
-		if ($log_dhcp) {
-    		    $dhcp_log[auth_id] = $aid;
-        	    $dhcp_log[ip] = $ip;
-		    $dhcp_log[ip_int] = $ip_aton;
-        	    $dhcp_log[mac] = $mac;
-		    $dhcp_log[action] = $action;
-    	        insert_record($db_link, "dhcp_log", $dhcp_log); 
-    		}
+
+	$auth = get_record_sql($db_link,"SELECT * FROM User_auth WHERE ip_int=" . $ip_aton . " AND deleted=0");
+
+	$aid = NULL;
+	if (!empty($auth)) {
+	    $aid = $auth['id'];
+	    LOG_VERBOSE($db_link,"Found auth for dhcp id: $aid with ip: $ip mac: $mac");
+	    }
+
+	if ($action ==='add' and empty($auth)) {
+	    LOG_VERBOSE($db_link,"Add user by dhcp request ip: $ip mac: $mac");
+	    $aid = resurrection_auth($db_link, $ip, $mac, $action, $dhcp_hostname);
+            }
+
+	if ($action ==='del' and !empty($auth)) {
+            $last_time = strtotime($auth['dhcp_time']);
+            LOG_VERBOSE($db_link,"Delete action found for ip $ip (id: $aid, userid: ".$auth['user_id']."). Last timestamp = ".strftime('%Y-%m-%d %H-%M-%S',$last_time)." Now = ".strftime('%Y-%m-%d %H-%M-%S',time()));
+	    if ((time() - $last_time>60) and ($auth['user_id'] == $default_user_id or $auth['user_id'] == $hotspot_user_id)) {
+                LOG_VERBOSE($db_link,"Remove dynamic user (id: $aid) by dhcp request for ip: $ip mac: $mac");
+	        delete_record($db_link,"User_auth","id=".$aid); 
+	        }
+	    }
+	
+	if ($log_dhcp) {
+    	    $dhcp_log['auth_id'] = $aid;
+            $dhcp_log['ip'] = $ip;
+	    $dhcp_log['ip_int'] = $ip_aton;
+            $dhcp_log['mac'] = $mac;
+	    $dhcp_log['action'] = $action;
+    	    insert_record($db_link, "dhcp_log", $dhcp_log); 
     	    }
-    } else {
+        } else {
         LOG_ERROR($db_link, "$ip - wrong network!");
-    }
+        }
 }
 unset($_GET);
 ?>

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

@@ -29,8 +29,8 @@ if (isset($_POST['s_save'])) {
         $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[alias] = trim($_POST['s_alias'][$j]);
-            $new[description] = trim($_POST['s_comment'][$j]);
+            $new['alias'] = trim($_POST['s_alias'][$j]);
+            $new['description'] = trim($_POST['s_comment'][$j]);
             update_record($db_link, "User_auth_alias", "id='{$save_id}'", $new);
         }
     }
@@ -40,8 +40,8 @@ if (isset($_POST['s_save'])) {
 if (isset($_POST["s_create"])) {
     $new_alias = $_POST["s_create_alias"];
     if (isset($new_alias)) {
-        $new[alias] = trim($new_alias);
-        $new[auth_id] = $id;
+        $new['alias'] = trim($new_alias);
+        $new['auth_id'] = $id;
         LOG_INFO($db_link, "Create new alias $new_alias");
         insert_record($db_link, "User_auth_alias", $new);
     }
@@ -56,7 +56,7 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
 <div id="cont">
 <br>
 <form name="def" action="edit_alias.php" method="post">
-<b>Альясы для <?php print_url($auth_info[ip],"/admin/users/editauth.php?id=$id"); ?></b> <br>
+<b>Альясы для <?php print_url($auth_info['ip'],"/admin/users/editauth.php?id=$id"); ?></b> <br>
 <table class="data">
 <tr align="center">
 	<td></td>

+ 95 - 93
html/admin/users/editauth.php

@@ -10,7 +10,7 @@ $msg_error = "";
 $sSQL = "SELECT * FROM User_auth WHERE id=$id";
 $old_auth_info = get_record_sql($db_link, $sSQL);
 
-if (isset($_POST["editauth"]) and !$old_auth_info[deleted]) {
+if (isset($_POST["editauth"]) and !$old_auth_info['deleted']) {
     $ip = trim($_POST["f_ip"]);
     if (checkValidIp($ip)) {
 	$mac=mac_dotted($_POST["f_mac"]);
@@ -36,48 +36,48 @@ if (isset($_POST["editauth"]) and !$old_auth_info[deleted]) {
         }
         $ip_aton = ip2long($first_user_ip);
         $ip_aton_end = ip2long($last_user_ip);
-        list ($parent_id) = mysqli_fetch_array(mysqli_query($db_link, "Select user_id from User_auth where id=$id"));
-        list ($lid) = mysqli_fetch_array(mysqli_query($db_link, "Select user_id from User_auth where ($ip_aton BETWEEN ip_int and ip_int_end) and id<>$id and deleted=0"));
+        $parent_user = get_record_sql($db_link, "SELECT user_id FROM User_auth WHERE id=$id");
+        $parent_id = $parent_user['user_id'];
+        $locate_user = get_record_sql($db_link, "SELECT * FROM User_auth WHERE `ip_int`=$ip_aton AND id<>$id AND deleted=0");
+        $lid = $locate_user['user_id'];
         if (isset($lid) and ($lid != $parent_id)) {
-            list ($lname) = mysqli_fetch_array(mysqli_query($db_link, "Select login from User_list where id=$lid"));
-            $msg_error = "$ip $msg_exists Принадлежит пользователю $lname.";
+            $msg_error = "$ip $msg_exists Принадлежит пользователю ".$locate_user['login'];
             unset($_POST);
     	    } else {
-            $new[ip] = $ip;
-            $new[ip_int] = $ip_aton;
-            $new[ip_int_end] = $ip_aton_end;
-            $new[mac] = mac_dotted($_POST["f_mac"]);
-            $new[clientid] = $_POST["f_clientid"];
-            $new[comments] = $_POST["f_comments"];
+            $new['ip'] = $ip;
+            $new['ip_int'] = $ip_aton;
+            $new['mac'] = mac_dotted($_POST["f_mac"]);
+            $new['clientid'] = $_POST["f_clientid"];
+            $new['comments'] = $_POST["f_comments"];
             $f_dnsname=trim($_POST["f_dns_name"]);
-            if (!empty($f_dnsname) and checkValidHostname($f_dnsname) and checkUniqHostname($db_link,$id,$f_dnsname)) { $new[dns_name] = $f_dnsname; }
-            if (empty($f_dnsname)) { $new[dns_name] = ''; }
-            $new[host_model] = $_POST["f_host_model"];
-            $new[save_traf] = $_POST["f_save_traf"] * 1;
-            $new[dhcp_acl] = trim($_POST["f_acl"]);
+            if (!empty($f_dnsname) and checkValidHostname($f_dnsname) and checkUniqHostname($db_link,$id,$f_dnsname)) { $new['dns_name'] = $f_dnsname; }
+            if (empty($f_dnsname)) { $new['dns_name'] = ''; }
+            $new['host_model'] = $_POST["f_host_model"];
+            $new['save_traf'] = $_POST["f_save_traf"] * 1;
+            $new['dhcp_acl'] = trim($_POST["f_acl"]);
             if ($default_user_id == $parent_id or $hotspot_user_id == $parent_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['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;
             } else {
-                $new[nagios_handler] = $_POST["f_handler"];
-                $new[enabled] = $_POST["f_enabled"] * 1;
-                $new[link_check] = $_POST["f_link"] * 1;
-                $new[nagios] = $_POST["f_nagios"] * 1;
-                $new[dhcp] = $_POST["f_dhcp"] * 1;
-                $new[blocked] = $_POST["f_blocked"] * 1;
-                $new[day_quota] = $_POST["f_day_q"] * 1;
-                $new[month_quota] = $_POST["f_month_q"] * 1;
-                $new[queue_id] = $_POST["f_queue_id"] * 1;
-                $new[filter_group_id] = $_POST["f_group_id"] * 1;
+                $new['nagios_handler'] = $_POST["f_handler"];
+                $new['enabled'] = $_POST["f_enabled"] * 1;
+                $new['link_check'] = $_POST["f_link"] * 1;
+                $new['nagios'] = $_POST["f_nagios"] * 1;
+                $new['dhcp'] = $_POST["f_dhcp"] * 1;
+                $new['blocked'] = $_POST["f_blocked"] * 1;
+                $new['day_quota'] = $_POST["f_day_q"] * 1;
+                $new['month_quota'] = $_POST["f_month_q"] * 1;
+                $new['queue_id'] = $_POST["f_queue_id"] * 1;
+                $new['filter_group_id'] = $_POST["f_group_id"] * 1;
             }
-            $changes = get_diff_rec($db_link,"User_auth","id='$id'", $new, 1);
+            $changes = get_diff_rec($db_link,"User_auth","id='$id'", $new, 0);
             if (!empty($changes)) { LOG_WARNING($db_link,"Изменен адрес доступа! Список изменений: $changes"); }
             update_record($db_link, "User_auth", "id='$id'", $new);
         }
@@ -87,9 +87,9 @@ if (isset($_POST["editauth"]) and !$old_auth_info[deleted]) {
     header("Location: " . $_SERVER["REQUEST_URI"]);
 }
 
-if (isset($_POST["moveauth"]) and !$old_auth_info[deleted]) {
-    $new[user_id] = $_POST["new_parent"];
-    $changes = get_diff_rec($db_link,"User_auth","id='$id'", $new, 1);
+if (isset($_POST["moveauth"]) and !$old_auth_info['deleted']) {
+    $new['user_id'] = $_POST["new_parent"];
+    $changes = get_diff_rec($db_link,"User_auth","id='$id'", $new, 0);
     if (!empty($changes)) { LOG_WARNING($db_link,"Адрес доступа перемещён к другому пользователю! Применено: $changes"); }
     update_record($db_link, "User_auth", "id='$id'", $new);
     header("Location: " . $_SERVER["REQUEST_URI"]);
@@ -109,37 +109,39 @@ if (isset($_POST["recovery"])) {
         }
         $ip_aton = ip2long($first_user_ip);
         $ip_aton_end = ip2long($last_user_ip);
-        list ($parent_id) = mysqli_fetch_array(mysqli_query($db_link, "Select user_id from User_auth where id=$id"));
-        list ($lid) = mysqli_fetch_array(mysqli_query($db_link, "Select user_id from User_auth where ($ip_aton BETWEEN ip_int and ip_int_end) and id<>$id and deleted=0"));
+
+        $parent_user = get_record_sql($db_link, "SELECT user_id FROM User_auth WHERE id=$id");
+        $parent_id = $parent_user['user_id'];
+        $locate_user = get_record_sql($db_link, "SELECT * FROM User_auth WHERE `ip_int`=$ip_aton AND id<>$id AND deleted=0");
+        $lid = $locate_user['user_id'];
         if (isset($lid) and ($lid != $parent_id)) {
-            list ($lname) = mysqli_fetch_array(mysqli_query($db_link, "Select login from User_list where id=$lid"));
-            $msg_error = "$ip $msg_exists Принадлежит пользователю $lname.";
+            $msg_error = "$ip $msg_exists Принадлежит пользователю ".$locate_user['login'];
             unset($_POST);
-        } else {
-            $new[deleted] = 0;
+            } else {
+            $new['deleted'] = 0;
             if ($default_user_id == $parent_id or $hotspot_user_id == $parent_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['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;
             } else {
-                $new[nagios_handler] = $_POST["f_handler"];
-                $new[enabled] = $_POST["f_enabled"] * 1;
-                $new[link_check] = $_POST["f_link"] * 1;
-                $new[nagios] = $_POST["f_nagios"] * 1;
-                $new[dhcp] = $_POST["f_dhcp"] * 1;
-                $new[blocked] = $_POST["f_blocked"] * 1;
-                $new[day_quota] = $_POST["f_day_q"] * 1;
-                $new[month_quota] = $_POST["f_month_q"] * 1;
-                $new[queue_id] = $_POST["f_queue_id"] * 1;
-                $new[filter_group_id] = $_POST["f_group_id"] * 1;
+                $new['nagios_handler'] = $_POST["f_handler"];
+                $new['enabled'] = $_POST["f_enabled"] * 1;
+                $new['link_check'] = $_POST["f_link"] * 1;
+                $new['nagios'] = $_POST["f_nagios"] * 1;
+                $new['dhcp'] = $_POST["f_dhcp"] * 1;
+                $new['blocked'] = $_POST["f_blocked"] * 1;
+                $new['day_quota'] = $_POST["f_day_q"] * 1;
+                $new['month_quota'] = $_POST["f_month_q"] * 1;
+                $new['queue_id'] = $_POST["f_queue_id"] * 1;
+                $new['filter_group_id'] = $_POST["f_group_id"] * 1;
             }
-            $changes = get_diff_rec($db_link,"User_auth","id='$id'", $new, 1);
+            $changes = get_diff_rec($db_link,"User_auth","id='$id'", $new, 0);
             if (!empty($changes)) { LOG_WARNING($db_link,"Восстановлен адрес доступа! Применено: $changes"); }
             update_record($db_link, "User_auth", "id='$id'", $new);
         }
@@ -156,13 +158,13 @@ require_once ($_SERVER['DOCUMENT_ROOT']."/inc/header.php");
 $sSQL = "SELECT * FROM User_auth WHERE id=$id";
 $auth_info = get_record_sql($db_link, $sSQL);
 
-$parent_name = get_login($db_link, $auth_info[user_id]);
-if ($auth_info[dhcp_time] == '0000-00-00 00:00:00') { $dhcp_str = ''; } else { $dhcp_str = $auth_info[dhcp_time] . " (" . $auth_info[dhcp_action] . ")"; }
-if ($auth_info[last_found] == '0000-00-00 00:00:00') { $auth_info[last_found] = ''; }
+$parent_name = get_login($db_link, $auth_info['user_id']);
+if ($auth_info['dhcp_time'] == '0000-00-00 00:00:00') { $dhcp_str = ''; } else { $dhcp_str = $auth_info['dhcp_time'] . " (" . $auth_info['dhcp_action'] . ")"; }
+if ($auth_info['last_found'] == '0000-00-00 00:00:00') { $auth_info['last_found'] = ''; }
 ?>
 <div id="cont">
 <?
-print "<b> Адрес доступа пользователя <a href=/admin/users/edituser.php?id=$auth_info[user_id]>$parent_name</a> <b>";
+print "<b> Адрес доступа пользователя <a href=/admin/users/edituser.php?id=".$auth_info['user_id'].">".$parent_name."</a> <b>";
 ?>
 <form name="def" action="editauth.php?id=<? echo $id; ?>" method="post">
 <input type="hidden" name="id" value=<? echo $id; ?>>
@@ -177,12 +179,12 @@ print "<b> Адрес доступа пользователя <a href=/admin/use
 <td width=70><?php print $cell_connection; ?></td>
 </tr>
 <tr>
-<td><input type="text" name="f_dns_name" value="<? echo $auth_info[dns_name]; ?>" pattern="^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$"></td>
-<td><input type="text" name="f_comments" value="<? echo $auth_info[comments]; ?>"></td>
-<td><?php print_qa_select('f_enabled', $auth_info[enabled]); ?></td>
-<td><?php print_qa_select('f_blocked', $auth_info[blocked]); ?></td>
-<td><input type="text" name="f_day_q" value="<? echo $auth_info[day_quota]; ?>" size=5></td>
-<td><input type="text" name="f_month_q"	value="<? echo $auth_info[month_quota]; ?>" size=5></td>
+<td><input type="text" name="f_dns_name" value="<? echo $auth_info['dns_name']; ?>" pattern="^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$"></td>
+<td><input type="text" name="f_comments" value="<? echo $auth_info['comments']; ?>"></td>
+<td><?php print_qa_select('f_enabled', $auth_info['enabled']); ?></td>
+<td><?php print_qa_select('f_blocked', $auth_info['blocked']); ?></td>
+<td><input type="text" name="f_day_q" value="<? echo $auth_info['day_quota']; ?>" size=5></td>
+<td><input type="text" name="f_month_q"	value="<? echo $auth_info['month_quota']; ?>" size=5></td>
 <td><?php print get_connection($db_link, $id); ?></td>
 </tr>
 <tr>
@@ -194,12 +196,12 @@ print "<b> Адрес доступа пользователя <a href=/admin/use
 <td><?php print $cell_shaper; ?></td>
 <td></td>
 <tr>
-<td><input type="text" name="f_ip" value="<? echo $auth_info[ip]; ?>" pattern="^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"></td>
-<td><input type="text" name="f_mac" value="<? echo $auth_info[mac]; ?>"></td>
-<td><input type="text" name="f_clientid" value="<? echo $auth_info[clientid]; ?>"></td>
-<td><?php print_qa_select('f_dhcp', $auth_info[dhcp]); ?></td>
-<td><?php print_group_select($db_link, 'f_group_id', $auth_info[filter_group_id]); ?> </td>
-<td><?php print_queue_select($db_link, 'f_queue_id', $auth_info[queue_id]); ?> </td>
+<td><input type="text" name="f_ip" value="<? echo $auth_info['ip']; ?>" pattern="^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"></td>
+<td><input type="text" name="f_mac" value="<? echo $auth_info['mac']; ?>"></td>
+<td><input type="text" name="f_clientid" value="<? echo $auth_info['clientid']; ?>"></td>
+<td><?php print_qa_select('f_dhcp', $auth_info['dhcp']); ?></td>
+<td><?php print_group_select($db_link, 'f_group_id', $auth_info['filter_group_id']); ?> </td>
+<td><?php print_queue_select($db_link, 'f_queue_id', $auth_info['queue_id']); ?> </td>
 <td></td>
 </tr>
 <tr>
@@ -211,27 +213,27 @@ print "<b> Адрес доступа пользователя <a href=/admin/use
 <td><?php print $cell_traf; ?></td>
 <td></td>
 <tr>
-<td><input type="text" name="f_host_model" value="<? echo $auth_info[host_model]; ?>"></td>
-<td><input type="text" name="f_handler"	value="<? echo $auth_info[nagios_handler]; ?>"></td>
-<td><input type="text" name="f_acl" value="<? echo $auth_info[dhcp_acl]; ?>"></td>
-<td><?php print_qa_select('f_nagios', $auth_info[nagios]); ?></td>
-<td><?php print_qa_select('f_link', $auth_info[link_check]); ?></td>
-<td><?php print_qa_select('f_save_traf', $auth_info[save_traf]); ?></td>
+<td><input type="text" name="f_host_model" value="<? echo $auth_info['host_model']; ?>"></td>
+<td><input type="text" name="f_handler"	value="<? echo $auth_info['nagios_handler']; ?>"></td>
+<td><input type="text" name="f_acl" value="<? echo $auth_info['dhcp_acl']; ?>"></td>
+<td><?php print_qa_select('f_nagios', $auth_info['nagios']); ?></td>
+<td><?php print_qa_select('f_link', $auth_info['link_check']); ?></td>
+<td><?php print_qa_select('f_save_traf', $auth_info['save_traf']); ?></td>
 <td></td>
 </tr>
 <tr>
-<td><?php print "Created: " . $auth_info[timestamp]; ?> </td>
+<td><?php print "Created: " . $auth_info['timestamp']; ?> </td>
 <td colspan=2><?php print "Dhcp status: " . $dhcp_str; ?></td>
-<td colspan=2><?php print "Dhcp hostname: " . $auth_info[dhcp_hostname]; ?></td>
-<td colspan=2><?php print "Last found: " . $auth_info[last_found]; ?></td>
+<td colspan=2><?php print "Dhcp hostname: " . $auth_info['dhcp_hostname']; ?></td>
+<td colspan=2><?php print "Last found: " . $auth_info['last_found']; ?></td>
 <td></td>
 </tr>
 <tr>
-<td colspan=2><input type="submit" name="moveauth" value=<?php print $btn_move; ?>><?php print_login_select($db_link, 'new_parent', $auth_info[user_id]); ?></td>
+<td colspan=2><input type="submit" name="moveauth" value=<?php print $btn_move; ?>><?php print_login_select($db_link, 'new_parent', $auth_info['user_id']); ?></td>
 <td><a href=/admin/logs/authlog.php?auth_id=<?php print $id; ?>>Лог</a></td>
 <?php
-if ($auth_info[deleted]) {
-    print "<td colspan=2>Deleted: " . $auth_info[changed_time]."</td>";
+if ($auth_info['deleted']) {
+    print "<td colspan=2>Deleted: " . $auth_info['changed_time']."</td>";
     print "<td colspan=2 align=right><input type=\"submit\" name=\"recovery\" value=\"Восстановить\"></td>";
 } else {
     print "<td colspan=2></td>";

Algunos archivos no se mostraron porque demasiados archivos cambiaron en este cambio