<?php
/*
 * AfraidIRC DNSbl API (Text Output)
 * Can be used with a .htaccess/regex module by passing [url]/([0-9a-zA-Z]+/[0-9a-zA-Z]+)/(.+/.+(?:/.+)) to api.php?p=$1&i=$2
 * Will return a HTTP Status code or HTTP 200 + a String as a reply.
 * Author: Jayden H Callahan <rails@rizon.net> for AfraidIRC
 * Co-Author: Robert Whitney <xnite@xnite.org> - adding pretty json formatted return.
 */
ob_start(); // stop any output so our header() calls dont fubar
header('Content-type: application/json'); // We will always be returning json, so that will be defined here.
require("dbfunctions.php");
$zone_file="/zone.db"; // TODO: CREATE CONFIGURATION VARIABLE FOR ZONE FILE

function isip($ip) {
    return filter_var($ip, FILTER_VALIDATE_IP);
}

function addentry($ip, $res) {
    $newline=reverse_ip($ip)." IN A 127.0.0.".$res;
    $current = file_get_contents($zone_file);
    $current = "$current\n$newline";
    $fp = fopen($zone_file, 'w');
    fwrite($fp, $current);
    fclose($fp);
}
function delentry($ip, $res) {
    $out = array();

    $delete = reverse_ip($ip)." IN A 127.0.0.".$res;

    foreach($data as $line) {
        if(trim($line) != $delete) {
            $out[] = $line;
        }
    }

    $fp = fopen($zone_file, "w+");
    flock($fp, LOCK_EX);
    foreach($out as $line) {
        fwrite($fp, $line);
    }
    flock($fp, LOCK_UN);
    fclose($fp);
}

if(is_null($_GET['p']) || is_null($_GET['i'])) {
        $reply['status']['code']='400';
        $reply['status']['err_msg']='BAD REQUEST';
        echo json_encode($reply, JSON_PRETTY_PRINT);
}


$p = explode("/", $_GET['p']);
$i = explode("/", strtolower($_GET['i']));

$reply['request']['authKey']=$p[0];
$reply['request']['authSecret']=$p[1];
$reply['request']['action']=$i[0];
$reply['request']['ip']=$i[1];
$reply['request']['reason_code']=$i[2];

if(!apikey_valid($p[0], $p[1])) {
        $reply['status']['code']='403';
        $reply['status']['err_msg']='Forbidden';
        echo json_encode($reply, JSON_PRETTY_PRINT);
        ob_end_flush();
        die;
}
