<?
/**
 * VoiceOne Settings/Provider/edit
 *
 * Frontend to provide access to the provider system in voiceone.
 * @package voiceone
 * @subpackage  settings_provider
 */
  include ("../../../../admin/config/cfg.php");
  global $cwlang, $cwLanguage;
 	require_once("$absBasePath/lib/xajax/xajax.inc.php");
  sajax_init();

  //================ XAJAX ================
	function roll(){
    global $relBasePath,$cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Build response
    $html=" <img src=\"".$relBasePath."public/img/ico-progress.gif"."\" alt=\"loading\" /><span>".T_("loading")."</span>";
    $objResponse->addAssign("loading","innerHTML",$html);
    // Return the xajaxResponse object
    return $objResponse->getXML();
  }
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Extract form's params
    $provider=$formData["res"];
    $id=$provider["id"];
    if(!(isset($provider["type"]))) $provider["type"]=$provider["hiddentype"];
    if(!(isset($provider["host"]))) $provider["host"]=$provider["hiddenhost"];
    if(!(isset($provider["port"]))) $provider["port"]=$provider["hiddenport"];
    if(!(isset($provider["tech"]))) $provider["tech"]=$provider["hiddentech"];
    $name=$provider["name"];
    $type=$provider["type"];
    $host=$provider["host"];
    $port=$provider["port"];
    $tech=$provider["tech"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">&nbsp;&nbsp;";
    // Retrieve all providers
    $providerArr=$asterisk->getProvider(0);
    if(is_array($providerArr)){
      foreach($providerArr as $p) {
        if($id==$p["id"]) continue;
        $pNameArr[]=$p["name"];
        if(($p["type"]!=1)&&($p["technology"]==$tech)) $pHostArr[]=$p["host"];
      }
    }
    // Check Name ((not null)&&(unique))
    $nameErr=false;
    if($name=="") {
      //name cannot be null
      $errOut[]= T_("Name cannot be null");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $nameErr=true;
    }else if((is_array($pNameArr))&&(in_array($name,$pNameArr))){
      //name must be unique
      $errOut[]= T_("Name already exists. Please change it");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $nameErr=true;
    }
    if($nameErr===false) $objResponse->addAssign("nameErr","innerHTML","");
    // Check Host ((not null)&&(unique))
    $hostErr=false;
    if($type!=1){
      if($host==""){
        //host cannot be null
        $errOut[]= T_("Host cannot be null");
        $objResponse->addAssign("hostErr","innerHTML",$imgErr);
        $hostErr=true;
      }else if((is_array($pHostArr))&&(in_array($host,$pHostArr))){
        //host must be unique
        $errOut[]= T_("Host already exists. Please change it");
        $objResponse->addAssign("hostErr","innerHTML",$imgErr);
        $hostErr=true;
      }
    }
    if($hostErr===false) $objResponse->addAssign("hostErr","innerHTML","");
    // Check Port ((null)or(numeric)or(port range))
    $portErr=false;
    if($port!=""){
      if(strpos($port,"-")){
        // port must be a valid range
        $portArr=explode("-",$port);
        if(count($portArr)!=2){
          $errOut[]=T_("Port is not a valid range");
          $objResponse->addAssign("portErr","innerHTML",$imgErr);
          $portErr=true;
        }else{
          // start port must be numeric and <= 65536
          for($i=0; $i<strlen($portArr[0]); $i++){
            $ch=ord($portArr[0][$i]);
            if(!((($ch>47)&&($ch<58)))){
              $errOut[]=T_("Port is not a valid range");
              $objResponse->addAssign("portErr","innerHTML",$imgErr);
              $portErr=true;
              break;
            }
          }
          if(($portErr===false)&&(($portArr[0]<1)||($portArr[0]>65536))){
            $errOut[]=T_("Port is not a valid range");
            $objResponse->addAssign("portErr","innerHTML",$imgErr);
            $portErr=true;
          }
          // end port must be numeric and <= 65536
          if($portErr===false){
            for($i=0; $i<strlen($portArr[1]); $i++){
              $ch=ord($portArr[1][$i]);
              if(!((($ch>47)&&($ch<58)))){
                $errOut[]=T_("Port is not a valid range");
                $objResponse->addAssign("portErr","innerHTML",$imgErr);
                $portErr=true;
                break;
              }
            }
            if(($portErr===false)&&(($portArr[1]<1)||($portArr[1]>65536))){
              $errOut[]=T_("Port is not a valid range");
              $objResponse->addAssign("portErr","innerHTML",$imgErr);
              $portErr=true;
            }
          }
          //star port must be < than end port
          if(($portErr===false)&&(($portArr[0]==$portArr[1])||($portArr[0]>$portArr[1]))){
            $errOut[]=T_("Port is not a valid range");
            $objResponse->addAssign("portErr","innerHTML",$imgErr);
            $portErr=true;
          }
        }
      }else{
        // port must be numeric
        for($i=0; $i<strlen($port); $i++){
          $ch=ord($port[$i]);
          if(!((($ch>47)&&($ch<58)))){
            $errOut[]=T_("Port allows only numeric characters. Please change it");
            $objResponse->addAssign("portErr","innerHTML",$imgErr);
            $portErr=true;
            break;
          }
        }
      }
    }
    if($portErr===false) $objResponse->addAssign("portErr","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","");
      $objResponse->addScript(" document.getElementById('mainform').submit(); ");
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();
  }
  $xajax = new xajax();
  $xajax->registerFunction("roll");
  $xajax->registerFunction("processFormData");
  $xajax->processRequests();

  //=================== POST ====================
  if (count($_POST)>0) {
    $data=$_POST["res"];
    if(!(isset($data["type"]))) $data["type"]=$data["hiddentype"];
    if(!(isset($data["host"]))) $data["host"]=$data["hiddenhost"];
    if(!(isset($data["port"]))) $data["port"]=$data["hiddenport"];
    if(!(isset($data["tech"]))) $data["tech"]=$data["hiddentech"];
    $entry=Array(
            "id"        => $data["id"],
            "name"      => $data["name"],
            "type"      => $data["type"],
            "host"      => $data["host"],
            "port"      => $data["port"],
            "technology"=> $data["tech"]
    );
    $ret=$asterisk->putProvider($entry);
    if ($err=$asterisk->getError()) $alert="<div class=\"AlertBad\">ERROR: $err</div>";
    if ($ret>0) {
      $alert.="<div class=\"AlertGood\">".T_("Provider has been successfully edited")."</div>";
      if((isset($_POST["next"]))&&($_POST["next"]=="next")) goToMainPage("","../account/?prov=$ret");
      else goToMainPage($alert);
    }
    else {
      $alert.="<div class=\"AlertBad\">".T_("Provider has NOT been edited")."</div>";
      goToMainPage($alert);
    }
  }
  //================ PAGE LOGIC ================
  // Get the provider informations
  if (isset($_GET["id"]) and $_GET["id"]!="") {
    $id=$_GET["id"];
    $ret=$asterisk->getProvider($id);
    if ($err=$asterisk->getError()) die("Error: $err");
    $v=$ret[0];
    $id=$v["id"];
    $name=$v["name"];
    $type=$v["type"];
    $host=$v["host"];
    $port=$v["port"];
    $technology=$v["technology"];
    $accounts=$v["accounts"];
 		// Define type of technology
		if ($technology==0) $_GET["type"]="telco";
		else {
			$_GET["type"]="voip";
  		$techs=$asterisk->getTechnology(0);
      foreach($techs as $t){
        $vid=$t["id"];
        $vname=$t["name"];
        if ($t["voip"]==1){
  				 if ($vid==$technology) $optVOIP.="<option value=\"$vid\" selected=\"selected\">$vname</option>\n";
					 else $optVOIP.="<option value=\"$vid\">$vname</option>\n";
  			}
      }
		}
    // If provider has accounts, disable all field except name
    if(is_array($accounts)) $disableModify=1; else $disableModify=0;
    // Set title
    $title=sprintf(T_("Edit provider: %s "),$name );
  }
  //New provider
  else{
		if ($_GET["type"]=="voip"){
  		$ret=$asterisk->getTechnology(0);
      foreach($ret as $t){
        $vid=$t["id"];
        $vname=$t["name"];
        if ($t["voip"]==1){
  				 if ($vid==$technology) $optVOIP.="<option value=\"$vid\" selected=\"selected\">$vname</option>\n";
					 else $optVOIP.="<option value=\"$vid\">$vname</option>\n";
  			}
      }
		}
    $type=0;
    $title=sprintf(T_("New Voip provider %s"),$_GET["type"] );
  }

  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../../admin/lib/xajax/");
  ?>
  <div class="SectionHeader">
    <div id="loading" style="float: right;"></div>
    <h1><?=$title?></h1>
    <h3>
      <a href="../" class="admin" ><?=T_("Back without saving")?></a>
    </h3>
  </div>
  <div id="alert"></div>
  <div id="basic_form">
    <form id="mainform" action="<?=$PHP_SELF?>?id=<?=$_GET['id']?>" method="post" >
      <input type="hidden" id="disableModify" name="disableModify" value="<?=$disableModify?>"/>
      
<? if ($_GET["type"]=="voip") { ?>
      
      <h2><?=T_("Provider Info")?></h2>
      <p class="blockintro"><?=T_("Provider general information")?></p>
      <div class="block">
        <dl>
          <dt class="required"><label for="res[name]"><?=T_("Name")?>:</label></dt>
          <dd>
					  <input type="text" size="25" id="res[name]" name="res[name]" value="<?=$name?>" />
					  <span id="nameErr"></span><span class="help"><?=T_("Enter a name for this provider, p.e. FreeWorldDialup.")?></span>
					</dd>
          <dt class="required"><label for="res[type]"><?=T_("Host Type")?>:</label></dt>
          <dd style="height:20px;color:#333;">
            <input type="radio" style="vertical-align:center;" id="res[type]" name="res[type]" value="0" onclick="disableEnableHost(this.value);" <?if($disableModify==1) echo "disabled=\"disabled\"";?><?if($type!=1) echo "checked=\"checked\"";?>/><?=T_("Static")?>
            <input type="radio" style="vertical-align:center;margin-left:25px;" id="res[type]" name="res[type]" value="1" onclick="disableEnableHost(this.value);" <?if($disableModify==1) echo "disabled=\"disabled\"";?><?if($type==1) echo "checked=\"checked\"";?>/><?=T_("Dynamic")?>
            <input type="hidden" size="25" id="res[hiddentype]" name="res[hiddentype]" value="<?=$type?>" />
					</dd>
					<dt class="required"><label for="res[host]"><?=T_("Host address")?>:</label></dt>
          <dd>
            <input type="text" size="25" id="res[host]" name="res[host]" value="<?=$host?>" <?if(($disableModify==1)||($type==1)) echo "disabled=\"disabled\"";?>/>
            <input type="hidden" size="25" id="res[hiddenhost]" name="res[hiddenhost]" value="<?=$host?>" />
            <span id="hostErr"></span><span class="help"><?=T_("Insert the IP address or the hostname")?></span>
          </dd>
          <dt class="required"><label for="res[port]"><?=T_("Port")?>:</label></dt>
          <dd>
					  <input type="text" size="25" id="res[port]" name="res[port]" value="<?=$port?>" <?if($disableModify==1) echo "disabled=\"disabled\"";?>/>
            <input type="hidden" size="25" id="res[hiddenport]" name="res[hiddenport]" value="<?=$port?>" />
						<span id="portErr"></span><span class="help"><?=T_("Server port, leave empty for default")?></span>
					</dd>
					<dt class="required"><label for="res[tech]"><?=T_("Technology")?>:</label></dt>
					<dd>
					  <select size="1" style="width: 153px;" id="res[tech]" name="res[tech]" <?if($disableModify==1) echo "disabled=\"disabled\"";?> > <?=$optVOIP?> </select>
            <input type="hidden" size="25" id="res[hiddentech]" name="res[hiddentech]" value="<?=$technology?>" />
						<span class="help"><?=T_("Choose Voip Technology")?></span>
					</dd>
        </dl>
      </div>
      <script>
        function disableEnableHost(val){
          if(document.getElementById('disableModify').value!=1){
            hostObj=document.getElementById('res[host]');
            if(val==1){
              hostObj.disabled=true;
              hostObj.value='';
            }else{
              hostObj.disabled=false;
              hostObj.value='<?=$host?>';
            }
          }
        }
      </script>
<?  } else { ?>

      <h2><?=T_("Provider Info")?></h2>
      <p class="blockintro"><?=T_("Provider general information")?></p>
      <div class="block">
        <dl>
          <dt class="required"><label for="res[name]"><?=T_("Name")?>:</label></dt>
          <dd><input type="text" size="25" id="res[name]" name="res[name]" value="<?=$name?>" /></dd>
          <?=T_("Enter a name for this provider, p.e. FreeWorldDialup.")?>
          <dt class="required"><label for="res[speeddial]"><?=T_("Prefix")?>:</label></dt>
          <dd><input type="text" size="25" maxlength="50" id="res[speeddial]" name="res[speeddial]" value="<?=$speeddial?>" /><big>*</big></dd>
          <?=T_("Insert the carrier prefix, e.g. 1033 or 1099")?>
        </dl>
      </div>

<?  } ?>

      <div class="action">
        <input type="hidden" name="res[id]" value="<?=$id?>" />
        <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/></a>
        <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="hidden" id="next" name="next" value="" />
        <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-next.gif" alt="Add an account" onclick=" document.getElementById('next').value='next'; document.getElementById('alert').innerHTML=''; xajax_processFormData(xajax.getFormValues('mainform')); "/></a>
    <!--
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/>
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick=" document.getElementById('alert').innerHTML=''; xajax_roll(); xajax_processProviderData(xajax.getFormValues('mainform')); " />
    -->
      </div>
    </form>
  </div>

  <?
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start();
  ?>
    <div class="Sidebar">
      <?$sel="providers";include("../../sidebar.php");?>
      <h1><?=T_("Informations")?></h1>
      <p><?=T_("This page allows you to create a new voip provider or to modify an existing one. To create a new provider you have to define the name, the type, the address, the technology and to press save button on the end of the page or next button to create now a new account for this new provider. Select static provider if you want that system sends registration request to the provider or if you want no registration, otherwise select dynamic if the provider send registration to system.")?></p>
    </div>
  <?
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================
 	sajax_handle_client_request();
  $smarty->assign("section", "providers");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->assign("ajax", $js);
  $smarty->display('settings.tpl');
?>

