<?php
$explode = explode('.', $_GET['host']);
$host = array_shift($explode);
$zone = implode('.', $explode);
$ip = ($_GET['ip']) ? $_GET['ip'] : $_SERVER['REMOTE_ADDR'];

function reload_zone($zone) {
        exec('/usr/sbin/rndc reload ' . $zone . ' 2>&1', $rndc);

        return $rndc;
}

function valid_ip($ip) {
        return (@gethostbyaddr($ip)) ? true : false;
}

function change_zonefile($zone, $host, $ip) {
        if(file_exists('/var/lib/named/' . $zone . '.hosts')) {
                $fp = fopen('/var/lib/named/' . $zone . '.hosts', 'r');
                $found = false; $update = false;
                while($line = fgets($fp, 1024)) {
                        $buffer = rtrim($line);
                        if(preg_match("/^" . $host . "/", $buffer)) {
                                preg_match("/([0-9]{2,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3})/", $buffer, $act_ip);
                                $update = ($act_ip[1] == $ip) ? false : true;
                                $buffer = preg_replace("/([0-9]{2,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3})/", $ip, $buffer);
                                $found = true;
                        }
                        if(preg_match("/[\t]?[0-9]{10}$/", $buffer)) {
                                $buffer = preg_replace("/[0-9]{8}([0-9]{2})$/e", date("Ymd") . "$1 + 1", $buffer);
                        }
                        $zone_file .= $buffer . "\n";
                }
                fclose($fp);
                if($update) {
                        $fp = fopen('/var/lib/named/' . $zone . '.hosts', 'w');
                        fputs($fp, $zone_file);
                        fclose($fp);
                        reload_zone($zone);
                }

                return ($found) ? true : false;
        } else {
                return false;
        }
}

header("Content-Type: text/plain");
if($host && $zone) {
        if(valid_ip($ip)) {
                echo (change_zonefile($zone, $host, $ip)) ? 'OK' : 'NOK';
        } else {
                echo 'NOK';
        }
} else {
        echo 'NOK';
}
?>
