#!/usr/bin/php
<?
include_once("/var/www/cacert/includes/mysql.php");

$query = "select id,domain,hash from `domains` where hash!='' and deleted=0";
$res = mysql_query($query);

while($row = mysql_fetch_assoc($res)) {
    $dom = $row['domain'];
    $hash = $row['hash'];
    $id = $row['id'];
    if ($dom && preg_match("/^([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/",$dom) && $hash)
    {
        $hash = sha1($hash);
        #if (matchTXT($dom,$hash)) { update($id);  continue; }
        #if (matchWWW($dom,$hash)) { update($id);  continue; }
        if (matchWHOIS($dom,$hash)) { update($id);  continue; }
    }

}
exit;

function matchTXT($dom,$hash)
{
    $line = trim(`dig +short TXT $dom 2>&1`);
    if ($line)
    {
        $list = explode("\n", $line);
                foreach($list as $r)
        {
            if ( $r == "\"$hash\"" ) {
                return TRUE;
            }
        }
    }
    return FALSE;
}

function matchWWW($dom,$hash)
{
    $list = array(  "http://$dom/cacert.txt",
            "https://$dom/cacert.txt",
            "http://www.$dom/cacert.txt",
            "httpis://$dom/cacert.txt");
    foreach ($list as $url)
    {
        $lines = trim(`wget --tries=1 --max-redirect=1 --quiet --read-timeout=4 -O - $url | head -c 100`);
        $res = explode("\n",$lines);
        foreach ($res as $o)
        {
            print "check row for ($hash): $o\n";
            if (preg_match("/$hash/",$o)) return TRUE;
        }
        
    }
    return FALSE;
}

function matchWHOIS($dom,$hash)
{
    $line = trim(`whois $dom`);
    $list = explode("\n", $line);
    foreach($list as $r)
    {
        if (preg_match("/$hash/",$r)) return TRUE;
    }
    return FALSE;
}

function update($id)
{
    $query="update `domains` set `hash`='',`modified`=NOW() where `id`=" . $id . " LIMIT 1";
    mysql_query($query);
}
?>
