<?
/**
 * VoiceOne Settings/Rules/outgoing/edit
 *
 * Frontend to provide access to the rules system in voiceone.
 * @package voiceone
 * @subpackage  settings_rules
 */
  include ("../../../../admin/config/cfg.php");
  global $cwlang, $cwLanguage;
  require_once("$absBasePath/lib/xajax/xajax.inc.php");
 	sajax_init();
  
  //================ XAJAX ================
  function delVariable($index){
    global $relBasePath,$cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Build response
    $objResponse->addAssign("var_".$index, 'innerHTML', "");
    // Return the xajaxResponse object
    return $objResponse->getXML(); 
  }
  function addVariable($index){
    global $relBasePath,$cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Build response
    ob_start(); 
    ?>
      <table cellpadding="0" cellspacing="0" style="width:70%;">
        <tr>
          <td><a href="#" onclick="xajax_delVariable(<?=$index?>); return false;"><img src="<?=$relBasePath?>/public/img/trash.gif" alt=""></a></td>        
          <td class="required"><label for="var_name_<?=$index?>"><?=T_('Name')?>:</label> <input type="text" size="20" id="var_name_<?=$index?>" name="var_name[]" value=""/></td>
          <td class="required"><label for="var_val_<?=$index?>"><?=T_('Value')?>:</label> <input type="text" size="20" id="var_val_<?=$index?>" name="var_val[]" value=""/></td>
        </tr>
      </table>
    <?
    $newvar=ob_get_contents();
    ob_end_clean();
    // Return the xajaxResponse object
    $objResponse->addCreate('variable_div', 'div', "var_".$index);
    $objResponse->addAssign("var_".$index, 'innerHTML', $newvar);
    return $objResponse->getXML(); 
  }
	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
    $group=$formData["group"];
    $groupType=$formData["kind"];
    $trunkList=$formData["listRight"];
    $action=$formData["action"];
    $var_name=$formData["var_name"];
    $var_val=$formData["var_val"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">&nbsp;&nbsp;";
    // Check Group ((not null))
    $groupErr=false;
    if((!isset($formData["group"]))||($group=="")) { 
      //group cannot be null
      $errOut[]= T_("Destination cannot be null");
      $objResponse->addAssign("groupErr","innerHTML",$imgErr);
      $groupErr=true;  
    }
    if($groupErr===false) $objResponse->addAssign("groupErr","innerHTML","");
    // Check Trunk List ((not null))
    $trunkErr=false;
    if(($groupType=GROUP_OF_PHONENUMBER)&&(!is_array($trunkList))) { 
      //trunk list cannot be null
      $errOut[]= T_("Lines list cannot be null");
      $objResponse->addAssign("trunkErr","innerHTML",$imgErr);
      $trunkErr=true;  
    }
    if($trunkErr===false) $objResponse->addAssign("trunkErr","innerHTML","");
    // Check Variables
    $varErr=false;
    if(($action==RULE_ALLOW)&&(is_array($var_name))&&(is_array($var_val))){
      foreach($var_name as $k=>$v){
        if(trim($v)==''){
          //var name cannot be null
          $errOut[]= T_("Parameter name cannot be null");
          $objResponse->addAssign("varErr","innerHTML",$imgErr);
          $varErr=true;
          break;
        }
        else{
          //var name and var val cannot contain character "|"
          for($i=0; $i<strlen($v); $i++){
            if(ord($v[$i])==ord('|')){
              $errOut[]=T_("Parameter name cannot contains char | (pipe)");
              $objResponse->addAssign("varErr","innerHTML",$imgErr);
              $varErr=true;
              break;
            }
          }
          if($varErr===true) break;
          for($i=0; $i<strlen($var_val[$k]); $i++){
            if(ord($var_val[$k][$i])==ord('|')){
              $errOut[]=T_("Parameter value cannot contains char | (pipe)");
              $objResponse->addAssign("varErr","innerHTML",$imgErr);
              $varErr=true;
              break;
            }
          }
          if($varErr===true) break;
        }
      }
    }
    if($varErr===false) $objResponse->addAssign("varErr","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("delVariable");
  $xajax->registerFunction("addVariable");
  $xajax->registerFunction("roll");
  $xajax->registerFunction("processFormData");
  $xajax->processRequests();
    
  //=================== POST ===================
  if (count($_POST)>0) {
    //read variables
    $variables='';
    if(($_POST["action"]==RULE_ALLOW)&&(is_array($_POST['var_name']))&&(is_array($_POST['var_val']))){
      foreach($_POST['var_name'] as $k=>$v){
        $variables.=trim($v)."=".trim($_POST['var_val'][$k])."|";
      }
    }
    if(strlen($variables)!=0) $variables=substr($variables,0,-1);
    //build structure
    if (is_array($_POST["listRight"])) $resource=implode("|",$_POST["listRight"]);
    $entry=Array(
      "id"  => $_POST["id"],
      "rule" => $_POST["rule"],
      "priority" => $_POST["priority"],
      "timesegment" => $_POST["timesegment"], 
      "action" => $_POST["action"], 
      "resource" => $resource,
      "failover" => $_POST["failover"],
      "variables" => $variables
    );
    if (substr($_POST["group"],0,2)=="g_")  $entry["group"]=substr($_POST["group"],2); 
    else $entry["entity"]=$_POST["group"]; 
    if ($_POST["kind"]==GROUP_OF_ALL) $entry["group"]=GROUP_OF_ALL;
    //save the group informations
    $ret=$asterisk->putOutgoingRule($entry);
    if ($ret>0) {
      $alert="<div class=\"AlertGood\">".T_("Rule created")."</div>";
      $_GET["id"]=$ret;
    } else $alert="<div class=\"AlertBad\">".T_("Error: Rule not created")."</div>";
    //return to main page
    goToMainPage($alert);
  }
  
  //================ PAGE LOGIC ================
  //if modify, read the group informations
  if (isset($_GET["id"])) {
    $ret=$asterisk->getOutgoingRule($_GET["id"]);
    if ($err=$asterisk->getError()) die("Error: $err");
    $id=$ret[0]["id"];
    $rule=$ret[0]["rule"];
    $priority=$ret[0]["priority"];
    $timesegment=$ret[0]["timesegment"];  
    $group=$ret[0]["group"]; 
    $entity=$ret[0]["entity"];  
    if($ret[0]["resource"]!="") $resource=explode("|",$ret[0]["resource"]);
    else $resource=array();
    $provider=$ret[0]["provider"];  
    $action=$ret[0]["action"];
    $failover=$ret[0]["failover"];
    if($ret[0]["variables"]!='') $variables=explode("|",$ret[0]["variables"]);
    else $variables=array();
  }
  //Get the time segment available
  $tsHtml.="<option value=\"0\">[any time]</option>\n";
  $ret=$asterisk->getTimeSegment(0);
  if ($err=$asterisk->getError()) die("Error: $err");
  if (is_array($ret)) 
  foreach ($ret as $ts) {
    $id=$ts["id"];
    $name=$ts["name"];
    if ($id==$timesegment) $selected=" selected=\"selected\" ";
    else $selected="";
    $tsHtml.="<option value=\"$id\" $selected>$name</option>\n";
  }
  //Get the trunk available
  $ret=$asterisk->getTrunk(0,0);
  if ($err=$asterisk->getError()) die("Error: $err");
  if (is_array($ret)) 
  foreach ($ret as $tr) {
    $id=$tr["id"];
    $name=$tr["name"];
    if (!@in_array($id,$resource)) $listLeft.="<option value=\"$id\" >$name</option>";    
  }
  //Get the trunk already selected
  if (is_array($resource)) 
  foreach ($resource as $r) {
    $id=$r;
    $tr=$asterisk->getTrunk($id,0);
    $name=$tr[0]["name"];
    if ($id=="0") $name="[any trunk]";
    $listRight.="<option value=\"$id\" >$name</option>";
  }
  //Adjust the trunk list
  if (isset($_GET["id"])) {
    if (!in_array("0",$resource)) $listLeft.="<option value=\"0\">[any trunk]</option>\n";
  } 
  else $listRight.="<option value=\"0\">[any trunk]</option>\n";
  //set GET values
  $id=$_REQUEST["id"];
  $rule=$_REQUEST["rule"];  
  //create variables html
  $html_var='';
  $index=0;
  if((is_array($variables))&&(count($variables)>0)){
    foreach($variables as $var){
      $varArr=explode("=",$var);
      ob_start(); 
      ?>
        <div id="var_<?=$index?>">
          <table cellpadding="0" cellspacing="0" style="width:70%;">
            <tr>
              <td><a href="#" onclick="xajax_delVariable(<?=$index?>); return false;"><img src="<?=$relBasePath?>/public/img/trash.gif" alt=""></a></td>        
              <td class="required"><label for="var_name_<?=$index?>"><?=T_('Name')?>:</label> <input type="text" size="20" id="var_name_<?=$index?>" name="var_name[]" value="<?=$varArr[0]?>"/></td>
              <td class="required"><label for="var_val_<?=$index?>"><?=T_('Value')?>:</label> <input type="text" size="20" id="var_val_<?=$index?>" name="var_val[]" value="<?=$varArr[1]?>"/></td>
            </tr>
          </table>
        </div>
      <?
      $html_var.=ob_get_contents();
      ob_end_clean();
      $index++;
    }
  }
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../../admin/lib/xajax/");?>
  <?$sel="outgoing";include("../../navigation.php");?> 
  
  <div class="SectionHeader">
    <div id="loading" style="float: right;"></div>
    <h1><?=T_("Outgoing rule")?></h1>
    <h3><a href="../" class="admin" ><?=T_("Return without save")?></a></h3>
  </div>
  <div id="alert"></div>
  <div id="basic_form">
    <form id="mainform" action="<?=$PHP_SELF?><?if (isset($_GET["id"])) echo "?id=".$_GET["id"];?>" method="post" onSubmit=" return selectAll(getElementById('listRight'));">
      <!-- TIME SEGMENT -->
    	<h2><?=T_("Time segment")?></h2>
      <p class="blockintro"><?=T_("set the time segment")?></p>
      <div class="block">
        <table>
          <tr>
            <td class="required" width="160"><label for="timesegment"><?=T_("Time segment")?>:</label></td>
            <td colspan="2"><select id="timesegment" name="timesegment" ><?=$tsHtml?></select></td>
          </tr>
        </table>
      </div>
      <!-- DESTINATION -->
      <? echo listGroupEntity($js, $group, $entity);?>      
      <!-- ACTION -->
    	<h2><?=T_("Action")?></h2>
      <p class="blockintro"><?=T_("What do you want to do?")?></p>
      <div class="block">
        <table>
          <tr>
            <td class="required" width="160"><label for="action"><?=T_("Action")?>:</label></td>
            <td >
              <select id="action" name="action" onchange="switchAllowDeny(this.options[this.selectedIndex].value)">
                <option value="<?=RULE_ALLOW?>" <?if ($action==RULE_ALLOW) echo "selected='selected'";?>><?=T_("ALLOW")?></option>
                <option value="<?=RULE_DENY?>" <?if ($action==RULE_DENY) echo "selected='selected'";?>><?=T_("DENY")?></option>
              </select>
            </td>
          </tr>
        </table>
      </div>
      <script>
        function switchAllowDeny(value){
          if(value==<?=RULE_DENY?>){
            document.getElementById('div_failover').style.display='none';
            document.getElementById('chan_var').style.display='none'; 
          }else{
            document.getElementById('div_failover').style.display='block';
            document.getElementById('chan_var').style.display='block';
          }
        }
      </script>
      <!-- TRUNKS -->
      <div id="trunkDiv">
      	<h2><?=T_("Line")?></h2>
        <p class="blockintro"><?=T_("Choose which of the available lines to be used in this rule")?></p>
        <div class="block">
          <table>
            <tr>
              <td class="required"  style="vertical-align:top;">
                <div ><?=T_("Available Resources")?>:</div>
                <select multiple size="5"  name="listLeft[]" id="listLeft"><?=$listLeft?></select>
                <div style="line-height:16px;">&nbsp;</div>
              </td>
              <td>   
                <div><input type="button" onclick="moveTrunkList( document.getElementById('listLeft'),  document.getElementById('listRight'), false , true)" name="Add     >>"  value="<?=T_("  Add          >")?>" style="width:100px"></div>
                <div><input type="button" onclick="moveTrunkList( document.getElementById('listRight'), document.getElementById('listLeft'),  false )" name="Add     <<"  value="<?=T_("<       Remove  ")?>" style="width:100px"></div>
                <div><input type="button" onclick="moveTrunkList( document.getElementById('listLeft'),  document.getElementById('listRight'), true  , true)" name="Add All >>"  value="<?=T_("  Add All     >>")?>" style="width:100px"></div>
                <div><input type="button" onclick="moveTrunkList( document.getElementById('listRight'), document.getElementById('listLeft'),  true  )" name="Add All <<"  value="<?=T_("<<   Remove All ")?>" style="width:100px"></div>
              </td>
              <td class="required" style="vertical-align:top;"><div ><?=T_("Ports added")?>:&nbsp;&nbsp;<span id="trunkErr"></span></div>
                <div style="float: left">
                  <input type="image"  src="<?=$relBasePath?>public/img/icon_up.gif"  onclick="moveOptions ( document.getElementById('listRight'), -1); return false" name="Up"  value="Down" style="display: block">
                  <input type="image"  src="<?=$relBasePath?>public/img/icon_down.gif"  onclick="moveOptions ( document.getElementById('listRight'), 1); return false;" name="Down"  value="Down" style="display: block">
                </div>
                <select multiple size="5" name="listRight[]" id="listRight"><?=$listRight?></select>
                <div id="div_failover" style="padding-left:20px;line-height:18px;<?if ($action==RULE_DENY) echo 'display:none;'?>">
                  <input style="vertical-align:top;" type="checkbox" name="failover" value="1" <? if(intval($failover)==1) echo "checked=\"checked\"" ?>/>
                  <span><?=T_("Fail Over")?></span>
                </div>
              </td>
            </tr>
          </table>
        </div>
      </div>
      <!-- CHANNEL VARIABLES -->
      <div id="chan_var" style="<?if ($action==RULE_DENY) echo 'display:none;'?>">
      	<h2><?=T_("Channel parameters")?></h2>
        <p class="blockintro"><?=T_("Set channel variables to use in macro executed on this rule.")?> <strong><?=T_("(only for expert users)")?></strong></p>
        <div class="block" >
          <span style="float: right; margin: 0 20px 1em 0;" id="varErr"></span>
          <div id="variable_div">
            <?=$html_var?>
          </div>
          <div style="float: right; margin: 0 20px 1em 0;">
            <a class="admin" href="#" onclick="xajax_addVariable(nVar); nVar++; return false;">(<?=T_("add Variable")?>)</a>
          </div>
          <br/>
          <script>
            var nVar=<?=$index?>
          </script>
        </div>
      </div>
      <!-- INPUT BUTTONS -->
      <?=$numHidden?>      
      <div class="action">
        <input type="hidden" name="id" value="<?=$id?>" />
        <input type="hidden" name="rule" value="<?=$rule?>" />
        <input type="hidden" name="priority" value="<?=$priority?>" />
        <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=" selectAll(getElementById('listRight')); 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="return checkDestination();" />
       -->
      </div>
    </form>
  </div>  
  
  
  <?
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start(); 
  ?>
        <div class="Sidebar">
          <h1><?=T_("Informations")?></h1>
          <p><?=T_("This page allows you to create a new outgoing rule or to modify an existing one. To create a new outgoing rule you have to define the validity time segment, the destination, the action, the list of the allowed lines and to press save button on the end of the page.")?></p>
        </div>
  <?
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================
 	sajax_handle_client_request();
  $smarty->assign("section", "rules");
  $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');
?>

