FE+BE: cleanup

Signed-off-by: jokob-sk <jokob.sk@gmail.com>
This commit is contained in:
jokob-sk
2025-12-18 17:16:17 +11:00
parent 70c65a17b3
commit 5cd4139d01
11 changed files with 382 additions and 616 deletions

View File

@@ -308,6 +308,7 @@
const apiToken = getSetting("API_TOKEN"); // dynamic token
const host = window.location.hostname;
const protocol = window.location.protocol;
const port = getSetting("GRAPHQL_PORT");
mac = $('#NEWDEV_devMac').val();
@@ -356,7 +357,7 @@
$.ajax({
url: "http://" + host + ":" + port + "/device/" + encodeURIComponent(mac),
url: `${protocol}//${host}:${port}/device/${encodeURIComponent(mac)}`,
type: "POST",
headers: {
"Authorization": "Bearer " + apiToken,

View File

@@ -6,7 +6,7 @@
<!-- INTERNET INFO -->
<?php if ($_REQUEST["mac"] == "Internet") { ?>
<h4 class=""><i class="fa-solid fa-globe"></i>
<?= lang("DevDetail_Tab_Tools_Internet_Info_Title") ?>
</h4>
@@ -25,7 +25,7 @@
<!-- COPY FROM DEVICE -->
<?php if ($_REQUEST["mac"] != "Internet") { ?>
<h4 class=""><i class="fa-solid fa-copy"></i>
<?= lang("DevDetail_Copy_Device_Title") ?>
</h4>
@@ -34,8 +34,8 @@
</h5>
<br>
<div style="width:100%; text-align: center;">
<select class="form-control"
title="<?= lang('DevDetail_Copy_Device_Tooltip');?>"
<select class="form-control"
title="<?= lang('DevDetail_Copy_Device_Tooltip');?>"
id="txtCopyFromDevice" >
<option value="lemp_loading" id="lemp_loading">Loading</option>
</select>
@@ -48,7 +48,7 @@
<!-- WAKE ON LAN - WOL -->
<?php if ($_REQUEST["mac"] != "Internet") { ?>
<h4 class=""><i class="fa-solid fa-bell"></i>
<?= lang("DevDetail_Tools_WOL_noti") ?>
</h4>
@@ -75,12 +75,12 @@
</h5>
<br>
<div style="width:100%; text-align: center;">
<button type="button"
class="btn btn-default pa-btn pa-btn-delete"
style="margin-left:0px;"
id="btnDeleteEvents"
onclick="askDeleteDeviceEvents()">
<?= lang('DevDetail_button_DeleteEvents');?>
<button type="button"
class="btn btn-default pa-btn pa-btn-delete"
style="margin-left:0px;"
id="btnDeleteEvents"
onclick="askDeleteDeviceEvents()">
<?= lang('DevDetail_button_DeleteEvents');?>
</button>
<br>
<div id="wol_output" style="margin-top: 10px;"></div>
@@ -88,19 +88,19 @@
<!-- Reset Custom Proprties -->
<h4 class=""><i class="fa-solid fa-list"></i>
<?= lang("DevDetail_CustomProperties_Title") ?>
<?= lang("DevDetail_CustomProperties_Title") ?>
</h4>
<h5 class="">
<?= lang("DevDetail_CustomProps_reset_info") ?>
</h5>
<br>
<div style="width:100%; text-align: center;">
<button type="button"
class="btn btn-default pa-btn pa-btn-delete"
style="margin-left:0px;"
id="btnDeleteEvents"
onclick="askResetDeviceProps()">
<?= lang("Gen_Reset") ?>
<button type="button"
class="btn btn-default pa-btn pa-btn-delete"
style="margin-left:0px;"
id="btnDeleteEvents"
onclick="askResetDeviceProps()">
<?= lang("Gen_Reset") ?>
</button>
<br>
<div id="wol_output" style="margin-top: 10px;"></div>
@@ -159,11 +159,11 @@
<div id="nslookupoutput" style="margin-top: 10px;"></div>
</div>
<?php } ?>
<?php } ?>
<!-- NMAP SCANS -->
<h4 class=""><i class="fa-solid fa-ethernet"></i>
<?= lang("DevDetail_Nmap_Scans") ?>
<?= lang("DevDetail_Nmap_Scans") ?>
</h4>
<div style="width:100%; text-align: center;">
<div>
@@ -210,66 +210,195 @@
<div id="scanoutput" style="margin-top: 30px;"></div>
<script>
// ----------------------------------------------------------------
const protocol = window.location.protocol;
const host = window.location.hostname;
const port = getSetting("GRAPHQL_PORT");
const apiToken = getSetting("API_TOKEN");
// ----------------------------------------------------------------
function manualnmapscan(targetip, mode) {
$( "#scanoutput" ).empty();
$.ajax({
method: "POST",
url: "./php/server/nmap_scan.php",
data: { scan: targetip, mode: mode },
beforeSend: function() { $('#scanoutput').addClass("ajax_scripts_loading"); },
complete: function() { $('#scanoutput').removeClass("ajax_scripts_loading"); },
success: function(data, textStatus) {
// console.log(data);
$("#scanoutput").html(data);
$("#scanoutput").empty();
const baseUrl = `${protocol}//${host}:${port}`;
$.ajax({
method: "POST",
url: `${baseUrl}/nettools/nmap`,
contentType: "application/json",
dataType: "json",
data: JSON.stringify({
scan: targetip,
mode: mode
}),
headers: {
"Authorization": "Bearer " + apiToken
},
beforeSend: function() {
$('#scanoutput').addClass("ajax_scripts_loading");
},
complete: function() {
$('#scanoutput').removeClass("ajax_scripts_loading");
},
success: function(resp) {
if (!resp.success) {
$("#scanoutput").text(resp.error || resp.message || "nmap scan failed");
return;
}
})
// Format output lines into HTML
const html = resp.output.map(line => `<div>${line}</div>`).join("");
$("#scanoutput").html(`<pre>` + html + `</pre>`);
},
error: function() {
$("#scanoutput").text("Request to nmap scan endpoint failed");
}
});
}
// ----------------------------------------------------------------
function speedtestcli() {
$( "#speedtestoutput" ).empty();
$.ajax({
method: "POST",
url: "./php/server/speedtestcli.php",
beforeSend: function() { $('#speedtestoutput').addClass("ajax_scripts_loading"); },
complete: function() { $('#speedtestoutput').removeClass("ajax_scripts_loading"); },
success: function(data, textStatus) {
$("#speedtestoutput").html(data);
$.ajax({
method: "GET",
url: `${protocol}//${host}:${port}/nettools/speedtest`,
headers: {
"Authorization": "Bearer " + apiToken,
"Content-Type": "application/json"
},
dataType: "json",
beforeSend: function () {
$('#speedtestoutput').addClass("ajax_scripts_loading");
},
complete: function () {
$('#speedtestoutput').removeClass("ajax_scripts_loading");
},
success: function (resp) {
if (!resp || resp.success !== true) {
$("#speedtestoutput").text(
resp?.error || "Speedtest failed"
);
return;
}
})
// Render output lines safely
const html = resp.output
.map(line => `<div>${$('<div>').text(line).html()}</div>`)
.join("");
$("#speedtestoutput").html(`<pre>` + html + `</pre>`);
},
error: function (xhr) {
$("#speedtestoutput").text(
xhr.responseJSON?.error || "Speedtest request failed"
);
}
});
}
// ----------------------------------------------------------------
function traceroute() {
$( "#tracerouteoutput" ).empty();
$.ajax({
method: "GET",
url: "./php/server/traceroute.php?action=get&ip=" + getDevDataByMac(getMac(), 'devLastIP') + "",
beforeSend: function() { $('#tracerouteoutput').addClass("ajax_scripts_loading"); },
complete: function() { $('#tracerouteoutput').removeClass("ajax_scripts_loading"); },
success: function(data, textStatus) {
$("#tracerouteoutput").html(data);
$("#tracerouteoutput").empty();
const ip = getDevDataByMac(getMac(), "devLastIP");
$.ajax({
method: "POST",
url: `${protocol}//${host}:${port}/nettools/traceroute`,
headers: {
"Authorization": "Bearer " + apiToken,
"Content-Type": "application/json"
},
dataType: "json",
data: JSON.stringify({
devLastIP: ip
}),
beforeSend: function () {
$('#tracerouteoutput').addClass("ajax_scripts_loading");
},
complete: function () {
$('#tracerouteoutput').removeClass("ajax_scripts_loading");
},
success: function (resp) {
if (!resp || resp.success !== true) {
$("#tracerouteoutput").text(
resp?.error || resp?.message || "Traceroute failed"
);
return;
}
})
const html = resp.output
.map(line => `<div>${$('<div>').text(line).html()}</div>`)
.join("");
$("#tracerouteoutput").html(`<pre>` + html + `</pre>`);
},
error: function (xhr) {
$("#tracerouteoutput").text(
xhr.responseJSON?.error || "Traceroute request failed"
);
}
});
}
// ----------------------------------------------------------------
function nslookup() {
$( "#nslookupoutput" ).empty();
$.ajax({
method: "GET",
url: "./php/server/nslookup.php?action=get&ip=" + getDevDataByMac(getMac(), 'devLastIP') + "",
beforeSend: function() { $('#nslookupoutput').addClass("ajax_scripts_loading"); },
complete: function() { $('#nslookupoutput').removeClass("ajax_scripts_loading"); },
success: function(data, textStatus) {
$("#nslookupoutput").html(data);
$("#nslookupoutput").empty();
$.ajax({
method: "POST",
url: `${protocol}//${host}:${port}/nettools/nslookup`,
headers: {
"Authorization": "Bearer " + apiToken,
"Content-Type": "application/json"
},
contentType: "application/json",
dataType: "json",
data: JSON.stringify({
devLastIP: getDevDataByMac(getMac(), 'devLastIP')
}),
beforeSend: function () {
$('#nslookupoutput').addClass("ajax_scripts_loading");
},
complete: function () {
$('#nslookupoutput').removeClass("ajax_scripts_loading");
},
success: function (resp) {
if (!resp.success) {
$("#nslookupoutput").text(resp.error || "nslookup failed");
return;
}
})
// Render output lines safely
const html = resp.output
.map(line => `<div>${$('<div>').text(line).html()}</div>`)
.join("");
$("#nslookupoutput").html(`<pre>` + html + `</pre>`);
},
error: function () {
$("#nslookupoutput").text("Request failed");
}
});
}
// ----------------------------------------------------------------
@@ -306,41 +435,98 @@
.text(device.devName);
$select.append(option);
});
}
// ----------------------------------------------------------------
function wakeonlan() {
macAddress = getMac();
// Execute
$.get('php/server/devices.php?action=wakeonlan&'
+ '&mac=' + macAddress
+ '&ip=' + getDevDataByMac(macAddress, "devLastIP")
, function(msg) {
showMessage (msg);
const macAddress = getMac();
const ipAddress = getDevDataByMac(macAddress, "devLastIP");
$.ajax({
method: "POST",
url: `${protocol}//${host}:${port}/nettools/wakeonlan`,
headers: {
"Authorization": "Bearer " + apiToken,
"Content-Type": "application/json"
},
contentType: "application/json",
dataType: "json",
data: JSON.stringify({
devMac: macAddress,
devLastIP: ipAddress
}),
beforeSend: function () {
$('#woloutput').addClass("ajax_scripts_loading");
},
complete: function () {
$('#woloutput').removeClass("ajax_scripts_loading");
},
success: function (resp) {
if (!resp.success) {
showMessage(resp.error || resp.message || "Wake-on-LAN failed");
return;
}
// Prefer human message, fallback to command output
showMessage(resp.message || resp.output || "WOL packet sent");
},
error: function () {
showMessage("Wake-on-LAN request failed");
}
});
}
// ------------------------------------------------------------
function copyFromDevice() {
macAddress = getMac();
// Execute
$.get('php/server/devices.php?action=copyFromDevice&'
+ '&macTo=' + macAddress
+ '&macFrom=' + $('#txtCopyFromDevice').val()
, function(msg) {
showMessage (msg);
setTimeout(function() {
const macTo = getMac();
const macFrom = $('#txtCopyFromDevice').val();
$.ajax({
method: "POST",
url: `${protocol}//${host}:${port}/device/copy`,
headers: {
"Authorization": "Bearer " + apiToken,
"Content-Type": "application/json"
},
contentType: "application/json",
dataType: "json",
data: JSON.stringify({
macFrom: macFrom,
macTo: macTo
}),
beforeSend: function () {
$('#copyDeviceOutput').addClass("ajax_scripts_loading");
},
complete: function () {
$('#copyDeviceOutput').removeClass("ajax_scripts_loading");
},
success: function (resp) {
if (!resp.success) {
showMessage(resp.error || resp.message || "Failed to copy device");
return;
}
showMessage(resp.message || "Device copied successfully");
// Reload page after short delay
setTimeout(function () {
window.location.reload();
}, 2000);
},
error: function () {
showMessage("Device copy request failed");
}
});
}
// ------------------------------------------------------------
@@ -348,7 +534,7 @@
{
// Read cache (skip cookie expiry check)
devicesList = getCache('devicesListAll_JSON', true);
if (devicesList != '') {
devicesList = JSON.parse (devicesList);
} else {
@@ -387,7 +573,7 @@
return;
}
// Ask delete device Events
// Ask delete device Events
showModalWarning ('<?= lang('DevDetail_button_DeleteEvents');?>', '<?= lang('DevDetail_button_DeleteEvents_Warning');?>',
'<?= lang('Gen_Cancel');?>', '<?= lang('Gen_Delete');?>', 'deleteDeviceEvents');
}
@@ -398,9 +584,38 @@
return;
}
const protocol = window.location.protocol; // "http:" or "https:"
const host = window.location.hostname; // current hostname
const port = getSetting("GRAPHQL_PORT"); // your dynamic port
const apiToken = getSetting("API_TOKEN"); // optional token if needed
// Build base URL dynamically
const baseUrl = `${protocol}//${host}:${port}`;
// Delete device events
$.get('php/server/devices.php?action=deleteDeviceEvents&mac='+ mac, function(msg) {
showMessage (msg);
$.ajax({
method: "DELETE",
url: `${baseUrl}/device/${encodeURIComponent(mac)}/events/delete`,
headers: {
"Authorization": "Bearer " + apiToken
},
dataType: "json",
beforeSend: function () {
$('#deviceEventsOutput').addClass("ajax_scripts_loading");
},
complete: function () {
$('#deviceEventsOutput').removeClass("ajax_scripts_loading");
},
success: function (resp) {
if (!resp.success) {
showMessage(resp.error || resp.message || "Failed to delete device events");
return;
}
showMessage("Device events deleted successfully");
},
error: function () {
showMessage("Request to delete device events failed");
}
});
}
@@ -411,39 +626,88 @@
return;
}
// Ask Resert Custom properties
// Ask Resert Custom properties
showModalWarning ('<?= lang('Gen_Reset');?>', '<?= lang('DevDetail_CustomProps_reset_info');?>',
'<?= lang('Gen_Cancel');?>', '<?= lang('Gen_Delete');?>', 'resetDeviceProps');
}
function resetDeviceProps () {
const mac = getMac(); // or the device MAC you want to reset
// Check MAC
if (mac == '') {
return;
}
// Execute
$.get('php/server/devices.php?action=resetDeviceProps&mac='+ mac, function(msg) {
showMessage (msg);
const baseUrl = `${protocol}//${host}:${port}`;
$.ajax({
method: "POST",
url: `${baseUrl}/device/${encodeURIComponent(mac)}/reset-props`,
dataType: "json",
headers: {
"Authorization": "Bearer " + apiToken
},
beforeSend: function() {
$('#devicePropsOutput').addClass("ajax_scripts_loading");
},
complete: function() {
$('#devicePropsOutput').removeClass("ajax_scripts_loading");
},
success: function(resp) {
if (!resp.success) {
showMessage(resp.error || resp.message || "Failed to reset device properties");
return;
}
showMessage("Device custom properties reset successfully");
},
error: function() {
showMessage("Request to reset device properties failed");
}
});
}
// ----------------------------------------------------------------
function internetinfo() {
$( "#internetinfooutput" ).empty();
$.ajax({
method: "POST",
url: "./php/server/internetinfo.php",
beforeSend: function() { $('#internetinfooutput').addClass("ajax_scripts_loading"); },
complete: function() { $('#internetinfooutput').removeClass("ajax_scripts_loading"); },
success: function(data, textStatus) {
$("#internetinfooutput").html(data);
$("#internetinfooutput").empty();
$.ajax({
method: "GET",
url: `${protocol}//${host}:${port}/nettools/internetinfo`,
headers: {
"Authorization": "Bearer " + apiToken,
"Content-Type": "application/json"
},
dataType: "json",
beforeSend: function () {
$('#internetinfooutput').addClass("ajax_scripts_loading");
},
complete: function () {
$('#internetinfooutput').removeClass("ajax_scripts_loading");
},
success: function (resp) {
if (!resp.success) {
$("#internetinfooutput").text(
resp.error || resp.message || "Failed to fetch internet info"
);
return;
}
})
const html = Object.entries(resp.output)
.map(([k, v]) => `<div><strong>${k}</strong>: ${v}</div>`)
.join("");
$("#internetinfooutput").html(`<pre>` + html + `</pre>`);
},
error: function () {
$("#internetinfooutput").text("Internet info request failed");
}
});
}
// init first time
// -----------------------------------------------------------
// -----------------------------------------------------------
var toolsPageInitialized = false;
function initDeviceToolsPage()
@@ -474,6 +738,6 @@
}
// start updater
deviceToolsPageUpdater();
deviceToolsPageUpdater();
</script>

View File

@@ -31,7 +31,7 @@
$action = $_REQUEST['action'];
switch ($action) {
// check server/api_server/api_server_start.py for equivalents
case 'getServerDeviceData': getServerDeviceData(); break; // equivalent: get_device_data
case 'getServerDeviceData': getServerDeviceData(); break; // equivalent: get_device_data
case 'deleteDevice': deleteDevice(); break; // equivalent: delete_device(mac)
case 'deleteAllWithEmptyMACs': deleteAllWithEmptyMACs(); break; // equivalent: delete_all_with_empty_macs
@@ -41,7 +41,7 @@
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 'resetDeviceProps': resetDeviceProps(); break; // equivalent: reset_device_props
case 'ExportCSV': ExportCSV(); break; // equivalent: export_devices
case 'ImportCSV': ImportCSV(); break; // equivalent: import_csv
@@ -50,9 +50,6 @@
case 'updateNetworkLeaf': updateNetworkLeaf(); break; // equivalent: update_device_column(mac, column_name, column_value)
case 'copyFromDevice': copyFromDevice(); break; // equivalent: copy_device(mac_from, mac_to)
case 'wakeonlan': wakeonlan(); break; // equivalent: wakeonlan
default: logServerConsole ('Action: '. $action); break; // equivalent:
}
}
@@ -202,149 +199,6 @@ function getServerDeviceData() {
}
//------------------------------------------------------------------------------
// Update Device Data
//------------------------------------------------------------------------------
function setDeviceData() {
global $db;
// Sanitize input
$mac = quotes($_POST['mac']);
$name = urldecode(quotes($_POST['name']));
$owner = urldecode(quotes($_POST['owner']));
$type = urldecode(quotes($_POST['type']));
$vendor = urldecode(quotes($_POST['vendor']));
$icon = urldecode(quotes($_POST['icon']));
$favorite = quotes($_POST['favorite']);
$group = urldecode(quotes($_POST['group']));
$location = urldecode(quotes($_POST['location']));
$comments = urldecode(quotes($_POST['comments']));
$parentMac = quotes($_POST['networknode']);
$parentPort = quotes($_POST['networknodeport']);
$ssid = urldecode(quotes($_POST['ssid']));
$site = quotes($_POST['networksite']);
$staticIP = quotes($_POST['staticIP']);
$scancycle = quotes($_POST['scancycle']);
$alertevents = quotes($_POST['alertevents']);
$alertdown = quotes($_POST['alertdown']);
$relType = quotes($_POST['relType']);
$reqNics = quotes($_POST['reqNics']);
$skiprepeated = quotes($_POST['skiprepeated']);
$newdevice = quotes($_POST['newdevice']);
$archived = quotes($_POST['archived']);
$devFirstConnection = quotes($_POST['devFirstConnection']);
$devLastConnection = quotes($_POST['devLastConnection']);
$ip = quotes($_POST['ip']);
$devCustomProps = quotes($_POST['devCustomProps']);
$createNew = quotes($_POST['createNew']);
$devNewGuid = generateGUID();
// An update
if ($_POST['createNew'] == 0) {
// UPDATE SQL query
$sql = "UPDATE Devices SET
devName = '$name',
devOwner = '$owner',
devType = '$type',
devVendor = '$vendor',
devIcon = '$icon',
devFavorite = '$favorite',
devGroup = '$group',
devLocation = '$location',
devComments = '$comments',
devParentMAC = '$parentMac',
devParentPort = '$parentPort',
devSSID = '$ssid',
devSite = '$site',
devStaticIP = '$staticIP',
devScan = '$scancycle',
devAlertEvents = '$alertevents',
devAlertDown = '$alertdown',
devParentRelType = '$relType',
devReqNicsOnline = '$reqNics',
devSkipRepeated = '$skiprepeated',
devIsNew = '$newdevice',
devIsArchived = '$archived',
devCustomProps = '$devCustomProps'
WHERE devMac = '$mac'";
} else { // An INSERT
$sql = "INSERT INTO Devices (
devMac,
devName,
devOwner,
devType,
devVendor,
devIcon,
devFavorite,
devGroup,
devLocation,
devComments,
devParentMAC,
devParentPort,
devSSID,
devSite,
devStaticIP,
devScan,
devAlertEvents,
devAlertDown,
devParentRelType,
devReqNicsOnline,
devSkipRepeated,
devIsNew,
devIsArchived,
devLastConnection,
devFirstConnection,
devLastIP,
devGUID,
devCustomProps,
devSourcePlugin
) VALUES (
'$mac',
'$name',
'$owner',
'$type',
'$vendor',
'$icon',
'$favorite',
'$group',
'$location',
'$comments',
'$parentMac',
'$parentPort',
'$ssid',
'$site',
'$staticIP',
'$scancycle',
'$alertevents',
'$alertdown',
'$relType',
'$reqNics',
'$skiprepeated',
'$newdevice',
'$archived',
'$devLastConnection',
'$devFirstConnection',
'$ip',
'$devNewGuid',
'$devCustomProps',
'DUMMY'
)";
}
// Execute the query
$result = $db->query($sql);
// Check the result
if ($result == TRUE) {
echo lang('BackDevices_DBTools_UpdDev');
} else {
echo lang('BackDevices_DBTools_UpdDevError')."\n\n$sql \n\n". $db->lastErrorMsg();
}
}
//------------------------------------------------------------------------------
// Delete Device
//------------------------------------------------------------------------------
@@ -421,25 +275,6 @@ function deleteDeviceEvents() {
}
}
//------------------------------------------------------------------------------
// Delete Device Properties
//------------------------------------------------------------------------------
function resetDeviceProps() {
global $db;
// sql
$sql = 'UPDATE Devices set devCustomProps = "'.getSettingValue("NEWDEV_devCustomProps").'" WHERE devMac="' . $_REQUEST['mac'] .'"';
// execute sql
$result = $db->query($sql);
// check result
if ($result == TRUE) {
echo lang('Gen_Okay');
} else {
echo lang('Gen_Error')."\n\n$sql \n\n". $db->lastErrorMsg();
}
}
//------------------------------------------------------------------------------
// Delete all devices
@@ -767,69 +602,6 @@ function updateNetworkLeaf()
}
//------------------------------------------------------------------------------
// Wake-on-LAN
// Inspired by @leiweibau: https://github.com/leiweibau/Pi.Alert/commit/30427c7fea180670c71a2b790699e5d9e9e88ffd
//------------------------------------------------------------------------------
function wakeonlan() {
$WOL_HOST_IP = $_REQUEST['ip'];
$WOL_HOST_MAC = $_REQUEST['mac'];
if (!filter_var($WOL_HOST_IP, FILTER_VALIDATE_IP)) {
echo "Invalid IP! ". lang('BackDevDetail_Tools_WOL_error'); exit;
}
elseif (!filter_var($WOL_HOST_MAC, FILTER_VALIDATE_MAC)) {
echo "Invalid MAC! ". lang('BackDevDetail_Tools_WOL_error'); exit;
}
exec('wakeonlan '.$WOL_HOST_MAC , $output);
echo lang('BackDevDetail_Tools_WOL_okay');
}
//------------------------------------------------------------------------------
// Copy from device
//------------------------------------------------------------------------------
function copyFromDevice() {
$MAC_FROM = $_REQUEST['macFrom'];
$MAC_TO = $_REQUEST['macTo'];
global $db;
// clean-up temporary table
$sql = "DROP TABLE IF EXISTS temp_devices ";
$result = $db->query($sql);
// create temporary table with the source data
$sql = "CREATE TABLE temp_devices AS SELECT * FROM Devices WHERE devMac = '". $MAC_FROM . "';";
$result = $db->query($sql);
// update temporary table with the correct target MAC
$sql = "UPDATE temp_devices SET devMac = '". $MAC_TO . "';";
$result = $db->query($sql);
// delete previous entry
$sql = "DELETE FROM Devices WHERE devMac = '". $MAC_TO . "';";
$result = $db->query($sql);
// insert new entry with the correct target MAC from the temporary table
$sql = "INSERT INTO Devices SELECT * FROM temp_devices WHERE devMac = '".$MAC_TO."'";
$result = $db->query($sql);
// clean-up temporary table
$sql = "DROP TABLE temp_devices ";
$result = $db->query($sql);
// check result
if ($result == TRUE) {
echo 'OK';
} else {
echo lang('BackDevices_Device_UpdDevError');
}
}
//------------------------------------------------------------------------------
// Status Where conditions

View File

@@ -1,59 +0,0 @@
<?php
###################################################################################
# NetAlertX #
# Open Source Network Guard / WIFI & LAN intrusion detector #
# #
# internetinfo.php # Front module. Server side. System Information #
###################################################################################
# Puche 2021 pi.alert.application@gmail.com GNU GPLv3 #
# jokob#sk 2022 jokob.sk@gmail.com GNU GPLv3 #
# leiweibau 2022 https://github.com/leiweibau GNU GPLv3 #
# cvc90 2023 https://github.com/cvc90 GNU GPLv3 #
###################################################################################
// 🔺----- API ENDPOINTS SUPERSEDED -----🔺
// check server/api_server/api_server_start.py for equivalents
// equivalent: /nettools
// 🔺----- API ENDPOINTS SUPERSEDED -----🔺
// Get init.php
require dirname(__FILE__).'/../server/init.php';
//------------------------------------------------------------------------------
// check if authenticated
require_once $_SERVER['DOCUMENT_ROOT'] . '/php/templates/security.php';
// Perform a test with the PING command
$output = shell_exec("curl ipinfo.io");
// Check if there is error
if (!isset($output) || empty($output)) {
// Error message
$output = lang('DevDetail_Tab_Tool_Internet_Info_Error');
// Show the result
echo "<pre>";
echo $output;
echo "</pre>";
exit;
}
// Replace "{" with ""
$output = str_replace("{", "", $output);
// Replace "}" with ""
$output = str_replace("}", "", $output);
// Replace "," with ""
$output = str_replace(",", "", $output);
// Replace '"' with ""
$output = str_replace('"', "", $output);
// Show the result
echo "<pre>";
echo $output;
echo "</pre>";
?>

View File

@@ -1,44 +0,0 @@
<?php
// 🔺----- API ENDPOINTS SUPERSEDED -----🔺
// check server/api_server/api_server_start.py for equivalents
// equivalent: /nettools
// 🔺----- API ENDPOINTS SUPERSEDED -----🔺
require 'util.php';
//------------------------------------------------------------------------------
// check if authenticated
require_once $_SERVER['DOCUMENT_ROOT'] . '/php/templates/security.php';
$PIA_HOST_IP = $_REQUEST['scan'];
$PIA_SCAN_MODE = $_REQUEST['mode'];
if(filter_var($PIA_HOST_IP, FILTER_VALIDATE_IP)) // Vulnerability fix v22.12.20
{
if ($PIA_SCAN_MODE == 'fast') {
exec('nmap -F '.$PIA_HOST_IP, $output);
} elseif ($PIA_SCAN_MODE == 'normal') {
exec('nmap '.$PIA_HOST_IP, $output);
} elseif ($PIA_SCAN_MODE == 'detail') {
exec('nmap -A '.$PIA_HOST_IP, $output);
} elseif ($PIA_SCAN_MODE == 'skipdiscovery') {
exec('nmap -Pn '.$PIA_HOST_IP, $output);
}
$message = '<h4>Scan ('.$PIA_SCAN_MODE.') Results of: '.$PIA_HOST_IP.'</h4><br/>'
.'<pre style="border: none;">';
foreach($output as $line){
$message = $message .$line . "<br/>";
}
$message = $message .'</pre>';
displayMessage($message, $logAlert = FALSE, $logConsole = TRUE, $logFile = TRUE, $logEcho = TRUE);
} else
{
echo '<h4>Internal error.</h4>';
}

View File

@@ -1,50 +0,0 @@
<?php
###################################################################################
# NetAlertX #
# Open Source Network Guard / WIFI & LAN intrusion detector #
# #
# nslookup.php # Front module. Server side. System Information #
###################################################################################
# Puche 2021 pi.alert.application@gmail.com GNU GPLv3 #
# jokob#sk 2022 jokob.sk@gmail.com GNU GPLv3 #
# leiweibau 2022 https://github.com/leiweibau GNU GPLv3 #
# cvc90 2023 https://github.com/cvc90 GNU GPLv3 #
###################################################################################
// 🔺----- API ENDPOINTS SUPERSEDED -----🔺
// check server/api_server/api_server_start.py for equivalents
// equivalent: /nettools
// 🔺----- API ENDPOINTS SUPERSEDED -----🔺
// Get init.php
require dirname(__FILE__).'/../server/init.php';
//------------------------------------------------------------------------------
// check if authenticated
require_once $_SERVER['DOCUMENT_ROOT'] . '/php/templates/security.php';
// Get IP
$ip = $_GET['ip'];
// Check if IP is valid
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
// Error message
$output = lang('DevDetail_Tab_Tools_Nslookup_Error');
// Show the result
echo "<pre>";
echo $output;
echo "</pre>";
exit;
}
// Test with the "nslookup" command
$output = shell_exec("nslookup $ip");
// Show the result
echo "<pre>";
echo $output;
echo "</pre>";
?>

View File

@@ -1,56 +0,0 @@
<?php
require dirname(__FILE__).'/../server/init.php';
// 🔺----- API ENDPOINTS SUPERSEDED -----🔺
// check server/api_server/api_server_start.py for equivalents
// equivalent: /nettools
// 🔺----- API ENDPOINTS SUPERSEDED -----🔺
//------------------------------------------------------------------------------
// check if authenticated
require_once $_SERVER['DOCUMENT_ROOT'] . '/php/templates/security.php';
// Prefer explicit binary paths, fall back to a sanitised PATH
$speedtestCandidates = [
'/opt/venv/bin/speedtest-cli',
'/usr/local/bin/speedtest-cli',
'/usr/bin/speedtest-cli',
];
$candidateDirs = array_unique(array_map('dirname', $speedtestCandidates));
$safePath = implode(':', $candidateDirs);
$resolvedCommand = null;
foreach ($speedtestCandidates as $candidate) {
if (is_executable($candidate)) {
$resolvedCommand = escapeshellcmd($candidate) . ' --secure --simple';
break;
}
}
$output = [];
$returnCode = 0;
if ($resolvedCommand === null) {
$resolvedCommand = 'env PATH=' . escapeshellarg($safePath) . ' speedtest-cli --secure --simple';
}
exec($resolvedCommand, $output, $returnCode);
echo '<h4>' . lang('Speedtest_Results') . '</h4>';
if ($returnCode !== 0 || empty($output)) {
$errorMessage = $returnCode === 127
? 'speedtest-cli command not found. Checked paths: ' . $safePath
: (empty($output) ? 'speedtest-cli returned no output.' : implode("\n", $output));
echo '<div class="alert alert-danger">' . htmlspecialchars('Speedtest failed: ' . $errorMessage, ENT_QUOTES, 'UTF-8') . '</div>';
return;
}
echo '<pre style="border: none;">';
foreach ($output as $line) {
echo htmlspecialchars($line, ENT_QUOTES, 'UTF-8') . "\n";
}
echo '</pre>';
?>

View File

@@ -1,51 +0,0 @@
<?php
###################################################################################
# NetAlertX #
# Open Source Network Guard / WIFI & LAN intrusion detector #
# #
# traceroute.php # Front module. Server side. System Information #
###################################################################################
# Puche 2021 pi.alert.application@gmail.com GNU GPLv3 #
# jokob-sk 2022 jokob.sk@gmail.com GNU GPLv3 #
# leiweibau 2022 https://github.com/leiweibau GNU GPLv3 #
# cvc90 2023 https://github.com/cvc90 GNU GPLv3 #
###################################################################################
// 🔺----- API ENDPOINTS SUPERSEDED -----🔺
// check server/api_server/api_server_start.py for equivalents
// equivalent: /nettools
// 🔺----- API ENDPOINTS SUPERSEDED -----🔺
// Get init.php
require dirname(__FILE__).'/../server/init.php';
//------------------------------------------------------------------------------
// check if authenticated
require_once $_SERVER['DOCUMENT_ROOT'] . '/php/templates/security.php';
// NEW ENDPOINT EQUIVALENT: /nettools/traceroute
// Get IP
$ip = $_GET['ip'];
// Check if IP is valid
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
// Error message
$output = lang('DevDetail_Tab_Tools_Traceroute_Error');
// Show the result
echo "<pre>";
echo $output;
echo "</pre>";
exit;
}
// Test with the "Traceroute" command
$output = shell_exec("traceroute $ip");
// Show the result
echo "<pre>";
echo $output;
echo "</pre>";
?>

View File

@@ -31,12 +31,6 @@ function getExternalIp() {
// Network
// ----------------------------------------------------------
// ----------------------------------------------------
// Network Stats (General)
// ----------------------------------------------------
// External IP
$externalIp = getExternalIp();
@@ -58,12 +52,9 @@ $network_referer = !empty($_SERVER['HTTP_REFERER'])
// ----------------------------------------------------
// Network Hardware Stats (FAST VERSION)
// Network Hardware Stats
// ----------------------------------------------------
// ----------------------------------------------------
// Network Stats (General)
// ----------------------------------------------------
// External IP
$externalIp = getExternalIp();
@@ -345,12 +336,13 @@ function formatDataSize(bytes) {
function loadInterfaces() {
const apiToken = getSetting("API_TOKEN");
const apiToken = getSetting("API_TOKEN");
const host = window.location.hostname;
const protocol = window.location.protocol;
const port = getSetting("GRAPHQL_PORT");
$.ajax({
url: "http://" + host + ":" + port + "/nettools/interfaces",
url: `${protocol}//${host}:${port}/nettools/interfaces`,
type: "GET",
headers: {
"Authorization": "Bearer " + apiToken,

View File

@@ -1,5 +1,6 @@
import subprocess
import re
import json
import sys
import ipaddress
import shutil
@@ -94,7 +95,7 @@ def traceroute(ip):
check=True, # Raise CalledProcessError on non-zero exit
)
# Return success response with traceroute output
return jsonify({"success": True, "output": result.stdout.strip()})
return jsonify({"success": True, "output": result.stdout.strip().splitlines()})
# --------------------------
# Step 3: Handle command errors
@@ -247,29 +248,24 @@ def internet_info():
Returns JSON with the info or error.
"""
try:
# Perform the request via curl
result = subprocess.run(
["curl", "-s", "https://ipinfo.io"],
["curl", "-s", "https://ipinfo.io/json"],
capture_output=True,
text=True,
check=True,
)
output = result.stdout.strip()
if not output:
if not result.stdout:
raise ValueError("Empty response from ipinfo.io")
# Clean up the JSON-like string by removing { } , and "
cleaned_output = (
output.replace("{", "")
.replace("}", "")
.replace(",", "")
.replace('"', "")
)
data = json.loads(result.stdout)
return jsonify({"success": True, "output": cleaned_output})
return jsonify({
"success": True,
"output": data
})
except (subprocess.CalledProcessError, ValueError) as e:
except (subprocess.CalledProcessError, ValueError, json.JSONDecodeError) as e:
return jsonify(
{
"success": False,

View File

@@ -127,7 +127,8 @@ def test_traceroute_device(client, api_token, test_mac):
data = resp.json
assert data.get("success") is True
assert "output" in data
assert isinstance(data["output"], str)
assert isinstance(data["output"], list)
assert all(isinstance(line, str) for line in data["output"])
@pytest.mark.parametrize("ip,expected_status", [
@@ -201,8 +202,8 @@ def test_internet_info_endpoint(client, api_token):
if resp.status_code == 200:
assert data.get("success") is True
assert isinstance(data.get("output"), str)
assert len(data["output"]) > 0 # ensure output is not empty
assert isinstance(data.get("output"), dict)
assert len(data["output"]) > 0 # ensure output is not empty
else:
# Handle errors, e.g., curl failure
assert data.get("success") is False