<?
/**
 * VoiceOne Settings/Extensions/Voicemail
 *
 * Frontend to provide access to the extensions system in voiceone.
 * @package voiceone
 * @subpackage  settings_extensions
 */

  include ("../../../../admin/config/cfg.php");
  global $cwlang;
  require_once("$absBasePath/lib/xajax/xajax.inc.php");

  //================ XAJAX ================
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    //extract form params
    $cfu=$formData["CFU"];
    $cfb=$formData["CFB"];
    $cfnr=$formData["CFNR"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">";
    // Check CFU ((not null)&&(numeric))
    $cfuErr=false;
    if($cfu["status"]==1) {
      if($cfu["target"]==""){
        //cfu cannot be null
        $errOut[]= T_("If active, CFU cannot be null");
        $objResponse->addAssign("cfuErr","innerHTML",$imgErr);
        $cfuErr=true;
      }else{
        //cfu must be numeric
        for($i=0; $i<strlen($cfu["target"]); $i++){
          $ch=ord($cfu["target"][$i]);
          if(!((($ch>47)&&($ch<58)))){
            $errOut[]= T_("CFU allow only numeric characters. Please change it");
            $objResponse->addAssign("cfuErr","innerHTML",$imgErr);
            $cfuErr=true;
            break;
          }
        }
      }
    }
    if($cfuErr===false) $objResponse->addAssign("cfuErr","innerHTML","");
    // Check CFB ((not null)&&(numeric))
    $cfbErr=false;
    if($cfb["status"]==1) {
      if($cfb["target"]==""){
        //cfb cannot be null
        $errOut[]= T_("If active, CFB cannot be null");
        $objResponse->addAssign("cfbErr","innerHTML",$imgErr);
        $cfbErr=true;
      }else{
        //cfb must be numeric
        for($i=0; $i<strlen($cfb["target"]); $i++){
          $ch=ord($cfb["target"][$i]);
          if(!((($ch>47)&&($ch<58)))){
            $errOut[]= T_("CFB allow only numeric characters. Please change it");
            $objResponse->addAssign("cfbErr","innerHTML",$imgErr);
            $cfbErr=true;
            break;
          }
        }
      }
    }
    if($cfbErr===false) $objResponse->addAssign("cfbErr","innerHTML","");
    // Check cfnr ((not null)&&(numeric))
    $cfnrErr=false;
    if($cfnr["status"]==1) {
      if($cfnr["target"]==""){
        //cfnr cannot be null
        $errOut[]= T_("If active, CFNR cannot be null");
        $objResponse->addAssign("cfnrErr","innerHTML",$imgErr);
        $cfnrErr=true;
      }else{
        //cfnr must be numeric
        for($i=0; $i<strlen($cfnr["target"]); $i++){
          $ch=ord($cfnr["target"][$i]);
          if(!((($ch>47)&&($ch<58)))){
            $errOut[]= T_("CFNR allow only numeric characters. Please change it");
            $objResponse->addAssign("cfnrErr","innerHTML",$imgErr);
            $cfnrErr=true;
            break;
          }
        }
      }
    }
    if($cfnrErr===false) $objResponse->addAssign("cfnrErr","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("processFormData");
  $xajax->processRequests();
  //================ POST & GET =================
  if((count($_POST)>0)&&(isset($_POST["extension"]))){
    $ret=1;
    $extension=$_POST["extension"];
    //set asterisk database
    if(isset($_POST["DND"])){ //set DND
      if($_POST["DND"]["status"]==1) $r=$asterisk->putInDB("DND",$extension,"yes");
      else $r=$asterisk->rmFromDB("DND",$extension);
      $ret=intval($ret)*($r);
    }
    if(isset($_POST["CFU"])){ //set CFU
      if($_POST["CFU"]["status"]==1) $r=$asterisk->putInDB("CFU",$extension,$_POST["CFU"]["target"]);
      else $r=$asterisk->rmFromDB("CFU",$extension);
      $ret=$ret*$r;
    }
    if(isset($_POST["CFB"])){ //set CFB
      if($_POST["CFB"]["status"]==1) $r=$asterisk->putInDB("CFB",$extension,$_POST["CFB"]["target"]);
      else $r=$asterisk->rmFromDB("CFB",$extension);
      $ret=$ret*$r;
    }
    if(isset($_POST["CFNR"])){ //set CFNR
      if($_POST["CFNR"]["status"]==1) $r=$asterisk->putInDB("CFNR",$extension,$_POST["CFNR"]["target"]);
      else $r=$asterisk->rmFromDB("CFNR",$extension);
      $ret=$ret*$r;
    }
		//If it is a virtual extension...
    if(($ret!=0)&&(isset($_POST["virtual"]))&&($_POST["virtual"]!="")&&($_POST["virtual"]!=0)){
    	//...set cf settings for each linked clients
      $virtual=$asterisk->getVirtualExtension($_POST["virtual"]);
      if((is_array($virtual))&&(is_array($virtual[0]))&&   
      	 (is_array($virtual[0]["linked_clients"]))&&(count($virtual[0]["linked_clients"])>0)){
      	foreach($virtual[0]["linked_clients"] as $client_id){
        	$clientArr=$asterisk->getClient($client_id,0);
          if((is_array($clientArr))&&(is_array($clientArr[0]))){
          	$extension=$clientArr[0]["extension"];
            if(isset($_POST["DND"])){ //set DND
              if($_POST["DND"]["status"]==1) $r=$asterisk->putInDB("DND",$extension,"yes");
              else $r=$asterisk->rmFromDB("DND",$extension);
              $ret=intval($ret)*($r);
            }
            if(isset($_POST["CFU"])){ //set CFU
              if($_POST["CFU"]["status"]==1) $r=$asterisk->putInDB("CFU",$extension,$_POST["CFU"]["target"]);
              else $r=$asterisk->rmFromDB("CFU",$extension);
              $ret=$ret*$r;
            }
            if(isset($_POST["CFB"])){ //set CFB
              if($_POST["CFB"]["status"]==1) $r=$asterisk->putInDB("CFB",$extension,$_POST["CFB"]["target"]);
              else $r=$asterisk->rmFromDB("CFB",$extension);
              $ret=$ret*$r;
            }
            if(isset($_POST["CFNR"])){ //set CFNR
              if($_POST["CFNR"]["status"]==1) $r=$asterisk->putInDB("CFNR",$extension,$_POST["CFNR"]["target"]);
              else $r=$asterisk->rmFromDB("CFNR",$extension);
              $ret=$ret*$r;
            }
            if($ret==0) break;
          }
    		}
      }
    }
    if ($ret>0) $alert="<div class=\"AlertGood\">".T_("Extension's Call Forward settings has been edited")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("Extension's Call Forward settings hasn't been edited")."</div>";
    //go to main page
    goToMainPage($alert,"../");
  }
  //================ PAGE LOGIC ================
  $is_virtual=false;
  //get settings
  switch ($_GET["type"]) {
    case 'extension':
      $ret=$asterisk->getClient($_GET["id"],0);
      if((is_array($ret))&&(is_array($ret[0]))){
        $extension=$ret[0]["extension"];
        $title=sprintf(T_("Edit Call Forward for extension \"%s\""),$extension );
        break;
      }else{
        header("location: ../");
        die();
      }
    case 'virtual':
      $ret=$asterisk->getVirtualExtension($_GET["id"]);
      if((is_array($ret))&&(is_array($ret[0]))){
        $extension=$ret[0]["extension"];
        $title=sprintf(T_("Edit Call Forward for extension \"%s\""),$extension );
        break;
      }else{
        header("location: ../");
        die();
      }
    case 'group':
      $ret=$asterisk->getGroup($_GET["id"],0);
      if((is_array($ret))&&(is_array($ret[0]))){
        $entityArr=$asterisk->resolveExstensionGroup($ret[0]['id']);
        if((is_array($entityArr))&&(count($entityArr)>1)){
          foreach($entityArr as $entity) $groupString.=$entity."&";
          if(trim($groupString)!='') $groupString=substr($groupString,0,-1);
          $extension=$groupString;
          $title=sprintf(T_("Edit Call Forward for group \"%s\""),$ret[0]['name'] );
          break;
        }else{
          header("location: ../");
          die();
        }
      }else{
        header("location: ../");
        die();
      }
    default:
      header("location: ../");
      die();
  }
  //inizialize DND
  $ret=$asterisk->getFromDB("DND",$extension);
  if($ret["present"]==1) $DND=1; else $DND=0;
  //inizialize CFU
  $ret=$asterisk->getFromDB("CFU",$extension);
  if($ret["present"]==1) {$CFU=1; $CFU_target=$ret["value"]; $CFU_disabled="";}
  else {$CFU=0; $CFU_disabled="disabled=\"disabled\"";}
  //inizialize CFB
  $ret=$asterisk->getFromDB("CFB",$extension);
  if($ret["present"]==1) {$CFB=1; $CFB_target=$ret["value"]; $CFB_disabled="";}
  else {$CFB=0; $CFB_disabled="disabled=\"disabled\"";}
  //inizialize CFNR
  $ret=$asterisk->getFromDB("CFNR",$extension);
  if($ret["present"]==1) {$CFNR=1; $CFNR_target=$ret["value"]; $CFNR_disabled="";}
  else {$CFNR=0; $CFNR_disabled="disabled=\"disabled\"";}

  //================ 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">
        <!-- DND -->
        <h2><?=T_("DND (Do Not Disturb)")?></h2>
        <p class="blockintro"><?=T_("Ignore any incoming calls")?></p>
        <div class="block">
          <dl>
            <dt class="required"><label for="DND[status]"><?=T_("DND:")?></label></dt>
            <dd>
              <input type="radio" id="DND[status]" name="DND[status]" value="1" <?if ($DND==1) echo "checked=\"checked\""; ?> /> <?=T_("ON")?>
              <input type="radio" id="DND[status]" name="DND[status]" value="0" <?if ($DND!=1) echo "checked=\"checked\""; ?> /> <?=T_("OFF")?>
            </dd>
          </dl>
        </div>
        <!-- CF -->
        <h2><?=T_("Call Forwarding")?></h2>
        <p class="blockintro"><?=T_("Route calls to some other destination")?></p>
        <div class="block">
          <dl>
            <table>
              <tr>
                <td>
                  <dt class="required" style="width:50px;"><label for="CFU[status]"><?=T_("CFU:")?></label></dt>
                  <dd>
                    <input type="radio" id="CFU[status]" name="CFU[status]" value="1" onclick="document.getElementById('CFU[target]').disabled='';" <?if ($CFU==1) echo "checked=\"checked\""; ?> /> <?=T_("ON")?>
                    <input type="radio" id="CFU[status]" name="CFU[status]" value="0" onclick="document.getElementById('CFU[target]').disabled='disabled';" <?if ($CFU!=1) echo "checked=\"checked\""; ?> /> <?=T_("OFF")?>
                  </dd>
                </td>
                <td><?=T_("(Call Forward Unconditional) calls are forwarded to number")?>:</td>
                <td><input type="text"  id="CFU[target]" name="CFU[target]" value="<?=$CFU_target?>" <?=$CFU_disabled?> /> <span id="cfuErr"></span></td>
              </tr>
              <tr>
                <td>
                  <dt class="required" style="width:50px;"><label for="CFB[status]"><?=T_("CFB:")?></label></dt>
                  <dd>
                    <input type="radio" id="CFB[status]" name="CFB[status]" value="1" onclick="document.getElementById('CFB[target]').disabled='';" <?if ($CFB==1) echo "checked=\"checked\""; ?> /> <?=T_("ON")?>
                    <input type="radio" id="CFB[status]" name="CFB[status]" value="0" onclick="document.getElementById('CFB[target]').disabled='disabled';" <?if ($CFB!=1) echo "checked=\"checked\""; ?> /> <?=T_("OFF")?>
                  </dd>
                </td>
                <td><?=T_("(Call forward on Busy) calls are forwarded to number")?>:</td>
                <td><input type="text"  id="CFB[target]" name="CFB[target]" value="<?=$CFB_target?>" <?=$CFB_disabled?> /> <span id="cfbErr"></span></td>
              </tr>
              <tr>
                <td>
                  <dt class="required" style="width:50px;"><label for="CFNR[status]"><?=T_("CFNR:")?></label></dt>
                  <dd>
                    <input type="radio" id="CFNR[status]" name="CFNR[status]" value="1" onclick="document.getElementById('CFNR[target]').disabled='';"<?if ($CFNR==1) echo "checked=\"checked\""; ?> /> <?=T_("ON")?>
                    <input type="radio" id="CFNR[status]" name="CFNR[status]" value="0" onclick="document.getElementById('CFNR[target]').disabled='disabled';"<?if ($CFNR!=1) echo "checked=\"checked\""; ?> /> <?=T_("OFF")?>
                  </dd>
                </td>
                <td><?=T_("(Call forward on No Reply) calls are forwarded to number")?>:</td>
                <td><input type="text" id="CFNR[target]" name="CFNR[target]" value="<?=$CFNR_target?>" <?=$CFNR_disabled?> /> <span id="cfnrErr"></span></td>
              </tr>
            </table>
          </dl>
        </div>
        <!-- Buttons -->
        <div class="action">
          <?if($_GET["id"]!="") {?> <input type="hidden" id="extension" name="extension" value="<?=$extension?>" /><?}?>
         	<?if($_GET["type"]!="") {?>	<input type="hidden" name="type" value="<?=$_GET['type']?>" /><?}?>
          <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>
        </div>
      </form>
    </div>
  <?
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start();
  ?>
    <div class="Sidebar">
      <?$sel="callforward";include("../../sidebar.php");?>
      <h1><?=T_("Informations")?></h1>
      <p><?=T_("This page allows you to configure DND and call forward services. The extensions which have DND enabled are always unreachable. The calls to extensions which have call forward enabled are transfered to the defined number only if the extension is busy (CFB) or only on no reply (CFNR) or always (CFU). Press save button on the end of the page to save the configuration.")?></p>
    </div>
  <?
  $sidebar=ob_get_contents();
  ob_end_clean();

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

