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

define("NO_SESSION_SWIPEIN", 				"nsi");
define("GET_REGISTRAR_ALIAS", 				"gra");
define("GET_ABOUT_INFO", 					"gai");
define("SAVE_BASIC_APP_SETTING", 			"opset");
define("GET_BASIC_APP_SETTINGS", 			"gba");
define("PARSE_WHOIS_AGAIN", 				"pwa");
define("GET_ALL_DOMAIN_COLUMNS",			"gacol");
define("ASA_GET_USER_ADMIN_DATA",			"gua");
define("ASA_ADD_TO_CATEGORIES",				"atc");
define("ASA_REMOVE_FROM_CATEGORIES",		"rfc");
define("ASA_SAVE_QUERY_AS_AUTOQUERY",		"scqa");
define("ASA_DELETE_CUSTOM_COLUMN",			"dcc");
define("ASA_INSERT_CUSTOM_COLUMN",			"icc");
define("ASA_BULK_EDIT_COLUMN",				"bec");
define("ASA_BULK_EDIT_SD_COLUMN",			"besdc");
define("ASA_GET_EDITABLE_DOMAIN_COLUMNS",	"gedc");
define("ASA_SAVE_SUPER_ADMIN",				"ssau");
define("ASA_SAVE_USER_DETAILS",				"sud");
define("ASA_GET_USER_DETAILS",				"gud");
define("ASA_GET_EDITABLE_SUBDOMAIN_COLUMNS", "gesdc");
define("ASA_GET_SERVER_STATUS_TABLE", 		"gsst");
define("ASA_CLEAR_SERVER_STATUS_TABLE", 	"csst");
define("ASA_SET_USER_PASSWORD",				"sup");
define("ASA_RESET_DOMAIN_MANUAL_EDIT",		"rmed");
define("ASA_RESET_SUBDOMAIN_MANUAL_EDIT",	"rmesd");
define("ASA_DELETE_ORPHAN_COLUMN",			"doc");

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

if(
	isset($_REQUEST[ASA_GET_USER_ADMIN_DATA]) || 
	isset($_REQUEST[ASA_GET_USER_DETAILS]) ||
	isset($_REQUEST[ASA_SAVE_USER_DETAILS]) ||
	isset($_REQUEST[ASA_SET_USER_PASSWORD])
	)
	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("../version.php");
require_once("../idn/idn.php");
require_once("../lookups/whois.php");

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

$auth = validateSession(isRequestCommand(NO_SESSION_SWIPEIN) ? false : true);

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

$response = array('validate'=>$auth);

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

if($auth == 0)
{
	$pdo = init_db(false);
	if($pdo !== false)
	{
		if(isRequestCommand(ASA_ADD_TO_CATEGORIES))
			doAddToCategories($pdo, $response);
		else if(isRequestCommand(ASA_REMOVE_FROM_CATEGORIES))
			doDeleteFromCategories($pdo, $response);
		else if(isRequestCommand(ASA_SAVE_QUERY_AS_AUTOQUERY))
			doSaveCustomQuerySQL($pdo, $response);
		else if(isRequestCommand(ASA_INSERT_CUSTOM_COLUMN))
			doInsertCustomColumn($pdo, $response);
		else if(isRequestCommand(ASA_DELETE_CUSTOM_COLUMN))
			doDeleteCustomColumn($pdo, $response);
		else if(isRequestCommand(ASA_DELETE_ORPHAN_COLUMN))
			doDeleteOrphanColumn($pdo, $response);
		else if(isRequestCommand(ASA_BULK_EDIT_COLUMN))
			doBulkEditColumn($pdo, $response);
		else if(isRequestCommand(ASA_BULK_EDIT_SD_COLUMN))
			doBulkEditSubdomainColumn($pdo, $response);
		else if(isRequestCommand(ASA_SAVE_SUPER_ADMIN))
			doSaveSuperAdmin($pdo, $response);
		else if(isRequestCommand(ASA_SAVE_USER_DETAILS))
			doSaveUserDetails($pdo, $response);
		else if(isRequestCommand(ASA_GET_USER_DETAILS))
			doGetUserDetails($pdo, $response);
		else if(isRequestCommand(ASA_SET_USER_PASSWORD))
			doSaveUserPassword($pdo, $response);
		else if(isRequestCommand(ASA_RESET_DOMAIN_MANUAL_EDIT))
			doResetDomainManualEdit($pdo, $response);
		else if(isRequestCommand(ASA_RESET_SUBDOMAIN_MANUAL_EDIT))
			doResetSubdomainManualEdit($pdo, $response);
		else if(isRequestCommand(GET_ABOUT_INFO))
		{
			$info = getApplicationData();
			$response['version'] = get_version();
			$response['build'] = get_build_date();
			$response['orderid'] = $info['purchase_id'];
			$response['orderdate'] = $info['purchase_date'];
			$response['licensee'] = $info['licensee_name'];
			$response['edition'] = $info['license_type'];
			$response['expiry'] = $info['days_left_in_demo'];
			echo json_encode($response);
		}
		else if(isRequestCommand(SAVE_BASIC_APP_SETTING))
		{
			require_once("../config/rc4two.php");
			$response['status'] = "notok";
			$response['error'] = "";
			if(isAdminUser() == false)
				noPermissionQuit();
			$key = $_REQUEST[SAVE_BASIC_APP_SETTING];
			$value = getRequestVariable("value", "");
			if(mb_strpos($key, ",") !== false)
			{
				$mkeys = explode(",", $key);
				$mvals  = explode(",", $value);
			}
			else
			{
				# Single Key.
				$mkeys[] = $key;
				$mvals[] = $value;
			}
			$c1 = count($mkeys);
			$c2 = count($mvals);
			$set = 0;
			if($c1 == $c2)
			{
				for($i = 0; $i < $c1; $i++)
				{
					$mkey = $mkeys[$i];
					$mval = $mvals[$i];
					if($mkey == "email_smtp_password" || $mkey == "cli_auth_key_code")
						$mval = rc4two($mval . substr(md5(uniqid(rand(), true)), 0, 25), md5("160119661604199705011969"));
					if($pdo->setPreference($mkey, $mval))
						$set++;
					else
						$response['error'] = $pdo->getLastError();
				}
			}
			if($set == $c1 && $c1)
				$response['status'] = "ok";
			echo json_encode($response);
		}
		else if(isRequestCommand(GET_BASIC_APP_SETTINGS))
		{
			$response['status'] = "notok";
			$keys = array('do_dns_record_lookup', 'requeue_on_empty_whois', 'fix_host_domain_names',
			'config_subdomain_entry', 'default_sub_domains', 'home_page_max_redirs', 
			'default_lookup_types', 'high_preference_lookups',
			'email_from_address', 'email_from_name', 'email_reply_address', 'email_reply_name',
			'email_send_method', 'email_smtp_server', 'email_smtp_secure', 'email_smtp_port',
			'email_smtp_user', 'interface_language', 'email_word_wrap',
			'auth_timeout_minutes', 'max_login_attempts', 'login_lockout_minutes', 'cli_auth_key_code',
			'home_screen_application', 'auth_queue_processing', 'custom_tools_file', 'main_logo_image',
			'product_page_link', 'support_page_link', 'contact_page_link', 'do_subdomain_ext_lookup'
			);
			foreach($keys as $key)
				if(isset($config_data[$key]))
					$response[$key] = $config_data[$key];
			echo json_encode($response);
		}
		else if(isRequestCommand(PARSE_WHOIS_AGAIN))
		{
			$count = 0;
			$sids = explode(",", $_REQUEST[PARSE_WHOIS_AGAIN]);
			$response['status'] = "notok";
			foreach($sids as $sid)
			{
				$sid = intval($sid);
				$response['sid'][] = $sid;
				if($sid > 0)
				{
					$domain = $pdo->getSingleEntry($pdo->getDomainTableName(), "sid", $sid, "domain"); 
					if(parseWhoisAgain($domain) !== false)
						$count++;
				}
			}
			if($count)
				$response['status'] = "ok";
			echo json_encode($response);
		}
		else if(isRequestCommand(GET_ALL_DOMAIN_COLUMNS))
		{
			$response['columns'] = "";
			$customcolumns = $pdo->getCustomColumns();
			$response['custominfo'] = $pdo->getCustomFieldInfo();
			$allcolumns = "";
			foreach($customcolumns as $column)
				$allcolumns .= "<li><b>" . $column . "</b></li>";
			//$domaincolumns = $pdo->getAllColumnNames($pdo->getDomainTableName());
			$domaincolumns = $pdo->getDefaultColumnNames($pdo->getDomainTableName());
			foreach($domaincolumns as $dc)
			{
				if(!in_array($dc, $customcolumns))
					$allcolumns .= "<li>" . $dc . "</li>";
			}
			$response['columnlist'] = $allcolumns;
			$response['columns'] = $domaincolumns;
			echo json_encode($response);
		}
		else if(isRequestCommand(ASA_GET_EDITABLE_DOMAIN_COLUMNS))
		{
			$customcolumns = $pdo->getCustomColumns();
			$response['custominfo'] = $pdo->getCustomFieldInfo();
			$allcolumns = "";
			foreach($customcolumns as $column)
				$allcolumns .= "<li><b>" . $column . "</b></li>";
			$domaincolumns = $pdo->getAllColumnNames($pdo->getDomainTableName());
			$ignorecolumns = $pdo->getNoGridDomainColumnNames();
			sort($domaincolumns, SORT_STRING);
			foreach($domaincolumns as $dc)
			{
				if(in_array($dc, $ignorecolumns))
					continue;
				$ft = $pdo->getFieldType($pdo->getDomainTableName(), $dc);
				if($ft !== false && stristr($ft,"datetime") !== false && $dc != "last_update")
					continue;
				if(!in_array($dc, $customcolumns) && $dc != "sid" && $dc != "domain" && $dc != "r_h_disp" && $dc != "edited")
					$allcolumns .= "<li>" . $dc . "</li>";
			}
			$response['columnlist'] = $allcolumns;
			$response['columns'] = $domaincolumns;
			echo json_encode($response);
		}
		else if(isRequestCommand(ASA_GET_EDITABLE_SUBDOMAIN_COLUMNS))
		{
			$customcolumns = array('notes_a', 'notes_b', 'notes_c', 'notes_d');
			foreach($customcolumns as $column)
				$allcolumns .= "<li><b>" . $column . "</b></li>";
			$response['columnlist'] = $allcolumns;
			$response['columns'] = $domaincolumns;
			echo json_encode($response);
		}
		else if(isset($_REQUEST['gclcb']))
		{
			$valid_columns = $pdo->getAllColumnNames($pdo->getDomainTableName());
			$vcids = getValidCategoryIDs();
			$append = getRequestVariable("append", "cbcq");
			$response['catlist'] = "";
			$catlist = $pdo->getTableData($pdo->getCategoryTableName(), "CategoryName,CategoryID", "ORDER BY SortOrder DESC"); 
			$response['status'] = "notok";
			if($catlist !== false)
			{
				foreach($catlist as $cat)
				{
					$catid = $cat['CategoryID'];
					if($catid == 1)
						continue;
					if(count($vcids))
						if(in_array($catid, $vcids) === false)
							continue;
					$catname = $cat['CategoryName'];
					$response['catlist'] .= "<label class=\"checkbox-inline no_indent\"><input class=\"$append\" type=\"checkbox\" name=\"$append$catid\" id=\"$append$catid\">$catname</label>\n";
				}
				$response['status'] = "ok";
				$response['dfields'] = $valid_columns;
				$response['catlist'] .= "<label class=\"checkbox-header text-center bg-danger\" style=\"color:#000;\"><input type=\"checkbox\" id=\"$append" . "selectall\" name=\"$append" . "selectall\" style=\"margin-right: 8px;\">Check / Uncheck All</label>";
			}
			echo json_encode($response);
		}
		else if(isRequestCommand(ASA_GET_USER_ADMIN_DATA))
		{
			$response['catlist'] = "";
			$catlist = $pdo->getTableData($pdo->getCategoryTableName(), "CategoryName,CategoryID"); 
			$response['status'] = "notok";
			if($catlist !== false)
			{
				foreach($catlist as $cat)
				{
					$catid = $cat['CategoryID'];
					if($catid == 1)
						continue;
					$catname = $cat['CategoryName'];
					$cb = "<label class=\"checkbox-inline no_indent\"><input class=\"cbua\" type=\"checkbox\" id=\"cbua$catid\" name=\"cbua$catid\">$catname</label>";
					$response['catlist'] .= $cb;
				}
				$response['catlist'] .= "<label class=\"checkbox-header text-center bg-danger\" style=\"color:#000;\"><input type=\"checkbox\" id=\"cbuaselectall\" name=\"cbuaselectall\" style=\"margin-right: 8px;\">Check / Uncheck All</label>";
				$response['saname'] = getConfigData('admin_user_name', "");
				$usl = array();
				$ust = "";
				$userlist = $pdo->getTableData($pdo->user_table, "id,name,display_name,active,readwrite,last_sign_in_stamp");
				if($userlist !== false)
				{
					foreach($userlist as $ul)
					{
						$usl[] = $ul;
						$uid = $ul['id'];
						$uname = $ul['name'];
						$udname = $ul['display_name'];
						$active = $ul['active'];
						$ust .= "<tr id=\"uid-$uid\"><td>$uname</td><td>$udname</td><td>$active</td></tr>";
					}
				}
				$response['utable'] = $ust;
				$response['users'] = $usl;
				$response['status'] = "ok";
			}
			echo json_encode($response);
		}
		else if(isRequestCommand(GET_REGISTRAR_ALIAS))
		{
			$sid = getNumericRequestVariable(GET_REGISTRAR_ALIAS, 0);
			$response['status'] = "notok";
			$response['sid'] = $sid;
			if($sid > 0)
			{
				$regname = $pdo->getSingleEntry($pdo->getDomainTableName(), "sid", $sid, "registrar");
				if($regname !== false)
				{
					$response['registrar'] = $regname;
					$response['status'] = "done";
					$alias =  $pdo->getSingleEntry($pdo->getRegistrarAliasTableName(), "name", $regname, "alias");
					if($alias !== false)
						$response['alias'] = $alias;
				}
				else
					$response['status'] = "database error.";
			}
			echo json_encode($response);
		}
		else if(isset($_REQUEST['sra']) && isset($_REQUEST['alias']))
		{
			if(getUserAccessRights() == 0)
				noPermissionQuit();
			$sid = intval($_REQUEST['sra']);
			$alias = filter_var($_REQUEST['alias'], FILTER_SANITIZE_STRING);
			$response['status'] = "notok";
			$response['sid'] = $sid;
			if($sid > 0)
			{
				$regname = $pdo->getSingleEntry($pdo->getDomainTableName(), "sid", $sid, "registrar");
				if($regname !== false)
				{
					$response['registrar'] = $regname;
					$response['oldalias']  = "";
					$oldalias =  $pdo->getSingleEntry($pdo->getRegistrarAliasTableName(), "name", $regname, "alias");
					if($oldalias !== false && $oldalias != $alias)
					{
						if($alias == "")
						{
							$status = $pdo->deleteFromTable($pdo->getRegistrarAliasTableName(), "name=?", array($regname));
							if($status !== false)
							{
								$response['status'] = "done";
								$response['alias']  = $alias;
							}
							else
								$response['status'] = "database error.";
						}
						else
						{
							$response['oldalias'] = $oldalias;
							$status = $pdo->updateTable($pdo->getRegistrarAliasTableName(), "alias=? where name=?", array($alias, $regname));
							if($status !== false)
							{
								$response['status'] = "done";
								$response['alias']  = $alias;
							}
							else
								$response['status'] =  "database error.";
						}
					}
					else if($oldalias !== false && $oldalias == $alias)
					{
						$response['alias']  = $alias;
						$response['status'] = "done";
					}
					else if($oldalias === false)
					{
						$status = $pdo->insertIntoTable($pdo->getRegistrarAliasTableName(), array('name'=>$regname, 'alias'=>$alias));
						if($status === false)
							$response['status'] = "database error.";
						else
						{
							$response['status'] = "done";
							$response['alias']  = $alias;
						}
					}
				}
				else
					$response['status'] = "database error.";
			}
			echo json_encode($response);
		}
		else if(isset($_REQUEST['dgroup']))
		{
			# Get the group's column names as check boxes
			$dgroup = $_REQUEST['dgroup'];
			$response['data'] = getSelectableColumnsText($dgroup);
			$response['title'] = "Setup " . beautifyDisplayGroupName($dgroup);
			echo json_encode($response);
			exit;
		}
		else if(isset($_REQUEST['sdcol']))
		{
			# Get the group's column names as check boxes
			$response['data'] = getSelectableColumnsTextForSubdomains('sub_domain_columns');
			$response['title'] = "Setup Subdomain Columns";
			echo json_encode($response);
			exit;
		}
		else if(isset($_REQUEST['dnscol']))
		{
			# Get the group's column names as check boxes
			$response['data'] = getSelectableColumnsTextForSubdomains('dns_subgrid_columns');
			$response['title'] = "Setup DNS Table Columns";
			echo json_encode($response);
			exit;
		}
		else if(isset($_REQUEST['sslcol']))
		{
			# Get the group's column names as check boxes
			$response['data'] = getSelectableColumnsTextForSubdomains('ssl_subgrid_columns');
			$response['title'] = "Setup SSL Table Columns";
			echo json_encode($response);
			exit;
		}
		else if(isset($_REQUEST['gfield']))
		{
			$accessrights = getUserAccessRights();
			# Get Label and Width for a domain field / column.
			$field = filter_var($_REQUEST['gfield'], FILTER_SANITIZE_STRING);
			
			$response['save'] = "none";
			if(isset($_REQUEST['sfield']) && $accessrights != 0)
			{
				$ofield = filter_var($_REQUEST['sfield'], FILTER_SANITIZE_STRING);
				if($ofield != "")
				{
					$width = filter_var($_REQUEST['swidth'], FILTER_SANITIZE_NUMBER_INT);
					$label = strip_tags(trim(($_REQUEST['slabel'])));
					if($pdo->setColumnLabelAndWidthForDomain($ofield, $label, $width))
						$response['save'] = "done";
					else
						$response['save'] = "error";
				}
			}

			$width = $pdo->getDefaultWidthForDomainColumn($field);
			$label = getLabelFromFieldName($field);
						
			if($field != "")
			{
				$status = $pdo->getColumnLabelAndWidthForDomain($field, $label, $width);
				
				if($label == "")
					$label = getLabelFromFieldName($field);

				$response['field'] = $field;
				$response['width'] = $width;
				$response['label'] = $label;
				$response['status'] = "done";
			}
			else
				$response['status'] = "noget";
				
			echo json_encode($response);
			exit;
		}
		else if(isset($_REQUEST['sdgf']))
		{
			$accessrights = getUserAccessRights();
			# Get Label and Width for a sub-domain field / column.
			$field = filter_var($_REQUEST['sdgf'], FILTER_SANITIZE_STRING);
			
			$response['save'] = "none";
			if(isset($_REQUEST['sdsf']) && $accessrights != 0)
			{
				$ofield = filter_var($_REQUEST['sdsf'], FILTER_SANITIZE_STRING);
				if($ofield != "")
				{
					$width = filter_var($_REQUEST['swidth'], FILTER_SANITIZE_NUMBER_INT);
					$label = strip_tags(trim(($_REQUEST['slabel'])));
					if($pdo->setColumnLabelAndWidthForSubdomain($ofield, $label, $width))
						$response['save'] = "done";
					else
						$response['save'] = "error";
				}
			}

			$width = $pdo->getDefaultWidthForSubdomainColumn($field);
			$label = getLabelFromFieldName($field);
						
			if($field != "")
			{
				$status = $pdo->getColumnLabelAndWidthForSubdomain($field, $label, $width);
				
				if($label == "")
					$label = getLabelFromFieldName($field);

				$response['field'] = $field;
				$response['width'] = $width;
				$response['label'] = $label;
				$response['status'] = "done";
			}
			else
				$response['status'] = "noget";
				
			echo json_encode($response);
			exit;
		}
		else if(isset($_REQUEST['dgset']))
		{
			$accessrights = getUserAccessRights();
			if($accessrights == 0)
				noPermissionQuit();
			# Change the current display group
			$response['status'] = "none";
			$dgroup = $_REQUEST['dgset'];
			if(isset($_REQUEST['entry']))
			{
				$entry = $_REQUEST['entry'];
				if($pdo->setDisplayColumns($dgroup, $entry) !== false)
					$response['status'] = "done";
			}
			echo json_encode($response);
			exit;
		}
		else if(isset($_REQUEST['dgreset']))
		{
			$accessrights = getUserAccessRights();
			if($accessrights == 0)
				noPermissionQuit();
			# Change the current display group
			$response['status'] = "none";
			$dgroup = $_REQUEST['dgreset'];
			$dcfg = get_default_columns_for_groups();
			if(isset($dcfg[$dgroup]))
			{
				$entry = $dcfg[$dgroup];
				if($pdo->setDisplayColumns($dgroup, $entry) !== false)
					$response['status'] = "done";
			}
			echo json_encode($response);
			exit;
		}
		else if(isset($_REQUEST['sdcolset']))
		{
			$accessrights = getUserAccessRights();
			if($accessrights == 0)
				noPermissionQuit();
			# Change the current display group
			$response['status'] = "none";
			$dgroup = getRequestVariable('sdcolset', '');
			if(isset($_REQUEST['entry']) && $dgroup != "")
			{
				$entry = trim($_REQUEST['entry']);
				if($pdo->setPreference($dgroup, $entry) !== false)
					$response['status'] = "done";
			}
			echo json_encode($response);
			exit;
		}
		else if(isset($_REQUEST['sdcolreset']))
		{
			$accessrights = getUserAccessRights();
			if($accessrights == 0)
				noPermissionQuit();
			# Change the current display group
			$response['status'] = "none";
			$dgroup = getRequestVariable('sdcolreset', '');
			$dcd = get_default_config_data();
			if(isset($dcd[$dgroup]) && $dgroup != "")
			{
				$entry = $dcd[$dgroup];
				if($pdo->setPreference($dgroup, $entry) !== false)
					$response['status'] = "done";
			}
			echo json_encode($response);
			exit;
		}
		else if(isset($_REQUEST['dgget']))
		{
			# Get the column model group
			$dateformat = getConfigData("cell_date_format", "d-M-Y");
			$builtInFields = $pdo->getDefaultColumnNames($pdo->getDomainTableName());
			$datacolumns = array();
			$dgroup = $_REQUEST['dgget'];
			$entry = $pdo->getDisplayColumnsForGroup($dgroup);
			if($entry !== false)
			{
				$entry = "r_h_disp;domain;" . $entry;
				$parts = explode(";", $entry);
				foreach($parts as $part)
				{
					$columns[0] = $part; // Label
					$columns[1] = strtolower(trim($part)); // Field Name
					$columns[1] = str_replace(" ","_", $columns[1]);
					# Avoid these two because they are dead
					if($columns[1] == "google_pr" || $columns[1] == "alexa_links")
						continue;
					$columns[2] = $pdo->getDefaultWidthForDomainColumn($columns[1]);
					$columns[0] = getLabelFromFieldName($columns[0]);
					$status = $pdo->getColumnLabelAndWidthForDomain($columns[1], $columns[0], $columns[2]);
					if(count($columns) == 3 && $columns[1] != "")
					{
						$classname = strtolower($columns[1]);
						$classname = str_replace("_","-", $classname) . "-cell";
						
						$append = array();
						
						if(strtolower($columns[1]) == "domain")
						{
							$append['editable'] = true;
							$append['editoptions'] = array('size'=>35, 'readonly'=>true);
						}
						else if(strtolower($columns[1]) == "r_h_disp")
						{
							$append['sortable'] = true;
							$append['editable'] = false;
							$append['search'] = false;
							$append['hidden'] = false;
							$append['fixed'] = true;
							$columns[0] = "!";
							$columns[2] = 20;
							$append['formatter'] = 'highlightFormatter';
						}
						else if(strtolower($columns[1]) == "edited")
						{
							$append['editable'] = false;
						}
						else if(strtolower($columns[1]) == "page_token_found")
						{
							$append['editable'] = false;
							$append['align'] = 'center';
							$append['search'] = false;
							$append['formatter'] = 'booleanFormatter';
							$columns[2] = 40;
						}
						else if(strtolower($columns[1]) == "registrar")
						{
							$append['editable'] = true;
							$append['editoptions'] = array('size'=>35);
							$append['formatter'] = 'registrarFormatter';
						}
						else if(strtolower($columns[1]) == "availability")
						{
							$append['editable'] = false;
							$append['align'] = 'center';
							$append['search'] = false;
							$append['formatter'] = 'domAvailFormatter';
							$columns[2] = 40;
						}
						else if(strtolower($columns[1]) == "ascii_domain")
							$append['editable'] = false;
						else
						{
							$ft = $pdo->getFieldType($pdo->getDomainTableName(), $columns[1]);
							if($ft !== false)
							{
								if(stristr($ft, "datetime") !== false && $columns[1] != "last_update")
								{
									$append['sorttype'] = 'date';
									$append['formatter'] = 'date';
									$append['formatoptions'] = array("srcformat"=>"Y-m-d H:i:s","newformat"=>"$dateformat H:i:s");
									if(in_array($columns[1], $builtInFields))
										$append['editable'] = 'hidden';
									else
										$append['editable'] = true;
								}
								else if(stristr($ft, "date") !== false)
								{
									$append['editable'] = true;
									$append['sorttype'] = 'date';
									$append['formatter'] = 'date';
									$append['formatoptions'] = array("srcformat"=>"Y-m-d H:i:s","newformat"=>"$dateformat");
								}
								else if(stristr($ft, "varchar") !== false)
								{
									$append['editable'] = true;
									$append['editoptions'] = array('size'=>35);
								}
							}
						}
						
						$append['classes'] = "dtcell $classname";
						$append['label'] = $columns[0];
						$append['name'] = $columns[1];
						$append['width'] = $columns[2];
							
						$datacolumns[] = $append;
						
						unset($append);
					}
				}
				$response['colmodel'] = $datacolumns;
				echo json_encode($response);
			}
			exit;
		}
		else if(isset($_REQUEST['sdget']))
		{
			$dgroup = getRequestVariable('sdget', '');
			doGetSubDomainColModel($pdo, $response, $dgroup);
		}
		else if(isRequestCommand(ASA_GET_SERVER_STATUS_TABLE))
			doGetServerStatusTable($pdo, $response);
		else if(isRequestCommand(ASA_CLEAR_SERVER_STATUS_TABLE))
			doResetServerStatusTable($pdo, $response);
	}
}
else
	echo json_encode($response);

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

function getSelectableColumnsText($group)
{
	$cblist = "";
	$pdo = init_db(false);
	
	if($pdo !== false)
	{
		$dgroups = $pdo->getDisplayColumns();
		$alldomaincolumns = $pdo->getAllColumnNames($pdo->getDomainTableName());
		$customdomaincolumns = $pdo->getCustomColumns();
		if($customdomaincolumns === false)
			$customdomaincolumns = array();
		sort($alldomaincolumns);
		$readonlycolumns = $pdo->getNoGridDomainColumnNames();
		
		if($dgroups !== false)
		{
			if(isset($dgroups[$group]))
			{
				$tbfields = explode(";", $dgroups[$group]);
				foreach($tbfields as $tbcolumn)
				{
					# Avoid these two because they are dead
					if(strtolower($tbcolumn) == "google_pr" || strtolower($tbcolumn) == "alexa_links")
						continue;
					if(in_array($tbcolumn, $alldomaincolumns))
					{
						$cblist .= "\t\t\t\t\t\t\t\t<li><div class='handle'><span class='ui-icon grip-drag-action-button'></span></div>";
						$cblist .= "<label for=\"cb-$tbcolumn\">";
						$cblist .= "<input id=\"cb-" . $tbcolumn . "\" type=\"checkbox\" checked>" . $tbcolumn . "</label></li>\n";
					}
				}
				foreach($customdomaincolumns as $tbcolumn)
				{
					if(!in_array($tbcolumn, $tbfields))
					{
						$cblist .= "\t\t\t\t\t\t\t\t<li><div class='handle'><span class='ui-icon grip-drag-action-button'></span></div>";
						$cblist .= "<label for=\"cb-$tbcolumn\">";
						$cblist .= "<input id=\"cb-" . $tbcolumn . "\" type=\"checkbox\">" . $tbcolumn . "</label></li>\n";
					}
				}
				foreach($alldomaincolumns as $tbcolumn)
				{
					//if(stristr($tbcolumn, "_checked_at") !== false)
					//	continue;
					if(in_array($tbcolumn, $readonlycolumns))
						continue;
					if(!in_array($tbcolumn, $tbfields) && !in_array($tbcolumn, $customdomaincolumns))
					{
						$cblist .= "\t\t\t\t\t\t\t\t<li><div class='handle'><span class='ui-icon grip-drag-action-button'></span></div>";
						$cblist .= "<label for=\"cb-$tbcolumn\">";
						$cblist .= "<input id=\"cb-" . $tbcolumn . "\" type=\"checkbox\">" . $tbcolumn . "</label></li>\n";
					}
				}
			}
		}
	}
	return $cblist;
}

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

function getSelectableColumnsTextForSubdomains($configkey)
{
	$cblist = "";
	$pdo = init_db(false);
	
	if($pdo !== false)
	{
		$columns = get_config_data($configkey, null);
		$allcolumns = $pdo->getAllColumnNames($pdo->getSubdomainTableName());
		if($configkey == "sub_domain_columns")
		{
			$allcolumns[] = "domain";
			$allcolumns[] = "hostname";
		}
		if (($key = array_search('hid', $allcolumns)) !== false) 
			unset($allcolumns[$key]);
		$allcolumns = array_values($allcolumns);
		sort($allcolumns);
		$tbfields = explode(";", $columns);
		foreach($tbfields as $tbcolumn)
		{
			if(in_array($tbcolumn, $allcolumns))
			{
				$cblist .= "\t\t\t\t\t\t\t\t<li><div class='handle'><span class='ui-icon grip-drag-action-button'></span></div>";
				$cblist .= "<label for=\"cb-$tbcolumn\">";
				$cblist .= "<input id=\"cb-" . $tbcolumn . "\" type=\"checkbox\" checked>" . $tbcolumn . "</label></li>\n";
			}
		}
		foreach($allcolumns as $tbcolumn)
		{
			if($tbcolumn == "r_h_disp" || $tbcolumn == "edited" || $tbcolumn == "sid" || $tbcolumn == "subdomain")
				continue;
			# legacy code because of v2.x. Remove after a few months (23-April-2016)
			if($tbcolumn == "ip_checked_at" || $tbcolumn == "ssl_checked_at")
				continue;
			# end of legacy code.
			if(!in_array($tbcolumn, $tbfields))
			{
				$cblist .= "\t\t\t\t\t\t\t\t<li><div class='handle'><span class='ui-icon grip-drag-action-button'></span></div>";
				$cblist .= "<label for=\"cb-$tbcolumn\">";
				$cblist .= "<input id=\"cb-" . $tbcolumn . "\" type=\"checkbox\">" . $tbcolumn . "</label></li>\n";
			}
		}
	}
	return $cblist;
}

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

function doAddToCategories($pdo, $response)
{
	$accessrights = getUserAccessRights();
	if($accessrights > 0)
	{
		$vcids = getValidCategoryIDs();
		$response['status'] = "notok";
		$catids = explode(",", getRequestVariable(ASA_ADD_TO_CATEGORIES, ""));
		$sids = explode(",", getRequestVariable("id", ""));
		$addinfo = array();
		$count = 0;
		foreach($catids as $catid)
		{
			if(count($vcids))
			{
				if(in_array($catid, $vcids) === false)
					continue;
			}
			$added = 0;
			foreach($sids as $sid)
			{
				if($catid > 0 && $sid > 0)
				{
					if($pdo->addDomainToCategory($sid, $catid) !== false)
					{
						$added++;
						$count++;
					}
				}
			}
			$addinfo[$catid] = $added;
		}
		$response['info'] = $addinfo;
		$response['added'] = $count;
		if($count)
			$response['status'] = "ok";
		echo json_encode($response);
	}
	else
		noPermissionQuit();
	exit;
}

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

function doDeleteFromCategories($pdo, $response)
{
	$accessrights = getUserAccessRights();
	if($accessrights > 0 && isAdminUser())
	{
		$vcids = getValidCategoryIDs();
		$response['status'] = "notok";
		$catids = explode(",", getRequestVariable(ASA_REMOVE_FROM_CATEGORIES, ""));
		$sids = explode(",", getRequestVariable("id", ""));
		$addinfo = array();
		$count = 0;
		foreach($catids as $catid)
		{
			if(count($vcids))
			{
				if(in_array($catid, $vcids) === false)
					continue;
			}
			$deleted = 0;
			foreach($sids as $sid)
			{
				if($catid > 0 && $sid > 0)
				{
					if($pdo->deleteFromTable($pdo->getCategoryIDToDomainIDTableName(), "sid=? AND CategoryID=?", array($sid, $catid)) !== false)
					{
						$deleted++;
						$count++;
					}
				}
			}
			$addinfo[$catid] = $deleted;
		}
		$response['info'] = $addinfo;
		$response['deleted'] = $count;
		if($count)
			$response['status'] = "ok";
		echo json_encode($response);
	}
	else
		noPermissionQuit();
	exit;
}

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

function doSaveCustomQuerySQL($pdo, $response)
{
	$accessrights = getUserAccessRights();
	if($accessrights == 0)
		noPermissionQuit();
	else
	{
		$response['status'] = "notok";
		$response['aqname'] = strip_tags(trim(getRequestVariable("aqname", "")));
		$cqdata = getCustomQueryData();
		$response['sql'] = $pdo->getCustomQuerySQL($cqdata);
		
		# Check SQL.
		$badsql = false;
		$gresp = new stdClass();
		$cids = getValidCategoryIDs();
		if($pdo->jqGridDomainCount(0, 0, $cqdata, $cids, $gresp) === false)
			$badsql = true;
		if($response['sql'] != "" && stristr($response['sql'], "(1=0)") === false && $response['aqname'] != "" && $badsql == false)
		{
			$aqsql = $pdo->getSingleEntry($pdo->getAutoQueryTableName(), "Name", $response['aqname'], "Query");
			if($aqsql === false)
			{
				
				if($pdo->insertIntoTable($pdo->getAutoQueryTableName(), array('Name'=>$response['aqname'], 'Query'=>$response['sql'])) !== false)
				{
					$response['status'] = "ok";
					$response['message'] = "<p>" . $gresp->records . " domains in result set.</p><p>Auto-query '" . $response['aqname'] . "' created.</p>";
					$qname = $response['aqname'];
					$qvalue = $response['sql'];
					$pdo->logAuditEntry(AUDIT_ADDED_AUTOQUERY, "Added autoquery '$qname' = \"$qvalue\"");
				}
			}
			else
				$response['message'] = "An Auto-Query with that name ('" . $response['aqname'] . "') already exists.";
		}
		else if($badsql)
		{
			$response['message'] = "<p>Unable to create a valid SQL. Please check your query data.</p><p>The SQL query was...</p>";
			$response['message'] .= "<p><code>..." . $response['sql'] . "</code></p>";
		}
		else if(stristr($response['sql'], "(1=0)") !== false)
		{
			$response['message'] = "<p>Custom Query contains an invalid clause or command.</p>";
			$response['message'] .= "<p>Keywords like SELECT, DROP, INSERT, etc. are prohibited.</p>";
		}
		else if($response['aqname'] == "")
		{
			$response['status'] = "ok";
			$response['message'] = "<p>" . $gresp->records . " domains in result set.</p>";
			$response['message'] .= "<p>You may specify an Auto-query name if you wish to save this query for later reuse.</p>";
		}
		echo json_encode($response);
	}
	exit;
}

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

function doInsertCustomColumn($pdo, $response)
{
	if(isAdminUser() == false)
		noPermissionQuit();
	else
	{
		$response['status'] = "notok";
		$response['error'] = "";
		$field_name = strip_tags(getRequestVariable(ASA_INSERT_CUSTOM_COLUMN, ""));
		$field_type = getRequestVariable("type", "");
		$field_size = getRequestVariable("width", "");
		
		$field_name = strtolower(trim($field_name));
		$field_name = str_replace(" ", "_", $field_name);
		$field_name = str_replace(";", "_", $field_name);
		$field_name = str_replace(",", "_", $field_name);
		$field_name = str_replace("-", "_", $field_name);
		$field_name = str_replace("(", "_", $field_name);
		$field_name = str_replace(")", "_", $field_name);
		$field_name = str_replace("[", "_", $field_name);
		$field_name = str_replace("]", "_", $field_name);
		$field_name = str_replace("}", "_", $field_name);
		$field_name = str_replace("{", "_", $field_name);
		# Remove repeated _ and leading / trailing _
		$field_name = trim(preg_replace('/_+/', '_', $field_name), '_');
		
		if(intval($field_size) < 10 || intval($field_size) > 255)
			$field_size = "128";
		if($field_type == "varchar")
			$field_type = "varchar(" . $field_size . ")";
		if($field_type == "bigint")
			$field_type = "bigint(20)";
		
		$columns[] = $field_name;
		$columns[] = $field_type;
		$columns[] = "DEFAULT NULL";
		if($pdo->addCustomColumn($columns) === true)
		{
			$response['status'] = "ok";
		}
		else
			$response['error'] = $pdo->getLastError();
		echo json_encode($response);
	}
	exit;
}

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

function doDeleteCustomColumn($pdo, $response)
{
	if(isAdminUser() == false)
		noPermissionQuit();
	else
	{
		$response['status'] = "notok";
		$customTable = $pdo->getCustomFieldsTableName();
		$field_name = getRequestVariable(ASA_DELETE_CUSTOM_COLUMN, "");
		$customcolumns = $pdo->getCustomColumns();
		if(in_array($field_name, $customcolumns) == true)
		{
			if($pdo->deleteFromTable($customTable, "name=?", array($field_name)) === true)
			{
				$response['status'] = "ok";
			}
		}
		echo json_encode($response);
	}
	exit;
}

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

function doDeleteOrphanColumn($pdo, $response)
{
	if(isAdminUser() == false)
		noPermissionQuit();
	else
	{
		$response['status'] = "notok";
		$domaintable = $pdo->getDomainTableName();
		$field_name = getRequestVariable(ASA_DELETE_ORPHAN_COLUMN, "");
		$orphancolumns = array();
		$customcolumns = $pdo->getCustomColumns();
		$defaultcolumns = $pdo->getDefaultColumnNames($pdo->getDomainTableName());
		$existingcolumns = $pdo->getAllColumnNames($pdo->getDomainTableName());
		foreach($existingcolumns as $column)
		{
			if(!in_array($column, $customcolumns) && !in_array($column, $defaultcolumns))
				$orphancolumns[] = $column;
		}
		if(in_array($field_name, $orphancolumns) == true)
		{
			$sql = "ALTER table $domaintable DROP column `$field_name`";
			try 
			{
				$pdo->db_connect_handle->exec($sql);
				$response['status'] = "ok";
			} 
			catch (PDOException $e) 
			{
				$pdo->setError($e->getMessage());
				$response['error'] = $pdo->getLastError();
			}
		}
		echo json_encode($response);
	}
	exit;
}

###############################################################################
# Edit the data for a single column for multiple rows (ids)

function doBulkEditColumn($pdo, $response)
{
	# 0 = View, 1 = View+Edit+Add+Delete, 2 = View+Edit, 3 = View=Edit+Add
	$accessrights = getUserAccessRights();
	if($accessrights == 0)
		noPermissionQuit();
	else
	{
		$domainlist = array();
		$updated = 0;
		$response['status'] = "notok";
		$response['error'] = "";
		$domaincolumns = $pdo->getAllColumnNames($pdo->getDomainTableName());
		$customcolumns = $pdo->getCustomColumns();
		$field = getRequestVariable(ASA_BULK_EDIT_COLUMN, "");
		$value = getRequestVariable("v", "");
		if($field != "" && in_array($field, $domaincolumns) === true && $field != "sid"  && $field != "domain")
		{
			$sids = explode(",", trim(getRequestVariable("ids", "")));
			foreach($sids as $sid)
			{
				if($sid > 0)
				{
					$timenow = date("Y-m-d H:i:s");
					if(!in_array($field, $customcolumns) && strcasecmp($field, "manual_edited_at") && strcasecmp($field, "edited"))
						$setclause = "`$field` = ?, edited=1, manual_edited_at='$timenow' WHERE sid=?";
					else
						$setclause = "`$field` = ? WHERE sid=?";
					if($pdo->updateTable($pdo->getDomainTableName(), $setclause, array($value, $sid)) !== false)
					{
						$updated++;
						$domain = $pdo->getSingleEntry($pdo->getDomainTableName(), "sid", $sid, "domain");
						if(count($domainlist) < MAX_AUDIT_LOG_DOMAINS)
							$domainlist[] = $domain;
					}
				}
			}
		}
		if($updated)
		{
			if($updated > MAX_AUDIT_LOG_DOMAINS)
				$domainlist[] = "...";
			$pdo->logAuditEntry(AUDIT_EDITED_DOMAIN, "Modified '$field' to '$value' for $updated domains (" . implode(", ", $domainlist) . ")");
		}
		$response['count'] = $updated;
		if($updated)
			$response['status'] = "ok";
		else
			$response['error'] = $pdo->getLastError();
		echo json_encode($response);
	}
	exit;
}

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

function doBulkEditSubdomainColumn($pdo, $response)
{
	# 0 = View, 1 = View+Edit+Add+Delete, 2 = View+Edit, 3 = View=Edit+Add
	$accessrights = getUserAccessRights();
	if($accessrights == 0)
		noPermissionQuit();
	else
	{
		$updated = 0;
		$response['status'] = "notok";
		$response['error'] = "";
		$customcolumns = array('notes_a', 'notes_b', 'notes_c', 'notes_d');
		$field = getRequestVariable(ASA_BULK_EDIT_SD_COLUMN, "");
		$value = getRequestVariable("v", "");
		if($field != "" && in_array($field, $customcolumns) === true)
		{
			$hids = explode(",", trim(getRequestVariable("ids", "")));
			foreach($hids as $hid)
			{
				if($hid > 0)
				{
					$timenow = date("Y-m-d H:i:s");
					if(!in_array($field, $customcolumns) && strcasecmp($field, "manual_edited_at") && strcasecmp($field, "edited"))
						$setclause = "$field = ?, edited=1, manual_edited_at='$timenow' WHERE hid=?";
					else
						$setclause = "$field = ? WHERE hid=?";
					if($pdo->updateTable($pdo->getSubdomainTableName(), $setclause, array($value, $hid)) !== false)
						$updated++;
				}
			}
		}
		$response['count'] = $updated;
		if($updated)
			$response['status'] = "ok";
		else
			$response['error'] = $pdo->getLastError();
		echo json_encode($response);
	}
	exit;
}

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

function doSaveSuperAdmin($pdo, $response)
{
	# 0 = View, 1 = View+Edit+Add+Delete, 2 = View+Edit, 3 = View=Edit+Add
	$accessrights = getUserAccessRights();
	if($accessrights == 0 || isAdminUser() == false)
		noPermissionQuit();
	else
	{
		$response['status'] = "notok";
		$username = getRequestVariable("user", "");
		$pass = getRequestVariable("pass", "");
		//if($username != "" && $pass != "")
		{
			$hpass = generateHash($pass);
			if($pdo->SetPreference("admin_user_name", $username) !== false) 
			{
				if($pdo->SetPreference("admin_password", $hpass) !== false) 
				{
					$response['status'] = "ok";
				}
			}
		}
		echo json_encode($response);
	}
	exit;
}

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

function doSaveUserDetails($pdo, $response)
{
	# 0 = View, 1 = View+Edit+Add+Delete, 2 = View+Edit, 3 = View=Edit+Add
	$accessrights = getUserAccessRights();
	if($accessrights == 0 || isAdminUser() == false)
		noPermissionQuit();
	else
	{
		$response['status'] = "notok";
		
		$uid = getNumericRequestVariable(ASA_SAVE_USER_DETAILS, 0);
		if($uid > 0)
		{
			$perms = getRequestVariable("perms", "");
			$permissions = array();
			$perms = str_replace(array("\r","\n"), ",", trim($perms));
			$cats = explode(",", $perms);
			foreach($cats as $cat)
			{
				$c = intval(strip_tags(trim($cat)));
				if($c > 0)
					$permissions[] = $c;
			}
			$pdo->setCategoryIdsForUser($uid, $permissions);
			
			$isadmin = getRequestVariable("admin", 0);
			if($isadmin == "yes" || $isadmin == "true" || $isadmin == 1)
				$pdo->addUserToGroup($uid, "Admin");
			else
				$pdo->removeUserFromGroup($uid, "Admin");
			
			$dname = getRequestVariable("dname", "");
			if($dname != "")
				$pdo->changeUserIDDisplayName($uid, $dname);
			
			$access = getNumericRequestVariable('rw', 0);
			if($access == 0 || $access == 1 || $access == 2 || $access == 3)
				$pdo->changeUserIDReadWrite($uid, $access);
			
			$isactive = getRequestVariable("active", 0);
			if($isactive == "yes" || $isactive == "true" || $isactive == 1)
				$pdo->changeUserIDStatus($uid, 1);
			else
				$pdo->changeUserIDStatus($uid, 0);
			
			$pass = getRequestVariable("p", "");
			if($pass != "" && strlen($pass) >= 6)
				$pdo->resetUserIDPassword($uid, $pass);

			$userInfo = $pdo->getUserInfo($uid);
			if($userInfo !== false)
			{
				if(is_array($userInfo))
				{
					$response['permissions'] = $userInfo['permissions'];
					$response['rw'] = $userInfo['readwrite'];
					$response['dname'] = $userInfo['displayname'];
					$response['admin'] = $userInfo['admin'];
					$response['active'] = $userInfo['active'];
					$response['status'] = "ok";
				}
			}
		}
		echo json_encode($response);
	}
	exit;
}

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

function doSaveUserPassword($pdo, $response)
{
	$response['status'] = "notok";
	$uid = getUserID();
	if($uid != 0)
	{
		$pass = getRequestVariable(ASA_SET_USER_PASSWORD, '');
		if($pass != "" && strlen($pass) >= 6)
		{
			$pdo->resetUserIDPassword($uid, $pass);
			$response['status'] = "ok";
		}
		echo json_encode($response);
	}
	else
		noPermissionQuit();
	exit;
}

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

function doGetUserDetails($pdo, $response)
{
	# 0 = View, 1 = View+Edit+Add+Delete, 2 = View+Edit, 3 = View=Edit+Add
	$accessrights = getUserAccessRights();
	if($accessrights == 0 || isAdminUser() == false)
		noPermissionQuit();
	else
	{
		$response['status'] = "notok";
		$uid = getNumericRequestVariable(ASA_GET_USER_DETAILS, 0);
		if($uid > 0)
		{
			$userInfo = $pdo->getUserInfo($uid);
			if($userInfo !== false)
			{
				if(is_array($userInfo))
				{
					$response['permissions'] = $userInfo['permissions'];
					$response['rw'] = $userInfo['readwrite'];
					$response['dname'] = $userInfo['displayname'];
					$response['admin'] = $userInfo['admin'];
					$response['active'] = $userInfo['active'];
					$response['status'] = "ok";
				}
			}
		}
		echo json_encode($response);
	}
	exit;
}

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

function doGetSubDomainColModel($pdo, $response, $configkey)
{
	$dateformat = getConfigData("cell_date_format", "d-M-Y");
	$builtInFields = $pdo->getDefaultColumnNames($pdo->getDomainTableName());
	$datacolumns = array();
	$entry = get_config_data($configkey, null);
	if($entry !== false)
	{
		if($configkey == "sub_domain_columns")
			$entry = "r_h_disp;subdomain;sid;" . $entry;
		else
			$entry = "subdomain;$entry";
		$parts = explode(";", $entry);
		foreach($parts as $part)
		{
			$columns[0] = $part; // Label
			$columns[1] = strtolower(trim($part)); // Field Name
			$columns[1] = str_replace(" ","_", $columns[1]);
			$columns[2] = $pdo->getDefaultWidthForSubdomainColumn($columns[1]);
			$columns[0] = getLabelFromFieldName($columns[0]);
			$status = $pdo->getColumnLabelAndWidthForSubdomain($columns[1], $columns[0], $columns[2]);
			if(count($columns) == 3 && $columns[1] != "")
			{
				$classname = strtolower($columns[1]);
				$classname = str_replace("_","-", $classname) . "-cell";
				
				if(strtolower($columns[1]) == "subdomain")
				{
					$append['editable'] = true;
					$append['editoptions'] = array('readonly'=>true,'size'=>35);
					$append['sortable'] = true;
					$append['search'] = true;
				}
				else if(strtolower($columns[1]) == "hostname")
				{
					$append['editable'] = false;
					$append['sortable'] = false;
					$append['search'] = false;
				}
				else if(strtolower($columns[1]) == "domain")
				{
					$append['editable'] = false;
					$append['sortable'] = true;
					$append['search'] = true;
				}
				else if(strtolower($columns[1]) == "edited")
				{
					$append['editable'] = false;
					$append['sortable'] = true;
					$append['search'] = true;
				}
				else if(strtolower($columns[1]) == "sid")
				{
					$append['hidden'] = true;
				}
				else if(strtolower($columns[1]) == "r_h_disp")
				{
					$append['sortable'] = true;
					$append['editable'] = false;
					$append['search'] = false;
					$append['hidden'] = false;
					$append['fixed'] = true;
					$columns[0] = "!";
					$columns[2] = 20;
					$append['formatter'] = 'highlightFormatter';
				}
				else
				{
					$append = array();
					$ft = $pdo->getFieldType($pdo->getSubdomainTableName(), $columns[1]);
					if($ft !== false)
					{
						if(stristr($ft, "datetime") !== false && $columns[1] != "last_update")
						{
							$append['sorttype'] = 'date';
							$append['formatter'] = 'date';
							$append['formatoptions'] = array("srcformat"=>"Y-m-d H:i:s","newformat"=>"$dateformat H:i:s");
							if(in_array($columns[1], $builtInFields))
								$append['editable'] = 'hidden';
							else
								$append['editable'] = true;
						}
						else if(stristr($ft, "date") !== false)
						{
							$append['editable'] = true;
							$append['sorttype'] = 'date';
							$append['formatter'] = 'date';
							$append['formatoptions'] = array("srcformat"=>"Y-m-d H:i:s","newformat"=>"$dateformat");
						}
						else if(stristr($ft, "varchar") !== false)
						{
							$append['editable'] = true;
							$append['editoptions'] = array('size'=>35);
						}
						else
						{
							$append['editable'] = true;
							$append['editoptions'] = array('size'=>20);
						}
					}
				}
				
				$append['classes'] = "dtcell $classname";
				$append['label'] = $columns[0];
				$append['name'] = $columns[1];
				$append['width'] = $columns[2];
					
				$datacolumns[] = $append;
				
				unset($append);
			}
		}
		$response['colmodel'] = $datacolumns;
	}
	echo json_encode($response);
	exit;
}

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

function get_time_difference_and_icon($time_in_secs, &$sdiff, &$alert_icon, $no_panic=false)
{
	$diff = time() - $time_in_secs;
	$alert_icon = "led_green_24.png";
	if($time_in_secs == 0)
	{
		$sdiff = "Never";
		$alert_icon = "led_black_24.png";
	}
	else if($diff > 0 && $diff <= 80)
	{
		$sdiff = "$diff seconds ago";
		$alert_icon = "led_green_24.png";
	}
	else if($diff > 80 && $diff <= 300)
	{
		$sdiff =  gmdate("H:i:s", $diff) . " ago.";
		$alert_icon = "led_amber_24.png";
	}
	else if($diff > 300 && $diff <= 3600)
	{
		$sdiff =  gmdate("H:i:s", $diff) . " ago.";
		$alert_icon = "led_red_24.png";
	}
	else if($diff > 3600)
	{
		$sdiff =  gmdate("H:i:s", $diff) . " ago.";
		if($no_panic)
			$alert_icon = "led_red_24.png";
		else
			$alert_icon = "led_panic_24.png";
	}
}

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

function doGetServerStatusTable($pdo, $response)
{
	# 0 = View, 1 = View+Edit+Add+Delete, 2 = View+Edit, 3 = View=Edit+Add
	$accessrights = getUserAccessRights();
	if($accessrights == 0 || isAdminUser() == false)
		noPermissionQuit();
	
	$response['status'] = "notok";
	$status = $pdo->getInstalledServerStatus();
	$tabletext = "";
	if($status !== false)
	{
		$img_path = get_install_url_path() . "lib/css/images/24/";
		
		$tabletext .= "<table class=\"tb-server-status\">\n";
		$tabletext .= '<tr><th class="status">&nbsp;</th><th>Name</th><th>Host Name</th><th>Conf Name</th><th>&quot;Q&quot; Index</th><th>Ver ID</th><th>IP Address</th><th>Last Lookup</th><th class="status">&nbsp;</th><th>Last Seen</th><th class="status">&nbsp;</th></tr>';
		foreach($status as $row)
		{
			$name = "";
			$address = "";
			$last_connect = 0;
			$cnfname = "-";
			$hostname = "";
			$baseurl = "";
			$last_lookup = 0;
			$qindex = "-";
			$vindex = "-";
			
			if(isset($row['name']))
				$name = $row['name'];
			if(isset($row['address']))
				$address = $row['address'];
			if(isset($row['hostname']))
				$hostname = $row['hostname'];
			if(isset($row['cnfname']))
				$cnfname = $row['cnfname'];
			if(isset($row['last_connect_at']))
				$last_connect = $row['last_connect_at'];
			if(isset($row['last_lookup_at']))
				$last_lookup = $row['last_lookup_at'];
			if(isset($row['baseurl']))
				$baseurl = $row['baseurl'];
			if(isset($row['queue_index']))
				$qindex = $row['queue_index'];
			if(isset($row['ver_index']))
				$vindex = $row['ver_index'];
			
			$sdiff = "";
			$status_img = "led_green_24.png";
			get_time_difference_and_icon($last_connect, $sdiff, $status_img);
			
			$ldiff = "";
			$lookup_img = "led_green_24.png";
			get_time_difference_and_icon($last_lookup, $ldiff, $lookup_img, true);

			$status = "<img src=\"" . $img_path . $status_img . "\">";
			$lstatus = "<img src=\"" . $img_path . $lookup_img . "\">";
			$openurl = "<a href=\"$baseurl\" target=\"_blank\"><img src=\"" . $img_path . "open.png" . "\"></a>";
			
			if(strtolower($name) == "master")
				$tablerow = "<tr class=\"master\"><td class=\"status\">$openurl</td><td>$name</td>";
			else
				$tablerow = "<tr><td class=\"status\">$openurl</td><td>$name</td>";
			$tablerow .= "<td>$hostname</td><td>$cnfname</td><td>$qindex</td><td>$vindex</td><td>$address</td><td>$ldiff</td><td class=\"status\">$lstatus</td><td>$sdiff</td><td class=\"status\">$status</td></tr>\n";
			$tabletext .= $tablerow;
		}
		$tabletext .= "</table>\n";
		$response['status'] = "ok";
	}
	$response['qsize'] = $pdo->getCount($pdo->getLookupQueueTableName());
	$response['table'] = $tabletext;
	echo json_encode($response);
	exit;
}

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

function doResetServerStatusTable($pdo, $response)
{
	# 0 = View, 1 = View+Edit+Add+Delete, 2 = View+Edit, 3 = View=Edit+Add
	$accessrights = getUserAccessRights();
	if($accessrights == 0 || isAdminUser() == false)
		noPermissionQuit();
	
	$response['status'] = "notok";
	if($pdo->resetInstalledServerTable() !== false)
		$response['status'] = "ok";
	
	echo json_encode($response);
	exit;
}

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

function doResetDomainManualEdit($pdo, $response)
{
	# 0 = View, 1 = View+Edit+Add+Delete, 2 = View+Edit, 3 = View=Edit+Add
	$accessrights = getUserAccessRights();
	if($accessrights == 0)
		noPermissionQuit();
	
	$response['count'] = 0;
	$ids = getRequestVariable(ASA_RESET_DOMAIN_MANUAL_EDIT, "");
	$sids = explode(",", $ids);
	foreach($sids as $sid)
	{
		if($pdo->resetDomainManualEditInfoForSid($sid) !== false)
			$response['count']++;
	}
	
	echo json_encode($response);
	exit;
}

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

function doResetSubdomainManualEdit($pdo, $response)
{
	# 0 = View, 1 = View+Edit+Add+Delete, 2 = View+Edit, 3 = View=Edit+Add
	$accessrights = getUserAccessRights();
	if($accessrights == 0)
		noPermissionQuit();
	
	$response['count'] = 0;
	$ids = getRequestVariable(ASA_RESET_SUBDOMAIN_MANUAL_EDIT, "");
	$hids = explode(",", $ids);
	foreach($hids as $hid)
	{
		if($pdo->resetSubdomainManualEditInfo($hid) !== false)
			$response['count']++;
	}
	
	echo json_encode($response);
	exit;
}

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