<?php
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright 2010-2011 Softnik Technologies
// Version 0.1.11 2011-01-15
// Initial Version: Anil Kumar
//
// Modified: Feb 15, 2013: SK
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////

// Nov 6, 2013
function is_ion_cube_installed_if_required()
{
	if(!file_exists(get_base_dir() . "lib/php/datagrid.php"))
	{
		$ion_status = check_ioncube_loader();
		if($ion_status == "Error")
			return false;
	}
	return true;
}
//

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

function is_wmdsed_installed(&$status, &$success)
{
	$success = true;
	
	global $db_config_host, $db_config_username, $db_config_password, $db_config_database, $valid_domain_table_array, $db_table_prefix;
	
	$dbLink = @mysql_connect($db_config_host, $db_config_username, $db_config_password);
	if(!$dbLink) 
	{
		$success = false;
		$status[] = 'Could not connect: ' . mysql_error();
	}
	else
	{
		mysql_query("SET NAMES 'utf8'");
		$db_selected = mysql_select_db($db_config_database);
		if (!$db_selected) 
		{
			$status[] = "Error: " . mysql_error();
			$success = false;
		}
	}

	if($success == true)
	{
		$dbtable_array = array();
		
		$i = 0; $found = 0;
		$sql = "SHOW TABLES FROM `$db_config_database`";
		$result = mysql_query($sql);
		if($result) 
		{
			while ($row = mysql_fetch_row($result)) 
			{
				$dbtable_array[$i++] = $row[0];
				if(in_array($row[0], $valid_domain_table_array))
					$found++;
			}
		}
		
		if($found)
		{
			if($found == count($valid_domain_table_array))
			{
				$added = add_missing_fields($status);
				if(!$added)
					$status[] = "Database is already setup!";
				return true;
			}
		}
	}
	return false;
}

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

function install_wmdsed($dbtablepath)
{
	$success = true;
	$status = array();
	
	global $db_config_host, $db_config_username, $db_config_password, $db_config_database, $valid_domain_table_array, $db_table_prefix;
	
	$dbLink = @mysql_connect($db_config_host, $db_config_username, $db_config_password);
	if(!$dbLink) 
	{
		$success = false;
		$status[] = 'Could not connect: ' . mysql_error();
	}
	else
	{
		mysql_query("SET NAMES 'utf8'");
		$db_selected = mysql_select_db($db_config_database);
		if (!$db_selected) 
		{
			$status[] = "Error: " . mysql_error();
			$success = false;
		}
	}

	if($success == true)
	{
		$dbtable_array = array();
		
		$i = 0; $found = 0;
		$sql = "SHOW TABLES FROM `$db_config_database`";
		$result = mysql_query($sql);
		if($result) 
		{
			while ($row = mysql_fetch_row($result)) 
			{
				$dbtable_array[$i++] = $row[0];
				if(in_array($row[0], $valid_domain_table_array))
					$found++;
			}
		}
		else
		{
		}
		
		if($found)
		{
			if($found == count($valid_domain_table_array))
			{
				$added = add_missing_fields($status);
				if(!$added)
					$status[] = "Database is already setup!";
				$status[] = "You should be able to <a href=" . get_base_path() . ">run the application</a> now.";
				$status[] = "If you wish to use a different set of database tables, please specify another \"db_table_prefix\" in \"config.php\" and run this script again.";
				$success = false;
			}
			else if($found > 0)
			{
				$trycount = 0;
				$successcount = 0;
				foreach($valid_domain_table_array as $key=>$val)
				{
					if(in_array($val, $dbtable_array))
						continue;
					else
					{
						$trycount++;
						if(make_db_tables($dbtablepath, $db_table_prefix, $status, $val) == true)
							$successcount++;
					}
				}
				if($trycount && $trycount == $successcount)
				{
					add_missing_fields($status);
					
					$status[] = "The database contained a partial prior installation. It was repaired.";
					$status[] = "You should be able to <a href=" . get_base_path() . ">run the application</a> now.";
					$status[] = "If you wish to use a different set of database tables, please specify another \"db_table_prefix\" in \"config.php\" and run this script again.";
					$success = false;
				}
				else
				{
					add_missing_fields($status);
					
					$status[] = "The database already contains some of the tables. This means your installation is only partially complete and there is a problem!";
					$status[] = "Please modify / clean the database or specify another \"db_table_prefix\" in 'config.php' before running this installation script.";
					$status[] = "<hr>";
					$status[] = "Please <a href=\"https://support.softnik.com/contactus/\">contact us</a> if you still have problems.";
					$success = false;
				}
			}
			
		}
		else
		{
			make_db_tables($dbtablepath, $db_table_prefix, $status);
			$temp_status = array();
			add_missing_fields($temp_status);
		}
	}
	
	// Aug 04/2013
	// start-fix
	// Temporary fix for godaddy date format.
	if(get_dateformat_from_whoisserver("whois.godaddy.com") == "ddyy")
	{
		set_dateformat_for_whoisserver("whois.godaddy.com", "auto");
		$status[] = "<hr>";
		$status[] = "Date format for whois.godaddy.com reset to 'auto'.";
	}
	// end-fix
		
	if($success == true)
	{
		$status[] = "Tables successfully created.";
		$status[] = "You should be able to <a href=" . get_base_path() . ">run the application</a> now.";
		show_success_page($status);
	}
	else
		show_error_page($status);
}

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

function make_db_tables($path, $prefix, &$status, $onetable="")
{
	$success = true;
	$handle = @fopen($path, "r"); 
	
	$process = true;
	$lookfor = "";
	if($onetable != "")
	{
		$onetable = str_replace($prefix, "", $onetable);
		if($onetable != "")
		{
			$lookfor = "DROP TABLE IF EXISTS `[[DB_PREFIX]]" . $onetable . '`';
			$process = false;
		}
	}
	
	if ($handle) 
	{ 
		$query = '';
		while (!feof($handle)) 
		{     
			$found = false;
			$text = fgets($handle, 4096);
			$text = trim($text);
			if($lookfor != "")
			{
				//echo "<pre> $text </pre>";
				if($process == false)
				{
					if(substr($text, 0, strlen($lookfor)) == $lookfor)
					{
						$process = true;
						$found = true;
					}
				}
				if($process == true && $found == false)
				{
					$nextdrop = "DROP TABLE IF EXISTS `[[DB_PREFIX]]";
					if(substr($text, 0, strlen($nextdrop)) == $nextdrop)
						$process = false;
				}
			}
			
			if($process == false)
				continue;
				
			$query .= $text;
			$last = mb_substr($text, -1, 1);
			if($last == ';')
			{      
				$query = str_replace("[[DB_PREFIX]]", $prefix, $query);
				//echo "<pre>$query \r\n</pre>";
				$result = mysql_query($query);
				if (!$result) 
				{
					$status[] = "Error: " . mysql_error();
					$success = false;
				}
				$query = '';     
			}
		} 
		fclose($handle); 
	} 
	else
	{
		$success = false;
		$status[] = "Unable to open lib/php/data/tables.sql";
	}
	return $success;
}

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

function add_missing_fields(&$status)
{
	global $db_config_domain_table, $db_config_database, $db_config_whoisservers_table, $db_config_customfields_table, $db_config_subdomain_table;
	global $db_config_lookup_queue_table, $db_config_last_connect_table, $db_config_inst_servers_table, $db_config_category_table;
	$added = 0;
	
	$utfsql = "ALTER TABLE " . $db_config_domain_table . " MODIFY domain varchar(210) COLLATE utf8_bin";
	$result = mysql_query($utfsql);
	
	$utfsql = "ALTER TABLE " . $db_config_domain_table . " MODIFY owner varchar(210)";
	$result = mysql_query($utfsql);
	
	$utfsql = "ALTER TABLE " . $db_config_lookup_queue_table . " MODIFY type int(20)";
	$result = mysql_query($utfsql);
	
	$utfsql = "ALTER TABLE " . $db_config_subdomain_table . " MODIFY subdomain varchar(210) COLLATE utf8_bin";
	$result = mysql_query($utfsql);
	
	$fields = mysql_list_fields($db_config_database, $db_config_domain_table);
	$columns = mysql_num_fields($fields);
	for ($i = 0; $i < $columns; $i++) 
	{
		$field_array[] = mysql_field_name($fields, $i);
	}
	
	$domain_table_fields = array(
		"ip_whois", 	"LONGTEXT NULL",
		"ip_whois_at", 	"datetime NULL",
		"added_on", 	"datetime NULL",
		"ip_org_name",  "varchar(255) NULL",
		"ip_net_name",  "varchar(255) NULL",
		"ip_rtech_name",  "varchar(255) NULL",
		"ip_asname",  "varchar(255) NULL",
		"ip_asnumber",  "varchar(16) NULL",
		"notes_a", "varchar(255) NULL",
		"notes_b", "varchar(255) NULL",
		"notes_c", "varchar(255) NULL",
		"notes_d", "varchar(255) NULL",
		"ascii_domain", "varchar(255) NULL",
		"registrant_email", "varchar(120) NULL",
		"r_h_disp", "tinyint(1) unsigned DEFAULT NULL",
		"ssl_checked_at", "datetime NULL",
		"dns_checked_at", "datetime NULL",
		
		"google_index_count", "bigint(20) NULL",
		"google_index_checked_at", "datetime NULL",
		"bing_index_count", "bigint(20) NULL",
		"bing_index_checked_at", "datetime NULL",
		"yahoo_index_count", "bigint(20) NULL",
		"yahoo_index_checked_at", "datetime NULL",
		
		"redirect_last_url", "varchar(120) NULL",
		"home_page_url", "varchar(120) NULL"
	);
	$count = count($domain_table_fields)/2;
	for($i = 0; $i < $count; $i++)
	{
		if (!in_array($domain_table_fields[$i*2], $field_array))
		{
			$result = mysql_query('ALTER TABLE ' . $db_config_domain_table . " ADD " . $domain_table_fields[$i*2] . " " . $domain_table_fields[$i*2+1]); 
			if($result)
			{
				$status[] = 'Added column ' . $domain_table_fields[$i*2];
				$added++;
			}
			else
				die("Couldn't execute your query.".mysql_error());
		}
	}
	
	// Nov 2013
	
	
	
	//
	
	// Oct 2013
	// Add Any Missing Custom Fields.
	$custom_fields = array();
	$cfieldsres = mysql_query('SELECT * FROM ' . $db_config_customfields_table);
	if($cfieldsres)
	{
		$i = 0;
		while($crow = mysql_fetch_array($cfieldsres,MYSQL_ASSOC)) 
		{
			$custom_fields[$i]['name'] = trim($crow['name']);
			$custom_fields[$i]['ftype'] = trim($crow['ftype']);
			$custom_fields[$i]['fdefault'] = trim($crow['fdefault']);
			$i++;
		}
	}
	$count = count($custom_fields);
	for($i = 0; $i < $count; $i++)
	{
		$fname = strtolower(trim($custom_fields[$i]['name']));
		$fname = str_replace(" ","_", $fname);
		$ftype = strtolower(trim($custom_fields[$i]['ftype']));
		if (!in_array($fname, $field_array))
		{
			if($ftype == "date")
				$ftype = "datetime";
			$fdefault = $custom_fields[$i]['fdefault'];
			if($fdefault == "")
				$fdefault = "DEFAULT NULL";
			$result = mysql_query('ALTER TABLE ' . $db_config_domain_table . " ADD `" . $fname . "` " . $ftype . " " . $fdefault); 
			if($result)
			{
				$status[] = 'Added column ' . $custom_fields[$i]['name'];
				$added++;
			}
			else
				die("Couldn't execute your query.".mysql_error());
		}
	}
	//
	// Oct 2013 - End

	unset($field_array);
	$fields = mysql_list_fields($db_config_database, $db_config_whoisservers_table);
	$columns = mysql_num_fields($fields);
	for ($i = 0; $i < $columns; $i++) 
	{
		$field_array[] = mysql_field_name($fields, $i);
	}
	$server_table_fields = array(
		"last_connect_at", "datetime NULL",
		"bannedtext", "varchar(128) NULL",
		"stop_lookups", "tinyint(1) unsigned DEFAULT NULL",
		"proxy", "varchar(255) DEFAULT NULL"
	);
	$count = count($server_table_fields)/2;
	for($i = 0; $i < $count; $i++)
	{
		if (!in_array($server_table_fields[$i*2], $field_array))
		{
			$result = mysql_query('ALTER TABLE ' . $db_config_whoisservers_table . " ADD " . $server_table_fields[$i*2] . " " . $server_table_fields[$i*2+1]); 
			if($result)
			{
				$status[] = 'Added column ' . $server_table_fields[$i*2];
				$added++;
			}
			else
				die("Couldn't execute your query.".mysql_error());
		}
	}
	
	// Dec 2013
	unset($field_array);
	$qfields = mysql_list_fields($db_config_database, $db_config_lookup_queue_table);
	$qcolumns = mysql_num_fields($qfields);
	for ($i = 0; $i < $qcolumns; $i++) 
	{
		$field_array[] = mysql_field_name($qfields, $i);
	}
	$luq_table_fields = array(
		"server", "varchar(255) NULL",
		"subid", "bigint(20) DEFAULT NULL"
	);
	$count = count($luq_table_fields)/2;
	for($i = 0; $i < $count; $i++)
	{
		if (!in_array($luq_table_fields[$i*2], $field_array))
		{
			$result = mysql_query('ALTER TABLE ' . $db_config_lookup_queue_table . " ADD " . $luq_table_fields[$i*2] . " " . $luq_table_fields[$i*2+1]); 
			if($result)
			{
				$status[] = 'Added column ' . $db_config_lookup_queue_table . "." . $luq_table_fields[$i*2];
				$added++;
			}
			else
				die("Couldn't execute your query.".mysql_error());
		}
	}
	
	// Dec 11 2013
	unset($field_array);
	$lcfields = mysql_list_fields($db_config_database, $db_config_last_connect_table);
	$lccolumns = mysql_num_fields($lcfields);
	for ($i = 0; $i < $lccolumns; $i++) 
	{
		$field_array[] = mysql_field_name($lcfields, $i);
	}
	$lc_table_fields = array(
		"stop_lookups", "tinyint(1) unsigned DEFAULT NULL"
	);
	$count = count($lc_table_fields)/2;
	for($i = 0; $i < $count; $i++)
	{
		if (!in_array($lc_table_fields[$i*2], $field_array))
		{
			$result = mysql_query('ALTER TABLE ' . $db_config_last_connect_table . " ADD " . $lc_table_fields[$i*2] . " " . $lc_table_fields[$i*2+1]); 
			if($result)
			{
				$status[] = 'Added column ' . $db_config_last_connect_table . "." . $lc_table_fields[$i*2];
				$added++;
			}
			else
				die("Couldn't execute your query.".mysql_error());
		}
	}
	
	// Jan 05 2014
	unset($field_array);
	$isfields = mysql_list_fields($db_config_database, $db_config_inst_servers_table);
	$iscolumns = mysql_num_fields($isfields);
	for ($i = 0; $i < $iscolumns; $i++) 
	{
		$field_array[] = mysql_field_name($isfields, $i);
	}
	$is_table_fields = array(
		"ver_index", "int(11) DEFAULT NULL",
		"queue_index", "int(11) DEFAULT NULL"
	);
	$count = count($is_table_fields)/2;
	for($i = 0; $i < $count; $i++)
	{
		if (!in_array($is_table_fields[$i*2], $field_array))
		{
			$result = mysql_query('ALTER TABLE ' . $db_config_inst_servers_table . " ADD " . $is_table_fields[$i*2] . " " . $is_table_fields[$i*2+1]); 
			if($result)
			{
				$status[] = 'Added column ' . $db_config_inst_servers_table . "." . $is_table_fields[$i*2];
				$added++;
			}
			else
				die("Couldn't execute your query.".mysql_error());
		}
	}
	
	// Apr 02 2014
	unset($field_array);
	$sdfields = mysql_list_fields($db_config_database, $db_config_subdomain_table);
	$sdcolumns = mysql_num_fields($sdfields);
	for ($i = 0; $i < $sdcolumns; $i++) 
	{
		$field_array[] = mysql_field_name($sdfields, $i);
	}
	$sd_table_fields = array(
		"record_type", "varchar(32) DEFAULT NULL",
		"record_value", "varchar(255) DEFAULT NULL",
		"ttl", "int(11) DEFAULT NULL",
		"auto_added", "tinyint(1) unsigned DEFAULT NULL"
	);
	
	$count = count($sd_table_fields)/2;
	for($i = 0; $i < $count; $i++)
	{
		if (!in_array($sd_table_fields[$i*2], $field_array))
		{
			$result = mysql_query('ALTER TABLE ' . $db_config_subdomain_table . " ADD " . $sd_table_fields[$i*2] . " " . $sd_table_fields[$i*2+1]); 
			if($result)
			{
				$status[] = 'Added column ' . $db_config_subdomain_table . "." . $sd_table_fields[$i*2];
				$added++;
			}
			else
				die("Couldn't execute your query.".mysql_error());
		}
	}
	
	// Feb 18 2015
	unset($field_array);
	$catfields = mysql_list_fields($db_config_database, $db_config_category_table);
	$colcount = mysql_num_fields($catfields);
	for ($i = 0; $i < $colcount; $i++) 
		$field_array[] = mysql_field_name($catfields, $i);
	$cat_table_fields = array("SortOrder", "int(11) DEFAULT NULL");
	$count = count($cat_table_fields)/2;
	for($i = 0; $i < $count; $i++)
	{
		if (!in_array($cat_table_fields[$i*2], $field_array))
		{
			$result = mysql_query('ALTER TABLE ' . $db_config_category_table . " ADD " . $cat_table_fields[$i*2] . " " . $cat_table_fields[$i*2+1]); 
			if($result)
			{
				$status[] = 'Added column ' . $db_config_category_table . "." . $cat_table_fields[$i*2];
				$added++;
			}
			else
				die("Couldn't execute your query.".mysql_error());
		}
	}
	
	// Feb 2014
	// Temporary Fix for Org Domains
	if(strtolower(get_whois_server_from_tld("org")) == "whois.publicinterestregistry.net")
		set_whois_server_for_tld("org", "whois.pir.org");
		
	// Feb 2015
	// Temporary Fix for WS Domains
	if(strtolower(get_whois_server_from_tld("ws")) == "whois.nic.ws")
		set_whois_server_for_tld("ws", "whois.website.ws");
		
	// Add New TLDs
	include("newtlds.inc.php");
	// End Fix
	
	// Aug 2015
	if(get_bannedtext_from_whoisserver("whois.networksolutions.com") == "")
		set_bannedtext_for_whoisserver("whois.networksolutions.com", "contained within a list of IP addresses that may have failed");
	if(get_bannedtext_from_whoisserver("whois.tucows.com") == "")
		set_bannedtext_for_whoisserver("whois.tucows.com", "Maximum Daily connection limit reached");
	if(get_bannedtext_from_whoisserver("whois.ausregistry.net.au") == "")
		set_bannedtext_for_whoisserver("whois.ausregistry.net.au", "BLACKLISTED: You have exceeded the query limit");
	if(get_bannedtext_from_whoisserver("google.com") == "")
		set_bannedtext_for_whoisserver("google.com", "Our systems have detected unusual traffic from your computer network");
	
	return $added;
}

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

?>
