settings rewrite to JS

This commit is contained in:
Jokob-sk
2023-08-01 08:11:52 +10:00
parent 6fd750e4e1
commit 1101bc9477
5 changed files with 70 additions and 57 deletions

View File

@@ -646,6 +646,11 @@ height: 50px;
} }
} }
.settingswrap .metadata
{
display: none;
}
.table_row { .table_row {
padding: 3px; padding: 3px;
width:100%; width:100%;

View File

@@ -295,14 +295,12 @@ function saveSettings()
$txt .= $settingKey . "=" . $val . "\n"; $txt .= $settingKey . "=" . $val . "\n";
} elseif ($settingType == 'text.multiselect' || $settingType == 'subnets' || $settingType == 'list') { } elseif ($settingType == 'text.multiselect' || $settingType == 'subnets' || $settingType == 'list') {
$temp = '['; $temp = '';
echo $settingType.'<br>'; if(is_array($settingValue) == FALSE)
echo $settingKey.'<br>'; {
echo json_encode($settingValue).'<br>'; $settingValue = json_decode($settingValue);
// echo json_decode($settingValue).'<br>'; }
// json_decode($settingValue) todo
if (count($setting) > 3 && is_array($settingValue) == true) { if (count($setting) > 3 && is_array($settingValue) == true) {
foreach ($settingValue as $val) { foreach ($settingValue as $val) {
@@ -312,7 +310,7 @@ function saveSettings()
$temp = substr_replace($temp, "", -1); // remove last comma ',' $temp = substr_replace($temp, "", -1); // remove last comma ','
} }
$temp .= ']'; // close brackets $temp = '['.$temp.']'; // wrap brackets
$txt .= $settingKey . "=" . $temp . "\n"; $txt .= $settingKey . "=" . $temp . "\n";
} elseif ($settingType == 'json') { } elseif ($settingType == 'json') {
$txt .= $settingKey . "=" . $settingValue . "\n"; $txt .= $settingKey . "=" . $settingValue . "\n";
@@ -330,7 +328,7 @@ function saveSettings()
$txt = $txt."#-------------------IMPORTANT INFO-------------------#\n"; $txt = $txt."#-------------------IMPORTANT INFO-------------------#\n";
// open new file and write the new configuration // open new file and write the new configuration
$newConfig = fopen($fullConfPath.'_debug', "w") or die("Unable to open file!"); // todo $newConfig = fopen($fullConfPath, "w") or die("Unable to open file!");
fwrite($newConfig, $txt); fwrite($newConfig, $txt);
fclose($newConfig); fclose($newConfig);

View File

@@ -414,6 +414,7 @@
"Plugins_DeleteAll" : "Delete all (filters are ignored)", "Plugins_DeleteAll" : "Delete all (filters are ignored)",
"Plugins_History" : "Events History", "Plugins_History" : "Events History",
"Plugins_Filters_Mac" : "Mac Filter", "Plugins_Filters_Mac" : "Mac Filter",
"Settings_Metadata_Toggle" : "Show/hide metadata for the given setting.",
"settings_missing" : "Not all settings loaded, refresh the page! This is probably caused by a high load on the database.", "settings_missing" : "Not all settings loaded, refresh the page! This is probably caused by a high load on the database.",
"settings_missing_block" : "You can not save your settings without specifying all setting keys. Refresh the page. This is probably caused by a high load on the database.", "settings_missing_block" : "You can not save your settings without specifying all setting keys. Refresh the page. This is probably caused by a high load on the database.",
"settings_old" : "The settings in the DB (shown on this page) are outdated. This is probably caused by a running scan. The settings were saved in the <code>pialert.conf</code> file, but the background process didn not have time to import it yet to the DB. You can wait until the settings get refreshed so you do not overwrite your old values. Feel free to save your settings either way if you don not mind losing the settings between the last save and now. There are also backup files created if you need to compare your settings later.", "settings_old" : "The settings in the DB (shown on this page) are outdated. This is probably caused by a running scan. The settings were saved in the <code>pialert.conf</code> file, but the background process didn not have time to import it yet to the DB. You can wait until the settings get refreshed so you do not overwrite your old values. Feel free to save your settings either way if you don not mind losing the settings between the last save and now. There are also backup files created if you need to compare your settings later.",

View File

@@ -71,7 +71,7 @@ while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
</h1> </h1>
<div class="settingsImported"><?= lang("settings_imported");?> <span id="lastImportedTime"></span></div> <div class="settingsImported"><?= lang("settings_imported");?> <span id="lastImportedTime"></span></div>
</section> </section>
<div class="content " id='accordion_gen'> <div class="content settingswrap" id='accordion_gen'>
<!-- PLACEHOLDER --> <!-- PLACEHOLDER -->
</div> </div>
@@ -93,7 +93,6 @@ while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
?> ?>
<script> <script>
@@ -178,12 +177,22 @@ while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
if(set["Group"] == group) if(set["Group"] == group)
{ {
// hide metadata by default by assigning it a special class
const isMetadata = set['Code_Name'].includes('__metadata');
isMetadata ? metadataClass = 'metadata' : metadataClass = '';
isMetadata ? infoIcon = '' : infoIcon = `<i
my-to-toggle="row_${set['Code_Name']}__metadata"
title="${getString("Settings_Metadata_Toggle")}"
class="fa fa-circle-question pointer"
onclick="toggleMetadata(this)">
</i>` ;
setHtml += ` setHtml += `
<div class="row table_row"> <div class="row table_row ${metadataClass}" id="row_${set['Code_Name']}">
<div class="table_cell setting_name bold"> <div class="table_cell setting_name bold">
<label>${getString(set['Code_Name'] + '_name', set['Display_Name'])}</label> <label>${getString(set['Code_Name'] + '_name', set['Display_Name'])}</label>
<div class="small"> <div class="small">
<code>${set['Code_Name']}</code> <code>${set['Code_Name']}</code>${infoIcon}
</div> </div>
</div> </div>
<div class="table_cell setting_description"> <div class="table_cell setting_description">
@@ -265,7 +274,7 @@ while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
<input class="form-control" type="text" id="${set['Code_Name']}_input" placeholder="Enter value"/> <input class="form-control" type="text" id="${set['Code_Name']}_input" placeholder="Enter value"/>
</div> </div>
<div class="col-xs-3"> <div class="col-xs-3">
<button class="btn btn-primary" onclick="addList${set['Code_Name']}()">Add</button> <button class="btn btn-primary" my-input-from="${set['Code_Name']}_input" my-input-to="${set['Code_Name']}" onclick="addList(this)">Add</button>
</div> </div>
</div> </div>
<div class="form-group"> <div class="form-group">
@@ -279,7 +288,7 @@ while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
}); });
input += '</select></div>' + input += '</select></div>' +
`<div><button class="btn btn-primary" onclick="removeFromList${set['Code_Name']}()">Remove last</button></div>`; `<div><button class="btn btn-primary" my-input="${set['Code_Name']}" onclick="removeFromList(this)">Remove last</button></div>`;
} else if (set['Type'] === 'json') { } else if (set['Type'] === 'json') {
input = `<textarea class="form-control input" my-data-type="${set['Type']}" id="${set['Code_Name']}" readonly>${JSON.stringify(set['Value'], null, 2)}</textarea>`; input = `<textarea class="form-control input" my-data-type="${set['Type']}" id="${set['Code_Name']}" readonly>${JSON.stringify(set['Value'], null, 2)}</textarea>`;
} }
@@ -288,11 +297,14 @@ while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
const eventsList = createArray(set['Events']); const eventsList = createArray(set['Events']);
console.log(eventsList)
if (eventsList.length > 0) { if (eventsList.length > 0) {
eventsList.forEach(event => { eventsList.forEach(event => {
eventsHtml += `<span class="input-group-addon pointer" eventsHtml += `<span class="input-group-addon pointer"
data-myparam="${set['Code_Name']}" data-myparam="${set['Code_Name']}"
data-myevent="${event}" data-myevent="${event}"
onclick="handleEvent(this)"
> >
<i title="${getString(event + "_event_tooltip")}" class="fa ${getString(event + "_event_icon")}"> <i title="${getString(event + "_event_tooltip")}" class="fa ${getString(event + "_event_icon")}">
</i> </i>
@@ -360,35 +372,27 @@ while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
showModalOk('WARNING', "<?= lang("settings_missing")?>"); showModalOk('WARNING', "<?= lang("settings_missing")?>");
} }
<?php // ---------------------------------------------------------
// generate javascript methods to handle add and remove items to lists function addList(element)
foreach($settingKeyOfLists as $settingKey ) {
{
$addList = 'function addList'.$settingKey.'()
{
input = $("#'.$settingKey.'_input").val();
$("#'.$settingKey.'").append($("<option disabled></option>").attr("value", input).text(input));
const fromId = $(element).attr('my-input-from');
$("#'.$settingKey.'_input").val(""); const toId = $(element).attr('my-input-to');
settingsChanged();
}
';
input = $(`#${fromId}`).val();
$(`#${toId}`).append($("<option disabled></option>").attr("value", input).text(input));
// clear input
$(`#${fromId}`).val("");
$remList = 'function removeFromList'.$settingKey.'() settingsChanged();
{ }
settingsChanged(); // ---------------------------------------------------------
// $("#'.$settingKey.'").empty(); function removeFromList(element)
$("#'.$settingKey.'").find("option:last").remove(); {
}'; settingsChanged();
$(`#${$(element).attr('my-input')}`).find("option:last").remove();
echo $remList; }
echo $addList;
}
?>
// --------------------------------------------------------- // ---------------------------------------------------------
function addInterface() function addInterface()
{ {
@@ -424,15 +428,12 @@ while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
{ {
var settingsArray = []; var settingsArray = [];
// generate javascript to collect values // collect values for each of the different input form controls
const noConversion = ['text', 'integer', 'string', 'password', 'readonly', 'text.select', 'integer.select', 'text.multiselect']; const noConversion = ['text', 'integer', 'string', 'password', 'readonly', 'text.select', 'integer.select', 'text.multiselect'];
settingsJSON["data"].forEach(set => { settingsJSON["data"].forEach(set => {
if (noConversion.includes(set['Type'])) { if (noConversion.includes(set['Type'])) {
console.log($('#'+set["Code_Name"]).val())
console.log(set["Code_Name"])
settingsArray.push([set["Group"], set["Code_Name"], set["Type"], $('#'+set["Code_Name"]).val()]); settingsArray.push([set["Group"], set["Code_Name"], set["Type"], $('#'+set["Code_Name"]).val()]);
} else if (set['Type'] === 'boolean' || set['Type'] === 'integer.checkbox') { } else if (set['Type'] === 'boolean' || set['Type'] === 'integer.checkbox') {
@@ -556,17 +557,25 @@ while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// handling events on the backend initiated by the front end START // handling events on the backend initiated by the front end START
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
$(window).on('load', function() { function toggleMetadata(element)
$('span[data-myevent]').each(function(index, element){ {
$(element).attr('onclick', const id = $(element).attr('my-to-toggle');
'handleEvent(\"' + $(element).attr('data-myevent') + '|'+ $(element).attr('data-myparam') + '\")'
); $(`#${id}`).toggle();
}); }
});
// -----------------------------------------------------------------------------
// handling events on the backend initiated by the front end START
// -----------------------------------------------------------------------------
modalEventStatusId = 'modal-message-front-event' modalEventStatusId = 'modal-message-front-event'
function handleEvent (value){ function handleEvent (element){
// value has to be in format event|param. e.g. run|ENABLE_ARPSCAN
value = $(element).attr('data-myevent') + '|'+ $(element).attr('data-myparam')
setParameter ('Front_Event', value) setParameter ('Front_Event', value)
// show message // show message
@@ -585,7 +594,7 @@ while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
displayedEvent = $('#'+modalEventStatusId).html() displayedEvent = $('#'+modalEventStatusId).html()
// loop until finished // loop until finished
if(displayedEvent.indexOf('finished') == -1) // if the message is different from finished, check again in 4s if(displayedEvent.indexOf('finished') == -1) // if the message is different from finished, check again in 2s
{ {
getParam(modalEventStatusId,"Front_Event", true) getParam(modalEventStatusId,"Front_Event", true)

View File

@@ -40,12 +40,12 @@ def ccd(key, default, config_dir, name, inputtype, options, group, events=[], de
conf.mySettingsSQLsafe.append((key, name, desc, inputtype, options, regex, str(result), group, str(events))) conf.mySettingsSQLsafe.append((key, name, desc, inputtype, options, regex, str(result), group, str(events)))
# save metadata in dummy setting # save metadata in dummy setting
if '__metadata' not in key: if '__metadata' not in key:
conf.mySettingsSQLsafe.append((f'{key}__metadata', "metadata name", "metadata desc", 'json', "", "", json.dumps(setJsonMetadata), group, "")) conf.mySettingsSQLsafe.append((f'{key}__metadata', "metadata name", "metadata desc", 'json', "", "", json.dumps(setJsonMetadata), group, []))
conf.mySettings.append((key, name, desc, inputtype, options, regex, result, group, str(events))) conf.mySettings.append((key, name, desc, inputtype, options, regex, result, group, str(events)))
# save metadata in dummy setting # save metadata in dummy setting
if '__metadata' not in key: if '__metadata' not in key:
conf.mySettings.append((f'{key}__metadata', "metadata name", "metadata desc", 'json', "", "", json.dumps(setJsonMetadata), group, "")) conf.mySettings.append((f'{key}__metadata', "metadata name", "metadata desc", 'json', "", "", json.dumps(setJsonMetadata), group, []))
return result return result
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------