<?php
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/*

Subdomain Manager /  Watch My Domains SED

Copyright 2015, Softnik Technologies.

*/
/////////////////////////////////////////////////////////////////////////////////////////////////////////
	
require_once("lib/php/config.check.php");
require_once("config.php");
require_once("lib/php/base.php");

$io_allowed_filter_operations	= array('AND', 'OR');

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

# Only admin users can use this script.
# If user authentication is disabled, everyone is an admin user!

session_start();
check_authentication_login();
doSessionSwipeIn();

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

$notes_a_label = "Notes-A";
$notes_b_label = "Notes-B";
$notes_c_label = "Notes-C";
$notes_d_label = "Notes-D";

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// 0 = View
// 1 = View+Edit+Add+Delete
// 2 = View+Edit
// 3 = View=Edit+Add

$allowed_category_ids = array();
$access_rights = 1;
$userinfo = get_userinfo_from_session();
if(!is_admin_user())
{
	$access_rights = $userinfo['readwrite'];	
	$permissions = get_permissions_from_session();
	if(is_array($permissions))
	{
		foreach($permissions as $p)
			$allowed_category_ids[] = $p['id'];
	}
}

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

function get_base_dir()
{
	return realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR;
}

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

function __fnGetSQLSearchString($searchOperation, $searchString)
{
	if($searchString == 'NULL')
		return "IS NULL";
	else if($searchString == 'EMPTY')
		return "= ''";
	else if($searchString == '!' || $searchString == 'NOT NULL')
		return "IS NOT NULL";
	else
		return fnGetSQLSearchString($searchOperation, $searchString);
}

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

function get_hid_for_subdomain_and_domain($sid, $subdomain)
{
	global $db_config_subdomain_table;
	$sql = "select hid from $db_config_subdomain_table where subdomain = '$subdomain' AND 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['hid']))
		return $row['hid'];
	return 0;
}

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

function AddSubDomainForDomain($domain, $subdomain, &$udomains, &$hid)
{
	global $db_config_domain_table, $db_config_catconnection_table, $allowed_category_ids, $access_rights;
	
	$domain = validate_request_data($domain);
	$subdomain = validate_request_data($subdomain);
	$sid = get_sid_from_domain_name($domain);
	
	// If not admin, check if the domain belongs to users' categories.
	// Otherwise don't add.
	if(count($allowed_category_ids) && $sid > 0)
	{
		$catids = implode(",", $allowed_category_ids);
		$sqlAdd = "select sid from $db_config_catconnection_table where CategoryID IN ($catids) AND sid=$sid LIMIT 1";
		$result = mysql_query( $sqlAdd );
		if($result)
		{
			$num_rows = mysql_num_rows($result);
			if($num_rows == 0)
				return false;
		}
		else
			return false;
	}
	if(count($allowed_category_ids) && $sid <= 0)
		return false;
	
	if($sid > 0)
		add_sub_domain($sid, $subdomain);
	else
	{
		$domain = cleanup_domain_name(trim($domain));
		if($domain == "" || substr_count($domain, ".") == 0)
			return false;
		
		$ascii_domain = strtolower(idn_convert($domain));
			
		$sqlAdd = "insert into " . $db_config_domain_table . "(`domain`, `added_on`, `ascii_domain`) values ('$domain', now(), '$ascii_domain')";
		$result = mysql_query( $sqlAdd );
		if($result)
		{
			$sid = get_sid_from_domain_name($domain);
			do_default_domain_lookups($sid);
			add_sub_domain($sid, $subdomain);
		}
	}
	if($sid > 0)
	{
		if(in_array($sid, $udomains) === false)
			$udomains[] = $sid;
		$hid = get_hid_for_subdomain_and_domain($sid, $subdomain);
		return true;
	}
	return false;
}

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

function manual_update_subdomain_data($hid, $darray)
{
	global $db_config_subdomain_table;
	global $subdomain_table_text_fields, $subdomain_table_datetime_fields;
	$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);		
	$sql .= " where hid = " . $hid;
	
	if(count($updateArray))
	{
		$result = mysql_query( $sql );
		if(!$result)
		{
			//$msg = "Couldn't execute your query. " . mysql_error() . "\n";
			//logToFile("php.log", $msg);
		}
	}
}

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

function doFileUploadProc(&$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))
	{
		$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, $responce, $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 
	{
		$responce->msg .= "<ul class=\"bullets\"><li class=\"lierr\">File upload failed.</li></ul>";	
		$responce->status = "Error";
	}
}

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

function uploadCSVData($filename, &$responce, $sep=",")
{
	global $allowed_category_ids;
	$allowed_subdomain_columns = array('hostname', 'notes_a', 'notes_b', 'notes_c', 'notes_d');
	
	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();
	$updateCount = 0;
	$luqAddCount = 0;
	$import_status = "<ul class=\"bullets\">";
	$addeddomains = array();
	
	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, $allowed_subdomain_columns))
				{
					$usableColumns[] = $cindex;
					$fieldNames[] = $column;
					$responce->msg .= "<li>Found DB field: " . $column . "</li>";
				}
				else if(in_array($field, $allowed_subdomain_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))
		{
			$hostname = "";
			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 != "")
						$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, $addeddomains, $hid))
							{
								if($hid > 0)
									manual_update_subdomain_data($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, $addeddomains, $hid))
								{
									if($hid > 0)
										manual_update_subdomain_data($hid, $domainData);
									$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")
	{
		$addCount = count($addeddomains);
		$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 affected.</li>";
		$import_status .= "<li>" . $updateCount . " subdomain records updated.</li>";
		
		$import_status .= "</ul>";
		$responce->msg .= $import_status;
	}
	
	fclose($file_handle);
}

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

if(isset($_REQUEST['upload']))
{
	$responce = new stdClass();
	$responce->status = "ok";
	$responce->msg = "";
	if(!empty($_FILES['csv_file']['name'])) 
	{
		if($access_rights == 2 || $access_rights == 0)
		{
			header("HTTP/1.0 403 Forbidden");
			echo "Permission Denied.";
			exit;
		}
		require_once("lib/php/idn.php");
		connect_to_mysql_and_select_db();
		doFileUploadProc($responce);
	}
	else
		$responce->msg = "Missing File.";
	echo json_encode($responce);
	exit;
}

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

if(isset($_REQUEST['grid']))
{
	connect_to_mysql_and_select_db();

	$page = get_numeric_request_variable('page', 1);     // get the requested page
	$limit = get_numeric_request_variable('rows', 20); // get how many rows we want to have into the grid
	$sidx = get_indexed_request_variable('sidx', 'sid', $db_allowed_subdomain_columns); // get index row - i.e. user click to sort
	$sord = get_indexed_request_variable('sord', 'asc', array('asc', 'desc')); // get the direction
	
	#########################################################################################
	
	$ui_search_status 				= "false";
	$ui_search_field  				= "";
	$ui_search_string 				= "";
	$ui_search_operator 			= "";
	$ui_search_filter				= "";
	
	if(isset($_REQUEST['_search']))
		$ui_search_status = validate_request_data($_REQUEST['_search']); 
	if(isset($_REQUEST['searchField']))
		$ui_search_field = validate_request_data($_REQUEST['searchField']); 
	if(isset($_REQUEST['searchString']))
		$ui_search_string = validate_request_data($_REQUEST['searchString']); 
	if(isset($_REQUEST['searchOper']))
		$ui_search_operator = validate_request_data($_REQUEST['searchOper']); 
	if(isset($_REQUEST['filters']))
	{
		// Skip input validation for now. We will do validation at a later stage for each individual column.
		$ui_search_filter = $_REQUEST['filters'];
		$ui_search_filter = str_replace("\\", "", $ui_search_filter);
	}
	
	#########################################################################################
	
	global $db_config_domain_table, $db_config_subdomain_table, $db_config_catconnection_table, $io_allowed_filter_operations;
	global $db_allowed_subdomain_columns;
	
	$qWhere = '';
	if($ui_search_status == 'true')
	{
		$qWhere = 'WHERE';
		if($ui_search_filter != "")
		{
			$firstElem = true;
			$searchData = json_decode($ui_search_filter);
			foreach ($searchData->rules as $rule) 
			{
				if (!$firstElem) 
				{
					if (in_array($searchData->groupOp, $io_allowed_filter_operations)) 
						$qWhere .= ' '.$searchData->groupOp.' ';
				}
				else 
					$firstElem = false;	
				if (in_array($rule->field, $db_allowed_subdomain_columns)) 
					$qWhere .= " a." . $rule->field . " " . __fnGetSQLSearchString($rule->op, $rule->data);
				else if($rule->field == 'domain')
					$qWhere .= " a.sid IN (SELECT sid FROM $db_config_domain_table WHERE " . $rule->field . " " . __fnGetSQLSearchString($rule->op, $rule->data) . ")";
			}
			if($qWhere == 'WHERE' && $ui_search_string != "")
				$qWhere .= " " . $ui_search_field . ' ' . __fnGetSQLSearchString($ui_search_operator, $ui_search_string);
		}
		else			
		{
			$qWhere .= " " . $ui_search_field . ' ' . __fnGetSQLSearchString($ui_search_operator, $ui_search_string);
		}
	}

	$usql = "";
	if(isset($_REQUEST['noroot']))
		$usql = "(record_type='CNAME' OR record_type='A' OR ssl_issued_by is not null OR subdomain LIKE '%__%')"; // OR a.subdomain <> '@'";
	else
		$usql = ""; 
	
	if(count($allowed_category_ids))
	{
		$catids = implode(",", $allowed_category_ids);
		if($usql != "")
			$usql .= " AND ";
		$usql .= " (a.sid IN (SELECT sid from $db_config_catconnection_table WHERE CategoryID IN ($catids)))";
	}

	if($qWhere != "" && $usql != "")
		$usql = " $qWhere AND $usql";
	else if($qWhere != "")
		$usql = " $qWhere";
	else if($usql != "")
		$usql = " WHERE $usql";
	
	$sqlCount = "SELECT COUNT(DISTINCT a.hid) AS count FROM  $db_config_subdomain_table a";
	$sqlCount .= $usql;
	
	$result = mysql_query($sqlCount) or die("Connection Error: " . mysql_error());
	$row = mysql_fetch_array($result,MYSQL_ASSOC);
	$count = $row['count'];

	if( $count >0 ) {
		$total_pages = ceil($count/$limit);
	} else {
		$total_pages = 0;
	}
	if ($page > $total_pages) $page=$total_pages;
	$start = $limit*$page - $limit; // do not put $limit*($page - 1)
	
	$sqlColumns = array('subdomain', 'domain', 'record_type', 'record_value', 'ip', 'ssl_valid_to', 'ssl_issued_by', 'ssl_issued_to', 'hostname', 'notes_a', 'notes_b', 'notes_c', 'notes_d');
	
	$sqtext = "a.sid, ";
	foreach($sqlColumns as $sc)
	{
		if($sc !== 'hostname')
			$sqtext .= "a." . $sc . ", ";
	}
	$sqtext = trim($sqtext, ", ");
	
	$SQL = "SELECT DISTINCT a.* FROM $db_config_subdomain_table a";
	$SQL .= $usql . " ORDER BY a.$sidx $sord";
	if($count > 0  && $dnload == false)
		$SQL .= " LIMIT $start , $limit";
	
	$result = mysql_query( $SQL ) or die("Couldn't execute query.".mysql_error());

	$responce = new stdClass();
	$responce->page = $page;
	$responce->total = $total_pages;
	$responce->records = $count;
	$i=0;
	while($row = mysql_fetch_array($result,MYSQL_ASSOC)) 
	{
		$responce->rows[$i]['id']=$row['hid'];
		$darray = array();
		$subdomain = "";
		$domain = "";
		foreach($sqlColumns as $sc)
		{
			if($sc == 'subdomain')
			{
				$subdomain = $row['subdomain'];
				$darray[] = $subdomain;
			}
			else if($sc == 'domain')
			{
				$domain = get_domain_name_from_sid($row['sid']);
				$darray[] = $domain;
			}
			else if($sc == 'hostname')
			{
				if($subdomain != "@")
					$darray[] = "$subdomain.$domain";
				else
					$darray[] = $domain;
			}
			else
				$darray[] = $row[$sc];
		}
		$responce->rows[$i]['cell'] = $darray;
		$i++;
	}        
	echo json_encode($responce);

	exit;
}
if(isset($_REQUEST['edit']))
{
	global $db_config_subdomain_table;
	
	if($access_rights == 0)
	{
		header("HTTP/1.0 403 Forbidden");
		echo "Permission Denied.";
		exit;
	}
	connect_to_mysql_and_select_db();
	if(isset($_REQUEST['oper']))
	{
		$opmode = $_REQUEST['oper'];
		if($opmode == "del")
		{
			if($access_rights == 2 || $access_rights == 3)
			{
				header("HTTP/1.0 403 Forbidden");
				echo "Permission Denied.";
				exit;
			}
			if(isset($_REQUEST['id']))
			{
				$idarray = trim($_REQUEST['id'], ",");
				$ids = explode(",", $idarray);
				$sqlw = array();
				for($i = 0; $i < count($ids); $i++)
				{
					# Make sure the ids are are just numbers.
					if(ctype_digit($ids[$i]))
						$sqlw[] = "hid = " . $ids[$i];
				}
				$sqlwhere = implode(" OR ", $sqlw);
				$sql = 'Delete from ' . $db_config_subdomain_table . ' where ' . $sqlwhere;
				mysql_query( $sql ) or die('Couldn t execute query.'.mysql_error());
			}
		}
		if($opmode == "edit")
		{
			if(isset($_REQUEST['id']))
			{
				$hid = intval(strip_tags(trim($_REQUEST['id'])));
				if($hid > 0)
					manual_update_subdomain_data($hid, $_REQUEST);
			}
		}
	}
	exit;
}
if(isset($_REQUEST['add']))
{
	if($access_rights == 2 || $access_rights == 0)
	{
		header("HTTP/1.0 403 Forbidden");
		echo "Permission Denied.";
		exit;
	}
	require_once("lib/php/idn.php");
	connect_to_mysql_and_select_db();
	$udomains = array();
	$responce = new stdClass();
	$responce->records = 0;
	if(isset($_REQUEST['ui_subdomains']) && is_ok_to_process_form("subdomains-entry-form"))
	{
		$ui_unclean_domain_data = $_REQUEST['ui_subdomains'];
		$split_tokens = "\n\r";
		$domain_names = array();
		$dentry = strtok($ui_unclean_domain_data, $split_tokens);
		while ($dentry !== false) 
		{
			$dearray = explode(",", $dentry);
			if(count($dearray) == 2)
			{
				$subdomain = $dearray[0];
				$domain = $dearray[1];
				if(substr_count($domain, ".") > 0)
				{
					$hid = 0;
					if(AddSubDomainForDomain($domain, $subdomain, $udomains, $hid))
						$responce->records++;
				}
			}
			else if(count($dearray) == 1)
			{
				$hostname = $dearray[0];
				$spos = mb_strpos($hostname, ".");
				if($spos !== false)
				{
					$subdomain = mb_substr($hostname, 0, $spos);
					$domain = mb_substr($hostname, $spos+1);
					if(substr_count($domain, ".") > 0)
					{
						$hid = 0;
						if(AddSubDomainForDomain($domain, $subdomain, $udomains, $hid))
							$responce->records++;
					}
				}
			}
			$dentry = strtok($split_tokens);
		}
		foreach($udomains as $sid)
			add_to_lookup_queue($sid, LOOKUP_SUB_DOMAINS, 0);
		$responce->status = "ok";
	}
	echo json_encode($responce);
	exit;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	$jqtheme = get_theme_name("");
	$title = "";
	if($title == "")
		$title = "Domain Portfolio Manager - Subdomain Manager";
	$panesjs = "cfgpanes.js";

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
		<title><?php echo $title; ?></title>
		<meta http-equiv="Content-Language" content="en">
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<link rel="shortcut icon" type="image/x-icon" href="lib/css/img/favicon.ico">
		
		<link type="text/css" href="lib/css/jqueryui/<?php echo $jqtheme; ?>/jquery-ui-1.8.7.custom.css" rel="stylesheet">
		<link type="text/css" href="lib/css/jqueryui/<?php echo $jqtheme; ?>/splitter.1.51.css" rel="stylesheet" media="screen">
		<link type="text/css" href="lib/css/jqueryui/splitter.1.51.css" rel="stylesheet" media="screen">
		<link type="text/css" href="lib/css/jqueryui/ui.jqgrid.css" rel="stylesheet" media="screen">

		<script type="text/javascript" src="lib/js/jquery/jquery-1.5.1.min.js"></script>
		<script type="text/javascript" src="lib/js/jquery/jquery.cookie.min.js"></script>
		<script type="text/javascript" src="lib/js/jquery/jquery-ui-1.8.7.noeffects.min.js"></script>
		<script type="text/javascript" src="lib/js/jquery/splitter.1.51.min.js"></script>
		<script type="text/javascript" src="lib/js/jquery/i18n/grid.locale-en.js"></script>
		<script type="text/javascript" src="lib/js/jquery/jquery.jqGrid.3.8.2.min.js"></script>
		
		<link type="text/css" href="lib/css/default.css" rel="stylesheet" media="all">
<?php
if(file_exists(get_base_dir() . "lib/css/custom.css"))
{
?>
		<link type="text/css" href="lib/css/custom.css" rel="stylesheet" media="all">
<?php
}
?>
		<link type="text/css" href="lib/css/<?php echo $jqtheme; ?>.css" rel="stylesheet" media="all">
		<script type="text/javascript" src="lib/js/buttons.js"></script>
		<script type="text/javascript" src="lib/js/scheck.js"></script>
		<style>
			body {min-width: 960px;}
			.controlbox label 
			{
				display: block;
				width: 150px;
				float: left;
				padding-top:2px;
				font-family: Trebuchet MS,Verdana,Arial,sans-serif; 
			}
			#bulktoolbox
			{
				min-height: 80px;	
			}
			button {height: 30px;}
			
			.ui-icon.hide-root-records { background-image: url('lib/css/img/hide_root_records.png'); }
			.ui-icon.show-root-records { background-image: url('lib/css/img/show_root_records.png'); }
			.ui-icon.import-subdomains { background-image: url('lib/css/img/import.png'); }
			
			#dialog-subdomain-upload ul.bullets
			{
			  list-style: none;
			  margin: 0px;
			  padding: 0px;
			  margin-bottom: 16px;
			}
			#dialog-subdomain-upload ul.bullets li
			{
			  text-align:left;
			  width:auto; 
			  padding: 1px;
			  padding-top: 0;
			  padding-left: 20px;
			  margin-bottom: 4px;
			  background: url(lib/css/img/ok.png) repeat-y top left; 
			  
			  margin-left: 0px;
			  line-height: 100%;
			  font-weight: normal;
			}
			#dialog-subdomain-upload ul.bullets li.lierr 
			{
				background-color: #FFA0A0;
				color: #000;
				background-image: url(lib/css/img/notok.png);
				background-repeat:	repeat-y;
				background-position: top left;
			}
		</style>

		<script type="text/javascript">
		var domGridScrollOffset = 18;
		var grid_url = 'subdomains.php?grid&noroot';
		var subdomain_row_num = 1000;
		var subdomain_rows = $.cookie('subdomain_row_num'); 
		if(subdomain_rows != 0 && subdomain_rows <= 5000 && subdomain_rows != null)
			subdomain_row_num = subdomain_rows;
		
		var report_columns_array = [
			{label:'Subdomain',name:'subdomain',width:'80',sortable:true, editable:true, editoptions:{readonly:true}, searchoptions:{sopt:['bw','ne','eq','ew','cn']}, classes:"dtcell subdomain-cell"},
			{label:'Domain',name:'domain',width:'130',editable:true, editoptions:{readonly:true}, classes:"dtcell domain-cell"},
			{label:'Type',name:'record_type',width:'60',editable:false,editoptions:{size:35}, classes:"dtcell record-type-cell"},
			{label:'Record',name:'record_value',width:'100',editable:false,editoptions:{size:35}, classes:"dtcell record-value-cell"},
			{label:'IP',name:'ip',width:'90',editable:false,editoptions:{size:35}, classes:"dtcell ip-cell"},
			{label:'SSL Expiry',name:'ssl_valid_to',width:'100',editable:false, classes:"dtcell ssl-valid-to-cell"},
			{label:'SSL Issued By',name:'ssl_issued_by',width:'100',editable:false, classes:"dtcell ssl-valid-to-cell"},
			{label:'SSL Issued To',name:'ssl_issued_to',width:'100',editable:false, classes:"dtcell ssl-valid-to-cell"},
			{label:'Hostname',name:'hostname',width:'150', sortable: false, editable:false,search:false, classes:"dtcell hostname-cell"},
			{label:'<?php echo $notes_a_label; ?>',name:'notes_a',width:'80',editable:true, classes:"dtcell notes-a-cell"},
			{label:'<?php echo $notes_b_label; ?>',name:'notes_b',width:'80',editable:true, classes:"dtcell notes-b-cell"},
			{label:'<?php echo $notes_c_label; ?>',name:'notes_c',width:'80',editable:true, classes:"dtcell notes-c-cell"},
			{label:'<?php echo $notes_d_label; ?>',name:'notes_d',width:'80',editable:true, classes:"dtcell notes-d-cell"}
			];

		if(!$.browser.msie && !$.browser.mozilla)
			domGridScrollOffset = 56+18;
	
		function addCSVTableDownloadButton()
		{
			$("#domain_table").navSeparatorAdd("#domain_pager",{})
			.navButtonAdd('#domain_pager',
			{
				caption:"", 
				buttonicon:"ui-icon-arrowthickstop-1-s", 
				onClickButton: function()
				{ 
					$('#dialog-csv-download').dialog('open');
					return false;
				}, 
				position:"last",
				title:'Download CSV...'
			});
		}

		function csvWrapQuotes(ptext)
		{
			if(typeof ptext === 'undefined' || ptext == "" || ptext == null)
				return "";
			else
			{
				ptext = ptext.trim();
				if(ptext.indexOf("\"") > -1)
				{
					while (ptext.indexOf("\"") > -1)
						ptext = ptext.replace("\"", "{{^&}}")
					while (ptext.indexOf("{{^&}}") > -1)
						ptext = ptext.replace("{{^&}}", "\"\"")
					return '"' + ptext + '"';
				}
				if (ptext.indexOf(",") > -1 || ptext.indexOf("'") > -1)
				   return '"' + ptext + '"';
				 return ptext;
			}
		}

		function downloadRows(dlType)
		{
			var rowText = "";
			var tablecolumns = [];
			var columns = jQuery("#domain_table").getGridParam("colModel");
			var colnum = columns.length;
			
			if(dlType != "alldomainnames" && dlType != "selecteddomainnames")
			{
				for(i = 0; i < colnum; i++)
				{
					if(columns[i].name != "rn" && columns[i].name != "cb" && columns[i].name != "r_h_disp")
					{
						tablecolumns.push(columns[i].name);
						var label = columns[i].label;
						rowText += csvWrapQuotes(label);
						if(i !== (colnum-1))
							rowText += ",";
						else
							rowText += "\n";
					}
				}
			}
			
			var clen = tablecolumns.length;
			var rowKey;
			if(dlType == "selectedrows" || dlType == "selecteddomainnames")
				rowKey = jQuery("#domain_table").getGridParam("selarrrow");
			else if(dlType == "allrows" || dlType == "alldomainnames")
				rowKey  = jQuery("#domain_table").getDataIDs(); 
			var rl = rowKey.length;
			for(i = 0; i < rl; i++)
			{
				var rowData = jQuery("#domain_table").jqGrid ('getRowData', rowKey[i]);
				if(dlType != "alldomainnames" && dlType != "selecteddomainnames")
				{
					for(j = 0; j < clen; j++)
					{
						if (typeof tablecolumns[j] != 'undefined') 
						{
							var entry = rowData[tablecolumns[j]];
							rowText += csvWrapQuotes(entry);
						}
						else
							rowText += "-";
						if(j != (clen-1))
							rowText += ",";
						else
							rowText += "\n";
					}
				}
				else if(typeof rowData['subdomain'] != "undefined")
					rowText += rowData['subdomain'] + "\n";
			}
			
			var posturl = "lib/php/dnloadcsv.php";
			if(dlType == "alldomainnames" || dlType == "selecteddomainnames")
				posturl += "?txt";
			$("#csvdnload").append('<form id="exportform" action="' + posturl + '" method="post"><input type="hidden" id="exportdata" name="exportdata"></form>');
			$("#exportdata").val(rowText);
			$("#exportform").submit().remove();
			return true; 
		}

		$(function()
		{
			jQuery("#domain_table").jqGrid({
			url: grid_url,
			editurl: "subdomains.php?edit",
			datatype: "json",
			altRows:true,
			altclass: "gridAltRowClass",
			scrollOffset: domGridScrollOffset,
			colModel: report_columns_array,
			rownumbers: true,
			rowNum: subdomain_row_num,
			rowList:[50,100,250,500,1000,2000,3000,5000],
			height: '300',
			width: 960,
			pager: '#domain_pager',
			sortname: 'ip',
			viewrecords: true,
			sortorder: "asc",
			multiselect: true,
			multiboxonly:true,
			caption: "Subdomain Table",
			gridComplete: function()
			{
				subdomain_row_num = $("#domain_table").jqGrid('getGridParam','rowNum');
				$.cookie('subdomain_row_num', subdomain_row_num, { expires: 30 }); 
			}
			});
			jQuery("#domain_table").jqGrid('navGrid','#domain_pager',{search:true,edit:true,add:false,del:true},{closeOnEscape:true},{},{},{multipleSearch:true,overlay:false,closeOnEscape:true});
			
			$("#domain_display_button").button().click(function() 
			{
				$("#domain_table").trigger("reloadGrid"); 
			});
			$("#domain_download_button").button().click(function() 
			{
				$("#domain_table").trigger("reloadGrid"); 
			});
			$("#csv_download_button").button().click(function() 
			{
				$("#domain_table").trigger("reloadGrid"); 
			});
			$('#importsubdomains').button({text: false, label:"Upload Data (CSV)",icons: {primary: 'import-subdomains'}});
			$("#importsubdomains").click(function(){ImportSubdomainsFromCSV();});
			
			jQuery("#domain_table").navButtonAdd('#domain_pager',
			{
				// Add domain names
				caption:"", 
				buttonicon:"ui-icon-plus", 
				onClickButton: function()
				{ 
					$('#dialog-add-subdomains').dialog('open');
					return false;
				}, 
				position:"first"
			}
			);
			
			jQuery("#domain_table").jqGrid(
				'filterToolbar',{
					stringResult: true,searchOnEnter : false
				}
			);
			
			$(window).bind('resize', function() {
				$("#domain_table").setGridWidth($(window).width()-20);
				$("#domain_table").setGridHeight($(window).height()-170);
			}).trigger('resize');
			
			addCSVTableDownloadButton();
			$( "#csv-download-radio" ).buttonset();
			
			$("#dialog-csv-download").dialog(
			{
				resizable: false,
				autoOpen: false,
				width: 450,
				
				modal: true,
				buttons: {
					'Download': function(event) {
						event.preventDefault();
						downloadRows($("#csv-download-radio :radio:checked").attr('id'));
					},
					'Cancel': function() {
						$(this).dialog('close');
					}
					
				}
			});
			
			$("#dialog-add-subdomains").dialog(
			{
				resizable: false,
				autoOpen: false,
				width: 450,
				
				modal: true,
				buttons: {
					'OK': function(event) {
						$(this).dialog('close');
						event.preventDefault();
						var user_entry_data = $("#subdomains-entry-form").serialize();
						add_subdomains(user_entry_data);
					},
					'Cancel': function() {
						$(this).dialog('close');
					}
				}
			});
			
			$("#dialog-subdomain-upload").dialog(
			{
				resizable: false,
				autoOpen: false,
				width: 450,
				
				modal: true,
				buttons: {
					'Clear': function() {
						$("#csverrors").html("&nbsp;")
					},
					'Upload': function() {
						//$(this).dialog('close');
						uploadCSVFile();
					},
					'Close': function() {
						$(this).dialog('close');
					}
					
				},
				open: function ()
				{
					$('input[type="file"]').blur();
				}
			});
			
			$( "#show_root_records" ).button({text: false, label:"All Records", icons: {primary: 'show-root-records'}}).click(function(){
				showRootButton();
			});
			
			$("#show_root_records").attr('checked');
			$("#show_root_records").button("option", {icons: { primary: "show-root-records" }, label: 'Show All Records'});
		});
		
		function add_subdomains(user_entry_data)
		{
			$.ajax({
				type: "POST",
				cache: false,
				dataType: 'json',
				url: "subdomains.php?add",
				data: user_entry_data,
				success: function(html)
				{
					$("#domain_table").trigger("reloadGrid"); 
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) 
				{ 
					if(XMLHttpRequest.status == 403)
						alert("Access Denied! No permission to add domains.");
					else
						alert("Error: " + errorThrown); 
				} 
			});
		}

		function ImportSubdomainsFromCSV()
		{
			$("#csverrors").css("height", "10px");
			$("#csverrors").html("&nbsp;");
			$('#csverrors').addClass('ui-state-default ui-corner-all');
			if ($.browser.msie  && parseInt($.browser.version, 10) < 10) 
				alert("CSV upload is not supported in IE9 and below.");
			else
				$('#dialog-subdomain-upload').dialog('open');
			return false;
		}
		
		function uploadCSVFile()
		{
			$("#csverrors").css("height", "150px");
			data = new FormData($('#subdomain-upload')[0]);
			$("#csverrors").html("Please wait...");
			if(data != "")
			{
				$.ajax({
					type: 'POST',
					url: 'subdomains.php?upload',
					data: data,
					cache: false,
					contentType: false,
					processData: false
				}).done(function(data) {
					var x = jQuery.parseJSON(data);
					$("#csverrors").html(x.msg);
					$("#domain_table").trigger("reloadGrid");
				}).fail(function(jqXHR,status, errorThrown) {
					//console.log(errorThrown);
					//console.log(jqXHR.responseText);
					//console.log(jqXHR.status);
					if(jqXHR.status == 403)
						alert("Access Denied! No permission to edit.");
					else if(jqXHR.status == 400)
						alert("Invalid Session. Please login again.");
					else if(jqXHR.status == 408)
						alert("Session timeout. Please login again.");
				});
			}
			else
				$("#csverrors").html("Nothing to upload!");
		}

		function showRootButton()
		{
			if(grid_url == 'subdomains.php?grid')
			{
				grid_url = 'subdomains.php?grid&noroot';
				jQuery("#domain_table").setGridParam({url:grid_url});
				$("#domain_table").trigger("reloadGrid"); 
				$("#show_root_records").removeAttr('checked');
				$("#show_root_records").button("option", {icons: { primary: "show-root-records" }, label: 'Show All Records'});
			}
			else
			{
				grid_url = 'subdomains.php?grid';
				jQuery("#domain_table").setGridParam({url:grid_url});
				$("#domain_table").trigger("reloadGrid"); 
				$("#show_root_records").attr('checked', 'checked');
				$("#show_root_records").button("option", {icons: { primary: "hide-root-records" }, label: 'Show Main Records'});
			}
		}
		
		</script>
<?php
		if(get_main_logo_image() != "")
			echo "\t\t<style> .mainlogo {background-image: url('" . get_main_logo_image() . "');}</style>\n";
?>
</head>
<body>
	<div id="header">
		<div class="mainlogo">&nbsp;</div>
		<div class="navbar">
				<button id="importsubdomains"></button>
				&nbsp;&nbsp;
				<button id="show_root_records"></button>
				&nbsp;&nbsp;
				<button id="menu"></button>
				&nbsp;&nbsp;
				<button id="pfolio"></button>
				&nbsp;&nbsp;
				<button id="runq"></button>
		<?php
			if(is_admin_user())
			{
		?>
				<button id="report"></button>
				<button id="config"></button>
				<button id="appsetup"></button>
				<button id="admin"></button>
		<?php
			}
			show_link_buttons();
			if(is_user_auth_enabled())
			{
		?>
				&nbsp;&nbsp;
				<button id="logout"></button>
		<?php
			}
		?>
		</div>
		<div class="clear">&nbsp;</div>
	</div>
	
	<div id="BulkViewPane">
		<div id="bulkgrid" style="padding:10px;">
			<table id="domain_table"></table>
			<div id="domain_pager"></div>
		</div>
	</div>
	
	<div id="dialog-csv-download" title="CSV File Download">
		<br>
		<h3 class="center">Select What To Download and then Click 'Download'</h3>
		<div id="csvdnload"></div>
		<br><br>
		<form>
			<div style="text-align:center;">
				<div id="csv-download-radio">
					<input type="radio" id="selectedrows" name="csv-download-radio"><label for="selectedrows">Selected Rows</label>
					<input type="radio" id="allrows" name="csv-download-radio" checked="checked"><label for="allrows">All Rows</label>
					<input type="radio" id="selecteddomainnames" name="csv-download-radio"><label for="selecteddomainnames">Selected Subdomains</label>
					<input type="radio" id="alldomainnames" name="csv-download-radio"><label for="alldomainnames">All Subdomains</label>
				</div>
			</div>
		</form>
		<br><br>
	</div>
	
	<div id="dialog-add-subdomains" title="Add Sub-domains">
		<form id="subdomains-entry-form">
		<div style="padding: 10px; text-align:left;">
			<input type="hidden" id="lgptoken" name="lgptoken" value="<?php echo_form_token('subdomains-entry-form'); ?>">
			<label for="ui_subdomains" id="subdomains_label">Sub-domains To Add. Please enter one entry per row, 
			with each entry as subdomain, a comma and the domain (eg. support,softnik.com) or as hostnames (support.softnik.com). 
			If you enter full hostnames the entry before the first dot will be taken as the subdomain.</label>
			<br><br>
			<textarea rows="15" id="ui_subdomains" name="ui_subdomains" cols="40" style="width:400px;"></textarea>
		</div>
		</form>
	</div>
	
	<div id="dialog-subdomain-upload" title="Subdomain Data Upload">
		<br>
		<form id="subdomain-upload" class="fileupload" action="subdomains.php" method="post" enctype="multipart/form-data">
		<p><label for="file">CSV File Name:</label>
		<input type="file" name="csv_file" id="csv_file"></p>
		<br>
		<label for csv_sep>Separator: </label>
		<select id="csv_sep" name="csv_sep">
		  <option value=",">Comma</option>
		  <option value=";">Semi Colon</option>
		  <option value="t">Tab</option>
		</select>
		<br><br>
		
		<div class="dotline"></div>
		
		<p>The CSV File should have a heading row that contains the field names. If the Upload
		fails, please check the encoding of the file ('UTF-8 without BOM' will always work).</p>
		
		<p>The supported columns are hostname, notes_a, notes_b, notes_c, notes_d.</p>
		
		<p>Please use this with care. Do not try to upload huge / binary files.</p>
		
		<p>This will not work in IE9 and less.</p>
		
		<div id="csverrors">&nbsp;</div>
		
		<p>Click 'Close' when you are done.</p>
		</form>
	</div>
		
</body>
</html>
<?php
?>
