<?php
###############################################################################
# kwdomains.php
# Track daily domains from zone that contain specified keywords
#
# @author Anil Kumar <akumar@codepunch.com>
# @link   https://codepunch.com
#
# Created on: Dec 8 2018

# Last modified on: Jan 23 2019
#
# Additions
#
# Combined all files so that there is only a single kwdomains.php file
# Added the tag option to tag domains with a number between 0 and 16
# Improved the Interface (bigger font, better layout)
#
###############################################################################
#
# Rename thirdparty/config-sample.php to config.php
# Edit it to include the "api key" and "secret key" for domain name data feed
#
# Create a text file containing the keywords you want to track (one keyword per row)
# save it as keywords.txt to the thirdparty folder.
# You can use % to specify keyword position
# %apple -> domains ending in apple
# apple -> domain that contain apple
# apple% -> domains that start with apple
#
# Run kwdomains.php as a cron-job once a day to insert data into the
# domain table.
#
# examples.
#
# 0 2 * * * php /path/to/wmdsed3/thirdparty/kwdomains.php >/dev/null 2>&1
#
# or
#
# 0 2 * * * wget -q -O /dev/null "http://<install-url>/thirdparty/kwdomains.php" >/dev/null 2>&1
#
# You can use tlds=  to specify which TLDs to track. Default is com,net,org,biz,info
#
# php /path/to/wmdsed3/thirdparty/kwdomains.php tlds=com,net,org
#
###############################################################################

require_once(dirname(__FILE__) . "/../include.php");
require_once(dirname(__FILE__) . "/config.check.php");
require_once(dirname(__FILE__) . "/../lib/php/idn/idn.php");

###############################################################################
# Parse command line if running in CLI

if(is_cli()) {
	parse_str(implode('&', array_slice($argv, 1)), $_REQUEST);
}
else {
	$isgrid = isset($_REQUEST['grid']) ? true : false;
	$isfile = isset($_REQUEST['file']) ? true : false;
	if($isfile) {
		doExportData();
		exit;
	}
	else if($isgrid) {
		domainGrid();
		exit;
	}
	else {
		doAuthentication("thirdparty/kwdomains.php");
		showInterface();
		exit;
	}
}

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

function doExportData()
{
	$auth = validateSession(isRequestCommand("nsi") ? false : true);
	if($auth == 0) {
		$filename = getRequestVariable("file", "");
		$csvdata = stripslashes($_REQUEST['exportdata']);
		header('Content-Encoding: UTF-8');
		if(stristr($filename, ".txt") !== false)
			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');
		echo $csvdata;
	}
	else
		header("Location: /login.php");
	exit;
}

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

function domainGrid()
{
	global $db_table_prefix;
	$kwtable = $db_table_prefix . "kwdomains";
	$auth = validateSession(isRequestCommand("nsi") ? false : true);
	$pdo = init_db(false);
	
	if($auth == 0 && $pdo !== false) {
		$oper = getRequestVariable("oper", "");
		if($oper == "edit") {
			$response = array('status'=>"notok", 'validate'=>$auth);
			if(isset($_REQUEST['level']) && isset($_REQUEST['id'])) {
				$level = getNumericRequestVariable("level", 0);
				if($level < 0 || $level > 16)
					$level = 0;
				$id = getNumericRequestVariable("id", 0);
				if($pdo->updateTable($kwtable, "level=? WHERE id=?", array($level,$id)) === false) 
					$response['error'] = $pdo->getLastError();
				else
					$response['status'] = "ok";
			}
			echo json_encode($response);
			exit;
		}
		else if($oper == "del") {
			$response = array('status'=>"notok", 'validate'=>$auth);
			$id = getNumericRequestVariable("id", 0);
			if($id > 0) {
				if($pdo->deleteFromTable($kwtable, "id=?", array($id)) === false) 
					$response['error'] = $pdo->getLastError();
				else
					$response['status'] = "ok";
			}
			echo json_encode($response);
			exit;
		}
		$columns = "id,domain,tld,level,zonedate";
		$response = new stdClass();
		if($pdo->jqGridCount($kwtable, "id", $response)) {
			if($pdo->jqGridData($kwtable, "id", $columns, $response)) {
			}
		}
		echo json_encode($response);
	}
	else
		invalidSessionQuit();
	exit;
}

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

loginIfRequired();

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

if(!function_exists('curl_version')) {
	smartEcho("Please install php-curl.");
	exit;
}

###############################################################################
# Get Command-line

$droptable = isset($_REQUEST['--drop']) ? true : false;
$tlds = getRequestVariable("tlds", "com,net,org,biz,info");
$zonedate = getRequestVariable("date", date("Ymd", time()-3600*24));

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

$keywords = getRequestVariable("kw", "");
if($keywords == "") {
	$kwfile = get_install_folder_path() . "thirdparty/keywords.txt";
	$keywords = file_get_contents($kwfile);
}
if($keywords != "") {
	$kws = array_filter(explode("\n", $keywords));
	foreach($kws as &$k) {
		$k = trim($k);
		if(strpos($k, '%') === false)
			$k = urlencode('%' . $k . '%');
	}
	$keywords = implode("#", $kws);
}

###############################################################################
# Open the Domain Database

$pdo = init_db();
if($pdo === false) {
	smartEcho("Unable to connect to database");
	exit;
}

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

$kwtable = $db_table_prefix . "kwdomains";
if($droptable) {
	if(!dropTable($kwtable)) {
		echo "Unable to drop $kwtable\n";
		echo $pdo->getLastError();
	}
	echo "$kwtable dropped\n";
}
$missing = $pdo->testIfTablesExist(array($kwtable));
if(count($missing)) {
	$columns[] = "id";
	$columns[] = "bigint(20)";
	$columns[] = "NOT NULL AUTO_INCREMENT";
		
	$columns[] = "domain";
	$columns[] = "varchar(256)";
	$columns[] = "CHARACTER SET utf8 COLLATE utf8_bin NOT NULL";
	
	$columns[] = "tld";
	$columns[] = "varchar(32)";
	$columns[] = "NOT NULL DEFAULT ''";
	
	$columns[] = "zonedate";
	$columns[] = "date";
	$columns[] = "DEFAULT NULL";
	
	$columns[] = "level";
	$columns[] = "tinyint(1)";
	$columns[] = "DEFAULT NULL";
	if($pdo->createTable($kwtable, $columns, "PRIMARY KEY (id),UNIQUE KEY domain(domain),INDEX(zonedate),INDEX(level),INDEX(tld)") !== false)
		echo "$kwtable created\n";
	else {
		echo "Unable to create $idxtable\n";
		exit(1);
	}
}

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

add_domains($zonedate, $tlds, $keywords);

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

function add_domains($zonedate="", $tlds="", $keywords="") {
	$starttime = microtime(true);
	$kws = array_filter(explode("#", $keywords));
	if(count($kws)) {
		foreach($kws as $kw)
			add_domains_by_tld($zonedate,$tlds,$kw);
	}
	else
		add_domains_by_tld($zonedate,$tlds,$keywords);
	$endtime = microtime(true);
	$timediff = $endtime - $starttime;
	smartEcho(seconds_to_time($timediff));
}

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

function dropTable($tablename) {
	global $pdo;
	try {
		$sql = "DROP TABLE " . $tablename;
		$q = $pdo->db_connect_handle->prepare($sql);
		$q->execute();
		return true;
	}
	catch (PDOException $e)  {
		$pdo->setError($e->getMessage());
		return false;
	}
}

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

function curl_get_url($url, $timeout=10) {
	$retv = array('result' => "", 'status' => 0);
	if(function_exists('curl_version')) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		$retv['result'] = curl_exec ($ch);
		$retv['result'] = ($retv['result'] === false) ? "" : $retv['result'];
		$retv['status'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close ($ch);
	}
	return $retv;
}

###########################################################################
		
function starts_with($string, $starts_with) {
	return strncmp($string, $starts_with, strlen($starts_with)) === 0;
}

###############################################################################
	
function seconds_to_time($seconds)  {
	$dtF = new \DateTime("@0");
	$seconds = round($seconds,0,PHP_ROUND_HALF_UP);
	$dtT = new \DateTime("@" . $seconds);
	return $dtF->diff($dtT)->format('%a:%h:%i:%s');
}

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

function add_domains_by_tld($zonedate="",$tld="",$keyword="") {
	global $dnfeed_api_key, $dnfeed_secret_key, $db_table_prefix, $pdo, $kwtable;
	$table = $kwtable;
	
	$url = "https://api.codepunch.com/dnfeed3.php?c=auth&k={$dnfeed_api_key}&s={$dnfeed_secret_key}";
	$authinfo = curl_get_url($url, 10);
	
	if(isset($authinfo['result'])) {
		$token = $authinfo['result'];
		if(starts_with($token, "OK:")) {
			$token = trim(str_replace("OK:", "", $token));
			$url = "https://api.codepunch.com/dnfeed3.php?t={$token}&idn=0&src=added&d={$zonedate}&m=stats&c=eq&z={$tld}&kw={$keyword}";
			$ddata = curl_get_url($url, 10);
			if(isset($ddata['result'])) {
				$total_added = 0;
				$count = intval($ddata['result']);
				if($count) {
					$starttime = microtime(true);
					$pagesize = 5000;
					$pages = $count / $pagesize + 1;
					for($i = 0; $i < $pages; $i++) {
						$start = $i*$pagesize;
						$url = "https://api.codepunch.com/dnfeed3.php?t={$token}&idn=0&d={$zonedate}&src=added&start=$start&limit=$pagesize&f=text&c=eq&z=$tld&kw={$keyword}";
						$ddata = curl_get_url($url, 30);
						if(isset($ddata['result'])) {
							$domains = array_filter(explode("\n", $ddata['result']));
							if(count($domains)) {
								$timestamp = date("Y-m-d H:i:s");
								$values = "";
								foreach($domains as $domain) {
									$pos = mb_strrpos($domain, ".");
									if($pos !== false) {
										$thistld = mb_substr($domain, $pos+1);
										$length = $pos;
										$values .= "('{$domain}','{$zonedate}','{$thistld}'),";
									}
								}
								$values = rtrim($values, ",");
								try {
									$sql = "INSERT IGNORE INTO $table (domain,zonedate,tld) VALUES " . $values;
									$q = $pdo->db_connect_handle->prepare($sql);
									$q->execute(array());
									$total_added += $q->rowCount();
									smartEcho("$added $tld domains containing $keyword added ($total_added/$count)");
								}
								catch (PDOException $e) {
									$pdo->setError($e->getMessage());
									smartEcho("Database update Failed, " . $pdo->get_last_error() . "\n" . $sql);
								}
							}
						}
					}
					$endtime = microtime(true);
					$timediff = $endtime - $starttime;
					smartEcho("\t".seconds_to_time($timediff));
				}
				else {
					smartEcho("Nothing found for $tld domains containing $keyword");
				}
			}
		}
	}
}

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

function showInterface()
{
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="shortcut icon" type="image/x-icon" href="../lib/css/images/favicon.ico">
	<meta name="author" content="">
	<title>Watch My Domains SED</title>
	<meta name="description" content="">
	<meta name="keywords" content="">
	<meta name="dcterms.rightsHolder" content="Softnik Technologies">
	<link rel="stylesheet" type="text/css" media="screen" href="../lib/css/jquery-ui/themes/redmond/jquery-ui.min.css">
	<link rel="stylesheet" type="text/css" media="screen" href="../lib/css/jqgrid/ui.jqgrid.min.css">
	<link href="../lib/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet">
	<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
	<!--[if lt IE 9]>
	  <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
	  <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
	<![endif]-->
	<link href="../lib/css/default.css" rel="stylesheet">
	<link href="../lib/css/noroundc.css" rel="stylesheet">
	<link href="../lib/css/nobg.css" rel="stylesheet">
	<link href="../lib/layouts/fonts/Dosis-regular/fonts.css" rel="stylesheet">
	<link href="../lib/layouts/fonts/Droid-Sans-regular/fonts.css" rel="stylesheet">
	<link href="../lib/layouts/fonts/Oswald/fonts.css" rel="stylesheet">
	<style>
	
	.dtcell a {
		color: #808080;
	}
	.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default
	{
		background: none;
		background-color: #E0F0FF;
	}

	.ui-widget input {font-size: 15px;}

	.ui-widget.ui-widget-content {
		padding: 2px;
	}


	td.dtcell {padding-left: 5px !important;} 

	.ui-jqgrid .ui-jqgrid-htable th,
	.ui-jqgrid tr.jqgrow td, .ui-pg-table td 
	{
		height: 1.9em !important;
	}

	.ui-state-active a, .ui-state-hover a, .ui-state-visited a, .ui-state-focus a  {
		outline: none;
	}
	
	.ui-state-hover {
		background-image: none;
	}

	.ui-pg-button, .ui-button-icon-only, .btn, .ui-button, .ui-corner-all .ui-jqdialog-titlebar-close, .ui-slider-handle
	{
		outline-color: transparent;
		outline: none;
	}

	.ui-search-input > input,
	.ui-pg-selbox, .input-elm, .opsel, .selectopts, .selectLabel, .fm-button,
	.FormElement,
	.btn:focus,.btn:active:focus,.btn.active:focus,
	.ui-jqgrid>.ui-jqgrid-view input,
	.ui-widget textarea:focus,
	.ui-slider-handle:focus
	{
		outline: none;
		box-shadow: none;
	}

	.ui-search-input {text-align: left;}

	.ui-jqgrid .ui-jqgrid-htable th.ui-th-ltr, .ui-th-ltr  {
		border-bottom: none;
	}

	.ui-jqgrid .searchFilter table  {
		border-collapse: separate; 
		border-spacing: 2px 10px;
	}

	.vertical-center {
	  min-height: 100%;  /* Fallback for browsers do NOT support vh unit */
	  min-height: 100vh; /* These two lines are counted as one :-)       */

	  display: flex;
	  align-items: center;
	}

	.ui-tabs .ui-tabs-panel {
		padding: 10px;
	}

	.ui-tabs .ui-tabs-nav {border:none; padding-left: 10px; min-height: 37px;}

	.ui-tabs .ui-tabs-nav li
	{
		border:none;
	}

	.ui-tabs .ui-tabs-nav li.ui-tabs-active 
	{
		border:none;
	}

	::-webkit-scrollbar {
		width: 12px;
	}

	::-webkit-scrollbar-track
	{
		background-color: rgba(255,255,255,1);
		-webkit-box-shadow: none; 
		-webkit-border-radius: 1px;
		border-radius: 1px;
	}

	::-webkit-scrollbar-thumb
	{
		background-color: rgba(210,240,255,0.9);
		-webkit-border-radius: 1px;
		border-radius: 1px;
		-webkit-box-shadow: none;
		background-image: none;
	}

	::-webkit-scrollbar-thumb:vertical {
	}

	h1,h2,h3,h4,h5,h6 {font-family: Coda;}

	h1,h2,h3,h4 {
		background-image: linear-gradient(to right,  rgba(240,240,240,0.1), rgba(240,240,240,0.15), rgba(240,240,240,0.1)), url(images/bg/square_grip.png);
		margin-bottom: 30px;
		margin-top: 0px;
		padding: 10px 5px 10px 5px;
		text-transform: uppercase;
		text-align: center;
	}

	h1 { font-size: 28px;}

	h3 {
		font-size: 20px;
	}

	h5 {font-size: 16px;}

	#editcntDomainTable {
		background-color: #FFFFFF;
	}
	
	.gridAltRowClass {
		background-color: #FAFAFA;
	}
	</style>
	<script type="text/javascript">
	</script>
</head>
<body>

<div class="container-fluid" id="header">
	<div class="row">
		<div class="col-sm-4">
			<a href="../menu.php"><img id="logo" src="../lib/css/images/logo-small-dark.png" alt="Watch My Domains SED"></a>
		</div>
		<div class="col-sm-8 text-right">
		</div>
	</div>
</div>

<div class="container-fluid1" id="content">
	<div class="row1">
		<div class="col-sm-121">
			<table id="DomainTable"></table>
			<div id="DomainTablePager"></div>
		</div>
	</div>
</div>
<div id="csvdnload"></div>
<script type="text/javascript" src="../lib/jquery/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="../lib/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../lib/jquery/jquery-ui/jquery-ui.min.js"></script>
<script type="text/javascript" src="../lib/jquery/jqgrid/i18n/min/grid.locale-en.js"></script>
<script type="text/javascript" src="../lib/jquery/jqgrid/jquery.jqgrid.min.js"></script>
<script type="text/javascript" src="../lib/jquery/jquery.matchHeight-min.js"></script>
<script type="text/javascript" src="../lib/jquery/jquery.cookie.js"></script>
<script type="text/javascript" src="../lib/js/split/split.min.js"></script>
<script type="text/javascript" src="../lib/js/basic.js"></script>
<script type="text/javascript">
var domain_columns_array = [
		{label:'Domain',name:'domain',width:'150', editable:false, classes:"dtcell",searchoptions:{sopt:['bw','cn','ew','eq']},formatter: 'showlink', formatoptions: { baseLinkUrl: 'javascript:', showAction: "Link('", addParam: "');"}},
		{label:'TLD',name:'tld',width:'90', editable:false, fixed: true, classes:"dtcell",align: 'center'},
		{label:'Date',name:'zonedate',width:'90', editable:false, classes:"dtcell",fixed: true, align: 'center',searchoptions:{sopt:['bw','cn','ew','eq']}},
		{label:'Tag',name:'level',width:'70', editable:true, classes:"dtcell", align: 'center', fixed: true, formatter:'integer', searchoptions:{sopt:['eq']}}
	];
	
var ajax_grid_url = "../thirdparty/kwdomains.php";

$(function()
{
	initInterfaceDivs();
	
	var gridurl = ajax_grid_url + "?grid";
	var editurl = gridurl;
	domain_table_grid = LoadDomainGrid("DomainTable", "DomainTablePager", gridurl, editurl, domain_columns_array, "", "domain");
	
	$("body").fadeIn(1000);
	$(window).bind('resize', function() {fixDivSizes(); setTimeout(function(){fixDivSizes();}, 50);}).trigger('resize');
});

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

function setTableFontSize(fs)
{
	var hfs = fs-1;
	// Change the font size in the jqgrid (titlebar, grid and pager)
	$('.ui-jqgrid-btable').css('font-size', fs+'px');
	$('.ui-pg-table').css('font-size', fs+'px');
	$('.ui-jqgrid-htable').css('font-size', hfs+'px');
	$('.ui-jqgrid-title').css('font-size', hfs+'px');
	$('.ui-search-input > input').css('font-size', fs+'px');
	
	// Change the Tab View font size.
	var tbfs = fs-1;
	
	$('.ui-jqdialog').css('font-size', fs+'px');
	$('.ui-autocomplete').css('font-size', fs+'px');
	
	$('.ui-widget-content').css('font-family', "Coda,\'Droid Sans\',sans-serif");
	
	$('.btn').css('font-size', tbfs+'px');
}


function fixDivSizes()
{
	setTableFontSize(15);
	if($(window).width() < 768 || $(window).height() < 500) {
		var dth = $(window).height() - $('#header').height();
		$('#content').css('height', dth);
		$('#content').css('width', '100%');		
	}
	else {
		var mih = $(window).height()-10- $('#header').height();
		$('#content').css('height', mih);
	}
	positionDomainGrid();
}

function LoadDomainGrid(gridtable, pagertable, gridurl, editurl, col_model_array, title, sortid)
{
	var hidegrid = true;	
	var sortorder = 'asc';
	var rowsinpage = 500;
	var scrolloption = 0;
	var rowlist = [500,1000,2000];

	if($(window).width() < 768)
	{
		hidegrid = false;
		rowsinpage = 100;
		scrolloption = 0;
	}
	var the_grid = jQuery("#" + gridtable).jqGrid({
		hidegrid: hidegrid,
		height: 400,
		width: 451,
		altRows:true,
		altclass: "gridAltRowClass",
		url: gridurl,
		editurl: editurl,
		datatype: "json",
		jsonReader : {repeatitems: false},
		colModel:col_model_array,
		rowNum: rowsinpage,
		rowList: rowlist,
		rownumWidth: 50,
		recordtext: "{0}-{1}/{2}",
		rownumbers: true,
		viewrecords: true,
		gridView: true,
		caption:title,
		pgtext: '', 
		multiselect: false,
		pager: "#" + pagertable,
		scrollOffset:18,
		sortname: sortid,
		sortorder: sortorder,
		shrinkToFit: true,
		scroll: scrolloption,
		loadError: function (jqXHR, textStatus, errorThrown) 
		{
			showGridLoadError(jqXHR, textStatus, errorThrown);
		},
		onSelectRow: function(ids) 
		{
			//GridRowSelected(gridtable, ids);
		},
		beforeSelectRow: function(rowid, e) 
		{
			if ($(this).getGridParam('selrow') == rowid) 
				return false;
			else
				return true;
        },
		loadComplete : function () 
		{
			//GridLoadComplete(gridtable);
        },
		beforeRequest: function() 
		{
		}
	});
	
	var doadd = false;
	var doedit = true;
	var dodel = true;
	
	jQuery("#" + gridtable).navGrid('#' + pagertable, {add:doadd,edit:doedit,del:dodel,search:false},
	{	// Edit
		width: 450,
		editCaption: "Edit " + title,
		viewPagerButtons: false,
		closeOnEscape:true,
		afterShowForm: function(form) 
		{
			centerDialog('editmod' + gridtable);
		},
		afterComplete:function() 
		{
			GenericGridRowChanged(gridtable);
		}
	},
	{	// Add
		width: 450,
		addCaption: "Add " + title,
		closeOnEscape:true,
		closeAfterAdd: true,
		afterShowForm: function(form) 
		{
			centerDialog('editmod' + gridtable);
		},
		afterComplete:function() 
		{
			GenericGridRowChanged(gridtable);
		}
	},
	{	// Delete
		width: 'auto',
		closeOnEscape:true,
		afterShowForm: function(form) 
		{
			centerDialog('delmod' + gridtable);
		},
		afterComplete:function() 
		{
			GenericGridRowChanged(gridtable);
		}
	}
	);
	
	the_grid.navSeparatorAdd("#"+pagertable,{})
	.navSeparatorAdd("#DomainTablePager",{})
	.navButtonAdd('#'+pagertable,
	{
		caption:"", 
		buttonicon:"ui-icon-arrowthick-1-s", 
		onClickButton: function()
		{ 
			downloadRows(gridtable, "csv")
			return false;
		}, 
		position:"last",
		title:'Download CSV'
	})
	.navButtonAdd('#'+pagertable,
	{
		caption:"", 
		buttonicon:"ui-icon-document", 
		onClickButton: function()
		{ 
			downloadRows(gridtable, "domainnames")
			return false;
		}, 
		position:"last",
		title:'Download List'
	});
	
	jQuery("#"+gridtable).jqGrid(
		'filterToolbar',{
			stringResult: true,
			searchOnEnter : false,
			searchOperators: true
		}
	);
	
	return the_grid;
}


function positionDomainGrid()
{
	if($('#DomainTable').is(':visible'))
	{
		var dtw = $("#content").width();
		var dth = $('#content').height();
		var title_height = $('#gview_DomainTable').find('.ui-jqgrid-titlebar').outerHeight();
		var pager_height = $('#pg_DomainTablePager').height();
		var header_height = $('#gbox_DomainTable').find('.ui-jqgrid-htable').outerHeight();
		jQuery("#DomainTable").setGridWidth(dtw-10, true); 
		jQuery("#DomainTable").setGridHeight(dth-pager_height-title_height-header_height); 
	}
}

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

function showGridLoadError(jqXHR, textStatus, errorThrown)
{
	if(jqXHR.status == 503)
		alert("Status Code: " + jqXHR.status + "\n" + errorThrown);
}

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

function downloadRows(gridtable, dlType)
{
	var rowText = "";
	var tablecolumns = [];
	var columns = jQuery("#"+gridtable).getGridParam("colModel");
	var colnum = columns.length;
	
	if(dlType == "csv")
	{
		for(i = 0; i < colnum; i++)
		{
			if(columns[i].name != "rn" && columns[i].name != "cb" && columns[i].name != "r_h_disp" && columns[i].name != "subgrid" && columns[i].name != "zoneid")
			{
				tablecolumns.push(columns[i].name);
				var label = columns[i].label;
				rowText += csvWrapQuotes(label);
				if(i !== (colnum-1))
					rowText += ",";
				else
					rowText += "\n";
			}
		}
	}
	var len = rowText.length;
    if (rowText.substr(len-1,1) == ",") 
        rowText = rowText.substring(0,len-1);
	rowText = $.trim(rowText);
	if(dlType == "csv")
		rowText += "\n";
	
	var colname = "domain";
	var clen = tablecolumns.length;
	var rowKey = jQuery("#" + gridtable).getDataIDs(); 
	var rl = rowKey.length;
	for(i = 0; i < rl; i++)
	{
		var rowData = jQuery("#" + gridtable).jqGrid ('getRowData', rowKey[i]);
		if(dlType != "domainnames")
		{
			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
			rowText += rowData[colname] + "\n";
	}
	
	var today = new Date();
	var dd = today.getDate();
	var mm = today.getMonth() + 1; //January is 0!
	var yyyy = today.getFullYear();

	if (dd < 10) {
	  dd = '0' + dd;
	}

	if (mm < 10) {
	  mm = '0' + mm;
	}

	today = mm + '_' + dd + '_' + yyyy;

	var posturl = ajax_grid_url + "?file=domains_" + today;
	if(dlType == "csv")
		posturl += ".csv";
	else
		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 GenericGridRowChanged(tableid)
{
}

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

function centerDialog(dlgid)
{
	var dlgDiv = $("#"+dlgid);
	var parentDiv = dlgDiv.parent(); 
	var dlgWidth = dlgDiv.width();
	var parentWidth = parentDiv.width();
	var dlgHeight = dlgDiv.height();
	var parentHeight = parentDiv.height();
	// TODO: change parentWidth and parentHeight in case of the grid
	//       is larger as the browser window
	dlgDiv[0].style.top = Math.round((parentHeight-dlgHeight)/2) + "px";
	dlgDiv[0].style.left = Math.round((parentWidth-dlgWidth)/2) + "px";
}

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

function Link(id) {

    var row = id.split("=");
    var row_ID = row[1];
    var sitename= $("#DomainTable").getCell(row_ID, 'domain');
    var url = "http://"+sitename; // sitename will be like google.com or yahoo.com
    window.open(url);
}
</script>
</body>
</html>
<?php
}

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

?>
