<?php 

session_start();

$dhcp_override = '';
$dhcp_enabled = '';
$message = '';

$vlan_priorities = array('Best Effort','Background','Excellent Effort','Critical Applications','Video','Voice','Internetwork Control','Network Control');

if(!$_SESSION['login']){
	header("Location: login.php");
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
	
	$errorArray = array();
	$message = '';
	
	$static_ip = $_POST["static_ip"];
	$netmask = $_POST["netmask"];
	$gateway = $_POST["gateway"];
	$vlanid = $_POST["vlanid"];
	$priority = $_POST["priority"];
	$ntp = $_POST["ntp"];
	$dhcp_enabled = $_POST["dhcp_enabled"];
	$dhcp_override = $_POST["dhcp_override"];
	$reboot_appliance = $_POST["reboot_appliance"];
	$tftp = $_POST["tftp"];	 
		
	if($dhcp_enabled == 'No'){
	  if(!filter_var($_POST["static_ip"], FILTER_VALIDATE_IP)) {
		  $errorArray[] = "The Static IP is not formatted as an IP Address.";
	  }
	  if(!filter_var($_POST["netmask"], FILTER_VALIDATE_IP)) {
		  $errorArray[] = "The Netmask is not formatted as an IP Address.";
	  }
	  if(!filter_var($_POST["gateway"], FILTER_VALIDATE_IP)) {
		  $errorArray[] = "The Gateway is not formatted as an IP Address.";
	  }
	}
	
	if($vlanid && ($vlanid < 0 || $vlanid > 4094))
		$errorArray[] = "Enter a VLAN ID from 0 to 4094";
	
	if($priority && ($priority < 0 || $priority > 7))
		$errorArray[] = "Enter a 802.1p priority from 0 to 7";

	// check if the ntp is an ip address
	 $ntpArray = explode('.', $_POST["ntp"]);
	 if(is_numeric($ntpArray[0])){
		 // validate ip address
		if(!filter_var($_POST["ntp"], FILTER_VALIDATE_IP)){
		 	$errorArray[] = "The NTP Server is not formatted correctly.";		
		}
	 } else {
		 // if not an ip address check the url
		$ntp = $_POST["ntp"];
		$ntp = strtolower($ntp);
   		$ntp = preg_replace('/[^a-z0-9-.]+/', '', $ntp);
    	$ntp = str_replace(' ', '-', $ntp);
    	$ntp = trim($ntp, '-');
		 if(filter_var('http://' . $ntp, FILTER_VALIDATE_URL) != 'http://' . $_POST["ntp"]){
		 	$errorArray[] = "The NTP Server is not formatted corrctly.";	
		}
	 }	

	// check if the tftp is an ip address
	if($_POST["tftp"]!=''){
		 $tftpArray = explode('.', $_POST["tftp"]);
		 if(is_numeric($tftpArray[0])){
			 // validate ip address
			if(!filter_var($_POST["tftp"], FILTER_VALIDATE_IP)){
				$errorArray[] = "The TFTP Server is not formatted correctly.";		
			}
		 } else {
			 // if not an ip address check the url
			$tftp = $_POST["tftp"];
			$tftp = strtolower($tftp);
			$tftp = preg_replace('/[^a-z0-9-.]+/', '', $tftp);
			$tftp = str_replace(' ', '-', $tftp);
			$tftp = trim($tftp, '-');
			 if(filter_var('http://' . $tftp, FILTER_VALIDATE_URL) != 'http://' . $_POST["tftp"]){
				$errorArray[] = "The TFTP Server is not formatted corrctly.";	
			}
		 }	
	}

	if(count($errorArray)>0){
		// show error messages
		$message = '<div class="isa_error"><i class="fa fa-times-circle"></i><div class="message_content">';
		foreach($errorArray as $error){
			$message .= $error . '<br>';
		}
		$message .= '</div></div>';
	} else if($dhcp_enabled=='No' && (empty($static_ip) || empty($netmask) || empty($gateway))){
		$message = '<div class="isa_error"><i class="fa fa-check"></i><div class="message_content">';
		$message .='Static IP, Gateway, and Netmask are required if DHCP is set to No.<br>';
		$message .= '</div></div>';
	} else {
		
		// show success message
		$reboot ='';
		if($reboot_appliance=='Yes'){
			$reboot = 'Nyquist appliance rebooted.';
			$_SESSION['saved'] = 'yes-reboot';
		} else {
			$reboot = '';
			$_SESSION['saved'] = 'yes';
		}
		$message = '<div class="isa_success"><i class="fa fa-check"></i><div class="message_content">';
		$message .='Network settings saved. '. $reboot .'<br>';
		$message .= '</div></div>';
				
		// set network script
		if($dhcp_enabled=='Yes'){
			$script_path = 'sudo /usr/local/bin/network_set webui dhcp';
			if($vlanid)
				$script_path =  $script_path . ' ' . $vlanid . ' ' . $priority;
			$run_script = shell_exec($script_path);	
			
		} else {
			$script_path1 = 'sudo /usr/local/bin/network_set webui static ' . $static_ip . ' ' . $gateway . ' ' . $netmask;
			if($vlanid)
				$script_path1 = $script_path1 . ' ' . $vlanid . ' ' . $priority;
			$run_script1 = shell_exec($script_path1);	
				
		}
		
		// run tftp script
		if($_POST["tftp"]==''){
			$script_path = 'sudo /usr/local/bin/network_set webui tftp Option66';
			$run_script = shell_exec($script_path);	
		} else {
			$script_path1 = 'sudo /usr/local/bin/network_set webui tftp ' . $tftp;
			$run_script1 = shell_exec($script_path1);
		}
		
		// set ntp
		if(!empty($ntp)){
			$script_path2 = '/usr/local/bin/clock_set ntp '.$ntp;
		  	$run_script2 = shell_exec($script_path2);
		}
		
		// reboot script
		if($reboot_appliance=='Yes'){
			$script_path3 = '/usr/local/bin/reboot_now';
		  	$run_script3 = shell_exec($script_path3);
		}
		if($dhcp_override=='Yes'){
			$script_path = '/usr/local/bin/find_tftp_server';
			$run_script = shell_exec($script_path);	
			$tftp = $run_script;
		}
		
		header("Location: /network.php");
	} 
} else {
	
  // set up the form variables
  $static_ip = '';
  $netmask = '';
  $gateway = '';
  $vlanid = '';
  $priority = '0';
  $priorityName ='0 - Best Effort';
  $ntp = '';
  $dhcp_enabled = 'No';
  $a = 0;
  $n = 0;
  $g = 0;
  $run_script = '';
  $tftp = '';
  $tftp_source = '';
  
  if($_SESSION['saved']=='yes'){
	  $message = '<div class="isa_success"><i class="fa fa-check"></i><div class="message_content">';
	  $message .='Network settings saved.<br>';
	  $message .= '</div></div>';
  } else if($_SESSION['saved']=='yes-reboot'){
	  $message = '<div class="isa_success"><i class="fa fa-check"></i><div class="message_content">';
	  $message .='Network settings saved. Nyquist appliance rebooted.<br>';
	  $message .= '</div></div>';
  }
  
  $_SESSION['saved'] = ''; // reset
  
  // load interface file and read in data
  $interface = fopen("/etc/network/interfaces", "r");
  
  // Construct the correct interface name to query
  $interface_name = 'eth0';
  if(!$interface ){
	  // show error message
	  $message = '<div class="isa_error"><i class="fa fa-times-circle"></i><div class="message_content">';
	  $message .= 'There was a problem reading the Network Interface file.';
	  $message .= '</div></div>';
  } else {
	    while(!feof($interface)) {
	  
	  $line_text = fgets($interface);
	  
	  if(preg_match('/^\s*iface (eth[[:print:]]+) inet (dhcp|static)/', $line_text, $matches) == TRUE) {	  	
		  if ($matches[2] == 'dhcp')
			$dhcp_enabled = 'Yes';
		  strtok($matches[1], '.');
		  $vlanid = strtok('.');
		  if($vlanid)
		  	$interface_name = $interface_name.'.'."$vlanid";
	  }
	  
	  if(strpos($line_text, 'address ') !== FALSE && $a==0 && $dhcp_enabled=='No'){
		  $static_ip = str_replace("address","",$line_text);
		  $static_ip = trim($static_ip);
		  $a++;
	  }
	  if(strpos($line_text, 'netmask ') !== FALSE && $n==0 && $dhcp_enabled=='No'){
		  $netmask = str_replace("netmask","",$line_text);
		  $netmask = trim($netmask);
		  $n++;
	  }
	  if(strpos($line_text, 'gateway ') !== FALSE && $g==0 && $dhcp_enabled=='No'){
		  $gateway = str_replace("gateway","",$line_text);
		  $gateway = trim($gateway);
		  $g++;
	  }
  }
  fclose($interface);

  // Find out the current priority on vlan interface
  if($vlanid) {
  	$script_path = "sudo sed -zn '/EGRESS/s/.*EGRESS.*0:\([[:digit:]]\).*/\\1/p' /proc/net/vlan/$interface_name";
  	$priority = shell_exec($script_path);
	  
	if (isset($vlan_priorities[$priority])) {
		$priorityName = $priority . ' - ' . $vlan_priorities[$priority];
	}
  }

  if($dhcp_enabled == 'Yes'){ // grab dhcp ip address info from ifconfig
	  $static_ip_search = "/sbin/ifconfig $interface_name | grep 'inet addr:'| cut -d: -f2 | awk '{ print $1}'";
	  $static_ip = shell_exec($static_ip_search);
	  $static_ip = trim($static_ip);
	  
	  $gateway_search = "/sbin/ip route show";
	  $gateway = shell_exec($gateway_search);
	  $gateway = str_replace("default via","",$gateway);
	  $gateway = strstr($gateway, "dev $interface_name", TRUE);
	  $gateway = trim($gateway);
	  
	  $netmask_search = "/sbin/ifconfig $interface_name | grep 'inet addr:'| cut -d: -f4 | awk '{ print $1}'";
	  $netmask = shell_exec($netmask_search);
	  $netmask = trim($netmask);
	  
	  $ntp_search = "ntpq -p | grep '*' | cut -d ' ' -f 1 | tr -d '*'";
	  $ntp = shell_exec($ntp_search);
	  $ntp = trim($ntp);
  }
 
  }
 
  // load ntp conf file and read in data
  $ntp_conf = fopen("/etc/ntp.conf", "r");
  
  if(!$ntp_conf){
	  // show error message
	  $message = '<div class="isa_error"><i class="fa fa-times-circle"></i><div class="message_content">';
	  $message .= 'There was a problem reading the NTP Configuration file.';
	  $message .= '</div></div>';
  } else {
	   while(!feof($ntp_conf)) {
	  
		  $line_text = fgets($ntp_conf);
			  
		  if(strpos($line_text, ' iburst') !== FALSE){
			  if(strpos($line_text, 'pool.ntp.org') !== FALSE){
				  $ntp = 'pool.ntp.org';
			  } else {
				$ntp = str_replace("iburst","",$line_text);
				$ntp = str_replace("server","",$ntp);
				$ntp = trim($ntp);
			  }
		  }
  	}
  	fclose($ntp_conf);
  }  
  
  // load network config for tftp server address and read in data
  $config_file = fopen("/opt/bogen/appliance/network.config", "r");
  
  if(!$config_file){
	  // show error message
	  $message = '<div class="isa_error"><i class="fa fa-times-circle"></i><div class="message_content">';
	  $message .= 'There was a problem reading the Network Configuration file.';
	  $message .= '</div></div>';
  } else {
		
	while(!feof($config_file)) {
	
	$line_text = fgets($config_file);
		
	  if(strpos($line_text, 'TFTP Server: ') !== FALSE){
				  $tftp = str_replace("TFTP Server: ","",$line_text);
				  $tftp = trim($tftp);
	  }
	  if(strpos($line_text, 'TFTP Source: ') !== FALSE){
				  $tftp_source = str_replace("TFTP Source: ","",$line_text);
				  $tftp_source = trim($tftp_source);
	  }
	}
	fclose($config_file);
	
	if($tftp_source == 'Option 66'){
		// if DHCP Server Override is Yes get the TFTP Address
		$script_path = '/usr/local/bin/find_tftp_server';
		$run_script = shell_exec($script_path);	
		$tftp = $run_script;
	}
  }  
}
?>

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="description" content="">
<meta name="author" content="Bogen Communications LLC">
<meta name="copyright" content="Bogen Communications LLC">
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />
<link rel="shortcut icon" href="">
<link rel="stylesheet" href="/css/styles.css">
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/font-awesome/css/font-awesome.min.css">
<link rel="icon" type="image/png" href="/favicon.png" />
<title><?php echo $_SESSION['device_type']; ?> (<?php echo $_SESSION['device_name']; ?>) - Network Settings</title>
</head>

<body>
<div class="container">

<?php include 'navbar.php';?>

<h4><strong><i class="fa fa-sitemap"></i> Network Settings</strong>&nbsp;&nbsp;<a href="/help/<?php echo $_SESSION['device_id']; ?>/#t=<?php echo $_SESSION['help_network']; ?>" type="button" class="btn btn-xs btn-primary" target="_blank"><i class="fa fa-question-circle"></i></a>&nbsp;&nbsp;<button  class="btn btn-xs btn-primary" id="ntcButton" type="button" onClick="check_login('ntcCheck')"><i class='fa fa-exchange'></i> Network Traffic Capture</button></h4>
<form action="network.php" method="post">
<div id="status"></div>
<div id="message_container"><?php echo $message; ?></div>
<table class="table-condensed">
<tr>
<td><strong>IP Address:</strong></td>
<td><input type="text" class="form-control" name="static_ip" id="static_ip" placeholder="" style="width:200px;" value="<?php echo $static_ip; ?>"></td>
<td></td>
</tr>
<tr>
<td><strong>Netmask:</strong></td>
<td><input type="text" class="form-control" name="netmask" id="netmask" placeholder="" style="width:200px;" value="<?php echo $netmask; ?>"></td>
<td></td>
</tr>
<tr>
<td><strong>Gateway:</strong></td>
<td><input type="text" class="form-control" name="gateway" id="gateway" placeholder="" style="width:200px;" value="<?php echo $gateway; ?>"></td>
<td></td>
</tr>
<tr>
<td><strong>VLAN ID:</strong></td>
<td><input type="text" class="form-control" name="vlanid" id="vlanid" placeholder="" style="width:200px;" value="<?php echo $vlanid; ?>"></td>
<td></td>
</tr>
<tr>
<td><strong>VLAN Priority:</strong></td>
<td>
<input name="priority" id="priority" type="hidden" value="<?php echo $priority; ?>">
<input name="priority_name" id="priority_name" type="hidden" value="<?php echo $priorityName; ?>">
<div class="btn-group priority-btn">
  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
    <span class="selection"><?php echo $priorityName; ?></span>&nbsp;<span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu">
    <?php foreach($vlan_priorities as $key => $vlan_priority){ ?>
		<li><a href="javascript:void(0)" class="priority-action" data-value="<?php echo $key ?>"><?php echo $key; ?> - <?php echo $vlan_priority; ?></a></li>
	<?php } ?>
  </ul>
</div>
</td>
<td></td>
</tr>
<tr>
<td><strong>NTP Server:</strong></td>
<td><input type="text" class="form-control" name="ntp" placeholder="" style="width:200px;" value="<?php echo $ntp; ?>" readonly></td>
<td></td>
</tr>
<tr>
<td><strong>TFTP Server:</strong></td>
<input type="hidden" name="tftp_source" id="tftp_source" value="<?php echo $tftp_source;?>">
<td><input type="text" class="form-control" id="tftp" name="tftp" placeholder="" style="width:200px;" value="<?php echo $tftp; ?>"></td>
<td></td>
</tr>
<tr>
<td><strong>TFTP Server from DHCP:</strong></td>
<td>
	<select name="dhcp_override" id="dhcp_override" onchange="dhcpOverride()">
  		<option value="No" <?php if($dhcp_override=='No'){ echo 'selected'; }?>>No</option>
  		<option value="Yes" <?php if($dhcp_override=='Yes'){ echo 'selected'; }?>>Yes</option>
	</select>
</td>
<td></td>
</tr>
<tr>
<td><strong>DHCP Enabled:</strong></td>
<td>
	<select name="dhcp_enabled" id="dhcp_enabled" onchange="dhcpChanged()">
  		<option value="No" <?php if($dhcp_enabled=='No'){ echo 'selected'; }?>>No</option>
  		<option value="Yes" <?php if($dhcp_enabled=='Yes'){ echo 'selected'; }?>>Yes</option>
	</select>
</td>
<td></td>
</tr>
<tr>
<td><strong>Reboot Appliance:</strong></td>
<td>
	<select name="reboot_appliance">
  		<option value="No">No</option>
  		<option value="Yes">Yes</option>
	</select>
</td>
<td></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
</table>
<button class="btn btn-xs btn-success" type="submit" onClick="show_processing()"><i class="fa fa-floppy-o"></i>&nbsp;&nbsp;Save</button>
</form>
	
<!--  start Network Traffic Capture modal -->
<div class="modal ntcModal" tabindex="-1" role="dialog" aria-labelledby="ntcModal" data-backdrop="static" data-keyboard="false">
	<div class="modal-dialog">
	<div class="modal-content">
			 <div class="modal-header">    
			<h4 class="modal-title"><p align="center">Network Traffic Capture</p></h4>
			</div>
			<form method="POST" action="" id="ntc_form" class="form-horizontal" enctype="multipart/form-data">
			<input type="hidden" name="_token" value="{{ csrf_token() }}">
				<div class="modal-body">
                	<div class="row">
                		<div class="col-md-12" style="max-height:410px;overflow-y: auto;">
                            <div align="left">
                                    The Network Traffic Capture feature uses <strong><a href="https://www.tcpdump.org/manpages/tcpdump.1-4.9.3.html" target="_blank">tcpdump</a></strong> to capture network traffic into a PCAP file that can be viewed with any application that can read PCAP files. See <strong><a href="https://www.tcpdump.org/manpages/tcpdump.1-4.9.3.html" target="_blank">tcpdump</a></strong> documentation for information related to the <strong>Options</strong> and <strong>Expression</strong> fields.<br><br>
								<div id="status2"></div>
								<table class="table">
									<tr>
										<td width="250" style="border-top: none;"><strong>Capture Seconds (default: 900): <a data-toggle="tooltip" data-placement="right" title='The number of seconds to capture network traffic. Warning: Long capture times may consume a lot of disk space. Default: 900'><i class='fa fa-lg fa-info-circle'></i></a></strong></td>
										<td style="border-top: none;"><input id="ntc_capture_seconds" name="ntc_capture_seconds" type="text" value="" placeholder=""></td>
									</tr>
									<tr>
										<td style="border-top: none;"><strong>Tcpdump Options (optional): <a data-toggle="tooltip" data-placement="right" title='Command line options to use with the tcpdump command. Only a few tcpdump options are supported, and none of the Print  modification related options are supported. Warning: Do not use unless you know what you’re doing. Default: -i any'><i class='fa fa-lg fa-info-circle'></i></a></strong></td>
										<td style="border-top: none;"><input id="ntc_options" name="ntc_options" type="text" value="" placeholder=""></td>
									</tr>
									<tr>
										<td style="border-top: none;"><strong>Tcpdump Expression (optional): <a data-toggle="tooltip" data-placement="right" title='Optional filter expression to use with the tcpdump comand.'><i class='fa fa-lg fa-info-circle'></i></a></strong></td>
										<td style="border-top: none;"><input id="ntc_expression" name="ntc_expression" style="min-width:300px;" type="text" value="" placeholder=""></td>
									</tr>
								</table>
								<textarea id="ntc_status" name="ntc_status" rows="8" cols="15" style="width:565px;font-size:14px;resize:none;" readonly></textarea>
								<br>
                            </div>
                		</div>
                      </div>
      			</div>
				</form>
			<div class="modal-footer justify-content-between">
				 <button type="button" style="margin-left:10px;float: left;" class="btn btn-danger" id="deletePCAPButton" onClick="check_login('deletePCAP');"><i class='fa fa-trash'></i> Delete PCAP</button>
				<button type="button" style="margin-left:10px;float: left;" class="btn btn-primary" id="downloadPCAPButton" onClick="check_login('downloadPCAP');"><i class='fa fa-download'></i> Download PCAP</button>
				<div>
                    <button type="button" class="btn btn-default" id="closeNTCButton" data-dismiss="modal" onClick="check_login('close');" >Close</button>
                    <button type="button" style="margin-left:10px;" class="btn btn-success" id="startNTCButton" onClick="check_login('startNTC');;"><i class='fa fa-chevron-circle-right'></i>  Start</button>
                    <button type="button" style="margin-left:10px;" class="btn btn-danger" id="cancelNTCButton" onClick="check_login('cancelNTC');"><i class='fa fa-close'></i> Cancel</button>
                    <button type="button" style="margin-left:10px;" class="btn btn-danger" id="stopNTCButton" onClick="check_login('stopNTC');"><i class='fa fa-stop'></i> Stop</button>
                    &nbsp;<span id="ntc_spinner"</span>
				</div>
			</div>
		  </form>
	</div>  							
	</div>
	</div>
<!--  end Network Traffic Capture modal -->

<!--  start Capture already running modal -->
<div class="modal ntcRunning" tabindex="-1" role="dialog" aria-labelledby="ntcRunning" data-backdrop="static" data-keyboard="false">
	<div class="modal-dialog">
	<div class="modal-content">
			 <div class="modal-header">    
			<h4 class="modal-title"><p align="center">Network Traffic Capture</p></h4>
			</div>
				<div class="modal-body">
                	<div class="row">
                		<div class="col-md-12" style="max-height:410px;overflow-y: auto;">
                            <div align="left">
                                   A network capture is already running; would you like to stop the currently running capture?
                            </div>
                		</div>
                      </div>
      			</div>
			<div class="modal-footer">
                    <button type="button" class="btn btn-danger" id="noNTCButtonRunning" data-dismiss="modal">No</button>
                    <button type="button" style="margin-left:10px;" class="btn btn-success" id="yesNTCButtonRunning" onClick="stopNTC('2');">Yes</button>&nbsp;<span id="ntc_running_spinner"</span>
			</div>
		  </form>
	</div>  							
	</div>
	</div>
<!--  end Capture already running modal -->
</div>
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
</body>
</html>
<script>
	
var nqnetcap_status;
	
window.onload = function() {  
	// clear message after 5 seconds
	setTimeout(function(){ 
		document.getElementById("message_container").innerHTML = '';
	}, 5000);
	
	var dhcp_enabled = document.getElementById("dhcp_enabled").value;
	var tftp_source = document.getElementById("tftp_source").value;
	if(dhcp_enabled=='Yes'){
		
		document.getElementById("static_ip").disabled = true;
		document.getElementById("netmask").disabled = true;
		document.getElementById("gateway").disabled = true;
		
		if(tftp_source=='Option 66'){
			document.getElementById("dhcp_override").disabled = false;
			document.getElementById("dhcp_override").value = "Yes";
			document.getElementById("tftp").disabled = true;
		} else { // Static
			document.getElementById("dhcp_override").disabled = false;
			document.getElementById("dhcp_override").value = "No";
			document.getElementById("tftp").disabled = false;
		}
		
		
	} else {
		document.getElementById("dhcp_override").disabled = true;
		document.getElementById("dhcp_override").value = "No";
		document.getElementById("tftp").disabled = false;
	}	
}

// dhcpChanged
function dhcpChanged(){
	var dhcp_enabled = document.getElementById("dhcp_enabled").value;
	if(dhcp_enabled=='Yes'){
		document.getElementById("dhcp_override").disabled = false;
		document.getElementById("static_ip").disabled = true;
		document.getElementById("netmask").disabled = true;
		document.getElementById("gateway").disabled = true;
		
	} else {
		document.getElementById("dhcp_override").disabled = true;
		document.getElementById("dhcp_override").value = "No";
		document.getElementById("tftp").disabled = false;
		document.getElementById("static_ip").disabled = false;
		document.getElementById("netmask").disabled = false;
		document.getElementById("gateway").disabled = false;
	}	
}
// dhcpOverride
function dhcpOverride(){
	var dhcp_override = document.getElementById("dhcp_override").value;
	if(dhcp_override=='Yes'){
		document.getElementById("tftp").disabled = true;
		document.getElementById("tftp").value = "";
	} else {
		document.getElementById("tftp").disabled = false;
	}
}
// show_processing
function show_processing(){
	document.getElementById("status").innerHTML = '<i class="fa fa-refresh fa-spin fa-fw"></i> <strong>Processing ... </strong>';
	
}
// priority drop down
	$(".priority-action").click(function(){
		$(this).parents(".priority-btn").find('.selection').text($(this).text());
  		$(this).parents(".priority-btn").find('.selection').val($(this).data('value'));
		document.getElementById("priority").value = $(this).data('value');
		document.getElementById("priority_name").value = $(this).text();
		$('.open').removeClass('open');
		return false;
	});
function ntcCheck(){
	
	var xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            // success 
            // console.log(xmlhttp.responseText);
			if(xmlhttp.responseText=='1'){
				document.getElementById("ntc_running_spinner").innerHTML = '';
                document.getElementById("noNTCButtonRunning").disabled = false;
                document.getElementById("yesNTCButtonRunning").disabled = false;
                $('.ntcRunning').modal('show');
			} else {
				ntcModal('1');
			}
		}
    }
	xmlhttp.open("GET","scripts.php?s=ntc_check",true);
    xmlhttp.send();
}
	
function check_login(data){
	
	var xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            // success 
            // console.log(xmlhttp.responseText);
			if(xmlhttp.responseText=='1'){
				if(data=='ntcCheck'){
				   ntcCheck();
				}
				if(data=='deletePCAP'){
				   deletePCAP(1);
				}
				if(data=='downloadPCAP'){
				   downloadPCAP();
				}
				if(data=='close'){
				}
				if(data=='startNTC'){
				   startNTC();
				}
				if(data=='cancelNTC'){
				   cancelNTC();
				}
				if(data=='stopNTC'){
				   stopNTC('1');
				}
			} else {
			  window.location.href = 'login.php';
			}
		}
    }
	xmlhttp.open("GET","scripts_no_login.php?s=check_login",true);
    xmlhttp.send();
}
	
// Network Traffic Capture modal
function ntcModal(mode){
		
	$("#deletePCAPButton").hide();
	$("#downloadPCAPButton").hide();
	
	// check for pcap and size
	statPCAP();
	
	nqnetcap_status = '';
	document.getElementById("ntc_spinner").innerHTML = '';
	$("#startNTCButton").show();
	$("#stopNTCButton").hide();
	$("#cancelNTCButton").hide();
	
	document.getElementById("ntc_capture_seconds").disabled = false;
	document.getElementById("ntc_options").disabled = false;
	document.getElementById("ntc_expression").disabled = false;
	
	document.getElementById("ntc_capture_seconds").value = '';
	document.getElementById("ntc_options").value = '';
	document.getElementById("ntc_expression").value = '';
	document.getElementById("ntc_status").value = '';
	
	$('.ntcModal').modal('show');
}
function startNTC(){
	
	document.getElementById("stopNTCButton").disabled = false;
	document.getElementById("cancelNTCButton").disabled = false;
	
	nqnetcap_status = 'start';
	document.getElementById("ntc_status").value = 'Network Traffic Capture Running ...';
	var ntc_capture_seconds = document.getElementById("ntc_capture_seconds").value;
	var ntc_options = document.getElementById("ntc_options").value;
	var ntc_expression = document.getElementById("ntc_expression").value;
	var ntc_capture_seconds_check = 0;
	
	// check Capture Seconds for integer 0 or greater
	if(parseInt(ntc_capture_seconds)>0 || ntc_capture_seconds==''){
	  	ntc_capture_seconds_check = 1;
	 } 
	
	if(ntc_capture_seconds_check==0){
	
		setStatus2('danger','Capture Seconds must be greater than 0.');
		
	} else {
	  // Tcpdump Options remove $&\ (and single-quote ' and back-tick `)
      ntc_options = ntc_options.replaceAll(/[`'$&\\]/gi, '');

      // Tcpdump Expression remove back-tick
      ntc_expression = ntc_expression.replaceAll(/[`]/gi, '');

      document.getElementById("ntc_capture_seconds").disabled = true;
      document.getElementById("ntc_options").disabled = true;
      document.getElementById("ntc_expression").disabled = true;

      document.getElementById("ntc_spinner").innerHTML = ' <i class="fa fa-refresh fa-spin fa-fw margin-bottom"></i>';
      $("#startNTCButton").hide();
      // $("#closeNTCButton").hide();
	  $("#deletePCAPButton").hide();
	  $("#downloadPCAPButton").hide();
      $("#stopNTCButton").show();
      $("#cancelNTCButton").show();
		
	  // base64 encode
	  var data = btoa(ntc_capture_seconds+','+ntc_options+','+ntc_expression);
			
		var xmlhttp=new XMLHttpRequest();
        xmlhttp.onreadystatechange=function() {
            if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                // success 
                // console.log(xmlhttp.responseText);
				
				var responseArray = xmlhttp.responseText.split(":");
				var response_code = responseArray[0];
				var response_text = responseArray[1];
				
				document.getElementById("ntc_capture_seconds").disabled = false;
                document.getElementById("ntc_options").disabled = false;
                document.getElementById("ntc_expression").disabled = false;

                document.getElementById("ntc_spinner").innerHTML = '';
                $("#startNTCButton").show();
                // $("#closeNTCButton").show();
                $("#stopNTCButton").hide();
                $("#cancelNTCButton").hide();
				
				if(response_code=='1'){
					
					if(nqnetcap_status=='start' || nqnetcap_status=='stop'){
						
						// stat pcap
						statPCAP();
						
						// show log
						getNTCStatusText('0');
						   
					   	// download pcap file
						downloadPCAP();	
					}
					if(nqnetcap_status=='cancel' ){
						
						$("#deletePCAPButton").hide();
						$("#downloadPCAPButton").hide();
						
						// show cancelled
					    document.getElementById("ntc_status").value = 'Cancelled';
								
						// added 4 second delay on Cancel to prevent delete button appearing when no file exists
						setTimeout(deletePCAP(2), 4000);
						
						// stat pcap
						statPCAP();
					}
				}
				if(response_code=='0'){
					
					// show error
				   	document.getElementById("ntc_status").value = response_text;
					
					// add log
					getNTCStatusText('1');
				}
				
				check_login();
            }
        };
		xmlhttp.open("GET","scripts.php?s=start_ntc&d="+data,true);
        xmlhttp.send();	
	}
}
function stopNTC(mode){
	
	nqnetcap_status = 'stop';
	document.getElementById("ntc_status").value = 'Stopping ...';
	document.getElementById("stopNTCButton").disabled = true;
	document.getElementById("cancelNTCButton").disabled = true;
	
	if(mode=='2'){
        document.getElementById("ntc_running_spinner").innerHTML = ' <i class="fa fa-refresh fa-spin fa-fw margin-bottom"></i>';
        document.getElementById("noNTCButtonRunning").disabled = true;
        document.getElementById("yesNTCButtonRunning").disabled = true;
        setTimeout(show_modal_after_running, 5000)  
	}
	
	var xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            // success 
            // console.log(xmlhttp.responseText);
			check_login();
        }
    }
	xmlhttp.open("GET","scripts.php?s=stop_ntc",true);
    xmlhttp.send();	
	
}
function show_modal_after_running(){
	
	$('.ntcRunning').modal('hide');
	ntcModal('1');
}
function cancelNTC(){
	nqnetcap_status = 'cancel';
	document.getElementById("ntc_status").value = 'Cancelling ...';
	document.getElementById("stopNTCButton").disabled = true;
	document.getElementById("cancelNTCButton").disabled = true;
	
	var xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            // success 
            // console.log(xmlhttp.responseText);
        }
    }
	xmlhttp.open("GET","scripts.php?s=stop_ntc",true);
    xmlhttp.send();	
	
}
function getNTCStatusText(add){
	
	var xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            // success 
            // console.log(xmlhttp.responseText);
			if(xmlhttp.responseText!=''){
				
				var status = document.getElementById("ntc_status").value;
				
				if(add=='1'){
				   	document.getElementById("ntc_status").value = status + '\n\n' + xmlhttp.responseText;
				} else {
					document.getElementById("ntc_status").value = xmlhttp.responseText;
				}
				
				// scroll to bottom of status_text
				// var $textarea = $('#ntc_status');
    			// $textarea.scrollTop($textarea[0].scrollHeight);
			}
        }
    }
	xmlhttp.open("GET","scripts.php?s=get_ntc_status_text",true);
    xmlhttp.send();	
}
function deletePCAP(mode){
	if(mode==1){
		document.getElementById("ntc_status").value = '';
	}
	
	var xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            // success 
            // console.log(xmlhttp.responseText);
			$("#deletePCAPButton").hide();
			$("#downloadPCAPButton").hide();
			
			if(mode==1){
				setStatus2('success','PCAP file deleted.');
			}
		}
    }
	xmlhttp.open("GET","scripts.php?s=delete_pcap",true);
    xmlhttp.send();	
}
function statPCAP(){
	
	var xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            // success 
            // console.log(xmlhttp.responseText);
			if(xmlhttp.responseText!=''){
			     document.getElementById("deletePCAPButton").innerHTML = '<i class=\'fa fa-trash\'></i> Delete PCAP ('+xmlhttp.responseText+')';
				$("#deletePCAPButton").show();
				$("#downloadPCAPButton").show();
				getNTCStatusText('0');
			} else {
				$("#deletePCAPButton").hide();
				$("#downloadPCAPButton").hide();
			}
		}
    }
	xmlhttp.open("GET","scripts.php?s=stat_pcap",true);
    xmlhttp.send();	
}
function downloadPCAP(){
	window.location = 'https://'+location.host+'/exports/nqnetcap.pcap';
}
function setStatus2(level,text){
	
	// levels: info, warning, success, danger
	document.getElementById("status2").innerHTML =  '<div class="alert alert-'+level+'">'+text+'</div>';
	
	setTimeout(function(){ 
		document.getElementById("status2").innerHTML = '';
	}, 7000);
}
//  tooltip
$(function () {
  $('[data-toggle="tooltip"]').tooltip()
})
</script>