Created
May 20, 2023 19:25
-
-
Save Bluscream/91bfa00ca75e062f50a32df20d2cf992 to your computer and use it in GitHub Desktop.
AdguardHome HOSTS file generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
header('Content-Type: text/plain; charset=utf-8'); | |
require("../.config.php"); // contains $servers array | |
if (isset($_GET["dl"])) header('Content-Disposition: attachment; filename="hosts"'); | |
function update_keypair(/* map[string,mixed] */ $array, /* string */ $key, /* string */ $value) { | |
if (!isset($array[$key])) { | |
$array[$key] = array($value); | |
} else { | |
if (!in_array($value, $array[$key])) { | |
$array[$key][] = $value; | |
} | |
} | |
return $array; | |
} | |
$rewrites = json_decode(file_get_contents($servers[0]."/rewrite/list")); | |
$hosts = array(); | |
foreach ($rewrites as $rewrite) { | |
$key = trim($rewrite->answer); | |
if(filter_var($key, FILTER_VALIDATE_IP) === false) { | |
continue; | |
$key = "# " . $key; | |
} | |
$value = trim($rewrite->domain); | |
if (!preg_match('/^[a-z0-9.\*_\-]+$/i', $value)) continue; | |
if (filter_var($value, FILTER_VALIDATE_IP) === true) continue; | |
$hosts = update_keypair($hosts, $key, $value); | |
} | |
$date = date('Y-m-d H:i:s'); | |
$separator = str_repeat('#', 50); | |
printf("%s\n# ADGUARD HOME HOSTS FILE GENERATED AT %s\n%s\n", $separator, $date, $separator); | |
ksort($hosts); | |
$maxIpLength = max(array_map('strlen', array_keys($hosts))); | |
foreach ($hosts as $ip => $domains) { | |
$formattedIp = str_pad($ip, $maxIpLength, ' '); | |
asort($domains); | |
printf("%s\t%s\n", $formattedIp, implode("\t", $domains)); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment