Front 2.50

This commit is contained in:
pucherot
2021-01-05 12:20:13 +01:00
parent 27cddc00c7
commit c6f11a428c
19 changed files with 4048 additions and 0 deletions

52
front/php/server/db.php Normal file
View File

@@ -0,0 +1,52 @@
<?php
//------------------------------------------------------------------------------
// PHP Open DB
//------------------------------------------------------------------------------
// DB File Path
$DBFILE = 'pialert.db';
//------------------------------------------------------------------------------
// Connect DB
//------------------------------------------------------------------------------
function SQLite3_connect ($trytoreconnect) {
global $DBFILE;
try
{
// connect to database
// return new SQLite3($DBFILE, SQLITE3_OPEN_READONLY);
return new SQLite3($DBFILE, SQLITE3_OPEN_READWRITE);
}
catch (Exception $exception)
{
// sqlite3 throws an exception when it is unable to connect
// try to reconnect one time after 3 seconds
if($trytoreconnect)
{
sleep(3);
return SQLite3_connect(false);
}
}
}
//------------------------------------------------------------------------------
// Open DB
//------------------------------------------------------------------------------
function OpenDB () {
global $DBFILE;
global $db;
if(strlen($DBFILE) == 0)
{
die ('No database available');
}
$db = SQLite3_connect(true);
if(!$db)
{
die ('Error connecting to database');
}
}
?>

View File

@@ -0,0 +1,377 @@
<?php
// External files
require 'db.php';
require 'util.php';
//------------------------------------------------------------------------------
// Action selector
//------------------------------------------------------------------------------
// Set maximum execution time to 1 minute
ini_set ('max_execution_time','60');
// Open DB
OpenDB();
// Action functions
if (isset ($_REQUEST['action']) && !empty ($_REQUEST['action'])) {
$action = $_REQUEST['action'];
switch ($action) {
case 'totals': queryTotals(); break;
case 'list': queryList(); break;
case 'queryDeviceData': queryDeviceData(); break;
case 'updateData': updateDeviceData(); break;
case 'calendar': queryCalendarList(); break;
case 'queryOwners': queryOwners(); break;
case 'queryDeviceTypes': queryDeviceTypes(); break;
case 'queryGroups': queryGroups(); break;
default: logServerConsole ('Action: '. $action); break;
}
}
//------------------------------------------------------------------------------
// Query total numbers of Devices by status
//------------------------------------------------------------------------------
function queryTotals() {
global $db;
// All
$result = $db->query('SELECT COUNT(*) FROM Devices ');
$row = $result -> fetchArray (SQLITE3_NUM);
$devices = $row[0];
// Connected
$result = $db->query('SELECT COUNT(*) FROM Devices ' . getDeviceCondition ('connected') );
$row = $result -> fetchArray (SQLITE3_NUM);
$connected = $row[0];
// New
$result = $db->query('SELECT COUNT(*) FROM Devices ' . getDeviceCondition ('new') );
$row = $result -> fetchArray (SQLITE3_NUM);
$newDevices = $row[0];
// Down Alerts
$result = $db->query('SELECT COUNT(*) FROM Devices ' . getDeviceCondition ('down'));
$row = $result -> fetchArray (SQLITE3_NUM);
$devicesDownAlert = $row[0];
echo (json_encode (array ($devices, $connected, $newDevices, $devicesDownAlert)));
}
//------------------------------------------------------------------------------
// Query the List of devices in a determined Status
//------------------------------------------------------------------------------
function queryList() {
global $db;
// Request Parameters
$periodDate = getDateFromPeriod();
// SQL
$condition = getDeviceCondition ($_REQUEST['status']);
$result = $db->query('SELECT *,
CASE WHEN dev_AlertDeviceDown=1 AND dev_PresentLastScan=0 THEN "Down"
WHEN dev_FirstConnection >= ' . $periodDate . ' THEN "New"
WHEN dev_PresentLastScan=1 THEN "On-line"
ELSE "Off-line"
END AS dev_Status
FROM Devices ' . $condition);
// arrays of rows
$tableData = array();
while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
$tableData['data'][] = array ($row['dev_Name'],
$row['dev_Owner'],
$row['dev_DeviceType'],
$row['dev_Favorite'],
$row['dev_Group'],
formatDate ($row['dev_FirstConnection']),
formatDate ($row['dev_LastConnection']),
$row['dev_LastIP'],
$row['dev_Status'],
$row['dev_MAC'], // MAC (hidden)
formatIPlong ($row['dev_LastIP']) // IP orderable
);
}
// Control no rows
if (empty($tableData['data'])) {
$tableData['data'] = '';
}
// Return json
echo (json_encode ($tableData));
}
//------------------------------------------------------------------------------
// Query the List of Owners
//------------------------------------------------------------------------------
function queryOwners() {
global $db;
// SQL
$result = $db->query('SELECT DISTINCT 1 as dev_Order, dev_Owner
FROM Devices
WHERE dev_Owner <> "(unknown)" AND dev_Owner <> ""
AND dev_Favorite = 1
UNION
SELECT DISTINCT 2 as dev_Order, dev_Owner
FROM Devices
WHERE dev_Owner <> "(unknown)" AND dev_Owner <> ""
AND dev_Favorite = 0
AND dev_Owner NOT IN (SELECT dev_Owner FROM Devices WHERE dev_Favorite = 1)
ORDER BY 1,2 ');
// arrays of rows
$tableData = array();
while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
$tableData[] = array ('order' => $row['dev_Order'],
'name' => $row['dev_Owner']);
}
// Return json
echo (json_encode ($tableData));
}
//------------------------------------------------------------------------------
// Query the List of types
//------------------------------------------------------------------------------
function queryDeviceTypes() {
global $db;
// SQL
$result = $db->query('SELECT DISTINCT 9 as dev_Order, dev_DeviceType
FROM Devices
WHERE dev_DeviceType NOT IN ("",
"Smartphone", "Tablet",
"Laptop", "Mini PC", "PC", "Printer", "Server",
"Game Console", "SmartTV", "TV Decoder", "Virtual Assistance",
"Clock", "House Appliance", "Phone", "Radio",
"AP", "NAS", "PLC", "Router")
UNION SELECT 1 as dev_Order, "Smartphone"
UNION SELECT 1 as dev_Order, "Tablet"
UNION SELECT 2 as dev_Order, "Laptop"
UNION SELECT 2 as dev_Order, "Mini PC"
UNION SELECT 2 as dev_Order, "PC"
UNION SELECT 2 as dev_Order, "Printer"
UNION SELECT 2 as dev_Order, "Server"
UNION SELECT 3 as dev_Order, "Game Console"
UNION SELECT 3 as dev_Order, "SmartTV"
UNION SELECT 3 as dev_Order, "TV Decoder"
UNION SELECT 3 as dev_Order, "Virtual Assistance"
UNION SELECT 4 as dev_Order, "Clock"
UNION SELECT 4 as dev_Order, "House Appliance"
UNION SELECT 4 as dev_Order, "Phone"
UNION SELECT 4 as dev_Order, "Radio"
UNION SELECT 5 as dev_Order, "AP"
UNION SELECT 5 as dev_Order, "NAS"
UNION SELECT 5 as dev_Order, "PLC"
UNION SELECT 5 as dev_Order, "Router"
UNION SELECT 10 as dev_Order, "Other"
ORDER BY 1,2 ');
// arrays of rows
$tableData = array();
while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
$tableData[] = array ('order' => $row['dev_Order'],
'name' => $row['dev_DeviceType']);
}
// Return json
echo (json_encode ($tableData));
}
//------------------------------------------------------------------------------
// Query the List of groups
//------------------------------------------------------------------------------
function queryGroups() {
global $db;
// SQL
$result = $db->query('SELECT DISTINCT 1 as dev_Order, dev_Group
FROM Devices
WHERE dev_Group <> "(unknown)" AND dev_Group <> "Others" AND dev_Group <> ""
UNION SELECT 1 as dev_Order, "Always on"
UNION SELECT 1 as dev_Order, "Friends"
UNION SELECT 1 as dev_Order, "Personal"
UNION SELECT 2 as dev_Order, "Others"
ORDER BY 1,2 ');
// arrays of rows
$tableData = array();
while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
$tableData[] = array ('order' => $row['dev_Order'],
'name' => $row['dev_Group']);
}
// Return json
echo (json_encode ($tableData));
}
//------------------------------------------------------------------------------
// Query the List of devices for calendar
//------------------------------------------------------------------------------
function queryCalendarList() {
global $db;
// Request Parameters
$periodDate = getDateFromPeriod();
// SQL
$condition = getDeviceCondition ($_REQUEST['status']);
$result = $db->query('SELECT * FROM Devices ' . $condition);
// arrays of rows
$tableData = array();
while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
if ($row['dev_Favorite'] == 1) {
$row['dev_Name'] = '<span class="text-yellow">&#9733</span>&nbsp'. $row['dev_Name'];
}
$tableData[] = array ('id' => $row['dev_MAC'],
'title' => $row['dev_Name'],
'favorite' => $row['dev_Favorite']);
}
// Return json
echo (json_encode ($tableData));
}
//------------------------------------------------------------------------------
// Query Device Data
//------------------------------------------------------------------------------
function queryDeviceData() {
global $db;
// Request Parameters
$periodDate = getDateFromPeriod();
$mac = $_REQUEST['mac'];
// Device Data
$result = $db->query('SELECT *,
CASE WHEN dev_AlertDeviceDown=1 AND dev_PresentLastScan=0 THEN "Down"
WHEN dev_PresentLastScan=1 THEN "On-line"
ELSE "Off-line" END as dev_Status
FROM Devices
WHERE dev_MAC="' . $mac .'"');
$row = $result -> fetchArray (SQLITE3_ASSOC);
$deviceData = $row;
$deviceData['dev_FirstConnection'] = formatDate ($row['dev_FirstConnection']); // Date formated
$deviceData['dev_LastConnection'] = formatDate ($row['dev_LastConnection']); // Date formated
// Count Totals
$condicion = ' WHERE eve_MAC="' . $mac .'" AND eve_DateTime >= ' . $periodDate;
// Connections
$result = $db->query('SELECT COUNT(*) FROM Sessions
WHERE ses_MAC="' . $mac .'"
AND ( ses_DateTimeConnection >= ' . $periodDate . '
OR ses_DateTimeDisconnection >= ' . $periodDate . '
OR ses_StillConnected = 1 ) ');
$row = $result -> fetchArray (SQLITE3_NUM);
$deviceData['dev_Sessions'] = $row[0];
// Events
$result = $db->query('SELECT COUNT(*) FROM Events ' . $condicion . ' AND eve_EventType <> "Connected" AND eve_EventType <> "Disconnected" ');
$row = $result -> fetchArray (SQLITE3_NUM);
$deviceData['dev_Events'] = $row[0];
// Donw Alerts
$result = $db->query('SELECT COUNT(*) FROM Events ' . $condicion . ' AND eve_EventType = "Device Down"');
$row = $result -> fetchArray (SQLITE3_NUM);
$deviceData['dev_DownAlerts'] = $row[0];
// Presence hours
$result = $db->query('SELECT SUM (julianday (IFNULL (ses_DateTimeDisconnection, DATETIME("now")))
- julianday (CASE WHEN ses_DateTimeConnection < ' . $periodDate . ' THEN ' . $periodDate . '
ELSE ses_DateTimeConnection END)) *24
FROM Sessions
WHERE ses_MAC="' . $mac .'"
AND ses_DateTimeConnection IS NOT NULL
AND (ses_DateTimeDisconnection IS NOT NULL OR ses_StillConnected = 1 )
AND ( ses_DateTimeConnection >= ' . $periodDate . '
OR ses_DateTimeDisconnection >= ' . $periodDate . '
OR ses_StillConnected = 1 ) ');
$row = $result -> fetchArray (SQLITE3_NUM);
$deviceData['dev_PresenceHours'] = round ($row[0]);
// Return json
echo (json_encode ($deviceData));
}
//------------------------------------------------------------------------------
// Status Where conditions
//------------------------------------------------------------------------------
function getDeviceCondition ($deviceStatus) {
// Request Parameters
$periodDate = getDateFromPeriod();
switch ($deviceStatus) {
case 'all':
return '';
case 'connected':
return 'WHERE dev_PresentLastScan=1';
case 'new':
return 'WHERE dev_FirstConnection >= ' . $periodDate;
case 'down':
return 'WHERE dev_AlertDeviceDown=1 AND dev_PresentLastScan=0';
case 'favorites':
return 'WHERE dev_Favorite=1';
default:
return 'WHERE 1=0';
}
}
//------------------------------------------------------------------------------
// Update Device Data
//------------------------------------------------------------------------------
function updateDeviceData() {
global $db;
// sql
$sql = 'UPDATE Devices SET
dev_Name = "'. $_REQUEST['name'] .'",
dev_Owner = "'. $_REQUEST['owner'] .'",
dev_DeviceType = "'. $_REQUEST['type'] .'",
dev_Vendor = "'. $_REQUEST['vendor'] .'",
dev_Favorite = "'. $_REQUEST['favorite'] .'",
dev_Group = "'. $_REQUEST['group'] .'",
dev_Comments = "'. $_REQUEST['comments'] .'",
dev_StaticIP = "'. $_REQUEST['staticIP'] .'",
dev_ScanCycle = "'. $_REQUEST['scancycle'] .'",
dev_AlertEvents = "'. $_REQUEST['alertevents'] .'",
dev_AlertDeviceDown = "'. $_REQUEST['alertdown'] .'",
dev_SkipRepeated = "'. $_REQUEST['skiprepeated'] .'"
WHERE dev_MAC="' . $_REQUEST['mac'] .'"';
// update Data
$result = $db->query($sql);
// check result
if ($result == TRUE) {
echo "Device updated successfully";
} else {
echo "Error updating device\n\n". $sql .'\n\n' . $db->lastErrorMsg();
}
}
?>

429
front/php/server/events.php Normal file
View File

@@ -0,0 +1,429 @@
<?php
// External files
require 'db.php';
require 'util.php';
//------------------------------------------------------------------------------
// Action selector
//------------------------------------------------------------------------------
// Set maximum execution time to 1 minute
ini_set ('max_execution_time','60');
// Open DB
OpenDB();
// Action functions
if (isset ($_REQUEST['action']) && !empty ($_REQUEST['action'])) {
$action = $_REQUEST['action'];
switch ($action) {
case 'totals': queryTotals(); break;
case 'list': queryList(); break;
case 'deviceSessions': queryDeviceSessions(); break;
case 'devicePresence': queryDevicePresence(); break;
case 'deviceEvents': queryDeviceEvents(); break;
case 'calendarPresence': queryCalendarPresence(); break;
default: logServerConsole ('Action: '. $action); break;
}
}
//------------------------------------------------------------------------------
// Query total numbers of Events
//------------------------------------------------------------------------------
function queryTotals() {
global $db;
// Request Parameters
$periodDate = getDateFromPeriod();
// SQL
$SQL1 = 'SELECT Count(*)
FROM Events
WHERE eve_DateTime >= '. $periodDate;
$SQL2 = 'SELECT Count(*)
FROM Sessions ';
// All
$result = $db->query($SQL1);
$row = $result -> fetchArray (SQLITE3_NUM);
$eventsAll = $row[0];
// 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];
// 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];
// Voided
$result = $db->query($SQL1. ' AND eve_EventType LIKE "VOIDED%" ');
$row = $result -> fetchArray (SQLITE3_NUM);
$eventsVoided = $row[0];
// New
$result = $db->query($SQL1. ' AND eve_EventType LIKE "New Device" ');
$row = $result -> fetchArray (SQLITE3_NUM);
$eventsNew = $row[0];
// 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)));
}
//------------------------------------------------------------------------------
// Query the List of events
//------------------------------------------------------------------------------
function queryList() {
global $db;
// Request Parameters
$type = $_REQUEST ['type'];
$periodDate = getDateFromPeriod();
// SQL
$SQL1 = 'SELECT eve_DateTime AS eve_DateTimeOrder, dev_name, dev_owner, eve_DateTime, eve_EventType, NULL, NULL, NULL, NULL, eve_IP, NULL, eve_AdditionalInfo, NULL, Dev_MAC
FROM Events_Devices
WHERE eve_DateTime >= '. $periodDate;
$SQL2 = 'SELECT IFNULL (ses_DateTimeConnection, ses_DateTimeDisconnection) ses_DateTimeOrder,
dev_name, dev_owner, Null, Null, ses_DateTimeConnection, ses_DateTimeDisconnection, NULL, NULL, ses_IP, NULL, ses_AdditionalInfo, ses_StillConnected, Dev_MAC
FROM Sessions_Devices ';
// SQL Variations for status
switch ($type) {
case 'all':
$SQL = $SQL1;
break;
case 'sessions':
$SQL = $SQL2 . ' WHERE ( ses_DateTimeConnection >= '. $periodDate .'
OR ses_DateTimeDisconnection >= '. $periodDate .'
OR ses_StillConnected = 1 ) ';
break;
case 'missing':
$SQL = $SQL2 . ' WHERE (ses_DateTimeConnection IS NULL AND ses_DateTimeDisconnection >= '. $periodDate .' )
OR (ses_DateTimeDisconnection IS NULL AND ses_StillConnected = 0 AND ses_DateTimeConnection >= '. $periodDate .' )';
break;
case 'voided':
$SQL = $SQL1 .' AND eve_EventType LIKE "VOIDED%" ';
break;
case 'new':
$SQL = $SQL1 .' AND eve_EventType = "New Device" ';
break;
case 'down':
$SQL = $SQL1 .' AND eve_EventType = "Device Down" ';
break;
default:
$SQL = $SQL1 .' AND 1==0 ';
break;
}
// Query
$result = $db->query($SQL);
$tableData = array();
while ($row = $result -> fetchArray (SQLITE3_NUM)) {
if ($type == 'sessions' || $type == 'missing' ) {
// Duration
if (!empty ($row[5]) && !empty($row[6]) ) {
$row[7] = formatDateDiff ($row[5], $row[6]);
$row[8] = abs(strtotime($row[6]) - strtotime($row[5]));
} elseif ($row[12] == 1) {
$row[7] = formatDateDiff ($row[5], '');
$row[8] = abs(strtotime("now") - strtotime($row[5]));
} else {
$row[7] = '...';
$row[8] = 0;
}
// Connection
if (!empty ($row[5]) ) {
$row[5] = formatDate ($row[5]);
} else {
$row[5] = '<missing event>';
}
// Disconnection
if (!empty ($row[6]) ) {
$row[6] = formatDate ($row[6]);
} elseif ($row[12] == 0) {
$row[6] = '<missing event>';
} else {
$row[6] = '...';
}
} else {
// Event Date
$row[3] = formatDate ($row[3]);
}
// IP Order
$row[10] = formatIPlong ($row[9]);
$tableData['data'][] = $row;
}
// Control no rows
if (empty($tableData['data'])) {
$tableData['data'] = '';
}
// Return json
echo (json_encode ($tableData));
}
//------------------------------------------------------------------------------
// Query Device Sessions
//------------------------------------------------------------------------------
function queryDeviceSessions() {
global $db;
// Request Parameters
$mac = $_REQUEST['mac'];
$periodDate = getDateFromPeriod();
// SQL
$result = $db->query('SELECT IFNULL (ses_DateTimeConnection, ses_DateTimeDisconnection) ses_DateTimeOrder,
ses_EventTypeConnection, ses_DateTimeConnection,
ses_EventTypeDisconnection, ses_DateTimeDisconnection, ses_StillConnected,
ses_IP, ses_AdditionalInfo
FROM Sessions
WHERE ses_MAC="' . $mac .'"
AND ( ses_DateTimeConnection >= '. $periodDate .'
OR ses_DateTimeDisconnection >= '. $periodDate .'
OR ses_StillConnected = 1 ) ');
// arrays of rows
$tableData = array();
while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
// Connection DateTime
if ($row['ses_EventTypeConnection'] == '<missing event>') {
$ini = $row['ses_EventTypeConnection'];
} else {
$ini = formatDate ($row['ses_DateTimeConnection']);
}
// Disconnection DateTime
if ($row['ses_StillConnected'] == true) {
$end = '...';
} elseif ($row['ses_EventTypeDisconnection'] == '<missing event>') {
$end = $row['ses_EventTypeDisconnection'];
} else {
$end = formatDate ($row['ses_DateTimeDisconnection']);
}
// Duration
if ($row['ses_EventTypeConnection'] == '<missing event>' || $row['ses_EventTypeDisconnection'] == '<missing event>') {
$dur = '...';
} elseif ($row['ses_StillConnected'] == true) {
$dur = formatDateDiff ($row['ses_DateTimeConnection'], ''); //*******************************************************************************************
} else {
$dur = formatDateDiff ($row['ses_DateTimeConnection'], $row['ses_DateTimeDisconnection']);
}
// Additional Info
$info = $row['ses_AdditionalInfo'];
if ($row['ses_EventTypeConnection'] == 'New Device' ) {
$info = $row['ses_EventTypeConnection'] .': '. $info;
}
// Push row data
$tableData['data'][] = array($row['ses_DateTimeOrder'], $ini, $end, $dur, $row['ses_IP'], $info);
}
// Control no rows
if (empty($tableData['data'])) {
$tableData['data'] = '';
}
// Return json
echo (json_encode ($tableData));
}
//------------------------------------------------------------------------------
// Query Device Presence Calendar
//------------------------------------------------------------------------------
function queryDevicePresence() {
global $db;
// Request Parameters
$mac = $_REQUEST['mac'];
$periodDate = getDateFromPeriod();
$startDate = '"'. formatDateISO ($_REQUEST ['start']) .'"';
$endDate = '"'. formatDateISO ($_REQUEST ['end']) .'"';
// SQL
$result = $db->query('SELECT ses_EventTypeConnection, ses_DateTimeConnection,
ses_EventTypeDisconnection, ses_DateTimeDisconnection, ses_IP, ses_AdditionalInfo,
CASE WHEN ses_EventTypeConnection = "<missing event>" THEN
IFNULL ((SELECT MAX(ses_DateTimeDisconnection) FROM Sessions AS SES2 WHERE SES2.ses_MAC = SES1.ses_MAC AND SES2.ses_DateTimeDisconnection < SES1.ses_DateTimeDisconnection), DATETIME(ses_DateTimeDisconnection, "-1 hour"))
ELSE ses_DateTimeConnection
END AS ses_DateTimeConnectionCorrected,
CASE WHEN ses_EventTypeDisconnection = "<missing event>" 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
FROM Sessions AS SES1
WHERE ses_MAC="' . $mac .'"
AND (ses_DateTimeConnectionCorrected <= date('. $endDate .')
AND (ses_DateTimeDisconnectionCorrected >= date('. $startDate .') OR ses_StillConnected = 1 ))
');
// arrays of rows
while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
// Event color
if ($row['ses_EventTypeConnection'] == '<missing event>' || $row['ses_EventTypeDisconnection'] == '<missing event>') {
$color = '#f39c12';
} else {
$color = '#0073b7';
}
// tooltip
$tooltip = 'Connection: ' . formatEventDate ($row['ses_DateTimeConnection'], $row['ses_EventTypeConnection']) . chr(13) .
'Disconnection: ' . formatEventDate ($row['ses_DateTimeDisconnection'], $row['ses_EventTypeDisconnection']) . chr(13) .
'IP: ' . $row['ses_IP'];
// Save row data
// 'start' => formatDateISO ($row['ses_DateTimeConnectionCorrected']),
// 'end' => formatDateISO ($row['ses_DateTimeDisconnectionCorrected']),
// 'start' => $row['ses_DateTimeConnectionCorrected'],
// 'end' => $row['ses_DateTimeDisconnectionCorrected'],
$tableData[] = array(
'title' => '',
'start' => formatDateISO ($row['ses_DateTimeConnectionCorrected']),
'end' => formatDateISO ($row['ses_DateTimeDisconnectionCorrected']),
'color' => $color,
'tooltip' => $tooltip
);
}
// Control no rows
if (empty($tableData)) {
$tableData = '';
}
// Return json
echo (json_encode($tableData));
}
//------------------------------------------------------------------------------
// Query Presence Calendar for all Devices
//------------------------------------------------------------------------------
function queryCalendarPresence() {
global $db;
// Request Parameters
$periodDate = getDateFromPeriod();
$startDate = '"'. $_REQUEST ['start'] .'"';
$endDate = '"'. $_REQUEST ['end'] .'"';
// SQL
$result = $db->query('SELECT ses_MAC, ses_EventTypeConnection, ses_DateTimeConnection,
ses_EventTypeDisconnection, ses_DateTimeDisconnection, ses_IP, ses_AdditionalInfo,
CASE WHEN ses_EventTypeConnection = "<missing event>" THEN
IFNULL ((SELECT MAX(ses_DateTimeDisconnection) FROM Sessions AS SES2 WHERE SES2.ses_MAC = SES1.ses_MAC AND SES2.ses_DateTimeDisconnection < SES1.ses_DateTimeDisconnection), DATETIME(ses_DateTimeDisconnection, "-1 hour"))
ELSE ses_DateTimeConnection
END AS ses_DateTimeConnectionCorrected,
CASE WHEN ses_EventTypeDisconnection = "<missing event>" 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
FROM Sessions AS SES1
WHERE ( ses_DateTimeConnectionCorrected <= Date('. $endDate .')
AND (ses_DateTimeDisconnectionCorrected >= Date('. $startDate .') OR ses_StillConnected = 1 ))
');
// arrays of rows
while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
// Event color
if ($row['ses_EventTypeConnection'] == '<missing event>' || $row['ses_EventTypeDisconnection'] == '<missing event>') {
$color = '#f39c12';
} else {
$color = '#0073b7';
}
// tooltip
$tooltip = 'Connection: ' . formatEventDate ($row['ses_DateTimeConnection'], $row['ses_EventTypeConnection']) . chr(13) .
'Disconnection: ' . formatEventDate ($row['ses_DateTimeDisconnection'], $row['ses_EventTypeDisconnection']) . chr(13) .
'IP: ' . $row['ses_IP'];
// Save row data
$tableData[] = array(
'resourceId' => $row['ses_MAC'],
'title' => '',
'start' => formatDateISO ($row['ses_DateTimeConnectionCorrected']),
'end' => formatDateISO ($row['ses_DateTimeDisconnectionCorrected']),
'color' => $color,
'tooltip' => $tooltip,
'className' => 'no-border'
);
}
// Control no rows
if (empty($tableData)) {
$tableData = '';
}
// Return json
echo (json_encode($tableData));
}
//------------------------------------------------------------------------------
// Query Device events
//------------------------------------------------------------------------------
function queryDeviceEvents() {
global $db;
// Request Parameters
$mac = $_REQUEST['mac'];
$periodDate = getDateFromPeriod();
$hideConnections = $_REQUEST ['hideConnections'];
// SQL
$result = $db->query('SELECT eve_DateTime, eve_EventType, eve_IP, eve_AdditionalInfo
FROM Events
WHERE eve_MAC="'. $mac .'" AND eve_DateTime >= '. $periodDate .'
AND ( (eve_EventType <> "Connected" AND eve_EventType <> "Disconnected" AND
eve_EventType <> "VOIDED - Connected" AND eve_EventType <> "VOIDED - Disconnected")
OR "'. $hideConnections .'" = "false" )
');
// arrays of rows
$tableData = array();
while ($row = $result -> fetchArray (SQLITE3_NUM)) {
$row[0] = formatDate ($row[0]);
$tableData['data'][] = $row;
}
// Control no rows
if (empty($tableData['data'])) {
$tableData['data'] = '';
}
// Return json
echo (json_encode ($tableData));
}
?>

48
front/php/server/util.php Normal file
View File

@@ -0,0 +1,48 @@
<?php
//------------------------------------------------------------------------------
// Formatting data functions
//------------------------------------------------------------------------------
function formatDate ($date1) {
return date_format (new DateTime ($date1) , 'Y-m-d H:i');
}
function formatDateDiff ($date1, $date2) {
return date_diff (new DateTime ($date1), new DateTime ($date2 ) )-> format ('%ad %H:%I');
}
function formatDateISO ($date1) {
return date_format (new DateTime ($date1),'c');
}
function formatEventDate ($date1, $eventType) {
if (!empty ($date1) ) {
$ret = formatDate ($date1);
} elseif ($eventType == '<missing event>') {
$ret = '<missing event>';
} else {
$ret = '<Still Connected>';
}
return $ret;
}
function formatIPlong ($IP) {
return sprintf('%u', ip2long($IP) );
}
//------------------------------------------------------------------------------
// Others functions
//------------------------------------------------------------------------------
function getDateFromPeriod () {
$period = $_REQUEST['period'];
return '"'. date ('Y-m-d', strtotime ('+1 day -'.$period) ) .'"';
}
function logServerConsole ($text) {
$x = array();
$y = $x['__________'. $text .'__________'];
}
?>

View File

@@ -0,0 +1,41 @@
<!-- Main Footer -->
<footer class="main-footer">
<!-- Default to the left -->
&copy; 2020 Puche
<!-- To the right -->
<div class="pull-right no-hidden-xs">
Pi.alert&nbsp&nbsp2.50&nbsp&nbsp<small>(2019-12-30)</small>
</div>
</footer>
<!-- Control Sidebar -->
<!-- DELETED -->
</div>
<!-- ./wrapper -->
<!-- REQUIRED JS SCRIPTS -->
<!-- jQuery 3 -->
<script src="lib/AdminLTE/bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="lib/AdminLTE/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- AdminLTE App -->
<script src="lib/AdminLTE/dist/js/adminlte.min.js"></script>
<!-- Optionally, you can add Slimscroll and FastClick plugins.
Both of these plugins are recommended to enhance the
user experience. -->
<!-- SlimScroll -->
<script src="lib/AdminLTE/bower_components/jquery-slimscroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="lib/AdminLTE/bower_components/fastclick/lib/fastclick.js"></script>
<!-- Pi.Alert -------------------------------------------------------------- -->
<script src="js/pialert_common.js"></script>
</body>
</html>

View File

@@ -0,0 +1,275 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Pi.alert</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.7 -->
<link rel="stylesheet" href="lib/AdminLTE/bower_components/bootstrap/dist/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="lib/AdminLTE/bower_components/font-awesome/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="lib/AdminLTE/bower_components/Ionicons/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="lib/AdminLTE/dist/css/AdminLTE.min.css">
<!-- AdminLTE Skins. We have chosen the skin-blue for this starter
page. However, you can choose any other skin. Make sure you
apply the skin class to the body tag so the changes take effect. -->
<link rel="stylesheet" href="lib/AdminLTE/dist/css/skins/skin-yellow-light.min.css">
<!-- Pi.alert CSS -->
<link rel="stylesheet" href="css/pialert.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Google Font -->
<link rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">
<!-- Page Icon -->
<link rel="icon" type="image/png" sizes="160x160" href="img/pialertLogoGray80.png" />
</head>
<!-- Layout Boxed Yellow -->
<body class="hold-transition skin-yellow-light layout-boxed sidebar-mini" style="background-image: url('img/backgroud.png');">
<!-- Site wrapper -->
<div class="wrapper">
<!-- Main Header -->
<header class="main-header">
<!-- Logo -->
<a href="/" class="logo">
<!-- mini logo for sidebar mini 50x50 pixels -->
<span class="logo-mini">P<b>a</b></span>
<!-- logo for regular state and mobile devices -->
<span class="logo-lg">Pi<b>.alert</b></span>
</a>
<!-- Header Navbar -->
<nav class="navbar navbar-static-top" role="navigation">
<!-- Sidebar toggle button-->
<a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button">
<span class="sr-only">Toggle navigation</span>
</a>
<!-- Navbar Right Menu -->
<div class="navbar-custom-menu">
<ul class="nav navbar-nav">
<!-- Server Name -->
<li><a style="pointer-events:none;"><?php echo gethostname(); ?></a></li>
<!-- Header right info -->
<li class="dropdown user user-menu">
<!-- Menu Toggle Button -->
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<!-- The user image in the navbar-->
<img src="img/pialertLogoWhite.png" class="user-image" style="border-radius: initial" alt="Pi.alert Logo">
<!-- hidden-xs hides the username on small devices so only the image appears. -->
<span class="hidden-xs">Pi.alert</span>
</a>
<ul class="dropdown-menu">
<!-- The user image in the menu -->
<li class="user-header">
<img src="img/pialertLogoWhite.png" class="img-circle" alt="Pi.alert Logo" style="border-color:transparent">
<p>
Open Source Network Guard
<small>Designed for Raspberry Pi</small>
</p>
</li>
<!-- Menu Body -->
<li class="user-body">
<div class="row">
<div class="col-xs-4 text-center">
<a href="https://github.com/pucherot/Pi.Alert">GitHub</a>
</div>
<div class="col-xs-4 text-center">
<a href="https://github.com/pucherot/Pi.Alert">Pi.Alert</a>
<!-- <a href="#">Website</a> -->
</div>
<div class="col-xs-4 text-center">
<a href="#">Updates</a>
</div>
</div>
<!-- /.row -->
</li>
</ul>
</li>
</ul>
</div>
</nav>
</header>
<!-- Left side column. contains the logo and sidebar -->
<aside class="main-sidebar">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar">
<!-- Sidebar user panel (optional) -->
<div class="user-panel">
<a href="/" class="logo">
<img src="img/pialertLogoGray80.png" class="img-responsive" alt="Pi.alert Logo"/>
</a>
<div class="pull-left image">
<!--
<br><img src="img/pialertLogoBlack.png" class="img-responsive" alt="Pi.alert Logo" style="display: table; table-layout: fixed;" />
-->
</div>
<div class="pull-left info" style="display: none">
<p>Status</p>
<?php
$pistatus = exec('sudo pihole status web');
$pistatus=1;
$FTL=true;
$celsius=56.7;
$temperatureunit='C';
$nproc=2;
$loaddata=array();
$loaddata[]=1.1;
$loaddata[]=1.2;
$loaddata[]=1.3;
$memory_usage=0.452;
if ($pistatus == "1") {
echo '<a id="status"><i class="fa fa-circle" style="color:#7FFF00"></i> Active</a>';
} elseif ($pistatus == "0") {
echo '<a id="status"><i class="fa fa-circle" style="color:#FF0000"></i> Offline</a>';
} elseif ($pistatus == "-1") {
echo '<a id="status"><i class="fa fa-circle" style="color:#FF0000"></i> DNS service not running</a>';
} else {
echo '<a id="status"><i class="fa fa-circle" style="color:#ff9900"></i> Unknown</a>';
}
// CPU Temp
if($FTL)
{
if ($celsius >= -273.15) {
echo "<a id=\"temperature\"><i class=\"fa fa-fire\" style=\"color:";
if ($celsius > 60) {
echo "#FF0000";
}
else
{
echo "#3366FF";
}
echo "\"></i> Temp:&nbsp;";
if($temperatureunit === "F")
{
echo round($fahrenheit,1) . "&nbsp;&deg;F";
}
elseif($temperatureunit === "K")
{
echo round($kelvin,1) . "&nbsp;K";
}
else
{
echo round($celsius,1) . "&nbsp;&deg;C";
}
echo "</a>";
}
}
else
{
echo '<a id=\"temperature\"><i class="fa fa-circle" style="color:#FF0000"></i> FTL offline</a>';
}
?>
<br/>
<?php
echo "<a title=\"Detected $nproc cores\"><i class=\"fa fa-circle\" style=\"color:";
if ($loaddata[0] > $nproc) {
echo "#FF0000";
}
else
{
echo "#7FFF00";
}
echo "\"></i> Load:&nbsp;&nbsp;" . $loaddata[0] . "&nbsp;&nbsp;" . $loaddata[1] . "&nbsp;&nbsp;". $loaddata[2] . "</a>";
?>
<br/>
<?php
echo "<a><i class=\"fa fa-circle\" style=\"color:";
if ($memory_usage > 0.75 || $memory_usage < 0.0) {
echo "#FF0000";
}
else
{
echo "#7FFF00";
}
if($memory_usage > 0.0)
{
echo "\"></i> Memory usage:&nbsp;&nbsp;" . sprintf("%.1f",100.0*$memory_usage) . "&thinsp;%</a>";
}
else
{
echo "\"></i> Memory usage:&nbsp;&nbsp; N/A</a>";
}
?>
</div>
</div>
<!-- search form (Optional) -->
<!--
<form action="#" method="get" class="sidebar-form">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="Search...">
<span class="input-group-btn">
<button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i>
</button>
</span>
</div>
</form>
-->
<!-- /.search form -->
<!-- Sidebar Menu -->
<ul class="sidebar-menu" data-widget="tree">
<!--
<li class="header">MAIN MENU</li>
-->
<!-- Optionally, you can add icons to the links -->
<li class=" <?php if (in_array (basename($_SERVER['SCRIPT_NAME']), array('devices.php', 'deviceDetails.php') ) ){ echo 'active'; } ?>">
<a href="devices.php"><i class="fa fa-laptop"></i> <span>Devices</span></a>
</li>
<!--
<li><a href="devices.php?status=favorites"><i class="fa fa-star"></i> <span>Favorites Devices</span></a></li>
-->
<li class=" <?php if (in_array (basename($_SERVER['SCRIPT_NAME']), array('presence.php') ) ){ echo 'active'; } ?>">
<a href="presence.php"><i class="fa fa-calendar"></i> <span>Presence</span></a>
</li>
<li class=" <?php if (in_array (basename($_SERVER['SCRIPT_NAME']), array('events.php') ) ){ echo 'active'; } ?>">
<a href="events.php"><i class="fa fa-bolt"></i> <span>Events</span></a>
</li>
<!--
<li class="treeview">
<a href="#"><i class="fa fa-link"></i> <span>Config</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li><a href="#">Scan Cycles</a></li>
<li><a href="#">Cron Status</a></li>
<li><a href="#">Current IP</a></li>
</ul>
</li>
-->
</ul>
<!-- /.sidebar-menu -->
</section>
<!-- /.sidebar -->
</aside>