Add Adlists group management

Signed-off-by: DL6ER <dl6er@dl6er.de>
This commit is contained in:
DL6ER
2019-12-13 15:41:14 +00:00
parent 912e2ddbd9
commit 70589fa844
8 changed files with 522 additions and 7 deletions

95
groups-adlists.php Normal file
View File

@@ -0,0 +1,95 @@
<?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.
*
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license. */
require "scripts/pi-hole/php/header.php";
?>
<!-- Title -->
<div class="page-header">
<h1>Adllist group management</h1>
</div>
<!-- Alerts -->
<div id="alInfo" class="alert alert-info alert-dismissible fade in" role="alert" hidden="true">
<button type="button" class="close" data-hide="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
Updating adlist...
</div>
<div id="alSuccess" class="alert alert-success alert-dismissible fade in" role="alert" hidden="true">
<button type="button" class="close" data-hide="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
Success! The list will refresh.
</div>
<div id="alFailure" class="alert alert-danger alert-dismissible fade in" role="alert" hidden="true">
<button type="button" class="close" data-hide="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
Failure! Something went wrong, see output below:<br/><br/><pre><span id="err"></span></pre>
</div>
<div id="alWarning" class="alert alert-warning alert-dismissible fade in" role="alert" hidden="true">
<button type="button" class="close" data-hide="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
Warning, see output below:<br/><br/><pre><span id="warn"></span></pre>
</div>
<!-- Domain Input -->
<div class="row">
<div class="col-md-12">
<div class="box" id="add-group">
<!-- /.box-header -->
<div class="box-header with-border">
<h3 class="box-title">
Add a new adlist
</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="row">
<div class="col-md-6">
<label for="ex1">Address:</label>
<input id="address" type="text" class="form-control" placeholder="http://..., https://..., file://...">
</div>
<div class="col-md-6">
<label for="ex2">Comment:</label>
<input id="comment" type="text" class="form-control" placeholder="Adlist description (optional)">
</div>
</div>
</div>
<div class="box-footer clearfix">
<button id="btnAdd" class="btn btn-primary pull-right">Add</button>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="box" id="adlists-list">
<div class="box-header with-border">
<h3 class="box-title">
List of configured adlists
</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<table id="adlistsTable" class="display table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Address</th>
<th>Status</th>
<th>Comment</th>
<th>Group assignment</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
</div>
<script src="scripts/pi-hole/js/groups-adlists.js"></script>
<?php
require "scripts/pi-hole/php/footer.php";
?>

View File

@@ -16,7 +16,7 @@
<!-- Alerts -->
<div id="alInfo" class="alert alert-info alert-dismissible fade in" role="alert" hidden="true">
<button type="button" class="close" data-hide="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
Updating client groups...
Updating client...
</div>
<div id="alSuccess" class="alert alert-success alert-dismissible fade in" role="alert" hidden="true">
<button type="button" class="close" data-hide="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>

View File

@@ -16,7 +16,7 @@
<!-- Alerts -->
<div id="alInfo" class="alert alert-info alert-dismissible fade in" role="alert" hidden="true">
<button type="button" class="close" data-hide="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
Updating domain groups...
Updating domain...
</div>
<div id="alSuccess" class="alert alert-success alert-dismissible fade in" role="alert" hidden="true">
<button type="button" class="close" data-hide="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
@@ -45,7 +45,7 @@
<div class="box-body">
<div class="row">
<div class="col-md-6">
<label for="ex1">Domain / Comment:</label>
<label for="ex1">Domain:</label>
<input id="domain" type="text" class="form-control" placeholder="Domain to be added">
</div>
<div class="col-md-2">

View File

@@ -0,0 +1,204 @@
var table, groups;
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;
}
if (messageElement != null)
messageElement.html(message);
alertElement.fadeIn(200);
alertElement.delay(8000).fadeOut(2000);
}
function get_groups()
{
$.get("scripts/pi-hole/php/groups.php", { 'action': 'get_groups' },
function(data) {
groups = data.data;
}, "json");
}
$.fn.redraw = function(){
return $(this).each(function(){
var redraw = this.offsetHeight;
});
};
$(document).ready(function() {
$('#btnAdd').on('click', addAdlist);
get_groups();
$('#select').on('change', function() {
$("#ip-custom").val("");
$("#ip-custom").prop( "disabled" , $( "#select option:selected" ).val() !== "custom");
});
table = $("#adlistsTable").DataTable( {
"ajax": "scripts/pi-hole/php/groups.php?action=get_adlists",
order: [[ 1, 'asc' ]],
columns: [
{ data: null },
{ data: null, "orderable": false },
{ data: null, "orderable": false },
{ data: null, "orderable": false },
{ data: null, width: "60px", "orderable": false }
],
"drawCallback": function( settings ) {
$('.editAdlist').on('click', editAdlist);
$('.deleteAdlist').on('click', deleteAdlist);
},
"rowCallback": function( row, data ) {
$('td:eq(0)', row).html( '<code>'+data["address"]+'</code>' );
const disabled = data["enabled"] === 0;
$('td:eq(1)', row).html( '<select id="status">'+
'<option value="0"'+(disabled?' selected':'')+'>Disabled</option>'+
'<option value="1"'+(disabled?'':' selected')+'>Enabled</option>'+
'</select>' );
$('td:eq(2)', row).html( '<input id="comment"><input id="id" type="hidden" value="'+data["id"]+'">' );
$('#comment', row).val(data["comment"]);
$('td:eq(3)', row).empty();
$('td:eq(3)', row).append( '<select id="multiselect" multiple="multiple"></select>' );
var sel = $('#multiselect', row);
// Add all known groups
for (var i = 0; i < groups.length; i++) {
var extra = 'ID ' + groups[i].id;
if(!groups[i].enabled)
{
extra += ', disabled';
}
sel.append($('<option />').val(groups[i].id).text(groups[i].name + ' (' + extra + ')'));
sel.redraw();
}
// Select assigned groups
sel.val(data.groups);
// Initialize multiselect
sel.multiselect({ includeSelectAllOption: true });
let button = "<button class=\"btn btn-success btn-xs editAdlist\" type=\"button\" data-id='"+data["id"]+"'>" +
"<span class=\"glyphicon glyphicon-pencil\"></span>" +
"</button>" +
" &nbsp;" +
"<button class=\"btn btn-danger btn-xs deleteAdlist\" type=\"button\" data-id='"+data["id"]+"'>" +
"<span class=\"glyphicon glyphicon-trash\"></span>" +
"</button>";
$('td:eq(4)', row).html( button );
},
"lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"stateSave": true,
stateSaveCallback: function(settings, data) {
// Store current state in client's local storage area
localStorage.setItem("groups-adlists-table", JSON.stringify(data));
},
stateLoadCallback: function(settings) {
// Receive previous state from client's local storage area
var data = localStorage.getItem("groups-adlists-table");
// Return if not available
if(data === null){ return null; }
data = JSON.parse(data);
// 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 addAdlist()
{
var address = $("#address").val();
var comment = $("#comment").val();
showAlert('info');
$.ajax({
url: "scripts/pi-hole/php/groups.php",
method: "post",
dataType: 'json',
data: {"action": "add_adlist", "address": address, "comment": comment},
success: function(response) {
if (response.success) {
showAlert('success');
$("#address").empty();
$("#comment").empty();
table.ajax.reload();
}
else
showAlert('error', response.message);
},
error: function(jqXHR, exception) {
showAlert('error', "Error while adding new adlist");
console.log(exception);
}
});
}
function editAdlist()
{
var tr = $(this).closest("tr");
var id = tr.find("#id").val();
var status = tr.find("#status").val();
var comment = tr.find("#comment").val();
var groups = tr.find("#multiselect").val();
showAlert('info');
$.ajax({
url: "scripts/pi-hole/php/groups.php",
method: "post",
dataType: 'json',
data: {"action": "edit_adlist", "id": id, "comment": comment, "status": status, "groups": groups},
success: function(response) {
if (response.success) {
showAlert('success');
table.ajax.reload();
}
else
showAlert('error', response.message);
},
error: function(jqXHR, exception) {
showAlert('error', "Error while editing adlist with ID "+id);
console.log(exception);
}
});
}
function deleteAdlist()
{
var id = $(this).attr("data-id");
showAlert('info');
$.ajax({
url: "scripts/pi-hole/php/groups.php",
method: "post",
dataType: 'json',
data: {"action": "delete_adlist", "id": id},
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 adlist with ID "+id);
console.log(exception);
}
});
}

View File

@@ -149,7 +149,7 @@ function addClient()
showAlert('error', response.message);
},
error: function(jqXHR, exception) {
showAlert('error', "Error while adding new group");
showAlert('error', "Error while adding new client");
console.log(exception);
}
});

View File

@@ -152,7 +152,7 @@ function addDomain()
showAlert('error', response.message);
},
error: function(jqXHR, exception) {
showAlert('error', "Error while adding new group");
showAlert('error', "Error while adding new domain");
console.log(exception);
}
});

View File

@@ -617,6 +617,215 @@ elseif($_REQUEST['action'] == "delete_domain")
return JSON_error($ex->getMessage());
}
}
elseif($_REQUEST['action'] == "get_adlists")
{
// List all available groups
try
{
$query = $db->query("SELECT * FROM adlist;");
if(!$query)
{
throw new Exception("Error while querying gravity's adlist table: ".$db->lastErrorMsg());
}
$data = array();
while($res = $query->fetchArray(SQLITE3_ASSOC))
{
$group_query = $db->query("SELECT group_id FROM adlist_by_group WHERE adlist_id = ".$res["id"].";");
if(!$group_query)
{
throw new Exception("Error while querying gravity's adlist_by_group table: ".$db->lastErrorMsg());
}
$groups = array();
while($gres = $group_query->fetchArray(SQLITE3_ASSOC))
{
array_push($groups,$gres["group_id"]);
}
$res["groups"] = $groups;
array_push($data,$res);
}
echo json_encode(array("data" => $data));
}
catch (\Exception $ex)
{
return JSON_error($ex->getMessage());
}
}
elseif($_REQUEST['action'] == "add_adlist")
{
// Add new adlist
try
{
$stmt = $db->prepare('INSERT INTO adlist (address,comment) VALUES (:address,:comment)');
if(!$stmt)
{
throw new Exception("While preparing statement: ".$db->lastErrorMsg());
}
if(!$stmt->bindValue(':address', $_POST["address"], SQLITE3_TEXT))
{
throw new Exception("While binding address: ".$db->lastErrorMsg());
}
if(!$stmt->bindValue(':comment', $_POST["comment"], SQLITE3_TEXT))
{
throw new Exception("While binding comment: ".$db->lastErrorMsg());
}
if(!$stmt->execute())
{
throw new Exception("While executing: ".$db->lastErrorMsg());
}
$reload = true;
return JSON_success();
}
catch (\Exception $ex)
{
return JSON_error($ex->getMessage());
}
}
elseif($_REQUEST['action'] == "edit_adlist")
{
// Edit adlist identified by ID
try
{
$stmt = $db->prepare('UPDATE adlist SET enabled=:enabled, comment=:comment WHERE id = :id');
if(!$stmt)
{
throw new Exception("While preparing statement: ".$db->lastErrorMsg());
}
$status = intval($_POST["status"]);
if($status !== 0)
{
$status = 1;
}
if(!$stmt->bindValue(':enabled', $status, SQLITE3_INTEGER))
{
throw new Exception("While binding enabled: ".$db->lastErrorMsg());
}
$comment = $_POST["comment"];
if(strlen($comment) == 0)
{
// Store NULL in database for empty comments
$comment = null;
}
if(!$stmt->bindValue(':comment', $comment, SQLITE3_TEXT))
{
throw new Exception("While binding comment: ".$db->lastErrorMsg());
}
if(!$stmt->bindValue(':id', intval($_POST["id"]), SQLITE3_INTEGER))
{
throw new Exception("While binding id: ".$db->lastErrorMsg());
}
if(!$stmt->execute())
{
throw new Exception("While executing: ".$db->lastErrorMsg());
}
$stmt = $db->prepare('DELETE FROM adlist_by_group WHERE adlist_id = :id');
if(!$stmt)
{
throw new Exception("While preparing DELETE statement: ".$db->lastErrorMsg());
}
if(!$stmt->bindValue(':id', intval($_POST["id"]), SQLITE3_INTEGER))
{
throw new Exception("While binding id: ".$db->lastErrorMsg());
}
if(!$stmt->execute())
{
throw new Exception("While executing DELETE statement: ".$db->lastErrorMsg());
}
$db->query("BEGIN TRANSACTION;");
foreach ($_POST["groups"] as $gid)
{
$stmt = $db->prepare('INSERT INTO adlist_by_group (adlist_id,group_id) VALUES(:id,:gid);');
if(!$stmt)
{
throw new Exception("While preparing INSERT INTO statement: ".$db->lastErrorMsg());
}
if(!$stmt->bindValue(':id', intval($_POST["id"]), SQLITE3_INTEGER))
{
throw new Exception("While binding id: ".$db->lastErrorMsg());
}
if(!$stmt->bindValue(':gid', intval($gid), SQLITE3_INTEGER))
{
throw new Exception("While binding gid: ".$db->lastErrorMsg());
}
if(!$stmt->execute())
{
throw new Exception("While executing INSERT INTO statement: ".$db->lastErrorMsg());
}
}
$db->query("COMMIT;");
$reload = true;
return JSON_success();
}
catch (\Exception $ex)
{
return JSON_error($ex->getMessage());
}
}
elseif($_REQUEST['action'] == "delete_adlist")
{
// Delete adlist identified by ID
try
{
$stmt = $db->prepare('DELETE FROM adlist_by_group WHERE adlist_id=:id');
if(!$stmt)
{
throw new Exception("While preparing adlist_by_group statement: ".$db->lastErrorMsg());
}
if(!$stmt->bindValue(':id', intval($_POST["id"]), SQLITE3_INTEGER))
{
throw new Exception("While binding id to adlist_by_group statement: ".$db->lastErrorMsg());
}
if(!$stmt->execute())
{
throw new Exception("While executing adlist_by_group statement: ".$db->lastErrorMsg());
}
$stmt = $db->prepare('DELETE FROM adlist WHERE id=:id');
if(!$stmt)
{
throw new Exception("While preparing adlist statement: ".$db->lastErrorMsg());
}
if(!$stmt->bindValue(':id', intval($_POST["id"]), SQLITE3_INTEGER))
{
throw new Exception("While binding id to adlist statement: ".$db->lastErrorMsg());
}
if(!$stmt->execute())
{
throw new Exception("While executing adlist statement: ".$db->lastErrorMsg());
}
$reload = true;
return JSON_success();
}
catch (\Exception $ex)
{
return JSON_error($ex->getMessage());
}
}
else
{
log_and_die("Requested action not supported!");

View File

@@ -219,7 +219,7 @@
<script src="style/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="scripts/vendor/app.min.js"></script>
<?php if(in_array($scriptname, array("groups-clients.php", "groups-domains.php"))){ ?>
<?php if(in_array($scriptname, array("groups-clients.php", "groups-domains.php", "groups-adlists.php"))){ ?>
<script src="style/vendor/bootstrap/js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="style/vendor/bootstrap/css/bootstrap-multiselect.css">
<?php } ?>
@@ -492,7 +492,7 @@ if($auth) {
</a>
</li>
<!-- Group Management -->
<li class="treeview <?php if(in_array($scriptname, array("groups.php", "groups-clients.php", "groups-domains.php"))){ ?>active<?php } ?>">
<li class="treeview <?php if(in_array($scriptname, array("groups.php", "groups-clients.php", "groups-domains.php", "groups-adlists.php"))){ ?>active<?php } ?>">
<a href="#">
<span class="pull-right-container">
<i class="fa fa-angle-down pull-right" style="padding-right: 5px;"></i>
@@ -520,6 +520,13 @@ if($auth) {
</a>
</li>
</ul>
<ul class="treeview-menu">
<li<?php if($scriptname === "groups-adlists.php"){ ?> class="active"<?php } ?>>
<a href="groups-adlists.php">
<i class="fa fa-address-book"></i> <span>Adlists</span>
</a>
</li>
</ul>
</li>
<!-- Toggle -->