<?php

#########################################################################################################
#  MakeQ.php
#
#  Copyright (C) Softnik Technologies. All rights reserved.
#
#  Use MakeQ.php to selectively add domains to the lookup queue. Though you can use RunQ.php with the 
#  auto option to do simple domain whois refresh, MakeQ.php offers more options and supports lookups
#  other than domain whois.
#
#  Options
#
#  d    - lookup domains that haven't been looked up within the last 'd' days. Set d=0 for all domains.
#         default is 180 days. Avoid using this script for extremely frequent lookups (d=0). 
#         If you have to do it make sure that the domain list / category is small.
#  cat  - specify a category name to lookup domains that belong to that category alone.
#  l    - limit the number of domains that will be added to lookup queue to 'l'. The script may timeout
#         if you have a large domain list and this value is not set.
#  w    - specify what to lookup. Default is domain whois (dw). The other supported values are
#         dw,ipw,gpr,mx,ping,alexa,ip,http,gi
#  kill - remove all entries from the lookup queue. Can be combined with 'w' to remove only selected
#         lookup. Combine with w=all to kill all lookup queue entries.
#  ue   - Lookup all domains that have a 'past' expiry date or are nearing expiry (within the next 
#         'ue' days). If you specify 'ue' without a value, it will be set to 30. Maximum is 60. Other
#         options will be ignored if you specify a 'ue' value.
#
#  The 'ue' option allows you to quickly refresh the data for domains after you have renewed them. You
#  can also invoke this script from the crontab once every month.
#
#  Examples
#
#  http://example.com/wmdsed22/makeq.php?d=5&l=2000&cat=Important+Domains&w=dw
#  http://example.com/wmdsed22/makeq.php?ue=60
#
#  Example cron entry to automatically refresh (monthly) domains that are near expiry date.
#
#  0 0 1 * * wget -q -O /dev/null "http://www.example.com/wmdsed22/makeq.php?ue=30" >/dev/null 2>&1
#
#########################################################################################################

require_once(dirname(__FILE__) . "/lib/php/config.check.php");
require_once(dirname(__FILE__) . "/config.php");
require_once(dirname(__FILE__) . "/lib/php/base.php");
require_once(dirname(__FILE__) . "/lib/php/version.php");

#########################################################################################################
# Parse command line if running in CLI

if(is_cli())
	parse_str(implode('&', array_slice($argv, 1)), $_REQUEST);
	
#########################################################################################################

$verbose = false;
if(isset($_REQUEST['v']))
	$verbose = true;

#########################################################################################################

function get_cid_from_category($category)
{
	$category = trim($category);
	if($category != "")
	{
		global $db_config_category_table;
		$sql = "select CategoryID from " . $db_config_category_table . " where CategoryName = '$category'";
		$idresults = mysql_query($sql) or die ("Error reading from database");  
		$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
		if(count($row) == 1 && isset($row['CategoryID']))
			return $row['CategoryID'];
	}
	return 0;
}

#########################################################################################################

echo "<div style=\"width:960px;margin-left:auto;margin-right:auto; text-align:center; font-family:Tahoma,Arial,Verdana;\">";
echo "<h2>Lookup Queue Management</h2><hr>";

#########################################################################################################

if(isset($_REQUEST['l']))
{
	$maxdomains = intval($_REQUEST['l']);
	if($maxdomains < 1)
		$maxdomains = 8;
}
	
$maxdays = 181;
if(isset($_REQUEST['d']))
{
	$maxdays = intval($_REQUEST['d']);
	if($maxdays > 181 || $maxdays < 0)
		$maxdays = 181;
}
$maxdays--;

$luwhat = intval(LOOKUP_DOMAIN_WHOIS);
if(isset($_REQUEST['w']))
{
	$luwhat = 0;
	$luw = strtolower(trim($_REQUEST['w']));
	if($luw == "alexa")
		$luwhat = intval(LOOKUP_ALEXA_DATA);
	else if($luw == "dw")
		$luwhat = intval(LOOKUP_DOMAIN_WHOIS);
	else if($luw == "sdw")
		$luwhat = intval(LOOKUP_SEC_DOMAIN_WHOIS);
	else if($luw == "gpr")
		$luwhat = intval(LOOKUP_GOOGLE_PR);
	else if($luw == "ip")
		$luwhat = intval(LOOKUP_IP_ADDRESS);
	else if($luw == "mx")
		$luwhat = intval(LOOKUP_MX_RECORDS);
	else if($luw == "ipw")
		$luwhat = intval(LOOKUP_IP_WHOIS);
	else if($luw == "http")
		$luwhat = intval(LOOKUP_HTTP_HOMEPAGE);
	else if($luw == "ping")
		$luwhat = intval(LOOKUP_PING_RESPONSE);
	else if($luw == "ssl")
		$luwhat = intval(LOOKUP_SSL_CERTS);
	else if($luw == "dns")
		$luwhat = intval(LOOKUP_SUB_DOMAINS);
	else if($luw == "gi")
		$luwhat = intval(LOOKUP_GOOGLE_INDEX);
}

#########################################################################################################

function add_to_queue($sid, $what=LOOKUP_DOMAIN_WHOIS, $ri=0)
{
	// echo $what . "<br>";
	$added = 0;
	if($what & LOOKUP_DOMAIN_WHOIS)
	{
		if(add_to_lookup_queue($sid, LOOKUP_DOMAIN_WHOIS, $ri))
			$added++;
	}
	if($what & LOOKUP_IP_ADDRESS)
	{
		if(add_to_lookup_queue($sid, LOOKUP_IP_ADDRESS, $ri))
			$added++;
	}
	if($what & LOOKUP_GOOGLE_PR)
	{
		if(add_to_lookup_queue($sid, LOOKUP_GOOGLE_PR, $ri))
			$added++;
	}
	if($what & LOOKUP_ALEXA_DATA)
	{
		if(add_to_lookup_queue($sid, LOOKUP_ALEXA_DATA, $ri))
			$added++;
	}
	if($what & LOOKUP_MX_RECORDS)
	{
		if(add_to_lookup_queue($sid, LOOKUP_MX_RECORDS, $ri))
			$added++;
	}
	if($what & LOOKUP_HTTP_HOMEPAGE)
	{
		if(add_to_lookup_queue($sid, LOOKUP_HTTP_HOMEPAGE, $ri))
			$added++;
	}
	if($what & LOOKUP_PING_RESPONSE)
	{
		if(add_to_lookup_queue($sid, LOOKUP_PING_RESPONSE, $ri))
			$added++;
	}
	if($what & LOOKUP_GOOGLE_LINKS)
	{
		if(add_to_lookup_queue($sid, LOOKUP_GOOGLE_LINKS, $ri))
			$added++;
	}
	if($what & LOOKUP_YAHOO_LINKS)
	{
		if(add_to_lookup_queue($sid, LOOKUP_YAHOO_LINKS, $ri))
			$added++;
	}
	if($what & LOOKUP_SSL_CERTS)
	{
		if(add_to_lookup_queue($sid, LOOKUP_SSL_CERTS, $ri))
			$added++;
	}
	if($what & LOOKUP_SUB_DOMAINS)
	{
		if(add_to_lookup_queue($sid, LOOKUP_SUB_DOMAINS, $ri))
			$added++;
	}
	if($what & LOOKUP_IP_WHOIS)
	{
		if(add_to_lookup_queue($sid, LOOKUP_IP_WHOIS, $ri))
			$added++;
	}
	if($what & LOOKUP_GOOGLE_INDEX)
	{
		if(add_to_lookup_queue($sid, LOOKUP_GOOGLE_INDEX, $ri))
			$added++;
	}
	return $added;
}

#########################################################################################################

function echo_footer()
{
	echo "<hr><p style=\"font-size:80%;\">Watch My Domains Server Edition " . get_version() . ", Build: " . get_build_date() . "</p></div>";
}

#########################################################################################################

connect_to_mysql_and_select_db();

#########################################################################################################

if(isset($_REQUEST['kill']))
{
	global $db_config_lookup_queue_table;
	if(isset($_REQUEST['w']))
	{
		$luw = strtolower(trim($_REQUEST['w']));
		if($luw == "all")
			$wheresql = "";
		else
			$wheresql = " WHERE type=" . $luwhat;
		$sql = 'Delete from ' . $db_config_lookup_queue_table . $wheresql;
		$result = mysql_query( $sql ) or die("Couldn't execute your query.".mysql_error());
		if($verbose)
			echo "<p>\"" . $sql . "\"</p>";
	}
	echo_footer();
	exit;
}

#########################################################################################################

if(isset($_REQUEST['ue']))
{
	global $db_config_domain_table;
	$count = 0;
	$addcount = 0;
	
	$edays = intval($_REQUEST['ue']);
	if($edays < 1 || $edays > 60)
		$edays = 30;
	
	$sql  = "SELECT sid,domain,registry_expiry,registrar_expiry from $db_config_domain_table"; 
	$sql .= " WHERE (registry_expiry <= [TODAY+$edays])";
	$sql .= " OR (registrar_expiry <= [TODAY+$edays])";
	
	$sql = parse_custom_sql_query($sql);
	if($verbose)
		echo "<div style=\"text-align:left;\">\n<p>Using Query</p><p>\"" . $sql . "\"</p>";
	$result = mysql_query( $sql ) or die("Couldn't execute your query.".mysql_error());
	$sid_array = array();
	while($row = mysql_fetch_array($result,MYSQL_ASSOC))
	{
		$sid = $row['sid'];
		if($verbose)
			echo $row['domain'] . "<br>";
		$addcount += add_to_queue($sid, intval(LOOKUP_DOMAIN_WHOIS));
		$count++;
	}
	echo "<p>Number of Domains: " . $count . " / New Queue Entries: " . $addcount . "</p>";
	if($verbose)
		echo "</div>\n";
	
	echo_footer();
	exit;
}

#########################################################################################################

global $db_config_domain_table, $db_config_catconnection_table;
$count = 0;
$addcount = 0;

$catid = -1;
if(isset($_REQUEST['cat']))
	$catid = get_cid_from_category($_REQUEST['cat']);
	
$last_lookup_time_field = get_last_lookup_time_field($luwhat);
if($last_lookup_time_field == "")// || $last_lookup_time_field == "ssl_checked_at")
{
	echo "<p>Error: Unknown / Unsupported Lookup Type</p>";
	echo_footer();
	exit;
}

#########################################################################################################
# First add any domain that has never been looked up.

$sqlCount = "SELECT COUNT(DISTINCT a.sid) AS count from " . $db_config_domain_table . " a"; 
if($catid != -1)
	$sqlCount .= ", " . $db_config_catconnection_table . " b WHERE (a." . $last_lookup_time_field . " IS NULL OR a." . $last_lookup_time_field . " = '0000-00-00') AND (a.sid = b.sid AND b.CategoryID = $catid)";
else
	$sqlCount .= " WHERE (a." . $last_lookup_time_field . " IS NULL OR a." . $last_lookup_time_field . " = '0000-00-00')";
//echo $sqlCount . "<br>";
$countResult = mysql_query( $sqlCount ) or die("Couldn't execute your query.".mysql_error());
$dcount = mysql_fetch_array($countResult); 
if($dcount['count'] > 0)
{
	$sql = "SELECT DISTINCT a.sid from " . $db_config_domain_table . " a"; 
	if($catid != -1)
		$sql .= ", " . $db_config_catconnection_table . " b WHERE (a." . $last_lookup_time_field . " IS NULL OR a." . $last_lookup_time_field . " = '0000-00-00') AND (a.sid = b.sid AND b.CategoryID = $catid)";
	else
		$sql .= " WHERE (a." . $last_lookup_time_field . " IS NULL OR a." . $last_lookup_time_field . " = '0000-00-00')";
	if(isset($maxdomains))
		$sql .= " LIMIT 0, " . $maxdomains;
	$result = mysql_query( $sql ) or die("Couldn't execute your query.".mysql_error());
	$sid_array = array();
	while($row = mysql_fetch_array($result,MYSQL_ASSOC))
	{
		$sid = $row['sid'];
		$addcount += add_to_queue($sid, $luwhat);
		$count++;
	}
	echo "<p>" . $count . " domains were never looked up before. " . $addcount . " new queue entries were added.</p>";
}
else
	echo "<p>All domains were looked up at least once.</p>";
	
#########################################################################################################
	
if(isset($maxdomains))
{
	# add only domains within the set limit.
	$maxdomains = $maxdomains - $addcount;	
	if($maxdomains < 1)
	{
		echo_footer();
		exit;
	}
}

#########################################################################################################

$sqlCount = "SELECT COUNT(DISTINCT a.sid) AS count from " . $db_config_domain_table . " a";
if($catid != -1)
	$sqlCount .= ", " . $db_config_catconnection_table . " b WHERE a." . $last_lookup_time_field . " <= [TODAY-" . $maxdays . "] AND (a.sid = b.sid AND b.CategoryID = $catid)";
else
	$sqlCount .= " WHERE a." . $last_lookup_time_field . " <= [TODAY-" . $maxdays . "]";
$sqlCount = parse_custom_sql_query($sqlCount);
//echo $sqlCount . "<br>";
$countResult = mysql_query( $sqlCount ) or die("Couldn't execute your query.".mysql_error());
$dcount = mysql_fetch_array($countResult); 
if($dcount['count'] > 0)
{
	$sql = "SELECT DISTINCT a.sid,a.domain from " . $db_config_domain_table . " a";
	if($catid != -1)
		$sql .= ", " . $db_config_catconnection_table . " b WHERE a." . $last_lookup_time_field . " <= [TODAY-" . $maxdays . "] AND (a.sid = b.sid AND b.CategoryID = $catid)";
	else
		$sql .= " WHERE a." . $last_lookup_time_field . " <= [TODAY-" . $maxdays . "]";
	$sql .= " ORDER BY a." . $last_lookup_time_field . " ASC";
	if(isset($maxdomains))
		$sql .= " LIMIT 0, " . $maxdomains;
	$sql = parse_custom_sql_query($sql);
	if($verbose)
		echo "<p>Using Query</p><p>\"" . $sql . "\"</p>";
	$result = mysql_query( $sql ) or die("Couldn't execute your query.".mysql_error());
	$sid_array = array();
	while($row = mysql_fetch_array($result,MYSQL_ASSOC))
	{
		$sid = $row['sid'];
		$addcount += add_to_queue($sid, $luwhat);
		$count++;
	}
	echo "<hr><p>Number of Domains: " . $count . " / New Queue Entries: " . $addcount . "</p>";
}
else
	echo "<hr><p>Nothing to do.</p>";
	
#########################################################################################################
	
echo_footer();
	
#########################################################################################################

?>
	