From 704c3522773a8a78276bed83fe5cab256a203d96 Mon Sep 17 00:00:00 2001 From: XhmikosR Date: Mon, 16 Dec 2019 13:37:34 +0200 Subject: [PATCH] Format JS code Signed-off-by: XhmikosR --- scripts/pi-hole/js/auditlog.js | 228 +-- scripts/pi-hole/js/customdns.js | 177 +-- scripts/pi-hole/js/db_graph.js | 500 +++--- scripts/pi-hole/js/db_lists.js | 325 ++-- scripts/pi-hole/js/db_queries.js | 622 ++++---- scripts/pi-hole/js/debug.js | 111 +- scripts/pi-hole/js/footer.js | 294 ++-- scripts/pi-hole/js/gravity.js | 121 +- scripts/pi-hole/js/groups-adlists.js | 65 +- scripts/pi-hole/js/groups-clients.js | 75 +- scripts/pi-hole/js/groups-domains.js | 64 +- scripts/pi-hole/js/groups.js | 58 +- scripts/pi-hole/js/index.js | 1792 +++++++++++----------- scripts/pi-hole/js/ip-address-sorting.js | 189 +-- scripts/pi-hole/js/list.js | 458 +++--- scripts/pi-hole/js/network.js | 300 ++-- scripts/pi-hole/js/queries.js | 798 +++++----- scripts/pi-hole/js/queryads.js | 216 +-- scripts/pi-hole/js/settings.js | 409 ++--- scripts/pi-hole/js/taillog-FTL.js | 61 +- scripts/pi-hole/js/taillog.js | 61 +- 21 files changed, 3536 insertions(+), 3388 deletions(-) diff --git a/scripts/pi-hole/js/auditlog.js b/scripts/pi-hole/js/auditlog.js index 6d5de9f8..d1e34d4f 100644 --- a/scripts/pi-hole/js/auditlog.js +++ b/scripts/pi-hole/js/auditlog.js @@ -1,12 +1,13 @@ /* Pi-hole: A black hole for Internet advertisements -* (c) 2017 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. */ + * (c) 2017 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. */ // Define global variables -var auditList = [], auditTimeout; +var auditList = [], + auditTimeout; // Credit: http://stackoverflow.com/questions/1787322/htmlspecialchars-equivalent-in-javascript/4835406#4835406 function escapeHtml(text) { @@ -14,123 +15,144 @@ function escapeHtml(text) { "&": "&", "<": "<", ">": ">", - "\"": """, + '"': """, "'": "'" }; - return text.replace(/[&<>"']/g, function(m) { return map[m]; }); + return text.replace(/[&<>"']/g, function(m) { + return map[m]; + }); } function updateTopLists() { - $.getJSON("api.php?topItems=audit", function(data) { + $.getJSON("api.php?topItems=audit", function(data) { + if ("FTLnotrunning" in data) { + return; + } - if("FTLnotrunning" in data) - { - return; + // Clear tables before filling them with data + $("#domain-frequency td") + .parent() + .remove(); + $("#ad-frequency td") + .parent() + .remove(); + var domaintable = $("#domain-frequency").find("tbody:last"); + var adtable = $("#ad-frequency").find("tbody:last"); + var url, domain; + for (domain in data.top_queries) { + if (Object.prototype.hasOwnProperty.call(data.top_queries, domain)) { + // Sanitize domain + domain = escapeHtml(domain); + url = '' + domain + ""; + domaintable.append( + " " + + url + + " " + + data.top_queries[domain] + + ' ' + ); + } + } + + for (domain in data.top_ads) { + if (Object.prototype.hasOwnProperty.call(data.top_ads, domain)) { + var input = domain.split(" "); + // Sanitize domain + var printdomain = escapeHtml(input[0]); + if (input.length > 1) { + url = + '' + + printdomain + + " (wildcard blocked)"; + adtable.append( + " " + + url + + " " + + data.top_ads[domain] + + ' ' + ); + } else { + url = '' + printdomain + ""; + adtable.append( + " " + + url + + " " + + data.top_ads[domain] + + ' ' + ); } + } + } - // Clear tables before filling them with data - $("#domain-frequency td").parent().remove(); - $("#ad-frequency td").parent().remove(); - var domaintable = $("#domain-frequency").find("tbody:last"); - var adtable = $("#ad-frequency").find("tbody:last"); - var url, domain; - for (domain in data.top_queries) { - if (Object.prototype.hasOwnProperty.call(data.top_queries,domain)){ - // Sanitize domain - domain = escapeHtml(domain); - url = ""+domain+""; - domaintable.append(" " + url + - " " + data.top_queries[domain] + " "); - } - } - - for (domain in data.top_ads) { - if (Object.prototype.hasOwnProperty.call(data.top_ads,domain)){ - var input = domain.split(" "); - // Sanitize domain - var printdomain = escapeHtml(input[0]); - if(input.length > 1) - { - url = ""+printdomain+" (wildcard blocked)"; - adtable.append(" " + url + - " " + data.top_ads[domain] + " "); - } - else - { - url = ""+printdomain+""; - adtable.append(" " + url + - " " + data.top_ads[domain] + " "); - } - } - } - - $("#domain-frequency .overlay").hide(); - $("#ad-frequency .overlay").hide(); - // Update top lists data every second - setTimeout(updateTopLists, 1000); - }); + $("#domain-frequency .overlay").hide(); + $("#ad-frequency .overlay").hide(); + // Update top lists data every second + setTimeout(updateTopLists, 1000); + }); } -function add(domain,list) { - var token = $("#token").text(); - $.ajax({ - url: "scripts/pi-hole/php/add.php", - method: "post", - data: {"domain":domain, "list":list, "token":token} - }); +function add(domain, list) { + var token = $("#token").text(); + $.ajax({ + url: "scripts/pi-hole/php/add.php", + method: "post", + data: { domain: domain, list: list, token: token } + }); } $(document).ready(function() { + // Pull in data via AJAX + updateTopLists(); - // Pull in data via AJAX - updateTopLists(); + $("#domain-frequency tbody").on("click", "button", function() { + var url = $(this) + .parents("tr")[0] + .textContent.split(" ")[0]; + if ($(this).context.textContent === " Blacklist") { + add(url, "audit"); + add(url, "black"); + $("#gravityBtn").prop("disabled", false); + } else { + auditUrl(url); + } + }); - $("#domain-frequency tbody").on( "click", "button", function () { - var url = ($(this).parents("tr"))[0].textContent.split(" ")[0]; - if($(this).context.textContent === " Blacklist") - { - add(url,"audit"); - add(url,"black"); - $("#gravityBtn").prop("disabled", false); - } - else - { - auditUrl(url); - } - }); - - $("#ad-frequency tbody").on( "click", "button", function () { - var url = ($(this).parents("tr"))[0].textContent.split(" ")[0].split(" ")[0]; - if($(this).context.textContent === " Whitelist") - { - add(url,"audit"); - add(url,"white"); - $("#gravityBtn").prop("disabled", false); - } - else - { - auditUrl(url); - } - }); + $("#ad-frequency tbody").on("click", "button", function() { + var url = $(this) + .parents("tr")[0] + .textContent.split(" ")[0] + .split(" ")[0]; + if ($(this).context.textContent === " Whitelist") { + add(url, "audit"); + add(url, "white"); + $("#gravityBtn").prop("disabled", false); + } else { + auditUrl(url); + } + }); }); function auditUrl(url) { - if (auditList.indexOf(url) > -1) { - return; - } - if (auditTimeout) { - clearTimeout(auditTimeout); - } - auditList.push(url); - // wait 3 seconds to see if more domains need auditing - // and batch them all into a single request - auditTimeout = setTimeout(function() { - add(auditList.join(' '), "audit"); - auditList = []; - }, 3000); + if (auditList.indexOf(url) > -1) { + return; + } + + if (auditTimeout) { + clearTimeout(auditTimeout); + } + + auditList.push(url); + // wait 3 seconds to see if more domains need auditing + // and batch them all into a single request + auditTimeout = setTimeout(function() { + add(auditList.join(" "), "audit"); + auditList = []; + }, 3000); } $("#gravityBtn").on("click", function() { - window.location.replace("gravity.php?go"); + window.location.replace("gravity.php?go"); }); diff --git a/scripts/pi-hole/js/customdns.js b/scripts/pi-hole/js/customdns.js index 3615ce70..15b9c9fc 100644 --- a/scripts/pi-hole/js/customdns.js +++ b/scripts/pi-hole/js/customdns.js @@ -1,105 +1,110 @@ /* Pi-hole: A black hole for Internet advertisements -* (c) 2017 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. */ + * (c) 2017 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. */ var table; -function showAlert(type, message) -{ - var alertElement = null; - var messageElement = null; +function showAlert(type, message) { + var alertElement = null; + var messageElement = null; - switch (type) - { - case 'info': alertElement = $('#alInfo'); break; - case 'success': alertElement = $('#alSuccess'); break; - case 'warning': alertElement = $('#alWarning'); messageElement = $('#warn'); break; - case 'error': alertElement = $('#alFailure'); messageElement = $('#err'); break; - default: return; - } + switch (type) { + case "info": + alertElement = $("#alInfo"); + break; + case "success": + alertElement = $("#alSuccess"); + break; + case "warning": + alertElement = $("#alWarning"); + messageElement = $("#warn"); + break; + case "error": + alertElement = $("#alFailure"); + messageElement = $("#err"); + break; + default: + return; + } - if (messageElement != null) - messageElement.html(message); + if (messageElement != null) messageElement.html(message); - alertElement.fadeIn(200); - alertElement.delay(8000).fadeOut(2000); + alertElement.fadeIn(200); + alertElement.delay(8000).fadeOut(2000); } $(document).ready(function() { + $("#btnAdd").on("click", addCustomDNS); - $('#btnAdd').on('click', addCustomDNS); - - table = $("#customDNSTable").DataTable( { - "ajax": "scripts/pi-hole/php/customdns.php?action=get", - columns: [ - {}, - {}, - {orderable: false, searchable: false} - ], - "columnDefs": [ { - "targets": 2, - "render": function ( data, type, row ) { - return ""; - } - } ], - "drawCallback": function() { - $('.deleteCustomDNS').on('click', deleteCustomDNS); + table = $("#customDNSTable").DataTable({ + ajax: "scripts/pi-hole/php/customdns.php?action=get", + columns: [{}, {}, { orderable: false, searchable: false }], + columnDefs: [ + { + targets: 2, + render: function(data, type, row) { + return ( + '" + ); } - }); + } + ], + drawCallback: function() { + $(".deleteCustomDNS").on("click", deleteCustomDNS); + } + }); }); -function addCustomDNS() -{ - var ip = $('#ip').val(); - var domain = $('#domain').val(); +function addCustomDNS() { + var ip = $("#ip").val(); + var domain = $("#domain").val(); - showAlert('info'); - $.ajax({ - url: "scripts/pi-hole/php/customdns.php", - method: "post", - dataType: 'json', - data: {"action":"add", "ip" : ip, "domain": domain}, - success: function(response) { - if (response.success) { - showAlert('success'); - table.ajax.reload(); - } - else - showAlert('error', response.message); - }, - error: function() { - showAlert('error', "Error while adding this custom DNS entry"); - } - }); + showAlert("info"); + $.ajax({ + url: "scripts/pi-hole/php/customdns.php", + method: "post", + dataType: "json", + data: { action: "add", ip: ip, domain: domain }, + success: function(response) { + if (response.success) { + showAlert("success"); + table.ajax.reload(); + } else showAlert("error", response.message); + }, + error: function() { + showAlert("error", "Error while adding this custom DNS entry"); + } + }); } -function deleteCustomDNS() -{ - var ip = $(this).attr("data-ip"); - var domain = $(this).attr("data-domain"); +function deleteCustomDNS() { + var ip = $(this).attr("data-ip"); + var domain = $(this).attr("data-domain"); - showAlert('info'); - $.ajax({ - url: "scripts/pi-hole/php/customdns.php", - method: "post", - dataType: 'json', - data: {"action":"delete", "domain": domain, "ip": ip}, - success: function(response) { - if (response.success) { - showAlert('success'); - table.ajax.reload(); - } - else - showAlert('error', response.message); - }, - error: function(jqXHR, exception) { - showAlert('error', "Error while deleting this custom DNS entry"); - console.log(exception); - } - }); + showAlert("info"); + $.ajax({ + url: "scripts/pi-hole/php/customdns.php", + method: "post", + dataType: "json", + data: { action: "delete", domain: domain, ip: ip }, + success: function(response) { + if (response.success) { + showAlert("success"); + table.ajax.reload(); + } else showAlert("error", response.message); + }, + error: function(jqXHR, exception) { + showAlert("error", "Error while deleting this custom DNS entry"); + console.log(exception); + } + }); } diff --git a/scripts/pi-hole/js/db_graph.js b/scripts/pi-hole/js/db_graph.js index 0ce616d6..aab3eb77 100644 --- a/scripts/pi-hole/js/db_graph.js +++ b/scripts/pi-hole/js/db_graph.js @@ -1,66 +1,97 @@ /* Pi-hole: A black hole for Internet advertisements -* (c) 2017 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. */ + * (c) 2017 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 Chart:false, moment:false */ var start__ = moment().subtract(6, "days"); -var from = moment(start__).utc().valueOf()/1000; +var from = + moment(start__) + .utc() + .valueOf() / 1000; var end__ = moment(); -var until = moment(end__).utc().valueOf()/1000; +var until = + moment(end__) + .utc() + .valueOf() / 1000; var interval = 0; var timeoutWarning = $("#timeoutWarning"); var dateformat = "MMMM Do YYYY, HH:mm"; -$(function () { - $("#querytime").daterangepicker( +$(function() { + $("#querytime").daterangepicker( { - timePicker: true, timePickerIncrement: 15, + timePicker: true, + timePickerIncrement: 15, locale: { format: dateformat }, - startDate: start__, endDate: end__, + startDate: start__, + endDate: end__, ranges: { - "Today": [moment().startOf("day"), moment()], - "Yesterday": [moment().subtract(1, "days").startOf("day"), moment().subtract(1, "days").endOf("day")], + Today: [moment().startOf("day"), moment()], + Yesterday: [ + moment() + .subtract(1, "days") + .startOf("day"), + moment() + .subtract(1, "days") + .endOf("day") + ], "Last 7 Days": [moment().subtract(6, "days"), moment()], "Last 30 Days": [moment().subtract(29, "days"), moment()], "This Month": [moment().startOf("month"), moment()], - "Last Month": [moment().subtract(1, "month").startOf("month"), moment().subtract(1, "month").endOf("month")], + "Last Month": [ + moment() + .subtract(1, "month") + .startOf("month"), + moment() + .subtract(1, "month") + .endOf("month") + ], "This Year": [moment().startOf("year"), moment()], "All Time": [moment(0), moment()] }, - "opens": "center", "showDropdowns": true, - "autoUpdateInput": false + opens: "center", + showDropdowns: true, + autoUpdateInput: false }, - function (startt, endt) { - from = moment(startt).utc().valueOf()/1000; - until = moment(endt).utc().valueOf()/1000; - }); - + function(startt, endt) { + from = + moment(startt) + .utc() + .valueOf() / 1000; + until = + moment(endt) + .utc() + .valueOf() / 1000; + } + ); }); function padNumber(num) { - return ("00" + num).substr(-2,2); + return ("00" + num).substr(-2, 2); } // Helper function needed for converting the Objects to Arrays -function objectToArray(p){ - var keys = Object.keys(p); - keys.sort(function(a, b) { - return a - b; - }); +function objectToArray(p) { + var keys = Object.keys(p); + keys.sort(function(a, b) { + return a - b; + }); - var arr = [], idx = []; - for (var i = 0; i < keys.length; i++) { - arr.push(p[keys[i]]); - idx.push(keys[i]); - } - return [idx,arr]; + var arr = [], + idx = []; + for (var i = 0; i < keys.length; i++) { + arr.push(p[keys[i]]); + idx.push(keys[i]); + } + + return [idx, arr]; } var timeLineChart; @@ -70,229 +101,238 @@ function compareNumbers(a, b) { } function updateQueriesOverTime() { - $("#queries-over-time .overlay").show(); - timeoutWarning.show(); + $("#queries-over-time .overlay").show(); + timeoutWarning.show(); - // Compute interval to obtain about 200 values - var num = 200; - interval = (until-from)/num; - // Default displaying axis scaling - timeLineChart.options.scales.xAxes[0].time.unit="hour" + // Compute interval to obtain about 200 values + var num = 200; + interval = (until - from) / num; + // Default displaying axis scaling + timeLineChart.options.scales.xAxes[0].time.unit = "hour"; - if(num*interval >= 6*29*24*60*60) - { - // If the requested data is more than 3 months, set ticks interval to quarterly - timeLineChart.options.scales.xAxes[0].time.unit="quarter" - } - else if(num*interval >= 3*29*24*60*60) - { - // If the requested data is more than 3 months, set ticks interval to months - timeLineChart.options.scales.xAxes[0].time.unit="month" - } - if(num*interval >= 29*24*60*60) - { - // If the requested data is more than 1 month, set ticks interval to weeks - timeLineChart.options.scales.xAxes[0].time.unit="week" - } - else if(num*interval >= 6*24*60*60) - { - // If the requested data is more than 1 week, set ticks interval to days - timeLineChart.options.scales.xAxes[0].time.unit="day" - } + if (num * interval >= 6 * 29 * 24 * 60 * 60) { + // If the requested data is more than 3 months, set ticks interval to quarterly + timeLineChart.options.scales.xAxes[0].time.unit = "quarter"; + } else if (num * interval >= 3 * 29 * 24 * 60 * 60) { + // If the requested data is more than 3 months, set ticks interval to months + timeLineChart.options.scales.xAxes[0].time.unit = "month"; + } - $.getJSON("api_db.php?getGraphData&from="+from+"&until="+until+"&interval="+interval, function(data) { + if (num * interval >= 29 * 24 * 60 * 60) { + // If the requested data is more than 1 month, set ticks interval to weeks + timeLineChart.options.scales.xAxes[0].time.unit = "week"; + } else if (num * interval >= 6 * 24 * 60 * 60) { + // If the requested data is more than 1 week, set ticks interval to days + timeLineChart.options.scales.xAxes[0].time.unit = "day"; + } - // convert received objects to arrays - data.domains_over_time = objectToArray(data.domains_over_time); - data.ads_over_time = objectToArray(data.ads_over_time); - // Remove possibly already existing data - timeLineChart.data.labels = []; - timeLineChart.data.datasets[0].data = []; - timeLineChart.data.datasets[1].data = []; + $.getJSON( + "api_db.php?getGraphData&from=" + from + "&until=" + until + "&interval=" + interval, + function(data) { + // convert received objects to arrays + data.domains_over_time = objectToArray(data.domains_over_time); + data.ads_over_time = objectToArray(data.ads_over_time); + // Remove possibly already existing data + timeLineChart.data.labels = []; + timeLineChart.data.datasets[0].data = []; + timeLineChart.data.datasets[1].data = []; - var dates = [], hour; + var dates = [], + hour; - for (hour in data.domains_over_time[0]) { - if (Object.prototype.hasOwnProperty.call(data.domains_over_time[0], hour)) { - dates.push(parseInt(data.domains_over_time[0][hour])); - } + for (hour in data.domains_over_time[0]) { + if (Object.prototype.hasOwnProperty.call(data.domains_over_time[0], hour)) { + dates.push(parseInt(data.domains_over_time[0][hour])); } + } - for (hour in data.ads_over_time[0]) { - if (Object.prototype.hasOwnProperty.call(data.ads_over_time[0], hour)) { - if(dates.indexOf(parseInt(data.ads_over_time[0][hour])) === -1) - { - dates.push(parseInt(data.ads_over_time[0][hour])); - } - } + for (hour in data.ads_over_time[0]) { + if (Object.prototype.hasOwnProperty.call(data.ads_over_time[0], hour)) { + if (dates.indexOf(parseInt(data.ads_over_time[0][hour])) === -1) { + dates.push(parseInt(data.ads_over_time[0][hour])); + } } + } - dates.sort(compareNumbers); + dates.sort(compareNumbers); - // Add data for each hour that is available - for (hour in dates) { - if (Object.prototype.hasOwnProperty.call(dates, hour)) { - var date, dom = 0, ads = 0; - date = new Date(1000*dates[hour]); + // Add data for each hour that is available + for (hour in dates) { + if (Object.prototype.hasOwnProperty.call(dates, hour)) { + var date, + dom = 0, + ads = 0; + date = new Date(1000 * dates[hour]); - var idx = data.domains_over_time[0].indexOf(dates[hour].toString()); - if (idx > -1) - { - dom = data.domains_over_time[1][idx]; - } + var idx = data.domains_over_time[0].indexOf(dates[hour].toString()); + if (idx > -1) { + dom = data.domains_over_time[1][idx]; + } - idx = data.ads_over_time[0].indexOf(dates[hour].toString()); - if (idx > -1) - { - ads = data.ads_over_time[1][idx]; - } + idx = data.ads_over_time[0].indexOf(dates[hour].toString()); + if (idx > -1) { + ads = data.ads_over_time[1][idx]; + } - timeLineChart.data.labels.push(date); - timeLineChart.data.datasets[0].data.push(dom - ads); - timeLineChart.data.datasets[1].data.push(ads); - } + timeLineChart.data.labels.push(date); + timeLineChart.data.datasets[0].data.push(dom - ads); + timeLineChart.data.datasets[1].data.push(ads); } + } - timeLineChart.options.scales.xAxes[0].display=true; - $("#queries-over-time .overlay").hide(); - timeoutWarning.hide(); - timeLineChart.update(); - }); + timeLineChart.options.scales.xAxes[0].display = true; + $("#queries-over-time .overlay").hide(); + timeoutWarning.hide(); + timeLineChart.update(); + } + ); } $(document).ready(function() { - var ctx = document.getElementById("queryOverTimeChart").getContext("2d"); - timeLineChart = new Chart(ctx, { - type: "bar", - data: { - labels: [ ], - datasets: [ - { - label: "Permitted DNS Queries", - fill: true, - backgroundColor: "rgba(0, 166, 90,.8)", - borderColor: "rgba(0, 166, 90,.8)", - pointBorderColor: "rgba(0, 166, 90,.8)", - pointRadius: 1, - pointHoverRadius: 5, - data: [], - pointHitRadius: 5 - }, - { - label: "Blocked DNS Queries", - fill: true, - backgroundColor: "rgba(0,192,239,1)", - borderColor: "rgba(0,192,239,1)", - pointBorderColor: "rgba(0,192,239,1)", - pointRadius: 1, - pointHoverRadius: 5, - data: [], - pointHitRadius: 5 - } - ] + var ctx = document.getElementById("queryOverTimeChart").getContext("2d"); + timeLineChart = new Chart(ctx, { + type: "bar", + data: { + labels: [], + datasets: [ + { + label: "Permitted DNS Queries", + fill: true, + backgroundColor: "rgba(0, 166, 90,.8)", + borderColor: "rgba(0, 166, 90,.8)", + pointBorderColor: "rgba(0, 166, 90,.8)", + pointRadius: 1, + pointHoverRadius: 5, + data: [], + pointHitRadius: 5 }, - options: { - tooltips: { - enabled: true, - mode: "x-axis", - callbacks: { - title: function(tooltipItem) { - var label = tooltipItem[0].xLabel; - var time = new Date(label); - var from_date = time.getFullYear() + - "-" + - padNumber(time.getMonth()+1) + - "-" + - padNumber(time.getDate()) + - " " + - padNumber(time.getHours()) + - ":" + - padNumber(time.getMinutes()) + - ":" + - padNumber(time.getSeconds()); - time = new Date(time.valueOf() + 1000 * interval); - var until_date = time.getFullYear() + - "-" + - padNumber(time.getMonth()+1) + - "-" + - padNumber(time.getDate()) + - " " + - padNumber(time.getHours()) + - ":" + - padNumber(time.getMinutes()) + - ":" + - padNumber(time.getSeconds()); - return "Queries from " + from_date + " to " + until_date; - }, - label: function(tooltipItems, data) { - if(tooltipItems.datasetIndex === 1) - { - var percentage = 0.0; - var total = parseInt(data.datasets[0].data[tooltipItems.index]); - var blocked = parseInt(data.datasets[1].data[tooltipItems.index]); - if(total > 0) - { - percentage = 100.0*blocked/total; - } - return data.datasets[tooltipItems.datasetIndex].label + ": " + tooltipItems.yLabel + " (" + percentage.toFixed(1) + "%)"; - } - - return data.datasets[tooltipItems.datasetIndex].label + ": " + tooltipItems.yLabel; - } - } - }, - legend: { - display: false - }, - scales: { - xAxes: [{ - type: "time", - stacked: true, - time: { - unit: "hour", - displayFormats: { - "minute": "HH:mm", - "hour": "HH:mm", - "day": "MMM DD", - "week": "MMM DD", - "month": "MMM", - "quarter": "MMM", - "year": "YYYY MMM" - } - } - }], - yAxes: [{ - stacked: true, - ticks: { - beginAtZero: true - } - }] - }, - maintainAspectRatio: false + { + label: "Blocked DNS Queries", + fill: true, + backgroundColor: "rgba(0,192,239,1)", + borderColor: "rgba(0,192,239,1)", + pointBorderColor: "rgba(0,192,239,1)", + pointRadius: 1, + pointHoverRadius: 5, + data: [], + pointHitRadius: 5 } - }); + ] + }, + options: { + tooltips: { + enabled: true, + mode: "x-axis", + callbacks: { + title: function(tooltipItem) { + var label = tooltipItem[0].xLabel; + var time = new Date(label); + var from_date = + time.getFullYear() + + "-" + + padNumber(time.getMonth() + 1) + + "-" + + padNumber(time.getDate()) + + " " + + padNumber(time.getHours()) + + ":" + + padNumber(time.getMinutes()) + + ":" + + padNumber(time.getSeconds()); + time = new Date(time.valueOf() + 1000 * interval); + var until_date = + time.getFullYear() + + "-" + + padNumber(time.getMonth() + 1) + + "-" + + padNumber(time.getDate()) + + " " + + padNumber(time.getHours()) + + ":" + + padNumber(time.getMinutes()) + + ":" + + padNumber(time.getSeconds()); + return "Queries from " + from_date + " to " + until_date; + }, + label: function(tooltipItems, data) { + if (tooltipItems.datasetIndex === 1) { + var percentage = 0.0; + var total = parseInt(data.datasets[0].data[tooltipItems.index]); + var blocked = parseInt(data.datasets[1].data[tooltipItems.index]); + if (total > 0) { + percentage = (100.0 * blocked) / total; + } + + return ( + data.datasets[tooltipItems.datasetIndex].label + + ": " + + tooltipItems.yLabel + + " (" + + percentage.toFixed(1) + + "%)" + ); + } + + return data.datasets[tooltipItems.datasetIndex].label + ": " + tooltipItems.yLabel; + } + } + }, + legend: { + display: false + }, + scales: { + xAxes: [ + { + type: "time", + stacked: true, + time: { + unit: "hour", + displayFormats: { + minute: "HH:mm", + hour: "HH:mm", + day: "MMM DD", + week: "MMM DD", + month: "MMM", + quarter: "MMM", + year: "YYYY MMM" + } + } + } + ], + yAxes: [ + { + stacked: true, + ticks: { + beginAtZero: true + } + } + ] + }, + maintainAspectRatio: false + } + }); }); $("#querytime").on("apply.daterangepicker", function(ev, picker) { - $(this).val(picker.startDate.format(dateformat) + " to " + picker.endDate.format(dateformat)); - $("#queries-over-time").show(); - updateQueriesOverTime(); + $(this).val(picker.startDate.format(dateformat) + " to " + picker.endDate.format(dateformat)); + $("#queries-over-time").show(); + updateQueriesOverTime(); }); -$("#queryOverTimeChart").click(function(evt){ - var activePoints = timeLineChart.getElementAtEvent(evt); - if(activePoints.length > 0) - { - //get the internal index in the chart - var clickedElementindex = activePoints[0]._index; +$("#queryOverTimeChart").click(function(evt) { + var activePoints = timeLineChart.getElementAtEvent(evt); + if (activePoints.length > 0) { + //get the internal index in the chart + var clickedElementindex = activePoints[0]._index; - //get specific label by index - var label = timeLineChart.data.labels[clickedElementindex]; + //get specific label by index + var label = timeLineChart.data.labels[clickedElementindex]; - //get value by index - var from = label/1000; - var until = label/1000 + 600; - window.location.href = "db_queries.php?from="+from+"&until="+until; - } - return false; + //get value by index + var from = label / 1000; + var until = label / 1000 + 600; + window.location.href = "db_queries.php?from=" + from + "&until=" + until; + } + + return false; }); diff --git a/scripts/pi-hole/js/db_lists.js b/scripts/pi-hole/js/db_lists.js index 42104ee9..3f055fe8 100644 --- a/scripts/pi-hole/js/db_lists.js +++ b/scripts/pi-hole/js/db_lists.js @@ -1,45 +1,75 @@ /* Pi-hole: A black hole for Internet advertisements -* (c) 2017 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. */ + * (c) 2017 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 */ var start__ = moment().subtract(6, "days"); -var from = moment(start__).utc().valueOf()/1000; +var from = + moment(start__) + .utc() + .valueOf() / 1000; var end__ = moment(); -var until = moment(end__).utc().valueOf()/1000; +var until = + moment(end__) + .utc() + .valueOf() / 1000; var timeoutWarning = $("#timeoutWarning"); var listsStillLoading = 0; var dateformat = "MMMM Do YYYY, HH:mm"; -$(function () { - $("#querytime").daterangepicker( +$(function() { + $("#querytime").daterangepicker( { - timePicker: true, timePickerIncrement: 15, + timePicker: true, + timePickerIncrement: 15, locale: { format: dateformat }, - startDate: start__, endDate: end__, + startDate: start__, + endDate: end__, ranges: { - "Today": [moment().startOf("day"), moment()], - "Yesterday": [moment().subtract(1, "days").startOf("day"), moment().subtract(1, "days").endOf("day")], + Today: [moment().startOf("day"), moment()], + Yesterday: [ + moment() + .subtract(1, "days") + .startOf("day"), + moment() + .subtract(1, "days") + .endOf("day") + ], "Last 7 Days": [moment().subtract(6, "days"), moment()], "Last 30 Days": [moment().subtract(29, "days"), moment()], "This Month": [moment().startOf("month"), moment()], - "Last Month": [moment().subtract(1, "month").startOf("month"), moment().subtract(1, "month").endOf("month")], + "Last Month": [ + moment() + .subtract(1, "month") + .startOf("month"), + moment() + .subtract(1, "month") + .endOf("month") + ], "This Year": [moment().startOf("year"), moment()], "All Time": [moment(0), moment()] }, - "opens": "center", "showDropdowns": true, - "autoUpdateInput": false + opens: "center", + showDropdowns: true, + autoUpdateInput: false }, - function (startt, endt) { - from = moment(startt).utc().valueOf()/1000; - until = moment(endt).utc().valueOf()/1000; - }); + function(startt, endt) { + from = + moment(startt) + .utc() + .valueOf() / 1000; + until = + moment(endt) + .utc() + .valueOf() / 1000; + } + ); }); // Credit: http://stackoverflow.com/questions/1787322/htmlspecialchars-equivalent-in-javascript/4835406#4835406 @@ -48,151 +78,174 @@ function escapeHtml(text) { "&": "&", "<": "<", ">": ">", - "\"": """, + '"': """, "'": "'" }; - return text.replace(/[&<>"']/g, function(m) { return map[m]; }); + return text.replace(/[&<>"']/g, function(m) { + return map[m]; + }); } function updateTopClientsChart() { - $("#client-frequency .overlay").show(); - $.getJSON("api_db.php?topClients&from="+from+"&until="+until, function(data) { + $("#client-frequency .overlay").show(); + $.getJSON("api_db.php?topClients&from=" + from + "&until=" + until, function(data) { + // Clear tables before filling them with data + $("#client-frequency td") + .parent() + .remove(); + var clienttable = $("#client-frequency").find("tbody:last"); + var client, percentage, clientname; + var sum = 0; + for (client in data.top_sources) { + if (Object.prototype.hasOwnProperty.call(data.top_sources, client)) { + sum += data.top_sources[client]; + } + } - // Clear tables before filling them with data - $("#client-frequency td").parent().remove(); - var clienttable = $("#client-frequency").find("tbody:last"); - var client, percentage, clientname; - var sum = 0; - for (client in data.top_sources) { - if (Object.prototype.hasOwnProperty.call(data.top_sources, client)){ - sum += data.top_sources[client]; - } + for (client in data.top_sources) { + if (Object.prototype.hasOwnProperty.call(data.top_sources, client)) { + // Sanitize client + client = escapeHtml(client); + if (escapeHtml(client) !== client) { + // Make a copy with the escaped index if necessary + data.top_sources[escapeHtml(client)] = data.top_sources[client]; } - for (client in data.top_sources) { - - if (Object.prototype.hasOwnProperty.call(data.top_sources, client)){ - // Sanitize client - client = escapeHtml(client); - if(escapeHtml(client) !== client) - { - // Make a copy with the escaped index if necessary - data.top_sources[escapeHtml(client)] = data.top_sources[client]; - } - if(client.indexOf("|") > -1) - { - var idx = client.indexOf("|"); - clientname = client.substr(0, idx); - } - else - { - clientname = client; - } - - percentage = data.top_sources[client] / sum * 100.0; - clienttable.append(" " + clientname + - " " + data.top_sources[client] + "
"); - } - + if (client.indexOf("|") > -1) { + var idx = client.indexOf("|"); + clientname = client.substr(0, idx); + } else { + clientname = client; } - $("#client-frequency .overlay").hide(); + percentage = (data.top_sources[client] / sum) * 100.0; + clienttable.append( + " " + + clientname + + " " + + data.top_sources[client] + + '
' + ); + } + } - listsStillLoading--; - if(listsStillLoading === 0) - timeoutWarning.hide(); - }); + $("#client-frequency .overlay").hide(); + + listsStillLoading--; + if (listsStillLoading === 0) timeoutWarning.hide(); + }); } function updateTopDomainsChart() { - $("#domain-frequency .overlay").show(); - $.getJSON("api_db.php?topDomains&from="+from+"&until="+until, function(data) { + $("#domain-frequency .overlay").show(); + $.getJSON("api_db.php?topDomains&from=" + from + "&until=" + until, function(data) { + // Clear tables before filling them with data + $("#domain-frequency td") + .parent() + .remove(); + var domaintable = $("#domain-frequency").find("tbody:last"); + var domain, percentage; + var sum = 0; + for (domain in data.top_domains) { + if (Object.prototype.hasOwnProperty.call(data.top_domains, domain)) { + sum += data.top_domains[domain]; + } + } - // Clear tables before filling them with data - $("#domain-frequency td").parent().remove(); - var domaintable = $("#domain-frequency").find("tbody:last"); - var domain, percentage; - var sum = 0; - for (domain in data.top_domains) { - if (Object.prototype.hasOwnProperty.call(data.top_domains, domain)){ - sum += data.top_domains[domain]; - } + for (domain in data.top_domains) { + if (Object.prototype.hasOwnProperty.call(data.top_domains, domain)) { + // Sanitize domain + domain = escapeHtml(domain); + if (escapeHtml(domain) !== domain) { + // Make a copy with the escaped index if necessary + data.top_domains[escapeHtml(domain)] = data.top_domains[domain]; } - for (domain in data.top_domains) { + percentage = (data.top_domains[domain] / sum) * 100.0; + domaintable.append( + " " + + domain + + " " + + data.top_domains[domain] + + '
' + ); + } + } - if (Object.prototype.hasOwnProperty.call(data.top_domains, domain)){ - // Sanitize domain - domain = escapeHtml(domain); - if(escapeHtml(domain) !== domain) - { - // Make a copy with the escaped index if necessary - data.top_domains[escapeHtml(domain)] = data.top_domains[domain]; - } + $("#domain-frequency .overlay").hide(); - percentage = data.top_domains[domain] / sum * 100.0; - domaintable.append(" " + domain + - " " + data.top_domains[domain] + "
"); - } - - } - - $("#domain-frequency .overlay").hide(); - - listsStillLoading--; - if(listsStillLoading === 0) - timeoutWarning.hide(); - }); + listsStillLoading--; + if (listsStillLoading === 0) timeoutWarning.hide(); + }); } function updateTopAdsChart() { - $("#ad-frequency .overlay").show(); - $.getJSON("api_db.php?topAds&from="+from+"&until="+until, function(data) { + $("#ad-frequency .overlay").show(); + $.getJSON("api_db.php?topAds&from=" + from + "&until=" + until, function(data) { + // Clear tables before filling them with data + $("#ad-frequency td") + .parent() + .remove(); + var adtable = $("#ad-frequency").find("tbody:last"); + var ad, percentage; + var sum = 0; + for (ad in data.top_ads) { + if (Object.prototype.hasOwnProperty.call(data.top_ads, ad)) { + sum += data.top_ads[ad]; + } + } - // Clear tables before filling them with data - $("#ad-frequency td").parent().remove(); - var adtable = $("#ad-frequency").find("tbody:last"); - var ad, percentage; - var sum = 0; - for (ad in data.top_ads) { - if (Object.prototype.hasOwnProperty.call(data.top_ads, ad)){ - sum += data.top_ads[ad]; - } + for (ad in data.top_ads) { + if (Object.prototype.hasOwnProperty.call(data.top_ads, ad)) { + // Sanitize ad + ad = escapeHtml(ad); + if (escapeHtml(ad) !== ad) { + // Make a copy with the escaped index if necessary + data.top_ads[escapeHtml(ad)] = data.top_ads[ad]; } - for (ad in data.top_ads) { + percentage = (data.top_ads[ad] / sum) * 100.0; + adtable.append( + " " + + ad + + " " + + data.top_ads[ad] + + '
' + ); + } + } - if (Object.prototype.hasOwnProperty.call(data.top_ads, ad)){ - // Sanitize ad - ad = escapeHtml(ad); - if(escapeHtml(ad) !== ad) - { - // Make a copy with the escaped index if necessary - data.top_ads[escapeHtml(ad)] = data.top_ads[ad]; - } + $("#ad-frequency .overlay").hide(); - percentage = data.top_ads[ad] / sum * 100.0; - adtable.append(" " + ad + " " + data.top_ads[ad] + "
"); - } - - } - - $("#ad-frequency .overlay").hide(); - - listsStillLoading--; - if(listsStillLoading === 0) - timeoutWarning.hide(); - }); + listsStillLoading--; + if (listsStillLoading === 0) timeoutWarning.hide(); + }); } $("#querytime").on("apply.daterangepicker", function(ev, picker) { - $(this).val(picker.startDate.format(dateformat) + " to " + picker.endDate.format(dateformat)); - timeoutWarning.show(); - listsStillLoading = 3; - updateTopClientsChart(); - updateTopDomainsChart(); - updateTopAdsChart(); + $(this).val(picker.startDate.format(dateformat) + " to " + picker.endDate.format(dateformat)); + timeoutWarning.show(); + listsStillLoading = 3; + updateTopClientsChart(); + updateTopDomainsChart(); + updateTopAdsChart(); }); diff --git a/scripts/pi-hole/js/db_queries.js b/scripts/pi-hole/js/db_queries.js index 2822f98d..d7f4fe12 100644 --- a/scripts/pi-hole/js/db_queries.js +++ b/scripts/pi-hole/js/db_queries.js @@ -1,16 +1,22 @@ /* Pi-hole: A black hole for Internet advertisements -* (c) 2017 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. */ + * (c) 2017 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 */ var start__ = moment().subtract(6, "days"); -var from = moment(start__).utc().valueOf()/1000; +var from = + moment(start__) + .utc() + .valueOf() / 1000; var end__ = moment(); -var until = moment(end__).utc().valueOf()/1000; +var until = + moment(end__) + .utc() + .valueOf() / 1000; var instantquery = false; var daterange; @@ -20,324 +26,364 @@ var dateformat = "MMMM Do YYYY, HH:mm"; // Do we want to filter queries? var GETDict = {}; -window.location.search.substr(1).split("&").forEach(function(item) {GETDict[item.split("=")[0]] = item.split("=")[1];}); +window.location.search + .substr(1) + .split("&") + .forEach(function(item) { + GETDict[item.split("=")[0]] = item.split("=")[1]; + }); -if("from" in GETDict && "until" in GETDict) -{ - from = parseInt(GETDict.from); - until = parseInt(GETDict.until); - start__ = moment(1000*from); - end__ = moment(1000*until); - instantquery = true; +if ("from" in GETDict && "until" in GETDict) { + from = parseInt(GETDict.from); + until = parseInt(GETDict.until); + start__ = moment(1000 * from); + end__ = moment(1000 * until); + instantquery = true; } -$(function () { - daterange = $("#querytime").daterangepicker( +$(function() { + daterange = $("#querytime").daterangepicker( { - timePicker: true, timePickerIncrement: 15, + timePicker: true, + timePickerIncrement: 15, locale: { format: dateformat }, - startDate: start__, endDate: end__, + startDate: start__, + endDate: end__, ranges: { - "Today": [moment().startOf("day"), moment()], - "Yesterday": [moment().subtract(1, "days").startOf("day"), moment().subtract(1, "days").endOf("day")], + Today: [moment().startOf("day"), moment()], + Yesterday: [ + moment() + .subtract(1, "days") + .startOf("day"), + moment() + .subtract(1, "days") + .endOf("day") + ], "Last 7 Days": [moment().subtract(6, "days"), moment()], "Last 30 Days": [moment().subtract(29, "days"), moment()], "This Month": [moment().startOf("month"), moment()], - "Last Month": [moment().subtract(1, "month").startOf("month"), moment().subtract(1, "month").endOf("month")], + "Last Month": [ + moment() + .subtract(1, "month") + .startOf("month"), + moment() + .subtract(1, "month") + .endOf("month") + ], "This Year": [moment().startOf("year"), moment()], "All Time": [moment(0), moment()] }, - "opens": "center", "showDropdowns": true, - "autoUpdateInput": false + opens: "center", + showDropdowns: true, + autoUpdateInput: false }, - function (startt, endt) { - from = moment(startt).utc().valueOf()/1000; - until = moment(endt).utc().valueOf()/1000; - }); + function(startt, endt) { + from = + moment(startt) + .utc() + .valueOf() / 1000; + until = + moment(endt) + .utc() + .valueOf() / 1000; + } + ); }); var tableApi, statistics; -function add(domain,list) { - var token = $("#token").text(); - var alInfo = $("#alInfo"); - var alList = $("#alList"); - var alDomain = $("#alDomain"); - alDomain.html(domain); - var alSuccess = $("#alSuccess"); - var alFailure = $("#alFailure"); - var err = $("#err"); +function add(domain, list) { + var token = $("#token").text(); + var alInfo = $("#alInfo"); + var alList = $("#alList"); + var alDomain = $("#alDomain"); + alDomain.html(domain); + var alSuccess = $("#alSuccess"); + var alFailure = $("#alFailure"); + var err = $("#err"); - if(list === "white") - { - alList.html("Whitelist"); - } - else - { - alList.html("Blacklist"); - } + if (list === "white") { + alList.html("Whitelist"); + } else { + alList.html("Blacklist"); + } - alInfo.show(); - alSuccess.hide(); - alFailure.hide(); - $.ajax({ - url: "scripts/pi-hole/php/add.php", - method: "post", - data: {"domain":domain, "list":list, "token":token}, - success: function(response) { - if (response.indexOf("not a valid argument") >= 0 || response.indexOf("is not a valid domain") >= 0) - { - alFailure.show(); - err.html(response); - alFailure.delay(4000).fadeOut(2000, function() { alFailure.hide(); }); - } - else - { - alSuccess.show(); - alSuccess.delay(1000).fadeOut(2000, function() { alSuccess.hide(); }); - } - alInfo.delay(1000).fadeOut(2000, function() { - alInfo.hide(); - alList.html(""); - alDomain.html(""); - }); - }, - error: function() { - alFailure.show(); - err.html(""); - alFailure.delay(1000).fadeOut(2000, function() { - alFailure.hide(); - }); - alInfo.delay(1000).fadeOut(2000, function() { - alInfo.hide(); - alList.html(""); - alDomain.html(""); - }); - } - }); -} -function handleAjaxError( xhr, textStatus ) { - if ( textStatus === "timeout" ) - { - alert( "The server took too long to send the data." ); + alInfo.show(); + alSuccess.hide(); + alFailure.hide(); + $.ajax({ + url: "scripts/pi-hole/php/add.php", + method: "post", + data: { domain: domain, list: list, token: token }, + success: function(response) { + if ( + response.indexOf("not a valid argument") >= 0 || + response.indexOf("is not a valid domain") >= 0 + ) { + alFailure.show(); + err.html(response); + alFailure.delay(4000).fadeOut(2000, function() { + alFailure.hide(); + }); + } else { + alSuccess.show(); + alSuccess.delay(1000).fadeOut(2000, function() { + alSuccess.hide(); + }); + } + + alInfo.delay(1000).fadeOut(2000, function() { + alInfo.hide(); + alList.html(""); + alDomain.html(""); + }); + }, + error: function() { + alFailure.show(); + err.html(""); + alFailure.delay(1000).fadeOut(2000, function() { + alFailure.hide(); + }); + alInfo.delay(1000).fadeOut(2000, function() { + alInfo.hide(); + alList.html(""); + alDomain.html(""); + }); } - else if(xhr.responseText.indexOf("Connection refused") >= 0) - { - alert( "An error occurred while loading the data: Connection refused. Is FTL running?" ); - } - else - { - alert( "An unknown error occurred while loading the data.\n"+xhr.responseText ); - } - $("#all-queries_processing").hide(); - tableApi.clear(); - tableApi.draw(); + }); } -function getQueryTypes() -{ - var queryType = []; - if($("#type_gravity").prop("checked")) - { - queryType.push(1); - } - if($("#type_forwarded").prop("checked")) - { - queryType.push(2); - } - if($("#type_cached").prop("checked")) - { - queryType.push(3); - } - if($("#type_regex").prop("checked")) - { - queryType.push(4); - } - if($("#type_blacklist").prop("checked")) - { - queryType.push(5); - } - if($("#type_external").prop("checked")) - { - // Multiple IDs correspond to this status - // We request queries with all of them - queryType.push([6,7,8]); - } - return queryType.join(","); +function handleAjaxError(xhr, textStatus) { + if (textStatus === "timeout") { + alert("The server took too long to send the data."); + } else if (xhr.responseText.indexOf("Connection refused") >= 0) { + alert("An error occurred while loading the data: Connection refused. Is FTL running?"); + } else { + alert("An unknown error occurred while loading the data.\n" + xhr.responseText); + } + + $("#all-queries_processing").hide(); + tableApi.clear(); + tableApi.draw(); } -var reloadCallback = function() -{ - timeoutWarning.hide(); - statistics = [0,0,0,0]; - var data = tableApi.rows().data(); - for (var i = 0; i < data.length; i++) { - statistics[0]++; - if(data[i][4] === 1) - { - statistics[2]++; - } - else if(data[i][4] === 3) - { - statistics[1]++; - } - else if(data[i][4] === 4) - { - statistics[3]++; - } - } - $("h3#dns_queries").text(statistics[0].toLocaleString()); - $("h3#ads_blocked_exact").text(statistics[2].toLocaleString()); - $("h3#ads_wildcard_blocked").text(statistics[3].toLocaleString()); +function getQueryTypes() { + var queryType = []; + if ($("#type_gravity").prop("checked")) { + queryType.push(1); + } - var percent = 0.0; - if(statistics[2] + statistics[3] > 0) - { - percent = 100.0*(statistics[2] + statistics[3]) / statistics[0]; + if ($("#type_forwarded").prop("checked")) { + queryType.push(2); + } + + if ($("#type_cached").prop("checked")) { + queryType.push(3); + } + + if ($("#type_regex").prop("checked")) { + queryType.push(4); + } + + if ($("#type_blacklist").prop("checked")) { + queryType.push(5); + } + + if ($("#type_external").prop("checked")) { + // Multiple IDs correspond to this status + // We request queries with all of them + queryType.push([6, 7, 8]); + } + + return queryType.join(","); +} + +var reloadCallback = function() { + timeoutWarning.hide(); + statistics = [0, 0, 0, 0]; + var data = tableApi.rows().data(); + for (var i = 0; i < data.length; i++) { + statistics[0]++; + if (data[i][4] === 1) { + statistics[2]++; + } else if (data[i][4] === 3) { + statistics[1]++; + } else if (data[i][4] === 4) { + statistics[3]++; } - $("h3#ads_percentage_today").text(parseFloat(percent).toFixed(1).toLocaleString()+" %"); + } + + $("h3#dns_queries").text(statistics[0].toLocaleString()); + $("h3#ads_blocked_exact").text(statistics[2].toLocaleString()); + $("h3#ads_wildcard_blocked").text(statistics[3].toLocaleString()); + + var percent = 0.0; + if (statistics[2] + statistics[3] > 0) { + percent = (100.0 * (statistics[2] + statistics[3])) / statistics[0]; + } + + $("h3#ads_percentage_today").text( + parseFloat(percent) + .toFixed(1) + .toLocaleString() + " %" + ); }; function refreshTableData() { - timeoutWarning.show(); - var APIstring = "api_db.php?getAllQueries&from="+from+"&until="+until; - // Check if query type filtering is enabled - var queryType = getQueryTypes(); - if(queryType !== "1,2,3,4,5,6") - { - APIstring += "&types="+queryType; - } - statistics = [0,0,0]; - tableApi.ajax.url(APIstring).load(reloadCallback); + timeoutWarning.show(); + var APIstring = "api_db.php?getAllQueries&from=" + from + "&until=" + until; + // Check if query type filtering is enabled + var queryType = getQueryTypes(); + if (queryType !== "1,2,3,4,5,6") { + APIstring += "&types=" + queryType; + } + + statistics = [0, 0, 0]; + tableApi.ajax.url(APIstring).load(reloadCallback); } $(document).ready(function() { - var APIstring; + var APIstring; - if(instantquery) - { - APIstring = "api_db.php?getAllQueries&from="+from+"&until="+until; - } - else - { - APIstring = "api_db.php?getAllQueries=empty"; - } - // Check if query type filtering is enabled - var queryType = getQueryTypes(); - if(queryType !== 63) // 63 (0b00111111) = all possible query types are selected - { - APIstring += "&types="+queryType; - } + if (instantquery) { + APIstring = "api_db.php?getAllQueries&from=" + from + "&until=" + until; + } else { + APIstring = "api_db.php?getAllQueries=empty"; + } - tableApi = $("#all-queries").DataTable( { - "rowCallback": function( row, data ){ - var fieldtext, buttontext, color; - switch (data[4]) - { - case 1: - color = "red"; - fieldtext = "Blocked (gravity)"; - buttontext = ""; - break; - case 2: - color = "green"; - fieldtext = "OK (forwarded)"; - buttontext = ""; - break; - case 3: - color = "green"; - fieldtext = "OK (cached)"; - buttontext = ""; - break; - case 4: - color = "red"; - fieldtext = "Blocked (regex/wildcard)"; - buttontext = ""; - break; - case 5: - color = "red"; - fieldtext = "Blocked (blacklist)"; - buttontext = ""; - break; - case 6: - color = "red"; - fieldtext = "Blocked (external, IP)"; - buttontext = ""; - break; - case 7: - color = "red"; - fieldtext = "Blocked (external, NULL)"; - buttontext = ""; - break; - case 8: - color = "red"; - fieldtext = "Blocked (external, NXRA)"; - buttontext = ""; - break; - default: - color = "black"; - fieldtext = "Unknown"; - buttontext = ""; - } + // Check if query type filtering is enabled + var queryType = getQueryTypes(); + if (queryType !== 63) { + // 63 (0b00111111) = all possible query types are selected + APIstring += "&types=" + queryType; + } - $(row).css("color", color); - $("td:eq(4)", row).html(fieldtext); - $("td:eq(5)", row).html(buttontext); - }, - dom: "<'row'<'col-sm-12'f>>" + - "<'row'<'col-sm-4'l><'col-sm-8'p>>" + - "<'row'<'col-sm-12'<'table-responsive'tr>>>" + - "<'row'<'col-sm-5'i><'col-sm-7'p>>", - "ajax": { - "url": APIstring, - "error": handleAjaxError, - "dataSrc": function(data){ - var dataIndex = 0; - return data.data.map(function(x){ - x[0] = x[0] * 1e6 + (dataIndex++); - return x; - }); - } - }, - "autoWidth" : false, - "processing": true, - "deferRender": true, - "order" : [[0, "desc"]], - "columns": [ - { "width" : "15%", "render": function (data, type) { if(type === "display"){return moment.unix(Math.floor(data/1e6)).format("Y-MM-DD []HH:mm:ss z");}return data; }}, - { "width" : "10%" }, - { "width" : "40%" }, - { "width" : "20%" }, - { "width" : "10%" }, - { "width" : "5%" } - ], - "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]], - "columnDefs": [ { - "targets": -1, - "data": null, - "defaultContent": "" - } ], - "initComplete": reloadCallback - }); - $("#all-queries tbody").on( "click", "button", function () { - var data = tableApi.row( $(this).parents("tr") ).data(); - if (data[4] === 1 || data[4] === 4 || data[5] === 5) - { - add(data[2],"white"); + tableApi = $("#all-queries").DataTable({ + rowCallback: function(row, data) { + var fieldtext, buttontext, color; + switch (data[4]) { + case 1: + color = "red"; + fieldtext = "Blocked (gravity)"; + buttontext = + ''; + break; + case 2: + color = "green"; + fieldtext = "OK (forwarded)"; + buttontext = + ''; + break; + case 3: + color = "green"; + fieldtext = "OK (cached)"; + buttontext = + ''; + break; + case 4: + color = "red"; + fieldtext = "Blocked (regex/wildcard)"; + buttontext = + ''; + break; + case 5: + color = "red"; + fieldtext = "Blocked (blacklist)"; + buttontext = + ''; + break; + case 6: + color = "red"; + fieldtext = "Blocked (external, IP)"; + buttontext = ""; + break; + case 7: + color = "red"; + fieldtext = "Blocked (external, NULL)"; + buttontext = ""; + break; + case 8: + color = "red"; + fieldtext = "Blocked (external, NXRA)"; + buttontext = ""; + break; + default: + color = "black"; + fieldtext = "Unknown"; + buttontext = ""; + } + + $(row).css("color", color); + $("td:eq(4)", row).html(fieldtext); + $("td:eq(5)", row).html(buttontext); + }, + dom: + "<'row'<'col-sm-12'f>>" + + "<'row'<'col-sm-4'l><'col-sm-8'p>>" + + "<'row'<'col-sm-12'<'table-responsive'tr>>>" + + "<'row'<'col-sm-5'i><'col-sm-7'p>>", + ajax: { + url: APIstring, + error: handleAjaxError, + dataSrc: function(data) { + var dataIndex = 0; + return data.data.map(function(x) { + x[0] = x[0] * 1e6 + dataIndex++; + return x; + }); + } + }, + autoWidth: false, + processing: true, + deferRender: true, + order: [[0, "desc"]], + columns: [ + { + width: "15%", + render: function(data, type) { + if (type === "display") { + return moment + .unix(Math.floor(data / 1e6)) + .format("Y-MM-DD []HH:mm:ss z"); + } + + return data; } - else - { - add(data[2],"black"); - } - } ); - - if(instantquery) - { - daterange.val(start__.format(dateformat) + " - " + end__.format(dateformat)); + }, + { width: "10%" }, + { width: "40%" }, + { width: "20%" }, + { width: "10%" }, + { width: "5%" } + ], + lengthMenu: [ + [10, 25, 50, 100, -1], + [10, 25, 50, 100, "All"] + ], + columnDefs: [ + { + targets: -1, + data: null, + defaultContent: "" + } + ], + initComplete: reloadCallback + }); + $("#all-queries tbody").on("click", "button", function() { + var data = tableApi.row($(this).parents("tr")).data(); + if (data[4] === 1 || data[4] === 4 || data[5] === 5) { + add(data[2], "white"); + } else { + add(data[2], "black"); } -} ); + }); + + if (instantquery) { + daterange.val(start__.format(dateformat) + " - " + end__.format(dateformat)); + } +}); $("#querytime").on("apply.daterangepicker", function(ev, picker) { - $(this).val(picker.startDate.format(dateformat) + " to " + picker.endDate.format(dateformat)); - refreshTableData(); + $(this).val(picker.startDate.format(dateformat) + " to " + picker.endDate.format(dateformat)); + refreshTableData(); }); diff --git a/scripts/pi-hole/js/debug.js b/scripts/pi-hole/js/debug.js index d658421b..fb0fd35b 100644 --- a/scripts/pi-hole/js/debug.js +++ b/scripts/pi-hole/js/debug.js @@ -1,74 +1,77 @@ /* Pi-hole: A black hole for Internet advertisements -* (c) 2017 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. */ + * (c) 2017 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 ActiveXObject: false */ // Credit: http://stackoverflow.com/a/10642418/2087442 -function httpGet(ta,theUrl) -{ - var xmlhttp; - if (window.XMLHttpRequest) - { +function httpGet(ta, theUrl) { + var xmlhttp; + if (window.XMLHttpRequest) { // code for IE7+ - xmlhttp = new XMLHttpRequest(); - } - else - { + xmlhttp = new XMLHttpRequest(); + } else { // code for IE6, IE5 - xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); + xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); + } + + xmlhttp.onreadystatechange = function() { + if (xmlhttp.readyState === 4 && xmlhttp.status === 200) { + ta.show(); + ta.empty(); + ta.append(xmlhttp.responseText); } - xmlhttp.onreadystatechange=function() - { - if (xmlhttp.readyState === 4 && xmlhttp.status === 200) - { - ta.show(); - ta.empty(); - ta.append(xmlhttp.responseText); - } - }; - xmlhttp.open("GET", theUrl, false); - xmlhttp.send(); + }; + + xmlhttp.open("GET", theUrl, false); + xmlhttp.send(); } function eventsource() { - var ta = $("#output"); - var upload = $( "#upload" ); - var checked = ""; - var token = encodeURIComponent($("#token").text()); + var ta = $("#output"); + var upload = $("#upload"); + var checked = ""; + var token = encodeURIComponent($("#token").text()); - if(upload.prop("checked")) - { - checked = "upload"; - } + if (upload.prop("checked")) { + checked = "upload"; + } - // IE does not support EventSource - load whole content at once - if (typeof EventSource !== "function") { - httpGet(ta,"scripts/pi-hole/php/debug.php?IE&token="+token+"&"+checked); - return; - } + // IE does not support EventSource - load whole content at once + if (typeof EventSource !== "function") { + httpGet(ta, "scripts/pi-hole/php/debug.php?IE&token=" + token + "&" + checked); + return; + } - var source = new EventSource("scripts/pi-hole/php/debug.php?&token="+token+"&"+checked); + var source = new EventSource("scripts/pi-hole/php/debug.php?&token=" + token + "&" + checked); - // Reset and show field - ta.empty(); - ta.show(); + // Reset and show field + ta.empty(); + ta.show(); - source.addEventListener("message", function(e) { - ta.append(e.data); - }, false); + source.addEventListener( + "message", + function(e) { + ta.append(e.data); + }, + false + ); - // Will be called when script has finished - source.addEventListener("error", function() { - source.close(); - }, false); + // Will be called when script has finished + source.addEventListener( + "error", + function() { + source.close(); + }, + false + ); } -$("#debugBtn").on("click", function(){ - $("#debugBtn").attr("disabled", true); - $("#upload").attr("disabled", true); - eventsource(); +$("#debugBtn").on("click", function() { + $("#debugBtn").attr("disabled", true); + $("#upload").attr("disabled", true); + eventsource(); }); diff --git a/scripts/pi-hole/js/footer.js b/scripts/pi-hole/js/footer.js index 3e7b467e..8dbd32e6 100644 --- a/scripts/pi-hole/js/footer.js +++ b/scripts/pi-hole/js/footer.js @@ -1,135 +1,128 @@ /* Pi-hole: A black hole for Internet advertisements -* (c) 2017 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. */ + * (c) 2017 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. */ //The following functions allow us to display time until pi-hole is enabled after disabling. //Works between all pages function secondsTimeSpanToHMS(s) { - var h = Math.floor(s/3600); //Get whole hours - s -= h*3600; - var m = Math.floor(s/60); //Get remaining minutes - s -= m*60; - return h+":"+(m < 10 ? "0"+m : m)+":"+(s < 10 ? "0"+s : s); //zero padding on minutes and seconds + var h = Math.floor(s / 3600); //Get whole hours + s -= h * 3600; + var m = Math.floor(s / 60); //Get remaining minutes + s -= m * 60; + return h + ":" + (m < 10 ? "0" + m : m) + ":" + (s < 10 ? "0" + s : s); //zero padding on minutes and seconds } -function piholeChanged(action) -{ - var status = $("#status"); - var ena = $("#pihole-enable"); - var dis = $("#pihole-disable"); +function piholeChanged(action) { + var status = $("#status"); + var ena = $("#pihole-enable"); + var dis = $("#pihole-disable"); - switch(action) { - case "enabled": - status.html(" Active"); - ena.hide(); - dis.show(); - dis.removeClass("active"); - break; - - case "disabled": - status.html(" Offline"); - ena.show(); - dis.hide(); - break; - } + switch (action) { + case "enabled": + status.html(" Active"); + ena.hide(); + dis.show(); + dis.removeClass("active"); + break; + case "disabled": + status.html(" Offline"); + ena.show(); + dis.hide(); + break; + } } -function countDown(){ - var ena = $("#enableLabel"); - var enaT = $("#enableTimer"); - var target = new Date(parseInt(enaT.html())); - var seconds = Math.round((target.getTime() - new Date().getTime()) / 1000); +function countDown() { + var ena = $("#enableLabel"); + var enaT = $("#enableTimer"); + var target = new Date(parseInt(enaT.html())); + var seconds = Math.round((target.getTime() - new Date().getTime()) / 1000); - if(seconds > 0){ - setTimeout(countDown,1000); - ena.text("Enable (" + secondsTimeSpanToHMS(seconds) + ")"); - } - else - { - ena.text("Enable"); - piholeChanged("enabled"); - localStorage.removeItem("countDownTarget"); - } + if (seconds > 0) { + setTimeout(countDown, 1000); + ena.text("Enable (" + secondsTimeSpanToHMS(seconds) + ")"); + } else { + ena.text("Enable"); + piholeChanged("enabled"); + localStorage.removeItem("countDownTarget"); + } } -function piholeChange(action, duration) -{ - var token = encodeURIComponent($("#token").text()); - var enaT = $("#enableTimer"); - var btnStatus; +function piholeChange(action, duration) { + var token = encodeURIComponent($("#token").text()); + var enaT = $("#enableTimer"); + var btnStatus; - switch(action) { - case "enable": - btnStatus = $("#flip-status-enable"); - btnStatus.html(" "); - $.getJSON("api.php?enable&token=" + token, function(data) { - if(data.status === "enabled") { - btnStatus.html(""); - piholeChanged("enabled"); - } - }); - break; + switch (action) { + case "enable": + btnStatus = $("#flip-status-enable"); + btnStatus.html(" "); + $.getJSON("api.php?enable&token=" + token, function(data) { + if (data.status === "enabled") { + btnStatus.html(""); + piholeChanged("enabled"); + } + }); + break; - case "disable": - btnStatus = $("#flip-status-disable"); - btnStatus.html(" "); - $.getJSON("api.php?disable=" + duration + "&token=" + token, function(data) { - if(data.status === "disabled") { - btnStatus.html(""); - piholeChanged("disabled"); - if(duration > 0) - { - enaT.html(new Date().getTime() + duration * 1000); - setTimeout(countDown,100); - } - } - }); - break; - } + case "disable": + btnStatus = $("#flip-status-disable"); + btnStatus.html(" "); + $.getJSON("api.php?disable=" + duration + "&token=" + token, function(data) { + if (data.status === "disabled") { + btnStatus.html(""); + piholeChanged("disabled"); + if (duration > 0) { + enaT.html(new Date().getTime() + duration * 1000); + setTimeout(countDown, 100); + } + } + }); + break; + } } -$( document ).ready(function() { - var enaT = $("#enableTimer"); - var target = new Date(parseInt(enaT.html())); - var seconds = Math.round((target.getTime() - new Date().getTime()) / 1000); - if (seconds > 0) - { - setTimeout(countDown,100); - } +$(document).ready(function() { + var enaT = $("#enableTimer"); + var target = new Date(parseInt(enaT.html())); + var seconds = Math.round((target.getTime() - new Date().getTime()) / 1000); + if (seconds > 0) { + setTimeout(countDown, 100); + } }); // Handle Enable/Disable -$("#pihole-enable").on("click", function(e){ - e.preventDefault(); - localStorage.removeItem("countDownTarget"); - piholeChange("enable",""); +$("#pihole-enable").on("click", function(e) { + e.preventDefault(); + localStorage.removeItem("countDownTarget"); + piholeChange("enable", ""); }); -$("#pihole-disable-permanently").on("click", function(e){ - e.preventDefault(); - piholeChange("disable","0"); +$("#pihole-disable-permanently").on("click", function(e) { + e.preventDefault(); + piholeChange("disable", "0"); }); -$("#pihole-disable-10s").on("click", function(e){ - e.preventDefault(); - piholeChange("disable","10"); +$("#pihole-disable-10s").on("click", function(e) { + e.preventDefault(); + piholeChange("disable", "10"); }); -$("#pihole-disable-30s").on("click", function(e){ - e.preventDefault(); - piholeChange("disable","30"); +$("#pihole-disable-30s").on("click", function(e) { + e.preventDefault(); + piholeChange("disable", "30"); }); -$("#pihole-disable-5m").on("click", function(e){ - e.preventDefault(); - piholeChange("disable","300"); +$("#pihole-disable-5m").on("click", function(e) { + e.preventDefault(); + piholeChange("disable", "300"); }); -$("#pihole-disable-custom").on("click", function(e){ - e.preventDefault(); - var custVal = $("#customTimeout").val(); - custVal = $("#btnMins").hasClass("active") ? custVal * 60 : custVal; - piholeChange("disable",custVal); +$("#pihole-disable-custom").on("click", function(e) { + e.preventDefault(); + var custVal = $("#customTimeout").val(); + custVal = $("#btnMins").hasClass("active") ? custVal * 60 : custVal; + piholeChange("disable", custVal); }); // Session timer @@ -137,70 +130,63 @@ var sessionTimerCounter = document.getElementById("sessiontimercounter"); var sessionvalidity = parseInt(sessionTimerCounter.textContent); var start = new Date(); -function updateSessionTimer() -{ - start = new Date(); - start.setSeconds(start.getSeconds() + sessionvalidity); +function updateSessionTimer() { + start = new Date(); + start.setSeconds(start.getSeconds() + sessionvalidity); } -if(sessionvalidity > 0) -{ - // setSeconds will correctly handle wrap-around cases - updateSessionTimer(); +if (sessionvalidity > 0) { + // setSeconds will correctly handle wrap-around cases + updateSessionTimer(); - setInterval(function() { - var current = new Date(); - var totalseconds = (start - current) / 1000; - var minutes = Math.floor(totalseconds / 60); - if(minutes < 10){ minutes = "0" + minutes; } + setInterval(function() { + var current = new Date(); + var totalseconds = (start - current) / 1000; + var minutes = Math.floor(totalseconds / 60); + if (minutes < 10) { + minutes = "0" + minutes; + } - var seconds = Math.floor(totalseconds % 60); - if(seconds < 10){ seconds = "0" + seconds; } + var seconds = Math.floor(totalseconds % 60); + if (seconds < 10) { + seconds = "0" + seconds; + } - if(totalseconds > 0) - { - sessionTimerCounter.textContent = minutes + ":" + seconds; - } - else - { - sessionTimerCounter.textContent = "-- : --"; - } - - }, 1000); -} -else -{ - document.getElementById("sessiontimer").style.display = "none"; + if (totalseconds > 0) { + sessionTimerCounter.textContent = minutes + ":" + seconds; + } else { + sessionTimerCounter.textContent = "-- : --"; + } + }, 1000); +} else { + document.getElementById("sessiontimer").style.display = "none"; } // Handle Strg + Enter button on Login page $(document).keypress(function(e) { - if((e.keyCode === 10 || e.keyCode === 13) && e.ctrlKey && $("#loginpw").is(":focus")) { - $("#loginform").attr("action", "settings.php"); - $("#loginform").submit(); - } + if ((e.keyCode === 10 || e.keyCode === 13) && e.ctrlKey && $("#loginpw").is(":focus")) { + $("#loginform").attr("action", "settings.php"); + $("#loginform").submit(); + } }); -function testCookies() -{ - if (navigator.cookieEnabled) - { - return true; - } +function testCookies() { + if (navigator.cookieEnabled) { + return true; + } - // set and read cookie - document.cookie = "cookietest=1"; - var ret = document.cookie.indexOf("cookietest=") !== -1; + // set and read cookie + document.cookie = "cookietest=1"; + var ret = document.cookie.indexOf("cookietest=") !== -1; - // delete cookie - document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT"; + // delete cookie + document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT"; - return ret; + return ret; } $(function() { - if(!testCookies() && $("#cookieInfo").length) - { - $("#cookieInfo").show(); - } + if (!testCookies() && $("#cookieInfo").length) { + $("#cookieInfo").show(); + } }); diff --git a/scripts/pi-hole/js/gravity.js b/scripts/pi-hole/js/gravity.js index 34aa1477..1512a800 100644 --- a/scripts/pi-hole/js/gravity.js +++ b/scripts/pi-hole/js/gravity.js @@ -1,73 +1,80 @@ /* Pi-hole: A black hole for Internet advertisements -* (c) 2017 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. */ + * (c) 2017 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. */ function eventsource() { - var alInfo = $("#alInfo"); - var alSuccess = $("#alSuccess"); - var ta = $("#output"); + var alInfo = $("#alInfo"); + var alSuccess = $("#alSuccess"); + var ta = $("#output"); - // IE does not support EventSource - exit early - if (typeof EventSource !== "function") { - ta.show(); - ta.html("Updating lists of ad-serving domains is not supported with this browser!"); - return; - } - var source = new EventSource("scripts/pi-hole/php/gravity.sh.php"); - - ta.html(""); + // IE does not support EventSource - exit early + if (typeof EventSource !== "function") { ta.show(); - alInfo.show(); - alSuccess.hide(); + ta.html("Updating lists of ad-serving domains is not supported with this browser!"); + return; + } - source.addEventListener("message", function(e) { - if(e.data.indexOf("Pi-hole blocking is") !== -1) - { - alSuccess.show(); - } + var source = new EventSource("scripts/pi-hole/php/gravity.sh.php"); - // Detect ${OVER} - if(e.data.indexOf("<------") !== -1) - { - ta.text(ta.text().substring(0, ta.text().lastIndexOf("\n")) + "\n"); - var new_string = e.data.replace("<------", ""); - ta.append(new_string); - } - else - { - ta.append(e.data); - } + ta.html(""); + ta.show(); + alInfo.show(); + alSuccess.hide(); - }, false); + source.addEventListener( + "message", + function(e) { + if (e.data.indexOf("Pi-hole blocking is") !== -1) { + alSuccess.show(); + } - // Will be called when script has finished - source.addEventListener("error", function() { - alInfo.delay(1000).fadeOut(2000, function() { alInfo.hide(); }); - source.close(); - $("#gravityBtn").removeAttr("disabled"); - }, false); + // Detect ${OVER} + if (e.data.indexOf("<------") !== -1) { + ta.text(ta.text().substring(0, ta.text().lastIndexOf("\n")) + "\n"); + var new_string = e.data.replace("<------", ""); + ta.append(new_string); + } else { + ta.append(e.data); + } + }, + false + ); + + // Will be called when script has finished + source.addEventListener( + "error", + function() { + alInfo.delay(1000).fadeOut(2000, function() { + alInfo.hide(); + }); + source.close(); + $("#gravityBtn").removeAttr("disabled"); + }, + false + ); } -$("#gravityBtn").on("click", function(){ - $("#gravityBtn").attr("disabled", true); - eventsource(); +$("#gravityBtn").on("click", function() { + $("#gravityBtn").attr("disabled", true); + eventsource(); }); // Handle hiding of alerts -$(function(){ - $("[data-hide]").on("click", function(){ - $(this).closest("." + $(this).attr("data-hide")).hide(); - }); +$(function() { + $("[data-hide]").on("click", function() { + $(this) + .closest("." + $(this).attr("data-hide")) + .hide(); + }); - // Do we want to start updating immediately? - // gravity.php?go - var searchString = window.location.search.substring(1); - if(searchString.indexOf("go") !== -1) - { - $("#gravityBtn").attr("disabled", true); - eventsource(); - } + // Do we want to start updating immediately? + // gravity.php?go + var searchString = window.location.search.substring(1); + if (searchString.indexOf("go") !== -1) { + $("#gravityBtn").attr("disabled", true); + eventsource(); + } }); diff --git a/scripts/pi-hole/js/groups-adlists.js b/scripts/pi-hole/js/groups-adlists.js index 33741953..a475c2d5 100644 --- a/scripts/pi-hole/js/groups-adlists.js +++ b/scripts/pi-hole/js/groups-adlists.js @@ -35,6 +35,7 @@ function showAlert(type, icon, title, message) { } else { $.notify(opts); } + break; case "warning": opts = { @@ -48,6 +49,7 @@ function showAlert(type, icon, title, message) { } else { $.notify(opts); } + break; case "error": opts = { @@ -61,9 +63,9 @@ function showAlert(type, icon, title, message) { } else { $.notify(opts); } + break; default: - return; } } @@ -90,10 +92,7 @@ $(document).ready(function() { $("#select").on("change", function() { $("#ip-custom").val(""); - $("#ip-custom").prop( - "disabled", - $("#select option:selected").val() !== "custom" - ); + $("#ip-custom").prop("disabled", $("#select option:selected").val() !== "custom"); }); }); @@ -130,9 +129,7 @@ function initTable() { var disabled = data.enabled === 0; $("td:eq(1)", row).html( - '" + '" ); var status = $("#status", row); status.bootstrapToggle({ @@ -154,9 +151,7 @@ function initTable() { comment.on("change", editAdlist); $("td:eq(3)", row).empty(); - $("td:eq(3)", row).append( - '' - ); + $("td:eq(3)", row).append(''); var sel = $("#multiselect", row); // Add all known groups for (var i = 0; i < groups.length; i++) { @@ -164,12 +159,14 @@ function initTable() { if (!groups[i].enabled) { extra = " (disabled)"; } + sel.append( $("