<?php
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright 2010-2013 Softnik Technologies
// Version 2013-09-26
// Initial Version: SK
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////

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

require_once("config.check.php");
require_once("../../config.php");
require_once("base.php");
require_once("idn.php");
require_once("whois.php");

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

# Ajax script. 
# Check authentication and quit with http error code if auth fails.

session_start();
check_authentication_error_quit();
doSessionSwipeIn();

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

if(is_user_auth_enabled())
{
	$access_rights = 1;
	$userinfo = get_userinfo_from_session();
	if(!is_admin_user_or_is_basic_version())
	{
		$access_rights = $userinfo['readwrite'];
	}
	if($access_rights == 0 || $access_rights == 2) // 2 = Only Edit
	{
		header("HTTP/1.0 403 Forbidden");
		echo "Permission Denied.";
		exit;
	}
}

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

$responce = new stdClass();
$responce->status = "ok";
$responce->msg = "";

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

function is_admin_user_or_is_basic_version()
{
	return is_admin_user();
}

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

if(!empty($_FILES['csv_file']['name'])) 
{
	doFileUploadProc();
}
else if(isset($_REQUEST['demo']))
{
	echo "<head><meta http-equiv=\"Content-Language\" content=\"en\">";
	echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head>\n";
	echo "<pre>";
	uploadCSVData("data/sampledata.csv");
	exit;
}
else
{
	$responce->msg = "Nothing To Do! Please select a file to upload.";
	$responce->status = "Error";
}

echo json_encode($responce);
exit;

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

function doFileUploadProc()
{
	global $responce;
	
	if($_FILES['csv_file']['error'] > 0) 
	{
		$responce->msg = 'Error ' . $_FILES['csv_file']['error'];
		$responce->status = "Error";
		return;
	}
	if(empty($_FILES['csv_file']['name'])) 
	{
		$responce->msg = 'No file sent.';
		$responce->status = "Error";
		return;
	}

	$tmp = $_FILES['csv_file']['tmp_name'];

	if(is_uploaded_file($tmp))
	{		
		$responce->msg = "<p>File Name: " . $_FILES["csv_file"]["name"] . "<br>";
		$responce->msg .= "File Type: " . $_FILES["csv_file"]["type"] . "<br>";
		
		$sep = ",";
		if(isset($_REQUEST['csv_sep']))
			$sep = $_REQUEST['csv_sep'];
			
		$size = $_FILES["csv_file"]["size"] / 1024;
		$displaysep = "TAB";
		if($sep == ";")
			$displaysep = "Semi Colon";
		else if($sep == ",")
			$displaysep = "Comma";
		
		$responce->msg .= "File Size: " . round($size, 3) . " KB<br>";
		$responce->msg .= "Separator: " . $displaysep . "</p>";
		
		$f = fopen($tmp, 'r');
		$first_line = fgets($f);
		fclose($f);
		if (mb_check_encoding($first_line, 'UTF-8')) 
			uploadCSVData($tmp, $sep);	
		else
		{
			$responce->msg .= "<ul class=\"bullets\"><li class=\"lierr\">The file is not UTF-8 or ANSI Encoded.</li></ul>";	
			$responce->status = "Error";
		}
	}
	else 
		echo 'Upload failed !';
}

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

function uploadCSVData($filename, $sep=",")
{
	global $db_allowed_domain_columns, $responce;
	
	if($sep == "t")
		$sep = "\t";
	if($sep != "," && $sep != ";" && $sep != "\t")
		$sep = ",";
	
	$file_handle = fopen($filename, "r");
	$i = 0;
	$row = 0;
	$numColumns = 0;
	$columnHeaders = array();
	$fieldNames = array();
	$usableColumns = array();
	$domainArray = array();
	$addCount = 0;
	$updateCount = 0;
	$luqAddCount = 0;
	
	connect_to_mysql_and_select_db();
	SetupAllowableFields();
	
	$ui_domain_category = 0;
	if(isset($_REQUEST["CategoryID"]))
		$ui_domain_category = validate_request_data($_REQUEST["CategoryID"]);
		
	$import_status = "<ul class=\"bullets\">";

	while (!feof($file_handle) ) 
	{
		$text_line = fgetcsv($file_handle, 2048, $sep);
		$column_count = count($text_line);
		
		$row++;
		# ignore empty rows at top.
		if($column_count == 1 && $i == 0 && $text_line[0] == "")
			continue;
		
		if($i == 0)
		{
			$numColumns = $column_count;
			$columnHeaders = $text_line;
			$cindex = 0;
			$responce->msg .= "<ul class=\"bullets\">";
			foreach($columnHeaders as $column)
			{
				$column = str_replace(chr(0), '', $column);
				$column = trim($column, "\" ");
				$column = strtolower($column);
				$field = getFieldNameFromLabel($column);
				if(in_array($column, $db_allowed_domain_columns))
				{
					$usableColumns[] = $cindex;
					$fieldNames[] = $column;
					$responce->msg .= "<li>Found DB field: " . $column . "</li>";
				}
				else if(in_array($field, $db_allowed_domain_columns))
				{
					$usableColumns[] = $cindex;
					$fieldNames[] = $field;
					$responce->msg .= "<li>Found DB field: " . $column . "</li>";
				}
				else
				{
					if($column_count == 1)
					{
						$responce->msg .= "<li class=\"lierr\">Unable to find anything that can be imported! Did you select the right separator?</li>";
						$responce->status = "Error";
					}
					else
					{
						$fieldNames[] = $column;
						$responce->msg .= "<li class=\"lierr\">Missing DB field: " . $column . "</li>";
					}
				}
				$cindex++;
			}
			$responce->msg .= "</ul>";
		}
		else if(count($usableColumns))
		{
			$domainName = "";
			if($numColumns && $numColumns == $column_count)
			{
				$domainData = array();
				foreach($usableColumns as $ci)
				{
					$centry = str_replace(chr(0), '', $text_line[$ci]);
					$key = $fieldNames[$ci];
					if($key == "domain")
						$domainName = trim($centry);
					else if($centry != "")
						$domainData[$key] = $centry;
				}
				if($domainName != "")
				{
					$addToLUQ = ($numColumns > 1) ? false : true;
					if(addDomain($domainName, $ui_domain_category, $addToLUQ))
					{
						$addCount++;
						if($addToLUQ)
							$luqAddCount++;
					}
					if(count($domainData))
					{
						if($domainName != "" && substr_count($domainName, ".") > 0)
						{
							update_domain_table($domainData, $domainName);
							$updateCount++;
						}
					}
				}
				unset($domainData);
			}
			else
			{
				if($column_count == 1 && $text_line[0] == "")
				{
					$import_status .= "<li class=\"lierr\">Ignoring Empty Row #";
					$import_status .= $row;
				}
				else
				{
					$import_status .= "<li class=\"lierr\">Ignoring Row #";
					$import_status .= $row;
					$import_status .= " (column count mismatch)";
					$import_status .= " Found only ";
					$import_status .= $column_count;
					$import_status .= " Column(s)";
				}
				$import_status .= "</li>";
			}
		}
		$i++;
	}
	
	if($responce->status != "Error")
	{
		$responce->msg .=  "<ul class=\"bullets\"><li>Importing ";
		$responce->msg .= $numColumns;
		$responce->msg .= " Column(s)</li></ul>";
		
		$import_status .= "</ul>";
		$responce->msg .= $import_status;
		$import_status = "<ul class=\"bullets\">";
		
		$import_status .= "<li>" . $row . " rows processed.</li>";
		$import_status .= "<li>" . $addCount . " domains inserted into the DB.</li>";
		$import_status .= "<li>" . $updateCount . " domain records updated.</li>";
		$import_status .= "<li>" . $luqAddCount . " domains added to whois and DNS lookup queue.</li>";
		
		$import_status .= "</ul>";
		$responce->msg .= $import_status;
	}
	
	fclose($file_handle);
}

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

function addDomain(&$domain_name, $ui_domain_category, $addToLUQ=false)
{
	$domain_name = validate_request_data($domain_name);
	
	$domain_name = cleanup_domain_name(trim($domain_name));
	if($domain_name == "" || substr_count($domain_name, ".") == 0)
		return false;
	$ascii_domain = strtolower(idn_convert($domain_name));
	
	$domain_added = false;
	
	global $db_config_domain_table, $db_config_catconnection_table;
	$sid = 0;
	$sqlCount = "SELECT COUNT(*) AS count FROM $db_config_domain_table WHERE domain='$domain_name'";  
	$results = mysql_query($sqlCount);
	if($results)
	{
		$existing = mysql_fetch_array($results);  
		if ($existing['count'] == 0) 
		{
			$sqlAdd = "insert into " . $db_config_domain_table . "(`domain`, `added_on`, `ascii_domain`) values ('$domain_name', now(), '$ascii_domain')";
			$result = mysql_query( $sqlAdd );
			if($result)
			{
				$sid = get_sid_from_domain_name($domain_name);
				if($addToLUQ && $sid > 0)
				{
					do_default_domain_lookups($sid);
				}
				$domain_added = true;
			}
		}
		else
			$sid = get_sid_from_domain_name($domain_name);
				
		if($ui_domain_category > 1)
		{
			if($sid > 0)
			{
				$sqlCount = "SELECT COUNT(*) AS count FROM $db_config_catconnection_table WHERE sid=$sid AND CategoryID=$ui_domain_category";  
				$result = mysql_query( $sqlCount );
				$existing = mysql_fetch_array($result);  
				if ($existing['count'] == 0) 
				{  
					$sqlCatConnection = "insert into $db_config_catconnection_table (`CategoryID`, `sid`) values ($ui_domain_category, $sid);";
					$result = mysql_query( $sqlCatConnection );
				}
			}
		}
	}
	return $domain_added;
}

?>