Ported groups-domains.lp and groups-adlists.lp

Signed-off-by: DL6ER <dl6er@dl6er.de>
This commit is contained in:
DL6ER
2023-05-06 19:26:09 +02:00
parent f3d7eb296a
commit 4d3d64b904
11 changed files with 1097 additions and 1129 deletions

View File

@@ -1,12 +1,11 @@
<?php
/*
* Pi-hole: A black hole for Internet advertisements
* (c) 2019 Pi-hole, LLC (https://pi-hole.net)
* Network-wide ad blocking via your own hardware.
<? --[[
* Pi-hole: A black hole for Internet advertisements
* (c) 2019 Pi-hole, LLC (https://pi-hole.net)
* Network-wide ad blocking via your own hardware.
*
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license.
*/
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license.
--]]
mg.include('scripts/pi-hole/lua/header_authenticated.lp','r')
?>
@@ -85,6 +84,7 @@ mg.include('scripts/pi-hole/lua/header_authenticated.lp','r')
<script src="<?=pihole.fileversion('scripts/vendor/bootstrap-select.min.js')?>"></script>
<script src="<?=pihole.fileversion('scripts/vendor/bootstrap-toggle.min.js')?>"></script>
<script src="<?=pihole.fileversion('scripts/pi-hole/js/groups-common.js')?>"></script>
<script src="<?=pihole.fileversion('scripts/pi-hole/js/groups-adlists.js')?>"></script>
<? mg.include('scripts/pi-hole/lua/footer.lp','r')?>

View File

@@ -93,6 +93,7 @@ mg.include('scripts/pi-hole/lua/header_authenticated.lp','r')
<script src="<?=pihole.fileversion('scripts/vendor/bootstrap-select.min.js')?>"></script>
<script src="<?=pihole.fileversion('scripts/vendor/bootstrap-toggle.min.js')?>"></script>
<script src="<?=pihole.fileversion('scripts/pi-hole/js/ip-address-sorting.js')?>"></script>
<script src="<?=pihole.fileversion('scripts/pi-hole/js/groups-common.js')?>"></script>
<script src="<?=pihole.fileversion('scripts/pi-hole/js/groups-clients.js')?>"></script>
<? mg.include('scripts/pi-hole/lua/footer.lp','r')?>

View File

@@ -1,12 +1,11 @@
<?php
/*
* Pi-hole: A black hole for Internet advertisements
* (c) 2019 Pi-hole, LLC (https://pi-hole.net)
* Network-wide ad blocking via your own hardware.
<? --[[
* Pi-hole: A black hole for Internet advertisements
* (c) 2019 Pi-hole, LLC (https://pi-hole.net)
* Network-wide ad blocking via your own hardware.
*
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license.
*/
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license.
--]]
mg.include('scripts/pi-hole/lua/header_authenticated.lp','r')
?>
@@ -91,11 +90,11 @@ mg.include('scripts/pi-hole/lua/header_authenticated.lp','r')
</p>
</div>
<div class="btn-toolbar pull-right" role="toolbar" aria-label="Toolbar with buttons">
<div class="btn-group" role="group" aria-label="Third group">
<button type="button" class="btn btn-primary" id="add2black">Add to Blacklist</button>
<div class="btn-group" role="group">
<button type="button" class="btn btn-primary" id="add_deny">Add to denied domains</button>
</div>
<div class="btn-group" role="group" aria-label="Third group">
<button type="button" class="btn btn-primary" id="add2white">Add to Whitelist</button>
<div class="btn-group" role="group">
<button type="button" class="btn btn-primary" id="add_allow">Add to allowed domains</button>
</div>
</div>
</div>
@@ -115,12 +114,12 @@ mg.include('scripts/pi-hole/lua/header_authenticated.lp','r')
</h3>
<div class="filter_types">
<div class="line">
<span><input type="checkbox" name="typ" value="0" id="typ0" checked><label for="typ0">Exact whitelist</label></span>
<span><input type="checkbox" name="typ" value="2" id="typ2" checked><label for="typ2">Regex whitelist</label></span>
<span><input type="checkbox" name="typ" value="allow/exact" id="typ0" checked><label for="typ0">Exact allow</label></span>
<span><input type="checkbox" name="typ" value="allow/regex" id="typ2" checked><label for="typ2">Regex allow</label></span>
</div>
<div class="line">
<span><input type="checkbox" name="typ" value="1" id="typ1" checked><label for="typ1">Exact blacklist</label></span>
<span><input type="checkbox" name="typ" value="3" id="typ3" checked><label for="typ3">Regex blacklist</label></span>
<span><input type="checkbox" name="typ" value="deny/exact" id="typ1" checked><label for="typ1">Exact deny</label></span>
<span><input type="checkbox" name="typ" value="deny/regex" id="typ3" checked><label for="typ3">Regex deny</label></span>
</div>
</div>
</div>
@@ -150,6 +149,7 @@ mg.include('scripts/pi-hole/lua/header_authenticated.lp','r')
<script src="<?=pihole.fileversion('scripts/vendor/bootstrap-select.min.js')?>"></script>
<script src="<?=pihole.fileversion('scripts/vendor/bootstrap-toggle.min.js')?>"></script>
<script src="<?=pihole.fileversion('scripts/pi-hole/js/groups-common.js')?>"></script>
<script src="<?=pihole.fileversion('scripts/pi-hole/js/groups-domains.js')?>"></script>
<? mg.include('scripts/pi-hole/lua/footer.lp','r')?>

View File

@@ -5,37 +5,18 @@
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license. */
/* global utils:false */
/* global utils:false, groups:false, apiFailure:false, updateFtlInfo:false, getGroups:false */
var table;
var groups = [];
var token = $("#token").text();
var GETDict = {};
function getGroups() {
$.post(
"scripts/pi-hole/php/groups.php",
{ action: "get_groups", token: token },
function (data) {
groups = data.data;
initTable();
},
"json"
);
}
$(function () {
window.location.search
.substr(1)
.split("&")
.forEach(function (item) {
GETDict[item.split("=")[0]] = item.split("=")[1];
});
GETDict = utils.parseQueryString();
$("#btnAdd").on("click", addAdlist);
utils.setBsSelectDefaults();
getGroups();
initTable();
});
function format(data) {
@@ -110,281 +91,290 @@ function format(data) {
}
function initTable() {
table = $("#adlistsTable").DataTable({
ajax: {
url: "scripts/pi-hole/php/groups.php",
data: { action: "get_adlists", token: token },
type: "POST",
},
order: [[0, "asc"]],
columns: [
{ data: "id", visible: false },
{ data: null, visible: true, orderable: false, width: "15px" },
{ data: "status", searchable: false, class: "details-control" },
{ data: "address" },
{ data: "enabled", searchable: false },
{ data: "comment" },
{ data: "groups", searchable: false },
{ data: null, width: "22px", orderable: false },
],
columnDefs: [
{
targets: 1,
className: "select-checkbox",
render: function () {
return "";
table = $("#adlistsTable")
.on("preXhr.dt", function () {
getGroups();
})
.DataTable({
processing: true,
ajax: {
url: "/api/lists",
dataSrc: "lists",
type: "GET",
},
order: [[0, "asc"]],
columns: [
{ data: "id", visible: false },
{ data: null, visible: true, orderable: false, width: "15px" },
{ data: "status", searchable: false, class: "details-control" },
{ data: "address" },
{ data: "enabled", searchable: false },
{ data: "comment" },
{ data: "groups", searchable: false },
{ data: null, width: "22px", orderable: false },
],
columnDefs: [
{
targets: 1,
className: "select-checkbox",
render: function () {
return "";
},
},
{
targets: "_all",
render: $.fn.dataTable.render.text(),
},
],
drawCallback: function () {
// Hide buttons if all adlists were deleted
var hasRows = this.api().rows({ filter: "applied" }).data().length > 0;
$(".datatable-bt").css("visibility", hasRows ? "visible" : "hidden");
$('button[id^="deleteAdlist_"]').on("click", deleteAdlist);
// Remove visible dropdown to prevent orphaning
$("body > .bootstrap-select.dropdown").remove();
},
{
targets: "_all",
render: $.fn.dataTable.render.text(),
},
],
drawCallback: function () {
// Hide buttons if all adlists were deleted
var hasRows = this.api().rows({ filter: "applied" }).data().length > 0;
$(".datatable-bt").css("visibility", hasRows ? "visible" : "hidden");
rowCallback: function (row, data) {
var dataId = utils.hexEncode(data.address);
$(row).attr("data-id", dataId);
$('button[id^="deleteAdlist_"]').on("click", deleteAdlist);
// Remove visible dropdown to prevent orphaning
$("body > .bootstrap-select.dropdown").remove();
},
rowCallback: function (row, data) {
$(row).attr("data-id", data.id);
var disabled = data.enabled === 0;
var statusCode = 0,
statusIcon;
// If there is no status or the list is disabled, we keep
// status 0 (== unknown)
if (data.status !== null && disabled !== true) {
statusCode = parseInt(data.status, 10);
}
switch (statusCode) {
case 1:
statusIcon = "fa-check";
break;
case 2:
statusIcon = "fa-history";
break;
case 3:
statusIcon = "fa-exclamation-circle";
break;
case 4:
statusIcon = "fa-times";
break;
default:
statusIcon = "fa-question-circle";
break;
}
$("td:eq(1)", row).addClass("list-status-" + statusCode);
$("td:eq(1)", row).html(
"<i class='fa " + statusIcon + "' title='Click for details about this list'></i>"
);
if (data.address.startsWith("file://")) {
// Local files cannot be downloaded from a distant client so don't show
// a link to such a list here
$("td:eq(2)", row).html(
'<code id="address_' + data.id + '" class="breakall">' + data.address + "</code>"
);
} else {
$("td:eq(2)", row).html(
'<a id="address_' +
data.id +
'" class="breakall" href="' +
data.address +
'" target="_blank" rel="noopener noreferrer">' +
data.address +
"</a>"
);
}
$("td:eq(3)", row).html(
'<input type="checkbox" id="status_' + data.id + '"' + (disabled ? "" : " checked") + ">"
);
var statusEl = $("#status_" + data.id, row);
statusEl.bootstrapToggle({
on: "Enabled",
off: "Disabled",
size: "small",
onstyle: "success",
width: "80px",
});
statusEl.on("change", editAdlist);
$("td:eq(4)", row).html('<input id="comment_' + data.id + '" class="form-control">');
var commentEl = $("#comment_" + data.id, row);
commentEl.val(utils.unescapeHtml(data.comment));
commentEl.on("change", editAdlist);
$("td:eq(5)", row).empty();
$("td:eq(5)", row).append(
'<select class="selectpicker" id="multiselect_' + data.id + '" multiple></select>'
);
var selectEl = $("#multiselect_" + data.id, row);
// Add all known groups
for (var i = 0; i < groups.length; i++) {
var dataSub = "";
if (!groups[i].enabled) {
dataSub = 'data-subtext="(disabled)"';
var statusCode = 0,
statusIcon;
// If there is no status or the list is disabled, we keep
// status 0 (== unknown)
if (data.status !== null && data.enabled) {
statusCode = parseInt(data.status, 10);
}
selectEl.append(
$("<option " + dataSub + "/>")
.val(groups[i].id)
.text(groups[i].name)
);
}
switch (statusCode) {
case 1:
statusIcon = "fa-check";
break;
case 2:
statusIcon = "fa-history";
break;
case 3:
statusIcon = "fa-exclamation-circle";
break;
case 4:
statusIcon = "fa-times";
break;
default:
statusIcon = "fa-question-circle";
break;
}
// Select assigned groups
selectEl.val(data.groups);
// Initialize bootstrap-select
selectEl
// fix dropdown if it would stick out right of the viewport
.on("show.bs.select", function () {
var winWidth = $(window).width();
var dropdownEl = $("body > .bootstrap-select.dropdown");
if (dropdownEl.length > 0) {
dropdownEl.removeClass("align-right");
var width = dropdownEl.width();
var left = dropdownEl.offset().left;
if (left + width > winWidth) {
dropdownEl.addClass("align-right");
$("td:eq(1)", row).addClass("list-status-" + statusCode);
$("td:eq(1)", row).html(
"<i class='fa " + statusIcon + "' title='Click for details about this list'></i>"
);
if (data.address.startsWith("file://")) {
// Local files cannot be downloaded from a distant client so don't show
// a link to such a list here
$("td:eq(2)", row).html(
'<code id="address_' + dataId + '" class="breakall">' + data.address + "</code>"
);
} else {
$("td:eq(2)", row).html(
'<a id="address_' +
dataId +
'" class="breakall" href="' +
data.address +
'" target="_blank" rel="noopener noreferrer">' +
data.address +
"</a>"
);
}
$("td:eq(3)", row).html(
'<input type="checkbox" id="enabled_' +
dataId +
'"' +
(data.enabled ? " checked" : "") +
">"
);
var statusEl = $("#enabled_" + dataId, row);
statusEl.bootstrapToggle({
on: "Enabled",
off: "Disabled",
size: "small",
onstyle: "success",
width: "80px",
});
statusEl.on("change", editAdlist);
$("td:eq(4)", row).html('<input id="comment_' + dataId + '" class="form-control">');
var commentEl = $("#comment_" + dataId, row);
commentEl.val(utils.unescapeHtml(data.comment));
commentEl.on("change", editAdlist);
$("td:eq(5)", row).empty();
$("td:eq(5)", row).append(
'<select class="selectpicker" id="multiselect_' + dataId + '" multiple></select>'
);
var selectEl = $("#multiselect_" + dataId, row);
// Add all known groups
for (var i = 0; i < groups.length; i++) {
var dataSub = "";
if (!groups[i].enabled) {
dataSub = 'data-subtext="(disabled)"';
}
selectEl.append(
$("<option " + dataSub + "/>")
.val(groups[i].id)
.text(groups[i].name)
);
}
// Select assigned groups
selectEl.val(data.groups);
// Initialize bootstrap-select
selectEl
// fix dropdown if it would stick out right of the viewport
.on("show.bs.select", function () {
var winWidth = $(window).width();
var dropdownEl = $("body > .bootstrap-select.dropdown");
if (dropdownEl.length > 0) {
dropdownEl.removeClass("align-right");
var width = dropdownEl.width();
var left = dropdownEl.offset().left;
if (left + width > winWidth) {
dropdownEl.addClass("align-right");
}
}
}
})
.on("changed.bs.select", function () {
// enable Apply button
if ($(applyBtn).prop("disabled")) {
$(applyBtn)
.addClass("btn-success")
.prop("disabled", false)
.on("click", function () {
editAdlist.call(selectEl);
});
}
})
.on("hide.bs.select", function () {
// Restore values if drop-down menu is closed without clicking the Apply button
if (!$(applyBtn).prop("disabled")) {
$(this).val(data.groups).selectpicker("refresh");
$(applyBtn).removeClass("btn-success").prop("disabled", true).off("click");
}
})
.selectpicker()
.siblings(".dropdown-menu")
.find(".bs-actionsbox")
.prepend(
'<button type="button" id=btn_apply_' +
data.id +
' class="btn btn-block btn-sm" disabled>Apply</button>'
);
})
.on("changed.bs.select", function () {
// enable Apply button
if ($(applyBtn).prop("disabled")) {
$(applyBtn)
.addClass("btn-success")
.prop("disabled", false)
.on("click", function () {
editAdlist.call(selectEl);
});
}
})
.on("hide.bs.select", function () {
// Restore values if drop-down menu is closed without clicking the Apply button
if (!$(applyBtn).prop("disabled")) {
$(this).val(data.groups).selectpicker("refresh");
$(applyBtn).removeClass("btn-success").prop("disabled", true).off("click");
}
})
.selectpicker()
.siblings(".dropdown-menu")
.find(".bs-actionsbox")
.prepend(
'<button type="button" id=btn_apply_' +
dataId +
' class="btn btn-block btn-sm" disabled>Apply</button>'
);
var applyBtn = "#btn_apply_" + data.id;
var applyBtn = "#btn_apply_" + dataId;
// Highlight row (if url parameter "adlistid=" is used)
if ("adlistid" in GETDict && data.id === parseInt(GETDict.adlistid, 10)) {
$(row).find("td").addClass("highlight");
}
var button =
'<button type="button" class="btn btn-danger btn-xs" id="deleteAdlist_' +
data.id +
'" data-del-id="' +
data.id +
'">' +
'<span class="far fa-trash-alt"></span>' +
"</button>";
$("td:eq(6)", row).html(button);
},
dom:
"<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-3'B><'col-sm-9'p>>" +
"<'row'<'col-sm-12'<'table-responsive'tr>>>" +
"<'row'<'col-sm-3'B><'col-sm-9'p>>" +
"<'row'<'col-sm-12'i>>",
lengthMenu: [
[10, 25, 50, 100, -1],
[10, 25, 50, 100, "All"],
],
select: {
style: "multi",
selector: "td:not(:last-child)",
info: false,
},
buttons: [
{
text: '<span class="far fa-square"></span>',
titleAttr: "Select All",
className: "btn-sm datatable-bt selectAll",
action: function () {
table.rows({ page: "current" }).select();
},
},
{
text: '<span class="far fa-plus-square"></span>',
titleAttr: "Select All",
className: "btn-sm datatable-bt selectMore",
action: function () {
table.rows({ page: "current" }).select();
},
},
{
extend: "selectNone",
text: '<span class="far fa-check-square"></span>',
titleAttr: "Deselect All",
className: "btn-sm datatable-bt removeAll",
},
{
text: '<span class="far fa-trash-alt"></span>',
titleAttr: "Delete Selected",
className: "btn-sm datatable-bt deleteSelected",
action: function () {
// For each ".selected" row ...
var ids = [];
$("tr.selected").each(function () {
// ... add the row identified by "data-id".
ids.push(parseInt($(this).attr("data-id"), 10));
});
// Delete all selected rows at once
delItems(ids);
},
},
],
stateSave: true,
stateDuration: 0,
stateSaveCallback: function (settings, data) {
utils.stateSaveCallback("groups-adlists-table", data);
},
stateLoadCallback: function () {
var data = utils.stateLoadCallback("groups-adlists-table");
// Return if not available
if (data === null) {
return null;
}
// Reset visibility of ID column
data.columns[0].visible = false;
// Apply loaded state to table
return data;
},
initComplete: function () {
if ("adlistid" in GETDict) {
var pos = table
.column(0, { order: "current" })
.data()
.indexOf(parseInt(GETDict.adlistid, 10));
if (pos >= 0) {
var page = Math.floor(pos / table.page.info().length);
table.page(page).draw(false);
// Highlight row (if url parameter "adlistid=" is used)
if ("adlistid" in GETDict && data.id === parseInt(GETDict.adlistid, 10)) {
$(row).find("td").addClass("highlight");
}
}
},
});
var button =
'<button type="button" class="btn btn-danger btn-xs" id="deleteAdlist_' +
dataId +
'" data-id="' +
dataId +
'">' +
'<span class="far fa-trash-alt"></span>' +
"</button>";
$("td:eq(6)", row).html(button);
},
dom:
"<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-3'B><'col-sm-9'p>>" +
"<'row'<'col-sm-12'<'table-responsive'tr>>>" +
"<'row'<'col-sm-3'B><'col-sm-9'p>>" +
"<'row'<'col-sm-12'i>>",
lengthMenu: [
[10, 25, 50, 100, -1],
[10, 25, 50, 100, "All"],
],
select: {
style: "multi",
selector: "td:not(:last-child)",
info: false,
},
buttons: [
{
text: '<span class="far fa-square"></span>',
titleAttr: "Select All",
className: "btn-sm datatable-bt selectAll",
action: function () {
table.rows({ page: "current" }).select();
},
},
{
text: '<span class="far fa-plus-square"></span>',
titleAttr: "Select All",
className: "btn-sm datatable-bt selectMore",
action: function () {
table.rows({ page: "current" }).select();
},
},
{
extend: "selectNone",
text: '<span class="far fa-check-square"></span>',
titleAttr: "Deselect All",
className: "btn-sm datatable-bt removeAll",
},
{
text: '<span class="far fa-trash-alt"></span>',
titleAttr: "Delete Selected",
className: "btn-sm datatable-bt deleteSelected",
action: function () {
// For each ".selected" row ...
var ids = [];
$("tr.selected").each(function () {
// ... add the row identified by "data-id".
ids.push($(this).attr("data-id"), 10);
});
// Delete all selected rows at once
delItems(ids);
},
},
],
stateSave: true,
stateDuration: 0,
stateSaveCallback: function (settings, data) {
utils.stateSaveCallback("groups-adlists-table", data);
},
stateLoadCallback: function () {
var data = utils.stateLoadCallback("groups-adlists-table");
// Return if not available
if (data === null) {
return null;
}
// Reset visibility of ID column
data.columns[0].visible = false;
// Apply loaded state to table
return data;
},
initComplete: function () {
if ("adlistid" in GETDict) {
var pos = table
.column(0, { order: "current" })
.data()
.indexOf(parseInt(GETDict.adlistid, 10));
if (pos >= 0) {
var page = Math.floor(pos / table.page.info().length);
table.page(page).draw(false);
}
}
},
});
table.on("init select deselect", function () {
utils.changeBulkDeleteStates(table);
@@ -434,8 +424,8 @@ function initTable() {
$.fn.dataTable.Buttons.defaults.dom.container.className = "dt-buttons";
function deleteAdlist() {
// Passes the button data-del-id attribute as ID
var ids = [parseInt($(this).attr("data-del-id"), 10)];
// Passes the button data-id attribute as ID
const ids = [$(this).attr("data-id")];
delItems(ids);
}
@@ -443,66 +433,51 @@ function delItems(ids) {
// Check input validity
if (!Array.isArray(ids)) return;
var address = "";
// Get first element from array
const addressRaw = ids[0];
const address = utils.hexDecode(addressRaw);
// Exploit prevention: Return early for non-numeric IDs
for (var id of ids) {
if (typeof id !== "number") return;
address += "<li>" + utils.escapeHtml($("#address_" + id).text()) + "</li>";
}
// Remove first element from array
ids.shift();
utils.disableAll();
var idstring = ids.join(", ");
const idstring = ids.join(", ");
utils.showAlert("info", "", "Deleting adlist(s) ...", "<ul>" + address + "</ul>");
$.ajax({
url: "scripts/pi-hole/php/groups.php",
method: "post",
dataType: "json",
data: { action: "delete_adlist", id: JSON.stringify(ids), token: token },
url: "/api/lists/" + encodeURIComponent(address),
method: "delete",
})
.done(function (response) {
.done(function () {
utils.enableAll();
if (response.success) {
utils.showAlert(
"success",
"far fa-trash-alt",
"Successfully deleted adlist(s): ",
"<ul>" + address + "</ul>"
);
for (var id in ids) {
if (Object.hasOwnProperty.call(ids, id)) {
table.row(id).remove().draw(false).ajax.reload(null, false);
}
}
} else {
utils.showAlert(
"error",
"",
"Error while deleting adlist(s): " + idstring,
response.message
);
utils.showAlert("success", "far fa-trash-alt", "Successfully deleted list: ", address);
table.row(addressRaw).remove().draw(false);
if (ids.length > 0) {
// Recursively delete all remaining items
delItems(ids);
return;
}
table.ajax.reload(null, false);
// Clear selection after deletion
table.rows().deselect();
utils.changeBulkDeleteStates(table);
// Update number of lists in the sidebar
updateFtlInfo();
})
.fail(function (jqXHR, exception) {
.fail(function (data, exception) {
apiFailure(data);
utils.enableAll();
utils.showAlert(
"error",
"",
"Error while deleting adlist(s): " + idstring,
jqXHR.responseText
);
utils.showAlert("error", "", "Error while deleting list(s): " + idstring, data.responseText);
console.log(exception); // eslint-disable-line no-console
});
}
function addAdlist() {
var address = utils.escapeHtml($("#new_address").val());
var comment = utils.escapeHtml($("#new_comment").val());
const address = utils.escapeHtml($("#new_address").val());
const comment = utils.escapeHtml($("#new_comment").val());
utils.disableAll();
utils.showAlert("info", "", "Adding adlist...", address);
@@ -515,120 +490,97 @@ function addAdlist() {
}
$.ajax({
url: "scripts/pi-hole/php/groups.php",
url: "/api/lists",
method: "post",
dataType: "json",
data: {
action: "add_adlist",
address: address,
comment: comment,
token: token,
},
success: function (response) {
data: JSON.stringify({ address: address, comment: comment }),
success: function () {
utils.enableAll();
if (response.success) {
if (response.warning) {
// Ignored items found! Showing ignored and added items in a warning.
utils.showAlert("warning", "fas fa-plus", "Warning", response.message);
} else {
// All items added.
utils.showAlert("success", "fas fa-plus", "Successfully added adlist", response.message);
}
utils.showAlert("success", "fas fa-plus", "Successfully added list", address);
table.ajax.reload(null, false);
table.rows().deselect();
table.ajax.reload(null, false);
$("#new_address").val("");
$("#new_comment").val("");
table.ajax.reload();
table.rows().deselect();
$("#new_address").focus();
} else {
utils.showAlert("error", "", "Error while adding new adlist: ", response.message);
}
// Update number of groups in the sidebar
updateFtlInfo();
},
error: function (jqXHR, exception) {
error: function (data, exception) {
apiFailure(data);
utils.enableAll();
utils.showAlert("error", "", "Error while adding new adlist: ", jqXHR.responseText);
utils.showAlert("error", "", "Error while adding new list", data.responseText);
console.log(exception); // eslint-disable-line no-console
},
});
}
function editAdlist() {
var elem = $(this).attr("id");
var tr = $(this).closest("tr");
var id = tr.attr("data-id");
var status = tr.find("#status_" + id).is(":checked") ? 1 : 0;
var comment = utils.escapeHtml(tr.find("#comment_" + id).val());
var groups = tr.find("#multiselect_" + id).val();
var address = utils.escapeHtml(tr.find("#address_" + id).text());
const elem = $(this).attr("id");
const tr = $(this).closest("tr");
const address = tr.attr("data-id");
const status = tr.find("#enabled_" + address).is(":checked");
const comment = utils.escapeHtml(tr.find("#comment_" + address).val());
// Convert list of string integers to list of integers using map(Number)
const groups = tr
.find("#multiselect_" + address)
.val()
.map(Number);
const enabled = tr.find("#enabled_" + address).is(":checked");
var done = "edited";
var notDone = "editing";
switch (elem) {
case "status_" + id:
if (status === 0) {
case "enabled_" + address:
if (status) {
done = "disabled";
notDone = "disabling";
} else if (status === 1) {
} else {
done = "enabled";
notDone = "enabling";
}
break;
case "comment_" + id:
case "comment_" + address:
done = "edited comment of";
notDone = "editing comment of";
break;
case "multiselect_" + id:
case "multiselect_" + address:
done = "edited groups of";
notDone = "editing groups of";
break;
default:
alert("bad element or invalid data-id!");
alert("bad element (" + elem + ") or invalid data-id!");
return;
}
utils.disableAll();
utils.showAlert("info", "", "Editing adlist...", address);
const addressDecoded = utils.hexDecode(address);
utils.showAlert("info", "", "Editing address...", addressDecoded);
$.ajax({
url: "scripts/pi-hole/php/groups.php",
method: "post",
url: "/api/lists/" + encodeURIComponent(addressDecoded),
method: "put",
dataType: "json",
data: {
action: "edit_adlist",
id: id,
comment: comment,
status: status,
data: JSON.stringify({
groups: groups,
token: token,
},
success: function (response) {
comment: comment,
enabled: enabled,
}),
success: function () {
utils.enableAll();
if (response.success) {
utils.showAlert(
"success",
"fas fa-pencil-alt",
"Successfully " + done + " adlist ",
address
);
table.ajax.reload(null, false);
} else {
utils.showAlert(
"error",
"",
"Error while " + notDone + " adlist with ID " + id,
Number(response.message)
);
}
utils.showAlert(
"success",
"fas fa-pencil-alt",
"Successfully " + done + " list",
addressDecoded
);
table.ajax.reload(null, false);
},
error: function (jqXHR, exception) {
error: function (data, exception) {
apiFailure(data);
utils.enableAll();
utils.showAlert(
"error",
"",
"Error while " + notDone + " adlist with ID " + id,
jqXHR.responseText
"Error while " + notDone + " list " + addressDecoded,
data.responseText
);
console.log(exception); // eslint-disable-line no-console
},

View File

@@ -5,11 +5,9 @@
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license. */
/* global utils:false, updateFtlInfo:false */
/* global utils:false, groups:false,, apiFailure:false, updateFtlInfo:false, getGroups:false */
var table;
var groups = [];
var token = $("#token").text();
function reloadClientSuggestions() {
$.ajax({
@@ -74,18 +72,6 @@ function reloadClientSuggestions() {
});
}
function getGroups() {
$.ajax({
url: "/api/groups",
type: "GET",
dataType: "json",
success: function (data) {
groups = data.groups;
initTable();
},
});
}
$(function () {
$("#btnAdd").on("click", addClient);
$("select").select2({
@@ -96,7 +82,7 @@ $(function () {
reloadClientSuggestions();
utils.setBsSelectDefaults();
getGroups();
initTable();
$("#select").on("change", function () {
$("#ip-custom").val("");
@@ -105,225 +91,230 @@ $(function () {
});
function initTable() {
table = $("#clientsTable").DataTable({
ajax: {
url: "/api/clients",
dataSrc: "clients",
type: "GET",
},
order: [[0, "asc"]],
columns: [
{ data: "id", visible: false },
{ data: null, visible: true, orderable: false, width: "15px" },
{ data: "client", type: "ip-address" },
{ data: "comment" },
{ data: "groups", searchable: false },
{ data: null, width: "22px", orderable: false },
],
columnDefs: [
{
targets: 1,
className: "select-checkbox",
render: function () {
return "";
table = $("#clientsTable")
.on("preXhr.dt", function () {
getGroups();
})
.DataTable({
processing: true,
ajax: {
url: "/api/clients",
dataSrc: "clients",
type: "GET",
},
order: [[0, "asc"]],
columns: [
{ data: "id", visible: false },
{ data: null, visible: true, orderable: false, width: "15px" },
{ data: "client", type: "ip-address" },
{ data: "comment" },
{ data: "groups", searchable: false },
{ data: null, width: "22px", orderable: false },
],
columnDefs: [
{
targets: 1,
className: "select-checkbox",
render: function () {
return "";
},
},
},
{
targets: "_all",
render: $.fn.dataTable.render.text(),
},
],
drawCallback: function () {
// Hide buttons if all clients were deleted
var hasRows = this.api().rows({ filter: "applied" }).data().length > 0;
$(".datatable-bt").css("visibility", hasRows ? "visible" : "hidden");
{
targets: "_all",
render: $.fn.dataTable.render.text(),
},
],
drawCallback: function () {
// Hide buttons if all clients were deleted
var hasRows = this.api().rows({ filter: "applied" }).data().length > 0;
$(".datatable-bt").css("visibility", hasRows ? "visible" : "hidden");
$('button[id^="deleteClient_"]').on("click", deleteClient);
// Remove visible dropdown to prevent orphaning
$("body > .bootstrap-select.dropdown").remove();
},
rowCallback: function (row, data) {
var dataId = data.client.replaceAll(":", "__");
$(row).attr("data-id", dataId);
var tooltip =
"Added: " +
utils.datetime(data.date_added, false) +
"\nLast modified: " +
utils.datetime(data.date_modified, false) +
"\nDatabase ID: " +
data.id;
var ipName =
'<code id="ip_' +
dataId +
'" title="' +
tooltip +
'" class="breakall">' +
data.client +
"</code>";
if (data.name !== null && data.name.length > 0)
ipName +=
'<br><code id="name_' +
$('button[id^="deleteClient_"]').on("click", deleteClient);
// Remove visible dropdown to prevent orphaning
$("body > .bootstrap-select.dropdown").remove();
},
rowCallback: function (row, data) {
var dataId = utils.hexEncode(data.client);
$(row).attr("data-id", dataId);
var tooltip =
"Added: " +
utils.datetime(data.date_added, false) +
"\nLast modified: " +
utils.datetime(data.date_modified, false) +
"\nDatabase ID: " +
data.id;
var ipName =
'<code id="ip_' +
dataId +
'" title="' +
tooltip +
'" class="breakall">' +
data.name +
data.client +
"</code>";
$("td:eq(1)", row).html(ipName);
if (data.name !== null && data.name.length > 0)
ipName +=
'<br><code id="name_' +
dataId +
'" title="' +
tooltip +
'" class="breakall">' +
data.name +
"</code>";
$("td:eq(1)", row).html(ipName);
$("td:eq(2)", row).html('<input id="comment_' + dataId + '" class="form-control">');
var commentEl = $("#comment_" + dataId, row);
commentEl.val(utils.unescapeHtml(data.comment));
commentEl.on("change", editClient);
$("td:eq(2)", row).html('<input id="comment_' + dataId + '" class="form-control">');
var commentEl = $("#comment_" + dataId, row);
commentEl.val(utils.unescapeHtml(data.comment));
commentEl.on("change", editClient);
$("td:eq(3)", row).empty();
$("td:eq(3)", row).append(
'<select class="selectpicker" id="multiselect_' + dataId + '" multiple></select>'
);
var selectEl = $("#multiselect_" + dataId, row);
// Add all known groups
for (var i = 0; i < groups.length; i++) {
var dataSub = "";
if (!groups[i].enabled) {
dataSub = 'data-subtext="(disabled)"';
$("td:eq(3)", row).empty();
$("td:eq(3)", row).append(
'<select class="selectpicker" id="multiselect_' + dataId + '" multiple></select>'
);
var selectEl = $("#multiselect_" + dataId, row);
// Add all known groups
for (var i = 0; i < groups.length; i++) {
var dataSub = "";
if (!groups[i].enabled) {
dataSub = 'data-subtext="(disabled)"';
}
selectEl.append(
$("<option " + dataSub + "/>")
.val(groups[i].id)
.text(groups[i].name)
);
}
selectEl.append(
$("<option " + dataSub + "/>")
.val(groups[i].id)
.text(groups[i].name)
);
}
// Select assigned groups
selectEl.val(data.groups);
// Initialize bootstrap-select
selectEl
// fix dropdown if it would stick out right of the viewport
.on("show.bs.select", function () {
var winWidth = $(window).width();
var dropdownEl = $("body > .bootstrap-select.dropdown");
if (dropdownEl.length > 0) {
dropdownEl.removeClass("align-right");
var width = dropdownEl.width();
var left = dropdownEl.offset().left;
if (left + width > winWidth) {
dropdownEl.addClass("align-right");
// Select assigned groups
selectEl.val(data.groups);
// Initialize bootstrap-select
selectEl
// fix dropdown if it would stick out right of the viewport
.on("show.bs.select", function () {
var winWidth = $(window).width();
var dropdownEl = $("body > .bootstrap-select.dropdown");
if (dropdownEl.length > 0) {
dropdownEl.removeClass("align-right");
var width = dropdownEl.width();
var left = dropdownEl.offset().left;
if (left + width > winWidth) {
dropdownEl.addClass("align-right");
}
}
}
})
.on("changed.bs.select", function () {
// enable Apply button
if ($(applyBtn).prop("disabled")) {
$(applyBtn)
.addClass("btn-success")
.prop("disabled", false)
.on("click", function () {
editClient.call(selectEl);
});
}
})
.on("hide.bs.select", function () {
// Restore values if drop-down menu is closed without clicking the Apply button
if (!$(applyBtn).prop("disabled")) {
$(this).val(data.groups).selectpicker("refresh");
$(applyBtn).removeClass("btn-success").prop("disabled", true).off("click");
}
})
.selectpicker()
.siblings(".dropdown-menu")
.find(".bs-actionsbox")
.prepend(
'<button type="button" id=btn_apply_' +
dataId +
' class="btn btn-block btn-sm" disabled>Apply</button>'
);
})
.on("changed.bs.select", function () {
// enable Apply button
if ($(applyBtn).prop("disabled")) {
$(applyBtn)
.addClass("btn-success")
.prop("disabled", false)
.on("click", function () {
editClient.call(selectEl);
});
}
})
.on("hide.bs.select", function () {
// Restore values if drop-down menu is closed without clicking the Apply button
if (!$(applyBtn).prop("disabled")) {
$(this).val(data.groups).selectpicker("refresh");
$(applyBtn).removeClass("btn-success").prop("disabled", true).off("click");
}
})
.selectpicker()
.siblings(".dropdown-menu")
.find(".bs-actionsbox")
.prepend(
'<button type="button" id=btn_apply_' +
dataId +
' class="btn btn-block btn-sm" disabled>Apply</button>'
);
var applyBtn = "#btn_apply_" + dataId;
var applyBtn = "#btn_apply_" + dataId;
var button =
'<button type="button" class="btn btn-danger btn-xs" id="deleteClient_' +
dataId +
'" data-id="' +
dataId +
'">' +
'<span class="far fa-trash-alt"></span>' +
"</button>";
$("td:eq(4)", row).html(button);
},
select: {
style: "multi",
selector: "td:not(:last-child)",
info: false,
},
buttons: [
{
text: '<span class="far fa-square"></span>',
titleAttr: "Select All",
className: "btn-sm datatable-bt selectAll",
action: function () {
table.rows({ page: "current" }).select();
var button =
'<button type="button" class="btn btn-danger btn-xs" id="deleteClient_' +
dataId +
'" data-id="' +
dataId +
'">' +
'<span class="far fa-trash-alt"></span>' +
"</button>";
$("td:eq(4)", row).html(button);
},
select: {
style: "multi",
selector: "td:not(:last-child)",
info: false,
},
buttons: [
{
text: '<span class="far fa-square"></span>',
titleAttr: "Select All",
className: "btn-sm datatable-bt selectAll",
action: function () {
table.rows({ page: "current" }).select();
},
},
},
{
text: '<span class="far fa-plus-square"></span>',
titleAttr: "Select All",
className: "btn-sm datatable-bt selectMore",
action: function () {
table.rows({ page: "current" }).select();
{
text: '<span class="far fa-plus-square"></span>',
titleAttr: "Select All",
className: "btn-sm datatable-bt selectMore",
action: function () {
table.rows({ page: "current" }).select();
},
},
},
{
extend: "selectNone",
text: '<span class="far fa-check-square"></span>',
titleAttr: "Deselect All",
className: "btn-sm datatable-bt removeAll",
},
{
text: '<span class="far fa-trash-alt"></span>',
titleAttr: "Delete Selected",
className: "btn-sm datatable-bt deleteSelected",
action: function () {
// For each ".selected" row ...
var ids = [];
$("tr.selected").each(function () {
// ... add the row identified by "data-id".
ids.push($(this).attr("data-id"));
});
// Delete all selected rows at once
delItems(ids);
{
extend: "selectNone",
text: '<span class="far fa-check-square"></span>',
titleAttr: "Deselect All",
className: "btn-sm datatable-bt removeAll",
},
{
text: '<span class="far fa-trash-alt"></span>',
titleAttr: "Delete Selected",
className: "btn-sm datatable-bt deleteSelected",
action: function () {
// For each ".selected" row ...
var ids = [];
$("tr.selected").each(function () {
// ... add the row identified by "data-id".
ids.push($(this).attr("data-id"));
});
// Delete all selected rows at once
delItems(ids);
},
},
],
dom:
"<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-3'B><'col-sm-9'p>>" +
"<'row'<'col-sm-12'<'table-responsive'tr>>>" +
"<'row'<'col-sm-3'B><'col-sm-9'p>>" +
"<'row'<'col-sm-12'i>>",
lengthMenu: [
[10, 25, 50, 100, -1],
[10, 25, 50, 100, "All"],
],
stateSave: true,
stateDuration: 0,
stateSaveCallback: function (settings, data) {
utils.stateSaveCallback("groups-clients-table", data);
},
],
dom:
"<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-3'B><'col-sm-9'p>>" +
"<'row'<'col-sm-12'<'table-responsive'tr>>>" +
"<'row'<'col-sm-3'B><'col-sm-9'p>>" +
"<'row'<'col-sm-12'i>>",
lengthMenu: [
[10, 25, 50, 100, -1],
[10, 25, 50, 100, "All"],
],
stateSave: true,
stateDuration: 0,
stateSaveCallback: function (settings, data) {
utils.stateSaveCallback("groups-clients-table", data);
},
stateLoadCallback: function () {
var data = utils.stateLoadCallback("groups-clients-table");
stateLoadCallback: function () {
var data = utils.stateLoadCallback("groups-clients-table");
// Return if not available
if (data === null) {
return null;
}
// Return if not available
if (data === null) {
return null;
}
// Reset visibility of ID column
data.columns[0].visible = false;
// Apply loaded state to table
return data;
},
});
// Reset visibility of ID column
data.columns[0].visible = false;
// Apply loaded state to table
return data;
},
});
// Disable autocorrect in the search box
var input = document.querySelector("input[type=search]");
@@ -358,7 +349,7 @@ $.fn.dataTable.Buttons.defaults.dom.container.className = "dt-buttons";
function deleteClient() {
// Passes the button data-id attribute as ID
var ids = [$(this).attr("data-id")];
const ids = [$(this).attr("data-id")];
delItems(ids);
}
@@ -366,18 +357,19 @@ function delItems(ids) {
// Check input validity
if (!Array.isArray(ids)) return;
var clientRaw = ids[0];
var client = clientRaw.replaceAll("__", ":");
// Get first element from array
const clientRaw = ids[0];
const client = utils.hexDecode(clientRaw);
// Remove first element from array
ids.shift();
utils.disableAll();
var idstring = ids.join(", ");
const idstring = ids.join(", ");
utils.showAlert("info", "", "Deleting client...", client);
$.ajax({
url: "/api/clients/" + client,
url: "/api/clients/" + encodeURIComponent(client),
method: "delete",
})
.done(function () {
@@ -396,16 +388,17 @@ function delItems(ids) {
table.rows().deselect();
utils.changeBulkDeleteStates(table);
// Update number of groups in the sidebar
// Update number of clients in the sidebar
updateFtlInfo();
})
.fail(function (jqXHR, exception) {
.fail(function (data, exception) {
apiFailure(data);
utils.enableAll();
utils.showAlert(
"error",
"",
"Error while deleting client(s): " + idstring,
jqXHR.responseText
data.responseText
);
console.log(exception); // eslint-disable-line no-console
});
@@ -413,7 +406,7 @@ function delItems(ids) {
function addClient() {
var ip = utils.escapeHtml($("#select").val().trim());
var comment = utils.escapeHtml($("#new_comment").val());
const comment = utils.escapeHtml($("#new_comment").val());
utils.disableAll();
utils.showAlert("info", "", "Adding client...", ip);
@@ -458,24 +451,26 @@ function addClient() {
// Update number of groups in the sidebar
updateFtlInfo();
},
error: function (jqXHR, exception) {
error: function (data, exception) {
apiFailure(data);
utils.enableAll();
utils.showAlert("error", "", "Error while adding new client", jqXHR.responseText);
utils.showAlert("error", "", "Error while adding new client", data.responseText);
console.log(exception); // eslint-disable-line no-console
},
});
}
function editClient() {
var elem = $(this).attr("id");
var tr = $(this).closest("tr");
var client = tr.attr("data-id");
var groups = tr.find("#multiselect_" + client).val();
// Convert list of string integers to list of integers
groups = groups.map(Number);
var ip = utils.escapeHtml(tr.find("#ip_" + client).text());
var name = utils.escapeHtml(tr.find("#name_" + client).text());
var comment = utils.escapeHtml(tr.find("#comment_" + client).val());
const elem = $(this).attr("id");
const tr = $(this).closest("tr");
const client = tr.attr("data-id");
// Convert list of string integers to list of integers using map(Number)
const groups = tr
.find("#multiselect_" + client)
.val()
.map(Number);
const comment = utils.escapeHtml(tr.find("#comment_" + client).val());
const enabled = tr.find("#enabled_" + client).is(":checked");
var done = "edited";
var notDone = "editing";
@@ -493,35 +488,37 @@ function editClient() {
return;
}
if (name.length > 0) {
ip += " (" + name + ")";
}
utils.disableAll();
const clientRaw = client.replaceAll("__", ":");
utils.showAlert("info", "", "Editing client...", ip);
const clientDecoded = utils.hexDecode(client);
utils.showAlert("info", "", "Editing client...", clientDecoded);
$.ajax({
url: "/api/clients/" + clientRaw,
url: "/api/clients/" + encodeURIComponent(clientDecoded),
method: "put",
dataType: "json",
data: JSON.stringify({
client: client,
groups: groups,
token: token,
comment: comment,
enabled: enabled,
}),
success: function () {
utils.enableAll();
utils.showAlert("success", "fas fa-pencil-alt", "Successfully " + done + " client", ip);
utils.showAlert(
"success",
"fas fa-pencil-alt",
"Successfully " + done + " client",
clientDecoded
);
table.ajax.reload(null, false);
},
error: function (jqXHR, exception) {
error: function (data, exception) {
apiFailure(data);
utils.enableAll();
utils.showAlert(
"error",
"",
"Error while " + notDone + " client " + clientRaw,
jqXHR.responseText
"Error while " + notDone + " client " + clientDecoded,
data.responseText
);
console.log(exception); // eslint-disable-line no-console
},

View File

@@ -0,0 +1,21 @@
/* Pi-hole: A black hole for Internet advertisements
* (c) 2023 Pi-hole, LLC (https://pi-hole.net)
* Network-wide ad blocking via your own hardware.
*
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license. */
// eslint-disable-next-line no-unused-vars
var groups = [];
// eslint-disable-next-line no-unused-vars
function getGroups() {
$.ajax({
url: "/api/groups",
type: "GET",
dataType: "json",
success: function (data) {
groups = data.groups;
},
});
}

View File

@@ -5,32 +5,13 @@
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license. */
/* global utils:false */
/* global utils:false, groups:false,, getGroups:false, updateFtlInfo:false, apiFailure:false */
var table;
var groups = [];
var token = $("#token").text();
var GETDict = {};
function getGroups() {
$.post(
"scripts/pi-hole/php/groups.php",
{ action: "get_groups", token: token },
function (data) {
groups = data.data;
initTable();
},
"json"
);
}
$(function () {
window.location.search
.substr(1)
.split("&")
.forEach(function (item) {
GETDict[item.split("=")[0]] = item.split("=")[1];
});
GETDict = utils.parseQueryString();
// sync description fields, reset inactive inputs on tab change
$('a[data-toggle="tab"]').on("shown.bs.tab", function () {
@@ -51,7 +32,7 @@ $(function () {
$("#suggest_domains").hide();
});
$("#add2black, #add2white").on("click", addDomain);
$("#add_deny, #add_allow").on("click", addDomain);
var suggestTimeout;
$("#new_domain").on("input", function (e) {
@@ -61,7 +42,7 @@ $(function () {
});
utils.setBsSelectDefaults();
getGroups();
initTable();
});
function showSuggestDomains(value) {
@@ -108,272 +89,288 @@ function hideSuggestDomains() {
}
function initTable() {
table = $("#domainsTable").DataTable({
ajax: {
url: "scripts/pi-hole/php/groups.php",
data: { action: "get_domains", token: token },
type: "POST",
},
order: [[0, "asc"]],
columns: [
{ data: "id", visible: false },
{ data: null, visible: true, orderable: false, width: "15px" },
{ data: "domain" },
{ data: "type", searchable: false },
{ data: "enabled", searchable: false },
{ data: "comment" },
{ data: "groups", searchable: false },
{ data: null, width: "22px", orderable: false },
],
columnDefs: [
{
targets: 1,
className: "select-checkbox",
render: function () {
return "";
table = $("#domainsTable")
.on("preXhr.dt", function () {
getGroups();
})
.DataTable({
processing: true,
ajax: {
url: "/api/domains",
dataSrc: "domains",
type: "GET",
},
order: [[0, "asc"]],
columns: [
{ data: "id", visible: false },
{ data: null, visible: true, orderable: false, width: "15px" },
{ data: "domain" },
{ data: "type", searchable: false },
{ data: "enabled", searchable: false },
{ data: "comment" },
{ data: "groups", searchable: false },
{ data: null, width: "22px", orderable: false },
],
columnDefs: [
{
targets: 1,
className: "select-checkbox",
render: function () {
return "";
},
},
{
targets: "_all",
render: $.fn.dataTable.render.text(),
},
],
drawCallback: function () {
// Hide buttons if all domains were deleted
var hasRows = this.api().rows({ filter: "applied" }).data().length > 0;
$(".datatable-bt").css("visibility", hasRows ? "visible" : "hidden");
$('button[id^="deleteDomain_"]').on("click", deleteDomain);
// Remove visible dropdown to prevent orphaning
$("body > .bootstrap-select.dropdown").remove();
},
{
targets: "_all",
render: $.fn.dataTable.render.text(),
},
],
drawCallback: function () {
// Hide buttons if all domains were deleted
var hasRows = this.api().rows({ filter: "applied" }).data().length > 0;
$(".datatable-bt").css("visibility", hasRows ? "visible" : "hidden");
rowCallback: function (row, data) {
var dataId = utils.hexEncode(data.domain);
$(row).attr("data-id", dataId);
var tooltip =
"Added: " +
utils.datetime(data.date_added, false) +
"\nLast modified: " +
utils.datetime(data.date_modified, false) +
"\nDatabase ID: " +
data.id;
$("td:eq(1)", row).html(
'<code id="domain_' +
dataId +
'" title="' +
tooltip +
'" class="breakall">' +
data.domain +
"</code>"
);
$('button[id^="deleteDomain_"]').on("click", deleteDomain);
// Remove visible dropdown to prevent orphaning
$("body > .bootstrap-select.dropdown").remove();
},
rowCallback: function (row, data) {
$(row).attr("data-id", data.id);
var tooltip =
"Added: " +
utils.datetime(data.date_added, false) +
"\nLast modified: " +
utils.datetime(data.date_modified, false) +
"\nDatabase ID: " +
data.id;
$("td:eq(1)", row).html(
'<code id="domain_' +
data.id +
'" title="' +
tooltip +
'" class="breakall">' +
data.domain +
"</code>"
);
// Drop-down type selector
$("td:eq(2)", row).html(
'<select id="type_' +
dataId +
'" class="form-control">' +
'<option value="allow/exact"' +
(data.type === "allow" && data.kind === "exact" ? " selected" : "") +
">Exact allow</option>" +
'<option value="allow/regex"' +
(data.type === "allow" && data.kind === "regex" ? " selected" : "") +
">Regex allow</option>" +
'<option value="deny/exact"' +
(data.type === "deny" && data.kind === "exact" ? " selected " : "") +
">Exact deny</option>" +
'<option value="deny/regex"' +
(data.type === "deny" && data.kind === "regex" ? " selected" : "") +
">Regex deny</option>" +
"</select>" +
"<input type='hidden' id='old_type_" +
dataId +
"' value='" +
data.type +
"/" +
data.kind +
"'>"
);
var typeEl = $("#type_" + dataId, row);
typeEl.on("change", editDomain);
// Drop-down type selector
$("td:eq(2)", row).html(
'<select id="type_' +
data.id +
'" class="form-control">' +
'<option value="0"' +
(data.type === 0 ? " selected" : "") +
">Exact whitelist</option>" +
'<option value="2"' +
(data.type === 2 ? " selected" : "") +
">Regex whitelist</option>" +
'<option value="1"' +
(data.type === 1 ? " selected " : " ") +
">Exact blacklist</option>" +
'<option value="3"' +
(data.type === 3 ? " selected" : "") +
">Regex blacklist</option>" +
"</select>"
);
var typeEl = $("#type_" + data.id, row);
typeEl.on("change", editDomain);
$("td:eq(3)", row).html(
'<input type="checkbox" id="enabled_' +
dataId +
'"' +
(data.enabled ? " checked" : "") +
">"
);
var statusEl = $("#enabled_" + dataId, row);
statusEl.bootstrapToggle({
on: "Enabled",
off: "Disabled",
size: "small",
onstyle: "success",
width: "80px",
});
statusEl.on("change", editDomain);
var disabled = data.enabled === 0;
$("td:eq(3)", row).html(
'<input type="checkbox" id="status_' + data.id + '"' + (disabled ? "" : " checked") + ">"
);
var statusEl = $("#status_" + data.id, row);
statusEl.bootstrapToggle({
on: "Enabled",
off: "Disabled",
size: "small",
onstyle: "success",
width: "80px",
});
statusEl.on("change", editDomain);
$("td:eq(4)", row).html('<input id="comment_' + dataId + '" class="form-control">');
var commentEl = $("#comment_" + dataId, row);
commentEl.val(utils.unescapeHtml(data.comment));
commentEl.on("change", editDomain);
$("td:eq(4)", row).html('<input id="comment_' + data.id + '" class="form-control">');
var commentEl = $("#comment_" + data.id, row);
commentEl.val(utils.unescapeHtml(data.comment));
commentEl.on("change", editDomain);
// Group assignment field
$("td:eq(5)", row).empty();
$("td:eq(5)", row).append(
'<select class="selectpicker" id="multiselect_' + dataId + '" multiple></select>'
);
var selectEl = $("#multiselect_" + dataId, row);
// Add all known groups
for (var i = 0; i < groups.length; i++) {
var dataSub = "";
if (!groups[i].enabled) {
dataSub = 'data-subtext="(disabled)"';
}
// Group assignment field
$("td:eq(5)", row).empty();
$("td:eq(5)", row).append(
'<select class="selectpicker" id="multiselect_' + data.id + '" multiple></select>'
);
var selectEl = $("#multiselect_" + data.id, row);
// Add all known groups
for (var i = 0; i < groups.length; i++) {
var dataSub = "";
if (!groups[i].enabled) {
dataSub = 'data-subtext="(disabled)"';
selectEl.append(
$("<option " + dataSub + "/>")
.val(groups[i].id)
.text(groups[i].name)
);
}
selectEl.append(
$("<option " + dataSub + "/>")
.val(groups[i].id)
.text(groups[i].name)
);
}
// Select assigned groups
selectEl.val(data.groups);
// Initialize bootstrap-select
selectEl
// fix dropdown if it would stick out right of the viewport
.on("show.bs.select", function () {
var winWidth = $(window).width();
var dropdownEl = $("body > .bootstrap-select.dropdown");
if (dropdownEl.length > 0) {
dropdownEl.removeClass("align-right");
var width = dropdownEl.width();
var left = dropdownEl.offset().left;
if (left + width > winWidth) {
dropdownEl.addClass("align-right");
// Select assigned groups
selectEl.val(data.groups);
// Initialize bootstrap-select
selectEl
// fix dropdown if it would stick out right of the viewport
.on("show.bs.select", function () {
var winWidth = $(window).width();
var dropdownEl = $("body > .bootstrap-select.dropdown");
if (dropdownEl.length > 0) {
dropdownEl.removeClass("align-right");
var width = dropdownEl.width();
var left = dropdownEl.offset().left;
if (left + width > winWidth) {
dropdownEl.addClass("align-right");
}
}
}
})
.on("changed.bs.select", function () {
// enable Apply button
if ($(applyBtn).prop("disabled")) {
$(applyBtn)
.addClass("btn-success")
.prop("disabled", false)
.on("click", function () {
editDomain.call(selectEl);
});
}
})
.on("hide.bs.select", function () {
// Restore values if drop-down menu is closed without clicking the Apply button
if (!$(applyBtn).prop("disabled")) {
$(this).val(data.groups).selectpicker("refresh");
$(applyBtn).removeClass("btn-success").prop("disabled", true).off("click");
}
})
.selectpicker()
.siblings(".dropdown-menu")
.find(".bs-actionsbox")
.prepend(
'<button type="button" id=btn_apply_' +
data.id +
' class="btn btn-block btn-sm" disabled>Apply</button>'
);
})
.on("changed.bs.select", function () {
// enable Apply button
if ($(applyBtn).prop("disabled")) {
$(applyBtn)
.addClass("btn-success")
.prop("disabled", false)
.on("click", function () {
editDomain.call(selectEl);
});
}
})
.on("hide.bs.select", function () {
// Restore values if drop-down menu is closed without clicking the Apply button
if (!$(applyBtn).prop("disabled")) {
$(this).val(data.groups).selectpicker("refresh");
$(applyBtn).removeClass("btn-success").prop("disabled", true).off("click");
}
})
.selectpicker()
.siblings(".dropdown-menu")
.find(".bs-actionsbox")
.prepend(
'<button type="button" id=btn_apply_' +
dataId +
' class="btn btn-block btn-sm" disabled>Apply</button>'
);
var applyBtn = "#btn_apply_" + data.id;
var applyBtn = "#btn_apply_" + dataId;
// Highlight row (if url parameter "domainid=" is used)
if ("domainid" in GETDict && data.id === parseInt(GETDict.domainid, 10)) {
$(row).find("td").addClass("highlight");
}
// Add delete domain button
var button =
'<button type="button" class="btn btn-danger btn-xs" id="deleteDomain_' +
data.id +
'" data-del-id="' +
data.id +
'">' +
'<span class="far fa-trash-alt"></span>' +
"</button>";
$("td:eq(6)", row).html(button);
},
select: {
style: "multi",
selector: "td:not(:last-child)",
info: false,
},
buttons: [
{
text: '<span class="far fa-square"></span>',
titleAttr: "Select All",
className: "btn-sm datatable-bt selectAll",
action: function () {
table.rows({ page: "current" }).select();
},
},
{
text: '<span class="far fa-plus-square"></span>',
titleAttr: "Select All",
className: "btn-sm datatable-bt selectMore",
action: function () {
table.rows({ page: "current" }).select();
},
},
{
extend: "selectNone",
text: '<span class="far fa-check-square"></span>',
titleAttr: "Deselect All",
className: "btn-sm datatable-bt removeAll",
},
{
text: '<span class="far fa-trash-alt"></span>',
titleAttr: "Delete Selected",
className: "btn-sm datatable-bt deleteSelected",
action: function () {
// For each ".selected" row ...
var ids = [];
$("tr.selected").each(function () {
// ... add the row identified by "data-id".
ids.push(parseInt($(this).attr("data-id"), 10));
});
// Delete all selected rows at once
delItems(ids);
},
},
],
dom:
"<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-3'B><'col-sm-9'p>>" +
"<'row'<'col-sm-12'<'table-responsive'tr>>>" +
"<'row'<'col-sm-3'B><'col-sm-9'p>>" +
"<'row'<'col-sm-12'i>>",
lengthMenu: [
[10, 25, 50, 100, -1],
[10, 25, 50, 100, "All"],
],
stateSave: true,
stateDuration: 0,
stateSaveCallback: function (settings, data) {
utils.stateSaveCallback("groups-domains-table", data);
},
stateLoadCallback: function () {
var data = utils.stateLoadCallback("groups-domains-table");
// Return if not available
if (data === null) {
return null;
}
// Reset visibility of ID column
data.columns[0].visible = false;
// Apply loaded state to table
return data;
},
initComplete: function () {
if ("domainid" in GETDict) {
var pos = table
.column(0, { order: "current" })
.data()
.indexOf(parseInt(GETDict.domainid, 10));
if (pos >= 0) {
var page = Math.floor(pos / table.page.info().length);
table.page(page).draw(false);
// Highlight row (if url parameter "domainid=" is used)
if ("domainid" in GETDict && data.id === parseInt(GETDict.domainid, 10)) {
$(row).find("td").addClass("highlight");
}
}
},
});
// Add delete domain button
var button =
'<button type="button" class="btn btn-danger btn-xs" id="deleteDomain_' +
dataId +
'" data-id="' +
dataId +
'">' +
'<span class="far fa-trash-alt"></span>' +
"</button>";
$("td:eq(6)", row).html(button);
},
select: {
style: "multi",
selector: "td:not(:last-child)",
info: false,
},
buttons: [
{
text: '<span class="far fa-square"></span>',
titleAttr: "Select All",
className: "btn-sm datatable-bt selectAll",
action: function () {
table.rows({ page: "current" }).select();
},
},
{
text: '<span class="far fa-plus-square"></span>',
titleAttr: "Select All",
className: "btn-sm datatable-bt selectMore",
action: function () {
table.rows({ page: "current" }).select();
},
},
{
extend: "selectNone",
text: '<span class="far fa-check-square"></span>',
titleAttr: "Deselect All",
className: "btn-sm datatable-bt removeAll",
},
{
text: '<span class="far fa-trash-alt"></span>',
titleAttr: "Delete Selected",
className: "btn-sm datatable-bt deleteSelected",
action: function () {
// For each ".selected" row ...
var ids = [];
$("tr.selected").each(function () {
// ... add the row identified by "data-id".
ids.push($(this).attr("data-id"));
});
// Delete all selected rows at once
delItems(ids);
},
},
],
dom:
"<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-3'B><'col-sm-9'p>>" +
"<'row'<'col-sm-12'<'table-responsive'tr>>>" +
"<'row'<'col-sm-3'B><'col-sm-9'p>>" +
"<'row'<'col-sm-12'i>>",
lengthMenu: [
[10, 25, 50, 100, -1],
[10, 25, 50, 100, "All"],
],
stateSave: true,
stateDuration: 0,
stateSaveCallback: function (settings, data) {
utils.stateSaveCallback("groups-domains-table", data);
},
stateLoadCallback: function () {
var data = utils.stateLoadCallback("groups-domains-table");
// Return if not available
if (data === null) {
return null;
}
// Reset visibility of ID column
data.columns[0].visible = false;
// Apply loaded state to table
return data;
},
initComplete: function () {
if ("domainid" in GETDict) {
var pos = table
.column(0, { order: "current" })
.data()
.indexOf(parseInt(GETDict.domainid, 10));
if (pos >= 0) {
var page = Math.floor(pos / table.page.info().length);
table.page(page).draw(false);
}
}
},
});
// Disable autocorrect in the search box
var input = document.querySelector("input[type=search]");
if (input !== null) {
@@ -410,7 +407,8 @@ $.fn.dataTable.ext.search.push(function (settings, searchData, index, rowData) {
})
.get();
if (types.indexOf(rowData.type.toString()) !== -1) {
const typeStr = rowData.type + "/" + rowData.kind;
if (types.indexOf(typeStr) !== -1) {
return true;
}
@@ -424,8 +422,8 @@ $(".filter_types input:checkbox").on("change", function () {
$.fn.dataTable.Buttons.defaults.dom.container.className = "dt-buttons";
function deleteDomain() {
// Passes the button data-del-id attribute as ID
var ids = [parseInt($(this).attr("data-del-id"), 10)];
// Passes the button data-id attribute as ID
const ids = [$(this).attr("data-id")];
delItems(ids);
}
@@ -433,250 +431,209 @@ function delItems(ids) {
// Check input validity
if (!Array.isArray(ids)) return;
var items = "";
var type = "";
var typeID = "";
// Get first element from array
const domainRaw = ids[0];
const domain = utils.hexDecode(domainRaw);
const typestr = $("#old_type_" + domainRaw).val();
for (var id of ids) {
// Exploit prevention: Return early for non-numeric IDs
if (typeof id !== "number") return;
// Retrieve domain type
typeID = $("#type_" + id).val();
if (typeID === "0" || typeID === "1") {
type = " (<i>domain</i>)";
} else if (typeID === "2" || typeID === "3") {
type = " (<i>regex</i>)";
}
// Add item
items += "<li>" + utils.escapeHtml($("#domain_" + id).text()) + type + "</li>";
}
// Remove first element from array
ids.shift();
utils.disableAll();
var idstring = ids.join(", ");
utils.showAlert("info", "", "Deleting domain(s)...", "<ul>" + items + "</ul>");
const idstring = ids.join(", ");
utils.showAlert("info", "", "Deleting domain...", "<ul>" + domain + "</ul>");
$.ajax({
url: "scripts/pi-hole/php/groups.php",
method: "post",
dataType: "json",
data: { action: "delete_domain", id: JSON.stringify(ids), token: token },
url: "/api/domains/" + typestr + "/" + encodeURIComponent(domain),
method: "delete",
})
.done(function (response) {
.done(function () {
utils.enableAll();
if (response.success) {
utils.showAlert(
"success",
"far fa-trash-alt",
"Successfully deleted domain(s): ",
"<ul>" + items + "</ul>"
);
for (var id in ids) {
if (Object.hasOwnProperty.call(ids, id)) {
table.row(id).remove().draw(false).ajax.reload(null, false);
}
}
} else {
utils.showAlert(
"error",
"",
"Error while deleting domain(s): " + idstring,
response.message
);
utils.showAlert("success", "far fa-trash-alt", "Successfully deleted list: ", domain);
table.row(domainRaw).remove().draw(false);
if (ids.length > 0) {
// Recursively delete all remaining items
delItems(ids);
return;
}
table.ajax.reload(null, false);
// Clear selection after deletion
table.rows().deselect();
utils.changeBulkDeleteStates(table);
// Update number of lists in the sidebar
updateFtlInfo();
})
.fail(function (jqXHR, exception) {
.fail(function (data, exception) {
apiFailure(data);
utils.enableAll();
utils.showAlert(
"error",
"",
"Error while deleting domain(s): " + idstring,
jqXHR.responseText
data.responseText
);
console.log(exception); // eslint-disable-line no-console
});
}
function addDomain() {
var action = this.id;
var tabHref = $('a[data-toggle="tab"][aria-expanded="true"]').attr("href");
var wildcardEl = $("#wildcard_checkbox");
var wildcardChecked = wildcardEl.prop("checked");
var type;
const action = this.id;
const tabHref = $('a[data-toggle="tab"][aria-expanded="true"]').attr("href");
const wildcardEl = $("#wildcard_checkbox");
const wildcardChecked = wildcardEl.prop("checked");
// current tab's inputs
var domainRegex, domainEl, commentEl;
var kind, domainEl, commentEl;
if (tabHref === "#tab_domain") {
domainRegex = "domain";
kind = "exact";
domainEl = $("#new_domain");
commentEl = $("#new_domain_comment");
} else if (tabHref === "#tab_regex") {
domainRegex = "regex";
kind = "regex";
domainEl = $("#new_regex");
commentEl = $("#new_regex_comment");
}
var domain = utils.escapeHtml(domainEl.val());
var comment = utils.escapeHtml(commentEl.val());
const comment = utils.escapeHtml(commentEl.val());
utils.disableAll();
utils.showAlert("info", "", "Adding " + domainRegex + "...", domain);
utils.showAlert("info", "", "Adding domain...", domain);
if (domain.length > 0) {
// strip "*." if specified by user in wildcard mode
if (domainRegex === "domain" && wildcardChecked && domain.startsWith("*.")) {
domain = domain.substr(2);
}
// determine list type
if (domainRegex === "domain" && action === "add2black" && wildcardChecked) {
type = "3W";
} else if (domainRegex === "domain" && action === "add2black" && !wildcardChecked) {
type = "1";
} else if (domainRegex === "domain" && action === "add2white" && wildcardChecked) {
type = "2W";
} else if (domainRegex === "domain" && action === "add2white" && !wildcardChecked) {
type = "0";
} else if (domainRegex === "regex" && action === "add2black") {
type = "3";
} else if (domainRegex === "regex" && action === "add2white") {
type = "2";
}
} else {
if (domain.length < 2) {
utils.enableAll();
utils.showAlert("warning", "", "Warning", "Please specify a " + domainRegex);
utils.showAlert("warning", "", "Warning", "Please specify a domain");
return;
}
// strip "*." if specified by user in wildcard mode
if (kind === "exact" && wildcardChecked && domain.startsWith("*.")) {
domain = domain.substr(2);
}
// determine list type
const type = action === "add_deny" ? "deny" : "allow";
// Transform domain to wildcard if specified by user
if (kind === "exact" && wildcardChecked) {
domain = "(\\.|^)" + domain.replaceAll(".", "\\.") + "$";
kind = "regex";
}
$.ajax({
url: "scripts/pi-hole/php/groups.php",
url: "/api/domains/" + type + "/" + kind,
method: "post",
dataType: "json",
data: {
action: "add_domain",
data: JSON.stringify({
domain: domain,
type: type,
comment: comment,
token: token,
},
success: function (response) {
type: type,
kind: kind,
}),
success: function () {
utils.enableAll();
if (response.success) {
utils.showAlert("success", "fas fa-plus", "Success!", response.message);
domainEl.val("");
commentEl.val("");
wildcardEl.prop("checked", false);
table.ajax.reload(null, false);
table.rows().deselect();
domainEl.focus();
} else {
utils.showAlert("error", "", "Error while adding new " + domainRegex, response.message);
}
utils.showAlert("success", "fas fa-plus", "Successfully added domain", domain);
table.ajax.reload(null, false);
table.rows().deselect();
// Update number of groups in the sidebar
updateFtlInfo();
},
error: function (jqXHR, exception) {
error: function (data, exception) {
apiFailure(data);
utils.enableAll();
utils.showAlert("error", "", "Error while adding new " + domainRegex, jqXHR.responseText);
utils.showAlert("error", "", "Error while adding new domain", data.responseText);
console.log(exception); // eslint-disable-line no-console
},
});
}
function editDomain() {
var elem = $(this).attr("id");
var tr = $(this).closest("tr");
var id = tr.attr("data-id");
var domain = utils.escapeHtml(tr.find("#domain_" + id).text());
var type = tr.find("#type_" + id).val();
var status = tr.find("#status_" + id).is(":checked") ? 1 : 0;
var comment = utils.escapeHtml(tr.find("#comment_" + id).val());
var groups = tr.find("#multiselect_" + id).val();
const elem = $(this).attr("id");
const tr = $(this).closest("tr");
const domain = tr.attr("data-id");
const newTypestr = tr.find("#type_" + domain).val();
const oldTypeStr = tr.find("#old_type_" + domain).val();
const enabled = tr.find("#enabled_" + domain).is(":checked");
const comment = utils.escapeHtml(tr.find("#comment_" + domain).val());
// Convert list of string integers to list of integers using map
const groups = tr
.find("#multiselect_" + domain)
.val()
.map(Number);
var domainRegex;
if (type === "0" || type === "1") {
domainRegex = "domain";
} else if (type === "2" || type === "3") {
domainRegex = "regex";
}
const oldType = oldTypeStr.split("/")[0];
const oldKind = oldTypeStr.split("/")[1];
var done = "edited";
var notDone = "editing";
switch (elem) {
case "status_" + id:
if (status === 0) {
case "enabled_" + domain:
if (enabled) {
done = "disabled";
notDone = "disabling";
} else if (status === 1) {
} else {
done = "enabled";
notDone = "enabling";
}
break;
case "name_" + id:
case "name_" + domain:
done = "edited name of";
notDone = "editing name of";
break;
case "comment_" + id:
case "comment_" + domain:
done = "edited comment of";
notDone = "editing comment of";
break;
case "type_" + id:
case "type_" + domain:
done = "edited type of";
notDone = "editing type of";
break;
case "multiselect_" + id:
case "multiselect_" + domain:
done = "edited groups of";
notDone = "editing groups of";
break;
default:
alert("bad element or invalid data-id!");
alert("bad element (" + elem + ") or invalid data-id!");
return;
}
utils.disableAll();
utils.showAlert("info", "", "Editing " + domainRegex + "...", name);
const domainDecoded = utils.hexDecode(domain);
utils.showAlert("info", "", "Editing domain...", domain);
$.ajax({
url: "scripts/pi-hole/php/groups.php",
method: "post",
url: "/api/domains/" + newTypestr + "/" + encodeURIComponent(domainDecoded),
method: "put",
dataType: "json",
data: {
action: "edit_domain",
id: id,
type: type,
comment: comment,
status: status,
data: JSON.stringify({
groups: groups,
token: token,
},
success: function (response) {
comment: comment,
enabled: enabled,
type: oldType,
kind: oldKind,
}),
success: function () {
utils.enableAll();
if (response.success) {
utils.showAlert(
"success",
"fas fa-pencil-alt",
"Successfully " + done + " " + domainRegex,
domain
);
table.ajax.reload(null, false);
} else
utils.showAlert(
"error",
"",
"Error while " + notDone + " " + domainRegex + " with ID " + id,
response.message
);
utils.showAlert(
"success",
"fas fa-pencil-alt",
"Successfully " + done + " domain",
domainDecoded
);
table.ajax.reload(null, false);
},
error: function (jqXHR, exception) {
error: function (data, exception) {
apiFailure(data);
utils.enableAll();
utils.showAlert(
"error",
"",
"Error while " + notDone + " " + domainRegex + " with ID " + id,
jqXHR.responseText
"Error while " + notDone + " domain " + domainDecoded,
data.responseText
);
console.log(exception); // eslint-disable-line no-console
},

View File

@@ -5,7 +5,7 @@
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license. */
/* global utils:false, updateFtlInfo:false */
/* global utils:false, apiFailure:false, updateFtlInfo:false */
var table,
idNames = {};
@@ -25,6 +25,7 @@ $(function () {
$("#btnAdd").on("click", addGroup);
table = $("#groupsTable").DataTable({
processing: true,
ajax: {
url: "/api/groups",
error: handleAjaxError,
@@ -220,7 +221,7 @@ $.fn.dataTable.Buttons.defaults.dom.container.className = "dt-buttons";
function deleteGroup() {
// Passes the button data-del-id attribute as ID
var ids = [parseInt($(this).attr("data-del-id"), 10)];
const ids = [parseInt($(this).attr("data-del-id"), 10)];
delItems(ids);
}
@@ -233,14 +234,15 @@ function delItems(ids) {
if (typeof id !== "number") return;
}
var id = ids[0];
var name = idNames[id];
// Get first element from array
const id = ids[0];
const name = idNames[id];
// Remove first element from array
ids.shift();
utils.disableAll();
var idstring = ids.join(", ");
const idstring = ids.join(", ");
utils.showAlert("info", "", "Deleting group...", name);
$.ajax({
@@ -266,21 +268,17 @@ function delItems(ids) {
// Update number of groups in the sidebar
updateFtlInfo();
})
.fail(function (jqXHR, exception) {
.fail(function (data, exception) {
apiFailure(data);
utils.enableAll();
utils.showAlert(
"error",
"",
"Error while deleting group(s): " + idstring,
jqXHR.responseText
);
utils.showAlert("error", "", "Error while deleting group(s): " + idstring, data.responseText);
console.log(exception); // eslint-disable-line no-console
});
}
function addGroup() {
var name = utils.escapeHtml($("#new_name").val());
var comment = utils.escapeHtml($("#new_comment").val());
const name = utils.escapeHtml($("#new_name").val());
const comment = utils.escapeHtml($("#new_comment").val());
utils.disableAll();
utils.showAlert("info", "", "Adding group...", name);
@@ -312,22 +310,23 @@ function addGroup() {
// Update number of groups in the sidebar
updateFtlInfo();
},
error: function (jqXHR, exception) {
error: function (data, exception) {
apiFailure(data);
utils.enableAll();
utils.showAlert("error", "", "Error while adding new group", jqXHR.responseText);
utils.showAlert("error", "", "Error while adding new group", data.responseText);
console.log(exception); // eslint-disable-line no-console
},
});
}
function editGroup() {
var elem = $(this).attr("id");
var tr = $(this).closest("tr");
var id = tr.attr("data-id");
var oldName = idNames[id];
var name = utils.escapeHtml(tr.find("#name_" + id).val());
var enabled = tr.find("#enabled_" + id).is(":checked");
var comment = utils.escapeHtml(tr.find("#comment_" + id).val());
const elem = $(this).attr("id");
const tr = $(this).closest("tr");
const id = tr.attr("data-id");
const oldName = idNames[id];
const name = utils.escapeHtml(tr.find("#name_" + id).val());
const enabled = tr.find("#enabled_" + id).is(":checked");
const comment = utils.escapeHtml(tr.find("#comment_" + id).val());
var done = "edited";
var notDone = "editing";
@@ -370,13 +369,14 @@ function editGroup() {
utils.enableAll();
utils.showAlert("success", "fas fa-pencil-alt", "Successfully " + done + " group", oldName);
},
error: function (jqXHR, exception) {
error: function (data, exception) {
apiFailure(data);
utils.enableAll();
utils.showAlert(
"error",
"",
"Error while " + notDone + " group with name " + oldName,
jqXHR.responseText
data.responseText
);
console.log(exception); // eslint-disable-line no-console
},

View File

@@ -489,7 +489,7 @@ $(function () {
"<'row'<'col-sm-12'<'table-responsive'tr>>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",
autoWidth: false,
processing: false,
processing: true,
order: [[0, "desc"]],
columns: [
{

View File

@@ -72,7 +72,7 @@ function padNumber(num) {
return ("00" + num).substr(-2, 2);
}
var info = null; // TODO clear this up; there shouldn't be a global var here
var info = null;
function showAlert(type, icon, title, message) {
var opts = {};
title = "&nbsp;<strong>" + title + "</strong><br>";
@@ -487,6 +487,43 @@ function getCSSval(cssclass, cssproperty) {
return val;
}
function parseQueryString(queryString = window.location.search) {
const GETDict = {};
queryString
.substr(1)
.split("&")
.forEach(function (item) {
GETDict[item.split("=")[0]] = item.split("=")[1];
});
return GETDict;
}
// https://stackoverflow.com/q/21647928
function hexEncode(string) {
var hex, i;
var result = "";
for (i = 0; i < string.length; i++) {
hex = string.codePointAt(i).toString(16);
result += ("000" + hex).slice(-4);
}
return result;
}
// https://stackoverflow.com/q/21647928
function hexDecode(string) {
var j;
var hexes = string.match(/.{1,4}/g) || [];
var back = "";
for (j = 0; j < hexes.length; j++) {
back += String.fromCodePoint(parseInt(hexes[j], 16));
}
return back;
}
window.utils = (function () {
return {
escapeHtml: escapeHtml,
@@ -517,5 +554,8 @@ window.utils = (function () {
htmlPass: htmlPass,
changeTableButtonStates: changeTableButtonStates,
getCSSval: getCSSval,
parseQueryString: parseQueryString,
hexEncode: hexEncode,
hexDecode: hexDecode,
};
})();

View File

@@ -59,7 +59,7 @@
</li>
<li class="menu-group<? if scriptname == 'groups-domains.lp' then mg.write(" active") end ?>">
<a href="groups-domains.lp">
<i class="fa fa-fw menu-icon fa-list"></i> <span class="text-red">Domains
<i class="fa fa-fw menu-icon fa-list"></i> <span class="text-green">Domains
<span class="pull-right-container">
<span class="label bg-red pull-right" id="num_denied" title="Number of deny rules (domains and regex)"></span>
<span class="label bg-green pull-right" id="num_allowed" title="Number of allow rules (domains and regex)"></span>
@@ -68,7 +68,7 @@
</li>
<li class="menu-group<? if scriptname == 'groups-adlists.lp' then mg.write(" active") end ?>">
<a href="groups-adlists.lp">
<i class="fa fa-fw menu-icon fa-shield-alt"></i> <span class="text-red">Adlists
<i class="fa fa-fw menu-icon fa-shield-alt"></i> <span class="text-green">Adlists
<span class="pull-right-container">
<span class="label bg-blue pull-right" id="num_lists" title="Number of defined adlists"></span>
<span class="label bg-yellow pull-right" id="num_gravity" title="Total number of domains blocked by your Pi-hole"></span>