mirror of
https://github.com/jokob-sk/NetAlertX.git
synced 2026-03-30 23:03:03 -07:00
@@ -26,7 +26,7 @@ The database and device structure may change with new releases. When using the C
|
||||

|
||||
|
||||
> [!NOTE]
|
||||
> The file containing a list of Devices including the Network relationships between Network Nodes and connected devices. You can also trigger this by acessing this URL: `<server>:20211/php/server/devices.php?action=ExportCSV` or via the `CSV Backup` plugin. (💡 You can schedule this)
|
||||
> The file containing a list of Devices including the Network relationships between Network Nodes and connected devices. You can also trigger this with the `CSV Backup` plugin. (💡 You can schedule this)
|
||||
|
||||

|
||||
|
||||
|
||||
@@ -1,31 +1,3 @@
|
||||
// --------------------------------------------------
|
||||
// Check if database is locked
|
||||
function lockDatabase(delay=20) {
|
||||
$.ajax({
|
||||
url: 'php/server/dbHelper.php', // Replace with the actual path to your PHP file
|
||||
type: 'GET',
|
||||
data: { action: 'lockDatabase', delay: delay },
|
||||
success: function(response) {
|
||||
console.log('Executed');
|
||||
},
|
||||
error: function() {
|
||||
console.log('Error ocurred');
|
||||
}
|
||||
});
|
||||
|
||||
let times = delay;
|
||||
let countdownInterval = setInterval(() => {
|
||||
times--;
|
||||
console.log(`Remaining time: ${times} seconds`);
|
||||
|
||||
if (times <= 0) {
|
||||
clearInterval(countdownInterval);
|
||||
console.log('Countdown finished');
|
||||
}
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
|
||||
const requiredFiles = [
|
||||
'app_state.json',
|
||||
'plugins.json',
|
||||
|
||||
@@ -1,310 +0,0 @@
|
||||
<?php
|
||||
//------------------------------------------------------------------------------
|
||||
// NetAlertX
|
||||
// Open Source Network Guard / WIFI & LAN intrusion detector
|
||||
//
|
||||
//------------------------------------------------------------------------------
|
||||
# Puche 2022+ jokob jokob@duck.com GNU GPLv3
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// 🔺----- API ENDPOINTS SUPERSEDED -----🔺
|
||||
// check server/api_server/api_server_start.py for equivalents
|
||||
// equivalent: /dbquery
|
||||
// 🔺----- API ENDPOINTS SUPERSEDED -----🔺
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// External files
|
||||
require dirname(__FILE__).'/init.php';
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// check if authenticated
|
||||
require_once $_SERVER['DOCUMENT_ROOT'] . '/php/templates/security.php';
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Action selector
|
||||
//------------------------------------------------------------------------------
|
||||
// Set maximum execution time to 15 seconds
|
||||
ini_set ('max_execution_time','15');
|
||||
|
||||
$skipCache = FALSE;
|
||||
$expireMinutes = 5;
|
||||
$defaultValue = '';
|
||||
$dbtable = '';
|
||||
$columns = '';
|
||||
$values = '';
|
||||
|
||||
|
||||
if (isset ($_REQUEST['skipcache'])) {
|
||||
$skipCache = TRUE;
|
||||
}
|
||||
|
||||
if (isset ($_REQUEST['defaultValue'])) {
|
||||
$defaultValue = $_REQUEST['defaultValue'];
|
||||
}
|
||||
|
||||
if (isset ($_REQUEST['expireMinutes'])) {
|
||||
$expireMinutes = $_REQUEST['expireMinutes'];
|
||||
}
|
||||
|
||||
if (isset ($_REQUEST['columnName'])) {
|
||||
$columnName = $_REQUEST['columnName'];
|
||||
}
|
||||
|
||||
if (isset ($_REQUEST['id'])) {
|
||||
$id = $_REQUEST['id'];
|
||||
}
|
||||
|
||||
if (isset ($_REQUEST['delay'])) {
|
||||
$delay = $_REQUEST['delay'];
|
||||
}
|
||||
|
||||
if (isset ($_REQUEST['values'])) {
|
||||
$values = $_REQUEST['values'];
|
||||
}
|
||||
|
||||
if (isset ($_REQUEST['columns'])) {
|
||||
$columns = $_REQUEST['columns'];
|
||||
}
|
||||
|
||||
if (isset ($_REQUEST['rawSql'])) {
|
||||
$rawSql = urldecode(base64_decode($_REQUEST['rawSql'])); // base64 encoded SQL
|
||||
}
|
||||
|
||||
if (isset ($_REQUEST['dbtable'])) {
|
||||
$dbtable = $_REQUEST['dbtable'];
|
||||
}
|
||||
// TODO: Security, read, delete, edge cases
|
||||
// Action functions
|
||||
if (isset ($_REQUEST['action']) && !empty ($_REQUEST['action'])) {
|
||||
$action = $_REQUEST['action'];
|
||||
switch ($action) {
|
||||
case 'create': create($defaultValue, $expireMinutes, $dbtable, $columns, $values ); break;
|
||||
case 'read' : read($rawSql); break;
|
||||
case 'write' : write($rawSql); break;
|
||||
case 'update': update($columnName, $id, $defaultValue, $expireMinutes, $dbtable, $columns, $values); break;
|
||||
case 'delete': delete($columnName, $id, $dbtable); break;
|
||||
case 'lockDatabase': lockDatabase($delay); break;
|
||||
default: logServerConsole ('Action: '. $action); break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// read
|
||||
//------------------------------------------------------------------------------
|
||||
function read($rawSql) {
|
||||
global $db;
|
||||
|
||||
// Construct the SQL query to select values
|
||||
$sql = $rawSql;
|
||||
|
||||
// Execute the SQL query
|
||||
$result = $db->query($sql);
|
||||
|
||||
// Check if the query executed successfully
|
||||
if (! $result == TRUE) {
|
||||
// Output an error message if the query failed
|
||||
echo "Error reading data\n\n " .$sql." \n\n". $db->lastErrorMsg();
|
||||
return;
|
||||
} else
|
||||
{
|
||||
// Output $result
|
||||
// Fetching rows from the result object and storing them in an array
|
||||
$rows = array();
|
||||
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
|
||||
$rows[] = $row;
|
||||
}
|
||||
|
||||
// Converting the array to JSON
|
||||
$json = json_encode($rows);
|
||||
|
||||
// Outputting the JSON
|
||||
echo $json;
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// write
|
||||
//------------------------------------------------------------------------------
|
||||
function write($rawSql) {
|
||||
global $db;
|
||||
|
||||
// Construct the SQL query to select values
|
||||
$sql = $rawSql;
|
||||
|
||||
// Execute the SQL query
|
||||
$result = $db->query($sql);
|
||||
|
||||
// Check if the query executed successfully
|
||||
if (! $result == TRUE) {
|
||||
// Output an error message if the query failed
|
||||
echo "Error writing data\n\n " .$sql." \n\n". $db->lastErrorMsg();
|
||||
return;
|
||||
} else
|
||||
{
|
||||
// Output
|
||||
echo "OK";
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// update
|
||||
//------------------------------------------------------------------------------
|
||||
function update($columnName, $id, $defaultValue, $expireMinutes, $dbtable, $columns, $values) {
|
||||
|
||||
global $db;
|
||||
|
||||
// Handle one or multiple columns
|
||||
if(strpos($columns, ',') !== false) {
|
||||
$columnsArr = explode(",", $columns);
|
||||
} else {
|
||||
$columnsArr = array($columns);
|
||||
}
|
||||
|
||||
// Handle one or multiple values
|
||||
if(strpos($values, ',') !== false) {
|
||||
$valuesArr = explode(",", $values);
|
||||
} else {
|
||||
$valuesArr = array($values);
|
||||
}
|
||||
|
||||
// Handle one or multiple IDs
|
||||
if(strpos($id, ',') !== false) {
|
||||
$idsArr = explode(",", $id);
|
||||
$idsPlaceholder = rtrim(str_repeat('?,', count($idsArr)), ',');
|
||||
} else {
|
||||
$idsArr = array($id);
|
||||
$idsPlaceholder = '?';
|
||||
}
|
||||
|
||||
// Build column-value pairs string
|
||||
$columnValues = '';
|
||||
foreach($columnsArr as $column) {
|
||||
$columnValues .= '"' . $column . '" = ?,';
|
||||
}
|
||||
// Remove trailing comma
|
||||
$columnValues = rtrim($columnValues, ',');
|
||||
|
||||
// Construct the SQL query
|
||||
$sql = 'UPDATE ' . $dbtable . ' SET ' . $columnValues . ' WHERE ' . $columnName . ' IN (' . $idsPlaceholder . ')';
|
||||
|
||||
// Prepare the statement
|
||||
$stmt = $db->prepare($sql);
|
||||
|
||||
// Check for errors
|
||||
if(!$stmt) {
|
||||
echo "Error preparing statement: " . $db->lastErrorMsg();
|
||||
return;
|
||||
}
|
||||
|
||||
// Bind the parameters
|
||||
$paramTypes = str_repeat('s', count($columnsArr));
|
||||
foreach($valuesArr as $i => $value) {
|
||||
$stmt->bindValue($i + 1, $value);
|
||||
}
|
||||
foreach($idsArr as $i => $idValue) {
|
||||
$stmt->bindValue(count($valuesArr) + $i + 1, $idValue);
|
||||
}
|
||||
|
||||
// Execute the statement
|
||||
$result = $stmt->execute();
|
||||
|
||||
$changes = $db->changes();
|
||||
if ($changes == 0) {
|
||||
// Insert new value
|
||||
create( $defaultValue, $expireMinutes, $dbtable, $columns, $values);
|
||||
}
|
||||
|
||||
// update cache
|
||||
$uniqueHash = hash('ripemd160', $dbtable . $columns);
|
||||
setCache($uniqueHash, $values, $expireMinutes);
|
||||
|
||||
echo 'OK' ;
|
||||
}
|
||||
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// create
|
||||
//------------------------------------------------------------------------------
|
||||
function create( $defaultValue, $expireMinutes, $dbtable, $columns, $values)
|
||||
{
|
||||
global $db;
|
||||
|
||||
echo "NOT IMPLEMENTED!\n\n";
|
||||
return;
|
||||
|
||||
// // Insert new value
|
||||
// $sql = 'INSERT INTO '.$dbtable.' ('.$columns.')
|
||||
// VALUES ("'. quotes($parameter) .'",
|
||||
// "'. $values .'")';
|
||||
// $result = $db->query($sql);
|
||||
|
||||
// if (! $result == TRUE) {
|
||||
// echo "Error creating entry\n\n$sql \n\n". $db->lastErrorMsg();
|
||||
// return;
|
||||
// }
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// delete
|
||||
//------------------------------------------------------------------------------
|
||||
function delete($columnName, $id, $dbtable)
|
||||
{
|
||||
global $db;
|
||||
|
||||
// Handle one or multiple ids
|
||||
if(strpos($id, ',') !== false)
|
||||
{
|
||||
$idsArr = explode(",", $id);
|
||||
} else
|
||||
{
|
||||
$idsArr = array($id);
|
||||
}
|
||||
|
||||
// Initialize an empty string to store the comma-separated list of IDs
|
||||
$idsStr = "";
|
||||
|
||||
// Iterate over each ID
|
||||
foreach ($idsArr as $index => $item)
|
||||
{
|
||||
// Append the current ID to the string
|
||||
$idsStr .= '"' . $item . '"';
|
||||
|
||||
// Add a comma if the current ID is not the last one
|
||||
if ($index < count($idsArr) - 1) {
|
||||
$idsStr .= ', ';
|
||||
}
|
||||
}
|
||||
|
||||
// Construct the SQL query to delete entries based on the given IDs
|
||||
$sql = 'DELETE FROM '.$dbtable.' WHERE "'.$columnName.'" IN ('. $idsStr .')';
|
||||
|
||||
// Execute the SQL query
|
||||
$result = $db->query($sql);
|
||||
|
||||
// Check if the query executed successfully
|
||||
if (! $result == TRUE) {
|
||||
// Output an error message if the query failed
|
||||
echo "Error deleting entry\n\n".$sql." \n\n". $db->lastErrorMsg();
|
||||
return;
|
||||
} else
|
||||
{
|
||||
// Output 'OK' if the deletion was successful
|
||||
echo 'OK' ;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Simulate database locking by starting a transaction
|
||||
function lockDatabase($delay) {
|
||||
$db = new SQLite3($GLOBALS['DBFILE']);
|
||||
$db->exec('BEGIN EXCLUSIVE;');
|
||||
sleep($delay); // Sleep for N seconds to simulate long-running transaction
|
||||
}
|
||||
|
||||
?>
|
||||
@@ -1,442 +0,0 @@
|
||||
<?php
|
||||
//------------------------------------------------------------------------------
|
||||
// NetAlertX
|
||||
// Open Source Network Guard / WIFI & LAN intrusion detector
|
||||
//
|
||||
// devices.php - Front module. Server side. Manage Devices
|
||||
//------------------------------------------------------------------------------
|
||||
# Puche 2021 / 2022+ jokob jokob@duck.com GNU GPLv3
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// 🔺----- API ENDPOINTS SUPERSEDED -----🔺
|
||||
// check server/api_server/api_server_start.py for equivalents
|
||||
// 🔺----- API ENDPOINTS SUPERSEDED -----🔺
|
||||
|
||||
// External files
|
||||
require dirname(__FILE__).'/init.php';
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// check if authenticated
|
||||
require_once $_SERVER['DOCUMENT_ROOT'] . '/php/templates/security.php';
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Action selector
|
||||
//------------------------------------------------------------------------------
|
||||
// Set maximum execution time to 15 seconds
|
||||
|
||||
ini_set ('max_execution_time','30');
|
||||
|
||||
// Action functions
|
||||
if (isset ($_REQUEST['action']) && !empty ($_REQUEST['action'])) {
|
||||
$action = $_REQUEST['action'];
|
||||
switch ($action) {
|
||||
// check server/api_server/api_server_start.py for equivalents
|
||||
case 'deleteDevice': deleteDevice(); break; // equivalent: delete_device(mac)
|
||||
case 'deleteAllWithEmptyMACs': deleteAllWithEmptyMACs(); break; // equivalent: delete_all_with_empty_macs
|
||||
|
||||
case 'deleteAllDevices': deleteAllDevices(); break; // equivalent: delete_devices(macs)
|
||||
case 'deleteUnknownDevices': deleteUnknownDevices(); break; // equivalent: delete_unknown_devices
|
||||
case 'deleteEvents': deleteEvents(); break; // equivalent: delete_events
|
||||
case 'deleteEvents30': deleteEvents30(); break; // equivalent: delete_events_30
|
||||
case 'deleteActHistory': deleteActHistory(); break; // equivalent: delete_online_history
|
||||
case 'deleteDeviceEvents': deleteDeviceEvents(); break; // equivalent: delete_device_events(mac)
|
||||
|
||||
case 'ExportCSV': ExportCSV(); break; // equivalent: export_devices
|
||||
case 'ImportCSV': ImportCSV(); break; // equivalent: import_csv
|
||||
|
||||
case 'getDevicesListCalendar': getDevicesListCalendar(); break; // equivalent: devices_by_status
|
||||
|
||||
case 'updateNetworkLeaf': updateNetworkLeaf(); break; // equivalent: update_device_column(mac, column_name, column_value)
|
||||
|
||||
default: logServerConsole ('Action: '. $action); break; // equivalent:
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Delete Device
|
||||
//------------------------------------------------------------------------------
|
||||
function deleteDevice() {
|
||||
global $db;
|
||||
|
||||
// sql
|
||||
$sql = 'DELETE FROM Devices WHERE devMac="' . $_REQUEST['mac'] .'"';
|
||||
// execute sql
|
||||
$result = $db->query($sql);
|
||||
|
||||
// check result
|
||||
if ($result == TRUE) {
|
||||
echo lang('BackDevices_DBTools_DelDev_a');
|
||||
} else {
|
||||
echo lang('BackDevices_DBTools_DelDevError_a')."\n\n$sql \n\n". $db->lastErrorMsg();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Delete all devices with empty MAC addresses
|
||||
//------------------------------------------------------------------------------
|
||||
function deleteAllWithEmptyMACs() {
|
||||
global $db;
|
||||
|
||||
// sql
|
||||
$sql = 'DELETE FROM Devices WHERE devMac=""';
|
||||
// execute sql
|
||||
$result = $db->query($sql);
|
||||
|
||||
// check result
|
||||
if ($result == TRUE) {
|
||||
echo lang('BackDevices_DBTools_DelDev_b');
|
||||
} else {
|
||||
echo lang('BackDevices_DBTools_DelDevError_b')."\n\n$sql \n\n". $db->lastErrorMsg();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Delete all devices with empty MAC addresses
|
||||
//------------------------------------------------------------------------------
|
||||
function deleteUnknownDevices() {
|
||||
global $db;
|
||||
|
||||
// sql
|
||||
$sql = 'DELETE FROM Devices WHERE devName="(unknown)" OR devName="(name not found)"';
|
||||
// execute sql
|
||||
$result = $db->query($sql);
|
||||
|
||||
// check result
|
||||
if ($result == TRUE) {
|
||||
echo lang('BackDevices_DBTools_DelDev_b');
|
||||
} else {
|
||||
echo lang('BackDevices_DBTools_DelDevError_b')."\n\n$sql \n\n". $db->lastErrorMsg();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Delete Device Events
|
||||
//------------------------------------------------------------------------------
|
||||
function deleteDeviceEvents() {
|
||||
global $db;
|
||||
|
||||
// sql
|
||||
$sql = 'DELETE FROM Events WHERE eve_MAC="' . $_REQUEST['mac'] .'"';
|
||||
// execute sql
|
||||
$result = $db->query($sql);
|
||||
|
||||
// check result
|
||||
if ($result == TRUE) {
|
||||
echo lang('BackDevices_DBTools_DelEvents');
|
||||
} else {
|
||||
echo lang('BackDevices_DBTools_DelEventsError')."\n\n$sql \n\n". $db->lastErrorMsg();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Delete all devices
|
||||
//------------------------------------------------------------------------------
|
||||
function deleteAllDevices() {
|
||||
global $db;
|
||||
|
||||
// sql
|
||||
$sql = 'DELETE FROM Devices';
|
||||
// execute sql
|
||||
$result = $db->query($sql);
|
||||
|
||||
// check result
|
||||
if ($result == TRUE) {
|
||||
echo lang('BackDevices_DBTools_DelDev_b');
|
||||
} else {
|
||||
echo lang('BackDevices_DBTools_DelDevError_b')."\n\n$sql \n\n". $db->lastErrorMsg();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Delete all Events
|
||||
//------------------------------------------------------------------------------
|
||||
function deleteEvents() {
|
||||
global $db;
|
||||
// sql
|
||||
$sql = 'DELETE FROM Events';
|
||||
// execute sql
|
||||
$result = $db->query($sql);
|
||||
|
||||
// check result
|
||||
if ($result == TRUE) {
|
||||
echo lang('BackDevices_DBTools_DelEvents');
|
||||
} else {
|
||||
echo lang('BackDevices_DBTools_DelEventsError')."\n\n$sql \n\n". $db->lastErrorMsg();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Delete all Events older than 30 days
|
||||
//------------------------------------------------------------------------------
|
||||
function deleteEvents30() {
|
||||
global $db;
|
||||
|
||||
// sql
|
||||
$sql = "DELETE FROM Events WHERE eve_DateTime <= date('now', '-30 day')";
|
||||
// execute sql
|
||||
$result = $db->query($sql);
|
||||
|
||||
// check result
|
||||
if ($result == TRUE) {
|
||||
echo lang('BackDevices_DBTools_DelEvents');
|
||||
} else {
|
||||
echo lang('BackDevices_DBTools_DelEventsError')."\n\n$sql \n\n". $db->lastErrorMsg();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Delete History
|
||||
//------------------------------------------------------------------------------
|
||||
function deleteActHistory() {
|
||||
global $db;
|
||||
|
||||
// sql
|
||||
$sql = 'DELETE FROM Online_History';
|
||||
// execute sql
|
||||
$result = $db->query($sql);
|
||||
|
||||
// check result
|
||||
if ($result == TRUE) {
|
||||
echo lang('BackDevices_DBTools_DelActHistory');
|
||||
} else {
|
||||
echo lang('BackDevices_DBTools_DelActHistoryError')."\n\n$sql \n\n". $db->lastErrorMsg();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// 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
|
||||
$columns = getDevicesColumns();
|
||||
|
||||
// wrap the headers with " (quotes)
|
||||
$resultCSV = '"'.implode('","', $columns).'"'."\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) {
|
||||
// Escape special chars (e.g.quotes) inside fields by replacing them with html definitions
|
||||
$fieldValue = encodeSpecialChars($row[$columnName]);
|
||||
|
||||
// add quotes around the value to prevent issues with commas in fields
|
||||
$resultCSV .= '"'.$fieldValue.'"';
|
||||
|
||||
// detect last loop - skip as no comma needed
|
||||
if ($index != count($columns) - 1) {
|
||||
$resultCSV .= ',';
|
||||
}
|
||||
$index++;
|
||||
}
|
||||
|
||||
// add a new line for the next row
|
||||
$resultCSV .= "\n";
|
||||
}
|
||||
|
||||
//write the built CSV string
|
||||
echo $resultCSV;
|
||||
}
|
||||
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Import CSV of devices
|
||||
//------------------------------------------------------------------------------
|
||||
function ImportCSV() {
|
||||
|
||||
global $db;
|
||||
$file = '../../../config/devices.csv';
|
||||
$data = "";
|
||||
$skipped = "";
|
||||
$error = "";
|
||||
|
||||
// check if content passed in query string
|
||||
if(isset ($_POST['content']) && !empty ($_POST['content']))
|
||||
{
|
||||
// Decode the Base64 string
|
||||
// $data = base64_decode($_POST['content']);
|
||||
$data = base64_decode($_POST['content'], true); // The second parameter ensures safe decoding
|
||||
|
||||
// // Ensure the decoded data is treated as UTF-8 text
|
||||
// $data = mb_convert_encoding($data, 'UTF-8', 'UTF-8');
|
||||
|
||||
} else if (file_exists($file)) { // try to get the data form the file
|
||||
|
||||
// Read the CSV file
|
||||
$data = file_get_contents($file);
|
||||
} else {
|
||||
echo lang('BackDevices_DBTools_ImportCSVMissing');
|
||||
}
|
||||
|
||||
if($data != "")
|
||||
{
|
||||
// data cleanup - new lines breaking the CSV
|
||||
$data = preg_replace_callback('/"([^"]*)"/', function($matches) {
|
||||
// Replace all \n within the quotes with a space
|
||||
return str_replace("\n", " ", $matches[0]); // Replace with a space
|
||||
}, $data);
|
||||
|
||||
$lines = explode("\n", $data);
|
||||
|
||||
// Get the column headers from the first line of the CSV
|
||||
$header = str_getcsv(array_shift($lines));
|
||||
$header = array_map('trim', $header);
|
||||
|
||||
// Delete everything form the DB table
|
||||
$sql = 'DELETE FROM Devices';
|
||||
$result = $db->query($sql);
|
||||
|
||||
// Build the SQL statement
|
||||
$sql = "INSERT INTO Devices (" . implode(', ', $header) . ") VALUES ";
|
||||
|
||||
// Parse data from CSV file line by line (max 10000 lines)
|
||||
$index = 0;
|
||||
foreach($lines as $row) {
|
||||
$rowArray = str_getcsv($row);
|
||||
|
||||
if (count($rowArray) === count($header)) {
|
||||
// Make sure the number of columns matches the header
|
||||
$rowArray = array_map(function ($value) {
|
||||
return "'" . SQLite3::escapeString(trim($value)) . "'";
|
||||
}, $rowArray);
|
||||
|
||||
$sql .= "(" . implode(', ', $rowArray) . "), ";
|
||||
} else {
|
||||
$skipped .= ($index + 1) . ",";
|
||||
}
|
||||
|
||||
$index++;
|
||||
}
|
||||
|
||||
// Remove the trailing comma and space from SQL
|
||||
$sql = rtrim($sql, ', ');
|
||||
|
||||
// Execute the SQL query
|
||||
$result = $db->query($sql);
|
||||
|
||||
if($error === "") {
|
||||
// Import successful
|
||||
echo lang('BackDevices_DBTools_ImportCSV') . " (Skipped lines: " . $skipped . ") ";
|
||||
} else {
|
||||
// An error occurred while writing to the DB, display the last error message
|
||||
echo lang('BackDevices_DBTools_ImportCSVError') . "\n" . $error . "\n" . $sql . "\n\n" . $result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Determine if Random MAC
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
function isRandomMAC($mac) {
|
||||
$isRandom = false;
|
||||
|
||||
// if detected as random, make sure it doesn't start with a prefix which teh suer doesn't want to mark as random
|
||||
$setting = getSettingValue("UI_NOT_RANDOM_MAC");
|
||||
$prefixes = createArray($setting);
|
||||
|
||||
$isRandom = in_array($mac[1], array("2", "6", "A", "E", "a", "e"));
|
||||
|
||||
// If detected as random, make sure it doesn't start with a prefix which the user doesn't want to mark as random
|
||||
if ($isRandom) {
|
||||
foreach ($prefixes as $prefix) {
|
||||
if (strpos($mac, $prefix) === 0) {
|
||||
$isRandom = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $isRandom;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Query the List of devices for calendar
|
||||
//------------------------------------------------------------------------------
|
||||
function getDevicesListCalendar() {
|
||||
global $db;
|
||||
|
||||
// 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['devFavorite'] == 1) {
|
||||
$row['devName'] = '<span class="text-yellow">★</span> '. $row['devName'];
|
||||
}
|
||||
|
||||
$tableData[] = array ('id' => $row['devMac'],
|
||||
'title' => $row['devName'],
|
||||
'favorite' => $row['devFavorite']);
|
||||
}
|
||||
|
||||
// Return json
|
||||
echo (json_encode ($tableData));
|
||||
}
|
||||
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Query Device Data
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// ----------------------------------------------------------------------------------------
|
||||
function updateNetworkLeaf()
|
||||
{
|
||||
$nodeMac = $_REQUEST['value']; // parent
|
||||
$leafMac = $_REQUEST['id']; // child
|
||||
|
||||
if ((false === filter_var($nodeMac , FILTER_VALIDATE_MAC) && $nodeMac != "Internet" && $nodeMac != "") || false === filter_var($leafMac , FILTER_VALIDATE_MAC) ) {
|
||||
throw new Exception('Invalid mac address');
|
||||
}
|
||||
else
|
||||
{
|
||||
global $db;
|
||||
// sql
|
||||
$sql = 'UPDATE Devices SET "devParentMAC" = "'. $nodeMac .'" WHERE "devMac"="' . $leafMac.'"' ;
|
||||
// update Data
|
||||
$result = $db->query($sql);
|
||||
|
||||
// check result
|
||||
if ($result == TRUE) {
|
||||
echo 'OK';
|
||||
} else {
|
||||
echo 'KO';
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Status Where conditions
|
||||
//------------------------------------------------------------------------------
|
||||
function getDeviceCondition ($deviceStatus) {
|
||||
switch ($deviceStatus) {
|
||||
case 'all': return 'WHERE devIsArchived=0'; break;
|
||||
case 'my': return 'WHERE devIsArchived=0'; break;
|
||||
case 'connected': return 'WHERE devIsArchived=0 AND devPresentLastScan=1'; break;
|
||||
case 'favorites': return 'WHERE devIsArchived=0 AND devFavorite=1'; break;
|
||||
case 'new': return 'WHERE devIsArchived=0 AND devIsNew=1'; break;
|
||||
case 'down': return 'WHERE devIsArchived=0 AND devAlertDown !=0 AND devPresentLastScan=0'; break;
|
||||
case 'archived': return 'WHERE devIsArchived=1'; break;
|
||||
default: return 'WHERE 1=0'; break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
?>
|
||||
@@ -5,5 +5,4 @@ require dirname(__FILE__).'/../templates/globals.php';
|
||||
require dirname(__FILE__).'/db.php';
|
||||
require dirname(__FILE__).'/util.php';
|
||||
require dirname(__FILE__).'/../templates/language/lang.php';
|
||||
require dirname(__FILE__).'/utilNotification.php';
|
||||
?>
|
||||
|
||||
@@ -1,209 +0,0 @@
|
||||
<?php
|
||||
|
||||
// 🔺----- API ENDPOINTS SUPERSEDED -----🔺
|
||||
// check server/api_server/api_server_start.py for equivalents
|
||||
// equivalent: /messaging/in-app
|
||||
// 🔺----- API ENDPOINTS SUPERSEDED -----🔺
|
||||
|
||||
require dirname(__FILE__).'/../templates/globals.php';
|
||||
|
||||
function get_notification_store_path(): string {
|
||||
$apiRoot = getenv('NETALERTX_API') ?: '/tmp/api';
|
||||
return rtrim($apiRoot, '/') . '/user_notifications.json';
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// check if authenticated
|
||||
require_once $_SERVER['DOCUMENT_ROOT'] . '/php/templates/security.php';
|
||||
|
||||
// ----------------------------------------------------------------------------------------
|
||||
// Check if the action parameter is set in the GET request
|
||||
if (isset($_GET['action'])) {
|
||||
// Collect GUID if provided
|
||||
$guid = isset($_GET['guid']) ? $_GET['guid'] : null;
|
||||
|
||||
// Perform the appropriate action based on the action parameter
|
||||
switch ($_GET['action']) {
|
||||
case 'write_notification':
|
||||
// Call the write_notification function with content and level parameters
|
||||
if (isset($_GET['content'])) {
|
||||
$content = $_GET['content'];
|
||||
$level = isset($_GET['level']) ? $_GET['level'] : "interrupt";
|
||||
write_notification($content, $level);
|
||||
}
|
||||
break;
|
||||
case 'remove_notification':
|
||||
// Call the remove_notification function with guid parameter
|
||||
if ($guid) {
|
||||
remove_notification($guid);
|
||||
}
|
||||
break;
|
||||
case 'mark_notification_as_read':
|
||||
// Call the mark_notification_as_read function with guid parameter
|
||||
if ($guid) {
|
||||
mark_notification_as_read($guid);
|
||||
}
|
||||
break;
|
||||
case 'notifications_clear':
|
||||
// Call the notifications_clear function
|
||||
notifications_clear();
|
||||
break;
|
||||
case 'notifications_mark_all_read':
|
||||
// Call the notifications_mark_all_read function
|
||||
notifications_mark_all_read();
|
||||
break;
|
||||
case 'get_unread_notifications':
|
||||
// Call the get_unread_notifications function
|
||||
get_unread_notifications();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------------
|
||||
// Generates a random GUID
|
||||
function generate_guid() {
|
||||
if (function_exists('com_create_guid') === true) {
|
||||
return trim(com_create_guid(), '{}');
|
||||
}
|
||||
return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X',
|
||||
mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535),
|
||||
mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535),
|
||||
mt_rand(0, 65535), mt_rand(0, 65535));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------------
|
||||
// Logs a notification in in-app notification system
|
||||
function write_notification($content, $level = "interrupt") {
|
||||
$NOTIFICATION_API_FILE = get_notification_store_path();
|
||||
|
||||
// Generate GUID
|
||||
$guid = generate_guid();
|
||||
|
||||
// Generate timestamp
|
||||
$timestamp = (new DateTime('now'))->format('Y-m-d H:i:s');
|
||||
|
||||
// Escape content to prevent breaking JSON
|
||||
$escaped_content = json_encode($content);
|
||||
|
||||
// Prepare notification array
|
||||
$notification = array(
|
||||
'timestamp' => $timestamp,
|
||||
'guid' => $guid,
|
||||
'read' => 0,
|
||||
'level'=> $level,
|
||||
'content' => $escaped_content,
|
||||
);
|
||||
|
||||
// Read existing notifications
|
||||
$notifications = json_decode(file_get_contents($NOTIFICATION_API_FILE), true);
|
||||
|
||||
// Add new notification
|
||||
$notifications[] = $notification;
|
||||
|
||||
// Write notifications to file
|
||||
file_put_contents($NOTIFICATION_API_FILE, json_encode($notifications));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------------
|
||||
// Removes a notification based on GUID
|
||||
function remove_notification($guid) {
|
||||
$NOTIFICATION_API_FILE = get_notification_store_path();
|
||||
|
||||
// Read existing notifications
|
||||
$notifications = json_decode(file_get_contents($NOTIFICATION_API_FILE), true);
|
||||
|
||||
// Filter out the notification with the specified GUID
|
||||
$filtered_notifications = array_filter($notifications, function($notification) use ($guid) {
|
||||
return $notification['guid'] !== $guid;
|
||||
});
|
||||
|
||||
// Write filtered notifications back to file
|
||||
file_put_contents($NOTIFICATION_API_FILE, json_encode(array_values($filtered_notifications)));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------------
|
||||
// Deletes all notifications
|
||||
function notifications_clear() {
|
||||
$NOTIFICATION_API_FILE = get_notification_store_path();
|
||||
|
||||
// Clear notifications by writing an empty array to the file
|
||||
file_put_contents($NOTIFICATION_API_FILE, json_encode(array()));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------------
|
||||
// Mark a notification read based on GUID
|
||||
function mark_notification_as_read($guid) {
|
||||
$NOTIFICATION_API_FILE = get_notification_store_path();
|
||||
$max_attempts = 3;
|
||||
$attempts = 0;
|
||||
|
||||
do {
|
||||
// Check if the file exists and is readable
|
||||
if (file_exists($NOTIFICATION_API_FILE) && is_readable($NOTIFICATION_API_FILE)) {
|
||||
// Attempt to read existing notifications
|
||||
$notifications = json_decode(file_get_contents($NOTIFICATION_API_FILE), true);
|
||||
|
||||
// Check if reading was successful
|
||||
if ($notifications !== null) {
|
||||
// Iterate over notifications to find the one with the specified GUID
|
||||
foreach ($notifications as &$notification) {
|
||||
if ($notification['guid'] === $guid) {
|
||||
// Mark the notification as read
|
||||
$notification['read'] = 1;
|
||||
break;
|
||||
} elseif ($guid == null) // no guid given, mark all read
|
||||
{
|
||||
$notification['read'] = 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Write updated notifications back to file
|
||||
file_put_contents($NOTIFICATION_API_FILE, json_encode($notifications));
|
||||
return; // Exit the function after successful operation
|
||||
}
|
||||
}
|
||||
|
||||
// Increment the attempt count
|
||||
$attempts++;
|
||||
|
||||
// Sleep for a short duration before retrying
|
||||
usleep(500000); // Sleep for 0.5 seconds (500,000 microseconds) before retrying
|
||||
|
||||
} while ($attempts < $max_attempts);
|
||||
|
||||
// If maximum attempts reached or file reading failed, handle the error
|
||||
echo "Failed to read notification file after $max_attempts attempts.";
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------------
|
||||
function notifications_mark_all_read() {
|
||||
mark_notification_as_read(null);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------------
|
||||
function get_unread_notifications() {
|
||||
$NOTIFICATION_API_FILE = get_notification_store_path();
|
||||
|
||||
// Read existing notifications
|
||||
if (file_exists($NOTIFICATION_API_FILE) && is_readable($NOTIFICATION_API_FILE)) {
|
||||
$notifications = json_decode(file_get_contents($NOTIFICATION_API_FILE), true);
|
||||
|
||||
if ($notifications !== null) {
|
||||
// Filter unread notifications
|
||||
$unread_notifications = array_filter($notifications, function($notification) {
|
||||
return $notification['read'] === 0;
|
||||
});
|
||||
|
||||
// Return unread notifications as JSON
|
||||
header('Content-Type: application/json');
|
||||
echo json_encode(array_values($unread_notifications));
|
||||
} else {
|
||||
echo json_encode([]);
|
||||
}
|
||||
} else {
|
||||
echo json_encode([]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
?>
|
||||
Reference in New Issue
Block a user