/* Pi-hole: A black hole for Internet advertisements
* (c) 2020 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. */
/* global moment:false, apiFailure: false, updateFtlInfo: false, NProgress:false, WaitMe:false */
$(function () {
// CSRF protection for AJAX requests, this has to be configured globally
// because we are using the jQuery $.ajax() function directly in some cases
// Furthermore, has this to be done before any AJAX request is made so that
// the CSRF token is sent along with each request to the API
$.ajaxSetup({
headers: { "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content") },
});
});
// Credit: https://stackoverflow.com/a/4835406
function escapeHtml(text) {
var map = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
};
// Return early when text is not a string
if (typeof text !== "string") return text;
return text.replaceAll(/[&<>"']/g, function (m) {
return map[m];
});
}
function unescapeHtml(text) {
var map = {
"&": "&",
"<": "<",
">": ">",
""": '"',
"'": "'",
"Ü": "Ü",
"ü": "ü",
"Ä": "Ä",
"ä": "ä",
"Ö": "Ö",
"ö": "ö",
"ß": "ß",
};
if (text === null) return null;
return text.replaceAll(
/&(?:amp|lt|gt|quot|#039|Uuml|uuml|Auml|auml|Ouml|ouml|szlig);/g,
function (m) {
return map[m];
}
);
}
// Helper function for converting Objects to Arrays after sorting the keys
function objectToArray(obj) {
var arr = [];
var idx = [];
var keys = Object.keys(obj);
keys.sort(function (a, b) {
return a - b;
});
for (var i = 0; i < keys.length; i++) {
arr.push(obj[keys[i]]);
idx.push(keys[i]);
}
return [idx, arr];
}
function padNumber(num) {
return ("00" + num).substr(-2, 2);
}
var showAlertBox = null;
function showAlert(type, icon, title, message, toast) {
const options = {
title: " " + escapeHtml(title) + "
",
message: escapeHtml(message),
icon: icon,
},
settings = {
type: type,
delay: 5000, // default value
mouse_over: "pause",
animate: {
enter: "animate__animated animate__fadeInDown",
exit: "animate__animated animate__fadeOutUp",
},
};
switch (type) {
case "info":
options.icon = icon !== null && icon.length > 0 ? icon : "fas fa-clock";
break;
case "success":
break;
case "warning":
options.icon = "fas fa-exclamation-triangle";
settings.delay *= 2;
break;
case "error":
options.icon = "fas fa-times";
if (title.length === 0)
options.title = " Error, something went wrong!
";
settings.delay *= 2;
// If the message is an API object, nicely format the error message
// Try to parse message as JSON
try {
var data = JSON.parse(message);
console.log(data); // eslint-disable-line no-console
if (data.error !== undefined) {
options.title = " " + escapeHtml(data.error.message) + "
";
if (data.error.hint !== null) options.message = escapeHtml(data.error.hint);
}
} catch {
// Do nothing
}
break;
default:
// Case not handled, do nothing
console.log("Unknown alert type: " + type); // eslint-disable-line no-console
return;
}
if (toast === undefined) {
if (type === "info") {
// Create a new notification for info boxes
showAlertBox = $.notify(options, settings);
return showAlertBox;
} else if (showAlertBox !== null) {
// Update existing notification for other boxes (if available)
showAlertBox.update(options);
showAlertBox.update(settings);
return showAlertBox;
} else {
// Create a new notification for other boxes if no previous info box exists
return $.notify(options, settings);
}
} else if (toast === null) {
// Always create a new toast
return $.notify(options, settings);
} else {
// Update existing toast
toast.update(options);
toast.update(settings);
return toast;
}
}
function datetime(date, html, humanReadable) {
if (date === 0 && humanReadable) {
return "Never";
}
var format = html === false ? "Y-MM-DD HH:mm:ss z" : "Y-MM-DD [
]HH:mm:ss z";
var timestr = moment.unix(Math.floor(date)).format(format).trim();
return humanReadable
? '' + moment.unix(Math.floor(date)).fromNow() + ""
: timestr;
}
function datetimeRelative(date) {
return moment.unix(Math.floor(date)).fromNow();
}
function disableAll() {
$("input").prop("disabled", true);
$("select").prop("disabled", true);
$("button").prop("disabled", true);
$("textarea").prop("disabled", true);
}
function enableAll() {
$("input").prop("disabled", false);
$("select").prop("disabled", false);
$("button").prop("disabled", false);
$("textarea").prop("disabled", false);
// Enable custom input field only if applicable
var ip = $("#select") ? $("#select").val() : null;
if (ip !== null && ip !== "custom") {
$("#ip-custom").prop("disabled", true);
}
}
// Pi-hole IPv4/CIDR validator by DL6ER, see regexr.com/50csh
function validateIPv4CIDR(ip) {
// One IPv4 element is 8bit: 0 - 256
var ipv4elem = "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)";
// CIDR for IPv4 is 1 - 32 bit
var v4cidr = "(\\/([1-9]|[1-2][0-9]|3[0-2])){0,1}";
var ipv4validator = new RegExp(
"^" + ipv4elem + "\\." + ipv4elem + "\\." + ipv4elem + "\\." + ipv4elem + v4cidr + "$"
);
return ipv4validator.test(ip);
}
// Pi-hole IPv6/CIDR validator by DL6ER, see regexr.com/50csn
function validateIPv6CIDR(ip) {
// One IPv6 element is 16bit: 0000 - FFFF
var ipv6elem = "[0-9A-Fa-f]{1,4}";
// CIDR for IPv6 is 1- 128 bit
var v6cidr = "(\\/([1-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8])){0,1}";
var ipv6validator = new RegExp(
"^(((?:" +
ipv6elem +
"))*((?::" +
ipv6elem +
"))*::((?:" +
ipv6elem +
"))*((?::" +
ipv6elem +
"))*|((?:" +
ipv6elem +
"))((?::" +
ipv6elem +
")){7})" +
v6cidr +
"$"
);
return ipv6validator.test(ip);
}
function validateMAC(mac) {
var macvalidator = /^([\da-fA-F]{2}:){5}([\da-fA-F]{2})$/;
return macvalidator.test(mac);
}
function validateHostname(name) {
var namevalidator = /[^<>;"]/;
return namevalidator.test(name);
}
// set bootstrap-select defaults
function setBsSelectDefaults() {
var bsSelectDefaults = $.fn.selectpicker.Constructor.DEFAULTS;
bsSelectDefaults.noneSelectedText = "none selected";
bsSelectDefaults.selectedTextFormat = "count > 1";
bsSelectDefaults.actionsBox = true;
bsSelectDefaults.width = "fit";
bsSelectDefaults.container = "body";
bsSelectDefaults.dropdownAlignRight = "auto";
bsSelectDefaults.selectAllText = "All";
bsSelectDefaults.deselectAllText = "None";
bsSelectDefaults.countSelectedText = function (num, total) {
if (num === total) {
return "All selected (" + num + ")";
}
return num + " selected";
};
}
var backupStorage = {};
function stateSaveCallback(itemName, data) {
if (localStorage === null) {
backupStorage[itemName] = JSON.stringify(data);
} else {
localStorage.setItem(itemName, JSON.stringify(data));
}
}
function stateLoadCallback(itemName) {
var data;
// Receive previous state from client's local storage area
if (localStorage === null) {
var item = backupStorage[itemName];
data = item === "undefined" ? null : item;
} else {
data = localStorage.getItem(itemName);
}
// Return if not available
if (data === null) {
return null;
}
// Parse JSON string
data = JSON.parse(data);
// Clear possible filtering settings
data.columns.forEach(function (value, index) {
data.columns[index].search.search = "";
});
// Always start on the first page to show most recent queries
data.start = 0;
// Always start with empty search field
data.search.search = "";
// Apply loaded state to table
return data;
}
function addFromQueryLog(domain, list) {
var alertModal = $("#alertModal");
var alProcessing = alertModal.find(".alProcessing");
var alSuccess = alertModal.find(".alSuccess");
var alFailure = alertModal.find(".alFailure");
var alNetworkErr = alertModal.find(".alFailure #alNetErr");
var alCustomErr = alertModal.find(".alFailure #alCustomErr");
var alList = "#alList";
var alDomain = "#alDomain";
// Exit the function here if the Modal is already shown (multiple running interlock)
if (alertModal.css("display") !== "none") {
return;
}
var listtype = list === "allow" ? "Allowlist" : "Denylist";
alProcessing.children(alDomain).text(domain);
alProcessing.children(alList).text(listtype);
alertModal.modal("show");
// add Domain to List after Modal has faded in
alertModal.one("shown.bs.modal", function () {
$.ajax({
url: document.body.dataset.apiurl + "/domains/" + list + "/exact",
method: "post",
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
domain: domain,
comment: "Added from Query Log",
type: list,
kind: "exact",
}),
success: function (response) {
alProcessing.hide();
if ("domains" in response && response.domains.length > 0) {
// Success
alSuccess.children(alDomain).text(domain);
alSuccess.children(alList).text(listtype);
alSuccess.fadeIn(1000);
// Update domains counter in the menu
updateFtlInfo();
setTimeout(function () {
alertModal.modal("hide");
}, 2000);
} else {
// Failure
alNetworkErr.hide();
alCustomErr.html(response.message);
alFailure.fadeIn(1000);
setTimeout(function () {
alertModal.modal("hide");
}, 10000);
}
},
error: function () {
// Network Error
alProcessing.hide();
alNetworkErr.show();
alFailure.fadeIn(1000);
setTimeout(function () {
alertModal.modal("hide");
}, 8000);
},
});
});
// Reset Modal after it has faded out
alertModal.one("hidden.bs.modal", function () {
alProcessing.show();
alSuccess.add(alFailure).hide();
alProcessing.add(alSuccess).children(alDomain).html("").end().children(alList).html("");
alCustomErr.html("");
});
}
// Helper functions to format the progress bars used on the Dashboard and Long-term Lists
function addTD(content) {
return "