<?php

libxml_use_internal_errors(true);
require_once('Net/PublicSuffix.php');
include_once('libDNSqual2.php');

// Allow to be run from the command line

if ( empty($_SERVER['TERM']) ) {

	if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {

		// Do the bits for checking form variables first
		if ( !empty($_POST['host']) && empty($_POST['domain']) ) {

				$_POST['domain'] = $_POST['host'];

		}

		if ( !empty($_POST['domain']) ) {

			$domain=strtolower(trim($_POST['domain']));

		}

		if ( !empty($_POST['return']) ) {

			$return=strtolower($_POST['return']);

		}

	} elseif ( $_SERVER['REQUEST_METHOD'] ) {

		if ( !empty($_GET['host']) && empty($_GET['domain']) ) {

	 		$_GET['domain'] = $_GET['host'];

		}

		if ( !empty($_GET['domain']) ) {

	 		$domain=strtolower(trim($_GET['domain']));

		}

		if ( !empty($_GET['return']) ) {

	 		$return=strtolower($_GET['return']);

		}

	}

} elseif ( !empty($argv[1]) ) {

	$domain=strtolower(trim($argv[1]) );
	$return='json';

}

if ( empty($return) || $return != 'json' ) {

	 $return='html';

}

// if return is HTML print stuff
if ( $return == 'html' ) {

	print "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
	include ("header");

	pagetop();

	print '<form action="' . $_SERVER['SCRIPT_NAME'] . '" method="POST">
	<p style="text-align:center;">
	Domain : <input name="domain" type="text" maxlength="128" size="32" />
	<br/>
	<input name="submit" type="submit" value="Check" />
	</p>
	</form>
	<p style="text-align:center;"><b>N.B.</b> The results generated by
	this tool will be recorded for research
	purposes - no other information will be saved.</p>';

}

// If there's no domain name provided just print the blurb and start
// over
if ( empty($domain) && $return == 'html' ) {

	 blurb();
	 include('DNS-qual-search');
	 include("footer");
	 exit;

} elseif ( empty($domain) ) {

	 $res['Error']="No domain given";
	 displayjson($res);
	 exit;

}


// We have a domain name is it valid
if ( !filter_var("user@$domain", FILTER_VALIDATE_EMAIL)) {

	if ( $return == 'json' ) {

		$res['Error']="Invalid domain";
		displayjson($res);
		exit;

	} else {

	 	print '<p>The domain name <b>' . $domain . '</b> appears to be invalid</p>';
	 	blurb();
	 	include('DNS-qual-search');
	 	include("footer");
	 	exit;

	}
} 

// We only do top lvel domain so make sure that's what we have
$domain=Net_PublicSuffix::registered_domain($domain);

// Set the first few variables for res
$res['dt']=date('Y-m-d');
$res['ts']=date('G:i:s');
$res['domain']="$domain";

if ( $return == 'html' ) {

	print '<hr style="width:50%;">
	<h2 style="text-align:center;">DNS Record Check for : ' . $domain;

}

// Check log files to see if we've looked it up today

$logline=getlog($domain,'');

if ( empty($logline) ) {

	// Check for NS records if it doesn't resolve then bail
	set_error_handler("warning_handler", E_WARNING);

	$myNS=dns_get_record($domain,DNS_NS);

	restore_error_handler();

	if ( empty($myNS) ) {


		if ( $return == 'html' ) {

			print '</h2>
			<p style="text-align:center;">Unable to find NS records for ' . $domain . '</p>' ;
	 		history($domain);
	 		blurb();
	 		include ('DNS-qual-search');
	 		include("footer");

		} else {

			print "Error: Unable to find NS records for $domain\n";

		}

	 	exit;

	}

} else {

	$res=parselog($logline);
	$res['Infrastructure']=explode(',',$res['Infrastructure']);
	$res['CAAissue']=explode(',',$res['CAAissue']);

}

if ( empty($logline) ) {

	$domrr=checks($domain);
	$res=array_merge($res,parsedom($domrr));
	$res['Score']= score($res);

	// Check for domain dependcies
	$dependents=dependents($domrr);
	$res['Infrastructure']=$dependents;
}

if ( !empty($dependents) ) {

	$dscore=0;
	$lowest='';

	foreach ( $dependents as $dom ) {

		unset($deprr);
		unset($deplog);
		unset($depdom);

		// check if the domain is already in the log
		$deplog=getlog($dom,1);

		if ( empty($deplog) ) {

			// Check if the domain has valid NS records
			set_error_handler("warning_handler",E_WARNING);

			$depNS=dns_get_record($dom,DNS_NS);

			restore_error_handler();

			if ( empty($depNS) ) {

				continue;

			}

			$deprr=checks($dom);
			$depdom['dt']=$res['dt'];
			$depdom['ts']=$res['ts'];
			$depdom['domain']=$dom;
			$depdom=array_merge($depdom,parsedom($deprr));
			$tscore=score($depdom);
			$depdom['Score']=$tscore;
			$depdom['Infrastructure']='';
			$depdom['Infrastructuremin']='';
			$depdom['Infrastructureavg']='';
			writelog($depdom);

		} else {

			$depdom=parselog($deplog);
			$tscore=$depdom['Score'];

		}

		$dscore = $dscore + $tscore;

		// record the lowest score
		if ( empty($lowest) || $lowest > $tscore ) {

			$lowest = $tscore;

		}
			
	}

	$res['Infrastructuremin'] = $lowest;
	$res['Infrastructureavg'] = round($dscore / count($dependents),1);

}

if ( empty($logline) ) {

	writelog($res);

}

if ( $return == 'json' ) {
	 displayjson($res);
	 exit; 
}

displayHTML($res);
history($domain);
blurb();

if ( !empty($debug) ) {
	print '<br/><hr/><p><code>';
// 	displayjson($res);
	print '</code></p>';
	print '<hr/><h4>res</h4><pre>';
	print_r($res);
	print '</pre><h4>domrr</h4><pre>';
	print_r($domrr);
	print '</pre>';
}


