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

$db_config_domain_table        	= $db_table_prefix . 'domains';
$db_config_category_table      	= $db_table_prefix . 'catlist';
$db_config_autoquery_table      = $db_table_prefix . 'queries';
$db_config_subdomain_table      = $db_table_prefix . 'subdomains';

$db_config_user_table			= $db_table_prefix . 'auth_users';
$db_config_auth_cataccess_table = $db_table_prefix . 'auth_domain_categories';

$db_config_catconnection_table 	= $db_table_prefix . 'catconn';
$db_config_lookup_queue_table 	= $db_table_prefix . 'luq';
$db_config_tldlist_table 		= $db_table_prefix . 'tlds';

$db_config_whoisservers_table 	= $db_table_prefix . 'whoisservers';

$db_config_customfields_table 	= $db_table_prefix . 'customfields';
$db_config_tablecolumns_table 	= $db_table_prefix . 'tablecolumns';

$db_config_last_connect_table 	= $db_table_prefix . 'last_lookups';

$db_config_inst_servers_table 	= $db_table_prefix . 'installed_servers';

$db_config_reg_alias_table 		= $db_table_prefix . 'registrar_aliases';

$db_config_data_history_table	= $db_table_prefix . 'data_history';

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

define("LOOKUP_DOMAIN_WHOIS", 		"1");
define("LOOKUP_IP_ADDRESS",			"2");
define("LOOKUP_HTTP_HOMEPAGE",		"4");
define("LOOKUP_US_TM",				"8");
define("LOOKUP_ALEXA_DATA",			"16");
define("LOOKUP_GOOGLE_PR",			"32");
define("LOOKUP_GOOGLE_LINKS",		"64");
define("LOOKUP_MX_RECORDS",			"128");
define("LOOKUP_PING_RESPONSE",		"256");
define("LOOKUP_BING_LINKS",			"512");
define("LOOKUP_YAHOO_LINKS",		"1024");
define("LOOKUP_SSL_CERTS",			"2048");
define("LOOKUP_IP_WHOIS",			"4096");
define("LOOKUP_SEC_DOMAIN_WHOIS",	"8192");
define("LOOKUP_SUB_DOMAINS",		"16384");
define("LOOKUP_GOOGLE_INDEX",		"32768");
define("LOOKUP_BING_INDEX",			"65536");
define("LOOKUP_YAHOO_INDEX",		"131072");

define("LOOKUP_MOZ_DATA",			"262144");
define("LOOKUP_ESTIBOT_DATA",		"524288");
define("LOOKUP_SIMILARWEB_DATA",	"1048576");

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

define("LUQSTAT_WAITING",		0);
define("LUQSTAT_IN_PROGRESS",	1);
define("LUQSTAT_COMPLETED",		2);
define("LUQSTAT_FAILED",		3);

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

$valid_domain_table_array		= array (	$db_config_domain_table, $db_config_category_table, $db_config_autoquery_table, 
											$db_config_catconnection_table, $db_config_lookup_queue_table, $db_config_tldlist_table, 
											$db_config_whoisservers_table, $db_config_subdomain_table,
											$db_config_customfields_table, $db_config_tablecolumns_table,
											$db_config_last_connect_table, $db_config_inst_servers_table,
											$db_config_reg_alias_table, $db_config_data_history_table
										);

$domain_table_text_fields 		= array (	'registrar', 'ip', 'registrar', 'ns1', 'ns2', 'ns3', 'ns4', 'status', 'availability',
											'registry_whois', 'registrar_whois', 
											'redirect_url', 'home_page_status', 'home_page_title', 'home_page_size', 'redirect_last_url', 'home_page_url',
											'home_page_token', 'page_token_found',
											'mx1', 'mx2', 'mx3', 'mxip1', 'mxip2', 'mxip3',
											'google_pr',
											'whois_server',
											'ping_time',
											'owner', 'organization', 'address', 'owner_country',
											'admin_email', 'tech_email', 'billing_email', 'registrant_email',
											'alexa_rank', 'alexa_links', 'google_links', 'yahoo_links',
											'notes_a', 'notes_b', 'notes_c', 'notes_d',
											'ip_whois', 'ip_net_name', 'ip_org_name', 'ip_rtech_name',
											'ip_asnumber', 'ip_asname',
											'ascii_domain', 'r_h_disp',
											'google_index_count'
										);
$domain_table_date_fields 		= array (	'registry_expiry', 'registrar_expiry', 'created_on', 'last_update');
$domain_table_datetime_fields 	= array (	'lookedup', 'ip_checked_at', 'home_page_checked_at', 'google_pr_checked_at', 
											'ping_checked_at', 'mx_checked_at', 'alexa_checked_at', 
											'google_sitepop_checked_at', 'yahoo_sitepop_checked_at',
											'ip_whois_at', 'ssl_checked_at', 'dns_checked_at',
											'google_index_checked_at'
										);
										
$subdomain_table_text_fields 	= array (	'ip', 'ssl_issued_to', 'ssl_issued_by', 
											'notes_a', 'notes_b', 'notes_c', 'notes_d',
											'record_type', 'record_value', 'ttl', 'auto_added'
										);
										
$subdomain_table_datetime_fields = array (	'ssl_valid_from', 'ssl_valid_to', 
											'ssl_checked_at', 'ip_checked_at'
										);
										
/////////////////////////////////////////////////////////////////////////////////////////////////////////
										
$global_allowed_themes 			= array(	'redmond', 'black-tie', 'smoothness', 'sunny', 'le-frog', 
											'ui-darkness', 'pepper-grinder', 'sed-start', 'flick', 'hot-sneaks'
										);
										
$chathu_poya_pids				= array( 'rISffYmvnHecaaWve2c=', 'rISfiIy6oXWhZ6jSdGeRi2l4h6Q=' );
										
/////////////////////////////////////////////////////////////////////////////////////////////////////////

require_once('postconfig.inc.php');				
require_once('datacolumns.inc.php');

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

$php_timezone_was_autoset = false;
autoset_php_timezone();
										
/////////////////////////////////////////////////////////////////////////////////////////////////////////

function get_request_variable($name, $default)
{
	if(isset($_REQUEST[$name]))
		return validate_request_data($_REQUEST[$name]);
	return $default;
}

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

function in_array_casei($needle, $haystack) 
{
    return in_array(strtolower($needle), array_map('strtolower', $haystack));
}

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

function get_numeric_request_variable($name, $default)
{
	if(isset($_REQUEST[$name]))
		return validate_request_data(intval($_REQUEST[$name]));
	return $default;
}

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

function get_indexed_request_variable($name, $default, $indexarray)
{
	$entry = $default;
	if(isset($_REQUEST[$name]))
		$entry = validate_request_data($_REQUEST[$name]);
	if(!in_array_casei($entry, $indexarray))
		$entry = $default;
	return $entry;
}

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

function getRequestVariable($name, $default)
{
	if(isset($_REQUEST[$name]))
		return $_REQUEST[$name];
	return $default;
}


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

function getNumericRequestVariable($name, $default)
{
	if(isset($_REQUEST[$name]))
		return intval($_REQUEST[$name]);
	return $default;
}

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

function getIndexedRequestVariable($name, $default, $indexarray)
{
	$entry = $default;
	if(isset($_REQUEST[$name]))
		$entry = $_REQUEST[$name];
	if(!in_array_casei($entry, $indexarray))
		$entry = $default;
	return $entry;
}

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

function is_ok_to_process_form($fname)
{
	$tname = $fname . "-ltk";
	$proc_form = false;
	if(isset($_SESSION[$tname]) && isset($_REQUEST['lgptoken']))
	{
		if($_SESSION[$tname] == $_REQUEST['lgptoken'])
			$proc_form = true;
	}
	return $proc_form;
}

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

function echo_form_token($fname)
{
	$tname = $fname . "-ltk";
	$_SESSION[$tname] = md5(uniqid(rand(), true));
	echo $_SESSION[$tname];
}

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

function is_cli()
{
    if( defined('STDIN') )
    {
        return true;
    }
     
    if( empty($_SERVER['REMOTE_ADDR']) and !isset($_SERVER['HTTP_USER_AGENT']) and count($_SERVER['argv']) > 0) 
    {
        return true;
    } 
     
    return false;
}

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

function get_theme_name($deftheme)
{
	global $ui_theme, $global_allowed_themes;
	
	$jqtheme = $deftheme;
	if(isset($_REQUEST['theme']))
		$jqtheme = $_REQUEST['theme'];
	if($jqtheme == "")
		$jqtheme = $ui_theme;
	if(!in_array($jqtheme, $global_allowed_themes)) 
		$jqtheme = "redmond";
	return $jqtheme;
}

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

function connect_to_mysql_and_select_db()
{
	global $db_config_host, $db_config_username, $db_config_password, $db_config_database;
	
	$dbLink = mysql_connect($db_config_host, $db_config_username, $db_config_password)
	or die("Connection Error: " . mysql_error());
	mysql_query("SET NAMES 'utf8'");
	mysql_select_db($db_config_database) or die("Error conecting to db.");
}

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

function get_last_lookup_time_field($lookup_type)
{
	switch($lookup_type)
	{
		case LOOKUP_DOMAIN_WHOIS:
			return "lookedup";
		case LOOKUP_IP_ADDRESS:
			return "ip_checked_at";
		case LOOKUP_HTTP_HOMEPAGE:
			return "home_page_checked_at";
		case LOOKUP_GOOGLE_PR:
			return "google_pr_checked_at";
		case LOOKUP_PING_RESPONSE:
			return 'ping_checked_at';
		case LOOKUP_MX_RECORDS:
			return 'mx_checked_at';
		case LOOKUP_YAHOO_LINKS:
			return 'yahoo_sitepop_checked_at';
		case LOOKUP_GOOGLE_LINKS:
			return 'google_sitepop_checked_at';
		case LOOKUP_ALEXA_DATA:
			return 'alexa_checked_at';
		case LOOKUP_SSL_CERTS:
			return 'ssl_checked_at';
		case LOOKUP_IP_WHOIS:
			return 'ip_whois_at';
		case LOOKUP_SUB_DOMAINS:
			return 'dns_checked_at';
		case LOOKUP_GOOGLE_INDEX:
			return "google_index_checked_at";
		default:
			return "";
	}
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// Add Lookup
// See if a lookup is required.
// See if the lookup entry already exists.
// If No, add


function add_to_lookup_queue($sid, $lookup_type, $min_gap=1440)
{	
	global $db_config_lookup_queue_table, $db_config_domain_table, $db_config_subdomain_table;
	$last_lookup_time_field = get_last_lookup_time_field($lookup_type);
	if($last_lookup_time_field != "")
	{
		$lookup_required = true;
		$sql = "select sid," . $last_lookup_time_field . " from " . $db_config_domain_table . " where sid = $sid";
		$result = mysql_query( $sql ) or die("Couldn't execute your query.".mysql_error());
		$row = mysql_fetch_array($result, MYSQL_ASSOC);
		if($row['sid'] > 0)
		{
			$next_lookup = $row[$last_lookup_time_field];
			if($next_lookup != NULL)
			{
				$next_lookup = strtotime($next_lookup) + $min_gap*60; 
				$current_time = time();
				if($next_lookup > $current_time)
					$lookup_required = false;
			}
		}
		if($lookup_required)
		{
			if($lookup_type == LOOKUP_DOMAIN_WHOIS)
				$sql = "SELECT COUNT(*) AS count FROM $db_config_lookup_queue_table WHERE sid=$sid AND (type=1 OR type=8192)";  
			else
				$sql = "SELECT COUNT(*) AS count FROM $db_config_lookup_queue_table WHERE sid=$sid AND type='$lookup_type'";  
			$results = mysql_query( $sql ) or die("Couldn't execute your query.".mysql_error() . "<br>" . $sql);
			$existing = mysql_fetch_array($results);  
			if ($existing['count'] == 0) 
			{
				$wait = LUQSTAT_WAITING;
				$sql  = "insert into $db_config_lookup_queue_table (sid, type, status, created_on) values ($sid, $lookup_type, $wait, now());";
				$result = mysql_query($sql) or die("Couldn't execute your query.".mysql_error() . "<br>" . $sql);
				return true;
			}
		}
		
	}
	return false;
}

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

function add_sid_to_lookup_queue($sid, $what, $ri)
{
	if($what & LOOKUP_DOMAIN_WHOIS)
		add_to_lookup_queue($sid, LOOKUP_DOMAIN_WHOIS, $ri);
	if($what & LOOKUP_IP_ADDRESS)
		add_to_lookup_queue($sid, LOOKUP_IP_ADDRESS, $ri);
	if($what & LOOKUP_GOOGLE_PR)
		add_to_lookup_queue($sid, LOOKUP_GOOGLE_PR, $ri);
	if($what & LOOKUP_ALEXA_DATA)
		add_to_lookup_queue($sid, LOOKUP_ALEXA_DATA, $ri);
	if($what & LOOKUP_MX_RECORDS)
		add_to_lookup_queue($sid, LOOKUP_MX_RECORDS, $ri);
	if($what & LOOKUP_HTTP_HOMEPAGE)
		add_to_lookup_queue($sid, LOOKUP_HTTP_HOMEPAGE, $ri);
	if($what & LOOKUP_PING_RESPONSE)
		add_to_lookup_queue($sid, LOOKUP_PING_RESPONSE, $ri);
	if($what & LOOKUP_GOOGLE_LINKS)
		add_to_lookup_queue($sid, LOOKUP_GOOGLE_LINKS, $ri);
	if($what & LOOKUP_YAHOO_LINKS)
		add_to_lookup_queue($sid, LOOKUP_YAHOO_LINKS, $ri);
	if($what & LOOKUP_SSL_CERTS)
		add_to_lookup_queue($sid, LOOKUP_SSL_CERTS, $ri);
	if($what & LOOKUP_IP_WHOIS)
		add_to_lookup_queue($sid, LOOKUP_IP_WHOIS, $ri);
	if($what & LOOKUP_SUB_DOMAINS)
		add_to_lookup_queue($sid, LOOKUP_SUB_DOMAINS, $ri);
	if($what & LOOKUP_GOOGLE_INDEX)
		add_to_lookup_queue($sid, LOOKUP_GOOGLE_INDEX, $ri);
}

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

function do_default_domain_lookups($sid)
{
	global $default_lookup_types;
	
	add_sub_domains($sid);
	
	$lookups = "dw,ip";
	if(isset($default_lookup_types))
	{
		if($default_lookup_types != "")
			$lookups = $default_lookup_types;
	}
	
	$luts = explode(",", $lookups);
	foreach($luts as $luw)
	{
		$luw = strtolower(trim($luw));
		if($luw == "alexa")
			add_to_lookup_queue($sid, LOOKUP_ALEXA_DATA);
		else if($luw == "dw")
			add_to_lookup_queue($sid, LOOKUP_DOMAIN_WHOIS);
		//else if($luw == "sdw") # Secondary domain whois is automatic
		//	add_to_lookup_queue($sid, LOOKUP_SEC_DOMAIN_WHOIS);
		else if($luw == "gpr")
			add_to_lookup_queue($sid, LOOKUP_GOOGLE_PR);
		else if($luw == "ip")
			add_to_lookup_queue($sid, LOOKUP_IP_ADDRESS);
		else if($luw == "mx")
			add_to_lookup_queue($sid, LOOKUP_MX_RECORDS);
		else if($luw == "ipw")
			add_to_lookup_queue($sid, LOOKUP_IP_WHOIS);
		else if($luw == "http")
			add_to_lookup_queue($sid, LOOKUP_HTTP_HOMEPAGE);
		else if($luw == "ping")
			add_to_lookup_queue($sid, LOOKUP_PING_RESPONSE);
		else if($luw == "ssl")
			add_to_lookup_queue($sid, LOOKUP_SSL_CERTS);
		else if($luw == "dns")
			add_to_lookup_queue($sid, LOOKUP_SUB_DOMAINS);
		else if($luw == "gi")
			add_to_lookup_queue($sid, LOOKUP_GOOGLE_INDEX);
	}
}

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

function add_sub_domains($sid)
{
	global $default_sub_domains;
	
	$sddata = trim($default_sub_domains);
	if($sddata != "")
	{
		$subdomains = explode(",", $sddata);
		foreach($subdomains as $sd)
			add_sub_domain($sid, $sd);
	}
}

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

function add_sub_domain($sid, $subdomain)
{
	global $db_config_subdomain_table;
	
	$sqlAddStart = "insert into `$db_config_subdomain_table` (`subdomain`, `added_on`, `sid`) values ";
	if($subdomain != "@")
		$subdomain = cleanup_domain_name(trim($subdomain));
	if($subdomain == "")
		$subdomain = "@";
	
	$sqlCount = "SELECT COUNT(*) AS count FROM $db_config_subdomain_table WHERE subdomain='$subdomain' AND sid=$sid";  
	$results = mysql_query($sqlCount) or die ("Error reading from database");  
	$existing = mysql_fetch_array($results);  
	$insertNew = true;
	if($subdomain != "@" && $existing['count'] != 0)
		$insertNew = false;
	if ($insertNew) 
	{  
		$sqlAdd = $sqlAddStart . "('$subdomain', now(), $sid);";
		$result = mysql_query( $sqlAdd ) or die ("Error adding to database");  
	}
}

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

function add_to_registrar_whois_lookup_queue($sid, $server, $mingap=1440)
{
	global $db_config_lookup_queue_table;
	
	$lookup_type = LOOKUP_SEC_DOMAIN_WHOIS;
	$sql = "SELECT COUNT(*) AS count FROM $db_config_lookup_queue_table WHERE sid=$sid AND type='$lookup_type'";  
	$results = mysql_query( $sql ) or die("Couldn't execute your query.".mysql_error() . "<br>" . $sql);
	$existing = mysql_fetch_array($results);  
	if ($existing['count'] == 0) 
	{
		$wait = LUQSTAT_WAITING;
		$sql  = "insert into $db_config_lookup_queue_table (sid, type, status, created_on, server) values ($sid, $lookup_type, $wait, now(), '$server');";
		$result = mysql_query($sql) or die("Couldn't execute your query.".mysql_error() . "<br>" . $sql);
		return true;
	}
	return false;
}

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

function add_lu_domains_to_lookup_queue($maxdays, $maxcount=8)
{
	# Find domains that were last looked up $maxdays ago or before.
	global $db_config_domain_table;
	
	$count = 0;
	$sqlCount = "SELECT COUNT(*) AS count from " . $db_config_domain_table . " where lookedup < [TODAY-" . $maxdays . "]";
	$sqlCount = parse_custom_sql_query($sqlCount);
	$countResult = mysql_query( $sqlCount ) or die("Couldn't execute your query.".mysql_error());
	$dcount = mysql_fetch_array($countResult); 
	if($dcount['count'] > 0)
	{
		$sql = "SELECT sid,domain,lookedup from " . $db_config_domain_table . " where lookedup < [TODAY-" . $maxdays . "] ORDER BY lookedup ASC LIMIT 0, " . $maxcount;
		$sql = parse_custom_sql_query($sql);
		$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'];
			add_to_lookup_queue($sid, LOOKUP_DOMAIN_WHOIS);
			$count++;
		}
	}
	return $count;
}

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

function add_elu_domains_to_lookup_queue($maxcount=8)
{
	# Find domains that have never been looked up.
	global $db_config_domain_table;
	
	$count = 0;
	$sqlCount = "SELECT COUNT(*) AS count from " . $db_config_domain_table . " where lookedup IS NULL OR lookedup = '0000-00-00'";
	$countResult = mysql_query( $sqlCount ) or die("Couldn't execute your query.".mysql_error());
	$dcount = mysql_fetch_array($countResult); 
	if($dcount['count'] > 0)
	{
		$sql = "SELECT sid from " . $db_config_domain_table . " where lookedup IS NULL OR lookedup = '0000-00-00' LIMIT 0, " . $maxcount;
		$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'];
			add_to_lookup_queue($sid, LOOKUP_DOMAIN_WHOIS);
			$count++;
		}
	}
	return $count;
}

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

# Set Column Label and Width into DB

function log_column_label_and_width($field, $label, $width)
{
	require_once("pdo/cppdo.php");
	require_once("preferences.php");
	global $db_config_host, $db_config_database, $db_config_username, $db_config_password, $db_table_prefix;
	
	$pdo = new cpPreferences($db_table_prefix);
	$dbh = $pdo->openMySQL($db_config_host, $db_config_database, $db_config_username, $db_config_password);
	if($dbh)
	{
		$pdo->initTables();
		$pdo->setNumber(get_install_server_id() . "-fw-".$field, $width);
		$pdo->setValue(get_install_server_id() . "-fl-".$field, $label);
		return true;
	}
	return false;
}

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

# Get Column Label and Width from DB

function get_column_label_and_width($field, &$label, &$width)
{
	require_once("pdo/cppdo.php");
	require_once("preferences.php");
	global $db_config_host, $db_config_database, $db_config_username, $db_config_password, $db_table_prefix;
	
	$pdo = new cpPreferences($db_table_prefix);
	$dbh = $pdo->openMySQL($db_config_host, $db_config_database, $db_config_username, $db_config_password);
	if($dbh)
	{
		$pdo->initTables();
		$wd = $pdo->getNumber(get_install_server_id() . "-fw-".$field);
		if($wd !== false)
			$width = $wd;
		$lb = $pdo->getValue(get_install_server_id() . "-fl-".$field);
		if($lb !== false)
			$label = $lb;
		if($lb !== false && $wd !== false)
			return true;
	}
	
	return false;
}

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

function get_installed_server_status_array($sort_on_last_connect_time=true)
{
	global $db_config_inst_servers_table;	
	$data_array = array();
	$sql = "SELECT * FROM $db_config_inst_servers_table";
	if($sort_on_last_connect_time)
		$sql .= " ORDER BY last_connect_at DESC";  
	$results = mysql_query($sql);
	if($results !== false)
	{
		while($row = mysql_fetch_array($results,MYSQL_ASSOC)) 
			$data_array[] = $row;
	}
	return $data_array;
}

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

function clear_installed_server_status_table()
{
	global $db_config_inst_servers_table;
	$sql = "truncate table $db_config_inst_servers_table";
	$results = mysql_query($sql);
	return ($results === false) ? false : true;
}

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

function get_time_difference_and_icon($time_in_secs, &$sdiff, &$alert_icon, $no_panic=false)
{
	$diff = time() - $time_in_secs;
	$alert_icon = "led_green_24.png";
	if($time_in_secs == 0)
	{
		$sdiff = "Never";
		$alert_icon = "led_black_24.png";
	}
	else if($diff > 0 && $diff <= 80)
	{
		$sdiff = "$diff seconds ago";
		$alert_icon = "led_green_24.png";
	}
	else if($diff > 80 && $diff <= 300)
	{
		$sdiff =  gmdate("H:i:s", $diff) . " ago.";
		$alert_icon = "led_amber_24.png";
	}
	else if($diff > 300 && $diff <= 3600)
	{
		$sdiff =  gmdate("H:i:s", $diff) . " ago.";
		$alert_icon = "led_red_24.png";
	}
	else if($diff > 3600)
	{
		$sdiff =  gmdate("H:i:s", $diff) . " ago.";
		if($no_panic)
			$alert_icon = "led_red_24.png";
		else
			$alert_icon = "led_panic_24.png";
	}
}

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

function get_installed_server_status_table()
{
	$img_path = get_base_path() . "lib/css/img/";
	$tabletext = "<table class=\"tb-server-status\" style=\"margin-top:0;\">\n";
	$tabletext .= '<tr><th class="status">&nbsp;</th><th>Name</th><th>Host Name</th><th>Conf Name</th><th>&quot;Q&quot; Index</th><th>Ver ID</th><th>IP Address</th><th>Last Lookup</th><th class="status">&nbsp;</th><th>Last Seen</th><th class="status">&nbsp;</th></tr>';
	$darray = get_installed_server_status_array(false);
	foreach($darray as $row)
	{
		$name = "";
		$address = "";
		$last_connect = 0;
		$cnfname = "-";
		$hostname = "";
		$baseurl = "";
		$last_lookup = 0;
		$qindex = "-";
		$vindex = "-";
		
		if(isset($row['name']))
			$name = $row['name'];
		if(isset($row['address']))
			$address = $row['address'];
		if(isset($row['hostname']))
			$hostname = $row['hostname'];
		if(isset($row['cnfname']))
			$cnfname = $row['cnfname'];
		if(isset($row['last_connect_at']))
			$last_connect = $row['last_connect_at'];
		if(isset($row['last_lookup_at']))
			$last_lookup = $row['last_lookup_at'];
		if(isset($row['baseurl']))
			$baseurl = $row['baseurl'];
		if(isset($row['queue_index']))
			$qindex = $row['queue_index'];
		if(isset($row['ver_index']))
			$vindex = $row['ver_index'];
			
		$sdiff = "";
		$status_img = "led_green_24.png";
		get_time_difference_and_icon($last_connect, $sdiff, $status_img);
		
		$ldiff = "";
		$lookup_img = "led_green_24.png";
		get_time_difference_and_icon($last_lookup, $ldiff, $lookup_img, true);

		$status = "<img src=\"" . $img_path . $status_img . "\">";
		$lstatus = "<img src=\"" . $img_path . $lookup_img . "\">";
		$openurl = "<a href=\"$baseurl\" target=\"_blank\"><img src=\"" . $img_path . "open.png" . "\"></a>";
		
		if(strtolower($name) == "master")
			$tablerow = "<tr class=\"master\"><td class=\"status\">$openurl</td><td>$name</td>";
		else
			$tablerow = "<tr><td class=\"status\">$openurl</td><td>$name</td>";
		$tablerow .= "<td>$hostname</td><td>$cnfname</td><td>$qindex</td><td>$vindex</td><td>$address</td><td>$ldiff</td><td class=\"status\">$lstatus</td><td>$sdiff</td><td class=\"status\">$status</td></tr>\n";
		$tabletext .= $tablerow;
	}
	$tabletext .= "</table>\n";
	return $tabletext;
}

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

# Log the lookup time-stamp into DB

function log_queue_lookup_timestamp()
{
	global $db_config_inst_servers_table, $install_server_id;
	
	$server_name = get_install_server_id();
	$conntime = strval(time());
	
	$sqlCount = "SELECT COUNT(*) AS count FROM $db_config_inst_servers_table WHERE name='$server_name'";  
	$results = mysql_query($sqlCount) or die("Couldn't execute query.".mysql_error());
	$existing = mysql_fetch_array($results);  
	if ($existing['count'] == 0) 
	{
		$sqlAdd  = "insert into $db_config_inst_servers_table (name, last_lookup_at, last_connect_at) values ('$server_name','$conntime', '$conntime');";
		$result = mysql_query($sqlAdd) or die("Couldn't execute your query.".mysql_error() . "<br>" . $sqlAdd);
		return true;
	}
	else if($existing['count'] == 1)
	{
		$sqlAdd = "update $db_config_inst_servers_table set last_lookup_at='$conntime', last_connect_at='$conntime' where name='$server_name'";
		$result = mysql_query( $sqlAdd ) or die("Couldn't execute query.".mysql_error());
		return true;
	}
	return false;
}

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

function get_version_index($name="")
{
	if($name == "")
		$name = get_install_server_id();
	
	global $db_config_inst_servers_table;

	$sql = "select ver_index from " . $db_config_inst_servers_table . " where name = '$name'";
	$idresults = mysql_query($sql) or die ("Error reading from database");  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(isset($row['ver_index']))
		return $row['ver_index'];
		
	return false;
}

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

function get_queue_index()
{
	$name = get_install_server_id();
	if(strtolower($name) == "master" || $name == "" || strtolower($name) == "default")
		return 0;
	
	global $db_config_inst_servers_table;
	$qindex = 0;
	$sql = "select queue_index from " . $db_config_inst_servers_table . " where name = '$name'";
	$idresults = mysql_query($sql) or die ("Error reading from database");  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(isset($row['queue_index']))
		$qindex = $row['queue_index'];
		
	return $qindex;
}

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

function find_a_queue_index($name)
{
	if(strtolower($name) == "master" || $name == "" || strtolower($name) == "default")
		return 0;
		
	$qdarray[] = 0;
	$server_array = get_installed_server_status_array();
	foreach($server_array as $row)
	{
		if(isset($row['queue_index']))
		{
			$qindex = $row['queue_index'];
			if(!in_array($qindex, $qdarray))
				$qdarray[] = $qindex;
		}
	}
	
	$sanity_check = 0;
	$qdx = 1;
	while(in_array($qdx, $qdarray))
	{
		$qdx++;
		$sanity_check++;
		if($sanity_check > 10000)
			break;
	}
	return $qdx;
}

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

# Log the time-stamp into DB

function log_queue_proc_timestamp()
{
	global $db_config_inst_servers_table, $install_server_id;
	
	$server_ip = "";
	if(isset($_SERVER['SERVER_ADDR']))
		$server_ip = $_SERVER['SERVER_ADDR'];
	$server_name = get_install_server_id();
	$host_name = strtolower(php_uname('n'));
	$cnf_name = "";
	$conntime = strval(time());
	if(isset($install_server_id))
		$cnf_name = strtolower(trim($install_server_id));
	$verindex = get_build_index();
		
	$base_url = "";
	if(isset($_SERVER['SERVER_NAME']))
	{
		$scheme = "https://";
		if(empty($_SERVER['HTTPS']))
			$scheme = "http://";
		$base_url = $scheme . $_SERVER['SERVER_NAME'] . get_base_path();
	}
	
	$sqlCount = "SELECT COUNT(*) AS count FROM $db_config_inst_servers_table WHERE name='$server_name'";  
	$results = mysql_query($sqlCount) or die("Couldn't execute query.".mysql_error());
	$existing = mysql_fetch_array($results);  
	if ($existing['count'] == 0) 
	{
		$qindex = find_a_queue_index($server_name);
		$sqlAdd  = "insert into $db_config_inst_servers_table (address, name, hostname, cnfname, baseurl, last_connect_at, ver_index, queue_index) values ('$server_ip', '$server_name', '$host_name', '$cnf_name', '$base_url', '$conntime', $verindex, $qindex);";
		$result = mysql_query($sqlAdd) or die("Couldn't execute your query.".mysql_error() . "<br>" . $sqlAdd);
		return true;
	}
	else if($existing['count'] == 1)
	{
		$sqlAdd = "update $db_config_inst_servers_table set last_connect_at='$conntime', ver_index=$verindex, address='$server_ip', hostname='$host_name', cnfname='$cnf_name', baseurl='$base_url' where name='$server_name'";
		$result = mysql_query( $sqlAdd ) or die("Couldn't execute query.".mysql_error());
		return true;
	}
	return false;
}

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

# Get the time-stamp into DB

function get_queue_proc_timestamp()
{
	$tstamp = get_queue_proc_time();
	if($tstamp !== false)
		return date("Y-m-d H:i:s", $tstamp);
	return "";
}

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

# Get the time-stamp from DB

function get_queue_proc_time()
{
	$server_name = get_install_server_id();
	global $db_config_inst_servers_table;
	
	$sql = "SELECT last_connect_at FROM $db_config_inst_servers_table WHERE name='$server_name'";  
	$results = @mysql_query($sql);
	if($results === false)
	{
		connect_to_mysql_and_select_db();
		$results = mysql_query($sql);
	}
	if($results !== false)
	{
		$row = mysql_fetch_array($results, MYSQL_ASSOC);
		if(count($row) == 1 && isset($row['last_connect_at']))
		{
			if(ctype_digit($row['last_connect_at']))
				return intval($row['last_connect_at']);
		}
	}
	return false;
}

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

function get_main_logo_image()
{
	global $main_logo_image;
	if(isset($main_logo_image)) 
	{
		$main_logo_image = trim($main_logo_image);
		if($main_logo_image != "")
		{
			if (substr($main_logo_image, 0, 7) == "http://" || substr($main_logo_image, 0, 8) == "https://")
				return $main_logo_image;
			else
				return get_base_path() . $main_logo_image;
		}
	}
	return  get_base_path() . "lib/css/img/wmdsedlogo.png";
}

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

function is_any_custom_button_used()
{
	$buttons = array("home", "products", "support", "contact");
	foreach($buttons as $button)
	{
		if(get_button_url($button) != "")
			return true;
	}
	return false;
}

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

function is_read_plus_write_user()
{
	if(is_admin_user())
		return true;
	else
	{
		$userinfo = get_userinfo_from_session();
		if($userinfo !== false)
			return $userinfo['readwrite'];
	}
	return false;
}

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

function is_admin_user()
{
	if(is_user_auth_enabled() == false)
		return true;
	else
	{
		if(isset($_SESSION['user']))
		{
			$userinfo = $_SESSION['user'];
			if(is_array($userinfo))
				if($userinfo['admin'])
					return true;
		}
		return false;
	}
}

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

function is_user_auth_enabled()
{
	global $admin_user_name, $admin_password;
	if(isset($admin_user_name) && isset($admin_password))
	{
		if($admin_user_name == "demo")
			return false;
		if($admin_user_name != "" && $admin_password != "")
			return true;
	}
	return false;
}

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

function is_recaptcha_enabled()
{
	global $recaptcha_public_key, $recaptcha_private_key;
	if(isset($recaptcha_public_key) && isset($recaptcha_private_key))
	{
		if($recaptcha_public_key != "" && $recaptcha_private_key != "")
			return true;
	}
	return false;
}

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

function get_button_url($page)
{
	global $home_page_link, $product_page_link, $support_page_link, $contact_page_link; 
	if($page == "home")
	{
		if(isset($home_page_link)) 
			return $home_page_link != "" ? $home_page_link : "";
	}
	else if($page == "products")
	{
		if(isset($product_page_link)) 
			return $product_page_link != "" ? $product_page_link : "";
	}
	else if($page == "support")
	{
		if(isset($support_page_link)) 
			return $support_page_link != "" ? $support_page_link : "";
	}
	else if($page == "contact")
	{
		if(isset($contact_page_link)) 
			return $contact_page_link != "" ? $contact_page_link : "";
	}
	else if($page == "buynow")
	{
		$buy_page_link = "https://watchmy.domains/sed/buy.php?sed";
		return $buy_page_link;
	}
	else if($page == "upgpro")
	{
		$buy_page_link = "https://watchmy.domains/sed/buy-std-pro-upgrade.php?sed";
		return $buy_page_link;
	}
	else if($page == "upgstd")
	{
		$buy_page_link = "https://watchmy.domains/sed/buy.php?sed";
		return $buy_page_link;
	}
	else if($page == "vercheck")
	{
		$vercheck_page_link = "https://watchmy.domains/sed/changelog.php?sed";
		return $vercheck_page_link;
	}
	return "";
}

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

function show_link_buttons()
{
				if(is_any_custom_button_used())
				{
			?>
					&nbsp;&nbsp;
			<?php 
				}
				if(get_button_url("home") != "") 
				{
			?>
					<button id="home"></button>
			<?php
				}
				if(get_button_url("products") != "") 
				{
			?>
					<button id="products"></button>
			<?php
				}
				if(get_button_url("support") != "") 
				{
			?>
					<button id="support"></button>
			<?php
				}
				if(get_button_url("contact") != "") 
				{
			?>
					<button id="contact"></button>
			<?php
				}
}

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

function validate_request_data($field)
{ 
	if(!is_array($field))
	{
		if(ctype_digit($field))
			return $field;
		$field = mysql_real_escape_string($field);
	}
    return $field;
}

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

function getUniqueCode($length = "")
{	
	$code = md5(uniqid(rand(), true));
	if ($length != "") return substr($code, 0, $length);
	else return $code;
}

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

function isValidemail($email)
{
	return preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",trim($email));
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////
# note - will convert to lowercase.

function simple_sanitize($str)
{
	return strtolower(strip_tags(trim(($str))));
}

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

function doSessionSwipeIn()
{
	$_SESSION['timeout'] = time();
}

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

function getSessionSwipeIn()
{
	if(isset($_SESSION['timeout']))
		return $_SESSION['timeout'];
	else
		return time();
}

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

function isSessionTimedOut()
{
	global $auth_timeout_minutes;
	
	if(!isset($auth_timeout_minutes))
		$auth_timeout_minutes = 10;
	
	if($auth_timeout_minutes > 0)
	{
		if(isset($_SESSION['timeout']))
		{
			$tseconds = $auth_timeout_minutes * 60;
			if(($_SESSION['timeout'] + $tseconds) < time()) 
			{
				return true;
			}
		}
	}
	
	return false;
}

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

function check_authentication_error_quit()
{
	if(is_user_auth_enabled())
	{
		$invalid_session = false;
		if(isset($_SESSION['logged']))
		{
			if($_SESSION['logged'] == false)
				$invalid_session = true;
		}
		else
			$invalid_session = true;
			
		if($invalid_session)
		{
			header("HTTP/1.0 400 Bad Request");
			echo "Error: Invalid Session. Please login again.";
			exit;
		}
		if(isSessionTimedOut()) 
		{
			//header("HTTP/1.0 408 Request Time-out");
			// Firefox has a problem with 408.
			// Since we are in control here, we will just use 400.
			header("HTTP/1.0 400 Bad Request");
			echo "Error: Session timeout. Please login again.";
			exit;
		}
	}
}

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

function check_authentication_login()
{
	if(is_user_auth_enabled())
	{
		$login_required = false;
		$extraparam = "";
		if(!isset($_SESSION['logged']))
			$login_required = true;
		else
		{
			if($_SESSION['logged'] == false)
				$login_required = true;
		}
		if(isSessionTimedOut()) 
		{
			$login_required = true;
			$extraparam = "timeout";
		}
		if($login_required)
		{
			$newlocation = get_base_path() . "lib/php/login.php";
			if($extraparam != "")
				$newlocation .= "?r=" . $extraparam;
			header("Location: " . $newlocation);
			exit;
		}
	}
	else
	{
		if(!isset($_SESSION['logged']))
		{
			$_SESSION['logged'] = true;
			$_SESSION['id'] = $_SERVER["REMOTE_ADDR"];
		}
	}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////
# Used by the report + email scripts

function cli_mode_authentication_check()
{
	$login_check = true;
	if(isset($_REQUEST['key']))
	{	
		global $cli_auth_key_code;
		if($_REQUEST['key'] == $cli_auth_key_code && $cli_auth_key_code != "")
			$login_check = false;
	}
	if($login_check)
	{
		if(isset($_SERVER['REQUEST_URI']))
			$_SESSION['redir'] = "lib/php/custom/" . basename($_SERVER['REQUEST_URI']);
		check_authentication_login();
		if(is_admin_user() == false)
		{
			echo "<p>Administrator privileges required.</p>";
			exit;
		}
	}
}

///////////////////////////////////////////////////////////////////////////////////////////////////
# Check if a new login is required. Otherwise redirect to the main page.

function login_verify(&$login_error_message, $success_page = "")
{
	$redir = false;
	if(is_user_auth_enabled())
	{
		if(isset($_SESSION['logged']))
		{
			if(isset($_REQUEST['logout']))
				do_logout();
			else if(isSessionTimedOut()) 
			{
				do_logout();
				$login_error_message = "Your session has expired. Please login again.";
			}
			else if($_SESSION['logged'])
				$redir = true;
		}
	}
	else
		$redir = true;
	if($redir)
	{
		if($success_page == "")
		{
			if($_REQUEST['redir'])
				$success_page = get_base_path() . $_REQUEST['redir'];
			else
				$success_page = get_base_path();
		}
		header("Location: " . $success_page);
		exit;
	}
}

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

function do_login($userinfo, $permissions = null)
{
	if($permissions == null)
		$permissions = array();
		
	$_SESSION['logged'] = true;
	$_SESSION['id'] = $_SERVER["REMOTE_ADDR"];
	doSessionSwipeIn();
	
	$_SESSION['user'] = $userinfo;
	$_SESSION['permissions'] = $permissions;
	
	if(isset($_SESSION['redir']))
	{
		$redirpath = $_SESSION['redir'];
		unset($_SESSION['redir']);
		header("Location: ". get_base_path() . $redirpath);
		exit;
	}
	
	header("Location: ". get_base_path());
	exit;
}

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

function do_logout()
{
	if(isset($_SESSION['logged']))
	{
		unset($_SESSION['logged']);
		unset($_SESSION['id']);
		unset($_SESSION['timeout']);
		unset($_SESSION['user']);
		unset($_SESSION['permissions']);
		unset($_SESSION['redir']);
	}
	if(isset($_REQUEST['redir']))
		$_SESSION['redir'] = $_REQUEST['redir'];
}

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

function get_permissions_from_session()
{
	if(isset($_SESSION['permissions']))
		return $_SESSION['permissions'];
	return false;
}

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

function get_userinfo_from_session()
{
	if(isset($_SESSION['user']))
		return $_SESSION['user'];
	return false;
}

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

function generateHash($plainText, $salt = null)
{
	if ($salt === null)
	{
		$salt = substr(md5(uniqid(rand(), true)), 0, 25);
	}
	else
	{
		$salt = substr($salt, 0, 25);
	}
	
	return $salt . sha1($salt . $plainText);
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////		
		
function add_quote($string)
{
	$string = validate_request_data($string);
	str_replace("'", "''", $string);
	return "'" . $string . "'";
}

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

function fnGetSQLSearchString($searchOperation, $searchString)
{
	switch($searchOperation)
	{
		case 'eq': $searchCondition = '= '    	. add_quote($searchString); 		break;
		case 'ne': $searchCondition = '!= '   	. add_quote($searchString); 		break;
		case 'bw': $searchCondition = 'LIKE ' 	. add_quote($searchString.'%'); 	break;
		case 'ew': $searchCondition = 'LIKE '	. add_quote('%'.$searchString); 	break;
		case 'cn': $searchCondition = 'LIKE '	. add_quote('%'.$searchString.'%'); break;
		case 'lt': $searchCondition = '< '    	. add_quote($searchString); 		break;
		case 'gt': $searchCondition = '> '    	. add_quote($searchString); 		break;
		case 'le': $searchCondition = '<= '   	. add_quote($searchString); 		break;
		case 'ge': $searchCondition = '>= '   	. add_quote($searchString); 		break;
	}
	return $searchCondition;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// @param string $dt            // MySQL formatted date (like 2010-01-01) 
// @param int $year_offset        // like 2 or -2, or 5 or -5 ... 
// @param int $month_offset    // like 2 or -2, or 5 or -5 ... 
// @param in $day_offset        // like 2 or -2, or 5 or -5 ...     
// @return string             // the new MySQL formatted date (like 2009-07-01) 
function MySQLDateOffset($dt,$year_offset='',$month_offset='',$day_offset='') 
{ 
      return ($dt=='0000-00-00') ? '' : 
		date ("Y-m-d", mktime(0,0,0,substr($dt,5,2)+$month_offset,substr($dt,8,2)+ 
		$day_offset,substr($dt,0,4)+$year_offset)); 
} 

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

function wrap_quotes($str)
{
	return "'" . $str . "'";
}

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

function get_date_difference($pdate, $pivot=null)
{
	if($pivot == null)
		$pivot = time(); 
	$datediff = $pdate - $pivot;
	return floor($datediff/(60*60*24));
}

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

function is_date( $str ) 
{ 
	$stamp = strtotime( $str ); 
	if (!is_numeric($stamp)) 
		return FALSE; 
	$month = date( 'm', $stamp ); 
	$day   = date( 'd', $stamp ); 
	$year  = date( 'Y', $stamp ); 
	if (checkdate($month, $day, $year)) 
		return TRUE; 
	return FALSE; 
} 

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Look for multiple [TODAY+XX] or [TODAY-XX] and replace it with appropriate date strings (wrapped 
// in single quotes.
function parse_custom_sql_query($query)
{
	$pos = stripos($query, "[TODAY");
	while($pos !== false)
	{
		$qleft  = trim(substr($query, 0, $pos));
		$qright = trim(substr($query, $pos+6, strlen($query)-$pos-6));
		$epos   = stripos($qright, "]");
		
		if($epos !== false)
		{
			$qdays  = trim(substr($qright, 0, $epos));
			$qright = trim(substr($qright, $epos+1, strlen($qright)-$epos-1));
			
			$sign = substr($qdays, 0, 1);
			$days = trim(substr($qdays, 1, strlen($qdays)-1));
			$days = $sign == "-" ? (-$days) : $days;
			$qdate = wrap_quotes(MySQLDateOffset(date("Y-m-d"),0,0,$days));
			
			$query = $qleft . " " . $qdate . " " . $qright;
		}
		else
			break;
			
		$pos = stripos($query, "[TODAY");
	}
	return $query;
}

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

function get_query_from_aqid($aqid)
{
	global $db_config_autoquery_table, $db_config_domain_table, $db_config_catconnection_table;
	global $db_config_category_table;
	$query = "";
	$sql = "select query from " . $db_config_autoquery_table . " where id = " . $aqid;
	$idresults = mysql_query($sql) or die ("Error reading from database");  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['query']))
	{
		$query = $row['query'];
		$query = str_replace("[domains]", $db_config_domain_table, $query);
		$query = str_replace("[catconn]", $db_config_catconnection_table, $query);
		$query = str_replace("[catlist]", $db_config_category_table, $query);
		$query = str_replace("[TODAY]", wrap_quotes(date("Y-m-d")), $query);
		$query = parse_custom_sql_query($query);
	}
	return $query;
}

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

function get_whois_server_from_tld($tld)
{
	global $db_config_tldlist_table;
	$sql = "select server from " . $db_config_tldlist_table . " where tld = '$tld'";
	$idresults = mysql_query($sql) or die ("Error reading from database");  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['server']))
		return $row['server'];
	return "";
}

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

function get_raw_whois_query_from_whoisserver($server)
{
	global $db_config_whoisservers_table;
	
	$query = "";
	$sql = "select query from " . $db_config_whoisservers_table . " where server = '" . $server . "'";
	$idresults = mysql_query($sql) or die ("Error reading from database" . mysql_error());  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['query']))
	{
		$query = trim($row['query']);
	}
	return $query;
}

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

function get_whois_query_from_whoisserver($domain, $server)
{
	global $db_config_whoisservers_table;
	
	$query = $domain;
	$sql = "select query from " . $db_config_whoisservers_table . " where server = '" . $server . "'";
	$idresults = mysql_query($sql) or die ("Error reading from database" . mysql_error());  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['query']))
	{
		$squery = trim($row['query']);
		if($squery != "")
		{
			$query = $squery;
			if(strstr($query, "{d}"))
				$query = str_replace("{d}", $domain, $query);
			else
				$query .= " " . $domain;
		}
	}
	return $query;
}

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

function get_lustatus_from_whoisserver($server)
{
	global $db_config_whoisservers_table;
	
	$stop_lookups = 0;
	$sql = "select stop_lookups from " . $db_config_whoisservers_table . " where server = '" . $server . "'";
	$idresults = mysql_query($sql) or die ("Error reading from database" . mysql_error());  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['stop_lookups']))
	{
		$stop_lookups = $row['stop_lookups'];
	}
	return $stop_lookups;
}

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

function get_whois_port_from_whoisserver($server)
{
	global $db_config_whoisservers_table;
	
	$port = 0;
	$sql = "select port from " . $db_config_whoisservers_table . " where server = '" . $server . "'";
	$idresults = mysql_query($sql) or die ("Error reading from database" . mysql_error());  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['port']))
	{
		$port = $row['port'];
	}
	return $port > 0 ? $port : 43;
}

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

function get_max_connections_from_whoisserver($server)
{
	global $db_config_whoisservers_table;
	
	$maxconnections = 0;
	$sql = "select maxconnections from " . $db_config_whoisservers_table . " where server = '" . $server . "'";
	$idresults = mysql_query($sql) or die ("Error reading from database" . mysql_error());  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['maxconnections']))
	{
		$maxconnections = $row['maxconnections'];
	}
	return $maxconnections >= 1 ? $maxconnections : 1;
}

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

function get_connection_interval_from_whoisserver($server)
{
	global $db_config_whoisservers_table;
	
	if(strtolower($server) == "whois.crsnic.net")
		$defi = 0;
	else if(strtolower($server) == "whois.ausregistry.net.au")
		$defi = 183;
	else
		$defi = 10;
	
	$conninterval = -1;
	$sql = "select conninterval from " . $db_config_whoisservers_table . " where server = '" . $server . "'";
	$idresults = mysql_query($sql) or die ("Error reading from database" . mysql_error());  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['conninterval']))
	{
		$conninterval = $row['conninterval'];
	}
	return $conninterval >= 0 ? $conninterval : $defi;
}

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

function get_bannedtext_from_whoisserver($server)
{
	global $db_config_whoisservers_table;
	
	$format = "";
	$sql = "select bannedtext from " . $db_config_whoisservers_table . " where server = '" . $server . "'";
	$idresults = mysql_query($sql) or die ("Error reading from database" . mysql_error());  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['bannedtext']))
	{
		$format = trim($row['bannedtext']);
	}
	/*
	// Aug 2015, Moved to dbtables.php
	if(strtolower($server) == "whois.ausregistry.net.au" && $format == "")
		$format = "BLACKLISTED: You have exceeded the query limit";
	else if(strtolower($server) == "google.com" && $format == "")
		$format = "Our systems have detected unusual traffic from your computer network";
	*/
	return $format;
}

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

function set_bannedtext_for_whoisserver($server, $bannedtext)
{
	global $db_config_whoisservers_table;
	
	$sqlCount = "SELECT COUNT(*) AS count FROM $db_config_whoisservers_table WHERE server='$server'";  
	$results = mysql_query($sqlCount) or die("Couldn't execute query.".mysql_error());
	$existing = mysql_fetch_array($results);  
	if ($existing['count'] == 0) 
	{
		$sqlAdd  = "insert into $db_config_whoisservers_table (server, bannedtext) values ('$server', '$bannedtext');";
		$result = mysql_query($sqlAdd) or die("Couldn't execute your query.".mysql_error() . "<br>" . $sqlAdd);
		return true;
	}
	else if($existing['count'] == 1)
	{
		$sqlAdd = "update $db_config_whoisservers_table set bannedtext='$bannedtext' where server='$server'";
		$result = mysql_query( $sqlAdd ) or die("Couldn't execute query.".mysql_error());
		return true;
	}
	return false;
}

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

function get_banned_time_from_whois_server($server)
{
	global $db_config_whoisservers_table;
	
	$sql = "select last_connect_at from " . $db_config_whoisservers_table . " where server = '$server'";
	$idresults = mysql_query($sql) or die ("Error reading from database");  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['last_connect_at']))
		return $row['last_connect_at'];
	return "";
}

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

function set_stop_lookups_for_whoisserver($server, $stopstatus)
{
	global $db_config_whoisservers_table;
	
	$sqlCount = "SELECT COUNT(*) AS count FROM $db_config_whoisservers_table WHERE server='$server'";  
	$results = mysql_query($sqlCount) or die("Couldn't execute query.".mysql_error());
	$existing = mysql_fetch_array($results);  
	if ($existing['count'] == 0) 
	{
		if($stopstatus)
			$sqlAdd  = "insert into $db_config_whoisservers_table (server, stop_lookups, last_connect_at) values ('$server', $stopstatus, now());";
		else
			$sqlAdd  = "insert into $db_config_whoisservers_table (server, stop_lookups) values ('$server', $stopstatus);";
		$result = mysql_query($sqlAdd) or die("Couldn't execute your query.".mysql_error() . "<br>" . $sqlAdd);
		return true;
	}
	else if($existing['count'] == 1)
	{
		if($stopstatus)
			$sqlAdd = "update $db_config_whoisservers_table set last_connect_at=now(), stop_lookups=$stopstatus where server='$server'";
		else
			$sqlAdd = "update $db_config_whoisservers_table set last_connect_at=NULL, stop_lookups=" . $stopstatus . " where server='$server'";
		$result = mysql_query( $sqlAdd ) or die("Couldn't execute query.".mysql_error());
		return true;
	}
	return false;
}

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

function get_proxy_from_whoisserver($server)
{
	global $db_config_whoisservers_table;
	
	$format = "";
	$sql = "select proxy from " . $db_config_whoisservers_table . " where server = '" . $server . "'";
	$idresults = mysql_query($sql) or die ("Error reading from database" . mysql_error());  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['proxy']))
	{
		$format = $row['proxy'];
	}
	return trim($format);
}

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

function get_dateformat_from_whoisserver($server)
{
	global $db_config_whoisservers_table;
	
	$format = "";
	$sql = "select dateformat from " . $db_config_whoisservers_table . " where server = '" . $server . "'";
	$idresults = mysql_query($sql) or die ("Error reading from database" . mysql_error());  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['dateformat']))
	{
		$format = $row['dateformat'];
	}
	return $format;
}

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

function get_searchtoken_from_whoisserver($server)
{
	global $db_config_whoisservers_table;
	
	$format = "";
	$sql = "select searchtoken from " . $db_config_whoisservers_table . " where server = '" . $server . "'";
	$idresults = mysql_query($sql) or die ("Error reading from database" . mysql_error());  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['searchtoken']))
	{
		$format = $row['searchtoken'];
	}
	return $format;
}

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

function set_searchtoken_for_whoisserver($server, $token)
{
	global $db_config_whoisservers_table;
	
	$sqlCount = "SELECT COUNT(*) AS count FROM $db_config_whoisservers_table WHERE server='$server'";  
	$results = mysql_query($sqlCount) or die("Couldn't execute query.".mysql_error());
	$existing = mysql_fetch_array($results);  
	if ($existing['count'] == 0) 
	{
		$sqlAdd  = "insert into $db_config_whoisservers_table (server, searchtoken) values ('$server', '$token');";
		$result = mysql_query($sqlAdd) or die("Couldn't execute your query.".mysql_error() . "<br>" . $sqlAdd);
		return true;
	}
	else if($existing['count'] == 1)
	{
		$sqlAdd = "update $db_config_whoisservers_table set searchtoken='$token' where server='$server'";
		$result = mysql_query( $sqlAdd ) or die("Couldn't execute query.".mysql_error());
		return true;
	}
	return false;
}

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

function set_dateformat_for_whoisserver($server, $format)
{
	global $db_config_whoisservers_table;
	
	$sqlCount = "SELECT COUNT(*) AS count FROM $db_config_whoisservers_table WHERE server='$server'";  
	$results = mysql_query($sqlCount) or die("Couldn't execute query.".mysql_error());
	$existing = mysql_fetch_array($results);  
	if ($existing['count'] == 0) 
	{
		$sqlAdd  = "insert into $db_config_whoisservers_table (server, searchtoken, dateformat) values ('$server', '', '$format');";
		$result = mysql_query($sqlAdd) or die("Couldn't execute your query.".mysql_error() . "<br>" . $sqlAdd);
		return true;
	}
	else if($existing['count'] == 1)
	{
		$sqlAdd = "update $db_config_whoisservers_table set dateformat='$format' where server='$server'";
		$result = mysql_query( $sqlAdd ) or die("Couldn't execute query.".mysql_error());
		return true;
	}
	return false;
}

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

function get_raw_translate_data_from_whoisserver($server)
{
	global $db_config_whoisservers_table;
	
	$xlate = "";
	$sql = "select xlate from " . $db_config_whoisservers_table . " where server = '" . $server . "'";
	$idresults = mysql_query($sql) or die ("Error reading from database" . mysql_error());  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['xlate']))
	{
		$xlate = trim($row['xlate']);
	}
	return $xlate;
}

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

function set_raw_translate_data_for_whoisserver($server, $xlat)
{
	global $db_config_whoisservers_table;
	
	$sqlCount = "SELECT COUNT(*) AS count FROM $db_config_whoisservers_table WHERE server='$server'";  
	$results = mysql_query($sqlCount) or die("Couldn't execute query.".mysql_error());
	$existing = mysql_fetch_array($results);  
	if ($existing['count'] == 0) 
	{
		$sqlAdd  = "insert into $db_config_whoisservers_table (server, searchtoken, xlat) values ('$server', '', '$xlat');";
		$result = mysql_query($sqlAdd) or die("Couldn't execute your query.".mysql_error() . "<br>" . $sqlAdd);
		return true;
	}
	else if($existing['count'] == 1)
	{
		$sqlAdd = "update $db_config_whoisservers_table set xlat='$xlat' where server='$server'";
		$result = mysql_query( $sqlAdd ) or die("Couldn't execute query.".mysql_error());
		return true;
	}
	return false;
}

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

function set_whois_server_for_tld($tld, $server)
{
	global $db_config_tldlist_table;
	
	$sqlCount = "SELECT COUNT(*) AS count FROM $db_config_tldlist_table WHERE tld='$tld'";  
	$results = mysql_query($sqlCount) or die("Couldn't execute query.".mysql_error());
	$existing = mysql_fetch_array($results);  
	if ($existing['count'] == 0) 
	{
		$sqlAdd  = "insert into $db_config_tldlist_table (tld, server) values ('$tld', '$server');";
		$result = mysql_query($sqlAdd) or die("Couldn't execute your query.".mysql_error() . "<br>" . $sqlAdd);
		return true;
	}
	else if($existing['count'] == 1)
	{
		$sqlAdd = "update $db_config_tldlist_table set server='$server' where tld='$tld'";
		$result = mysql_query( $sqlAdd ) or die("Couldn't execute query.".mysql_error());
		return true;
	}
	return false;
}

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

function get_install_server_id()
{
	global $install_server_id;
	if(isset($install_server_id))
	{
		$install_id = strtolower(trim($install_server_id));
		if($install_id != "")
		{
			if($install_id == "auto")
				$install_id = strtolower(php_uname('n'));
		}
		if($install_id != "")
			return $install_id;
	}
	return "master";
}

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

function reset_last_connect_time_for_external_server($server)
{
	global $db_config_last_connect_table;
	$lusid = get_install_server_id();
	
	$sqlCount = "SELECT COUNT(*) AS count FROM $db_config_last_connect_table WHERE server='$server' AND name='$lusid'";  
	$results = mysql_query($sqlCount) or die("Couldn't execute query.".mysql_error());
	$existing = mysql_fetch_array($results);  
	if($existing['count'] == 1)
	{
		$sqlAdd = "update $db_config_last_connect_table set last_connect_at=NULL where server='$server' AND name='$lusid'";
		$result = mysql_query( $sqlAdd ) or die("Couldn't execute query.".mysql_error());
		return true;
	}
	return false;
}

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

function set_last_connect_time_for_external_server($server)
{
	global $db_config_last_connect_table;
	$lusid = get_install_server_id();
	
	$sqlCount = "SELECT COUNT(*) AS count FROM $db_config_last_connect_table WHERE server='$server' AND name='$lusid'";  
	$results = mysql_query($sqlCount) or die("Couldn't execute query.".mysql_error());
	$existing = mysql_fetch_array($results);  
	if ($existing['count'] == 0) 
	{
		$sqlAdd  = "insert into $db_config_last_connect_table (name, server, last_connect_at) values ('$lusid', '$server', now());";
		$result = mysql_query($sqlAdd) or die("Couldn't execute your query.".mysql_error() . "<br>" . $sqlAdd);
		return true;
	}
	else if($existing['count'] == 1)
	{
		$sqlAdd = "update $db_config_last_connect_table set last_connect_at=now() where server='$server' AND name='$lusid'";
		$result = mysql_query( $sqlAdd ) or die("Couldn't execute query.".mysql_error());
		return true;
	}
	return false;
}

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

function get_last_connect_time_from_external_server($server)
{
	global $db_config_last_connect_table;
	$lusid = get_install_server_id();
	
	$sql = "select last_connect_at from " . $db_config_last_connect_table . " where server = '$server' AND name='$lusid'";
	$idresults = mysql_query($sql) or die ("Error reading from database");  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['last_connect_at']))
		return $row['last_connect_at'];
	return "";
}

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

function is_ok_to_connect_to_external_server($server)
{
	$stopstatus = get_lustatus_from_whoisserver($server);
	if($stopstatus)
	{
		$banned_at = get_banned_time_from_whois_server($server);
		if($banned_at != "")
		{
			// Wait 24 hours.
			$next_connect = strtotime($banned_at) + 24*3600 + 10;
			if($next_connect < time())
			{
				set_stop_lookups_for_whoisserver($server, 0);
				$stopstatus = false;
			}
		}
	}
	
	if($stopstatus)
		return false;
		
	$last_connect_at = get_last_connect_time_from_external_server($server);
	if($last_connect_at != "")
	{
		$conninterval = get_connection_interval_from_whoisserver($server);
		$next_connect = strtotime($last_connect_at) + $conninterval;
		if($next_connect > time())
			return false;
	}
	return true;
}

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

function get_translate_array_from_whoisserver($server, &$darray)
{
	global $db_config_whoisservers_table;
	
	$rawdata = "";
	$sql = "select xlate from " . $db_config_whoisservers_table . " where server = '" . $server . "'";
	$idresults = mysql_query($sql) or die ("Error reading from database" . mysql_error());  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['xlate']))
		$rawdata = trim($row['xlate']);
		
	if($rawdata != "")
	{
		$entries = explode("\n", $rawdata);
		foreach($entries as $k => $v)
		{
			$kvpair = explode("=>", $v);
			if(count($kvpair) == 2)
			$kv = trim($kvpair[0]);
			$vv = trim($kvpair[1]);
			$kv = trim($kv, "'");
			$vv = trim($vv, "'");
			if($kv != "" && $vv != "")
				$darray[$kv] = $vv;
		}
	}
	return count($darray) > 0 ? true : false;
}

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

function get_subdomain_name_from_id($id)
{
	global $db_config_subdomain_table;
	$subdomain = "";
	$sql = "select subdomain from " . $db_config_subdomain_table . " where hid = " . $id;
	$idresults = mysql_query($sql) or die ("Error reading from database");  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['subdomain']))
		$subdomain = $row['subdomain'];
	return $subdomain;
}

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

function get_whoisdata_for_domain($domain)
{
	global $db_config_domain_table;
	$whoisdata = array();
	$sql = "select registrar_whois,registry_whois,ip_whois from " . $db_config_domain_table . " where domain = '$domain'";
	$idresults = mysql_query($sql) or die ("Error reading from database. ".mysql_error());  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(isset($row['registry_whois']))
	{
		$rwdata = $row['registry_whois'];
		//if(preg_match('!!u', $rwdata))
		//	$rwdata = utf8_decode($rwdata);
		$whoisdata['registry_whois'] = str_replace("<br>", "\n", $rwdata);
	}
	if(isset($row['registrar_whois']))
	{
		$rwdata = $row['registrar_whois'];
		//if(preg_match('!!u', $rwdata))
		//	$rwdata = utf8_decode($rwdata);
		$whoisdata['registrar_whois'] = str_replace("<br>", "\n", $rwdata);
	}
	if(isset($row['ip_whois']))
	{
		$rwdata = $row['ip_whois'];
		//if(preg_match('!!u', $rwdata))
		//	$rwdata = utf8_decode($rwdata);
		$whoisdata['ip_whois'] = str_replace("<br>", "\n", $rwdata);
	}
	return $whoisdata;
}

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

function get_domain_name_from_sid($sid)
{
	global $db_config_domain_table;
	$domain = "";
	$sql = "select domain from " . $db_config_domain_table . " where sid = " . $sid;
	$idresults = mysql_query($sql) or die ("Error reading from database");  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['domain']))
		$domain = $row['domain'];
	return $domain;
}

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

function get_sid_from_domain_name($domain)
{
	global $db_config_domain_table;
	$sql = "select sid from " . $db_config_domain_table . " where domain = '$domain'";
	$idresults = mysql_query($sql) or die ("Error reading from database");  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['sid']))
		return $row['sid'];
	return 0;
}

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

function get_ip_from_domain_name($domain)
{
	global $db_config_domain_table;
	$sql = "select ip from " . $db_config_domain_table . " where domain = '$domain'";
	$idresults = mysql_query($sql) or die ("Error reading from database");  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['ip']))
		return $row['ip'];
	return "";
}

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

function get_registrar_whois_server_from_domain_name($domain)
{
	global $db_config_domain_table;
	$sql = "select whois_server from " . $db_config_domain_table . " where domain = '$domain'";
	$idresults = mysql_query($sql) or die ("Error reading from database");  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['whois_server']))
		return $row['whois_server'];
	return "";
}

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

function get_text_field_from_domain_name($domain, $field)
{
	global $db_config_domain_table;
	$sql = "select $field from " . $db_config_domain_table . " where domain = '$domain'";
	$idresults = mysql_query($sql) or die ("Error reading from database");  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row[$field]))
		return $row[$field];
	return "";
}

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

function get_hid_from_subdomain($subdomain)
{
	global $db_config_subdomain_table;
	$sql = "select sid from " . $db_config_subdomain_table . " where subdomain = '$subdomain'";
	$idresults = mysql_query($sql) or die ("Error reading from database");  
	$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
	if(count($row) == 1 && isset($row['hid']))
		return $row['hid'];
	return 0;
}

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

function get_catid_from_category_name($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;
}

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

function rename_category($CategoryID, $CategoryName)
{
	global $db_config_category_table;
	
	$CategoryName = trim(strip_tags($CategoryName));
	if($CategoryName == "")
		return false;
	
	$sqlCount = "SELECT COUNT(*) AS count FROM $db_config_category_table WHERE CategoryName='$CategoryName'";  
	$results = mysql_query($sqlCount) or die("Couldn't execute query.".mysql_error());
	$existing = mysql_fetch_array($results);  
	if ($existing['count'] == 0) 
	{
		$sqlAdd = "update $db_config_category_table set CategoryName='$CategoryName' where CategoryID=$CategoryID";
		$result = mysql_query( $sqlAdd ) or die("Couldn't execute query.".mysql_error());
		return true;
	}
	return false;
}

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

function reset_domain_table($domain)
{
	global $db_config_domain_table, $db_resettable_domain_columns;
	
	$sql = 'update ' . $db_config_domain_table . ' set ';
	foreach($db_resettable_domain_columns as $cname)
		$sql .= "$cname = NULL,";
	$sql = trim($sql, ",");
	$sql .= " where domain = '" . $domain . "'";
	
	$result = mysql_query( $sql );
	if(!$result)
	{
		//$msg = "Couldn't execute your query. " . mysql_error() . "\n";
		//echo $msg;
	}
}

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

function is_data_history_enabled($what)
{
	global $enable_data_history;
	if(isset($enable_data_history))
	{
		$parts = explode(",", $enable_data_history);
		if(count($parts))
		{
			if(in_array($what, $parts))
				return true;
		}
	}
	return false;
}

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

function update_data_history($domain, $ftype, $fval)
{
	$value = intval($fval);
	$ftype = intval($ftype);
	$domain = trim(validate_request_data($domain));
	$domain = trim($domain,chr(0xC2).chr(0xA0)); 
	
	global $db_config_data_history_table;
	$sql = "insert into $db_config_data_history_table (domain, ftype, fvalue, lookedup_at) values ('$domain', '$ftype', '$value', now())";
	$result = mysql_query( $sql );
	if(!$result)
	{
		echo $value . "<br>";
		echo mysql_error();
		return false;
	}
	return true;
}

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

function update_domain_table($darray, $domain, $manualedit=0)
{
	global $db_config_domain_table, $domain_table_text_fields, $domain_table_datetime_fields, $domain_table_date_fields;
	
	$sql = 'update ' . $db_config_domain_table . ' set ';
		
	$updateArray = array();
	
	foreach($darray as $key=>$uvalue) 
	{
		$value = trim(validate_request_data($uvalue));
		$value = trim($value,chr(0xC2).chr(0xA0)); 
		
		if($key == 'id' || $key == 'domain')
			continue;
		else if(in_array($key, $domain_table_text_fields))
		{
			if($key == 'address' || $key == 'owner' || $key == 'organization')
			{
				if(preg_match('!!u', $value) === false)
					$value = utf8_encode($value);
				if(strlen($value) > 255)
					$value = substr($value, 0, 254);
			}
			$updateArray[$key] = "`$key`" . '=' . "'" . $value . "'"; 
		}
		else if(in_array($key, $domain_table_date_fields))
		{
			if(strlen($value) < 6)
				$updateArray[$key] = "`$key`" . "=NULL"; 
			else if(is_date($value) === true)
			{
				$dateval = strtotime($value);
				$updateArray[$key] = "`$key`" . '=' . "'" . date("Y-m-d", $dateval) . "'"; 
			}
		}
		else if(in_array($key, $domain_table_datetime_fields))
		{
			if(strlen($value) < 12)
				$updateArray[$key] = "`$key`" . "=NULL"; 
			else if(is_date($value) === true)
			{
				$dateval = strtotime($value);
				$updateArray[$key] = "`$key`" . '=' . "'" . date("Y-m-d H:i:s", $dateval) . "'"; 
			}
		}
	}
	$sql .= implode(',',$updateArray);
	if($manualedit)
		$sql .= ',edited=1,manual_edited_at=NOW()';
	$sql .= " where domain = '" . $domain . "'";
	
	if(count($updateArray) || $manualedit)
	{
		$result = mysql_query( $sql );
		if(!$result)
		{
			//$msg = "Couldn't execute your query. " . mysql_error() . "\n";
			//echo $msg;
			//logToFile("php.log", $msg);
		}
	}
}

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

function update_subdomain_table($darray, $host, $domain, $manualedit=0)
{
	global $db_config_domain_table, $domain_table_text_fields, $domain_table_datetime_fields, $domain_table_date_fields, $db_config_subdomain_table;
	global $subdomain_table_text_fields, $subdomain_table_datetime_fields;
	
	$did = get_sid_from_domain_name($domain);
	
	$sql = 'update ' . $db_config_subdomain_table . ' set ';
		
	$updateArray = array();
	
	foreach($darray as $key=>$uvalue) 
	{
		$value = trim(validate_request_data($uvalue));
		$value = trim($value,chr(0xC2).chr(0xA0)); 
		
		if($key == 'id' || $key == 'domain' || $key == 'subdomain' || $key == 'hid' || $key == 'sid')
			continue;
		else if($key == 'ttl')
		{
			if($value == "")
				$updateArray[$key] = $key . '=' . "NULL"; 
			else 
				$updateArray[$key] = $key . '=' . intval($value); 
		}
		else if(in_array($key, $subdomain_table_text_fields))
		{
			$updateArray[$key] = $key . '=' . "'" . $value . "'"; 
		}
		else if(in_array($key, $subdomain_table_datetime_fields))
		{
			if(strlen($value) < 12)
				$updateArray[$key] = $key . "=NULL"; 
			else if(is_date($value) === true)
			{
				$dateval = strtotime($value);
				$updateArray[$key] = $key . '=' . "'" . date("Y-m-d H:i:s", $dateval) . "'"; 
			}
		}
	}
	$sql .= implode(',',$updateArray);
	if($manualedit)
		$sql .= ',edited=1,manual_edited_at=NOW()';
		
	// Find the actual ID
	if(isset($darray['id']))
		$sql .= " where hid = " . intval($darray['id']) . " AND sid = " . $did;
	else 
		$sql .= " where subdomain = '" . $host . "' AND sid = " . $did;
	
	if(count($updateArray) || $manualedit)
	{
		$result = mysql_query( $sql );
		if(!$result)
		{
			//$msg = "Couldn't execute your query. " . mysql_error() . "\n";
			//logToFile("php.log", $msg);
		}
	}
}

function ioncube_loader_version_array () 
{
	if ( function_exists('ioncube_loader_iversion') ) {
		// Mmmrr
		$ioncube_loader_iversion = ioncube_loader_iversion();
		$ioncube_loader_version_major = (int)substr($ioncube_loader_iversion,0,1);
		$ioncube_loader_version_minor = (int)substr($ioncube_loader_iversion,1,2);
		$ioncube_loader_version_revision = (int)substr($ioncube_loader_iversion,3,2);
		$ioncube_loader_version = "$ioncube_loader_version_major.$ioncube_loader_version_minor.$ioncube_loader_version_revision";
	} else {
		$ioncube_loader_version = ioncube_loader_version();
		$ioncube_loader_version_major = (int)substr($ioncube_loader_version,0,1);
		$ioncube_loader_version_minor = (int)substr($ioncube_loader_version,2,1);
	}
	return array('version'=>$ioncube_loader_version, 'major'=>$ioncube_loader_version_major, 'minor'=>$ioncube_loader_version_minor);
}

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

function check_ioncube_loader()
{
	if ( extension_loaded('ionCube Loader') ) 
	{
		 $ioncube_loader_version = ioncube_loader_version_array();
		 return $ioncube_loader_version['version'];
	}
	else
		return "Error";
}

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

function get_base_path()
{
	$basepath = $_SERVER['PHP_SELF'];
	$pieces = explode("/", $basepath);
	if(count($pieces) > 1)
		unset($pieces[count($pieces)-1]);
	$basepath = implode("/", $pieces);
	$basepath = str_ireplace("/lib/php/custom", "", $basepath);
	$basepath = str_ireplace("/lib/php", "", $basepath);
	$basepath = str_ireplace("/tools/sales/php", "", $basepath);
	$basepath = str_ireplace("/tools/sales", "", $basepath);
	$basepath = str_ireplace("/tools", "", $basepath);
	return $basepath . "/";
}

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

function debug_out_domain_data($dataarray)
{
	global $domain_table_text_fields, $domain_table_datetime_fields, $domain_table_date_fields;
	echo "<pre>";
	foreach($dataarray as $key=>$val)
	{
		if(in_array($key, $domain_table_text_fields) || in_array($key, $domain_table_date_fields) || in_array($key, $domain_table_datetime_fields))
		{
			if($key != "registrar_whois" && $key != "registry_whois" && $key != "ip_whois")
				echo "[" . $key . "] => " . $val . "\r\n";
		}
	}
	if(isset($dataarray["registry_whois"]))
	{
		echo "<pre>\r\n\r\n";
		echo $dataarray["registry_whois"];
		echo "\r\n\r\n</pre>";
	}
	if(isset($dataarray["registrar_whois"]))
	{
		echo "<pre>\r\n\r\n";
		echo $dataarray["registrar_whois"];
		echo "\r\n\r\n</pre>";
	}
	if(isset($dataarray["ip_whois"]))
	{
		echo "<pre>\r\n\r\n";
		echo $dataarray["ip_whois"];
		echo "\r\n\r\n</pre>";
	}
}

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

function wmdsed_hexTobin($data) 
{ 
    $len = strlen($data); 
    return pack("H" . $len, $data); 
} 

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

function logToFile($filename, $msg)
{ 
	$fd = fopen($filename, "a");
	fwrite($fd, $msg);
	fclose($fd);
}

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

function logRequestData()
{
	$timestamp = strftime("%c",time());
	$ldata = "\n--" . $timestamp . "--\n";
	foreach ($_REQUEST as $key=>$value) 
	{
		$ldata .= $key . " - " . $value . "\n";
	}
	logToFile("php.log", $ldata);
}

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

function cleanup_domain_name($domain)
{
	$ascii_domain = idn_convert($domain);
	$url = idn_reconvert($ascii_domain);
	# idn_convert returns domain in lowercase.
	
	if ( substr($url, 0, 11) == 'http://www.')  { $url = substr($url, 11); }
	if ( substr($url, 0, 12) == 'https://www.') { $url = substr($url, 12); }
	if ( substr($url, 0, 7) == 'http://')  { $url = substr($url, 7); }
	if ( substr($url, 0, 8) == 'https://') { $url = substr($url, 8); }
	if ( strpos($url, '/') !== false) 
	{
		$ex = explode('/', $url);
		$url = $ex[0];
	}
	return trim(strip_tags($url));
}

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

function get_string_between($string, $start, $end, $includetokens=false)
{
    $string = " ".$string;
    $ini = strpos($string,$start);
    if ($ini == 0) return "";
	if(!$includetokens)
		$ini += strlen($start);
    $len = strpos($string,$end,$ini) - $ini;
	if($includetokens)
		$len += strlen($end);
    return substr($string,$ini,$len);
}

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

function autoset_php_timezone()
{
	$php_timezone = date_default_timezone_get();
	$phptzones = array($php_timezone,'');
	global $db_config_host, $db_config_username, $db_config_password, $db_config_database;
	global $php_timezone_was_autoset;
	
	$dbLink = @mysql_connect($db_config_host, $db_config_username, $db_config_password);
	if ($dbLink !== false) 
	{
		if(mysql_select_db($db_config_database))
		{
			$idresults = @mysql_query("select NOW() as CT");
			if($idresults !== false)
			{
				$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
				if(isset($row['CT']))
				{
					$mysql_time = $row['CT'];
					$phptime = date("Y-m-d H:i:s");
					if($mysql_time != "" && $phptime != "")
					{
						$gmdiff = strtotime($mysql_time) - strtotime(gmdate("Y-m-d H:i:s"));
						$mysqltimezone  = timezone_name_from_abbr("", $gmdiff, false);
						if($mysqltimezone !== false)
						{
							$tdiff = strtotime($phptime) - strtotime($mysql_time);
							if(abs($tdiff) > 1) // || ($php_timezone != $mysqltimezone && $mysqltimezone != ""))
							{
								date_default_timezone_set($mysqltimezone);
								$phptzones[1] = $mysqltimezone;
								$php_timezone_was_autoset = true;
							}
						}
					}
				}
			}
		}
		mysql_close($dbLink);
	}
	return $phptzones;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Oct 2013

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

function set_tablecolumns_for_displaygroup($dgroup, $entry)
{
	global $db_config_tablecolumns_table;
	
	$sqlCount = "SELECT COUNT(*) AS count FROM $db_config_tablecolumns_table WHERE name='$dgroup'";  
	$results = mysql_query($sqlCount) or die("Couldn't execute query.".mysql_error());
	$existing = mysql_fetch_array($results);  
	if ($existing['count'] == 0) 
	{
		$sqlAdd  = "insert into $db_config_tablecolumns_table (name, entry) values ('$dgroup', '$entry');";
		$result = mysql_query($sqlAdd) or die("Couldn't execute your query.".mysql_error() . "<br>" . $sqlAdd);
		return true;
	}
	else if($existing['count'] == 1)
	{
		$sqlAdd = "update $db_config_tablecolumns_table set entry='$entry' where name='$dgroup'";
		$result = mysql_query( $sqlAdd ) or die("Couldn't execute query.".mysql_error());
		return true;
	}
	return false;
}

function SetupAllowableFields()
{
	global $db_config_customfields_table, $db_allowed_domain_columns, $domain_table_date_fields, $domain_table_datetime_fields, $domain_table_text_fields;
	
	$custom_fields = array();
	$cfieldsres = mysql_query('SELECT * FROM ' . $db_config_customfields_table);
	if($cfieldsres)
	{
		while($crow = mysql_fetch_array($cfieldsres,MYSQL_ASSOC)) 
		{
			$fieldname = strtolower(trim($crow['name']));
			$fieldname = str_replace(" ","_", $fieldname);
			$fieldtype = strtolower(trim($crow['ftype']));
			if(!in_array($fieldname, $db_allowed_domain_columns) && $fieldname != "")
				$db_allowed_domain_columns[] = $fieldname;
				
			if(stristr($fieldtype, "varchar") !== false)
			{
				if(!in_array($fieldname, $domain_table_text_fields) && $fieldname != "")
					$domain_table_text_fields[] = $fieldname;
			}
			else if(stristr($fieldtype, "bigint") !== false)
			{
				if(!in_array($fieldname, $domain_table_text_fields) && $fieldname != "")
					$domain_table_text_fields[] = $fieldname;
			}
			else if(stristr($fieldtype, "datetime") !== false)
			{
				if(!in_array($fieldname, $domain_table_datetime_fields) && $fieldname != "")
					$domain_table_datetime_fields[] = $fieldname;
			}
			else if(stristr($fieldtype, "date") !== false)
			{
				if(!in_array($fieldname, $domain_table_date_fields) && $fieldname != "")
					$domain_table_date_fields[] = $fieldname;
			}
			else
			{
				if(!in_array($fieldname, $domain_table_text_fields) && $fieldname != "")
					$domain_table_text_fields[] = $fieldname;
			}
			
			$custom_fields[] = $fieldname;
		}
	}
	
	return $custom_fields;
	//echo "<pre>";
	//print_r($domain_table_date_fields);
	//exit;
}

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

function getLabelFromFieldName($field)
{
	$label = $field;
	$label = ucwords(str_replace("_"," ", $label));
	if(strlen($label) <= 3)
		$label = strtoupper($label);
	else if(stristr($label, "mxip") !== false)
		$label = strtoupper($label);
		
	$label = str_replace("Redirect Url", "Redirect URL", $label);
	$label = str_replace("Google Pr", "Google PR", $label);
	$label = str_replace("Google Index Count", "Google Index #", $label);
	$label = str_replace("Ascii Domain", "ASCII Name", $label);
	$label = str_replace("Mx ", "MX ", $label);
	$label = str_replace("Ip ", "IP ", $label);
	$label = str_replace("Ssl ", "SSL ", $label);
	$label = str_replace("Dns ", "DNS ", $label);
	$label = str_replace("Asname", "AS Name", $label);
	$label = str_replace("Asnumber", "AS Number", $label);
	
	return $label;
}

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

function getFieldNameFromLabel($label)
{
	$field = strtolower(trim($label));
	$field = str_replace(" ","_", $field);
	return $field;
}

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

function getDefaultColumnsForGroup($dgroup)
{
	$jsDefault = "ip;notes_a;notes_b;ns1;ns2";
	if($dgroup == "custom_columns02_array")
		$jsDefault = "ip;notes_c;notes_d;ns3;ns4";
	else if($dgroup == "custom_columns01_array")
		$jsDefault = "ip;notes_a;notes_b;ns1;ns2";
	else if($dgroup == "report_columns_array")
		$jsDefault = "registry_expiry;registrar_expiry;lookedup;status;registrar";
	else if($dgroup == "date_columns_array")
		$jsDefault = "registry_expiry;registrar_expiry;created_on;last_update;lookedup";
	else if($dgroup == "http_columns_array")
		$jsDefault = "ip;home_page_url;home_page_title;home_page_status;redirect_url;home_page_checked_at";
	else if($dgroup == "registrar_columns_array")
		$jsDefault = "registrar;status;last_update;lookedup;ascii_domain";
	else if($dgroup == "network_columns_array")
		$jsDefault = "ns1;ns2;ns3;ping_time;mx1;mx2;ip";
	else if($dgroup == "sitepop_columns_array")
		$jsDefault = "google_pr;google_index_count;alexa_links;alexa_rank;ping_time;ip";
	else if($dgroup == "notes_columns_array")
		$jsDefault = "notes_a;notes_b;notes_c;notes_d;ip";
	else if($dgroup == "ipdata_columns_array")
		$jsDefault = "ip;ip_org_name;ip_net_name;ip_asnumber;ip_asname";
	return $jsDefault;
}

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

function get_real_root_folder()
{
	$base_dir =  realpath(dirname(__FILE__));
	$base_dir =  str_ireplace(DIRECTORY_SEPARATOR . "lib" . DIRECTORY_SEPARATOR . "php" . DIRECTORY_SEPARATOR . "custom", "", $base_dir);
	$base_dir =  str_ireplace(DIRECTORY_SEPARATOR . "lib" . DIRECTORY_SEPARATOR . "php", "", $base_dir);
	return $base_dir . DIRECTORY_SEPARATOR;
}

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

function get_grid_base_file_name()
{
	$ion_loader_is_old = true;
	if ( extension_loaded('ionCube Loader') ) 
	{
		$ion_status = ioncube_loader_version_array();
		$ion_version = $ion_status['version'];
		if($ion_status['major'] >= 4 && $ion_status['minor'] >= 4)
			$ion_loader_is_old = false;
	}
		
	$base_dir = get_real_root_folder();
	$grid_url_file = "stdgrid.8.3.5.3.php";
	if(file_exists($base_dir . "lib/php/datagrid.php"))
		$grid_url_file = "datagrid.php";
	else
	{
		if($ion_loader_is_old || substr(phpversion(), 0, 3) == "5.2")
			$grid_url_file = "stdgrid.7.0.5.0.php";
	}
	return $grid_url_file;
}

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

function get_favicon_name($pngf = false)
{
	$base_dir = get_real_root_folder();
	$extn = "ico";
	if($pngf)
		$extn = "png";
	if(file_exists($base_dir . "lib/css/img/myfavicon." . $extn))
		return "myfavicon." . $extn;
	else
		return "favicon." . $extn;
}

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

function GetRegistrarAliasJS()
{
	global $db_config_reg_alias_table;

	$vararray = "\t\t\tvar registrar_aliases = new Array(";
	$sql = "select name,alias from " . $db_config_reg_alias_table;
	$result = mysql_query($sql) or die ("Error reading from alias database. " . mysql_error());  
	if($result)
	{
		while($row = mysql_fetch_array($result,MYSQL_ASSOC)) 
		{
			$registrar = trim($row['name']);
			$alias = trim($row['alias']);
			$registrar = str_replace('"','\"',$registrar);
			$vararray .= '"'.$registrar.'",';
			$alias = str_replace('"','\"',$alias);
			$vararray .= '"'.$alias.'",';
		}
		$vararray = trim($vararray, ",");
		$vararray .= ")\n";
	}
	return $vararray;
}

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

function emitCustomColumnJS()
{
	global $db_config_tablecolumns_table, $db_allowed_domain_columns, $domain_table_date_fields, $domain_table_datetime_fields, $domain_table_text_fields;
	global $domain_grid_search;
	
	$tbnames[] = "custom_columns01_array";
	$tbnames[] = "custom_columns02_array";
	$tbnames[] = "date_columns_array";
	$tbnames[] = "http_columns_array";
	$tbnames[] = "registrar_columns_array";
	$tbnames[] = "network_columns_array";
	$tbnames[] = "sitepop_columns_array";
	$tbnames[] = "notes_columns_array";
	$tbnames[] = "ipdata_columns_array";
	
	$date_format = "d-M-Y";
	global $cell_date_format;
	if(isset($cell_date_format))
		$date_format = $cell_date_format;
	
	foreach($tbnames as $tbn)
		$jsDefault[] = getDefaultColumnsForGroup($tbn);
	
	$jsData = array();
	
	connect_to_mysql_and_select_db();
	
	$customfields = SetupAllowableFields();
	
	for($i = 0; $i < count($tbnames); $i++)
	{
		$jsData[$i] = "";
		$result = mysql_query('SELECT * FROM ' . $db_config_tablecolumns_table . " WHERE name = '" . $tbnames[$i] . "'");
		if($result)
		{
			while($row = mysql_fetch_array($result,MYSQL_ASSOC)) 
			{
				$entry = trim($row['entry']);
				if($entry == "")
					$entry = $jsDefault[$i];
				$jsData[$i] = "r_h_disp;domain;" . $entry;
			}
		}
		if($jsData[$i] == "")
			$jsData[$i] = "r_h_disp;domain;" . $jsDefault[$i];
	}
?>
<script type="text/javascript">
<?php
	for($i = 0; $i < count($tbnames); $i++)
	{
?>
			var <?php echo $tbnames[$i]; ?> = [
<?php
		$parts = explode(";", $jsData[$i]);
		$j = 0;
		foreach($parts as $part)
		{
			$columns[0] = $part; // Label
			$columns[1] = strtolower(trim($part)); // Field Name
			$columns[1] = str_replace(" ","_", $columns[1]);
			$columns[2] = 100; // Width
			if($columns[1] == "domain") // For the domain column, the normal default width is 170.
				$columns[2] = 170;
			$columns[0] = getLabelFromFieldName($columns[0]);
			$status = get_column_label_and_width($columns[1], $columns[0], $columns[2]);
			
			if(count($columns) == 3 && in_array($columns[1], $db_allowed_domain_columns) && $columns[1] != "")
			{
				$classname = strtolower($columns[1]);
				$classname = str_replace("_","-", $classname) . "-cell";
				
				if(strtolower($columns[1]) == "domain")
					$append = ",editable:true,editoptions:{readonly:true,size:35}";
				else if(strtolower($columns[1]) == "r_h_disp")
				{
					$append = ",editable:false,search:false,hidden:true";
					$columns[0] = "!";
					$columns[2] = 20;
				}
				else if(strtolower($columns[1]) == "page_token_found")
				{
					$append = ",editable:false,align:'center',search:false,formatter:'booleanFormatter'";
					$columns[2] = 40;
				}
				else if(strtolower($columns[1]) == "registrar")
					$append = ",editable:true,editoptions:{size:35},formatter:'registrarFormatter'";
				else if(strtolower($columns[1]) == "availability")
				{
					$append = ",editable:false,align:'center',search:false,formatter:'domAvailFormatter'";
					$columns[2] = 40;
				}
				else if(strtolower($columns[1]) == "ascii_domain")
					$append = ",editable:false";
				else if(in_array($columns[1], $domain_table_date_fields))
					$append = ",sorttype:\"date\", editable:true, formatter:'date', formatoptions:{srcformat:\"Y-m-d\",newformat:\"$date_format\"}";
				else if(in_array($columns[1], $domain_table_datetime_fields))
				{
					if(in_array($columns[1], $customfields))
						$append = ",sorttype:\"date\", editable:true, formatter:'date', formatoptions:{srcformat:\"Y-m-d H:i:s\",newformat:\"$date_format H:i:s\"}";
					else
						$append = ",sorttype:\"date\", editable:false, formatter:'date', formatoptions:{srcformat:\"Y-m-d H:i:s\",newformat:\"$date_format H:i:s\"}";
				}
				else if(in_array($columns[1], $domain_table_text_fields))
					$append = ",editable:true,editoptions:{size:35}";
					
				$append .= ", classes:\"dtcell $classname\"";
				
				echo "\t\t\t{label:";
				echo "'" . addslashes($columns[0]) . "',";
				echo "name:'" . $columns[1] . "',";
				echo "width:'" . $columns[2] . "'";
				echo $append;
				echo "}";
				if($j != (count($parts)-1))
					echo ",";
				echo "\n";
				$j++;
			}
		}
?>
			];
<?php
	}
	$grid_url_file = get_grid_base_file_name();
		
	if(!isset($domain_grid_search))
		$domain_grid_search = false;
	echo "\t\t\tvar domain_grid_search_enable = ";
	echo $domain_grid_search ? "true" : "false";
	echo ";\n";
	echo "\t\t\tvar is_an_admin_user = " . (is_admin_user() ? "true;\n" : "false;\n");
	$ar = 0;
	$access_rights = is_read_plus_write_user();
	if($access_rights !== false)
		$ar = $access_rights;
	echo "\t\t\tvar user_access_rights = " . $ar . ";\n";
	echo "\t\t\tvar grid_url_base = 'lib/php/" . $grid_url_file . "';\n";
	echo GetRegistrarAliasJS();
?>
		</script>
<?php
}

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

?>
