<?
/**
 * VoiceOne Settings/System/CLI
 *
 * Frontend to provide access to the system Command Line Interface  
 * @package voiceone
 * @subpackage  settings_system_cli
 */
  include ("../../../admin/config/cfg.php");
  global $cwlang, $cwLanguage;
  require_once("$absBasePath/lib/xajax/xajax.inc.php");
  $alert=getAlert();
  //================ XAJAX ================
	function isValidIP($string){
  	if(strpos($string," ")!==false) return false;
    if(strpos($string,".")===false) return false;
    $stringArr=explode(".",$string);
    if((!is_array($stringArr))||(count($stringArr)!=4)) return false;
    foreach($stringArr as $field){
    	if((trim($field)=="")||(!is_numeric($field))||($field<0)||($field>255)) return false;
      for($i=0; $i<strlen($field); $i++){
        $ch=ord($field[$i]);
        if(!(($ch>47)&&($ch<58))) return false;
     	}
    }
    return true;
  }
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    $confirmBeforeSubmit="";
    //extract form params
    $form=$formData["network"];
    $host=$form["host"];
    $domain=$form["domain"];
    $address=$form["address"];
		$netmask=$form["netmask"];
    $network=$form["network"];
    $broadcast=$form["broadcast"];
    $gateway=$form["gateway"];
    $dns1=$form["dns1"];
    $dns2=$form["dns2"];
    $dhcp_range_from=$form["dhcp_range_from"];
    $dhcp_range_to=$form["dhcp_range_to"];
    if(isset($form["vpn_range_from"])) $vpn_range_from=$form["vpn_range_from"];
    if(isset($form["vpn_range_to"])) $vpn_range_to=$form["vpn_range_to"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">";
    //Check hostname (not null)&&(alphanumeric)
    $hostErr=false;
    if(trim($host)==""){
      //host must be not null
      $errOut[]= T_("Host name must be not null");
      $objResponse->addAssign("hostErr","innerHTML",$imgErr);
      $hostErr=true;
    }else{
      //host must be alphanumeric or "-"
      for($i=0; $i<strlen($host); $i++){
        $ch=ord($host[$i]);
        if(!((($ch>96)&&($ch<123))||(($ch>64)&&($ch<91))||(($ch>47)&&($ch<58))||($ch==45))){
          $errOut[]= T_("Host name allows only alphanumeric characters. Please change it");
          $objResponse->addAssign("hostErr","innerHTML",$imgErr);
          $hostErr=true;
          break;
        }
     	}
    }
    if($hostErr===false) $objResponse->addAssign("hostErr","innerHTML","");
    //Check hostname (not null)&&(alphanumeric + ".")
    $domainErr=false;
    if(trim($domain)==""){
      //domain must be not null
      $errOut[]= T_("Domain name must be not null");
      $objResponse->addAssign("domainErr","innerHTML",$imgErr);
      $domainErr=true;
    }if(substr($domain,0,1)=="."){
      //domain can not start with dot
      $errOut[]= T_("Domain can not start with dot char");
      $objResponse->addAssign("domainErr","innerHTML",$imgErr);
      $domainErr=true;
    }else{
      //domain must be alphanumeric + "."
      for($i=0; $i<strlen($domain); $i++){
        $ch=ord($domain[$i]);
        if(!((($ch>96)&&($ch<123))||(($ch>64)&&($ch<91))||(($ch>47)&&($ch<58))||($ch==45)||($ch==46))){
          $errOut[]= T_("Domain name allows only alphanumeric characters separated by dot. Please change it");
          $objResponse->addAssign("domainErr","innerHTML",$imgErr);
          $domainErr=true;
          break;
        }
     	}
    }
    if($domainErr===false) $objResponse->addAssign("domainErr","innerHTML","");
    //Check address (must be a valid ip)
    $addressErr=false;
    if(!isValidIP($address)) {
      //address must be a valid ip
      $errOut[]= T_("Address must be a valid ip address");
      $objResponse->addAssign("addressErr","innerHTML",$imgErr);
      $addressErr=true;
    }
    if($addressErr===false) $objResponse->addAssign("addressErr","innerHTML","");
    //Check netmask (must be a valid ip)
    $netmaskErr=false;
    if(!isValidIP($netmask)) {
      //netmask must be a valid ip
      $errOut[]= T_("Netmask must be a valid ip address");
      $objResponse->addAssign("netmaskErr","innerHTML",$imgErr);
      $netmaskErr=true;
    }
    if($netmaskErr===false) $objResponse->addAssign("netmaskErr","innerHTML","");
    //Check network (must be a valid ip)
    $networkErr=false;
    if(!isValidIP($network)) {
      //network must be a valid ip
      $errOut[]= T_("Network must be a valid ip address");
      $objResponse->addAssign("networkErr","innerHTML",$imgErr);
      $networkErr=true;
    }
    if($networkErr===false) $objResponse->addAssign("networkErr","innerHTML","");
    //Check broadcast (must be a valid ip)
    $broadcastErr=false;
    if(!isValidIP($broadcast)) {
      //broadcast must be a valid ip
      $errOut[]= T_("Broadcast must be a valid ip address");
      $objResponse->addAssign("broadcastErr","innerHTML",$imgErr);
      $broadcastErr=true;
    }
    if($broadcastErr===false) $objResponse->addAssign("broadcastErr","innerHTML","");
    //Check gateway (must be a valid ip)
    $gatewayErr=false;
    if(!isValidIP($gateway)) {
      //gateway must be a valid ip
      $errOut[]= T_("Gateway must be a valid ip address");
      $objResponse->addAssign("gatewayErr","innerHTML",$imgErr);
      $gatewayErr=true;
    }
    if($gatewayErr===false) $objResponse->addAssign("gatewayErr","innerHTML","");
    //Check dns1 (must be a valid ip)
    $dns1Err=false;
    if(!isValidIP($dns1)) {
      //dns1 must be a valid ip
      $errOut[]= T_("Dns 1 must be a valid ip address");
      $objResponse->addAssign("dns1Err","innerHTML",$imgErr);
      $dns1Err=true;
    }
    if($dns1Err===false) $objResponse->addAssign("dns1Err","innerHTML","");
    //Check dns2 (must be null or a valid ip)
    $dns2Err=false;
    if((trim($dns2)!="")&&(!isValidIP($dns2))) {
      //dns2 must be a valid ip
      $errOut[]= T_("DNS 2 must be a valid ip address");
      $objResponse->addAssign("dns2Err","innerHTML",$imgErr);
      $dns2Err=true;
    }
    if($dns2Err===false) $objResponse->addAssign("dns2Err","innerHTML","");
    //Check dhcp_range_from (must be a valid ip)
    $dhcp_range_fromErr=false;
    if(!isValidIP($dhcp_range_from)) {
      //dhcp_range_from must be a valid ip
      $errOut[]= T_("DHCP range start must be a valid ip address");
      $objResponse->addAssign("dhcp_range_fromErr","innerHTML",$imgErr);
      $dhcp_range_fromErr=true;
    }
    if($dhcp_range_fromErr===false) $objResponse->addAssign("dhcp_range_fromErr","innerHTML","");
    //Check dhcp_range_to (must be a valid ip)
    $dhcp_range_toErr=false;
    if(!isValidIP($dhcp_range_to)) {
      //dhcp_range_to must be a valid ip
      $errOut[]= T_("DHCP range end must be a valid ip address");
      $objResponse->addAssign("dhcp_range_toErr","innerHTML",$imgErr);
      $dhcp_range_toErr=true;
    }
    if($dhcp_range_toErr===false) $objResponse->addAssign("dhcp_range_toErr","innerHTML","");
    //Check vpn_range_from (must be unset or a valid ip)
    $vpn_range_fromErr=false;
    if((isset($vpn_range_from))&&(!isValidIP($vpn_range_from))) {
      //vpn_range_from must be unset or a valid ip
      $errOut[]= T_("VPN range start must be a valid ip address");
      $objResponse->addAssign("vpn_range_fromErr","innerHTML",$imgErr);
      $vpn_range_fromErr=true;
    }
    if($vpn_range_fromErr===false) $objResponse->addAssign("vpn_range_fromErr","innerHTML","");
    //Check vpn_range_to (must be unset or a valid ip)
    $vpn_range_toErr=false;
    if((isset($vpn_range_to))&&(!isValidIP($vpn_range_to))) {
      //vpn_range_to must be unset or a valid ip
      $errOut[]= T_("VPN range end must be a valid ip address");
      $objResponse->addAssign("vpn_range_toErr","innerHTML",$imgErr);
      $vpn_range_toErr=true;
    }
    if($vpn_range_toErr===false) $objResponse->addAssign("vpn_range_toErr","innerHTML","");
    // Process Form 
    if(isset($errOut)){
      $error="<div class=\"AlertBad\"><ul>";
      foreach($errOut as $err) $error.="<li>".$err."</li>";
      $error.="</ul></div>";
      $objResponse->addAssign("alert","innerHTML",$error);
      $objResponse->addAssign("loading","innerHTML","");
    }else{
      $objResponse->addAssign("loading","innerHTML","");
      $script=" if(confirm('".addslashes(T_("Saving configuration network interface will be reloaded.\\nAre you sure you want to proceed?"))."')) document.getElementById('mainform').submit(); "; 
      $objResponse->addScript($script);
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();
  }
  $xajax = new xajax();
  $xajax->registerFunction("processFormData");
  $xajax->processRequests();
  //================== POST ====================
  if(count($_POST)>0){
  	//prepare structure
    $networkArr=$_POST["network"];
    if(trim($networkArr["dhcp_status"])==1){
    	$networkArr["vpn_range_from"]=$networkArr["dhcp_range_from"];
      $networkArr["vpn_range_to"]=$networkArr["dhcp_range_to"];
    }
    $entry=array(
          "host" => trim($networkArr["host"]),
          "domain" => trim($networkArr["domain"]),
      		"address" => trim($networkArr["address"]),
      		"netmask" => trim($networkArr["netmask"]),
          "network" => trim($networkArr["network"]),
          "broadcast" => trim($networkArr["broadcast"]),
          "gateway" => trim($networkArr["gateway"]),
          "dns1" => trim($networkArr["dns1"]),
          "dns2" => trim($networkArr["dns2"]),
          "dhcp_status" => trim($networkArr["dhcp_status"]),
          "dhcp_range_from" => trim($networkArr["dhcp_range_from"]),
          "dhcp_range_to" => trim($networkArr["dhcp_range_to"]),
          "vpn_range_from" => trim($networkArr["vpn_range_from"]),
          "vpn_range_to" => trim($networkArr["vpn_range_to"]),
          "ntp_host" => trim($networkArr["ntp_host"]),
          "ntp_zone" => trim($networkArr["ntp_zone"])
      	);
  	//save configuration
   	$ret=$asterisk->putNetworkConf($entry); 
    if($ret>0) $alert="<div class=\"AlertGood\">".T_('Network Configuration has been successfully saved')."</div>";
		else $alert="<div class=\"AlertBad\">".T_('Edit failed')."</div>";
	  //go to main page
    goToMainPage($alert,"./?rnd=".rand(0,99999));
  }
  //================= PAGE LOGIC ==================
  //extract network configuration
  $ret=$asterisk->getNetworkConf();
  if(is_array($ret)){
    $host_name=$ret["host"];
    $domain_name=$ret["domain"];
  	$address=$ret["address"];
		$netmask=$ret["netmask"];
    $network=$ret["network"];
    $broadcast=$ret["broadcast"];
    $gateway=$ret["gateway"];
    $dns1=$ret["dns1"];
    $dns2=$ret["dns2"];
    $dhcp_status=$ret["dhcp_status"];
    $dhcp_range_from=$ret["dhcp_range_from"];
    $dhcp_range_to=$ret["dhcp_range_to"];
    $vpn_range_from=$ret["vpn_range_from"];
    $vpn_range_to=$ret["vpn_range_to"];
    $ntp_host=$ret["ntp_host"];
    $ntp_time=$ret["ntp_time"];
    $ntp_zone=$ret["ntp_zone"];
  }
  //timezone
  $tz_html="";
  $timezoneArray=getTimeZones();
  if(is_array($timezoneArray)){
    foreach($timezoneArray as $zone=>$zoneArr){
      $tz_html.="<optgroup label=\"".$zone."\">\n";
      if(is_array($zoneArr)){
        foreach($zoneArr as $z){
          if($ntp_zone==$zone."/".$z) $s="selected=\"selected\""; else $s="";
          $tz_html.="<option value=\"".$zone."/".$z."\" $s>".str_replace("_"," ",$z)."</option>\n";
        }
      }
      $tz_html.="</optgroup>\n"; 
    }
  }
	//================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../admin/lib/xajax/");
  ?>
    <?$sel="network";include("../navigation.php");?>
    <div class="SectionHeader">
      <?=$alert?>
      <h3 style="float:right;margin: 7px 7px 0 0;"><img style="cursor:pointer;" src="<?=$relBasePath?>/public/img/reboot.png" alt="Refresh" onclick="location.href='';"/></h3>
      <h1><?=T_("Network")?></h1>
      
    </div>
    <div id="alert"></div>
    <div id="basic_form">
      <form id="mainform" action="<?=$PHP_SELF?>" method="post">
        <!-- Host -->
        <h2><?=T_('Host Settings')?></h2>
        <p class="blockintro"><?=T_('Insert here the host settings')?></p>
        <div class="block">
          <dl>     
            <dt class="required"><label for="network[host]"><?=T_("Host name")?>:</label></dt>
            <dd><input type="text" size="25" id="network[host]" name="network[host]" value="<?=$host_name?>" /> <span id="hostErr"></span></dd>
            <dt class="required"><label for="network[domain]"><?=T_("Domain name")?>:</label></dt>
            <dd><input type="text" size="25" id="network[domain]" name="network[domain]" value="<?=$domain_name?>" /> <span id="domainErr"></span></dd>
          </dl>
        </div>
  			<!-- Network -->
        <h2><?=T_('Network Settings')?></h2>
        <p class="blockintro"><?=T_('Insert here the network settings')?></p>
        <div class="block">
          <dl>     
            <dt class="required"><label for="network[address]"><?=T_("Address")?>:</label></dt>
            <dd><input type="text" size="25" id="network[address]" name="network[address]" value="<?=$address?>" /> <span id="addressErr"></span></dd>
            <dt class="required"><label for="network[netmask]"><?=T_("Netmask")?>:</label></dt>
            <dd><input type="text" size="25" id="network[netmask]" name="network[netmask]" value="<?=$netmask?>" /> <span id="netmaskErr"></span></dd>
            <dt class="required"><label for="network[network]"><?=T_("Network")?>:</label></dt>
            <dd><input type="text" size="25" id="network[network]" name="network[network]" value="<?=$network?>" /> <span id="networkErr"></span></dd>
            <dt class="required"><label for="network[broadcast]"><?=T_("Broadcast")?>:</label></dt>
            <dd><input type="text" size="25" id="network[broadcast]" name="network[broadcast]" value="<?=$broadcast?>" /> <span id="broadcastErr"></span></dd>
            <dt class="required"><label for="network[gateway]"><?=T_("Gateway")?>:</label></dt>
            <dd><input type="text" size="25" id="network[gateway]" name="network[gateway]" value="<?=$gateway?>" /> <span id="gatewayErr"></span></dd>
            <dt class="required"><label for="network[dns1]"><?=T_("DNS 1")?>:</label></dt>
            <dd><input type="text" size="25" id="network[dns1]" name="network[dns1]" value="<?=$dns1?>" /> <span id="dns1Err"></span></dd>
            <dt class="required"><label for="network[dns2]"><?=T_("DNS 2")?>:</label></dt>
            <dd><input type="text" size="25" id="network[dns2]" name="network[dns2]" value="<?=$dns2?>" /> <span id="dns2Err"></span></dd>
          </dl>
        </div>
				<!-- DHCP -->
        <h2><?=T_('DHCP Server')?></h2>
        <p class="blockintro"><?=T_('Insert here the DHCP settings')?></p>
        <div class="block">
          <dl>     
						<dt class="required"><label for="network[dhcp_status]"><?=T_("DHCP")?>:</label></dt>
            <dd>
              <input type="radio" id="network[dhcp_status]" name="network[dhcp_status]" value="1" onclick="disableVPNRange();" <?if ($dhcp_status==1) echo "checked=\"checked\""; ?> /> <?=T_("ON")?>
              <input type="radio" id="network[dhcp_status]" name="network[dhcp_status]" value="0" onclick="enableVPNRange();" <?if ($dhcp_status!=1) echo "checked=\"checked\""; ?> /> <?=T_("OFF")?>
            </dd>
            <dt class="required"><label for="network[dhcp_range_from]"><?=T_("Range Start")?>:</label></dt>
            <dd><input type="text" size="25" id="network[dhcp_range_from]" name="network[dhcp_range_from]" value="<?=$dhcp_range_from?>"/> <span id="dhcp_range_fromErr"></span></dd> 
            <dt class="required"><label for="network[dhcp_range_to]"><?=T_("Range End")?>:</label></dt>
            <dd><input type="text" size="25" id="network[dhcp_range_to]" name="network[dhcp_range_to]" value="<?=$dhcp_range_to?>"/> <span id="dhcp_range_toErr"></span></dd>
          </dl>
        </div>
        <!-- VPN -->
        <h2><?=T_('VPN Server')?></h2>
        <p class="blockintro"><?=T_('Insert here the VPN settings')?></p>
        <div class="block">
          <dl>     
            <dt class="required"><label for="network[vpn_range_from]"><?=T_("Range Start")?>:</label></dt>
            <dd><input type="text" size="25" id="network[vpn_range_from]" name="network[vpn_range_from]" value="<?if ($dhcp_status==1) echo T_(' ---  DHCP Range Start --- '); else echo $vpn_range_from;?>" <?if ($dhcp_status==1) echo "disabled=\"disabled\""?> /> <span id="vpn_range_fromErr"></span></dd> 
            <dt class="required"><label for="network[vpn_range_to]"><?=T_("Range End")?>:</label></dt>
            <dd><input type="text" size="25" id="network[vpn_range_to]" name="network[vpn_range_to]" value="<?if ($dhcp_status==1) echo T_(' ---  DHCP Range End  --- '); else echo $vpn_range_to;?>" <?if ($dhcp_status==1) echo "disabled=\"disabled\""?> /> <span id="vpn_range_toErr"></span></dd>
          </dl>
        </div>
        <!-- Host -->
        <h2><?=T_('NTP Settings')?></h2>
        <p class="blockintro"><?=T_('Insert here the NTP settings')?></p>
        <div class="block">
          <dl>
            <dt class="required"><label for="network[ntp_host]"><?=T_("Host")?>:</label></dt>
            <dd><input type="text" size="25" id="network[ntp_host]" name="network[ntp_host]" value="<?=$ntp_host?>" /> <span id="ntp_hostErr"></span></dd>
            <dt class="required"><label for="network[ntp_zone]"><?=T_("Timezone")?>:</label></dt>
            <dd><select id="network[ntp_zone]" name="network[ntp_zone]"><?=$tz_html?></select> <span id="ntp_zoneErr"></span></dd>
            <dt class="required"><label for="network[time]"><?=T_("Time")?>:</label></dt>
            <dd><input type="text" size="25" disabled="disabled" id="network[time]" name="network[time]" value="<?=$ntp_time?>" /> <span id="ntp_timeErr"></span></dd>
          </dl>
        </div>
  			<!-- Buttons -->
        <div class="action">
          <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick=" document.getElementById('alert').innerHTML=''; xajax_processFormData(xajax.getFormValues('mainform')); "/></a>
      		<!--
            <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick="return checkParam(document.getElementById('client[extension]').value, document.getElementById('client[alias]').value, document.getElementById('client[password]').value, document.getElementById('client[confirm]').value);"/>
          -->
        </div>
			</form>
    </div>
    <script>
    	function disableVPNRange(){
      	document.getElementById("network[vpn_range_from]").value="<?=T_(' ---  DHCP Range Start  --- ')?>";
        document.getElementById("network[vpn_range_to]").value="<?=T_(' ---  DHCP Range End --- ')?>";
        document.getElementById("network[vpn_range_from]").disabled="disabled";
        document.getElementById("network[vpn_range_to]").disabled="disabled";
      }
      function enableVPNRange(){
      	document.getElementById("network[vpn_range_from]").value="<?=$vpn_range_from?>";
        document.getElementById("network[vpn_range_to]").value="<?=$vpn_range_to?>";
        document.getElementById("network[vpn_range_from]").disabled="";
        document.getElementById("network[vpn_range_to]").disabled="";
      }
    </script>
  <?
  $contents=ob_get_contents();
  ob_end_clean();
  //================ SIDEBAR ================
  ob_start(); 
  ?>
    <div class="Sidebar">
      <h1><?=T_("Informations")?></h1>
      <p><?=T_("This page shows the configuration of network, DHCP, VPN and NTP services. To modify this configuration edit parameters and press save button on the end of the page.")?></p>
    </div>         
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();
  //================ SETTINGS ================
  $smarty->assign("section", "system");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->display('settings.tpl');
?>

