<?
/**
 * VoiceOne Settings/Extensions/edit
 *
 * Frontend to provide access to the extensions system in voiceone.
 * @package voiceone
 * @subpackage  settings_extensions
 * @todo Remove hardcoded italian message for confirmation box (AlertGood. AlertBad etc)
 */
  include ("../../../../admin/config/cfg.php");
  global $cwlang;
  //============= CHECK MODULE ============
  if(!_isModuleLoaded('fax')) goToMainPage('',"../");
  require_once("$absBasePath/lib/xajax/xajax.inc.php");
  sajax_init();
  //================ XAJAX ================
  function changeLocation($id,$area_code){
    global $asterisk,$cwlang;
		// Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
		// Build response
		$ret=$asterisk->getLocation($id);
  	if((is_array($ret))&&(is_array($ret[0]))){
      $area_codeArr=$ret[0]["area_codes"];
    }
    $area_codelist="";
    if((is_array($area_codeArr))&&(count($area_codeArr)>0)){
      foreach($area_codeArr as $ac){
        if($area_code==$ac) $s="selected=\"selected\""; else $s="";
        $area_codelist.="<option value=\"".$ac."\" $s>".$ac."</option>\n";
      }
    }else $area_codelist="<option value=\"\">[none]</option>\n";
    $html="<select id=\"fax[area_code]\" name=\"fax[area_code]\">".$area_codelist."</select>";
    // Return the xajaxResponse object
		$objResponse->addAssign("area_code_div","innerHTML",$html);
    $objResponse->addAssign("area_code_roll","innerHTML","");
    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();
    $confirmBeforeSubmit="";
    //extract form params
    $fax=$formData["fax"];
    $id=$fax["id_client"];
    $exten=$fax["extension"];
    $alias=$fax["alias"];
    $password=$fax["password"];
    $confirm=$fax["confirm"];
    $phonenumber=$fax["phonenumber"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">";
    //retrieve old exten and alias value
    if($id!=""){
      $ret=$asterisk->getClient($id,0);
      $v=$ret[0];
      $oldExen=$v["extension"];
      $oldAlias=$v["alias"];
    }
    // Check Extension ((no null)&&(numeric)&&(unique)&&( -neq Alias)
    $extensionErr=false;
    if($exten=="") {
      //extension cannot be null
      $errOut[]= T_("Extension cannot be null");
      $objResponse->addAssign("extensionErr","innerHTML",$imgErr);
      $extensionErr=true;
    }else{
      //extension must be numeric
      for($i=0; $i<strlen($exten); $i++){
        $ch=ord($exten[$i]);
        if(!((($ch>47)&&($ch<58)))){
          $errOut[]= T_("Extension allow only numeric characters. Please change it");
          $objResponse->addAssign("extensionErr","innerHTML",$imgErr);
          $extensionErr=true;
          break;
        }
      }
      //extension must be unique
      if(!(($id!="")and($exten==$oldExen))) {
        $ret=$asterisk->getExtension(0);
        if(is_array($ret)){
          foreach($ret as $e) {
            if($exten==$e["extension"]){
              $errOut[]= T_("Extension already exists. Please change it");
              $objResponse->addAssign("extensionErr","innerHTML",$imgErr);
              $extensionErr=true;
            }
          }
        }
      }
    }
    if($extensionErr===false) $objResponse->addAssign("extensionErr","innerHTML","");
    // Check Account Password ((no null)&&(==confirm)&&(alphanumeric))
    $passwordErr=false;
    if($password==""){
      //account password cannot be not null
      $errOut[]=T_("Account password cannot be null");
      $objResponse->addAssign("passwordErr","innerHTML",$imgErr);
      $passwordErr=true;
    }else if($password!=$confirm){
      //account password must be equal to confirm
      $errOut[]=T_("Account password and confirmation password do not match");
      $objResponse->addAssign("passwordErr","innerHTML",$imgErr);
      $objResponse->addAssign("confirmErr","innerHTML",$imgErr);
      $passwordErr=true;
    }else{
      //account password must be alphanumeric
      for($i=0; $i<strlen($password); $i++){
        $ch=ord($password[$i]);
        if(!((($ch>96)&&($ch<123))||(($ch>64)&&($ch<91))||(($ch>47)&&($ch<58)))){
          $errOut[]=T_("Account password allows only alphanumeric characters. Please change it");
          $objResponse->addAssign("passwordErr","innerHTML",$imgErr);
          $passwordErr=true;
          break;
        }
      }
    }
    if($passwordErr===false){
      $objResponse->addAssign("passwordErr","innerHTML","");
      $objResponse->addAssign("confirmErr","innerHTML","");
    }
    // Check Alias ((alphanumeric)&&(unique))
    $aliasErr=false;
    if($alias!=""){
      //alias must be alphanumeric
      for($i=0; $i<strlen($alias); $i++){
        $ch=ord($alias[$i]);
        if(!((($ch>96)&&($ch<123))||(($ch>64)&&($ch<91))||(($ch>47)&&($ch<58)))) {
          $errOut[]=T_("Alias allows only alphanumeric characters. Please change it");
          $objResponse->addAssign("aliasErr","innerHTML",$imgErr);
          $aliasErr=true;
          break;
        }
      }
      //alias must be unique
      if(!(($id!="")and($alias==$oldAlias))) {
        $ret=$asterisk->getExtension(0,0);
        if(is_array($ret)){
          foreach($ret as $e){
            if($alias==$e["extension"]){
              $errOut[]=T_("Alias already exist. Please change it");
              $objResponse->addAssign("aliasErr","innerHTML",$imgErr);
              $aliasErr=true;
              break;
            }
          }
        }
      }
      //extension must be different from Alias
      if($alias==$exten){
        $errOut[]=T_("Alias cannot match Extension. Please change it");
        $objResponse->addAssign("aliasErr","innerHTML",$imgErr);
        $aliasErr=true;
      }
    }
    if($aliasErr===false) $objResponse->addAssign("aliasErr","innerHTML","");
    // Check Phonenumber (not null)
    $phonenumberErr=false;
    if(trim($phonenumber)==""){
      //phonenumber cannot be null
      $errOut[]= T_("Phonenumber cannot be null");
      $objResponse->addAssign("phonenumberErr","innerHTML",$imgErr);
      $phonenumberErr=true;
    }
    if($phonenumberErr===false) $objResponse->addAssign("phonenumberErr","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=" document.getElementById('mainform').submit(); ";
      $objResponse->addScript($script);
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();
  }
  $xajax = new xajax();
  $xajax->registerFunction("changeLocation");
  $xajax->registerFunction("roll");
  $xajax->registerFunction("processFormData");
  $xajax->processRequests();
  //================== POST ====================
  if(count($_POST)>0){
    $group=$_POST["group"];
    $technology=$_POST["techSelect"];
    $allowed=array();
    if((is_array($_POST["listRight"]))&&(count($_POST["listRight"])>0)){
      $allowed=$_POST["listRight"];
    }
    //build client structure
    $client=Array(
        "id" => $fax["id_client"],
        "name" => $fax["name"],
        "surname" => $fax["surname"],
        "extension" => $fax["extension"],
        "alias" => $fax["alias"],
      //"username" => $client["username"],
        "password" => $fax["password"],
        "language" => $fax["language"],
        "groups" => $group,
        "technology" => $technology,
        "location" => $fax["location"],
        "area_code" => $fax["area_code"]
      );
    //add options to the client
    foreach ($_POST as $k=>$v) {
      if (substr($k,0,7)=="status_") {
        $k=substr($k,7);
        if ($v=="1") {
          $o["key"]=$k;
          $o["value"]=$_POST["option_".$k];
          $options[]=$o;
        }
      }
    }
    $client["options"]=$options;
    //create fax entry
    $entry=Array(
        "id" => $fax["id"],
        "client" => $client,
        "label" => $fax["label"],
        "email" => $fax["email"],
        "printer" => $fax["printer"],
        "phonenumber" => $fax["phonenumber"],
        "allow_everyone" => $fax["allow_everyone"],
        "allowed" => $allowed
      );
    //put Fax Client
    $ret=$asterisk->putFaxExtension($entry);
    if($ret>0) $alert="<div class=\"AlertGood\">".T_("Fax extension successfully saved")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("Edit failed")."</div>";
    //go to main page
    goToMainPage($alert,"../");
  }
  //================ PAGE LOGIC ================
  //Get the client informations
  if (isset($_GET["id"]) and $_GET["id"]!=""){
    $id=$_GET["id"];
    $ret=$asterisk->getFaxExtension($id);
    if ($err=$asterisk->getError()) die("Error: $err");
    //fax params
    $id=$ret[0]["id"];
    $phonenumber=$ret[0]["phonenumber"];
    $label=$ret[0]['label'];
    $email=$ret[0]['email'];
    $printer=$ret[0]['printer'];
    $client=$ret[0]["client"];
    $allow_everyone=$ret[0]["allow_everyone"];
    $allowed=$ret[0]["allowed"];
    //client params
    $id_client=$client["id"];
    $name=$client["name"];
    $surname=$client["surname"];
    $extension=$client["extension"];
    $alias=$client["alias"];
    $username=$client["username"];
    $password=$client["password"];
    $language=$client["language"];
    $rule=$client["rule"];
    $technology=$client["technology"];
    $optionsArr=$client["options"];
    $location=$client["location"];
    $area_code=$client["area_code"];
    //title
    $title=sprintf(T_("Account: %1\$s &lt;%2\$s %3\$s&gt;"),$extension ,$surname, $name );
  }
  else{
    //title
    $title=T_("New Fax Extension");
  }
  //create the language list
  $langSelect="";
  $availLang=getAvailLang();
  if(is_array($availLang)){
    foreach($availLang as $l) {
      if($l['key']==$language) $s="selected=\"selected\""; else $s="";
      $langSelect.="<option value=\"".$l['key']."\" $s>".$l['value']."</option>\n";
    }
  }
  //get trunk list
  $numberAlreadyLinked=array();
  $ret=$asterisk->getFaxExtension(0);
  if(is_array($ret)){
    foreach($ret as $f){
      if($f["id"]==$_GET["id"]) continue;
      $numberAlreadyLinked[]=$f["phonenumber"];
    }
  }
  $ret=$asterisk->getTrunk(0,0);
  $trunklist="<option value=\"\">[none]</option>";
	if((is_array($ret))&&(count($ret)>0)){
    $trunklist="";
    foreach($ret as $t){
      $trunklist.="<optgroup label=\"".$t["name"]."\">";
  		if(is_array($t["cid_list"])){
        foreach($t["cid_list"] as $n){
          if($n==$phonenumber) $s="selected=\"selected\""; 
          else if((is_array($numberAlreadyLinked))&&(in_array($n,$numberAlreadyLinked))) $s="disabled=\"disabled\"";
          else $s="";
          $trunklist.="<option value=\"".$n."\" $s>".$n."</option>";
        } 
      }
      $trunklist.="</optgroup>";
		}
  }
  //build right and left user list
  $listLeft="";
  $listRight="";
  $faxEntityArr=array();
  $ret=$asterisk->getFaxExtension(0);
  if(is_array($ret)){
    foreach($ret as $f) $faxEntityArr[]=$f['client']['id'];
  }
  $ret=$asterisk->getUser(0);
  if(is_array($ret)) {
    foreach($ret as $u){
      if(($u['type']==USER_CONFIGURATOR)||($u['type']==USER_SUPERUSER)) continue;
      $entity=getEntity($u['entity_id']);
      if((!is_array($faxEntityArr))||(in_array($u['entity_id'],$faxEntityArr))) continue;
      if(trim($u['exten'])!='') $exten="&lt;".$u['exten']."&gt;"; else $exten='';
      if((is_array($allowed))&&(in_array($u['id'],$allowed))){
        $listRight.="<option value=\"".$u['id']."\">".$u['fullname']." ".$exten."</option>\n";
      }else{
        $listLeft.="<option value=\"".$u['id']."\">".$u['fullname']." ".$exten."</option>\n";
      }
    }
  }
  //get location list
  $countrylist="";
  $location_script="";
  $locationArr=$asterisk->getLocation(0);
  if(is_array($locationArr)){
    $loc_sel_id=0;
    $loc_def_id=0;
    foreach($locationArr as $l){
      if($l["default"]==1) $loc_def_id=$l["id"];
      if($location==$l["id"]){
        $s="selected=\"selected\"";
        $loc_sel_id=$l["id"];
      }else $s="";
      $countrylist.="<option value=\"".$l["id"]."\" $s>".$l["name"]."</option>\n";
    }
    if($loc_sel_id==0) $loc_sel_id=loc_def_id;
    $location_script=" xajax_changeLocation('".$loc_sel_id."','".$area_code."'); ";
  }
  //set default tech options
  if(!(isset($_GET["id"]) and $_GET["id"]!="")) {
    $ret=$asterisk->getConfOption("","IAX2",SECTION_DEFAULT);
    if(is_array($ret)){
      foreach($ret as $o){
        if($o["name"]=="requirecalltoken") $optionsArr[]=array("key" => $o["id"] , "value" => "no");
      }
    }
  }
  //================ 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_("Return without save")?></a></h3>
    </div>
    <div id="alert"></div>
    <div id="basic_form">
      <form id="mainform" action="<?=$PHP_SELF?>" method="post">
        <table>
          <tr>
            <td>
              <p class="blockintro"><?=T_("Personal information")?></p>
              <div class="block">
                <dl>
                  <dt class="required"><label for="fax[name]"><?=T_("Name")?>:</label></dt>
                  <dd><input type="text" size="25" maxlength="30" id="fax[name]" name="fax[name]" value="<?=$name?>" /><span id="nameErr"></span></dd>
                  <dt class="required"><label for="fax[surname]"><?=T_("Surname")?>:</label></dt>
                  <dd><input type="text" size="25" maxlength="50" id="fax[surname]" name="fax[surname]" value="<?=$surname?>" /><span id="surnameErr"></span></dd>
                  <dt class="required"><label for="fax[extension]"><?=T_("Extension")?>:</label></dt>
                  <dd><input type="text" size="25" maxlength="20" id="fax[extension]" name="fax[extension]" value="<?=$extension?>" onkeyup="document.getElementById('fax[username]').value=this.value;"  onblur="document.getElementById('fax[username]').value=this.value;" /><span id="extensionErr"></span></dd>
                  <dt class="required"><label for="fax[alias]"><?=T_('Alias')?>:</label></dt>
                  <dd><input type="text" size="25" maxlength="100" id="fax[alias]" name="fax[alias]" value="<?=$alias?>" /><span id="aliasErr"></span></dd>
                </dl>
              </div>
            </td>
            <td>
              <p class="blockintro"><?=T_("Account Information")?></p>
              <div class="block">
                <dl>
                  <dt class="required"><label for="fax[username]"><?=T_("Username")?>:</label></dt>
                  <dd><input type="text" size="25" maxlength="20" id="fax[username]" name="fax[username]" value="<?=$extension?>" disabled="disabled" /><span id="usernameErr"></span></dd>
                  <dt class="required"><label for="fax[password]"><?=T_("Password")?>:</label></dt>
                  <dd><input type="password" size="25" maxlength="20" id="fax[password]" name="fax[password]" value="<?=$password?>" /><span id="passwordErr"></span></dd>
                  <dt class="required"><label for="fax[confirm]"><?=T_("Confirm")?>:</label></dt>
                  <dd><input type="password" size="25" maxlength="20" id="fax[confirm]" name="fax[confirm]" value="<?=$password?>" /><span id="confirmErr"></span></dd>
                	<dt class="required"><label for="fax[language]"><?=T_('Language')?>:</label></dt>
                  <dd><select id="fax[language]" name="fax[language]"><?=$langSelect?></select></dd>
                </dl>
              </div>
            </td>
          </tr>
        </table>
        
        <? echo listOption($js, IAX2, $optionsArr, false, false, RULE_OUTGOING);?>
        
        <!-- Fax Settings -->
        <h2><?=T_("Fax Settings")?></h2>
        <p class="blockintro"><?=T_("Set the location for this extension")?></p>
        <div class="block">
          <dl>
            <dt class="required"><label for="fax[label]"><?=T_('Label')?>:</label></dt>
            <dd><input type="text" size="25" id="fax[label]" name="fax[label]" value="<?=$label?>" /><span id="labelErr"></span></dd>
            <dt class="required"><label for="fax[phonenumber]"><?=T_('Pnonenumber')?>:</label></dt>
            <dd><select id="fax[phonenumber]" name="fax[phonenumber]"><?=$trunklist?></select><span id="phonenumberErr"></span></dd>
            <dt class="required"><label for="fax[email]"><?=T_('Email')?>:</label></dt>
            <dd><input type="text" size="25" id="fax[email]" name="fax[email]" value="<?=$email?>" /><span id="emailErr"></span></dd>
            <dt class="required"><label for="fax[printer]"><?=T_('Printer')?>:</label></dt>
            <dd><input type="text" size="25" id="fax[printer]" name="fax[printer]" value="<?=$printer?>" /><span id="printerErr"></span></dd>
          </dl>
        </div>
        
        <!-- Authorizations -->
      	<h2><?=T_("Authorizations")?></h2>
        <p class="blockintro"><?=T_("Users whose can see and send faxes through this fax account. Admin users are enabled to operate on every account for default")?></p>
        <div class="block">
          <table border="0">
            <tr>
              <td class="required">
                <div ><?=T_("Availabled users")?>:</div>
                <select multiple size="5"  name="listLeft[]" id="listLeft"><?=$listLeft?></select>
              </td>
              <td>   
                <div><input type="button" style="width:100px" onclick="moveDualList( document.getElementById('listLeft'),  document.getElementById('listRight'), false )" name="Add     >>"  value="<?=T_("Add   >")?>"></div>
                <div><input type="button" style="width:100px" onclick="moveDualList( document.getElementById('listRight'), document.getElementById('listLeft'),  false )" name="Add     <<"  value="<?=T_("<   Remove")?>"></div>
                <div><input type="button" style="width:100px" onclick="moveDualList( document.getElementById('listLeft'),  document.getElementById('listRight'), true  )" name="Add All >>"  value="<?=T_("Add All  >>")?>"></div>
                <div><input type="button" style="width:100px" onclick="moveDualList( document.getElementById('listRight'), document.getElementById('listLeft'),  true  )" name="Add All <<"  value="<?=T_("<<  Remove All")?>"></div>
              </td>
              <td class="required">
                <div><?=T_("Enabled users")?>:<span id="portlistErr"></span></div>
                <select multiple size="5" name="listRight[]" id="listRight"><?=$listRight?></select>
              </td>
            </tr>
            <tr>
              <td colspan="3">
                <input type="checkbox" id="fax[allow_everyone]" name="fax[allow_everyone]" value="1" <? if(($allow_everyone==1)||($allow_everyone=='1')) echo "checked=\"checked\""?> />
                <?=T_('Allow every user to access and use this fax account')?>
              </td>
            </tr>
          </table>
        </div>   
        
  		  <!-- Location -->
        <h2><?=T_("Location")?></h2>
        <p class="blockintro"><?=T_("Set the location for this extension")?></p>
        <div class="block">
          <dl>
            <dt class="required"><label for="fax[location]"><?=T_("Country")?>:</label></dt>
            <dd>
              <select id="fax[location]" name="fax[location]" onchange="document.getElementById('area_code_roll').innerHTML='<img src=\'<?=$relBasePath?>public/img/ico-progress.gif\' alt=\'loading\' /><span><?=T_("loading")?>';xajax_changeLocation(this.options[this.selectedIndex].value,'<?=$area_code?>')">
                <?=$countrylist?>
              </select>
            </dd>
            <dt class="required"><label for="fax[area_code]"><?=T_("Area Code")?>:</label></dt>
            <dd>
              <div id="area_code_div" style="display:inline;">&nbsp;</div>
              <div id="area_code_roll" style="display:inline;"><img src="<?=$relBasePath?>public/img/ico-progress.gif" alt="loading" /><span><?=T_("loading")?></span></div>            
            </dd>
          </dl>
        </div>  
        <!-- Buttons -->
        <div class="action">
          <?if ($_GET["id"]!="") {?>
            <input type="hidden" id="fax[id]" name="fax[id]" value="<?=$id?>" />
            <input type="hidden" id="fax[id_client]" name="fax[id_client]" value="<?=$id_client?>" />
          <?}?>
          <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="javascript:history.back(); return false;"/></a> <!-- onclick=" location.href='../'; return false;" -->
          <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 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>
      <?=$location_script?>
    </script>
  <?
  $contents=ob_get_contents();
  ob_end_clean();
  //================ SIDEBAR ================
  ob_start();
  ?>
    <div class="Sidebar">
      <?$sel="extensions";include("../../sidebar.php");?>
      <h1><?=T_('Informations')?></h1>
      <p><?=T_("This page allows you to create a new fax extension or to modify an existing one. To create a new fax extension you have to define the extension's number, the password, the fax phone number and to press save button on the end of the page. Moreover it's possible to define other parameters like the ruleset, the mail address for the forwarding of the incoming faxes, the fax use authorizations, etc...")?></p>
    </div>
  <?
  $sidebar=ob_get_contents();
  ob_end_clean();
  //================ SETTINGS ================
  sajax_handle_client_request();
  $smarty->assign("section", "extensions");
  $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');
?>

