diff --git a/.github/workflows/php-cs-fixer.yml b/.github/workflows/php-cs-fixer.yml new file mode 100644 index 00000000..55eedc48 --- /dev/null +++ b/.github/workflows/php-cs-fixer.yml @@ -0,0 +1,13 @@ +# .github/workflows/php-cs-fixer.yml +on: [push, pull_request] +name: Lint +jobs: + php-cs-fixer: + name: PHP-CS-Fixer + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3.0.2 + - name: PHP-CS-Fixer + uses: docker://oskarstark/php-cs-fixer-ga + with: + args: --diff --dry-run diff --git a/.gitignore b/.gitignore index 259446a0..c8bdf0d6 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ TODO *.zip test.html *.log +.php-cs-fixer.cache # Intellij IDEA Project Files *.iml diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 00000000..c1e2ed6b --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,30 @@ +ignoreDotFiles(false) + ->ignoreVCSIgnored(true) + ->exclude('scripts/vendor') + ->in(__DIR__) +; + +$config = new PhpCsFixer\Config(); +$config + ->setRules(array( + '@Symfony' => true, + 'array_syntax' => array('syntax' => 'long'), + )) + ->setLineEnding(PHP_EOL) + ->setFinder($finder) +; + +return $config; diff --git a/api.php b/api.php index ba638f5d..7176e243 100644 --- a/api.php +++ b/api.php @@ -8,200 +8,190 @@ */ $api = true; -require_once("scripts/pi-hole/php/FTL.php"); -require_once("scripts/pi-hole/php/password.php"); -require_once("scripts/pi-hole/php/database.php"); -require_once("scripts/pi-hole/php/auth.php"); +require_once 'scripts/pi-hole/php/FTL.php'; +require_once 'scripts/pi-hole/php/password.php'; +require_once 'scripts/pi-hole/php/database.php'; +require_once 'scripts/pi-hole/php/auth.php'; check_cors(); $data = array(); // Common API functions if (isset($_GET['enable']) && $auth) { - if(isset($_GET["auth"])) - { - if($_GET["auth"] !== $pwhash) - die("Not authorized!"); - } - else - { + if (isset($_GET['auth'])) { + if ($_GET['auth'] !== $pwhash) { + exit('Not authorized!'); + } + } else { // Skip token validation if explicit auth string is given check_csrf($_GET['token']); } pihole_execute('enable'); - $data = array_merge($data, array("status" => "enabled")); - if (file_exists("../custom_disable_timer")) - { - unlink("../custom_disable_timer"); + $data = array_merge($data, array('status' => 'enabled')); + if (file_exists('../custom_disable_timer')) { + unlink('../custom_disable_timer'); } -} -elseif (isset($_GET['disable']) && $auth) -{ - if(isset($_GET["auth"])) - { - if($_GET["auth"] !== $pwhash) - die("Not authorized!"); - } - else - { +} elseif (isset($_GET['disable']) && $auth) { + if (isset($_GET['auth'])) { + if ($_GET['auth'] !== $pwhash) { + exit('Not authorized!'); + } + } else { // Skip token validation if explicit auth string is given check_csrf($_GET['token']); } $disable = intval($_GET['disable']); // intval returns the integer value on success, or 0 on failure - if($disable > 0) - { + if ($disable > 0) { $timestamp = time(); - pihole_execute("disable ".$disable."s"); - file_put_contents("../custom_disable_timer",($timestamp+$disable)*1000); - } - else - { + pihole_execute('disable '.$disable.'s'); + file_put_contents('../custom_disable_timer', ($timestamp + $disable) * 1000); + } else { pihole_execute('disable'); - if (file_exists("../custom_disable_timer")) - { - unlink("../custom_disable_timer"); + if (file_exists('../custom_disable_timer')) { + unlink('../custom_disable_timer'); } } - $data = array_merge($data, array("status" => "disabled")); -} -elseif (isset($_GET['versions'])) -{ + $data = array_merge($data, array('status' => 'disabled')); +} elseif (isset($_GET['versions'])) { // Determine if updates are available for Pi-hole // using the same script that we use for the footer // on the dashboard (update notifications are // suppressed if on development branches) - require "scripts/pi-hole/php/update_checker.php"; - $updates = array("core_update" => $core_update, - "web_update" => $web_update, - "FTL_update" => $FTL_update); - $current = array("core_current" => $core_current, - "web_current" => $web_current, - "FTL_current" => $FTL_current); - $latest = array("core_latest" => $core_latest, - "web_latest" => $web_latest, - "FTL_latest" => $FTL_latest); - $branches = array("core_branch" => $core_branch, - "web_branch" => $web_branch, - "FTL_branch" => $FTL_branch); + require 'scripts/pi-hole/php/update_checker.php'; + $updates = array('core_update' => $core_update, + 'web_update' => $web_update, + 'FTL_update' => $FTL_update, ); + $current = array('core_current' => $core_current, + 'web_current' => $web_current, + 'FTL_current' => $FTL_current, ); + $latest = array('core_latest' => $core_latest, + 'web_latest' => $web_latest, + 'FTL_latest' => $FTL_latest, ); + $branches = array('core_branch' => $core_branch, + 'web_branch' => $web_branch, + 'FTL_branch' => $FTL_branch, ); $data = array_merge($data, $updates); $data = array_merge($data, $current); $data = array_merge($data, $latest); $data = array_merge($data, $branches); -} -elseif (isset($_GET['list'])) -{ - if (!$auth) - die("Not authorized!"); +} elseif (isset($_GET['list'])) { + if (!$auth) { + exit('Not authorized!'); + } - if(!isset($_GET["list"])) - die("List has not been specified."); + if (!isset($_GET['list'])) { + exit('List has not been specified.'); + } - switch ($_GET["list"]) { + switch ($_GET['list']) { case 'black': $_POST['type'] = ListType::blacklist; + break; + case 'regex_black': $_POST['type'] = ListType::regex_blacklist; + break; + case 'white': $_POST['type'] = ListType::whitelist; + break; + case 'regex_white': $_POST['type'] = ListType::regex_whitelist; + break; default: - die("Invalid list [supported: black, regex_black, white, regex_white]"); + exit('Invalid list [supported: black, regex_black, white, regex_white]'); } - if (isset($_GET['add'])) - { + if (isset($_GET['add'])) { // Set POST parameters and invoke script to add domain to list $_POST['domain'] = $_GET['add']; $_POST['action'] = 'add_domain'; - require("scripts/pi-hole/php/groups.php"); - } - elseif (isset($_GET['sub'])) - { + require 'scripts/pi-hole/php/groups.php'; + } elseif (isset($_GET['sub'])) { // Set POST parameters and invoke script to remove domain from list $_POST['domain'] = $_GET['sub']; $_POST['action'] = 'delete_domain_string'; - require("scripts/pi-hole/php/groups.php"); - } - else - { + require 'scripts/pi-hole/php/groups.php'; + } else { // Set POST parameters and invoke script to get all domains $_POST['action'] = 'get_domains'; - require("scripts/pi-hole/php/groups.php"); + require 'scripts/pi-hole/php/groups.php'; } return; -} -elseif(isset($_GET['customdns']) && $auth) -{ - if (isset($_GET["auth"])) { - if ($_GET["auth"] !== $pwhash) { - die("Not authorized!"); +} elseif (isset($_GET['customdns']) && $auth) { + if (isset($_GET['auth'])) { + if ($_GET['auth'] !== $pwhash) { + exit('Not authorized!'); } } else { // Skip token validation if explicit auth string is given check_csrf($_GET['token']); } - switch ($_GET["action"]) { + switch ($_GET['action']) { case 'get': $data = echoCustomDNSEntries(); + break; case 'add': $data = addCustomDNSEntry(); + break; case 'delete': $data = deleteCustomDNSEntry(); + break; default: - die("Wrong action"); + exit('Wrong action'); } -} -elseif(isset($_GET['customcname']) && $auth) -{ - if (isset($_GET["auth"])) { - if ($_GET["auth"] !== $pwhash) { - die("Not authorized!"); +} elseif (isset($_GET['customcname']) && $auth) { + if (isset($_GET['auth'])) { + if ($_GET['auth'] !== $pwhash) { + exit('Not authorized!'); } } else { // Skip token validation if explicit auth string is given check_csrf($_GET['token']); } - switch ($_GET["action"]) { + switch ($_GET['action']) { case 'get': $data = echoCustomCNAMEEntries(); + break; case 'add': $data = addCustomCNAMEEntry(); + break; case 'delete': $data = deleteCustomCNAMEEntry(); + break; default: - die("Wrong action"); + exit('Wrong action'); } } // Other API functions -require("api_FTL.php"); +require 'api_FTL.php'; header('Content-type: application/json'); -if(isset($_GET["jsonForceObject"])) { +if (isset($_GET['jsonForceObject'])) { echo json_encode($data, JSON_FORCE_OBJECT); } else { echo json_encode($data); } -?> diff --git a/api_FTL.php b/api_FTL.php index dafa4eef..f1b7c237 100644 --- a/api_FTL.php +++ b/api_FTL.php @@ -8,47 +8,47 @@ */ if (!isset($api)) { - die("Direct call to api_FTL.php is not allowed!"); + exit('Direct call to api_FTL.php is not allowed!'); } if (isset($_GET['type'])) { - $data["type"] = "FTL"; + $data['type'] = 'FTL'; } if (isset($_GET['version'])) { - $data["version"] = 3; + $data['version'] = 3; } if (isset($_GET['status'])) { - $return = callFTLAPI("stats"); - if (array_key_exists("FTLnotrunning", $return)) { - $data = array("FTLnotrunning" => true); + $return = callFTLAPI('stats'); + if (array_key_exists('FTLnotrunning', $return)) { + $data = array('FTLnotrunning' => true); } else { - if (in_array("status enabled", $return)) { - $data = array_merge($data, array("status" => "enabled")); + if (in_array('status enabled', $return)) { + $data = array_merge($data, array('status' => 'enabled')); } else { - $data = array_merge($data, array("status" => "disabled")); + $data = array_merge($data, array('status' => 'disabled')); } } } if (isset($_GET['summary']) || isset($_GET['summaryRaw']) || !count($_GET)) { - require_once("scripts/pi-hole/php/gravity.php"); + require_once 'scripts/pi-hole/php/gravity.php'; - $return = callFTLAPI("stats"); - if (array_key_exists("FTLnotrunning", $return)) { - $data = array("FTLnotrunning" => true); + $return = callFTLAPI('stats'); + if (array_key_exists('FTLnotrunning', $return)) { + $data = array('FTLnotrunning' => true); } else { - $stats = []; + $stats = array(); foreach ($return as $line) { - $tmp = explode(" ",$line); + $tmp = explode(' ', $line); - if ($tmp[0] === "domains_being_blocked" && !is_numeric($tmp[1]) || $tmp[0] === "status") { + if ('domains_being_blocked' === $tmp[0] && !is_numeric($tmp[1]) || 'status' === $tmp[0]) { // Expect string response $stats[$tmp[0]] = $tmp[1]; } elseif (isset($_GET['summary'])) { // "summary" expects a formmated string response - if ($tmp[0] !== "ads_percentage_today") { + if ('ads_percentage_today' !== $tmp[0]) { $stats[$tmp[0]] = number_format($tmp[1]); } else { $stats[$tmp[0]] = number_format($tmp[1], 1, '.', ''); @@ -57,43 +57,42 @@ if (isset($_GET['summary']) || isset($_GET['summaryRaw']) || !count($_GET)) { // Expect float response $stats[$tmp[0]] = floatval($tmp[1]); } - } $stats['gravity_last_updated'] = gravity_last_update(true); - $data = array_merge($data,$stats); + $data = array_merge($data, $stats); } } -if (isset($_GET["getMaxlogage"]) && $auth) { - $return = callFTLAPI("maxlogage"); - if (array_key_exists("FTLnotrunning", $return)) { - $data = array("FTLnotrunning" => true); +if (isset($_GET['getMaxlogage']) && $auth) { + $return = callFTLAPI('maxlogage'); + if (array_key_exists('FTLnotrunning', $return)) { + $data = array('FTLnotrunning' => true); } else { // Convert seconds to hours and rounds to one decimal place. $ret = round(intval($return[0]) / 3600, 1); // Return 24h if value is 0, empty, null or non numeric. $ret = $ret ?: 24; - $data = array_merge($data, array("maxlogage" => $ret)); + $data = array_merge($data, array('maxlogage' => $ret)); } } if (isset($_GET['overTimeData10mins'])) { - $return = callFTLAPI("overTime"); - if (array_key_exists("FTLnotrunning", $return)) { - $data = array("FTLnotrunning" => true); + $return = callFTLAPI('overTime'); + if (array_key_exists('FTLnotrunning', $return)) { + $data = array('FTLnotrunning' => true); } else { $domains_over_time = array(); $ads_over_time = array(); foreach ($return as $line) { - $tmp = explode(" ",$line); + $tmp = explode(' ', $line); $domains_over_time[intval($tmp[0])] = intval($tmp[1]); $ads_over_time[intval($tmp[0])] = intval($tmp[2]); } $result = array( 'domains_over_time' => $domains_over_time, - 'ads_over_time' => $ads_over_time + 'ads_over_time' => $ads_over_time, ); $data = array_merge($data, $result); @@ -101,45 +100,45 @@ if (isset($_GET['overTimeData10mins'])) { } if (isset($_GET['topItems']) && $auth) { - if ($_GET['topItems'] === "audit") { - $return = callFTLAPI("top-domains for audit"); + if ('audit' === $_GET['topItems']) { + $return = callFTLAPI('top-domains for audit'); } elseif (is_numeric($_GET['topItems'])) { - $return = callFTLAPI("top-domains (".$_GET['topItems'].")"); + $return = callFTLAPI('top-domains ('.$_GET['topItems'].')'); } else { - $return = callFTLAPI("top-domains"); + $return = callFTLAPI('top-domains'); } - if (array_key_exists("FTLnotrunning", $return)) { - $data = array("FTLnotrunning" => true); + if (array_key_exists('FTLnotrunning', $return)) { + $data = array('FTLnotrunning' => true); } else { $top_queries = array(); foreach ($return as $line) { - $tmp = explode(" ",$line); - if (count($tmp) == 2) { - $tmp[2]=""; + $tmp = explode(' ', $line); + if (2 == count($tmp)) { + $tmp[2] = ''; } $domain = utf8_encode($tmp[2]); $top_queries[$domain] = intval($tmp[1]); } } - if ($_GET['topItems'] === "audit") { - $return = callFTLAPI("top-ads for audit"); + if ('audit' === $_GET['topItems']) { + $return = callFTLAPI('top-ads for audit'); } elseif (is_numeric($_GET['topItems'])) { - $return = callFTLAPI("top-ads (".$_GET['topItems'].")"); + $return = callFTLAPI('top-ads ('.$_GET['topItems'].')'); } else { - $return = callFTLAPI("top-ads"); + $return = callFTLAPI('top-ads'); } - if (array_key_exists("FTLnotrunning", $return)) { - $data = array("FTLnotrunning" => true); + if (array_key_exists('FTLnotrunning', $return)) { + $data = array('FTLnotrunning' => true); } else { $top_ads = array(); foreach ($return as $line) { - $tmp = explode(" ",$line); + $tmp = explode(' ', $line); $domain = utf8_encode($tmp[2]); if (count($tmp) > 3) { - $top_ads[$domain." (".$tmp[3].")"] = intval($tmp[1]); + $top_ads[$domain.' ('.$tmp[3].')'] = intval($tmp[1]); } else { $top_ads[$domain] = intval($tmp[1]); } @@ -147,7 +146,7 @@ if (isset($_GET['topItems']) && $auth) { $result = array( 'top_queries' => $top_queries, - 'top_ads' => $top_ads + 'top_ads' => $top_ads, ); $data = array_merge($data, $result); @@ -155,7 +154,6 @@ if (isset($_GET['topItems']) && $auth) { } if ((isset($_GET['topClients']) || isset($_GET['getQuerySources'])) && $auth) { - if (isset($_GET['topClients'])) { $number = $_GET['topClients']; } elseif (isset($_GET['getQuerySources'])) { @@ -163,20 +161,20 @@ if ((isset($_GET['topClients']) || isset($_GET['getQuerySources'])) && $auth) { } if (is_numeric($number)) { - $return = callFTLAPI("top-clients (".$number.")"); + $return = callFTLAPI('top-clients ('.$number.')'); } else { - $return = callFTLAPI("top-clients"); + $return = callFTLAPI('top-clients'); } - if (array_key_exists("FTLnotrunning", $return)) { - $data = array("FTLnotrunning" => true); + if (array_key_exists('FTLnotrunning', $return)) { + $data = array('FTLnotrunning' => true); } else { $top_clients = array(); foreach ($return as $line) { - $tmp = explode(" ",$line); + $tmp = explode(' ', $line); $clientip = utf8_encode($tmp[2]); if (count($tmp) > 3 && strlen($tmp[3]) > 0) { $clientname = utf8_encode($tmp[3]); - $top_clients[$clientname."|".$clientip] = intval($tmp[1]); + $top_clients[$clientname.'|'.$clientip] = intval($tmp[1]); } else { $top_clients[$clientip] = intval($tmp[1]); } @@ -188,26 +186,25 @@ if ((isset($_GET['topClients']) || isset($_GET['getQuerySources'])) && $auth) { } if (isset($_GET['topClientsBlocked']) && $auth) { - if (isset($_GET['topClientsBlocked'])) { $number = $_GET['topClientsBlocked']; } if (is_numeric($number)) { - $return = callFTLAPI("top-clients blocked (".$number.")"); + $return = callFTLAPI('top-clients blocked ('.$number.')'); } else { - $return = callFTLAPI("top-clients blocked"); + $return = callFTLAPI('top-clients blocked'); } - if (array_key_exists("FTLnotrunning", $return)) { - $data = array("FTLnotrunning" => true); + if (array_key_exists('FTLnotrunning', $return)) { + $data = array('FTLnotrunning' => true); } else { $top_clients = array(); foreach ($return as $line) { - $tmp = explode(" ",$line); + $tmp = explode(' ', $line); $clientip = utf8_encode($tmp[2]); if (count($tmp) > 3 && strlen($tmp[3]) > 0) { $clientname = utf8_encode($tmp[3]); - $top_clients[$clientname."|".$clientip] = intval($tmp[1]); + $top_clients[$clientname.'|'.$clientip] = intval($tmp[1]); } else { $top_clients[$clientip] = intval($tmp[1]); } @@ -219,21 +216,21 @@ if (isset($_GET['topClientsBlocked']) && $auth) { } if (isset($_GET['getForwardDestinations']) && $auth) { - if ($_GET['getForwardDestinations'] === "unsorted") { - $return = callFTLAPI("forward-dest unsorted"); + if ('unsorted' === $_GET['getForwardDestinations']) { + $return = callFTLAPI('forward-dest unsorted'); } else { - $return = callFTLAPI("forward-dest"); + $return = callFTLAPI('forward-dest'); } - if (array_key_exists("FTLnotrunning", $return)) { - $data = array("FTLnotrunning" => true); + if (array_key_exists('FTLnotrunning', $return)) { + $data = array('FTLnotrunning' => true); } else { $forward_dest = array(); foreach ($return as $line) { - $tmp = explode(" ",$line); + $tmp = explode(' ', $line); $forwardip = utf8_encode($tmp[2]); if (count($tmp) > 3 && strlen($tmp[3]) > 0) { $forwardname = utf8_encode($tmp[3]); - $forward_dest[$forwardname."|".$forwardip] = floatval($tmp[1]); + $forward_dest[$forwardname.'|'.$forwardip] = floatval($tmp[1]); } else { $forward_dest[$forwardip] = floatval($tmp[1]); } @@ -245,13 +242,13 @@ if (isset($_GET['getForwardDestinations']) && $auth) { } if (isset($_GET['getQueryTypes']) && $auth) { - $return = callFTLAPI("querytypes"); - if (array_key_exists("FTLnotrunning", $return)) { - $data = array("FTLnotrunning" => true); + $return = callFTLAPI('querytypes'); + if (array_key_exists('FTLnotrunning', $return)) { + $data = array('FTLnotrunning' => true); } else { $querytypes = array(); foreach ($return as $ret) { - $tmp = explode(": ",$ret); + $tmp = explode(': ', $ret); // Reply cannot contain non-ASCII characters $querytypes[$tmp[0]] = floatval($tmp[1]); } @@ -262,13 +259,13 @@ if (isset($_GET['getQueryTypes']) && $auth) { } if (isset($_GET['getCacheInfo']) && $auth) { - $return = callFTLAPI("cacheinfo"); - if (array_key_exists("FTLnotrunning", $return)) { - $data = array("FTLnotrunning" => true); + $return = callFTLAPI('cacheinfo'); + if (array_key_exists('FTLnotrunning', $return)) { + $data = array('FTLnotrunning' => true); } else { $cacheinfo = array(); foreach ($return as $ret) { - $tmp = explode(": ",$ret); + $tmp = explode(': ', $ret); // Reply cannot contain non-ASCII characters $cacheinfo[$tmp[0]] = floatval($tmp[1]); } @@ -279,33 +276,33 @@ if (isset($_GET['getCacheInfo']) && $auth) { } if (isset($_GET['getAllQueries']) && $auth) { - if (isset($_GET['from']) && isset($_GET['until'])) { + if (isset($_GET['from'], $_GET['until'])) { // Get limited time interval - $return = callFTLAPI("getallqueries-time ".$_GET['from']." ".$_GET['until']); + $return = callFTLAPI('getallqueries-time '.$_GET['from'].' '.$_GET['until']); } elseif (isset($_GET['domain'])) { // Get specific domain only - $return = callFTLAPI("getallqueries-domain ".$_GET['domain']); - } elseif (isset($_GET['client']) && (isset($_GET['type']) && $_GET['type'] === "blocked")) { + $return = callFTLAPI('getallqueries-domain '.$_GET['domain']); + } elseif (isset($_GET['client']) && (isset($_GET['type']) && 'blocked' === $_GET['type'])) { // Get specific client only - $return = callFTLAPI("getallqueries-client-blocked ".$_GET['client']); + $return = callFTLAPI('getallqueries-client-blocked '.$_GET['client']); } elseif (isset($_GET['client'])) { // Get specific client only - $return = callFTLAPI("getallqueries-client ".$_GET['client']); + $return = callFTLAPI('getallqueries-client '.$_GET['client']); } elseif (isset($_GET['querytype'])) { // Get specific query type only - $return = callFTLAPI("getallqueries-qtype ".$_GET['querytype']); + $return = callFTLAPI('getallqueries-qtype '.$_GET['querytype']); } elseif (isset($_GET['forwarddest'])) { // Get specific forward destination only - $return = callFTLAPI("getallqueries-forward ".$_GET['forwarddest']); + $return = callFTLAPI('getallqueries-forward '.$_GET['forwarddest']); } elseif (is_numeric($_GET['getAllQueries'])) { - $return = callFTLAPI("getallqueries (".$_GET['getAllQueries'].")"); + $return = callFTLAPI('getallqueries ('.$_GET['getAllQueries'].')'); } else { // Get all queries - $return = callFTLAPI("getallqueries"); + $return = callFTLAPI('getallqueries'); } - if (array_key_exists("FTLnotrunning", $return)) { - $data = array("FTLnotrunning" => true); + if (array_key_exists('FTLnotrunning', $return)) { + $data = array('FTLnotrunning' => true); } else { // Set the header header('Content-type: application/json'); @@ -314,49 +311,49 @@ if (isset($_GET['getAllQueries']) && $auth) { echo '{"data":['; $first = true; - foreach($return as $line) { + foreach ($return as $line) { // Insert a comma before the next record (except on the first one) if (!$first) { - echo ","; + echo ','; } else { $first = false; } - $row = str_getcsv($line," "); + $row = str_getcsv($line, ' '); // UTF-8 encode domain - $domain = utf8_encode(str_replace("~"," ",$row[2])); + $domain = utf8_encode(str_replace('~', ' ', $row[2])); // UTF-8 encode client host name $client = utf8_encode($row[3]); // Insert into array and output it in JSON format // array: time type domain client status dnssecStatus reply response_time CNAMEDomain regexID upstream destination EDE - echo json_encode([$row[0], $row[1], $domain, $client, $row[4], $row[5], $row[6], $row[7], $row[8], $row[9], $row[10], $row[11]]); + echo json_encode(array($row[0], $row[1], $domain, $client, $row[4], $row[5], $row[6], $row[7], $row[8], $row[9], $row[10], $row[11])); } // Finish the JSON string echo ']}'; // exit at the end - exit(); + exit; } } -if (isset($_GET["recentBlocked"]) && $auth) { - die(utf8_encode(callFTLAPI("recentBlocked")[0])); +if (isset($_GET['recentBlocked']) && $auth) { + exit(utf8_encode(callFTLAPI('recentBlocked')[0])); unset($data); } if (isset($_GET['getForwardDestinationNames']) && $auth) { - $return = callFTLAPI("forward-names"); + $return = callFTLAPI('forward-names'); - if (array_key_exists("FTLnotrunning", $return)) { - $data = array("FTLnotrunning" => true); + if (array_key_exists('FTLnotrunning', $return)) { + $data = array('FTLnotrunning' => true); } else { $forward_dest = array(); foreach ($return as $line) { - $tmp = explode(" ",$line); + $tmp = explode(' ', $line); $forwardip = utf8_encode($tmp[2]); if (count($tmp) > 3) { $forwardname = utf8_encode($tmp[3]); - $forward_dest[$forwardname."|".$forwardip] = floatval($tmp[1]); + $forward_dest[$forwardname.'|'.$forwardip] = floatval($tmp[1]); } else { $forward_dest[$forwardip] = floatval($tmp[1]); } @@ -368,15 +365,15 @@ if (isset($_GET['getForwardDestinationNames']) && $auth) { } if (isset($_GET['overTimeDataQueryTypes']) && $auth) { - $return = callFTLAPI("QueryTypesoverTime"); - if (array_key_exists("FTLnotrunning", $return)) { - $data = array("FTLnotrunning" => true); + $return = callFTLAPI('QueryTypesoverTime'); + if (array_key_exists('FTLnotrunning', $return)) { + $data = array('FTLnotrunning' => true); } else { $over_time = array(); foreach ($return as $line) { - $tmp = explode(" ",$line); - for ($i=0; $i < count($tmp)-1; $i++) { - $over_time[intval($tmp[0])][$i] = floatval($tmp[$i+1]); + $tmp = explode(' ', $line); + for ($i = 0; $i < count($tmp) - 1; ++$i) { + $over_time[intval($tmp[0])][$i] = floatval($tmp[$i + 1]); } } $result = array('over_time' => $over_time); @@ -385,16 +382,16 @@ if (isset($_GET['overTimeDataQueryTypes']) && $auth) { } if (isset($_GET['getClientNames']) && $auth) { - $return = callFTLAPI("client-names"); - if (array_key_exists("FTLnotrunning", $return)) { - $data = array("FTLnotrunning" => true); + $return = callFTLAPI('client-names'); + if (array_key_exists('FTLnotrunning', $return)) { + $data = array('FTLnotrunning' => true); } else { $client_names = array(); foreach ($return as $line) { - $tmp = explode(" ", $line); + $tmp = explode(' ', $line); $client_names[] = array( - "name" => utf8_encode($tmp[0]), - "ip" => utf8_encode($tmp[1]) + 'name' => utf8_encode($tmp[0]), + 'ip' => utf8_encode($tmp[1]), ); } @@ -404,16 +401,16 @@ if (isset($_GET['getClientNames']) && $auth) { } if (isset($_GET['overTimeDataClients']) && $auth) { - $return = callFTLAPI("ClientsoverTime"); + $return = callFTLAPI('ClientsoverTime'); - if (array_key_exists("FTLnotrunning", $return)) { - $data = array("FTLnotrunning" => true); + if (array_key_exists('FTLnotrunning', $return)) { + $data = array('FTLnotrunning' => true); } else { $over_time = array(); foreach ($return as $line) { - $tmp = explode(" ",$line); - for ($i=0; $i < count($tmp)-1; $i++) { - $over_time[intval($tmp[0])][$i] = floatval($tmp[$i+1]); + $tmp = explode(' ', $line); + for ($i = 0; $i < count($tmp) - 1; ++$i) { + $over_time[intval($tmp[0])][$i] = floatval($tmp[$i + 1]); } } $result = array('over_time' => $over_time); @@ -422,20 +419,19 @@ if (isset($_GET['overTimeDataClients']) && $auth) { } if (isset($_GET['delete_lease']) && $auth) { - $return = callFTLAPI("delete-lease ".$_GET['delete_lease']); - if (array_key_exists("FTLnotrunning", $return)) { - $data = array("FTLnotrunning" => true); + $return = callFTLAPI('delete-lease '.$_GET['delete_lease']); + if (array_key_exists('FTLnotrunning', $return)) { + $data = array('FTLnotrunning' => true); } else { - $data["delete_lease"] = $return[0]; + $data['delete_lease'] = $return[0]; } } if (isset($_GET['dns-port']) && $auth) { - $return = callFTLAPI("dns-port"); - if (array_key_exists("FTLnotrunning", $return)) { - $data = array("FTLnotrunning" => true); + $return = callFTLAPI('dns-port'); + if (array_key_exists('FTLnotrunning', $return)) { + $data = array('FTLnotrunning' => true); } else { - $data["dns-port"] = $return[0]; + $data['dns-port'] = $return[0]; } } -?> diff --git a/api_db.php b/api_db.php index 50362ad0..1ab47ff1 100644 --- a/api_db.php +++ b/api_db.php @@ -9,14 +9,14 @@ $api = true; header('Content-type: application/json'); -require("scripts/pi-hole/php/database.php"); -require("scripts/pi-hole/php/password.php"); -require("scripts/pi-hole/php/auth.php"); -require_once("scripts/pi-hole/php/func.php"); +require 'scripts/pi-hole/php/database.php'; +require 'scripts/pi-hole/php/password.php'; +require 'scripts/pi-hole/php/auth.php'; +require_once 'scripts/pi-hole/php/func.php'; check_cors(); // Set maximum execution time to 10 minutes -ini_set("max_execution_time","600"); +ini_set('max_execution_time', '600'); $data = array(); @@ -26,31 +26,29 @@ $data = array(); $QUERYDB = getQueriesDBFilename(); $db = SQLite3_connect($QUERYDB); -if(isset($_GET["network"]) && $auth) -{ +if (isset($_GET['network']) && $auth) { $network = array(); $results = $db->query('SELECT * FROM network'); - while($results !== false && $res = $results->fetchArray(SQLITE3_ASSOC)) - { - $id = intval($res["id"]); + while (false !== $results && $res = $results->fetchArray(SQLITE3_ASSOC)) { + $id = intval($res['id']); // Get IP addresses and host names for this device - $res["ip"] = array(); - $res["name"] = array(); - $network_addresses = $db->query("SELECT ip,name FROM network_addresses WHERE network_id = $id ORDER BY lastSeen DESC"); - while($network_addresses !== false && $network_address = $network_addresses->fetchArray(SQLITE3_ASSOC)) - { - array_push($res["ip"],$network_address["ip"]); - if($network_address["name"] !== null) - array_push($res["name"],utf8_encode($network_address["name"])); - else - array_push($res["name"],""); + $res['ip'] = array(); + $res['name'] = array(); + $network_addresses = $db->query("SELECT ip,name FROM network_addresses WHERE network_id = {$id} ORDER BY lastSeen DESC"); + while (false !== $network_addresses && $network_address = $network_addresses->fetchArray(SQLITE3_ASSOC)) { + array_push($res['ip'], $network_address['ip']); + if (null !== $network_address['name']) { + array_push($res['name'], utf8_encode($network_address['name'])); + } else { + array_push($res['name'], ''); + } } $network_addresses->finalize(); // UTF-8 encode vendor - $res["macVendor"] = utf8_encode($res["macVendor"]); + $res['macVendor'] = utf8_encode($res['macVendor']); array_push($network, $res); } $results->finalize(); @@ -58,48 +56,42 @@ if(isset($_GET["network"]) && $auth) $data = array_merge($data, array('network' => $network)); } -if (isset($_GET['getAllQueries']) && $auth) -{ +if (isset($_GET['getAllQueries']) && $auth) { $allQueries = array(); - if($_GET['getAllQueries'] !== "empty") - { - $from = intval($_GET["from"]); - $until = intval($_GET["until"]); + if ('empty' !== $_GET['getAllQueries']) { + $from = intval($_GET['from']); + $until = intval($_GET['until']); // Use table "query_storage" // - replace domain ID with domain // - replace client ID with client name // - replace forward ID with forward destination - $dbquery = "SELECT timestamp, type,"; + $dbquery = 'SELECT timestamp, type,'; $dbquery .= " CASE typeof(domain) WHEN 'integer' THEN (SELECT domain FROM domain_by_id d WHERE d.id = q.domain) ELSE domain END domain,"; $dbquery .= " CASE typeof(client) WHEN 'integer' THEN ("; $dbquery .= " SELECT CASE TRIM(name) WHEN '' THEN c.ip ELSE c.name END name FROM client_by_id c WHERE c.id = q.client"; - $dbquery .= " ) ELSE client END client,"; + $dbquery .= ' ) ELSE client END client,'; $dbquery .= " CASE typeof(forward) WHEN 'integer' THEN (SELECT forward FROM forward_by_id f WHERE f.id = q.forward) ELSE forward END forward,"; - $dbquery .= " status, reply_type, reply_time, dnssec"; - $dbquery .= " FROM query_storage q"; - $dbquery .= " WHERE timestamp >= :from AND timestamp <= :until "; - if(isset($_GET["types"])) - { - $types = $_GET["types"]; - if(preg_match("/^[0-9]+(?:,[0-9]+)*$/", $types) === 1) - { + $dbquery .= ' status, reply_type, reply_time, dnssec'; + $dbquery .= ' FROM query_storage q'; + $dbquery .= ' WHERE timestamp >= :from AND timestamp <= :until '; + if (isset($_GET['types'])) { + $types = $_GET['types']; + if (1 === preg_match('/^[0-9]+(?:,[0-9]+)*$/', $types)) { // Append selector to DB query. The used regex ensures // that only numbers, separated by commas are accepted // to avoid code injection and other malicious things // We accept only valid lists like "1,2,3" // We reject ",2,3", "1,2," and similar arguments - $dbquery .= "AND status IN (".$types.") "; - } - else - { - die("Error. Selector types specified using an invalid format."); + $dbquery .= 'AND status IN ('.$types.') '; + } else { + exit('Error. Selector types specified using an invalid format.'); } } - $dbquery .= "ORDER BY timestamp ASC"; + $dbquery .= 'ORDER BY timestamp ASC'; $stmt = $db->prepare($dbquery); - $stmt->bindValue(":from", intval($from), SQLITE3_INTEGER); - $stmt->bindValue(":until", intval($until), SQLITE3_INTEGER); + $stmt->bindValue(':from', intval($from), SQLITE3_INTEGER); + $stmt->bindValue(':until', intval($until), SQLITE3_INTEGER); $results = $stmt->execute(); // Start the JSON string @@ -110,24 +102,24 @@ if (isset($_GET['getAllQueries']) && $auth) while ($row = $results->fetchArray(SQLITE3_ASSOC)) { // Insert a comma before the next record (except on the first one) if (!$first) { - echo ","; + echo ','; } else { $first = false; } // Format, encode, transform each field (if necessary). - $time = $row["timestamp"]; - $query_type = getQueryTypeStr($row["type"]); // Convert query type ID to name - $domain = utf8_encode(str_replace("~"," ",$row["domain"])); - $client = $row["client"]; - $status = $row["status"]; - $destination = utf8_encode($row["forward"]); - $reply_type = $row["reply_type"]; - $reply_time = $row["reply_time"]; - $dnssec = $row["dnssec"]; + $time = $row['timestamp']; + $query_type = getQueryTypeStr($row['type']); // Convert query type ID to name + $domain = utf8_encode(str_replace('~', ' ', $row['domain'])); + $client = $row['client']; + $status = $row['status']; + $destination = utf8_encode($row['forward']); + $reply_type = $row['reply_type']; + $reply_time = $row['reply_time']; + $dnssec = $row['dnssec']; // Insert into array and output it in JSON format - echo json_encode([$time, $query_type, $domain, $client, $status, $destination, $reply_type, $reply_time, $dnssec]); + echo json_encode(array($time, $query_type, $domain, $client, $status, $destination, $reply_type, $reply_time, $dnssec)); } } @@ -135,56 +127,47 @@ if (isset($_GET['getAllQueries']) && $auth) echo ']}'; // exit at the end - exit(); + exit; } // only used if getAllQueries==empty $result = array('data' => $allQueries); $data = array_merge($data, $result); } -if (isset($_GET['topClients']) && $auth) -{ +if (isset($_GET['topClients']) && $auth) { // $from = intval($_GET["from"]); - $limit = ""; - if(isset($_GET["from"]) && isset($_GET["until"])) - { - $limit = "WHERE timestamp >= :from AND timestamp <= :until"; - } - elseif(isset($_GET["from"]) && !isset($_GET["until"])) - { - $limit = "WHERE timestamp >= :from"; - } - elseif(!isset($_GET["from"]) && isset($_GET["until"])) - { - $limit = "WHERE timestamp <= :until"; + $limit = ''; + if (isset($_GET['from'], $_GET['until'])) { + $limit = 'WHERE timestamp >= :from AND timestamp <= :until'; + } elseif (isset($_GET['from']) && !isset($_GET['until'])) { + $limit = 'WHERE timestamp >= :from'; + } elseif (!isset($_GET['from']) && isset($_GET['until'])) { + $limit = 'WHERE timestamp <= :until'; } $dbquery = "SELECT CASE typeof(client) WHEN 'integer' THEN ("; $dbquery .= " SELECT CASE TRIM(name) WHEN '' THEN c.ip ELSE c.name END name FROM client_by_id c WHERE c.id = q.client)"; - $dbquery .= " ELSE client END client, count(client) FROM query_storage q ".$limit." GROUP BY client ORDER BY count(client) DESC LIMIT 20"; + $dbquery .= ' ELSE client END client, count(client) FROM query_storage q '.$limit.' GROUP BY client ORDER BY count(client) DESC LIMIT 20'; $stmt = $db->prepare($dbquery); - $stmt->bindValue(":from", intval($_GET['from']), SQLITE3_INTEGER); - $stmt->bindValue(":until", intval($_GET['until']), SQLITE3_INTEGER); + $stmt->bindValue(':from', intval($_GET['from']), SQLITE3_INTEGER); + $stmt->bindValue(':until', intval($_GET['until']), SQLITE3_INTEGER); $results = $stmt->execute(); $clientnums = array(); - if(!is_bool($results)) - while ($row = $results->fetchArray()) - { + if (!is_bool($results)) { + while ($row = $results->fetchArray()) { // $row[0] is the client IP - if(array_key_exists($row[0], $clientnums)) - { + if (array_key_exists($row[0], $clientnums)) { // Entry already exists, add to it (might appear multiple times due to mixed capitalization in the database) $clientnums[$row[0]] += intval($row[1]); - } - else - { + } else { // Entry does not yet exist $clientnums[$row[0]] = intval($row[1]); } } + } // Sort by number of hits arsort($clientnums); @@ -196,46 +179,37 @@ if (isset($_GET['topClients']) && $auth) $data = array_merge($data, $result); } -if (isset($_GET['topDomains']) && $auth) -{ - $limit = ""; +if (isset($_GET['topDomains']) && $auth) { + $limit = ''; - if(isset($_GET["from"]) && isset($_GET["until"])) - { - $limit = " AND timestamp >= :from AND timestamp <= :until"; - } - elseif(isset($_GET["from"]) && !isset($_GET["until"])) - { - $limit = " AND timestamp >= :from"; - } - elseif(!isset($_GET["from"]) && isset($_GET["until"])) - { - $limit = " AND timestamp <= :until"; + if (isset($_GET['from'], $_GET['until'])) { + $limit = ' AND timestamp >= :from AND timestamp <= :until'; + } elseif (isset($_GET['from']) && !isset($_GET['until'])) { + $limit = ' AND timestamp >= :from'; + } elseif (!isset($_GET['from']) && isset($_GET['until'])) { + $limit = ' AND timestamp <= :until'; } // Select top permitted domains only $stmt = $db->prepare('SELECT domain,count(domain) FROM queries WHERE status IN (2,3,12,13,14)'.$limit.' GROUP by domain order by count(domain) desc limit 20'); - $stmt->bindValue(":from", intval($_GET['from']), SQLITE3_INTEGER); - $stmt->bindValue(":until", intval($_GET['until']), SQLITE3_INTEGER); + $stmt->bindValue(':from', intval($_GET['from']), SQLITE3_INTEGER); + $stmt->bindValue(':until', intval($_GET['until']), SQLITE3_INTEGER); $results = $stmt->execute(); $domains = array(); - if(!is_bool($results)) - while ($row = $results->fetchArray()) - { + if (!is_bool($results)) { + while ($row = $results->fetchArray()) { // Convert domain to lower case UTF-8 $c = utf8_encode(strtolower($row[0])); - if(array_key_exists($c, $domains)) - { + if (array_key_exists($c, $domains)) { // Entry already exists, add to it (might appear multiple times due to mixed capitalization in the database) $domains[$c] += intval($row[1]); - } - else - { + } else { // Entry does not yet exist $domains[$c] = intval($row[1]); } } + } // Sort by number of hits arsort($domains); @@ -247,130 +221,119 @@ if (isset($_GET['topDomains']) && $auth) $data = array_merge($data, $result); } -if (isset($_GET['topAds']) && $auth) -{ - $limit = ""; +if (isset($_GET['topAds']) && $auth) { + $limit = ''; - if(isset($_GET["from"]) && isset($_GET["until"])) - { - $limit = " AND timestamp >= :from AND timestamp <= :until"; - } - elseif(isset($_GET["from"]) && !isset($_GET["until"])) - { - $limit = " AND timestamp >= :from"; - } - elseif(!isset($_GET["from"]) && isset($_GET["until"])) - { - $limit = " AND timestamp <= :until"; + if (isset($_GET['from'], $_GET['until'])) { + $limit = ' AND timestamp >= :from AND timestamp <= :until'; + } elseif (isset($_GET['from']) && !isset($_GET['until'])) { + $limit = ' AND timestamp >= :from'; + } elseif (!isset($_GET['from']) && isset($_GET['until'])) { + $limit = ' AND timestamp <= :until'; } $stmt = $db->prepare('SELECT domain,count(domain) FROM queries WHERE status IN (1,4,5,6,7,8,9,10,11)'.$limit.' GROUP by domain order by count(domain) desc limit 10'); - $stmt->bindValue(":from", intval($_GET['from']), SQLITE3_INTEGER); - $stmt->bindValue(":until", intval($_GET['until']), SQLITE3_INTEGER); + $stmt->bindValue(':from', intval($_GET['from']), SQLITE3_INTEGER); + $stmt->bindValue(':until', intval($_GET['until']), SQLITE3_INTEGER); $results = $stmt->execute(); $addomains = array(); - if(!is_bool($results)) - while ($row = $results->fetchArray()) - { + if (!is_bool($results)) { + while ($row = $results->fetchArray()) { $addomains[utf8_encode($row[0])] = intval($row[1]); } + } $result = array('top_ads' => $addomains); $data = array_merge($data, $result); } -if (isset($_GET['getMinTimestamp']) && $auth) -{ +if (isset($_GET['getMinTimestamp']) && $auth) { $results = $db->query('SELECT MIN(timestamp) FROM queries'); - if(!is_bool($results)) + if (!is_bool($results)) { $result = array('mintimestamp' => $results->fetchArray()[0]); - else + } else { $result = array(); + } $data = array_merge($data, $result); } -if (isset($_GET['getMaxTimestamp']) && $auth) -{ +if (isset($_GET['getMaxTimestamp']) && $auth) { $results = $db->query('SELECT MAX(timestamp) FROM queries'); - if(!is_bool($results)) + if (!is_bool($results)) { $result = array('maxtimestamp' => $results->fetchArray()[0]); - else + } else { $result = array(); + } $data = array_merge($data, $result); } -if (isset($_GET['getQueriesCount']) && $auth) -{ +if (isset($_GET['getQueriesCount']) && $auth) { $results = $db->query('SELECT COUNT(timestamp) FROM queries'); - if(!is_bool($results)) + if (!is_bool($results)) { $result = array('count' => $results->fetchArray()[0]); - else + } else { $result = array(); + } $data = array_merge($data, $result); } -if (isset($_GET['getDBfilesize']) && $auth) -{ - $filesize = filesize("/etc/pihole/pihole-FTL.db"); +if (isset($_GET['getDBfilesize']) && $auth) { + $filesize = filesize('/etc/pihole/pihole-FTL.db'); $result = array('filesize' => $filesize); $data = array_merge($data, $result); } -if (isset($_GET['getGraphData']) && $auth) -{ - $limit = ""; +if (isset($_GET['getGraphData']) && $auth) { + $limit = ''; - if(isset($_GET["from"]) && isset($_GET["until"])) - { - $limit = " AND timestamp >= :from AND timestamp <= :until"; - } - elseif(isset($_GET["from"]) && !isset($_GET["until"])) - { - $limit = " AND timestamp >= :from"; - } - elseif(!isset($_GET["from"]) && isset($_GET["until"])) - { - $limit = " AND timestamp <= :until"; + if (isset($_GET['from'], $_GET['until'])) { + $limit = ' AND timestamp >= :from AND timestamp <= :until'; + } elseif (isset($_GET['from']) && !isset($_GET['until'])) { + $limit = ' AND timestamp >= :from'; + } elseif (!isset($_GET['from']) && isset($_GET['until'])) { + $limit = ' AND timestamp <= :until'; } $interval = 600; - if(isset($_GET["interval"])) - { - $q = intval($_GET["interval"]); - if($q >= 10) + if (isset($_GET['interval'])) { + $q = intval($_GET['interval']); + if ($q >= 10) { $interval = $q; + } } // Round $from and $until to match the requested $interval - $from = intval((intval($_GET['from'])/$interval)*$interval); - $until = intval((intval($_GET['until'])/$interval)*$interval); + $from = intval((intval($_GET['from']) / $interval) * $interval); + $until = intval((intval($_GET['until']) / $interval) * $interval); // Count permitted queries in intervals $stmt = $db->prepare('SELECT (timestamp/:interval)*:interval interval, COUNT(*) FROM queries WHERE (status != 0 )'.$limit.' GROUP by interval ORDER by interval'); - $stmt->bindValue(":from", $from, SQLITE3_INTEGER); - $stmt->bindValue(":until", $until, SQLITE3_INTEGER); - $stmt->bindValue(":interval", $interval, SQLITE3_INTEGER); + $stmt->bindValue(':from', $from, SQLITE3_INTEGER); + $stmt->bindValue(':until', $until, SQLITE3_INTEGER); + $stmt->bindValue(':interval', $interval, SQLITE3_INTEGER); $results = $stmt->execute(); // Parse the DB result into graph data, filling in missing interval sections with zero - function parseDBData($results, $interval, $from, $until) { + function parseDBData($results, $interval, $from, $until) + { $data = array(); $first_db_timestamp = -1; - if(!is_bool($results)) { + if (!is_bool($results)) { // Read in the data - while($row = $results->fetchArray()) { + while ($row = $results->fetchArray()) { // $data[timestamp] = value_in_this_interval $data[$row[0]] = intval($row[1]); - if($first_db_timestamp === -1) + if (-1 === $first_db_timestamp) { $first_db_timestamp = intval($row[0]); + } } } @@ -381,9 +344,10 @@ if (isset($_GET['getGraphData']) && $auth) $aligned_from = $from + (($first_db_timestamp - $from) % $interval); // Fill gaps in returned data - for($i = $aligned_from; $i < $until; $i += $interval) { - if(!array_key_exists($i, $data)) + for ($i = $aligned_from; $i < $until; $i += $interval) { + if (!array_key_exists($i, $data)) { $data[$i] = 0; + } } return $data; @@ -396,9 +360,9 @@ if (isset($_GET['getGraphData']) && $auth) // Count blocked queries in intervals $stmt = $db->prepare('SELECT (timestamp/:interval)*:interval interval, COUNT(*) FROM queries WHERE status IN (1,4,5,6,7,8,9,10,11)'.$limit.' GROUP by interval ORDER by interval'); - $stmt->bindValue(":from", $from, SQLITE3_INTEGER); - $stmt->bindValue(":until", $until, SQLITE3_INTEGER); - $stmt->bindValue(":interval", $interval, SQLITE3_INTEGER); + $stmt->bindValue(':from', $from, SQLITE3_INTEGER); + $stmt->bindValue(':until', $until, SQLITE3_INTEGER); + $stmt->bindValue(':interval', $interval, SQLITE3_INTEGER); $results = $stmt->execute(); $addomains = parseDBData($results, $interval, $from, $until); @@ -407,37 +371,38 @@ if (isset($_GET['getGraphData']) && $auth) $data = array_merge($data, $result); } -if (isset($_GET['status']) && $auth) -{ - $extra = ";"; - if(isset($_GET["ignore"]) && $_GET["ignore"] === 'DNSMASQ_WARN') +if (isset($_GET['status']) && $auth) { + $extra = ';'; + if (isset($_GET['ignore']) && 'DNSMASQ_WARN' === $_GET['ignore']) { $extra = "WHERE type != 'DNSMASQ_WARN';"; + } $results = $db->query('SELECT COUNT(*) FROM message '.$extra); - if(!is_bool($results)) + if (!is_bool($results)) { $result = array('message_count' => $results->fetchArray()[0]); - else + } else { $result = array(); + } $data = array_merge($data, $result); } -if(isset($_GET["messages"]) && $auth) -{ - $extra = ";"; - if(isset($_GET["ignore"]) && $_GET["ignore"] === 'DNSMASQ_WARN') +if (isset($_GET['messages']) && $auth) { + $extra = ';'; + if (isset($_GET['ignore']) && 'DNSMASQ_WARN' === $_GET['ignore']) { $extra = "WHERE type != 'DNSMASQ_WARN';"; + } $messages = array(); $results = $db->query('SELECT * FROM message '.$extra); - while($results !== false && $res = $results->fetchArray(SQLITE3_ASSOC)) - { + while (false !== $results && $res = $results->fetchArray(SQLITE3_ASSOC)) { // Convert string to to UTF-8 encoding to ensure php-json can handle it. // Furthermore, convert special characters to HTML entities to prevent XSS attacks. foreach ($res as $key => $value) { - if (is_string($value)) + if (is_string($value)) { $res[$key] = htmlspecialchars(utf8_encode($value)); + } } array_push($messages, $res); } @@ -445,11 +410,8 @@ if(isset($_GET["messages"]) && $auth) $data = array_merge($data, array('messages' => $messages)); } -if(isset($_GET["jsonForceObject"])) -{ +if (isset($_GET['jsonForceObject'])) { echo json_encode($data, JSON_FORCE_OBJECT); -} -else -{ +} else { echo json_encode($data); } diff --git a/auditlog.php b/auditlog.php index 42eed377..b1e7cfb3 100644 --- a/auditlog.php +++ b/auditlog.php @@ -8,7 +8,7 @@ * Please see LICENSE file for your rights under this license. */ -require "scripts/pi-hole/php/header.php"; +require 'scripts/pi-hole/php/header.php'; ?> @@ -79,8 +79,8 @@ require "scripts/pi-hole/php/header.php"; - + diff --git a/cname_records.php b/cname_records.php index 7fce4339..a4bb97e9 100644 --- a/cname_records.php +++ b/cname_records.php @@ -8,7 +8,7 @@ * Please see LICENSE file for your rights under this license. */ -require "scripts/pi-hole/php/header.php"; +require 'scripts/pi-hole/php/header.php'; ?> @@ -79,8 +79,8 @@ require "scripts/pi-hole/php/header.php"; - + diff --git a/db_graph.php b/db_graph.php index 6594411e..9f9be574 100644 --- a/db_graph.php +++ b/db_graph.php @@ -8,7 +8,7 @@ * Please see LICENSE file for your rights under this license. */ -require "scripts/pi-hole/php/header.php"; +require 'scripts/pi-hole/php/header.php'; ?> @@ -75,8 +75,8 @@ require "scripts/pi-hole/php/header.php"; - - + + diff --git a/db_lists.php b/db_lists.php index 47f5a8e5..511f58a8 100644 --- a/db_lists.php +++ b/db_lists.php @@ -8,7 +8,7 @@ * Please see LICENSE file for your rights under this license. */ -require "scripts/pi-hole/php/header.php"; +require 'scripts/pi-hole/php/header.php'; ?> @@ -49,13 +49,10 @@ require "scripts/pi-hole/php/header.php";
@@ -148,9 +145,9 @@ else
- - + + diff --git a/db_queries.php b/db_queries.php index 8c4461af..73e43c88 100644 --- a/db_queries.php +++ b/db_queries.php @@ -8,7 +8,7 @@ * Please see LICENSE file for your rights under this license. */ -require "scripts/pi-hole/php/header.php"; +require 'scripts/pi-hole/php/header.php'; ?> @@ -206,10 +206,10 @@ require "scripts/pi-hole/php/header.php"; - - - + + + diff --git a/debug.php b/debug.php index 9c6baee0..f3472026 100644 --- a/debug.php +++ b/debug.php @@ -8,7 +8,7 @@ * Please see LICENSE file for your rights under this license. */ -require "scripts/pi-hole/php/header.php"; +require 'scripts/pi-hole/php/header.php'; ?> - - + + diff --git a/gravity.php b/gravity.php index 406d4c06..20937937 100644 --- a/gravity.php +++ b/gravity.php @@ -8,7 +8,7 @@ * Please see LICENSE file for your rights under this license. */ -require "scripts/pi-hole/php/header.php"; +require 'scripts/pi-hole/php/header.php'; ?> - - - + + + diff --git a/groups-clients.php b/groups-clients.php index 9e35e406..2fa3cd79 100644 --- a/groups-clients.php +++ b/groups-clients.php @@ -8,7 +8,7 @@ * Please see LICENSE file for your rights under this license. */ -require "scripts/pi-hole/php/header.php"; +require 'scripts/pi-hole/php/header.php'; ?> @@ -91,11 +91,11 @@ require "scripts/pi-hole/php/header.php"; - - - - + + + + diff --git a/groups-domains.php b/groups-domains.php index bdff2871..f8c854a4 100644 --- a/groups-domains.php +++ b/groups-domains.php @@ -8,7 +8,7 @@ * Please see LICENSE file for your rights under this license. */ -require "scripts/pi-hole/php/header.php"; +require 'scripts/pi-hole/php/header.php'; ?> @@ -138,10 +138,10 @@ require "scripts/pi-hole/php/header.php"; - - - + + + diff --git a/groups.php b/groups.php index 80b8e8e6..640033c6 100644 --- a/groups.php +++ b/groups.php @@ -8,7 +8,7 @@ * Please see LICENSE file for your rights under this license. */ -require "scripts/pi-hole/php/header.php"; +require 'scripts/pi-hole/php/header.php'; ?> @@ -80,10 +80,10 @@ require "scripts/pi-hole/php/header.php"; - - - + + + diff --git a/index.php b/index.php index 95b867b5..8db55d00 100644 --- a/index.php +++ b/index.php @@ -8,8 +8,8 @@ */ $indexpage = true; -require "scripts/pi-hole/php/header.php"; -require_once "scripts/pi-hole/php/gravity.php"; +require 'scripts/pi-hole/php/header.php'; +require_once 'scripts/pi-hole/php/gravity.php'; ?> @@ -95,8 +95,8 @@ require_once "scripts/pi-hole/php/gravity.php"; // Even if we would include them here anyhow, there would be nothing to // show since the API will respect the privacy of the user if he defines // a password -if($auth){ -?> +if ($auth) { + ?>
@@ -159,15 +159,11 @@ if($auth){
+ if ($boxedlayout) { + $tablelayout = 'col-md-6'; + } else { + $tablelayout = 'col-md-6 col-lg-6'; + } ?>
@@ -289,10 +285,11 @@ if($auth){
- + - + diff --git a/messages.php b/messages.php index adf4cc88..639a2a64 100644 --- a/messages.php +++ b/messages.php @@ -8,7 +8,7 @@ * Please see LICENSE file for your rights under this license. */ -require "scripts/pi-hole/php/header.php"; +require 'scripts/pi-hole/php/header.php'; ?> @@ -47,8 +47,8 @@ require "scripts/pi-hole/php/header.php";
- + diff --git a/network.php b/network.php index f6b0ed5b..7d58db6e 100644 --- a/network.php +++ b/network.php @@ -7,7 +7,7 @@ * Please see LICENSE file for your rights under this license. */ -require "scripts/pi-hole/php/header.php"; +require 'scripts/pi-hole/php/header.php'; ?>
@@ -66,9 +66,9 @@ require "scripts/pi-hole/php/header.php";
- - + + diff --git a/queries.php b/queries.php index 63d4a675..3c1c9252 100644 --- a/queries.php +++ b/queries.php @@ -8,93 +8,66 @@ * Please see LICENSE file for your rights under this license. */ -require "scripts/pi-hole/php/header.php"; +require 'scripts/pi-hole/php/header.php'; -$showing = ""; +$showing = ''; -if(isset($setupVars["API_QUERY_LOG_SHOW"])) -{ - if($setupVars["API_QUERY_LOG_SHOW"] === "all") - { - $showing = "showing"; +if (isset($setupVars['API_QUERY_LOG_SHOW'])) { + if ('all' === $setupVars['API_QUERY_LOG_SHOW']) { + $showing = 'showing'; + } elseif ('permittedonly' === $setupVars['API_QUERY_LOG_SHOW']) { + $showing = 'showing permitted'; + } elseif ('blockedonly' === $setupVars['API_QUERY_LOG_SHOW']) { + $showing = 'showing blocked'; + } elseif ('nothing' === $setupVars['API_QUERY_LOG_SHOW']) { + $showing = 'showing no queries (due to setting)'; } - elseif($setupVars["API_QUERY_LOG_SHOW"] === "permittedonly") - { - $showing = "showing permitted"; - } - elseif($setupVars["API_QUERY_LOG_SHOW"] === "blockedonly") - { - $showing = "showing blocked"; - } - elseif($setupVars["API_QUERY_LOG_SHOW"] === "nothing") - { - $showing = "showing no queries (due to setting)"; - } -} -else if(isset($_GET["type"]) && $_GET["type"] === "blocked") -{ - $showing = "showing blocked"; -} -else -{ +} elseif (isset($_GET['type']) && 'blocked' === $_GET['type']) { + $showing = 'showing blocked'; +} else { // If filter variable is not set, we // automatically show all queries - $showing = "showing"; + $showing = 'showing'; } $showall = false; -if(isset($_GET["all"])) -{ - $showing .= " all queries within the Pi-hole log"; -} -else if(isset($_GET["client"])) -{ +if (isset($_GET['all'])) { + $showing .= ' all queries within the Pi-hole log'; +} elseif (isset($_GET['client'])) { // Add switch between showing all queries and blocked only - if (isset($_GET["type"]) && $_GET["type"] === "blocked") - { + if (isset($_GET['type']) && 'blocked' === $_GET['type']) { // Show blocked queries for this client + link to all - $showing .= " blocked queries for client ".htmlentities($_GET["client"]); - $showing .= ", show all"; - } - else - { + $showing .= ' blocked queries for client '.htmlentities($_GET['client']); + $showing .= ', show all'; + } else { // Show All queries for this client + link to show only blocked - $showing .= " all queries for client ".htmlentities($_GET["client"]); - $showing .= ", show blocked only"; + $showing .= ' all queries for client '.htmlentities($_GET['client']); + $showing .= ', show blocked only'; } -} -else if(isset($_GET["forwarddest"])) -{ - if($_GET["forwarddest"] === "blocked") - $showing .= " queries blocked by Pi-hole"; - elseif($_GET["forwarddest"] === "cached") - $showing .= " queries answered from cache"; - else - $showing .= " queries for upstream destination ".htmlentities($_GET["forwarddest"]); -} -else if(isset($_GET["querytype"])) -{ - $showing .= " type ".getQueryTypeStr($_GET["querytype"])." queries"; -} -else if(isset($_GET["domain"])) -{ - $showing .= " queries for domain ".htmlentities($_GET["domain"]); -} -else if(isset($_GET["from"]) || isset($_GET["until"])) -{ - $showing .= " queries within specified time interval"; -} -else -{ - $showing .= " up to 100 queries"; +} elseif (isset($_GET['forwarddest'])) { + if ('blocked' === $_GET['forwarddest']) { + $showing .= ' queries blocked by Pi-hole'; + } elseif ('cached' === $_GET['forwarddest']) { + $showing .= ' queries answered from cache'; + } else { + $showing .= ' queries for upstream destination '.htmlentities($_GET['forwarddest']); + } +} elseif (isset($_GET['querytype'])) { + $showing .= ' type '.getQueryTypeStr($_GET['querytype']).' queries'; +} elseif (isset($_GET['domain'])) { + $showing .= ' queries for domain '.htmlentities($_GET['domain']); +} elseif (isset($_GET['from']) || isset($_GET['until'])) { + $showing .= ' queries within specified time interval'; +} else { + $showing .= ' up to 100 queries'; $showall = true; } -if(strlen($showing) > 0) -{ - $showing = "(".$showing.")"; - if($showall) - $showing .= ", show all"; +if (strlen($showing) > 0) { + $showing = '('.$showing.')'; + if ($showall) { + $showing .= ', show all'; + } } ?> @@ -178,9 +151,9 @@ if(strlen($showing) > 0)
- - + + diff --git a/queryads.php b/queryads.php index 4adff8e4..7e2ab4aa 100644 --- a/queryads.php +++ b/queryads.php @@ -8,7 +8,7 @@ * Please see LICENSE file for your rights under this license. */ -require "scripts/pi-hole/php/header.php"; +require 'scripts/pi-hole/php/header.php'; ?> "; + echo ''; + echo 'Raw API Token: '.$pwhash.''; } else { - echo "

No password set

"; + echo '

No password set

'; } } else { - echo "

Not authorized!

"; + echo '

Not authorized!

'; } ?> diff --git a/scripts/pi-hole/php/auth.php b/scripts/pi-hole/php/auth.php index 44b2bc76..a3120924 100644 --- a/scripts/pi-hole/php/auth.php +++ b/scripts/pi-hole/php/auth.php @@ -7,7 +7,7 @@ * Please see LICENSE file for your rights under this license. */ -require_once('func.php'); +require_once 'func.php'; $ERRORLOG = getenv('PHP_ERROR_LOG'); if (empty($ERRORLOG)) { @@ -22,35 +22,41 @@ if (empty($ERRORLOG)) { } } -function pi_log($message) { - error_log(date('Y-m-d H:i:s') . ': ' . $message . "\n", 3, $GLOBALS['ERRORLOG']); +function pi_log($message) +{ + error_log(date('Y-m-d H:i:s').': '.$message."\n", 3, $GLOBALS['ERRORLOG']); } -function log_and_die($message) { +function log_and_die($message) +{ pi_log($message); - die($message); + + exit($message); } -function check_cors() { +function check_cors() +{ $ip = $_SERVER['SERVER_ADDR']; // Check CORS $AUTHORIZED_HOSTNAMES = array( $ip, - str_replace(array("[","]"), array("",""), $_SERVER["SERVER_NAME"]), - "pi.hole", - "localhost" + str_replace(array('[', ']'), array('', ''), $_SERVER['SERVER_NAME']), + 'pi.hole', + 'localhost', ); - # Allow user set virtual hostnames + // Allow user set virtual hostnames $virtual_host = getenv('VIRTUAL_HOST'); - if (! empty($virtual_host)) + if (!empty($virtual_host)) { array_push($AUTHORIZED_HOSTNAMES, $virtual_host); + } - # Allow user set CORS + // Allow user set CORS $cors_hosts = getenv('CORS_HOSTS'); - if (! empty($cors_hosts)) - array_push($AUTHORIZED_HOSTNAMES, ...explode(",", $cors_hosts)); + if (!empty($cors_hosts)) { + array_push($AUTHORIZED_HOSTNAMES, ...explode(',', $cors_hosts)); + } // Since the Host header is easily manipulated, we can only check if it's wrong and can't use it // to validate that the client is authorized, only unauthorized. @@ -64,43 +70,42 @@ function check_cors() { // Don't use parse_url for IPv6 addresses, since it does not support them // see PHP bug report: https://bugs.php.net/bug.php?id=72811 - if(strpos($server_host, ":") && !strpos($server_host, "[") && !strpos($server_host, "]")) - { + if (strpos($server_host, ':') && !strpos($server_host, '[') && !strpos($server_host, ']')) { $server_host = parse_url($_SERVER['HTTP_HOST'], PHP_URL_HOST); } // Remove "[" ... "]" - $server_host = str_replace(array("[","]"), array("",""), $server_host); + $server_host = str_replace(array('[', ']'), array('', ''), $server_host); - if(isset($_SERVER['HTTP_HOST']) && !in_array($server_host, $AUTHORIZED_HOSTNAMES)) { - log_and_die("Failed Host Check: " . $server_host .' vs '. htmlspecialchars(join(', ', $AUTHORIZED_HOSTNAMES))); + if (isset($_SERVER['HTTP_HOST']) && !in_array($server_host, $AUTHORIZED_HOSTNAMES)) { + log_and_die('Failed Host Check: '.$server_host.' vs '.htmlspecialchars(join(', ', $AUTHORIZED_HOSTNAMES))); } - if(isset($_SERVER['HTTP_ORIGIN'])) { + if (isset($_SERVER['HTTP_ORIGIN'])) { $server_origin = $_SERVER['HTTP_ORIGIN']; // Detect colon in $_SERVER['HTTP_ORIGIN'] (see comment above) - if(strpos($server_origin, ":") && !strpos($server_origin, "[") && !strpos($server_origin, "]")) - { + if (strpos($server_origin, ':') && !strpos($server_origin, '[') && !strpos($server_origin, ']')) { $server_origin = parse_url($_SERVER['HTTP_ORIGIN'], PHP_URL_HOST); } // Remove "[", "]","http://", and "https://" - $server_origin = str_replace(array("[","]","http://","https://"), array("","","",""), $server_origin); + $server_origin = str_replace(array('[', ']', 'http://', 'https://'), array('', '', '', ''), $server_origin); - if(!in_array($server_origin, $AUTHORIZED_HOSTNAMES)) { - log_and_die("Failed CORS: " . htmlspecialchars($server_origin) .' vs '. htmlspecialchars(join(', ', $AUTHORIZED_HOSTNAMES))); + if (!in_array($server_origin, $AUTHORIZED_HOSTNAMES)) { + log_and_die('Failed CORS: '.htmlspecialchars($server_origin).' vs '.htmlspecialchars(join(', ', $AUTHORIZED_HOSTNAMES))); } header("Access-Control-Allow-Origin: ${_SERVER['HTTP_ORIGIN']}"); } // If there's no HTTP_ORIGIN, CORS should not be used } -function check_csrf($token) { +function check_csrf($token) +{ // Check CSRF token - $session_started = function_exists("session_status") ? - session_status() == PHP_SESSION_ACTIVE : - session_id() == ""; + $session_started = function_exists('session_status') ? + PHP_SESSION_ACTIVE == session_status() : + '' == session_id(); - if(!$session_started) { + if (!$session_started) { // Start a new PHP session (or continue an existing one) // Prevents javascript XSS attacks aimed to steal the session ID ini_set('session.cookie_httponly', 1); @@ -109,26 +114,25 @@ function check_csrf($token) { session_start(); } - if(!isset($_SESSION['token'])) { - log_and_die("Session expired! Please re-login on the Pi-hole dashboard."); + if (!isset($_SESSION['token'])) { + log_and_die('Session expired! Please re-login on the Pi-hole dashboard.'); } - if(empty($token)) { - log_and_die("Empty token! Check if cookies are enabled on your system."); + if (empty($token)) { + log_and_die('Empty token! Check if cookies are enabled on your system.'); } - if(!hash_equals($_SESSION['token'], $token)) { - log_and_die("Wrong token! Please re-login on the Pi-hole dashboard."); + if (!hash_equals($_SESSION['token'], $token)) { + log_and_die('Wrong token! Please re-login on the Pi-hole dashboard.'); } } -function check_domain(&$domains) { - foreach($domains as &$domain) - { +function check_domain(&$domains) +{ + foreach ($domains as &$domain) { $validDomain = validDomain($domain); - if(!$validDomain){ - log_and_die(htmlspecialchars($domain. ' is not a valid domain')); + if (!$validDomain) { + log_and_die(htmlspecialchars($domain.' is not a valid domain')); } } } -?> diff --git a/scripts/pi-hole/php/customcname.php b/scripts/pi-hole/php/customcname.php index 814a83a0..7b89dfe7 100644 --- a/scripts/pi-hole/php/customcname.php +++ b/scripts/pi-hole/php/customcname.php @@ -1,6 +1,7 @@ diff --git a/scripts/pi-hole/php/customdns.php b/scripts/pi-hole/php/customdns.php index 5a0216af..351781c4 100644 --- a/scripts/pi-hole/php/customdns.php +++ b/scripts/pi-hole/php/customdns.php @@ -1,6 +1,7 @@ diff --git a/scripts/pi-hole/php/database.php b/scripts/pi-hole/php/database.php index 5fdc32c9..57efcf14 100644 --- a/scripts/pi-hole/php/database.php +++ b/scripts/pi-hole/php/database.php @@ -10,68 +10,52 @@ function getGravityDBFilename() { // Get possible non-standard location of FTL's database - $FTLsettings = parse_ini_file("/etc/pihole/pihole-FTL.conf"); - if(isset($FTLsettings["GRAVITYDB"])) - { - return $FTLsettings["GRAVITYDB"]; - } - else - { - return "/etc/pihole/gravity.db"; + $FTLsettings = parse_ini_file('/etc/pihole/pihole-FTL.conf'); + if (isset($FTLsettings['GRAVITYDB'])) { + return $FTLsettings['GRAVITYDB']; } + + return '/etc/pihole/gravity.db'; } function getQueriesDBFilename() { // Get possible non-standard location of FTL's database - $FTLsettings = parse_ini_file("/etc/pihole/pihole-FTL.conf"); - if(isset($FTLsettings["DBFILE"])) - { - return $FTLsettings["DBFILE"]; - } - else - { - return "/etc/pihole/pihole-FTL.db"; + $FTLsettings = parse_ini_file('/etc/pihole/pihole-FTL.conf'); + if (isset($FTLsettings['DBFILE'])) { + return $FTLsettings['DBFILE']; } + + return '/etc/pihole/pihole-FTL.db'; } function SQLite3_connect_try($filename, $mode, $trytoreconnect) { - try - { + try { // connect to database return new SQLite3($filename, $mode); - } - catch (Exception $exception) - { + } catch (Exception $exception) { // sqlite3 throws an exception when it is unable to connect, try to reconnect after 3 seconds - if($trytoreconnect) - { + if ($trytoreconnect) { sleep(3); + return SQLite3_connect_try($filename, $mode, false); } - else - { - // If we should not try again (or are already trying again!), we return the exception string - // so the user gets it on the dashboard - return $filename.": ".$exception->getMessage(); - } + // If we should not try again (or are already trying again!), we return the exception string + // so the user gets it on the dashboard + return $filename.': '.$exception->getMessage(); } } -function SQLite3_connect($filename, $mode=SQLITE3_OPEN_READONLY) +function SQLite3_connect($filename, $mode = SQLITE3_OPEN_READONLY) { - if(strlen($filename) > 0) - { + if (strlen($filename) > 0) { $db = SQLite3_connect_try($filename, $mode, true); + } else { + exit('No database available'); } - else - { - die("No database available"); - } - if(is_string($db)) - { - die("Error connecting to database\n".$db); + if (is_string($db)) { + exit("Error connecting to database\n".$db); } // Add busy timeout so methods don't fail immediately when, e.g., FTL is currently reading from the DB @@ -80,9 +64,8 @@ function SQLite3_connect($filename, $mode=SQLITE3_OPEN_READONLY) return $db; } - /** - * Add domains to a given table + * Add domains to a given table. * * @param $db object The SQLite3 database connection object * @param $table string The target table @@ -90,233 +73,218 @@ function SQLite3_connect($filename, $mode=SQLITE3_OPEN_READONLY) * @param $wildcardstyle boolean Whether to format the input domains in legacy wildcard notation * @param $returnnum boolean Whether to return an integer or a string * @param $type integer The target type (0 = exact whitelist, 1 = exact blacklist, 2 = regex whitelist, 3 = regex blacklist) + * @param mixed|null $comment + * * @return string Success/error and number of processed domains */ -function add_to_table($db, $table, $domains, $comment=null, $wildcardstyle=false, $returnnum=false, $type=-1) +function add_to_table($db, $table, $domains, $comment = null, $wildcardstyle = false, $returnnum = false, $type = -1) { - if(!is_int($type)) - { - return "Error: Argument type has to be of type integer (is ".gettype($type).")"; + if (!is_int($type)) { + return 'Error: Argument type has to be of type integer (is '.gettype($type).')'; } // Begin transaction - if(!$db->exec("BEGIN TRANSACTION;")) - { - if($returnnum) + if (!$db->exec('BEGIN TRANSACTION;')) { + if ($returnnum) { return 0; - else - return "Error: Unable to begin transaction for $table table."; + } + + return "Error: Unable to begin transaction for {$table} table."; } // To which column should the record be added to? - if ($table === "adlist") - { - $field = "address"; - } - else - { - $field = "domain"; + if ('adlist' === $table) { + $field = 'address'; + } else { + $field = 'domain'; } // Get initial count of domains in this table - if($type === -1) - { - $countquery = "SELECT COUNT(*) FROM $table;"; - } - else - { - $countquery = "SELECT COUNT(*) FROM $table WHERE type = $type;"; + if (-1 === $type) { + $countquery = "SELECT COUNT(*) FROM {$table};"; + } else { + $countquery = "SELECT COUNT(*) FROM {$table} WHERE type = {$type};"; } $initialcount = intval($db->querySingle($countquery)); // Prepare INSERT SQLite statement $bindcomment = false; - if($table === "domain_audit") { - $querystr = "INSERT OR IGNORE INTO $table ($field) VALUES (:$field);"; - } elseif($type === -1) { - $querystr = "INSERT OR IGNORE INTO $table ($field,comment) VALUES (:$field, :comment);"; + if ('domain_audit' === $table) { + $querystr = "INSERT OR IGNORE INTO {$table} ({$field}) VALUES (:{$field});"; + } elseif (-1 === $type) { + $querystr = "INSERT OR IGNORE INTO {$table} ({$field},comment) VALUES (:{$field}, :comment);"; $bindcomment = true; } else { - $querystr = "REPLACE INTO $table ($field,comment,type) VALUES (:$field, :comment, $type);"; + $querystr = "REPLACE INTO {$table} ({$field},comment,type) VALUES (:{$field}, :comment, {$type});"; $bindcomment = true; } $stmt = $db->prepare($querystr); // Return early if we failed to prepare the SQLite statement - if(!$stmt) - { - if($returnnum) + if (!$stmt) { + if ($returnnum) { return 0; - else - return "Error: Failed to prepare statement for $table table (type = $type, field = $field)."; + } + + return "Error: Failed to prepare statement for {$table} table (type = {$type}, field = {$field})."; } // Loop over domains and inject the lines into the database $num = 0; - foreach($domains as $domain) - { + foreach ($domains as $domain) { // Limit max length for a domain entry to 253 chars - if(strlen($domain) > 253) + if (strlen($domain) > 253) { continue; - - if($wildcardstyle) - $domain = "(\\.|^)".str_replace(".","\\.",$domain)."$"; - - $stmt->bindValue(":$field", htmlentities($domain), SQLITE3_TEXT); - if($bindcomment) { - $stmt->bindValue(":comment", htmlentities($comment), SQLITE3_TEXT); } - if($stmt->execute() && $stmt->reset()) - $num++; - else - { + if ($wildcardstyle) { + $domain = '(\\.|^)'.str_replace('.', '\\.', $domain).'$'; + } + + $stmt->bindValue(":{$field}", htmlentities($domain), SQLITE3_TEXT); + if ($bindcomment) { + $stmt->bindValue(':comment', htmlentities($comment), SQLITE3_TEXT); + } + + if ($stmt->execute() && $stmt->reset()) { + ++$num; + } else { $stmt->close(); - if($returnnum) + if ($returnnum) { return $num; - else - { - if($num === 1) - $plural = ""; - else - $plural = "s"; - return "Error: ".$db->lastErrorMsg().", added ".$num." domain".$plural; } + if (1 === $num) { + $plural = ''; + } else { + $plural = 's'; + } + + return 'Error: '.$db->lastErrorMsg().', added '.$num.' domain'.$plural; } } // Close prepared statement and return number of processed rows $stmt->close(); - $db->exec("COMMIT;"); + $db->exec('COMMIT;'); - if($returnnum) + if ($returnnum) { return $num; - else - { - $finalcount = intval($db->querySingle($countquery)); - $modified = $finalcount - $initialcount; - - // If we add less domains than the user specified, then they wanted to add duplicates - if($modified !== $num) - { - $delta = $num - $modified; - $extra = " (skipped ".$delta." duplicates)"; - } - else - { - $extra = ""; - } - - if($num === 1) - $plural = ""; - else - $plural = "s"; - return "Success, added ".$modified." of ".$num." domain".$plural.$extra; } + $finalcount = intval($db->querySingle($countquery)); + $modified = $finalcount - $initialcount; + + // If we add less domains than the user specified, then they wanted to add duplicates + if ($modified !== $num) { + $delta = $num - $modified; + $extra = ' (skipped '.$delta.' duplicates)'; + } else { + $extra = ''; + } + + if (1 === $num) { + $plural = ''; + } else { + $plural = 's'; + } + + return 'Success, added '.$modified.' of '.$num.' domain'.$plural.$extra; } /** - * Remove domains from a given table + * Remove domains from a given table. * * @param $db object The SQLite3 database connection object * @param $table string The target table * @param $domains array Array of domains (strings) to be removed from the table * @param $returnnum boolean Whether to return an integer or a string * @param $type integer The target type (0 = exact whitelist, 1 = exact blacklist, 2 = regex whitelist, 3 = regex blacklist) + * * @return string Success/error and number of processed domains */ -function remove_from_table($db, $table, $domains, $returnnum=false, $type=-1) +function remove_from_table($db, $table, $domains, $returnnum = false, $type = -1) { - if(!is_int($type)) - { - return "Error: Argument type has to be of type integer (is ".gettype($type).")"; + if (!is_int($type)) { + return 'Error: Argument type has to be of type integer (is '.gettype($type).')'; } // Begin transaction - if(!$db->exec("BEGIN TRANSACTION;")) - { - if($returnnum) + if (!$db->exec('BEGIN TRANSACTION;')) { + if ($returnnum) { return 0; - else - return "Error: Unable to begin transaction for domainlist table."; + } + + return 'Error: Unable to begin transaction for domainlist table.'; } // Get initial count of domains in this table - if($type === -1) - { - $countquery = "SELECT COUNT(*) FROM $table;"; - } - else - { - $countquery = "SELECT COUNT(*) FROM $table WHERE type = $type;"; + if (-1 === $type) { + $countquery = "SELECT COUNT(*) FROM {$table};"; + } else { + $countquery = "SELECT COUNT(*) FROM {$table} WHERE type = {$type};"; } $initialcount = intval($db->querySingle($countquery)); // Prepare SQLite statement - if($type === -1) - { - $querystr = "DELETE FROM $table WHERE domain = :domain AND type = $type;"; - } - else - { - $querystr = "DELETE FROM $table WHERE domain = :domain;"; + if (-1 === $type) { + $querystr = "DELETE FROM {$table} WHERE domain = :domain AND type = {$type};"; + } else { + $querystr = "DELETE FROM {$table} WHERE domain = :domain;"; } $stmt = $db->prepare($querystr); // Return early if we failed to prepare the SQLite statement - if(!$stmt) - { - if($returnnum) + if (!$stmt) { + if ($returnnum) { return 0; - else - return "Error: Failed to prepare statement for ".$table." table (type = ".$type.")."; + } + + return 'Error: Failed to prepare statement for '.$table.' table (type = '.$type.').'; } // Loop over domains and remove the lines from the database $num = 0; - foreach($domains as $domain) - { - $stmt->bindValue(":domain", $domain, SQLITE3_TEXT); + foreach ($domains as $domain) { + $stmt->bindValue(':domain', $domain, SQLITE3_TEXT); - if($stmt->execute() && $stmt->reset()) - $num++; - else - { + if ($stmt->execute() && $stmt->reset()) { + ++$num; + } else { $stmt->close(); - if($returnnum) + if ($returnnum) { return $num; - else - { - if($num === 1) - $plural = ""; - else - $plural = "s"; - return "Error: ".$db->lastErrorMsg().", removed ".$num." domain".$plural; } + if (1 === $num) { + $plural = ''; + } else { + $plural = 's'; + } + + return 'Error: '.$db->lastErrorMsg().', removed '.$num.' domain'.$plural; } } // Close prepared statement and return number or processed rows $stmt->close(); - $db->exec("COMMIT;"); + $db->exec('COMMIT;'); - if($returnnum) + if ($returnnum) { return $num; - else - { - if($num === 1) - $plural = ""; - else - $plural = "s"; - return "Success, removed ".$num." domain".$plural; } + if (1 === $num) { + $plural = ''; + } else { + $plural = 's'; + } + + return 'Success, removed '.$num.' domain'.$plural; } -if (!class_exists("ListType")) { - class ListType{ - const whitelist = 0; - const blacklist = 1; - const regex_whitelist = 2; - const regex_blacklist = 3; +if (!class_exists('ListType')) { + class ListType + { + public const whitelist = 0; + public const blacklist = 1; + public const regex_whitelist = 2; + public const regex_blacklist = 3; } } diff --git a/scripts/pi-hole/php/debug.php b/scripts/pi-hole/php/debug.php index eb50ef60..a994feee 100644 --- a/scripts/pi-hole/php/debug.php +++ b/scripts/pi-hole/php/debug.php @@ -1,70 +1,71 @@ '', - chr(27)."[1;32m" => '', - chr(27)."[1;33m" => '', - chr(27)."[1;34m" => '', - chr(27)."[1;35m" => '', - chr(27)."[1;36m" => '', + chr(27).'[1;91m' => '', + chr(27).'[1;32m' => '', + chr(27).'[1;33m' => '', + chr(27).'[1;34m' => '', + chr(27).'[1;35m' => '', + chr(27).'[1;36m' => '', - chr(27)."[90m" => '', - chr(27)."[91m" => '', - chr(27)."[32m" => '', - chr(27)."[33m" => '', - chr(27)."[94m" => '', - chr(27)."[95m" => '', - chr(27)."[96m" => '', + chr(27).'[90m' => '', + chr(27).'[91m' => '', + chr(27).'[32m' => '', + chr(27).'[33m' => '', + chr(27).'[94m' => '', + chr(27).'[95m' => '', + chr(27).'[96m' => '', - chr(27)."[1m" => '', - chr(27)."[4m" => '', + chr(27).'[1m' => '', + chr(27).'[4m' => '', - chr(27)."[0m" => '', + chr(27).'[0m' => '', ); $data = str_replace(array_keys($ANSIcolors), $ANSIcolors, htmlspecialchars($datatext)); - if (!isset($_GET["IE"])) { - echo "data: ".implode("\ndata: ", explode("\n", $data))."\n\n"; + if (!isset($_GET['IE'])) { + echo 'data: '.implode("\ndata: ", explode("\n", $data))."\n\n"; } else { echo $data; } } // Execute "pihole" using Web option -$command = "export TERM=dumb && sudo pihole -d -w"; +$command = 'export TERM=dumb && sudo pihole -d -w'; // Add auto-upload option -if (isset($_GET["upload"])) { - $command .= " -a"; +if (isset($_GET['upload'])) { + $command .= ' -a'; } // Execute database integrity_check -if (isset($_GET["dbcheck"])) { - $command .= " -c"; +if (isset($_GET['dbcheck'])) { + $command .= ' -c'; } -$proc = popen($command, "r"); +$proc = popen($command, 'r'); while (!feof($proc)) { echoEvent(fread($proc, 4096)); } -?> diff --git a/scripts/pi-hole/php/footer.php b/scripts/pi-hole/php/footer.php index 035209ee..29709e13 100644 --- a/scripts/pi-hole/php/footer.php +++ b/scripts/pi-hole/php/footer.php @@ -43,26 +43,26 @@