<?php
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright 2010-2011 Softnik Technologies
// Version 0.1.11 2011-01-15
/////////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////////////
require_once('whois/include.php');
/////////////////////////////////////////////////////////////////////////////////////////////////////////

function get_domainparts_from_url($url, &$tld, &$domain, &$subdomain, &$wserver)
{
	global $db_config_tldlist_table;
	
	$domain = $url;

	$url = idn_convert($domain);
	
	$parts = parse_url($url);
	if($parts !== false)
	{
		if(isset($parts['host']))
		{
			$domain = $parts['host'];
			$domain = idn_reconvert($domain);
		}
	}
	
	$res = mysql_query("SELECT tld,server FROM " . $db_config_tldlist_table . " ORDER BY LENGTH(tld) DESC") or die('Couldn t execute query.'.mysql_error());
	while ($arr = mysql_fetch_assoc($res)) 
	{
		$lookfor = "." . $arr['tld'];
		$domaintail = mb_substr($domain, -mb_strlen($lookfor));
		//if ($domaintail == $lookfor) 
		if(!strcasecmp($domaintail, $lookfor))
		{ 
			$tld = ltrim($arr['tld'], ".");
			$domainhead = mb_substr($domain, 0, mb_strlen($domain)-strlen($tld)-1); 
			$domain_parts = explode(".", $domainhead);
			$domain = array_pop($domain_parts);
			$subdomain  = implode(".", $domain_parts);
			$wserver = $arr['server'];
			return true;
		}
    }
	return false;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

function whois_lookup_domain($domain, $whoisserver)
{
	$domain = idn_convert($domain);
	
	$proxy = get_proxy_from_whoisserver($whoisserver);
	if($proxy != "")
	{
		$turl = str_replace("{D}", $domain, $proxy);
		$data = file_get_contents($turl);
		if($data === false)
			$data = "Error - unable to connect to $turl";
		return strip_tags($data);
	}

	$query = get_whois_query(mb_strtolower($domain), $whoisserver);
	
	$m_connectiontimeout = 10;
	$m_sockettimeout = 30;

	$whoisserver = strtolower($whoisserver);
	
	$port = get_whois_port_from_whoisserver($whoisserver);
	$bannedtext = get_bannedtext_from_whoisserver($whoisserver);
	
	$data = "";
	if($query != '' && $whoisserver != '' ) 
	{
		set_last_connect_time_for_external_server($whoisserver);
		$hip = gethostbyname($whoisserver);
		$fp = @fsockopen($hip, $port, $errno, $errstr, $m_connectiontimeout);
		if( $fp )
		{
			@fputs($fp, $query."\r\n");
			@socket_set_timeout($fp, $m_sockettimeout);
			while( !@feof($fp) )
				$data .= @fread($fp, 4096);
			@fclose($fp);
		}
		else
		{
			$extramsg = "";
			if($errno == 13)
				$extramsg = "Please <b>check if SELinux is enabled</b>. ";
			$extramsg .= "You may want to see <a target=\"_blank\" href=\"https://watchmy.domains/sed/guide/troubleshooting.php\">the trouble shooting page</a>";
			$data = "Error - unable to connect to $whoisserver.\n\n$errstr.\n\n$extramsg";
		}
	}
	
	if(strlen($data) > 0 && strlen($bannedtext) > 0)
	{
		if(stristr($data, $bannedtext) !== false)
			set_stop_lookups_for_whoisserver($whoisserver, true);
	}
	
	return $data;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////
# Sort of a hack. Can fail for many second level country code domains. This is acceptable because the
# purpose of this function is to mitigate bad user inputs (www.domain.com instead of domain.com)
# as much as possible. Also, this will be used only if it is manually configured in config.php.

function get_real_domain_name($fulldomain)
{
	global $fix_host_domain_names;
	if(isset($fix_host_domain_names))
	{
		if($fix_host_domain_names)
		{
			$newdomain = str_replace("www.", "", $fulldomain);
			if(substr_count($newdomain, ".") != 0 && $newdomain != "com.au" && $newdomain != "net.au" && $newdomain != "co.uk" && $newdomain != "co.in")
				return $newdomain;
		}
	}
	return $fulldomain;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Will lookup the registrar whois server

function do_domain_registrar_whois($domain_name, $rserver, $spit_out=false)
{
	// Make sure that only actual domain is passed.
	// Things like www.domain.com will create problems.
	$fulldomain = $domain_name; //$domain . "." . $tld;
	
	// Is the server ready to allow connection?
	if(!is_ok_to_connect_to_external_server($rserver))
		return false;
	
	$ludomain = get_real_domain_name($fulldomain);
	$whois02 = whois_lookup_domain($ludomain, $rserver);
	if($whois02 == "")
	{
		$whois02 = "Whois returned an empty result!";
		global $requeue_on_empty_whois;
		if(isset($requeue_on_empty_whois))
			if($requeue_on_empty_whois)
				return false;
	}

	$data_array02 = array();
	do_whois_post2ndlookup($fulldomain, $rserver, $whois02, $data_array02);
	if(is_array($data_array02))
	{
		update_domain_table($data_array02, $fulldomain);
		if($spit_out)
		{
			debug_out_domain_data($data_array02);
		}
		return true;
	}
	else
	{
		$wlines     = explode("\n", $whois02);
		$rwdata = implode("<br>", $wlines);
		if(preg_match('!!u', $rwdata) === false)
			$rwdata = utf8_encode($rwdata);
		$data_array['registrar_whois']  = $rwdata;
		update_domain_table($data_array, $domain_name);
		return true;
	}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Will lookup the registrar whois server

function do_domain_registry_whois($domain_name, $spit_out=false)
{
	$dpcheck = get_domainparts_from_url($domain_name, $tld, $domain, $subdomain, $wserver);
	if($dpcheck === false)
	{
		$wserver = find_whois_server_from_iana($domain_name);
		if($wserver != "" && $wserver != "unknown")
			$dpcheck = true;
	}
	if($dpcheck === true)
	{
		// Make sure that only actual domain is passed.
		// Things like www.domain.com will create problems.
		$fulldomain = $domain_name; //$domain . "." . $tld;
		
		// Is the server ready to allow connection?
		if(!is_ok_to_connect_to_external_server($wserver))
			return false;
		
		$ludomain = get_real_domain_name($fulldomain);
		$whois01 = whois_lookup_domain($ludomain, $wserver);
		
		if($whois01 == "")
		{
			$whois01 = "Whois returned an empty result!";
			global $requeue_on_empty_whois;
			if(isset($requeue_on_empty_whois))
				if($requeue_on_empty_whois)
					return false;
		}
	
		$data_array01 = array();
		do_whois_postlookup($fulldomain, $wserver, $whois01, $data_array01, $deeplookup, $secserver);
		if(is_array($data_array01))
		{
			reset_domain_table($fulldomain);
			update_domain_table($data_array01, $fulldomain);
			if($spit_out)
			{
				//echo "<pre>"; print_r($data_array01); echo "</pre>";
				debug_out_domain_data($data_array01);
			}
		}
		
		if($deeplookup)
		{
			$status = do_domain_registrar_whois($domain_name, $secserver, $spit_out);
			if($status == false)
			{
				// Add the registrar lookup to the queue
				$sid = get_sid_from_domain_name($domain_name);
				add_to_registrar_whois_lookup_queue($sid, $secserver, 0);
			}
		}
		return true;
	}
	else
	{
		$whoisdata  = "\nTLD not setup\n";
		$wlines     = explode("\n", $whoisdata);
		$data_array['status']          = "Setup Error";
		$data_array['lookedup']        = date("Y-m-d H:i:s");
		$data_array['whois_server']    = "unknown";
		$data_array['registry_whois']  = implode("<br>", $wlines);
		update_domain_table($data_array, $domain_name);
		return true;
	}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

function find_whois_server_from_iana($domain_name)
{
	$wserver = "";
	$tld = $domain_name;
	$parts = explode(".", $domain_name);
	if(count($parts) > 1)
		$tld = $parts[count($parts)-1];
	$ascii_name = idn_convert($tld);
	$url = "http://www.iana.org/domains/root/db/$ascii_name.html";
	$result = @file_get_contents($url);
	if($result !== false)
	{
		$p1 = strip_tags(get_string_between($result, "<b>URL for registration services:</b>", "\n"));
		$rurl = trim($p1);
		$p2 = strip_tags(get_string_between($result, "<b>WHOIS Server:</b>", "\n"));
		$wserver = trim($p2);
	}
	if($wserver == "")
	{
		$tserver = "whois.nic." . $tld;
		$ip = gethostbyname($tserver);
		if($ip != $tserver)
			$wserver = $tserver;
	}
	if($wserver != "")
		set_whois_server_for_tld($tld, $wserver);
		
	return $wserver;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

function do_domain_whois($domain_name, $spit_out=false)
{
	$dpcheck = get_domainparts_from_url($domain_name, $tld, $domain, $subdomain, $wserver);
	if($dpcheck === false)
	{
		$wserver = find_whois_server_from_iana($domain_name);
		if($wserver != "" && $wserver != "unknown")
			$dpcheck = true;
	}
	if($dpcheck === true)
	{
		// Make sure that only actual domain is passed.
		// Things like www.domain.com will create problems.
		$fulldomain = $domain_name; //$domain . "." . $tld;
		
		$ludomain = get_real_domain_name($fulldomain);
		$whois01 = whois_lookup_domain($ludomain, $wserver);
	
		$data_array01 = array();
		do_whois_postlookup($fulldomain, $wserver, $whois01, $data_array01, $deeplookup, $secserver);
		if(is_array($data_array01))
		{
			update_domain_table($data_array01, $fulldomain);
			if($spit_out)
			{
				//echo "<pre>"; print_r($data_array01); echo "</pre>";
				debug_out_domain_data($data_array01);
			}
		}
		
		if($deeplookup)
		{
			$ludomain = get_real_domain_name($fulldomain);
			$whois02 = whois_lookup_domain($ludomain, $secserver);
			$data_array02 = array();
			do_whois_post2ndlookup($fulldomain, $secserver, $whois02, $data_array02, NULL, NULL);
			if(is_array($data_array02))
			{
				update_domain_table($data_array02, $fulldomain);
				if($spit_out)
				{
					//echo "<pre>"; print_r($data_array02); echo "</pre>";
					debug_out_domain_data($data_array02);
				}
			}
		}
	}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

function whois_lookup_ip($ip, $whoisserver, $port=43)
{
	$whoisserver = strtolower($whoisserver);
	$query = trim($ip);
	$validip = filter_var($query, FILTER_VALIDATE_IP);
	if($whoisserver == "whois.arin.net" && $validip == $query && $query != "")
		$query = "n " . $query;
	else if($whoisserver == "whois.arin.net" && $query != "")
		$query = "z " . $query;
	
	$m_connectiontimeout = 10;
	$m_sockettimeout = 30;
	
	$data = "";
	if($query != '' && $whoisserver != '' ) 
	{
		$fp = @fsockopen($whoisserver, $port, $errno, $errstr, $m_connectiontimeout);
		if( $fp )
		{
			@fputs($fp, $query."\r\n");
			@socket_set_timeout($fp, $m_sockettimeout);
			while( !@feof($fp) )
				$data .= @fread($fp, 4096);
			@fclose($fp);
		}
		else
			$data = "Error - unable to connect to $whoisserver";
	}
	
	return $data;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

function ip_whois($ip)
{
	$whoisserver = "whois.arin.net";
	$data = whois_lookup_ip($ip, $whoisserver);
	if(stristr($data, "ReferralServer:"))
	{
		$port = 43;
		$p1 = Trim(get_string_between($data, "ReferralServer:", "\n"));
		$p1 = str_replace("rwhois://", "", $p1);
		$p1 = str_replace("whois://", "", $p1);
		$s1 = strpos($p1, ":");
		if($s1 !== false)
		{
			$port = substr($p1, $s1+1);
			$p1 = substr($p1, 0, strlen($p1)-strlen($port)-1);
		}
		$whoisserver = $p1;
		$ndata = whois_lookup_ip($ip, $whoisserver, $port);
		if(strlen($ndata) > 200)
			$data = $ndata;
	}
	else if(stristr($data, "Allocated to APNIC"))
	{
		$whoisserver = "whois.apnic.net";
		$data = whois_lookup_ip($ip, $whoisserver);
	}
	else if(stristr($data, "Allocated to RIPE"))
	{
		$whoisserver = "whois.ripe.net";
		$data = whois_lookup_ip($ip, $whoisserver);
	}
	else if(stristr($data, "Allocated to AfriNIC"))
	{
		$whoisserver = "whois.afrinic.net";
		$data = whois_lookup_ip($ip, $whoisserver);
	}
	else if(stristr($data, "Allocated to LACNIC"))
	{
		$whoisserver = "whois.lacnic.net";
		$data = whois_lookup_ip($ip, $whoisserver);
	}
	else if(stristr($data, "NetHandle:"))
	{
		$handle = Trim(get_string_between($data, "NetHandle:", "\n"));
		$data = whois_lookup_ip($handle, $whoisserver);
	}
	else
	{
		$dcopy = $data;
		$netblocks = array();
		while(1)
		{
			$p1 = Trim(get_string_between($dcopy, "(NET", ")", true));
			if($p1 != "")
			{
				$netblocks[] = substr($p1, 1, strlen($p1)-2);
				$dcopy = str_replace($p1, "", $dcopy);
			}
			else
				break;
		}
		$count = count($netblocks);
		if($count)
		{
			$lookup = $netblocks[$count-1];
			$data = whois_lookup_ip($lookup, $whoisserver);
		}
	}
	$data_array = array();
	generic_ipwhois_parser($whoisserver, $data, $data_array);
	//echo "*<br><pre>"; print_r($data_array); echo "</pre>";
	return $data_array;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

function do_ip_whois($domain_name, $spit_out=false)
{
	$ip = get_ip_from_domain_name($domain_name);
	if($ip == "")
	{
		$sid = get_sid_from_domain_name($domain_name);
		if($sid > 0)
		{
			do_ip_lookup($domain_name);
			$ip = get_ip_from_domain_name($domain_name);
		}
	}
	
	if($ip != "" && $ip != "-" && $ip != "error")
	{
		$data_array = ip_whois($ip);
		if($spit_out)
		{
			debug_out_domain_data($data_array);
		}
		update_domain_table($data_array, $domain_name);
	}
	else 
	{
		if($spit_out)
			echo $ip . " " . $domain_name . "<br>";
	}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////


?>
