-
-
+
+
-
-
-
-
+
-'.$pia_func_netdevname.' / '.$pia_func_netdevtyp;
- if ($pia_func_netdevport != "") {echo ' ('.$pia_func_netdevport.')';}
- echo '';
-}
-function createnetworktabcontent($pia_func_netdevid, $pia_func_netdevname, $pia_func_netdevtyp, $pia_func_netdevport, $activetab) {
- global $pia_lang;
- echo '
-
'.$pia_func_netdevname.' (ID: '.$pia_func_netdevid.')
';
- echo '
-
-
- | Port |
- '.$pia_lang['Network_Table_State'].' |
- '.$pia_lang['Network_Table_Hostname'].' |
- '.$pia_lang['Network_Table_IP'].' |
-
';
- // Prepare Array for Devices with Port value
- // If no Port is set, the Port number is set to 1
- if ($pia_func_netdevport == "") {$pia_func_netdevport = 1;}
- // Create Array with specific length
- $network_device_portname = array();
- $network_device_portmac = array();
- $network_device_portip = array();
- $network_device_portstate = array();
- // make sql query for Network Hardware ID
- global $db;
- $func_sql = 'SELECT * FROM "Devices" WHERE "dev_Infrastructure" = "'.$pia_func_netdevid.'"';
- $func_result = $db->query($func_sql);//->fetchArray(SQLITE3_ASSOC);
- while($func_res = $func_result->fetchArray(SQLITE3_ASSOC)) {
- //if(!isset($func_res['dev_Name'])) continue;
- if ($func_res['dev_PresentLastScan'] == 1) {$port_state = 'Online
';} else {$port_state = 'Offline
';}
- // Prepare Table with Port > push values in array
- if ($pia_func_netdevport > 1)
- {
- if (stristr($func_res['dev_Infrastructure_port'], ',') == '') {
- if ($network_device_portname[$func_res['dev_Infrastructure_port']] != '') {$network_device_portname[$func_res['dev_Infrastructure_port']] = $network_device_portname[$func_res['dev_Infrastructure_port']].','.$func_res['dev_Name'];} else {$network_device_portname[$func_res['dev_Infrastructure_port']] = $func_res['dev_Name'];}
- if ($network_device_portmac[$func_res['dev_Infrastructure_port']] != '') {$network_device_portmac[$func_res['dev_Infrastructure_port']] = $network_device_portmac[$func_res['dev_Infrastructure_port']].','.$func_res['dev_MAC'];} else {$network_device_portmac[$func_res['dev_Infrastructure_port']] = $func_res['dev_MAC'];}
- if ($network_device_portip[$func_res['dev_Infrastructure_port']] != '') {$network_device_portip[$func_res['dev_Infrastructure_port']] = $network_device_portip[$func_res['dev_Infrastructure_port']].','.$func_res['dev_LastIP'];} else {$network_device_portip[$func_res['dev_Infrastructure_port']] = $func_res['dev_LastIP'];}
- if (isset($network_device_portstate[$func_res['dev_Infrastructure_port']])) {$network_device_portstate[$func_res['dev_Infrastructure_port']] = $network_device_portstate[$func_res['dev_Infrastructure_port']].','.$func_res['dev_PresentLastScan'];} else {$network_device_portstate[$func_res['dev_Infrastructure_port']] = $func_res['dev_PresentLastScan'];}
- } else {
- $multiport = array();
- $multiport = explode(',',$func_res['dev_Infrastructure_port']);
- foreach($multiport as $row) {
- $network_device_portname[trim($row)] = $func_res['dev_Name'];
- $network_device_portmac[trim($row)] = $func_res['dev_MAC'];
- $network_device_portip[trim($row)] = $func_res['dev_LastIP'];
- $network_device_portstate[trim($row)] = $func_res['dev_PresentLastScan'];
- }
- unset($multiport);
+
+
+ echo values
- // Specific icon for devicetype
- if ($pia_func_netdevtyp == "WLAN") {$dev_port_icon = 'fa-wifi';}
- if ($pia_func_netdevtyp == "Powerline") {$dev_port_icon = 'fa-flash';}
- echo ' | '.$port_state.' | '.$func_res['dev_Name'].' | '.$func_res['dev_LastIP'].' |
';
- }
- }
- // Create table with Port
- if ($pia_func_netdevport > 1)
- {
- for ($x=1; $x<=$pia_func_netdevport; $x++)
+
+ // online/offline status circle (red/green)
+ $node_badge = "";
+ if($node_status == 1) // 1 means online, 0 offline
{
- // Prepare online/offline badge for later functions
- $online_badge = 'Online
';
- $offline_badge = 'Offline
';
- // Set online/offline badge
- echo '';
- echo '| '.$x.' | ';
- // Set online/offline badge
- // Check if multiple badges necessary
- if (stristr($network_device_portstate[$x],',') == '') {
- // Set single online/offline badge
- if ($network_device_portstate[$x] == 1) {$port_state = $online_badge;} else {$port_state = $offline_badge;}
- echo ''.$port_state.' | ';
- } else {
- // Set multiple online/offline badges
- $multistate = array();
- $multistate = explode(',',$network_device_portstate[$x]);
- echo '';
- foreach($multistate as $key => $value) {
- if ($value == 1) {$port_state = $online_badge;} else {$port_state = $offline_badge;}
- echo $port_state.' ';
- }
- echo ' | ';
- unset($multistate);
- }
- // Check if multiple Hostnames are set
- // print single hostname
- if (stristr($network_device_portmac[$x],',') == '') {
- echo ''.$network_device_portname[$x].' | ';
- } else {
- // print multiple hostnames with separate links
- $multimac = array();
- $multimac = explode(',',$network_device_portmac[$x]);
- $multiname = array();
- $multiname = explode(',',$network_device_portname[$x]);
- echo '';
- foreach($multiname as $key => $value) {
- echo ''.$value.' ';
- }
- echo ' | ';
- unset($multiname, $multimac);
- }
- // Check if multiple IP are set
- // print single IP
- if (stristr($network_device_portip[$x],',') == '') {
- echo ''.$network_device_portip[$x].' | ';
- } else {
- // print multiple IPs
- $multiip = array();
- $multiip = explode(',',$network_device_portip[$x]);
- echo '';
- foreach($multiip as $key => $value) {
- echo $value.' ';
- }
- echo ' | ';
- unset($multiip);
- }
- echo '
';
+ $node_badge = circle_online;
+ } else
+ {
+ $node_badge = circle_offline;
}
- }
- echo '
-
';
- echo '
';
-}
-// #####################################
-// ## End Function Setup
-// #####################################
+
-// #####################################
-// ## Create Tabs
-// #####################################
-$sql = 'SELECT "device_id", "net_device_name", "net_device_typ", "net_device_port" FROM "network_infrastructure"';
-$result = $db->query($sql);//->fetchArray(SQLITE3_ASSOC);
-?>
-
-
-fetchArray(SQLITE3_ASSOC)){
- if(!isset($res['device_id'])) continue;
- if ($i == 0) {$active = 'active';} else {$active = '';}
- createnetworktab($res['device_id'], $res['net_device_name'], $res['net_device_typ'], $res['net_device_port'], $active);
- $i++;
-}
-?>
-
-
-fetchArray(SQLITE3_ASSOC)){
- if(!isset($res['device_id'])) continue;
- if ($i == 0) {$active = 'active';} else {$active = '';}
- createnetworktabcontent($res['device_id'], $res['net_device_name'], $res['net_device_typ'], $res['net_device_port'], $active);
- $i++;
-}
-unset($i);
-?>
-
-
-
-
-
-
+ $str_tab_header = '
+ '
+ .$node_name.' ' .$str_port.$node_badge.
+ '
+ ';
+
+ echo $str_tab_header;
+
+ }
+
+ // Create pane content (displayed inside of the tabs)
+ function createPane($node_mac, $node_name, $node_status, $node_type, $node_ports_count, $node_parent_mac, $activetab){
+ global $pia_lang; //language strings
+
+ // online/offline status circle (red/green)
+ $node_badge = "";
+ if($node_status == 1) // 1 means online, 0 offline
+ {
+ $node_badge = badge_online;
+ } else
+ {
+ $node_badge = badge_offline;
+ }
+
+ $str_tab_pane = '
+
+ '.$node_name.'
+
+
+
+
+ |
+ MAC:
+ |
+ '
+ .$node_mac.
+ ' |
+
+
+ |
+ '.$pia_lang['Device_TableHead_Type'].'
+ |
+
+ ' .$node_type. '
+ |
+
+
+ |
+ '.$pia_lang['Network_Table_State'].':
+ |
+ '
+ .$node_badge.
+ ' |
+
+
+ |
+ '.$pia_lang['DevDetail_MainInfo_Network'].'
+ |
+
+
+ '.$node_parent_mac.'
+
+ |
+
+
+
+
+
';
+
+ $str_table = '
+ '.$pia_lang['Device_Title'].'
+
+
+
+
+ | Port |
+ '.$pia_lang['Network_Table_State'].' |
+ '.$pia_lang['Network_Table_Hostname'].' |
+ '.$pia_lang['Network_Table_IP'].' |
+
';
+
+ // Prepare Array for Devices with Port value
+ // If no Port is set, the Port number is set to 0
+ if ($node_ports_count == "") {
+ $node_ports_count = 0;
+ }
+
+ // Get all leafs connected to a node based on the node_mac
+ $func_sql = 'SELECT dev_Network_Node_port as port,
+ dev_MAC as mac,
+ dev_PresentLastScan as online,
+ dev_Name as name,
+ dev_DeviceType as type,
+ dev_LastIP as last_ip,
+ (select dev_DeviceType from Devices a where dev_MAC = "'.$node_mac.'") as node_type
+ FROM Devices WHERE dev_Network_Node_MAC_ADDR = "'.$node_mac.'" order by port asc';
+
+ global $db;
+ $func_result = $db->query($func_sql);
+
+ // array
+ $tableData = array();
+ while ($row = $func_result -> fetchArray (SQLITE3_ASSOC)) {
+ // Push row data
+ $tableData[] = array( 'port' => $row['port'],
+ 'mac' => $row['mac'],
+ 'online' => $row['online'],
+ 'name' => $row['name'],
+ 'type' => $row['type'],
+ 'last_ip' => $row['last_ip'],
+ 'node_type' => $row['node_type']);
+ }
+
+ // Control no rows
+ if (empty($tableData)) {
+ $tableData = [];
+ }
+
+ $str_table_rows = "";
+
+ foreach ($tableData as $row) {
+
+ if ($row['online'] == 1) {
+ $port_state = badge_online;
+ } else {
+ $port_state = badge_offline;
+ }
+
+ // prepare HTML for the port table column cell
+ $port_content = "N/A";
+
+ if ($row['node_type'] == "WLAN" || $row['node_type'] == "AP" ) {
+ $port_content = '';
+ } elseif ($row['node_type'] == "Powerline")
+ {
+ $port_content = '';
+ } elseif ($row['port'] != NULL && $row['port'] != "")
+ {
+ $port_content = $row['port'];
+ }
+
+ $str_table_rows = $str_table_rows.
+ '
+ |
+ '.$port_content.'
+ |
+ '
+ .$port_state.
+ ' |
+
+
+ '.$row['name'].'
+
+ |
+ '
+ .$row['last_ip'].
+ ' |
+
';
+
+ }
+
+ $str_table_close = '
+
';
+
+ // no connected device - don't render table, just display some info
+ if($str_table_rows == "")
+ {
+ $str_table = "
+
+ ".$pia_lang['Device_Title']."
+
+
+ This network device (node) doesn't have any assigned devices (leaf nodes).
+ Go to
".$pia_lang['Device_Title'].", select a device you want to attach to this node and assign it in the
Details tab by selecting it in the
".$pia_lang['DevDetail_MainInfo_Network'] ." dropdown.
+
+
";
+ $str_table_close = "";
+ }
+
+ $str_close_pane = '
+
';
+
+ // write the HTML
+ echo ''.$str_tab_header.
+ $str_tab_pane.
+ $str_table.
+ $str_table_rows.
+ $str_table_close.
+ $str_close_pane;
+ }
+
+
+ // Create Top level tabs (List of network devices), explanation of the terminology below:
+ //
+ // Switch 1 (node)
+ // /(p1) \ (p2) <----- port numbers
+ // / \
+ // Smart TV (leaf) Switch 2 (node (for the PC) and leaf (for Switch 1))
+ // \
+ // PC (leaf)
+
+ $sql = "SELECT node_name, node_mac, online, node_type, node_ports_count, parent_mac
+ FROM
+ (
+ SELECT a.dev_Name as node_name,
+ a.dev_MAC as node_mac,
+ a.dev_PresentLastScan as online,
+ a.dev_DeviceType as node_type,
+ a.dev_Network_Node_MAC_ADDR as parent_mac
+ FROM Devices a
+ WHERE a.dev_DeviceType in ('AP', 'Gateway', 'Powerline', 'Switch', 'WLAN', 'PLC', 'Router','USB LAN Adapter', 'USB WIFI Adapter', 'Internet')
+ ) t1
+ LEFT JOIN
+ (
+ SELECT b.dev_Network_Node_MAC_ADDR as node_mac_2,
+ count() as node_ports_count
+ FROM Devices b
+ WHERE b.dev_Network_Node_MAC_ADDR NOT NULL group by b.dev_Network_Node_MAC_ADDR
+ ) t2
+ ON (t1.node_mac = t2.node_mac_2);
+ ";
+
+ $result = $db->query($sql);
+
+ // array
+ $tableData = array();
+ while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
+ // Push row data
+ $tableData[] = array( 'node_mac' => $row['node_mac'],
+ 'node_name' => $row['node_name'],
+ 'online' => $row['online'],
+ 'node_type' => $row['node_type'],
+ 'parent_mac' => $row['parent_mac'],
+ 'node_ports_count' => $row['node_ports_count']);
+ }
+
+ // Control no rows
+ if (empty($tableData)) {
+ $tableData = [];
+ }
+
+ echo '
+
';
+
+ $activetab='active';
+ foreach ($tableData as $row) {
+ createDeviceTabs( $row['node_mac'],
+ $row['node_name'],
+ $row['online'],
+ $row['node_type'],
+ $row['node_ports_count'],
+ $activetab);
+
+ $activetab = ""; // reset active tab indicator, only the first tab is active
+
+ }
+ echo '
';
+
+ $activetab='active';
+
+ foreach ($tableData as $row) {
+ createPane($row['node_mac'],
+ $row['node_name'],
+ $row['online'],
+ $row['node_type'],
+ $row['node_ports_count'],
+ $row['parent_mac'],
+ $activetab);
+
+ $activetab = ""; // reset active tab indicator, only the first tab is active
+
+ }
+
+ $db->close();
+
+ ?>
+
+
+
+
+
+ query($func_sql);
+
+ // array
+ $tableData = array();
+ while ($row = $func_result -> fetchArray (SQLITE3_ASSOC)) {
+ // Push row data
+ $tableData[] = array( 'mac' => $row['mac'],
+ 'online' => $row['online'],
+ 'name' => $row['name'],
+ 'last_ip' => $row['last_ip']);
+ }
+
+ // Don't do anything if empty
+ if (!(empty($tableData))) {
+ $str_table_header = '
+
+
+
+
+ '.$pia_lang['Network_UnassignedDevices'].'
+
+
+
+
+ | '.$pia_lang['Network_Table_State'].' |
+ '.$pia_lang['Network_Table_Hostname'].' |
+ '.$pia_lang['Network_Table_IP'].' |
+
';
+
+ $str_table_rows = "";
+
+ foreach ($tableData as $row) {
+
+ if ($row['online'] == 1) {
+ $state = badge_online;
+ } else {
+ $state = badge_offline;
+ }
+
+ $str_table_rows = $str_table_rows.
+ '
+ | '
+ .$state.
+ ' |
+
+
+ '.$row['name'].'
+
+ |
+ '
+ .$row['last_ip'].
+ ' |
+
';
+
+ }
+
+ $str_table_close = '
+
+
+
+
';
+
+ // write the html
+ echo $str_table_header.$str_table_rows.$str_table_close;
+ }
+
+ $db->close();
+ ?>
@@ -371,4 +433,4 @@ unset($i);
\ No newline at end of file
+?>
diff --git a/front/php/server/cache-bottom.php b/front/php/server/cache-bottom.php
new file mode 100644
index 00000000..63ff81ca
--- /dev/null
+++ b/front/php/server/cache-bottom.php
@@ -0,0 +1,7 @@
+
\ No newline at end of file
diff --git a/front/php/server/cache-top.php b/front/php/server/cache-top.php
new file mode 100644
index 00000000..17be21e8
--- /dev/null
+++ b/front/php/server/cache-top.php
@@ -0,0 +1,15 @@
+\n";
+ readfile($cachefile);
+ exit;
+}
+ob_start(); // Start the output buffer
+?>
\ No newline at end of file
diff --git a/front/php/server/db.php b/front/php/server/db.php
index 8e3e7706..d4458bc6 100644
--- a/front/php/server/db.php
+++ b/front/php/server/db.php
@@ -8,6 +8,13 @@
// Puche 2021 pi.alert.application@gmail.com GNU GPLv3
//------------------------------------------------------------------------------
+// ## TimeZone processing
+$config_file = "../../../config/pialert.conf";
+$config_file_lines = file($config_file);
+$config_file_lines_timezone = array_values(preg_grep('/^TIMEZONE\s.*/', $config_file_lines));
+$timezone_line = explode("'", $config_file_lines_timezone[0]);
+$Pia_TimeZone = $timezone_line[1];
+date_default_timezone_set($Pia_TimeZone);
//------------------------------------------------------------------------------
// DB File Path
@@ -51,10 +58,11 @@ function OpenDB () {
}
$db = SQLite3_connect(true);
+ $db->exec('PRAGMA journal_mode = wal;');
if(!$db)
{
die ('Error connecting to database');
}
}
-?>
+?>
\ No newline at end of file
diff --git a/front/php/server/devices.php b/front/php/server/devices.php
index 9ea82d40..89ad77e4 100644
--- a/front/php/server/devices.php
+++ b/front/php/server/devices.php
@@ -7,6 +7,13 @@
//------------------------------------------------------------------------------
// Puche 2021 pi.alert.application@gmail.com GNU GPLv3
//------------------------------------------------------------------------------
+// ## TimeZone processing
+$config_file = "../../../config/pialert.conf";
+$config_file_lines = file($config_file);
+$config_file_lines_timezone = array_values(preg_grep('/^TIMEZONE\s.*/', $config_file_lines));
+$timezone_line = explode("'", $config_file_lines_timezone[0]);
+$Pia_TimeZone = $timezone_line[1];
+date_default_timezone_set($Pia_TimeZone);
foreach (glob("../../../db/setting_language*") as $filename) {
$pia_lang_selected = str_replace('setting_language_','',basename($filename));
@@ -34,9 +41,9 @@ if (strlen($pia_lang_selected) == 0) {$pia_lang_selected = 'en_us';}
switch ($action) {
case 'getDeviceData': getDeviceData(); break;
case 'setDeviceData': setDeviceData(); break;
- case 'deleteDevice': deleteDevice(); break;
case 'getNetworkNodes': getNetworkNodes(); break;
- case 'deleteAllWithEmptyMACs': deleteAllWithEmptyMACs(); break;
+ case 'deleteDevice': deleteDevice(); break;
+ case 'deleteAllWithEmptyMACs': deleteAllWithEmptyMACs(); break;
case 'createBackupDB': createBackupDB(); break;
case 'restoreBackupDB': restoreBackupDB(); break;
case 'deleteAllDevices': deleteAllDevices(); break;
@@ -44,13 +51,16 @@ if (strlen($pia_lang_selected) == 0) {$pia_lang_selected = 'en_us';}
case 'runScan1min': runScan1min(); break;
case 'deleteUnknownDevices': deleteUnknownDevices(); break;
case 'deleteEvents': deleteEvents(); break;
+ case 'deleteEvents30': deleteEvents30(); break;
case 'deleteActHistory': deleteActHistory(); break;
case 'deleteDeviceEvents': deleteDeviceEvents(); break;
case 'PiaBackupDBtoArchive': PiaBackupDBtoArchive(); break;
case 'PiaRestoreDBfromArchive': PiaRestoreDBfromArchive(); break;
case 'PiaPurgeDBBackups': PiaPurgeDBBackups(); break;
case 'PiaEnableDarkmode': PiaEnableDarkmode(); break;
- case 'PiaToggleArpScan': PiaToggleArpScan(); break;
+ case 'PiaToggleArpScan': PiaToggleArpScan(); break;
+ case 'ExportCSV': ExportCSV(); break;
+ case 'ImportCSV': ImportCSV(); break;
case 'getDevicesTotals': getDevicesTotals(); break;
case 'getDevicesList': getDevicesList(); break;
@@ -88,8 +98,8 @@ function getDeviceData() {
$deviceData = $row;
$mac = $deviceData['dev_MAC'];
- $deviceData['dev_Network_Node_MAC'] = $row['dev_Infrastructure'];
- $deviceData['dev_Network_Node_port'] = $row['dev_Infrastructure_port'];
+ $deviceData['dev_Network_Node_MAC_ADDR'] = $row['dev_Network_Node_MAC_ADDR'];
+ $deviceData['dev_Network_Node_port'] = $row['dev_Network_Node_port'];
$deviceData['dev_FirstConnection'] = formatDate ($row['dev_FirstConnection']); // Date formated
$deviceData['dev_LastConnection'] = formatDate ($row['dev_LastConnection']); // Date formated
@@ -120,8 +130,10 @@ function getDeviceData() {
$row = $result -> fetchArray (SQLITE3_NUM);
$deviceData['dev_DownAlerts'] = $row[0];
+ // Get current date using php, sql datetime does not return time respective to timezone.
+ $currentdate = date("Y-m-d H:i:s");
// Presence hours
- $sql = 'SELECT CAST(( MAX (0, SUM (julianday (IFNULL (ses_DateTimeDisconnection, DATETIME("now","localtime")))
+ $sql = 'SELECT CAST(( MAX (0, SUM (julianday (IFNULL (ses_DateTimeDisconnection,"'. $currentdate .'" ))
- julianday (CASE WHEN ses_DateTimeConnection < '. $periodDate .' THEN '. $periodDate .'
ELSE ses_DateTimeConnection END)) *24 )) AS INT)
FROM Sessions
@@ -149,23 +161,23 @@ function setDeviceData() {
// sql
$sql = 'UPDATE Devices SET
- dev_Name = "'. quotes($_REQUEST['name']) .'",
- dev_Owner = "'. quotes($_REQUEST['owner']) .'",
- dev_DeviceType = "'. quotes($_REQUEST['type']) .'",
- dev_Vendor = "'. quotes($_REQUEST['vendor']) .'",
- dev_Favorite = "'. quotes($_REQUEST['favorite']) .'",
- dev_Group = "'. quotes($_REQUEST['group']) .'",
- dev_Location = "'. quotes($_REQUEST['location']) .'",
- dev_Comments = "'. quotes($_REQUEST['comments']) .'",
- dev_Infrastructure = "'. quotes($_REQUEST['networknode']).'",
- dev_Infrastructure_port = "'. quotes($_REQUEST['networknodeport']).'",
- dev_StaticIP = "'. quotes($_REQUEST['staticIP']) .'",
- dev_ScanCycle = "'. quotes($_REQUEST['scancycle']) .'",
- dev_AlertEvents = "'. quotes($_REQUEST['alertevents']) .'",
- dev_AlertDeviceDown = "'. quotes($_REQUEST['alertdown']) .'",
- dev_SkipRepeated = "'. quotes($_REQUEST['skiprepeated']) .'",
- dev_NewDevice = "'. quotes($_REQUEST['newdevice']) .'",
- dev_Archived = "'. quotes($_REQUEST['archived']) .'"
+ dev_Name = "'. quotes($_REQUEST['name']) .'",
+ dev_Owner = "'. quotes($_REQUEST['owner']) .'",
+ dev_DeviceType = "'. quotes($_REQUEST['type']) .'",
+ dev_Vendor = "'. quotes($_REQUEST['vendor']) .'",
+ dev_Favorite = "'. quotes($_REQUEST['favorite']) .'",
+ dev_Group = "'. quotes($_REQUEST['group']) .'",
+ dev_Location = "'. quotes($_REQUEST['location']) .'",
+ dev_Comments = "'. quotes($_REQUEST['comments']) .'",
+ dev_Network_Node_MAC_ADDR = "'. quotes($_REQUEST['networknode']).'",
+ dev_Network_Node_port = "'. quotes($_REQUEST['networknodeport']).'",
+ dev_StaticIP = "'. quotes($_REQUEST['staticIP']) .'",
+ dev_ScanCycle = "'. quotes($_REQUEST['scancycle']) .'",
+ dev_AlertEvents = "'. quotes($_REQUEST['alertevents']) .'",
+ dev_AlertDeviceDown = "'. quotes($_REQUEST['alertdown']) .'",
+ dev_SkipRepeated = "'. quotes($_REQUEST['skiprepeated']) .'",
+ dev_NewDevice = "'. quotes($_REQUEST['newdevice']) .'",
+ dev_Archived = "'. quotes($_REQUEST['archived']) .'"
WHERE dev_MAC="' . $_REQUEST['mac'] .'"';
// update Data
$result = $db->query($sql);
@@ -299,6 +311,26 @@ function deleteEvents() {
}
}
+//------------------------------------------------------------------------------
+// Delete all Events older than 30 days
+//------------------------------------------------------------------------------
+function deleteEvents30() {
+ global $db;
+ global $pia_lang;
+
+ // sql
+ $sql = "DELETE FROM Events WHERE eve_DateTime <= date('now', '-30 day')";
+ // execute sql
+ $result = $db->query($sql);
+
+ // check result
+ if ($result == TRUE) {
+ echo $pia_lang['BackDevices_DBTools_DelEvents'];
+ } else {
+ echo $pia_lang['BackDevices_DBTools_DelEventsError']."\n\n$sql \n\n". $db->lastErrorMsg();
+ }
+}
+
//------------------------------------------------------------------------------
// Delete History
//------------------------------------------------------------------------------
@@ -407,6 +439,120 @@ function PiaPurgeDBBackups() {
}
+//------------------------------------------------------------------------------
+// Export CSV of devices
+//------------------------------------------------------------------------------
+function ExportCSV() {
+
+ header("Content-Type: application/octet-stream");
+ header("Content-Transfer-Encoding: Binary");
+ header("Content-disposition: attachment; filename=\"devices.csv\"");
+
+ global $db;
+ $func_result = $db->query("SELECT * FROM Devices");
+
+ // prepare CSV header row
+ // header array with column names
+ $columns = getDevicesColumns();
+
+ // wrap the headers with " (quotes)
+ $resultCSV = '"'.implode('","', $columns).'"';
+
+ //and append a new line
+ $resultCSV = $resultCSV."\n";
+
+ // retrieve the devices from the DB
+ while ($row = $func_result -> fetchArray (SQLITE3_ASSOC)) {
+
+ // loop through columns and add values to the string
+ $index = 0;
+ foreach ($columns as $columnName) {
+
+ // add quotes around the value to prevent issues with commas in fields
+ $resultCSV = $resultCSV.'"'.$row[$columnName].'"';
+
+ // detect last loop - skip as no comma needed
+ if ($index != count($columns) - 1 )
+ {
+ $resultCSV = $resultCSV.',';
+ }
+ $index++;
+ }
+
+ //$resultCSV = $resultCSV.implode(",", [$row["dev_MAC"], $row["dev_Name"]]);
+ $resultCSV = $resultCSV."\n";
+ }
+
+ //write the built CSV string
+ echo $resultCSV;
+}
+
+//------------------------------------------------------------------------------
+// Import CSV of devices
+//------------------------------------------------------------------------------
+function ImportCSV() {
+
+
+ $file = '../../../config/devices.csv';
+
+ if (file_exists($file)) {
+
+ global $db;
+ global $pia_lang;
+
+ $error = "";
+
+ // sql
+ $sql = 'DELETE FROM Devices';
+ // execute sql
+ $result = $db->query($sql);
+
+ // Open the CSV file with read-only mode
+ $csvFile = fopen($file, 'r');
+
+ // Skip the first line
+ fgetcsv($csvFile);
+
+ $columns = getDevicesColumns();
+
+ // Parse data from CSV file line by line (max 10000 lines)
+ while (($row = fgetcsv($csvFile, 10000, ",")) !== FALSE)
+ {
+ $sql = 'INSERT INTO Devices ('.implode(',', $columns).') VALUES ("' .implode('","', $row).'")';
+
+ $result = $db->query($sql);
+
+ // check result
+ if ($result != TRUE) {
+ $error = $db->lastErrorMsg();
+ // break the while loop on error
+ break;
+ }
+ }
+
+ // Close opened CSV file
+ fclose($csvFile);
+
+ if($error == "")
+ {
+ // import succesful
+ echo $pia_lang['BackDevices_DBTools_ImportCSV'];
+
+ }
+ else{
+ // an error occurred while writing to the DB, display the last error message
+ echo $pia_lang['BackDevices_DBTools_ImportCSVError']."\n\n$sql \n\n".$error;
+ }
+
+ } else {
+ echo $pia_lang['BackDevices_DBTools_ImportCSVMissing'];
+ }
+
+
+ $db->close();
+
+}
+
//------------------------------------------------------------------------------
// Toggle Dark/Light Themes
//------------------------------------------------------------------------------
@@ -448,22 +594,35 @@ function PiaToggleArpScan() {
// Query total numbers of Devices by status
//------------------------------------------------------------------------------
function getDevicesTotals() {
- global $db;
- // combined query
- $result = $db->query(
- 'SELECT
- (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('all').') as devices,
- (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('connected').') as connected,
- (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('favorites').') as favorites,
- (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('new').') as new,
- (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('down').') as down,
- (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('archived').') as archived
- ');
+ $resultJSON = "";
- $row = $result -> fetchArray (SQLITE3_NUM);
+ if(getCache("getDevicesTotals") != "")
+ {
+ $resultJSON = getCache("getDevicesTotals");
+ } else
+ {
+ global $db;
- echo (json_encode (array ($row[0], $row[1], $row[2], $row[3], $row[4], $row[5])));
+ // combined query
+ $result = $db->query(
+ 'SELECT
+ (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('all').') as devices,
+ (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('connected').') as connected,
+ (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('favorites').') as favorites,
+ (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('new').') as new,
+ (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('down').') as down,
+ (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('archived').') as archived
+ ');
+
+ $row = $result -> fetchArray (SQLITE3_NUM);
+ $resultJSON = json_encode (array ($row[0], $row[1], $row[2], $row[3], $row[4], $row[5]));
+
+ // save to cache
+ setCache("getDevicesTotals", $resultJSON );
+ }
+
+ echo ($resultJSON);
}
@@ -574,12 +733,43 @@ function getOwners() {
}
+//------------------------------------------------------------------------------
+// Query Device Data
+//------------------------------------------------------------------------------
+function getNetworkNodes() {
+ global $db;
+
+ // Device Data
+ $sql = 'SELECT * FROM Devices WHERE dev_DeviceType in ( "AP", "Gateway", "Powerline", "Switch", "WLAN", "PLC", "Router","USB LAN Adapter", "USB WIFI Adapter")';
+
+ $result = $db->query($sql);
+
+ // arrays of rows
+ $tableData = array();
+ while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
+ // Push row data
+ $tableData[] = array('id' => $row['dev_MAC'],
+ 'name' => $row['dev_Name'] );
+ }
+
+ // Control no rows
+ if (empty($tableData)) {
+ $tableData = [];
+ }
+
+ // Return json
+ echo (json_encode ($tableData));
+}
+
+
//------------------------------------------------------------------------------
// Query the List of types
//------------------------------------------------------------------------------
function getDeviceTypes() {
global $db;
+ $networkTypes = getNetworkTypes();
+
// SQL
$sql = 'SELECT DISTINCT 9 as dev_Order, dev_DeviceType
FROM Devices
@@ -588,7 +778,7 @@ function getDeviceTypes() {
"Laptop", "Mini PC", "PC", "Printer", "Server", "Singleboard Computer (SBC)",
"Game Console", "SmartTV", "TV Decoder", "Virtual Assistance",
"Clock", "House Appliance", "Phone", "Radio",
- "AP", "NAS", "PLC", "Router")
+ "AP", "Gateway", "Powerline", "Switch", "WLAN", "PLC", "Router","USB LAN Adapter", "USB WIFI Adapter" )
UNION SELECT 1 as dev_Order, "Smartphone"
UNION SELECT 1 as dev_Order, "Tablet"
@@ -599,6 +789,7 @@ function getDeviceTypes() {
UNION SELECT 2 as dev_Order, "Printer"
UNION SELECT 2 as dev_Order, "Server"
UNION SELECT 2 as dev_Order, "Singleboard Computer (SBC)"
+ UNION SELECT 2 as dev_Order, "NAS"
UNION SELECT 3 as dev_Order, "Domotic"
UNION SELECT 3 as dev_Order, "Game Console"
@@ -611,8 +802,12 @@ function getDeviceTypes() {
UNION SELECT 4 as dev_Order, "Phone"
UNION SELECT 4 as dev_Order, "Radio"
+ -- network devices
UNION SELECT 5 as dev_Order, "AP"
- UNION SELECT 5 as dev_Order, "NAS"
+ UNION SELECT 5 as dev_Order, "Gateway"
+ UNION SELECT 5 as dev_Order, "Powerline"
+ UNION SELECT 5 as dev_Order, "Switch"
+ UNION SELECT 5 as dev_Order, "WLAN"
UNION SELECT 5 as dev_Order, "PLC"
UNION SELECT 5 as dev_Order, "Router"
UNION SELECT 5 as dev_Order, "USB LAN Adapter"
@@ -621,6 +816,8 @@ function getDeviceTypes() {
UNION SELECT 10 as dev_Order, "Other"
ORDER BY 1,2';
+
+
$result = $db->query($sql);
// arrays of rows
@@ -633,8 +830,6 @@ function getDeviceTypes() {
// Return json
echo (json_encode ($tableData));
}
-
-
//------------------------------------------------------------------------------
// Query the List of groups
//------------------------------------------------------------------------------
@@ -761,4 +956,5 @@ function getDeviceCondition ($deviceStatus) {
}
}
+
?>
diff --git a/front/php/server/events.php b/front/php/server/events.php
index 60e79478..b5450543 100644
--- a/front/php/server/events.php
+++ b/front/php/server/events.php
@@ -7,7 +7,13 @@
//------------------------------------------------------------------------------
// Puche 2021 pi.alert.application@gmail.com GNU GPLv3
//------------------------------------------------------------------------------
-
+// ## TimeZone processing
+$config_file = "../../../config/pialert.conf";
+$config_file_lines = file($config_file);
+$config_file_lines_timezone = array_values(preg_grep('/^TIMEZONE\s.*/', $config_file_lines));
+$timezone_line = explode("'", $config_file_lines_timezone[0]);
+$Pia_TimeZone = $timezone_line[1];
+date_default_timezone_set($Pia_TimeZone);
//------------------------------------------------------------------------------
// External files
@@ -46,51 +52,57 @@ function getEventsTotals() {
global $db;
// Request Parameters
- $periodDate = getDateFromPeriod();
+ $periodDate = $_REQUEST['period'];
- // SQL
- $SQL1 = 'SELECT Count(*)
- FROM Events
- WHERE eve_DateTime >= '. $periodDate;
-
- $SQL2 = 'SELECT Count(*)
- FROM Sessions ';
+ $periodDateSQL = "";
+ $days = "";
- // All
- $result = $db->query($SQL1);
- $row = $result -> fetchArray (SQLITE3_NUM);
- $eventsAll = $row[0];
+ switch ($periodDate) {
+ case '7 days':
+ $days = "7";
+ break;
+ case '1 month':
+ $days = "30";
+ break;
+ case '1 year':
+ $days = "365";
+ break;
+ case '100 years':
+ $days = "3650"; //10 years
+ break;
+ default:
+ $days = "1";
+ }
- // Sessions
- $result = $db->query($SQL2. ' WHERE ( ses_DateTimeConnection >= '. $periodDate .'
- OR ses_DateTimeDisconnection >= '. $periodDate .'
- OR ses_StillConnected = 1 ) ');
- $row = $result -> fetchArray (SQLITE3_NUM);
- $eventsSessions = $row[0];
+ $periodDateSQL = "-".$days." day";
- // Missing
- $result = $db->query($SQL2. ' WHERE (ses_DateTimeConnection IS NULL AND ses_DateTimeDisconnection >= '. $periodDate .' )
- OR (ses_DateTimeDisconnection IS NULL AND ses_StillConnected = 0 AND ses_DateTimeConnection >= '. $periodDate .' )' );
- $row = $result -> fetchArray (SQLITE3_NUM);
- $eventsMissing = $row[0];
+ $resultJSON = "";
- // Voided
- $result = $db->query($SQL1. ' AND eve_EventType LIKE "VOIDED%" ');
- $row = $result -> fetchArray (SQLITE3_NUM);
- $eventsVoided = $row[0];
+ // check cache if JSON available in a cookie
+ if(getCache("getEventsTotals".$days) != "")
+ {
+ $resultJSON = getCache("getEventsTotals".$days);
+ } else
+ {
+ // one query to get all numbers, whcih is quicker than multiple queries
+ $sql = "select
+ (SELECT Count(*) FROM Events WHERE eve_DateTime >= date('now', '".$periodDateSQL."')) as all_events,
+ (SELECT Count(*) FROM Sessions as sessions WHERE ( ses_DateTimeConnection >= date('now', '".$periodDateSQL."') OR ses_DateTimeDisconnection >= date('now', '".$periodDateSQL."') OR ses_StillConnected = 1 )) as sessions,
+ (SELECT Count(*) FROM Sessions WHERE ((ses_DateTimeConnection IS NULL AND ses_DateTimeDisconnection >= date('now', '".$periodDateSQL."' )) OR (ses_DateTimeDisconnection IS NULL AND ses_StillConnected = 0 AND ses_DateTimeConnection >= date('now', '".$periodDateSQL."' )))) as missing,
+ (SELECT Count(*) FROM Events WHERE eve_DateTime >= date('now', '".$periodDateSQL."') AND eve_EventType LIKE 'VOIDED%' ) as voided,
+ (SELECT Count(*) FROM Events WHERE eve_DateTime >= date('now', '".$periodDateSQL."') AND eve_EventType LIKE 'New Device' ) as new,
+ (SELECT Count(*) FROM Events WHERE eve_DateTime >= date('now', '".$periodDateSQL."') AND eve_EventType LIKE 'Device Down' ) as down";
- // New
- $result = $db->query($SQL1. ' AND eve_EventType LIKE "New Device" ');
- $row = $result -> fetchArray (SQLITE3_NUM);
- $eventsNew = $row[0];
+ $result = $db->query($sql);
+ $row = $result -> fetchArray (SQLITE3_NUM);
+ $resultJSON = json_encode (array ($row[0], $row[1], $row[2], $row[3], $row[4], $row[5]));
- // Down
- $result = $db->query($SQL1. ' AND eve_EventType LIKE "Device Down" ');
- $row = $result -> fetchArray (SQLITE3_NUM);
- $eventsDown = $row[0];
-
- // Return json
- echo (json_encode (array ($eventsAll, $eventsSessions, $eventsMissing, $eventsVoided, $eventsNew, $eventsDown)));
+ // save JSON result to cache
+ setCache("getEventsTotals".$days, $resultJSON );
+ }
+
+ // Return json
+ echo ($resultJSON);
}
@@ -217,15 +229,15 @@ function getDeviceSessions() {
// Disconnection DateTime
if ($row['ses_StillConnected'] == true) {
- $end = '...';
+ $end = '...';
} elseif ($row['ses_EventTypeDisconnection'] == '
') {
- $end = $row['ses_EventTypeDisconnection'];
+ $end = $row['ses_EventTypeDisconnection'];
} else {
$end = formatDate ($row['ses_DateTimeDisconnection']);
}
// Duration
- if ($row['ses_EventTypeConnection'] == '' || $row['ses_EventTypeDisconnection'] == '') {
+ if ($row['ses_EventTypeConnection'] == '' || $row['ses_EventTypeConnection'] == NULL || $row['ses_EventTypeDisconnection'] == '' || $row['ses_EventTypeDisconnection'] == NULL) {
$dur = '...';
} elseif ($row['ses_StillConnected'] == true) {
$dur = formatDateDiff ($row['ses_DateTimeConnection'], ''); //***********
@@ -261,7 +273,6 @@ function getDevicePresence() {
// Request Parameters
$mac = $_REQUEST['mac'];
- $periodDate = getDateFromPeriod();
$startDate = '"'. formatDateISO ($_REQUEST ['start']) .'"';
$endDate = '"'. formatDateISO ($_REQUEST ['end']) .'"';
@@ -276,7 +287,7 @@ function getDevicePresence() {
END AS ses_DateTimeConnectionCorrected,
CASE
- WHEN ses_EventTypeDisconnection = "" THEN
+ WHEN ses_EventTypeDisconnection = "" OR ses_EventTypeDisconnection = NULL THEN
(SELECT MIN(ses_DateTimeConnection) FROM Sessions AS SES2 WHERE SES2.ses_MAC = SES1.ses_MAC AND SES2.ses_DateTimeConnection > SES1.ses_DateTimeConnection)
ELSE ses_DateTimeDisconnection
END AS ses_DateTimeDisconnectionCorrected
@@ -290,13 +301,14 @@ function getDevicePresence() {
// arrays of rows
while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
// Event color
- if ($row['ses_EventTypeConnection'] == '' || $row['ses_EventTypeDisconnection'] == '') {
- $color = '#f39c12';
- } elseif ($row['ses_StillConnected'] == 1 ) {
- $color = '#00a659';
- } else {
- $color = '#0073b7';
- }
+ if ($row['ses_EventTypeConnection'] == '' || $row['ses_EventTypeDisconnection'] == '') {
+ $color = '#f39c12';
+ } elseif ($row['ses_StillConnected'] == 1 ) {
+ $color = '#00a659';
+ } else {
+ $color = '#0073b7';
+ }
+
// tooltip
$tooltip = 'Connection: ' . formatEventDate ($row['ses_DateTimeConnection'], $row['ses_EventTypeConnection']) . chr(13) .
@@ -333,7 +345,7 @@ function getEventsCalendar() {
$startDate = '"'. $_REQUEST ['start'] .'"';
$endDate = '"'. $_REQUEST ['end'] .'"';
- // SQL
+ // SQL
$SQL = 'SELECT ses_MAC, ses_EventTypeConnection, ses_DateTimeConnection,
ses_EventTypeDisconnection, ses_DateTimeDisconnection, ses_IP, ses_AdditionalInfo, ses_StillConnected,
@@ -358,12 +370,12 @@ function getEventsCalendar() {
while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
// Event color
if ($row['ses_EventTypeConnection'] == '' || $row['ses_EventTypeDisconnection'] == '') {
- $color = '#f39c12';
- } elseif ($row['ses_StillConnected'] == 1 ) {
- $color = '#00a659';
- } else {
- $color = '#0073b7';
- }
+ $color = '#f39c12';
+ } elseif ($row['ses_StillConnected'] == 1 ) {
+ $color = '#00a659';
+ } else {
+ $color = '#0073b7';
+ }
// tooltip
$tooltip = 'Connection: ' . formatEventDate ($row['ses_DateTimeConnection'], $row['ses_EventTypeConnection']) . chr(13) .
diff --git a/front/php/server/util.php b/front/php/server/util.php
index a4f345f3..58e75f4f 100644
--- a/front/php/server/util.php
+++ b/front/php/server/util.php
@@ -8,6 +8,13 @@
// Puche 2021 pi.alert.application@gmail.com GNU GPLv3
//------------------------------------------------------------------------------
+// ## TimeZone processing
+$config_file = "../../../config/pialert.conf";
+$config_file_lines = file($config_file);
+$config_file_lines_timezone = array_values(preg_grep('/^TIMEZONE\s.*/', $config_file_lines));
+$timezone_line = explode("'", $config_file_lines_timezone[0]);
+$Pia_TimeZone = $timezone_line[1];
+date_default_timezone_set($Pia_TimeZone);
//------------------------------------------------------------------------------
// Formatting data functions
@@ -58,4 +65,62 @@ function logServerConsole ($text) {
$y = $x['__________'. $text .'__________'];
}
+function getNetworkTypes(){
+
+ $array = array(
+ "AP", "Gateway", "Powerline", "Switch", "WLAN", "PLC", "Router","USB LAN Adapter", "USB WIFI Adapter"
+ );
+
+ return $array;
+}
+
+function getDevicesColumns(){
+
+ $columns = ["dev_MAC",
+ "dev_Name",
+ "dev_Owner",
+ "dev_DeviceType",
+ "dev_Vendor",
+ "dev_Favorite",
+ "dev_Group",
+ "dev_Comments",
+ "dev_FirstConnection",
+ "dev_LastConnection",
+ "dev_LastIP",
+ "dev_StaticIP",
+ "dev_ScanCycle",
+ "dev_LogEvents",
+ "dev_AlertEvents",
+ "dev_AlertDeviceDown",
+ "dev_SkipRepeated",
+ "dev_LastNotification",
+ "dev_PresentLastScan",
+ "dev_NewDevice",
+ "dev_Location",
+ "dev_Archived",
+ "dev_Network_Node_port",
+ "dev_Network_Node_MAC_ADDR"];
+
+ return $columns;
+}
+
+//------------------------------------------------------------------------------
+// Simple cookie cache
+//------------------------------------------------------------------------------
+function getCache($key) {
+ if( isset($_COOKIE[$key]))
+ {
+ return $_COOKIE[$key];
+ }else
+ {
+ return "";
+ }
+}
+
+function setCache($key, $value) {
+ setcookie($key, $value, time()+300, "/","", 0); // 5min cache
+}
+
+
+
?>
diff --git a/front/php/templates/graph.php b/front/php/templates/graph.php
index 3765820e..8b1a9751 100644
--- a/front/php/templates/graph.php
+++ b/front/php/templates/graph.php
@@ -1,10 +1,16 @@
query('SELECT * FROM Online_History ORDER BY Scan_Date DESC LIMIT 144');
while ($row = $results->fetchArray()) {
$time_raw = explode(' ', $row['Scan_Date']);
@@ -23,4 +29,5 @@ function pia_graph_devices_data($Pia_Graph_Array) {
}
}
$db->close();
+
?>
\ No newline at end of file
diff --git a/front/php/templates/header.php b/front/php/templates/header.php
index 064bf4d6..113764d9 100644
--- a/front/php/templates/header.php
+++ b/front/php/templates/header.php
@@ -88,6 +88,7 @@ if ($ENABLED_DARKMODE === True) {
?>