<?php
###############################################################################
# datagrid.php
# Watch My Domains SED v3
# (c) Softnik Technologies. All rights reserved.
###############################################################################

define("USE_AUTH_DB","TRUE");

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

require_once("../basic.php");					# Basic UI is always required.
require_once("../pdo/dbinit.php");				# The database
require_once("../config.check.php");			# Load default settings.
require_once("../config/displaygroups.php");	# Domain table display groups
require_once("../idn/idn.php");					# IDN Library

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

define("DGA_CATEGORY_GRID", 			"cg");
define("DGA_CATEGORY_GRID_EDIT", 		"cge");

define("DGA_QUERY_GRID", 				"qg");
define("DGA_QUERY_GRID_EDIT", 			"qge");

define("DGA_DOMAIN_GRID", 				"dg");
define("DGA_DOMAIN_GRID_EDIT", 			"dge");

define("DGA_SUBDOMAIN_GRID", 			"sdg");
define("DGA_SUBDOMAIN_GRID_EDIT", 		"sdge");

define("DGA_SSL_GRID", 					"sslg");
define("DGA_SSL_GRID_EDIT", 			"sslge");

define("DGA_USER_GRID", 				"ug");
define("DGA_USER_GRID_EDIT", 			"uge");

define("DGA_SUBDOMAIN_MGR_GRID", 		"sdmg");
define("DGA_SUBDOMAIN_MGR_GRID_EDIT", 	"sdmge");

define("GET_CATEGORIES_FOR_DOMAIN", 	"gcd");
define("ORDER_CATEGORIES", 				"oc");
define("EMPTY_CATEGORY", 				"ec");
define("WHOIS_DATA_FOR_DOMAIN", 		"wdd");

define("DGA_GET_TLD_INFO", 				"gti");
define("DGA_GET_SERVER_INFO",			"gsi");
define("DGA_SET_TLD_INFO", 				"sti");
define("DGA_SET_SERVER_FOR_TLD", 		"ssft");
define("DGA_EXPORT_DATA",				"exportdata");
define("DGA_DOMAIN_LOOKUP", 			"dlu");
define("DGA_DOMAIN_CSV_UPLOAD", 		"csvdu");
define("DGA_SUBDOMAIN_CSV_UPLOAD",		"csvsdu");

define("CSV_TEXT_DOWNLOAD", 			"export");
define("GET_QUEUE_INFO", 				"gqi");

define("GET_DNS_DATA", 					"dnsdata");  
define("GET_SSL_DATA", 					"ssldata");  

define("GET_WHOIS_HISTORY", 			"whistory");  

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

$auth = validateSession(isRequestCommand("nsi") ? false : true);
$pdo = init_db(false);

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

if($pdo !== false)
{
	if(isRequestCommand(DGA_CATEGORY_GRID))
		doCategoryGrid($pdo, $auth);
	else if(isRequestCommand(DGA_CATEGORY_GRID_EDIT))
		doCategoryGridEdit($pdo, $auth);
	
	else if(isRequestCommand(DGA_QUERY_GRID))
		doQueryGrid($pdo, $auth);
	else if(isRequestCommand(DGA_QUERY_GRID_EDIT))
		doQueryGridEdit($pdo, $auth);
	
	else if(isRequestCommand(DGA_DOMAIN_GRID))
		doDomainGrid($pdo, $auth);
	else if(isRequestCommand(DGA_DOMAIN_GRID_EDIT))
		doDomainGridEdit($pdo, $auth);
	
	else if(isRequestCommand(DGA_SUBDOMAIN_GRID))
		doSubdomainGrid($pdo, $auth);
	else if(isRequestCommand(DGA_SUBDOMAIN_GRID_EDIT))
		doSubdomainGridEdit($pdo, $auth);
	
	else if(isRequestCommand(DGA_SSL_GRID))
		doSSLGrid($pdo, $auth);
	else if(isRequestCommand(DGA_SSL_GRID_EDIT))
		doSSLGridEdit($pdo, $auth);
	
	else if(isRequestCommand(DGA_SUBDOMAIN_MGR_GRID))
		doSubdomainManagerGrid($pdo, $auth);
	else if(isRequestCommand(DGA_SUBDOMAIN_MGR_GRID_EDIT))
		doSubdomainManagerGridEdit($pdo, $auth);
	
	else if(isRequestCommand(DGA_SET_SERVER_FOR_TLD))
		doSetServerForTLD($pdo, $auth);
	else if(isRequestCommand(DGA_GET_TLD_INFO))
		doGetTLDInfo($pdo, $auth);
	else if(isRequestCommand(DGA_GET_SERVER_INFO))
		doGetServerInfo($pdo, $auth);
	else if(isRequestCommand(DGA_SET_TLD_INFO))
		doSetTLDInfo($pdo, $auth);
	else if(isRequestCommand(DGA_EXPORT_DATA))
		doExportData($pdo, $auth);
	else if(isRequestCommand(DGA_DOMAIN_LOOKUP))
		doLookupDomains($pdo, $auth);
	else if(isRequestCommand(DGA_DOMAIN_CSV_UPLOAD))
		doDomainCSVUpload($pdo, $auth);
	else if(isRequestCommand(DGA_SUBDOMAIN_CSV_UPLOAD))
		doSubdomainCSVUpload($pdo, $auth);
	
	else if(isRequestCommand(GET_CATEGORIES_FOR_DOMAIN))
		doCategoriesForDomain($pdo, $auth);
	else if(isRequestCommand(ORDER_CATEGORIES))
		doCategoryReorder($pdo, $auth);
	else if(isRequestCommand(WHOIS_DATA_FOR_DOMAIN))
		doWhoisDataForDomain($pdo, $auth);
	else if(isRequestCommand(EMPTY_CATEGORY))
		doEmptyCategory($pdo, $auth);
	else if(isRequestCommand(GET_QUEUE_INFO))
		doGetQueueInfo($pdo, $auth);
	else if(isRequestCommand(GET_DNS_DATA))
		doGetDNSData($pdo, $auth);
	else if(isRequestCommand(GET_SSL_DATA))
		doGetSSLData($pdo, $auth);
	else if(isRequestCommand(DGA_USER_GRID))
		doUserGrid($pdo, $auth);
	else if(isRequestCommand(DGA_USER_GRID_EDIT))
		doUserGridEdit($pdo, $auth);
	
	else if(isRequestCommand(GET_WHOIS_HISTORY))
		doWhoisHistory($pdo, $auth);
}
else
{
	# Handle PDO Error
}

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

function doSubdomainCSVUpload($pdo, $auth)
{
	$response = new stdClass();
	$response->validate = $auth;
	$response->status = "ok";
	$response->msg = "";
	# 0 = View, 1 = View+Edit+Add+Delete, 2 = View+Edit, 3 = View=Edit+Add
	$accessrights = getUserAccessRights();
	if($accessrights == 1 || $accessrights == 3)
	{
		if(!empty($_FILES['csv_file']['name'])) 
			doSDFileUploadProc($pdo, $auth, $response);
		else
		{
			$response->msg = "Nothing To Do! Please select a file to upload.";
			$response->status = "Error";
		}
	}
	else
	{
		$response->msg = "Permission denied. You don't have sufficient access right to add domains.";
		$response->status = "Error";
	}
	echo json_encode($response);
	exit;
}

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

function doDomainCSVUpload($pdo, $auth)
{
	$response = new stdClass();
	$response->validate = $auth;
	$response->status = "ok";
	$response->msg = "";
	# 0 = View, 1 = View+Edit+Add+Delete, 2 = View+Edit, 3 = View=Edit+Add
	$accessrights = getUserAccessRights();
	if($accessrights == 1 || $accessrights == 3)
	{
		if(!empty($_FILES['csv_file']['name'])) 
			doFileUploadProc($pdo, $auth, $response);
		else
		{
			$response->msg = "Nothing To Do! Please select a file to upload.";
			$response->status = "Error";
		}
	}
	else
	{
		$response->msg = "Permission denied. You don't have sufficient access right to add domains.";
		$response->status = "Error";
	}
	echo json_encode($response);
	exit;
}

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

function doLookupDomains($pdo, $auth)
{
	$response['validate'] = $auth;
	$response['lucount'] = 0;
	$response['status'] = "notdone";
	$accessrights = getUserAccessRights();
	if($accessrights != 0 && $auth == 0)
	{
		$ri = 1440;
		if(isset($_REQUEST['ri']))
			$ri = intval($_REQUEST['ri']);
		$what = LOOKUP_DOMAIN_WHOIS;
		if(isset($_REQUEST['what']))
			$what = intval($_REQUEST['what']);
		$idarray = trim($_REQUEST['id'], ",");
		$ids = explode(",", $idarray);
		for($i = 0; $i < count($ids); $i++)
		{
			$sid = $ids[$i];
			if(ctype_digit($sid))
				$response['lucount'] += $pdo->addDomainToLookupQueue($sid, $what, $ri);
		}
		$response['status'] = "done";
	}
	else
	{
		$response['msg'] = "Permission denied. You don't have sufficient access right to add domains.";
		$response['status'] = "Error";
	}
	echo json_encode($response);
	exit;
}

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

function doExportData($pdo, $auth)
{
	if($auth == 0)
	{
		header('Content-Encoding: UTF-8');
		$csvdata = stripslashes($_POST[DGA_EXPORT_DATA]);
		$filename = "domain-columns.csv";
		if(isset($_REQUEST['txt']))
		{
			$filename = "domain-names.txt";
			header('Content-type: text/txt; charset=UTF-8');
		}
		else
			header('Content-type: text/csv; charset=UTF-8');
		header('Content-Length: ' . strlen($csvdata));
		header('Content-Disposition: attachment; filename=' . $filename);
		header('Content-Transfer-Encoding: binary');
		$fsize = strlen($csvdata);
		$pdo->logAuditEntry(AUDIT_CSV_DOWNLOAD, "Downloaded $filename ({$fsize} bytes)");
		echo $csvdata;
	}
	else
		header("Location: ../../../login.php");
	exit;
}

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

function doGetTLDInfo($pdo, $auth)
{
	# Get TLD Info
	$response = array('whoisserver'=> '','validate'=>$auth, 'config'=>false, 'lastconnectat'=>'');
	$tld = filter_var($_REQUEST[DGA_GET_TLD_INFO], FILTER_SANITIZE_STRING);
	$wserver = $pdo->getSingleEntry($pdo->getTldsTableName(), "tld", $tld, "server");
	if($wserver === false)
	{
		$info = findWhoisServerFromIANA($tld);
		if($info != false)
			$wserver = $info['whoisserver'];;
	}
	else
		$response['config'] = true;
	if($wserver !== false)
	{
		$conni = $pdo->getConnectionIntervalForWhoisServer($wserver);
		$lct = $pdo->getLastConnectTimeForExternalServer($wserver);
		if($lct !== false)
			$response['lastconnectat'] = $lct;
		$response['whoisserver'] = $wserver;
		$sinfo = $pdo->getWhoisServerInfo($wserver);
		if($sinfo !== false)
		{
			foreach($sinfo as $key=>$val)
			{
				if($key == "port" and $val == null)
					$val = 43;
				else if($key == "dateformat" and $val == null)
					$val = "auto";
				else if($key == "conninterval" && $conni !== false)
					$val = $conni;
				if($val !== null)
					$response[$key] = $val;
				else
					$response[$key] = "";
			}
		}
	}
	echo json_encode($response);
	exit;
}

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

function doSetServerForTLD($pdo, $auth)
{
	# 0 = View, 1 = View+Edit+Add+Delete, 2 = View+Edit, 3 = View=Edit+Add
	$accessrights = getUserAccessRights();
	if($accessrights == 1 || $accessrights == 3)
	{
		$response = array('validate'=>$auth, 'status'=>'notok');
		$tld = getRequestVariable(DGA_SET_SERVER_FOR_TLD, '');
		$server = getRequestVariable('server', '');
		if($server != "" && $tld != "")
		{
			if($server == '-')
				$server = "";
			$status = $pdo->setWhoisServerForTLD($tld, $server);
			if($status !== false)
				$response['status'] = "ok";
		}
	}
	else 
		noPermissionQuit();
	echo json_encode($response);
	exit;
}

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

function doGetServerInfo($pdo, $auth)
{
	# Get TLD Info
	$response = array('whoisserver'=> '','validate'=>$auth, 'config'=>false, 'lastconnectat'=>'');
	$wserver = filter_var($_REQUEST[DGA_GET_SERVER_INFO], FILTER_SANITIZE_STRING);
	if($wserver != "")
	{
		$conni = $pdo->getConnectionIntervalForWhoisServer($wserver);
		$lct = $pdo->getLastConnectTimeForExternalServer($wserver);
		if($lct !== false)
			$response['lastconnectat'] = $lct;
		$response['whoisserver'] = $wserver;
		$sinfo = $pdo->getWhoisServerInfo($wserver);
		if($sinfo !== false)
		{
			foreach($sinfo as $key=>$val)
			{
				if($key == "port" and $val == null)
					$val = 43;
				else if($key == "dateformat" and $val == null)
					$val = "auto";
				else if($key == "conninterval" && $conni !== false)
					$val = $conni;
				if($val !== null)
					$response[$key] = $val;
				else
					$response[$key] = "";
			}
		}
	}
	echo json_encode($response);
	exit;
}

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

function doSetTLDInfo($pdo, $auth)
{
	# Set Whois Server Info
	# 0 = View, 1 = View+Edit+Add+Delete, 2 = View+Edit, 3 = View=Edit+Add
	$accessrights = getUserAccessRights();
	if($accessrights == 0)
		noPermissionQuit();
	else
	{
		$response = array('whoisserver'=> '','validate'=>$auth, 'status'=>'notok');
		$wserver = filter_var($_REQUEST[DGA_SET_TLD_INFO], FILTER_SANITIZE_STRING);
		if($wserver != "")
		{
			if($pdo->setWhoisServerInfo($wserver, $_REQUEST) !== false)
			{
				$response['status'] = "ok";
				$response['server'] = $wserver;
			}
			else
				$response['error'] = $pdo->getLastError();
		}
		echo json_encode($response);
	}
	exit;
}

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

function doGetDNSData($pdo, $auth)
{
	$csvdata = "domain,record,type,value,ttl,ip,notes A,notes B\n";
	$sids = explode(",", getRequestVariable("dnsdata", ""));
	foreach($sids as $sid)
	{
		if($sid > 0)
		{
			$domain_name = $pdo->getSingleEntry($pdo->getDomainTableName(), "sid", $sid, "domain");
			$rows = $pdo->getTableData($pdo->getSubdomainTableName(), "*", "where sid=?", array($sid));
			if($rows !== false)
			{
				foreach($rows as $row)
				{
					$host = $row['subdomain'];
					$type = $row['record_type'];
					$target = $row['record_value'];
					$ip = $row['ip'];
					$ttl = $row['ttl'];
					$notes_a = $row['notes_a'];
					$notes_b = $row['notes_b'];
					$notes_a = str_replace('"', '%^%^%', $notes_a);
					$notes_a = str_replace('%^%^%', '""', $notes_a);
					$notes_b = str_replace('"', '%^%^%', $notes_b);
					$notes_b = str_replace('%^%^%', '""', $notes_b);
					$csvdata .= "$domain_name,$host,$type,$target,$ttl,$ip,\"$notes_a\",\"$notes_b\"\n";
				}
			}
			$csvdata .= "\n";
		}
	}
	
	header('Content-Encoding: UTF-8');
	$filename = "domain-dns.csv";
	header('Content-type: text/csv; charset=UTF-8');
	header('Content-Length: ' . strlen($csvdata));
	header('Content-Disposition: attachment; filename=' . $filename);
	header('Content-Transfer-Encoding: binary');
	$fsize = strlen($csvdata);
	$pdo->logAuditEntry(AUDIT_DNS_CSV_DOWNLOAD, "Downloaded $filename ({$fsize} bytes)");
	echo $csvdata;
	exit;
}

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

function doGetSSLData($pdo, $auth)
{
	$csvdata = "domain,record,ssl_valid_from,ssl_valid_till,ssl_issued_to,ssl_issued_by,notes A,notes B\n";
	$sids = explode(",", getRequestVariable("ssldata", ""));
	foreach($sids as $sid)
	{
		if($sid > 0)
		{
			$domain_name = $pdo->getSingleEntry($pdo->getDomainTableName(), "sid", $sid, "domain");
			$rows = $pdo->getTableData($pdo->getSubdomainTableName(), "*", "where sid=?", array($sid));
			if($rows !== false)
			{
				foreach($rows as $row)
				{
					$subdomain = $row['subdomain'];
					$ssl_from = $row['ssl_valid_from'];
					$ssl_to = $row['ssl_valid_to'];
					$ssl_issue = $row['ssl_issued_to'];
					$ssl_by = $row['ssl_issued_by'];
					$notes_a = $row['notes_a'];
					$notes_b = $row['notes_b'];
					$notes_a = str_replace('"', '%^%^%', $notes_a);
					$notes_a = str_replace('%^%^%', '""', $notes_a);
					$notes_b = str_replace('"', '%^%^%', $notes_b);
					$notes_b = str_replace('%^%^%', '""', $notes_b);
					if($ssl_from != "")
						$csvdata .= "$domain_name,$subdomain,$ssl_from,$ssl_to,$ssl_issue,$ssl_by,\"$notes_a\",\"$notes_b\"\n";
				}
			}
		}
	}
	
	header('Content-Encoding: UTF-8');
	$filename = "domain-ssl.csv";
	header('Content-type: text/csv; charset=UTF-8');
	header('Content-Length: ' . strlen($csvdata));
	header('Content-Disposition: attachment; filename=' . $filename);
	header('Content-Transfer-Encoding: binary');
	$fsize = strlen($csvdata);
	$pdo->logAuditEntry(AUDIT_DNS_CSV_DOWNLOAD, "Downloaded $filename ({$fsize} bytes)");
	echo $csvdata;
	exit;
}


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

function doGetQueueInfo($pdo, $auth)
{
	$responce = new stdClass();
	$responce->validate = $auth;
	if($auth == 0)
	{
		$responce->status = "ok";
		$responce->server_time = date("Y-m-d H:i:s");
		$responce->queue_size = $pdo->getCount($pdo->getLookupQueueTableName());
		$responce->server_time_zone = date_default_timezone_get(); 
		$tstamp = $pdo->getLastQueueProcessedTime();
		if($tstamp !== false)
			$responce->last_queue_proc = date("Y-m-d H:i:s", $tstamp);
		else
			$responce->last_queue_proc = "";
		$responce->ipw_size   = $pdo->getCount($pdo->getLookupQueueTableName(), "type=" . LOOKUP_IP_WHOIS);
		$responce->dw_size    = $pdo->getCount($pdo->getLookupQueueTableName(), "type=" . LOOKUP_DOMAIN_WHOIS);
		$responce->ip_size    = $pdo->getCount($pdo->getLookupQueueTableName(), "type=" . LOOKUP_IP_ADDRESS);
		$responce->sdw_size   = $pdo->getCount($pdo->getLookupQueueTableName(), "type=" . LOOKUP_SEC_DOMAIN_WHOIS);
		$responce->ssl_size   = $pdo->getCount($pdo->getLookupQueueTableName(), "type=" . LOOKUP_SSL_CERTS);
		$responce->ping_size  = $pdo->getCount($pdo->getLookupQueueTableName(), "type=" . LOOKUP_PING_RESPONSE);
		$responce->mx_size    = $pdo->getCount($pdo->getLookupQueueTableName(), "type=" . LOOKUP_MX_RECORDS);
		$responce->alexa_size = $pdo->getCount($pdo->getLookupQueueTableName(), "type=" . LOOKUP_ALEXA_DATA);
		$responce->dns_size   = $pdo->getCount($pdo->getLookupQueueTableName(), "type=" . LOOKUP_SUB_DOMAINS);
		$responce->gi_size    = $pdo->getCount($pdo->getLookupQueueTableName(), "type=" . LOOKUP_GOOGLE_INDEX);
		$responce->http_size  = $pdo->getCount($pdo->getLookupQueueTableName(), "type=" . LOOKUP_HTTP_HOMEPAGE);
		$responce->gpr_size   = $pdo->getCount($pdo->getLookupQueueTableName(), "type=" . LOOKUP_GOOGLE_PR);
		$responce->swipedin   = get_last_swipein();
		$responce->timeout    = get_timeout();
	}
	echo json_encode($responce);
	exit;
}

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

function doUserGrid($pdo, $auth)
{
	if($auth == 0)
	{
		$responce = new stdClass();
		if($pdo->jqGridCount($pdo->getUserTableName(), "id", $responce))
		{
			$pdo->jqGridData($pdo->getUserTableName(), "id", "id,name,password,active,readwrite,display_name", $responce);
			if(isset($responce->rows))
			{
				# 0 = View, 1 = View+Edit+Add+Delete, 2 = View+Edit, 3 = View+Edit+Add
				foreach($responce->rows as &$r)
				{
					if(isset($r['readwrite']))
					{
						if($r['readwrite'] == 0)
							$r['readwrite'] = "<img src=\"lib/css/images/16/view.png\" title=\"View\" alt=\"View\">";
						else if($r['readwrite'] == 1)
							$r['readwrite'] = "<img src=\"lib/css/images/16/addeditdelview.png\" title=\"View+Edit+Add+Delete\" alt=\"View+Edit+Add+Delete\">";
						else if($r['readwrite'] == 2)
							$r['readwrite'] = "<img src=\"lib/css/images/16/editview.png\" title=\"View+Edit\" alt=\"View+Edit\">"; 
						else if($r['readwrite'] == 3)
							$r['readwrite'] = "<img src=\"lib/css/images/16/addeditview.png\" title=\"View+Edit+Add\" alt=\"View+Edit+Add\">"; 
					}
				}
			}
		}
		echo json_encode($responce);
	}
	else
		invalidSessionQuit();
	exit;
}

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

function doUserGridEdit($pdo, $auth)
{
	$responce = array('validate'=>$auth, 'added'=>0);
	if($auth == 0 && isAdminUser())
	{
		if(isset($_REQUEST['oper']))
		{
			$opmode = $_REQUEST['oper'];
			if($opmode == "add")
			{
				if($_REQUEST['name'] && $_REQUEST['password'])
				{
					$name = strip_tags(trim($_REQUEST['name']));
					$password = strip_tags(trim($_REQUEST['password']));
					
					$display_name = "";
					if(isset($_REQUEST['display_name']))
						$display_name = strip_tags(trim($_REQUEST['display_name']));
					
					$active = 0;
					if(isset($_REQUEST['active']))
					{
						if($_REQUEST['active'] == "Yes" || $_REQUEST['active'] == "true" || $_REQUEST['active'] == "1")
							$active = 1;
					}
					
					$readwrite = 0;
					if(isset($_REQUEST['readwrite']))
					{
						$access = getNumericRequestVariable('readwrite', 0);
						if($access == 0 || $access == 1 || $access == 2 || $access == 3)
							$readwrite = $access;
					}
					$status = $pdo->createUser($name, $display_name, $password, "New User", $active, $readwrite);
					if($status !== false)
						$responce['status'] = "ok";
					else
					{
						$responce['status'] = "notok";
						$responce['error'] = $pdo->getLastError();
					}
				}
			}
			else if($opmode == "del")
			{
				$responce['status'] = "notok";
				if(isset($_REQUEST['id']))
				{
					$uid = strip_tags(trim($_REQUEST['id']));
					if(getUserID() != $uid)
					{
						$status = $pdo->deleteUserID($uid);
						if($status !== false)
							$responce['status'] = "ok";
					}
					else
						noPermissionQuit();
				}
			}
		}
	}
	else
		invalidSessionQuit();
	echo json_encode($responce);
	exit;
}

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

function doCategoryGrid($pdo, $auth)
{
	if($auth == 0)
	{
		$cids = getValidCategoryIDs();
		if(!count($cids))
			$cids = $pdo->getAllCategoryIDs();
		$response = new stdClass();
		if($pdo->getCategoryGridCounts($cids, $response))
			$pdo->getCategoryGridData($cids, $response);
		echo json_encode($response);
	}
	else
		invalidSessionQuit();
	exit;
}

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

function doCategoryGridEdit($pdo, $auth)
{
	if($auth == 0)
	{
		$response = categoryGridEdit($pdo, $auth);
		if($response !== false)
			echo json_encode($response);
		else
			noPermissionQuit();
	}
	else
		noPermissionQuit();
	exit;
}

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

function doQueryGrid($pdo, $auth)
{
	if($auth == 0)
	{
		$response = new stdClass();
		if($pdo->jqGridCount($pdo->getAutoQueryTableName(), "id", $response))
			$pdo->jqGridData($pdo->getAutoQueryTableName(), "id", "id,Name,Query", $response);
		echo json_encode($response);
	}
	else
		invalidSessionQuit();
	exit;
}

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

function doQueryGridEdit($pdo, $auth)
{
	# Query Grid Edit
	if($auth == 0)
	{
		$response = queryGridEdit($pdo, $auth);
		if($response !== false)
			echo json_encode($response);
		else
			noPermissionQuit();
	}
	else
		noPermissionQuit();
	exit;
}

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

function doDomainGrid($pdo, $auth)
{
	if($auth == 0)
	{
		$cids = getValidCategoryIDs();
		$response = new stdClass();
		$cid = getNumericRequestVariable("cid", 0);
		$aqid = getNumericRequestVariable("aqid", 0);
		$cqid = getNumericRequestVariable("cqid", 0);
		$hdays = getNumericRequestVariable("hd", 7);
		$pdo->setRowHighlights($hdays);
		$cqdata = null;
		if($cqid > 0 && $cid == 0 && $aqid == 0)
			$cqdata = getCustomQueryData();
		if($pdo->jqGridDomainCount($cid, $aqid, $cqdata, $cids, $response))
		{
			if(isset($_REQUEST['columns']))
				$columns = trim($_REQUEST['columns'], ",");
			else
				$columns = "sid,r_h_disp,domain";
			$pdo->jqGridDomainData($cid, $aqid, $cqdata, $columns, $cids, $response);
		}
		echo json_encode($response);
	}
	else
		invalidSessionQuit();
	exit;
}

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

function doDomainGridEdit($pdo, $auth)
{
	# Domain Grid Edit
	if($auth == 0)
	{
		$response = domainGridEdit($pdo, $auth);
		if($response !== false)
			echo json_encode($response);
		else
			noPermissionQuit();
	}
	else if($_REQUEST['oper'] == "add")
		echo json_encode(array('validate'=>$auth));
	else
		noPermissionQuit();
	exit;
}

###############################################################################
// Subdomain grid for a specific domain

function doSubdomainGrid($pdo, $auth)
{
	if($auth == 0)
	{
		$responce = new stdClass();
		$sid = getNumericRequestVariable("sid", 0);
		if($sid > 0)
		{
			if(isset($_REQUEST['columns']))
				$columns = trim($_REQUEST['columns'], ",");
			else
				$columns = "hid,subdomain";
			$_REQUEST['ecf'] = "sid";
			$_REQUEST['ecv'] = $sid;
			if($pdo->jqGridCount($pdo->getSubdomainTableName(), "hid", $responce))
			{
				$pdo->jqGridData($pdo->getSubdomainTableName(), "hid", $columns, $responce);
			}
		}
		echo json_encode($responce);
	}
	else
		invalidSessionQuit();
	exit;
}

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

function doSubdomainGridEdit($pdo, $auth)
{
	# Domain Grid Edit
	if($auth == 0)
	{
		$response = subDomainGridEdit($pdo, $auth);
		if($response !== false)
			echo json_encode($response);
		else
			noPermissionQuit();
	}
	else if($_REQUEST['oper'] == "add")
		echo json_encode(array('validate'=>$auth));
	else
		noPermissionQuit();
	exit;
}

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

function doSSLGrid($pdo, $auth)
{
	if($auth == 0)
	{
		$responce = new stdClass();
		$sid = getNumericRequestVariable("sid", 0);
		if($sid > 0)
		{
			if(isset($_REQUEST['columns']))
				$columns = trim($_REQUEST['columns'], ",");
			else
				$columns = "hid,subdomain";
			$_REQUEST['ecf'] = "sid,ssl_issued_to";
			$_REQUEST['ecv'] = "$sid,not null";
			if($pdo->jqGridCount($pdo->getSubdomainTableName(), "hid", $responce))
			{
				$pdo->jqGridData($pdo->getSubdomainTableName(), "hid", $columns, $responce);
			}
		}
		echo json_encode($responce);
	}
	else
		invalidSessionQuit();
	exit;
}

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

function doSSLGridEdit($pdo, $auth)
{
	# SSL Grid Edit
	if($auth == 0)
	{
		$response = SSLGridEdit($pdo, $auth);
		if($response !== false)
			echo json_encode($response);
		else
			noPermissionQuit();
	}
	else if($_REQUEST['oper'] == "add")
		echo json_encode(array('validate'=>$auth));
	else
		noPermissionQuit();
	exit;
}

###############################################################################
// Subdomain grid for all domains

function doSubdomainManagerGrid($pdo, $auth)
{
	if($auth == 0)
	{
		$cids = getValidCategoryIDs();
		$responce = new stdClass();
		$cid = getNumericRequestVariable("cid", 0);
		$aqid = getNumericRequestVariable("aqid", 0);
		$cqid = getNumericRequestVariable("cqid", 0);
		$hdays = getNumericRequestVariable("hd", 7);
		$pdo->setSubdomainRowHighlights($hdays);
		$cqdata = null;
		if($cqid > 0 && $cid == 0 && $aqid == 0)
			$cqdata = getCustomQueryData();
		if($pdo->jqGridSubdomainCount($cid, $aqid, $cqdata, $cids, $responce))
		{
			if(isset($_REQUEST['columns']))
				$columns = trim($_REQUEST['columns'], ",");
			else
				$columns = "hid,sid,subdomain";
			$pdo->jqGridSubdomainData($cid, $aqid, $cqdata, $columns, $cids, $responce);
			
			if(isset($responce->rows))
			{
				$i = 0;
				foreach($responce->rows as &$row)
				{
					$domain = "";
					$subdomain = "";
					foreach($row as $key=>&$val)
					{
						if($key == "subdomain")
						{
							$subdomain = ($val == "@" ? "" : $val);
						}
						else if($key == "domain")
						{
							$domain = $pdo->getSingleEntry($pdo->getDomainTableName(), "sid", $val, "domain");
							$val = $domain;
						}
						else if($key == "hostname")
						{
							$val = $subdomain != "" ? "$subdomain.$domain" : $domain;
						}
					}
				}
			}
		}
		echo json_encode($responce);
	}
	else
		invalidSessionQuit();
	exit;
}

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

function doSubdomainManagerGridEdit($pdo, $auth)
{
	# Domain Grid Edit
	if($auth == 0)
	{
		$response = subDomainManagerGridEdit($pdo, $auth);
		if($response !== false)
			echo json_encode($response);
		else
			noPermissionQuit();
	}
	else if($_REQUEST['oper'] == "add")
		echo json_encode(array('validate'=>$auth));
	else
		noPermissionQuit();
	exit;
}

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

function doCategoriesForDomain($pdo, $auth)
{
	$responce['validate'] = $auth;
	$responce['cids'] = array(0);
	if($auth == 0)
		$responce['cids'] = $pdo->getCategoryIdsForDomain(intval($_REQUEST[GET_CATEGORIES_FOR_DOMAIN]));
	echo json_encode($responce);
	exit;
}

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

function doEmptyCategory($pdo, $auth)
{
	$responce['validate'] = $auth;
	$cid = intval($_REQUEST[EMPTY_CATEGORY]);
	$responce['status'] = 'notdone';
	$responce['cid'] = $cid;
	if($auth == 0 && $cid > 0)
	{
		if($pdo->emptyCategory($cid))
			$responce['status'] = "done";
		else
			$responce['status'] = $pdo->getLastError();
	}
	echo json_encode($responce);
	exit;
}

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

function doCategoryReorder($pdo, $auth)
{
	# Order Categories (Move a specified Category Up or Down)
	# Access rights Should not be 0
	if($auth !== 0)
		echo json_encode(array('validate'=>$auth));
	else if(getUserAccessRights()) 
		echo json_encode(sortCategoryList($pdo, $auth));
	else # No access rights.
		noPermissionQuit();
	exit;
}

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

function getOrphanColumns($pdo)
{
	$orphancolumns = array();
	$customcolumns = $pdo->getCustomColumns();
	$defaultcolumns = $pdo->getDefaultColumnNames($pdo->getDomainTableName());
	$existingcolumns = $pdo->getAllColumnNames($pdo->getDomainTableName());
	$displaycolumns = $pdo->getAllDisplayColumns();
	foreach($existingcolumns as $column)
	{
		if(!in_array($column, $customcolumns) && !in_array($column, $defaultcolumns) && !in_array($column, $displaycolumns))
			$orphancolumns[] = $column;
	}
	return $orphancolumns;
}

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

function doWhoisHistory($pdo, $auth)
{
	if($auth !== 0)
	{
		echo json_encode(array('validate'=>$auth));
		return;
	}
	$id = intval($_REQUEST['whistory']);
	$responce = array('whois'=>'','validate'=>$auth, 'id'=>$id, 'domain' => '', 'type' => '');
	$output = $pdo->getTableData($pdo->data_history_table, 'tvalue,domain, ftype, lookedup_at', "WHERE id=?", array($id));
	if($output !== false && isset($output[0])) {
		$responce['whois'] = $output[0]['tvalue'];
		$responce['domain'] = $output[0]['domain'];
		$responce['timeat'] = $output[0]['lookedup_at'];
		$responce['type'] = $output[0]['ftype'] == 1 ? "Registry" : "Registrar";
	}
	echo json_encode($responce);
	exit;
}

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

function doWhoisDataForDomain($pdo, $auth)
{
	if($auth !== 0)
	{
		echo json_encode(array('validate'=>$auth));
		return;
	}
	# Get Raw Whois Data for Domain
	$responce = array('registry_whois'=>'', 'registrar_whois'=>'','ip_whois'=>'','validate'=>$auth,'domain_details'=>'');
	$output = $pdo->getDomainTableData(intval($_REQUEST['wdd']));
	if($output !== false)
	{
		$responce['registry_whois'] = '';
		$responce['registrar_whois'] = '';
		$responce['ip_whois'] = '';
		$responce['whois_history'] = '';
		$customcolumns = $pdo->getCustomColumns();
		$orphancolumns = getOrphanColumns($pdo);
		$nogridcolumns = $pdo->getNoGridDomainColumnNames();
		$responce['domain_details'] = "<table class=\"dataviewtable\">\n";
		foreach($output as $what => $info)
		{
			if($what == 'registry_whois')
				$responce['registry_whois'] = $info;
			else if($what == 'registrar_whois')
				$responce['registrar_whois'] = $info;
			else if($what == 'ip_whois')
				$responce['ip_whois'] = $info;
			else if($what == 'whois_history')
				$responce['whois_history'] = $info;
			else if(!function_exists("sedf_format_domain_details")) {
				if($pdo->getColumnLabelAndWidthForDomain($what, $label, $width) === false)
					$label = getLabelFromFieldName($what);
				$img = "";
				if(in_array($what, $orphancolumns))
					$img = "<a href=\"#\" class=\"del-orphan\" id=\"del-orphan-$what\"><img alt=\"Orphan Column\" src=\"lib/css/images/16/deletecol.png\"></a>";
				else
				{	
					if(!in_array($what, $nogridcolumns))
					{
						$ft = $pdo->getFieldType($pdo->getDomainTableName(), $what);
						if(($ft !== false && stristr($ft,"datetime") === false) || $what == "last_update")
						{
							if($what != "sid" && $what != "domain" && $what != "r_h_disp" && $what != "edited")
							{
								if(in_array($what, $customcolumns))
									$img = "<a href=\"#\" class=\"edit-detail\" id=\"edit-detail-$what\"><img alt=\"Edit Custom Column\" src=\"lib/css/images/16/customeditcol.png\"></a>";
								else
									$img = "<a href=\"#\" class=\"edit-detail\" id=\"edit-detail-$what\"><img alt=\"Edit Column\" src=\"lib/css/images/16/editcol.png\"></a>";
								$img .= "<input type=\"hidden\" id=\"edit-detailv-$what\" value=\"" . url_encode_sed($info) . "\">";
							}
						}
					}
					if(in_array($what, $customcolumns) && $img == "")
						$img = "<img title=\"Custom Column\" alt=\"Custom Column\" src=\"lib/css/images/16/customcol.png\">";
				}
				$responce['domain_details'] .= "<tr><td class=\"control\">$img</td><td class=\"column\">$label</td><td class=\"value\"><div class=\"dtabv dtabv-$what\">$info</div></td></tr>\n";
			}
		}
		if(function_exists("sedf_format_domain_details"))
			$responce['domain_details'] = sedf_format_domain_details($output, $pdo);
		else
			$responce['domain_details'] .= "</table>\n";
	}
	echo json_encode($responce);
	exit;
}

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

function url_encode_sed($in) 
{ 
	$out = ''; 
	for ($i=0;$i<strlen($in);$i++) 
	{ 
		$hex = dechex(ord($in[$i])); 
		if ($hex=='') 
		   $out = $out.urlencode($in[$i]); 
		else 
		   $out = $out .'%'.((strlen($hex)==1) ? ('0'.strtoupper($hex)):(strtoupper($hex))); 
	} 
	$out = str_replace('+','%20',$out); 
	$out = str_replace('_','%5F',$out); 
	$out = str_replace('.','%2E',$out); 
	$out = str_replace('-','%2D',$out); 
	return $out; 
} 

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

function sortCategoryList($pdo, $auth)
{
	$responce = array('status'=>'notok', 'validate'=>$auth);
	$cid = intval($_REQUEST['oc']);
	$inc = intval($_REQUEST['i']);
	$cids = $pdo->getAllCategoryIDsBySortOrder();
	if($cids !== false)
	{
		$foundat = array_search($cid, $cids);
		if($foundat !== false)
		{
			if($inc == 1 && $foundat < count($cids)-1 && $foundat > 0)
			{
				$temp = $cids[$foundat];
				$cids[$foundat] = $cids[$foundat+1];
				$cids[$foundat+1] = $temp;
			}
			else if($inc == -1 && $foundat > 1)
			{
				$temp = $cids[$foundat];
				$cids[$foundat] = $cids[$foundat-1];
				$cids[$foundat-1] = $temp;
			}
			$sortorder = 9999;
			foreach($cids as $id)
			{
				$pdo->setCategorySortOrder($id, $sortorder);
				$sortorder--;
			}
			$responce['status'] = 'ok';
		}
	}
	return $responce;
}

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

function categoryGridEdit($pdo, $auth)
{
	$opmode = strtolower(trim(getRequestVariable('oper', "")));
	$response = array('validate'=>$auth);
	
	# 0 = View, 1 = View+Edit+Add+Delete, 2 = View+Edit, 3 = View=Edit+Add
	$accessrights = getUserAccessRights();
	if($opmode == "edit" && $accessrights != 0)
	{
		# Don't allow renaming "All Columns" (id=1)
		if(getNumericRequestVariable("id", 0) == 1)
			return false;
		if($pdo->jqGridEdit($pdo->getCategoryTableName(), "CategoryID", array("CategoryName")) === false)
		{
			$response['status'] = "notok";
			$response['error'] = $pdo->getLastError();
		}
		else
			$response['status'] = "ok";
	}
	else if($opmode == "add" && ($accessrights == 1 || $accessrights == 3))
	{
		if($pdo->jqGridAdd($pdo->getCategoryTableName(), "CategoryID", array("CategoryName")) === false)
		{
			$response['status'] = "notok";
			$response['error'] = $pdo->getLastError();
		}
		else
		{
			$response['status'] = "ok";
			if(isset($_REQUEST['CategoryName']))
			{
				$categoryname = filter_var($_REQUEST['CategoryName'], FILTER_SANITIZE_STRING);
				$pdo->logAuditEntry(AUDIT_ADDED_CATEGORY, "Added Category $categoryname");
			}
		}
	}
	else if($opmode == "del" && $accessrights == 1)
	{
		if($pdo->deleteCategories($_REQUEST['id']) === false)
		{
			$response['status'] = "notok";
			$response['error'] = $pdo->getLastError();
		}
		else
			$response['status'] = "ok";
	}
	else
		return false;
	return $response;
}

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

function queryGridEdit($pdo, $auth)
{
	$opmode = strtolower(trim(getRequestVariable('oper', "")));
	$response = array('validate'=>$auth);
	
	# 0 = View, 1 = View+Edit+Add+Delete, 2 = View+Edit, 3 = View=Edit+Add
	$accessrights = getUserAccessRights();
	if($opmode == "edit" && $accessrights != 0)
	{
		# Kill any query that contains 'drop', 'delete' or 'truncate'.
		foreach($_REQUEST as $key=>$uvalue) 
		{
			if(mb_stristr($uvalue, "drop") !== false || mb_stristr($uvalue, "delete") !== false || mb_stristr($uvalue, "truncate") !== false)
			{
				return false;
			}
			if($key == "id")
				$qoldvalue = $pdo->getSingleEntry($pdo->getAutoQueryTableName(), "id", intval($uvalue), "Query");
		}
		if($pdo->jqGridEdit($pdo->getAutoQueryTableName(), "id", array("Name")) === false)
		{
			$response['status'] = "notok";
			$response['error'] = $pdo->getLastError();
		}
		else
		{
			$response['status'] = "ok";
			if(isset($_REQUEST['Name']) && isset($_REQUEST['Query']))
			{
				$qname = $_REQUEST['Name'];
				$qvalue = $_REQUEST['Query'];
				if(!isset($qoldvalue))
					$qoldvalue = "";
				if($qvalue != $qoldvalue)
					$pdo->logAuditEntry(AUDIT_EDITED_AUTOQUERY, "Modified autoquery '$qname' to \"$qvalue\". It was \"$qoldvalue\"");
			}
		}
	}
	else if($opmode == "add" && ($accessrights == 1 || $accessrights == 3))
	{
		# Kill any query that contains 'drop', 'delete' or 'truncate'.
		foreach($_REQUEST as $key=>$uvalue) 
		{
			if(mb_stristr($uvalue, "drop") !== false || mb_stristr($uvalue, "delete") !== false || mb_stristr($uvalue, "truncate") !== false)
			{
				return false;
			}
		}
		if($pdo->jqGridAdd($pdo->getAutoQueryTableName(), "id", array("Name")) === false)
		{
			$response['status'] = "notok";
			$response['error'] = $pdo->getLastError();
		}
		else
		{
			$response['status'] = "ok";
			if(isset($_REQUEST['Name']) && isset($_REQUEST['Query']))
			{
				$qname = $_REQUEST['Name'];
				$qvalue = $_REQUEST['Query'];
				$pdo->logAuditEntry(AUDIT_ADDED_AUTOQUERY, "Added autoquery '$qname' = \"$qvalue\"");
			}
		}
	}
	else if($opmode == "del" && $accessrights == 1)
	{
		if(isset($_REQUEST['id']))
		{
			$qid = intval($_REQUEST['id']);
			$qname = $pdo->getSingleEntry($pdo->getAutoQueryTableName(), "id", $qid, "Name");
		}
		if($pdo->jqGridDelete($pdo->getAutoQueryTableName(), "id") === false)
		{
			$response['status'] = "notok";
			$response['error'] = $pdo->getLastError();
		}
		else
		{
			$response['status'] = "ok";
			if(isset($qname))
				$pdo->logAuditEntry(AUDIT_DELETED_AUTOQUERY, "Deleted autoquery '$qname'");
		}
	}
	else
		return false;
	
	return $response;
}

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

function domainGridEdit($pdo, $auth)
{
	$opmode = strtolower(trim(getRequestVariable('oper', "")));
	$response = array('validate'=>$auth, 'added'=>0);
	
	# 0 = View, 1 = View+Edit+Add+Delete, 2 = View+Edit, 3 = View=Edit+Add
	$accessrights = getUserAccessRights();
	if($opmode == "add" && ($accessrights == 1 || $accessrights == 3) && isset($_REQUEST['data']))
	{
		$cid = getNumericRequestVariable('cid', 0);
		$response['category'] = $cid;
		$domaindata = $_REQUEST['data'];
		$added = $pdo->addDomains($domaindata, $cid);
		if($added === false)
		{
			$response['status'] = "notok";
			$response['error'] = $pdo->getLastError();
		}
		else
		{
			$response['added'] = $added;
			$response['status'] = "$added domains added.";
		}
	}
	else if($opmode == "del" && $accessrights == 1)
	{
		if($pdo->deleteDomains($_REQUEST['id']) === false)
		{
			$response['status'] = "notok";
			$response['error'] = $pdo->getLastError();
		}
		else
			$response['status'] = "ok";
	}
	else if($opmode == "edit" && $accessrights != 0)
	{
		if($pdo->editDomain(intval($_REQUEST['id'])) === false)
		{
			$response['status'] = "notok";
			$response['error'] = $pdo->getLastError();
		}
		else
			$response['status'] = "ok";
	}
	else
		return false;
	return $response;
}

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

function subDomainGridEdit($pdo, $auth)
{
	$opmode = strtolower(trim(getRequestVariable('oper', "")));
	$response = array('validate'=>$auth, 'added'=>0);
	
	# 0 = View, 1 = View+Edit+Add+Delete, 2 = View+Edit, 3 = View=Edit+Add
	$accessrights = getUserAccessRights();
	if($opmode == "add" && ($accessrights == 1 || $accessrights == 3) && isset($_REQUEST['data']))
	{
		$sids = getRequestVariable('sids', "");
		$cid = getNumericRequestVariable('cid', 0);
		$domaindata = $_REQUEST['data'];
		$added = addSubomainsForDomains($domaindata, $cid, $sids);
		if($added !== false)
		{
			$response['status'] = "ok";
			$response['added'] = $added;
		}
		else
		{
			$response['status'] = "notok";
			$response['error'] = $pdo->getLastError();
		}
	}
	else if($opmode == "del" && $accessrights == 1)
	{
		if($pdo->deleteSubdomains($_REQUEST['id']) === false)
		{
			$response['status'] = "notok";
			$response['error'] = $pdo->getLastError();
		}
		else
			$response['status'] = "ok";
	}
	else if($opmode == "edit" && $accessrights != 0)
	{
		if($pdo->editSubdomain(intval($_REQUEST['id'])) === false)
		{
			$response['status'] = "notok";
			$response['error'] = $pdo->getLastError();
		}
		else
			$response['status'] = "ok";
	}
	else
		return false;
	return $response;
}

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

function SSLGridEdit($pdo, $auth)
{
	$opmode = strtolower(trim(getRequestVariable('oper', "")));
	$response = array('validate'=>$auth, 'added'=>0);
	
	# 0 = View, 1 = View+Edit+Add+Delete, 2 = View+Edit, 3 = View=Edit+Add
	$accessrights = getUserAccessRights();
	if($opmode == "add" && ($accessrights == 1 || $accessrights == 3) && isset($_REQUEST['data']))
	{
		# Not supported
	}
	else if($opmode == "del" && $accessrights == 1)
	{
		if($pdo->deleteSubdomains($_REQUEST['id']) === false)
		{
			$response['status'] = "notok";
			$response['error'] = $pdo->getLastError();
		}
		else
			$response['status'] = "ok";
	}
	else if($opmode == "edit" && $accessrights != 0)
	{
		if($pdo->editSubdomain(intval($_REQUEST['id'])) === false)
		{
			$response['status'] = "notok";
			$response['error'] = $pdo->getLastError();
		}
		else
			$response['status'] = "ok";
	}
	else
		return false;
	return $response;
}

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

function subDomainManagerGridEdit($pdo, $auth)
{
	$opmode = strtolower(trim(getRequestVariable('oper', "")));
	$response = array('validate'=>$auth);
	# 0 = View, 1 = View+Edit+Add+Delete, 2 = View+Edit, 3 = View=Edit+Add
	$accessrights = getUserAccessRights();
	if($opmode == "edit" && $accessrights != 0)
	{
		if($pdo->editSubdomain(intval($_REQUEST['id'])) === false)
		{
			$response['status'] = "notok";
			$response['error'] = $pdo->getLastError();
		}
		else
			$response['status'] = "ok";
	}
	else if($opmode == "add" && ($accessrights == 1 || $accessrights == 3))
	{
		$sids = getRequestVariable('sids', "");
		$cid = getNumericRequestVariable('cid', 0);
		$domaindata = $_REQUEST['data'];
		$added = addSubomainsForDomains($domaindata, $cid, $sids);
		if($added !== false)
		{
			$response['status'] = "ok";
			$response['added'] = $added;
		}
		else
		{
			$response['status'] = "notok";
			$response['error'] = $pdo->getLastError();
		}
	}
	else if($opmode == "del" && $accessrights == 1)
	{
		if($pdo->deleteSubdomains($_REQUEST['id']) === false)
		{
			$response['status'] = "notok";
			$response['error'] = $pdo->getLastError();
		}
		else
			$response['status'] = "ok";
	}
	else
		return false;
	return $response;
}

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

function doFileUploadProc($pdo, $auth, &$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($pdo, $auth, $responce, $tmp, $sep);	
		else
		{
			$responce->msg .= "<ul class=\"bullets\"><li class=\"err\">The file is not UTF-8 or ANSI Encoded.</li></ul>";	
			$responce->status = "Error";
		}
	}
	else 
		echo 'Upload failed !';
}

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

function uploadCSVData($pdo, $auth, &$responce, $filename, $sep=",")
{
	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;
	$dberrors = 0;
	
	$cid = 0;
	if(isset($_REQUEST["cid"]))
		$cid = intval($_REQUEST["cid"]);
		
	$import_status = "<ul class=\"bullets\">";
	
	$domainlist = array();
	$domaintable = $pdo->getDomainTableName();
	$valid_columns = $pdo->getAllColumnNames($domaintable);

	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 = $pdo->getFieldNameFromLabel($column);
				if(in_array($column, $valid_columns))
				{
					$usableColumns[] = $cindex;
					$fieldNames[] = $column;
					$responce->msg .= "<li>Found DB field: " . $column . "</li>";
				}
				else if(in_array($field, $valid_columns))
				{
					$usableColumns[] = $cindex;
					$fieldNames[] = $field;
					$responce->msg .= "<li>Found DB field: " . $column . "</li>";
				}
				else
				{
					if($column_count == 1)
					{
						$responce->msg .= "<li class=\"err\">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=\"err\">The field / column: '" . $column . "' was not found in the DB table, ignored.</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 != "")
					{
						// Fix the last_update value to include date+time
						if($key == "last_update" && strpos($centry, ":") === false)
							$centry .= " 00:00:00";
						$centry = $pdo->cleanupFieldData($domaintable, $centry, $key);
						$domainData[$key] = $centry;
					}
				}
				
				if($domainName != "")
				{
					$addToLUQ = ($numColumns > 1) ? false : true;
					$sid = 0;
					$status = $pdo->addDomain($domainName, $cid, $sid);
					if($status !== false && $sid > 0 && $status > 0)
					{
						if($addToLUQ)
						{
							$pdo->doDefaultDomainLookups($sid);
							$luqAddCount++;
						}
						$addCount++;
						if(count($domainlist) < MAX_AUDIT_LOG_DOMAINS)
							$domainlist[] = $domainName;
					}
					if(count($domainData))
					{
						if($domainName != "" && substr_count($domainName, ".") > 0)
						{
							if (strlen($domainName) == strlen(utf8_decode($domainName)))
								$domainName = strtolower($domainName);
							if($pdo->setDomainDataFromArray($domainName, $domainData) !== false)
								$updateCount++;
							else
							{
								$dberrors++;
							}
						}
					}
				}
				
				unset($domainData);
			}
			else
			{
				if($column_count == 1 && $text_line[0] == "")
				{
					$import_status .= "<li class=\"err\">Ignoring Empty Row #";
					$import_status .= $row;
				}
				else
				{
					$import_status .= "<li class=\"err\">Ignoring Row #";
					$import_status .= $row;
					$import_status .= " (column count mismatch)";
					$import_status .= " Found only ";
					$import_status .= $column_count;
					$import_status .= " Column(s)";
				}
				if($dberrors)
				{
					$import_status .= "</li><li class=\"err\">There were database errors while updating columns.";
				}
				$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;
	}
	
	if(count(domainlist) && $addCount)
	{
		if($addCount > MAX_AUDIT_LOG_DOMAINS)
			$domainlist[] = "...";
		$pdo->logAuditEntry(AUDIT_ADD_DOMAINS, "Imported $addCount domains (" . implode(", ", $domainlist) . ")");
	}
	
	fclose($file_handle);
}

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

function doSDFileUploadProc($pdo, $auth, &$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')) 
			uploadSDCSVData($pdo, $auth, $responce, $tmp, $sep);	
		else
		{
			$responce->msg .= "<ul class=\"bullets\"><li class=\"err\">The file is not UTF-8 or ANSI Encoded.</li></ul>";	
			$responce->status = "Error";
		}
	}
	else 
		echo 'Upload failed !';
}

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

function uploadSDCSVData($pdo, $auth, &$responce, $filename, $sep=",")
{
	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;
	$dberrors = 0;
	
	$cid = 0;
	if(isset($_REQUEST["cid"]))
		$cid = intval($_REQUEST["cid"]);
		
	$import_status = "<ul class=\"bullets\">";
	
	$domaintable = $pdo->getDomainTableName();
	$subdomaintable = $pdo->getSubdomainTableName();
	$allowed_subdomain_columns = array('hostname', 'notes_a', 'notes_b', 'notes_c', 'notes_d');

	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 = $pdo->getFieldNameFromLabel($column);
				if(in_array($column, $allowed_subdomain_columns))
				{
					$usableColumns[] = $cindex;
					$fieldNames[] = $column;
					$responce->msg .= "<li>Found DB field: " . $column . "</li>";
				}
				else if(in_array($field, $valid_columns))
				{
					$usableColumns[] = $cindex;
					$fieldNames[] = $field;
					$responce->msg .= "<li>Found DB field: " . $column . "</li>";
				}
				else
				{
					if($column_count == 1)
					{
						$responce->msg .= "<li class=\"err\">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=\"err\">The field / column: '" . $column . "' was not found in the DB table, ignored.</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 == "hostname")
						$hostname = trim($centry);
					else if($centry != "")
					{
						$centry = $pdo->cleanupFieldData($subdomaintable, $centry, $key);
						$domainData[$key] = $centry;
					}
				}
				
				if($hostname != "")
				{
					$dearray = explode(",", $hostname);
					if(count($dearray) == 2)
					{
						$subdomain = $dearray[0];
						$domain = $dearray[1];
						if(substr_count($domain, ".") > 0)
						{
							$hid = 0;
							if(AddSubDomainForDomain($domain, $subdomain, $cid, $addeddomains, $hid))
							{
								if($hid > 0)
									$pdo->setSubdomainDataFromArray($hid, $domainData);
								$updateCount++;
							}
						}
					}
					else if(count($dearray) == 1)
					{
						$hostname = $dearray[0];
						$spos = mb_strpos($hostname, ".");
						if($spos !== false)
						{
							$hid = 0;
							$subdomain = mb_substr($hostname, 0, $spos);
							$domain = mb_substr($hostname, $spos+1);
							if(substr_count($domain, ".") > 0)
							{
								if(AddSubDomainForDomain($domain, $subdomain, $cid, $addeddomains, $hid))
								{
									if($hid > 0)
										$pdo->setSubdomainDataFromArray($hid, $domainData);
									$updateCount++;
								}
							}
						}
					}
				}
				unset($domainData);
			}
			else
			{
				if($column_count == 1 && $text_line[0] == "")
				{
					$import_status .= "<li class=\"err\">Ignoring Empty Row #";
					$import_status .= $row;
				}
				else
				{
					$import_status .= "<li class=\"err\">Ignoring Row #";
					$import_status .= $row;
					$import_status .= " (column count mismatch)";
					$import_status .= " Found only ";
					$import_status .= $column_count;
					$import_status .= " Column(s)";
				}
				if($dberrors)
				{
					$import_status .= "</li><li class=\"err\">There were database errors while updating columns.";
				}
				$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 . " subdomain records updated.</li>";
		
		$import_status .= "</ul>";
		$responce->msg .= $import_status;
	}
	
	fclose($file_handle);
}

###############################################################################
?>
