<?php 

session_start();

$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"];
	$dns = $_POST["dns"];
	$vlanid = $_POST["vlanid"];
	$priority = $_POST["priority"];
	$priorityName = $_POST["priority_name"];
	$ntp = $_POST["ntp"];
	$ntpServerConfig = $_POST["ntp_server_config"];
	$ntpServerConfigName = $_POST["ntp_server_config_name"];
	$dhcp_enabled = $_POST["dhcp_enabled"];
	$reboot_appliance = $_POST["reboot_appliance"];
	
	if($dhcp_enabled == 'No'){
	  if(!filter_var($_POST["static_ip"], FILTER_VALIDATE_IP)) {
		  $errorArray[] = "The IP Address 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('.', $ntp);
	 if(is_numeric($ntpArray[0])){
		 // validate ip address
		if(!filter_var($ntp, FILTER_VALIDATE_IP)){
		 	$errorArray[] = "The NTP Server is not formatted correctly.";		
		}
	 } else if($ntp!=''){
		 // if not an ip address check the url
		$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://' . $ntp){
		 	$errorArray[] = "The NTP 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 .='IP Address, 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);	
				
		}
		
		// set ntp
		if(!empty($ntp)){
			$script_path2 = '/usr/local/bin/clock_set ntp '.$ntp;
		  	$run_script2 = shell_exec($script_path2);
		}
		
		// set dns
		if(!empty($dns)){
			$script_path_dns = 'sudo /usr/local/bin/nyquist_dns set "'.$dns.'"';
			$run_script_dns = shell_exec($script_path_dns);
		}
		
		// reboot script
		if($reboot_appliance=='Yes'){
			$script_path3 = '/usr/local/bin/reboot_now';
		  	$run_script3 = shell_exec($script_path3);
		}
		
		// reload page to fill in network fields
		header('Location: http://'.$_SERVER['SERVER_NAME'].''.$_SERVER['REQUEST_URI']);
		
		/*
		// edit standalone.config
		// read the current file
        $standalone = fopen("/etc/nyquist/standalone.config", "r");
        $config_file_array = array();
        if(!$standalone){
          // 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 Standalone Configuration file.';
          $message .= '</div></div>';
         } else { 
            // go through the config file one line at a time
            while(!feof($standalone)){
                $line_text = fgets($standalone);
                array_push($config_file_array,$line_text);
            }
            fclose($config_file);
        }

        // search through rows and insert changes
        $edited_array = array();
        foreach($config_file_array as $key => $row){

            if(strpos($row, 'NTP_SERVER_CONFIG =') !== FALSE){
                $new_row = 'NTP_SERVER_CONFIG = '. $ntpServerConfig. '' . PHP_EOL;
                array_push($edited_array, $new_row);

            } else if(strpos($row, 'NTP_SERVER =') !== FALSE){
                $new_row = 'NTP_SERVER = '. $ntp . '' . PHP_EOL;
                array_push($edited_array, $new_row);
			} else if(strpos($row, 'VLAN_ID =') !== FALSE){
                $new_row = 'VLAN_ID = '. $vlanid . '' . PHP_EOL;
                array_push($edited_array, $new_row);

            } else if(strpos($row, 'PRIORITY_802_1P =') !== FALSE){
                $new_row = 'PRIORITY_802_1P = '. $priority . '' . PHP_EOL;
                array_push($edited_array, $new_row);
            } else { 
                array_push($edited_array, $row);
            } 
        }

        // create new file
        $new_config_file = '';
        foreach($edited_array as $row){
            $new_config_file .= $row;
        }

        // write the file
        $config_file = fopen("/etc/nyquist/standalone.config", "w");

        if(!$config_file){
            // show error message
            $message = '<div class="isa_error"><i class="fa fa-times-circle"></i><div class="message_content">';
            $message .= 'Save failed. There was a problem writing to the Standalone Configuration file.';
            $message .= '</div></div>';

        } else {
            // complete write
            fwrite($config_file, $new_config_file);
            fclose($config_file);	
			
			$script_path = 'sudo /usr/local/bin/update_configuration';
			$run_script = shell_exec($script_path);
			
			// show success message
            $message = '<div class="isa_success"><i class="fa fa-check"></i><div class="message_content">';
            $message .='Network settings saved.<br>';
            $message .= '</div></div>';
        }
		
		*/
	} 
} else {
	
	  $static_ip = '';
      $netmask = '';
      $gateway = '';
	  $dns = '';
      $vlanid = '';
      $priority = '0';
      $priorityName ='0 - Best Effort';
      $ntp = '';
	  $ntpServerConfig = 'none';
      $ntpServerConfigName = 'None';
      $dhcp_enabled = 'No';
      $a = 0;
      $n = 0;
      $g = 0;
      $run_script = '';
	
	  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);
          }
		  
	  }
	
	  // 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);
      }  
	
	// get dns
	$script_path_dns = 'sudo /usr/local/bin/nyquist_dns get';
	$run_script_dns = shell_exec($script_path_dns);	
	$dns = $run_script_dns;	
	$dns = str_replace(PHP_EOL, ' ', $dns);
		  	  
	/*
      // get standalone.config data
      $standalone = fopen("/etc/nyquist/standalone.config", "r");
	
      if(!$standalone){
          // 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 Standalone Configuration file.';
          $message .= '</div></div>';
      } else {
            while(!feof($standalone)) {

              $line_text = fgets($standalone);

              if(strpos($line_text, 'VLAN_ID =') !== FALSE){
                  $vlanid = str_replace("VLAN_ID = ","",$line_text);
                  $vlanid = trim($vlanid);
              }
              if(strpos($line_text, 'PRIORITY_802_1P =') !== FALSE){
                  $priority = str_replace("PRIORITY_802_1P = ","",$line_text);
                  $priority = trim($priority);
				  if($priority==''){
					  $priority = 0;
				  }
				  $priorityName = $priority.' - '.$vlan_priorities[3];
              }
              if(strpos($line_text, 'NTP_SERVER_CONFIG =') !== FALSE){
                  $ntpServerConfig = str_replace("NTP_SERVER_CONFIG =","",$line_text);
                  $ntpServerConfig = trim($ntpServerConfig);
				  if($ntpServerConfig=='ntpserver'){
					  $ntpServerConfigName ='NTP Server';
				  }
              }
			  if(strpos($line_text, 'NTP_SERVER =') !== FALSE){
                  $ntp = str_replace("NTP_SERVER = ","",$line_text);
                  $ntp = trim($ntp);
              }
          }
      	fclose($standalone);
    }
	
	*/
}
?>

<!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></h4>
<form action="network_s.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>DNS:</strong></td>
<td><input type="text" class="form-control" name="dns" id="dns" placeholder="" style="width:200px;" value="<?php echo $dns; ?>"></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>	
<?php /* ?>
<tr>
<td><strong>NTP Server Configuration:</strong></td>
<td>
<input name="ntp_server_config" id="ntp_server_config" type="hidden" value="<?php echo $ntpServerConfig; ?>">
<input name="ntp_server_config_name" id="ntp_server_config_name" type="hidden" value="<?php echo $ntpServerConfigName; ?>">
<div class="btn-group ntp-server-config-btn">
  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
    <span class="selection"><?php echo $ntpServerConfigName; ?></span>&nbsp;<span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu">  
	  <li><a href="javascript:void(0)" class="ntp-server-config-action" data-value="none">None</a></li>
	  <li><a href="javascript:void(0)" class="ntp-server-config-action" data-value="ntpserver">NTP Server</a></li>
  </ul>
</div>
</td>
<td></td>
</tr>
<?php */ ?>
<tr>
<td><strong>NTP Server:</strong></td>
<td><input type="text" class="form-control" name="ntp" placeholder="" style="width:200px;" value="<?php echo $ntp; ?>"></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>
</div>
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
</body>
</html>
<script>
window.onload = function() {  
	// clear message after 5 seconds
	setTimeout(function(){ 
		document.getElementById("message_container").innerHTML = '';
	}, 5000);
	
	var dhcp_enabled = document.getElementById("dhcp_enabled").value;
	if(dhcp_enabled=='Yes'){
		
		document.getElementById("static_ip").disabled = true;
		document.getElementById("netmask").disabled = true;
		document.getElementById("gateway").disabled = true;
	} else {
		
	}	
}
// dhcpChanged
function dhcpChanged(){
	var dhcp_enabled = document.getElementById("dhcp_enabled").value;
	if(dhcp_enabled=='Yes'){
		document.getElementById("static_ip").disabled = true;
		document.getElementById("netmask").disabled = true;
		document.getElementById("gateway").disabled = true;
		
	} else {
		document.getElementById("static_ip").disabled = false;
		document.getElementById("netmask").disabled = false;
		document.getElementById("gateway").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;
});
// ntp_server_config drop down
$(".ntp-server-config-action").click(function(){
    $(this).parents(".ntp-server-config-btn").find('.selection').text($(this).text());
    $(this).parents(".ntp-server-config-btn").find('.selection').val($(this).data('value'));
    document.getElementById("ntp_server_config").value = $(this).data('value');
    document.getElementById("ntp_server_config_name").value = $(this).text();
    $('.open').removeClass('open');
    return false;
});
</script>