<?
/**
 * VoiceOne Settings/sounds
 *
 * Frontend to manage asterisk's sounds in voiceone.
 * @package voiceone
 * @subpackage  settings_sounds
 */
  include ("../../admin/config/cfg.php");
  global $cwlang;
  require_once("$absBasePath/lib/xajax/xajax.inc.php");

  //=================== XAJAX ==================
  function saveEmptyMessage($filename, $cat_id, $cat_tag, $cat_name, $language){
    global $asterisk, $cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // check file name
    $exist=false;
    $filename=str_replace(" ","_",$filename);
    $filename=str_replace(array("'","\""),"",$filename);
    $files=getSoundDesc("", $cat_id, $language);
    foreach($files as $file){
      if($file["name"]==$filename) $exist=true;
    }
    // create empty "custom" file
    if($exist===false) $ret=$asterisk->createEmptyFile($filename, $cat_id, $language);
    // Return the xajaxResponse object
    if($exist===true){
      $script=" if(confirm('File \"".addslashes($filename)."\" ".addslashes(T_("already exist: edit it?"))."')) xajax_editFile('".addslashes($filename)."', '".addslashes($cat_tag)."', '".addslashes($cat_id)."', '".addslashes($cat_name)."', '".addslashes($language)."'); ";
      $objResponse->addScript($script);
    }else{
      if($ret==1){
        $script=" location.href = './index.php?action=insert&file=".addslashes($filename)."&catid=".addslashes($cat_id)."&cattag=".addslashes($cat_tag)."&catname=".addslashes($cat_name)."&lang=".addslashes($language)."'; \n";
        $objResponse->addScript($script);
      }else{
        $html=" <div class=\"AlertBad\">".T_("Creation error")."</div>";
        $objResponse->addAssign("error","innerHTML", $html);
      }
    }
    return $objResponse->getXML();
  }
  function deleteMessage($filename, $cat_id, $cat_tag, $cat_name, $language){
    global $asterisk, $cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // delete "custom" file
    $ret=$asterisk->deleteFile($filename, $cat_id, $language);
    // Return the xajaxResponse object
    if($ret==1){
      $script=" location.href = './index.php?action=delete&file=".addslashes($filename)."&catid=".addslashes($cat_id)."&cattag=".addslashes($cat_tag)."&catname=".addslashes($cat_name)."&lang=".addslashes($language)."'; \n";
      $objResponse->addScript($script);
    }else{
      $html=" <div class=\"AlertBad\">".T_("Delete error")."</div>";
      $objResponse->addAssign("error","innerHTML", $html);
    }
    return $objResponse->getXML();
  }
  function modify($filename, $cat_id, $cat_tag, $cat_name, $lng, $newcontent, $modtext, $newtext){
    global $relBasePath, $cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // print load icon
    $html="<table><tr><td><img src='".$relBasePath."/public/img/ico-progress.gif'></td><td><p> waiting...</p></td>";
    $script=" xajax_modifySoundFile('".addslashes($filename)."', '".addslashes($cat_id)."', '".addslashes($cat_tag)."', '".addslashes($cat_name)."', '".addslashes($lng)."', '".addslashes($newcontent)."', '".addslashes($modtext)."', '".addslashes($newtext)."'); ";
    // Return the xajaxResponse object
    $objResponse->addAssign("main","innerHTML", $html);
    $objResponse->addAssign("error","innerHTML", "");
    $objResponse->addScript($script);
    return $objResponse->getXML();
  }
  function modifySoundFile($filename, $cat_id, $cat_tag, $cat_name, $lng, $newcontent, $modtext, $newtext){
    global $asterisk, $cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // insert entry in db
    $ret=$asterisk->modifySound($filename, $cat_id, $lng, $newcontent, $modtext, $newtext);
    // Return the xajaxResponse object
    if($ret==1) {
      $script=" xajax_showFolder('".addslashes($cat_id)."', '".addslashes($cat_tag)."', '".addslashes($cat_name)."', '".addslashes($lng)."', 'on', '".addslashes($filename)."'); ";
      $objResponse->addScript($script);
    }else{
      $html=" <div class=\"AlertBad\">".T_("Upload error")."</div>";
      $objResponse->addAssign("error","innerHTML", $html);
      $script=" xajax_showFolder('".addslashes($cat_id)."', '".addslashes($cat_tag)."', '".addslashes($cat_name)."', '".addslashes($lng)."'); ";
      $objResponse->addScript($script);
    }
    return $objResponse->getXML();
  }
  function recordMessage($client_id, $messagename){
    global $asterisk;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // insert entry in db
    $ret=$asterisk->recordNewMessage($client_id, $messagename);
    if($ret==1) $ret=$asterisk->putTempSound($messagename);
    // refresh file list
    $tmp_id=$asterisk->getCatidByTagname("tmp");
    $tmpfiles=$asterisk->getSoundDesc("", $tmp_id, "");
    $fileselect="<select size=\"5\" id=\"fileList\" onclick=\"document.getElementById('selected').value=this.options[this.selectedIndex].value;\"> ";
    foreach($tmpfiles as $tmpfile){
      $fileselect.="    <option value=\"".$tmpfile["name"]."\">".$tmpfile["name"]."</option>";
    }
    $fileselect.="</select>";
    // Return the xajaxResponse object
    $objResponse->addAssign("fileselect","innerHTML", $fileselect);
    $objResponse->addAssign("error","innerHTML", "");
    return $objResponse->getXML();
  }
  function deleteTempMessage($messagename){
    global $asterisk;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // insert entry in db
    $ret=$asterisk->deleteTempSound($messagename);
    if($ret==1) $ret=$asterisk->deleteRecordedMessage($messagename);
    // Create file list
    $tmp_id=$asterisk->getCatidByTagname("tmp");
    $tmpfiles=$asterisk->getSoundDesc("", $tmp_id, "");
    $fileselect="<select size=\"5\" id=\"fileList\" onclick=\"document.getElementById('selected').value=this.options[this.selectedIndex].value;\"> ";
    foreach($tmpfiles as $tmpfile){
      $tmpfilename=trim($tmpfile["name"]);
      if(strlen($tmpfilename)>15) $tmpfilename=substr($tmpfilename,0,12)."...";
      $fileselect.="    <option value=\"".$tmpfile["name"]."\">".$tmpfilename."</option>";
    }
    $fileselect.="</select>";
    // Return the xajaxResponse object
    $objResponse->addAssign("fileselect","innerHTML", $fileselect);
    $objResponse->addAssign("error","innerHTML", "");
    return $objResponse->getXML();
  }
  function showFolder($cat_id, $cat_tag, $category, $lang, $effect='off', $target=''){
    global $cwlang, $asterisk, $relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Build response
    $html="<div class=\"SectionHeader\"><h1>".T_("Category")." \"".$category."\"</h1> \n";
    if(($cat_tag=="custom")||($cat_tag=="IVR")) $html.="<h3><a class=\"admin\" href=\"javascript:newFile('".$cat_id."','".$cat_tag."','".$category."','".$lang."');\" >".T_("new file")."</a></h3> \n";
    $html.="</div> \n";
    $ret=$asterisk->getSoundDesc("", $cat_id, $lang);
    if (is_array($ret)){
      $count=0;
      $html.="<table style=\"font-size: smaller;\"><tr>  \n";
      foreach($ret as $file){
        $html.="<td>      \n";
        $html.="  <table id=".$file["name"]."> \n";
        $html.="    <tr>  \n";
        $html.="      <td><img src=\"$relBasePath/public/img/music_note.gif\"/> <a href=\"javascript:editFile('".addslashes($file["name"])."','".addslashes($cat_id)."','".addslashes($cat_tag)."','".addslashes($category)."','".addslashes($lang)."');\">".str_replace("_"," ",str_replace(array("'","\""),"",$file["name"]))."</a></td>    \n";
        if(($cat_tag=="custom")||($cat_tag=="IVR")) $html.="      <td><input type=\"image\" src=\"$relBasePath/public/img/trash.gif\" alt=\"Delete\" onclick=\"javascript:deleteFile('".addslashes($file["name"])."','".$cat_id."','".$cat_tag."','".$category."','".$lang."');\" /></td>\n";
        $html.="      <td><input type=\"image\" src=\"$relBasePath/public/img/play.gif\" alt=\"Play\" onclick=\"location.href='stream.php?filename=".addslashes($file["name"])."&id=".addslashes($cat_id)."&lang=".addslashes($lang)."';\" /></td>\n";
        $html.="    </tr> \n";
        $html.="  </table>\n";
        $html.="</td>     \n";
        if((++$count)%3==0) $html.="</tr><tr>  \n";
      }
      $html.="</tr></table>  \n";
    }
    $script=" Fat.fade_element('".addslashes($target)."', 30, 300, '#FFFF33', '#FFFFFF'); ";
    // Return the xajaxResponse object
    if(($effect=="on")&&($target!="")) $objResponse->addScript($script);
    $objResponse->addAssign("main","innerHTML", $html);
    $objResponse->addAssign("error","innerHTML", "");
    return $objResponse->getXML();
  }
  function editFile($name, $cat_id, $cat_tag, $category, $lang){
    global $cwlang, $asterisk, $relBasePath, $cwLanguage;
    // Set upload limit
    function return_bytes($val) {
      $val = trim($val);
      $last = $val{strlen($val)-1};
      switch($last) {
        case 'k':
        case 'K':
          return (int) $val * 1024;
          break;
        case 'm':
        case 'M':
          return (int) $val * 1048576;
          break;
        default:
          return $val;
      }
    }
    $uploadlimit=min(return_bytes(ini_get("post_max_size")),return_bytes(ini_get("upload_max_filesize")));
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Create client list
    $clients=$asterisk->getClient("","");
    if(is_array($clients)){
      $extselect="<select id=\"clientsList\" name=\"clientsList\">";
      foreach($clients as $client){
        $clientname=$client["name"]." ".$client["surname"]." <".$client["extension"].">";
        $extselect.="           <option value=\"".$client["id"]."\">".$clientname."</option>";
      }
      $extselect.="</select>";
      $disablerecord="";
    }else{
      $extselect="<input type=\"text\" size=\"35\" id=\"clientsList\" name=\"clientsList\" disabled=\"disabled\" value=\"[".T_("There are no defined extensions")."]\" />";
      $disablerecord="disabled=\"disabled\"";
    }
    // Create file list
    $tmp_id=$asterisk->getCatidByTagname("tmp");
    $tmpfiles=$asterisk->getSoundDesc("", $tmp_id, "");
    $fileselect="<select size=\"5\" id=\"fileList\" onclick=\"document.getElementById('selected').value=this.options[this.selectedIndex].value;\"> ";
    foreach($tmpfiles as $tmpfile){
      $tmpfilename=trim($tmpfile["name"]);
      if(strlen($tmpfilename)>15) $tmpfilename=substr($tmpfilename,0,12)."...";
      $fileselect.="    <option value=\"".$tmpfile["name"]."\">".$tmpfilename."</option>";
    }
    $fileselect.="</select>";

    // Build response
    $ret=$asterisk->getSoundDesc($name, $cat_id, $lang);
    if($ret[0]["lastmodified"]=="0000-00-00 00:00:00") $modified="-- ".T_("never")." -- ";
    else $modified=$ret[0]['lastmodified'];
    ob_start();
    ?>
      <div class="SectionHeader">
        <h1><input type="image" src="<?=$relBasePath?>/public/img/play.gif" alt="Play" onclick="location.href='stream.php?filename=<?=addslashes($ret[0]['name'])?>&id=<?=addslashes($ret[0]['cat_id'])?>&lang=<?=addslashes($lang)?>';"/>
            <? if(($ret[0]['cat_tag']=='custom')||($ret[0]['cat_tag']=='IVR')) { ?>
              <input type="image" src="<?=$relBasePath?>/public/img/trash.gif" alt="Delete" onclick="javascript:deleteFile('<?=addslashes($ret[0]['name'])?>','<?=addslashes($ret[0]['cat_id'])?>','<?=addslashes($ret[0]['cat_tag'])?>','<?=addslashes($ret[0]['category'])?>','<?=addslashes($lang)?>');" />
            <? } ?>
            File "<?=$name?>" </h1>
      </div>
      <div id="basic_form">
        <h2><?=T_("File")?></h2>
        <p class="blockintro"><?=T_("General file informations")?></p>
          <div class="block">
            <dl>
              <dt class="required"><label><?=$cwlang[sounds][fileName]?>:</label></dt>
                <dd><input style="width: 150px" disabled="disabled" type="text" value="<?=$ret[0]['name']?>"></dd>
              <dt class="required"><label><?=$cwlang[sounds][fileCategory]?>:</label></dt>
                <dd><input style="width: 150px" disabled="disabled" type="text" value="<?=$ret[0]['category']?>"></dd>
              <dt class="required"><label><?=$cwlang[sounds][fileLanguage]?>:</label></dt>
                <dd><input style="width: 150px" disabled="disabled" type="text" value="<?=$lang?>"></dd>
              <dt class="required"><label><?=$cwlang[sounds][fileLastmod]?>:</label></dt>
                <dd><input style="width: 150px" disabled="disabled" type="text" value="<?=$modified?>"></dd>
              <dt class="required"><label><?=$cwlang[sounds][filePath]?>:</label></dt>
                <dd><input style="width: 494px" disabled="disabled" type="text" value="<?=$ret[0]['filepath']?>"></dd>
              <dt class="required"><label><?=$cwlang[sounds][fileText]?>:</label></dt>
                <dd><textarea id="desctext" name="desctext" style="width: 500px"><?=$ret[0]['text']?></textarea></dd>
            </dl>
          </div>
        <h2><?=T_("Audio")?></h2>
        <p class="blockintro"><?=T_("Record or upload a new message and overwrite the existing one")?></p>
          <div class="block">
            <table cellpadding="0" cellspacing="0">
              <tr>
                <td style="border-right: 1px solid gray;">
                  <table style="width: 250px;" cellpadding="0" cellspacing="0" >
                    <tr>
                      <td colspan="2"><label><?=T_("1a) Record a new audio file: ")?></label></td>
                    </tr>
                    <tr>
                      <td><?=$extselect?></td>
                      <td width="1"><input type="image" src="<?=$relBasePath?>/public/img/record.gif" alt="Record" onclick="recordMessage();" <?=$disablerecord?>/></td>
                    </tr>
                    <tr>
                      <td  style="text-align: center"><strong><?=T_("-- OR --")?></strong>&nbsp;</td>
                      <td></td>
                    </tr>
                    <tr>
                      <td colspan="2"><label><?=T_("1b) Upload a new audio file (.wav):")?></label></td>
                    </tr>
                    <tr>
                      <td colspan="2">
                        <form action="./index.php?lang=<?=$lang?>" method="post" enctype="multipart/form-data">
                          <table>
                            <tr>
                              <td>
                                <input type="hidden" name="MAX_FILE_SIZE" value="<?=$uploadlimit?>" />
                                <input type="hidden" name="oldFilename" value="<?=$name?>" />
                                <input type="hidden" name="oldCatid" value="<?=$cat_id?>" />
                                <input type="hidden" name="oldCattag" value="<?=$cat_tag?>" />
                                <input type="hidden" name="oldCategory" value="<?=$category?>" />
                                <input type="hidden" name="oldLang" value="<?=$lang?>" />
                                <input type="file" name="uploadedfile" id="uploadedfile" size="25" value="" />
                              </td>
                              <td>
                                <input type="image" src="<?=$relBasePath?>/public/img/add.gif" alt="Upload" onclick="if(document.getElementById('uploadedfile').value==''){ alert('<?=addslashes($cwlang['sounds']['emptyPath'])?>'); return false;} else return true;"/>
                              </td>
                            </tr>
                          </table>
                        </form>
                      </td>
                    </tr>
                    <tr><td colspan="2" align="center">(<?=T_("upload limit")?>: <?=byte_converter($uploadlimit)?>)</td></tr>
                  </table>
                </td>
                <td>
                  <table>
                    <tr>
                      <td colspan="3"><label><?=T_("2) Select new audio content:")?></label></td>
                    </tr>
                    <tr>
                      <td width="1"><input type="image" src="<?=$relBasePath?>/public/img/play.gif" alt="Play" onclick="location.href='stream.php?filename=' + document.getElementById('fileList').options[document.getElementById('fileList').selectedIndex].value + '&id=<?=addslashes($tmp_id)?>&lang=default';"/>
                                    <input type="image" src="<?=$relBasePath?>/public/img/trash.gif" alt="Delete" onclick="deleteTempMessage();"/></td>
                      <td><div id="fileselect"><?=$fileselect?></div></td>
                      <td><?=T_("selected")?>:<input type="text" id="selected" name="selected" value="" /></td>
                    </tr>
                  </table>
                </td>
            </table></tr>
          </div>
          <div class="action">
            <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="showFolder('<?=addslashes($cat_id)?>','<?=addslashes($cat_tag)?>','<?=addslashes($ret[0]['category'])?>','<?=addslashes($lang)?>');"/>
            <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick="save('<?=addslashes($name)?>','<?=addslashes($cat_id)?>','<?=addslashes($cat_tag)?>','<?=addslashes($ret[0]['category'])?>','<?=addslashes($lang)?>');"/>

          </div>
          <input type="hidden" id="oldText" name="oldText" value="<?=$ret[0]['text']?>" />
      </div>
    <?
    $html=ob_get_contents();
    ob_end_clean();
    // Return the xajaxResponse object
    $objResponse->addAssign("main","innerHTML", $html);
    $objResponse->addAssign("error","innerHTML", "");
    return $objResponse->getXML();
  }
  function buildTree($lang, $toexpand=''){
    global $relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Build response
    $html=" <table><tr>";
    $html.=" <td><img src=\"".$relBasePath."public/img/ico-progress.gif"."\" alt=\"loading\" /></td>";
    $html.=" <td><p>".T_("loading...")."</p></td>";
    $html.=" </tr></table>";
    $script=" xajax_makeTree('".addslashes($lang)."','".addslashes($toexpand)."') ";
    // Return the xajaxResponse object
    $objResponse->addAssign("tree","innerHTML", $html);
    $objResponse->addAssign("error","innerHTML", "");
    $objResponse->addScript($script);
    return $objResponse->getXML();
  }
  function makeTree($lang, $toexpand){
    global $cwlang, $asterisk, $relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // make tree
    $htmlscript="  var tree = new WebFXTree('".T_("Sounds")."'); \n";
    $htmlscript.="  tree.setBehavior('explorer');  \n";
    $htmlscript.="  tree.icon = '".$relBasePath."public/img/cd.jpg';  \n";
    $htmlscript.="  tree.openIcon = '".$relBasePath."public/img/cd.jpg';  \n";
    $htmlscript.="  tree.action = './index.php';  \n";
    // insert categories
    $ret=$asterisk->getCategories();
    foreach($ret as $category){
      if($category["tag"]=="tmp") continue;
      $htmlscript.="  var ".$category["tag"]." = new WebFXTreeItem('".$category["description"]."');  \n";
      $htmlscript.="  ".$category["tag"].".showButtons = false;  \n";
      $htmlscript.="  ".$category["tag"].".action = 'javascript:showFolder(\'".addslashes($category["id"])."\',\'".addslashes($category["tag"])."\',\'".addslashes($category["description"])."\',\'".addslashes($lang)."\');';  \n";
      $htmlscript.="  tree.add(".$category["tag"].");  \n";
      if($category["tag"]=="custom"){
        $htmlscript.="  var newcustom = new WebFXTreeItem('new...');  \n";
        $htmlscript.="  newcustom.showButtons = false;  \n";
        $htmlscript.="  newcustom.icon = '".$relBasePath."public/img/xtree/file.png';  \n";
        $htmlscript.="  newcustom.openIcon = '".$relBasePath."public/img/xtree/file.png';  \n";
        $htmlscript.="  newcustom.action = 'javascript:newFile(\'".addslashes($category["id"])."\',\'".addslashes($category["tag"])."\',\'".addslashes($category["description"])."\',\'".addslashes($lang)."\');';  \n";
        $htmlscript.="  ".$category["tag"].".add(newcustom);  \n";
      }
      else if($category["tag"]=="IVR"){
        $htmlscript.="  var newIVR = new WebFXTreeItem('new...');  \n";
        $htmlscript.="  newIVR.showButtons = false;  \n";
        $htmlscript.="  newIVR.icon = '".$relBasePath."public/img/xtree/file.png';  \n";
        $htmlscript.="  newIVR.openIcon = '".$relBasePath."public/img/xtree/file.png';  \n";
        $htmlscript.="  newIVR.action = 'javascript:newFile(\'".addslashes($category["id"])."\',\'".addslashes($category["tag"])."\',\'".addslashes($category["description"])."\',\'".addslashes($lang)."\');';  \n";
        $htmlscript.="  ".$category["tag"].".add(newIVR);  \n";
      }
    }
    // insert files
    $ret=$asterisk->getSoundDesc("", 0, $lang);
    foreach($ret as $file){
      if($file["cat_tag"]=="tmp") continue;
      $file["name"]=addslashes($file["name"]);
      $htmlscript.="  var "."file".$file["id"]." = new WebFXTreeItem('".$file["name"]."');  \n";
      $htmlscript.="  "."file".$file["id"].".showButtons = false;  \n";
      $htmlscript.="  "."file".$file["id"].".icon = '".$relBasePath."public/img/music_note.gif';  \n";
      $htmlscript.="  "."file".$file["id"].".openIcon = '".$relBasePath."public/img/music_note_small.gif';  \n";
      //$htmlscript.="  "."file".$file["id"].".action = 'javascript:editFile(\'".$file["name"]."\',\'".$file["cat_id"]."\',\'".$file["cat_tag"]."\',\'".$file["category"]."\',\'".$lang."\');';  \n";
      $htmlscript.="  "."file".$file["id"].".action = \"javascript:editFile('".addslashes($file["name"])."','".addslashes($file["cat_id"])."','".addslashes($file["cat_tag"])."','".addslashes($file["category"])."','".addslashes($lang)."');\";  \n";
      $htmlscript.="  ".$file["cat_tag"].".add("."file".$file["id"].");  \n";
    }
    $htmlscript.="  document.getElementById('tree').innerHTML=tree;  \n";
    if($toexpand=='custom') $htmlscript.="  custom.expand();  \n";
    if($toexpand=='IVR') $htmlscript.="  IVR.expand();  \n";
    // Return the xajaxResponse object
    $objResponse->addScript($htmlscript);
    return $objResponse->getXML();
  }
  $xajax = new xajax();
  $xajax->registerFunction("buildTree");
  $xajax->registerFunction("makeTree");
  $xajax->registerFunction("showFolder");
  $xajax->registerFunction("editFile");
  $xajax->registerFunction("recordMessage");
  $xajax->registerFunction("deleteTempMessage");
  $xajax->registerFunction("modifySoundFile");
  $xajax->registerFunction("saveEmptyMessage");
  $xajax->registerFunction("deleteMessage");
  $xajax->registerFunction("modify");
  $xajax->processRequests();
  //================= GET & POST ==================
  $lang="en";
  $loading=false;
  if((isset($_GET["lang"]))&&($_GET["lang"]!="")){
    $lang=$_GET["lang"];
  }
  if(count($_GET)>1){
    // reload sounds
    if((isset($_GET["action"]))&&($_GET["action"]!="")){
      if($_GET["action"]=="reload"){
        $ret=$asterisk->soundsInit(1);
        goToMainPage("","./");
      }else if($_GET["action"]=="updatereload"){
        // Build lost ambient
        $exec=" <script> xajax_buildTree('".addslashes($_GET["oldLang"])."'); \n";
        $exec.="         xajax_editFile('".addslashes($_GET["oldFilename"])."','".addslashes($_GET["oldCatid"])."','".addslashes($_GET["oldCattag"])."','".addslashes($_GET["oldCategory"])."','".addslashes($_GET["oldLang"])."'); </script> \n";
        $loading=true;
      }
    }
    // refresh after insert
    else if(($_GET["file"]!="")&&($_GET["catid"]!="")&&($_GET["cattag"]!="")&&($_GET["catname"]!="")&&($_GET["lang"]!="")){
      if($_GET["action"]=="insert"){
        $exec=" <script> xajax_buildTree('".addslashes($_GET["lang"])."','".addslashes($_GET["cattag"])."'); ";
        $exec.="         xajax_editFile('".addslashes($_GET["file"])."','".addslashes($_GET["catid"])."','".addslashes($_GET["cattag"])."','".addslashes($_GET["catname"])."','".addslashes($_GET["lang"])."'); </script> \n";
        $loading=true;
      }
      else if($_GET["action"]=="delete"){
        $exec=" <script> xajax_buildTree('".addslashes($_GET["lang"])."','".addslashes($_GET["cattag"])."'); ";
        $exec.="         xajax_showFolder('".addslashes($_GET["catid"])."','".addslashes($_GET["cattag"])."','".addslashes($_GET["catname"])."','".addslashes($_GET["lang"])."'); </script> \n";
        $loading=true;
      }
    }
  }
  else if(count($_FILES)>0){
    // File upload check
    if (!is_uploaded_file($_FILES['uploadedfile']['tmp_name'])) @unlink($_FILES['uploadedfile']['tmp_name']);
    else if(($_POST["oldFilename"]!="")&&($_POST["oldCatid"]!="")&&($_POST["oldCattag"]!="")&&
            ($_POST["oldCategory"]!="")&&($_POST["oldLang"]!="")   ){
      // Check file name
      $file_name=$_FILES['uploadedfile']['name'];
      $new_file_name=$file_name;
      $tmp_id=$asterisk->getCatidByTagname("tmp");
      $tmpfiles=$asterisk->getSoundDesc("", $tmp_id, "");
      $go=false;
      $count=2;
      // Remove Spaces
      $new_file_name=str_replace(" ","_",$new_file_name);
      $new_file_name=str_replace(array("'","\""),"",$new_file_name);
      // Manage duplicate
      while($go!==true){
        $go=true;
        foreach($tmpfiles as $tmpfile){
          if($tmpfile["name"]==substr($new_file_name, 0, -4)) {
            $new_file_name=$count."_".$file_name;
            $new_file_name=str_replace(" ","_",$new_file_name);
            $new_file_name=str_replace(array("'","\""),"",$new_file_name);
            $go=false;
            break;
          }
        }
        $count++;
      }
      // upload file
      $handle = fopen($_FILES['uploadedfile']['tmp_name'],"rb");
      $file_content = fread($handle,filesize($_FILES['uploadedfile']['tmp_name']));
      $ret=$asterisk->uploadMessage($new_file_name, $file_content);
      // write db
      if($ret==1) $ret=$asterisk->putTempSound(substr($new_file_name, 0, -4));
      // reload page
      goToMainPage($alert,"./?action=updatereload&oldLang=".$_POST["oldLang"]."&oldFilename=".$_POST["oldFilename"]."&oldCatid=".$_POST["oldCatid"]."&oldCattag=".$_POST["oldCattag"]."&oldCategory=".$_POST["oldCategory"]);
    }
  }

  //================= PAGE LOGIC ==================
  // create language select list
  $ret=$asterisk->getLanguages();
  $htmllang=" <select style=\"float:right\" name=\"language\"   onChange=\"location.href='index.php?lang=' + this.options[this.selectedIndex].value;\" > \n";
  if(is_array($ret)){
    foreach($ret as $language){
      if($language==$lang) $selected="selected=\"selected\"";
      else $selected="";
      $htmllang.="              <option value=\"$language\" $selected>$language</option>  \n";
    }
  }
  $htmllang.=" </select>  \n";
  // print exec script
  if($exec=="") $exec=" <script> xajax_buildTree('".addslashes($lang)."'); </script> \n";
  // define main content
  if($loading===true){
    $main="  <table class=\"todolist\"><tr>";
    $main.="   <td><img src=\"".$relBasePath."public/img/ico-progress.gif"."\" alt=\"loading\" /></td>";
    $main.="   <td><p>".T_("loading...")."</p></td>";
    $main.=" </tr></table>";
  }
  else {
    $main="  <div class=\"SectionHeader\"> ";
    $main.="   <h1>".T_("Sounds")."</h1> ";
    $main.=" </div> ";
    $main.=" <table class=\"todolist\"> ";
    $main.="   <tr>".T_("Choose a node to modify from the tree on the right")."</tr> ";
    $main.=" </table> ";
  }
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../admin/lib/xajax/"); ?>
  <?=$exec?>
  <div id="error"></div>

  <div id="main">
    <?=$main?>
  </div>

  <script>
    function showFolder(cat_id, cat_tag, category, lng){
      location.href='#';
      xajax_showFolder(cat_id, cat_tag, category, lng);
    }
    function editFile(filename, cat_id, cat_tag, category, lng){
      location.href='#';
      xajax_editFile(filename, cat_id, cat_tag, category, lng);
    }
    function recordMessage(){
      var selectedIndex=document.getElementById("clientsList").selectedIndex;
      var client_id=document.getElementById("clientsList").options[selectedIndex].value;
      var messagename = prompt('<?=addslashes(T_("Enter message name:"))?>');
      while(messagename=='') messagename = prompt('<?=addslashes(T_("Enter message name:"))?>');
      objSelect=document.getElementById("fileList");
      for (var i=0; i<objSelect.childNodes.length; i++) {
        currObj=objSelect.childNodes[i];
        if(currObj.tagName=="OPTION")
          if(messagename==currObj.value)
            if(!(confirm('File "' + messagename + '" <?=addslashes(T_("already exist: override it?"))?>'))) messagename=null;
      }
      if(messagename!=null) xajax_recordMessage(client_id, messagename);
    }
    function deleteTempMessage(){
      var selectedIndex=document.getElementById("fileList").selectedIndex;
      var messagename=document.getElementById("fileList").options[selectedIndex].value;
      if(confirm('<?=addslashes(T_("Are you sure to delete"))?> "' + messagename + '" ?')){
        document.getElementById('selected').value=null;
        xajax_deleteTempMessage(messagename);
      }
    }
    function save(oldname, cat_id, cat_tag, cat_name, lng){
      var oldtext=document.getElementById("oldText").value;
      var newname=document.getElementById("selected").value;
      var newtext=document.getElementById("desctext").value;
      // check name
      var check=false;
      objSelect=document.getElementById("fileList");
      for (var i=0; i<objSelect.childNodes.length; i++) {
        currObj=objSelect.childNodes[i];
        if(currObj.tagName=="OPTION")
          if(newname==currObj.value) check=true;
      }
      if((check==true)||(newname=="")){
        // select field is empty
        if((newname=='')&&(newtext==oldtext)){
          alert('<?=addslashes(T_("Please, select a file from the list to overwrite"))?> "' + oldname + '"');
        }else if((newname=='')&&(newtext!=oldtext)){
          if(confirm('<?=addslashes(T_("Are you sure to change text in\\n"))?> "' + newtext + '" ?')){
            xajax_modify(oldname, cat_id, cat_tag, cat_name, lng, '', 1, newtext);
          }
        }
        // select field is populated
        else if((newname!='')&&(newtext==oldtext)){
          if(confirm('<?=addslashes(T_("Are you sure to change content to"))?> "' + newname + '" ?')){
            xajax_modify(oldname, cat_id, cat_tag, cat_name, lng, newname, 0, '');
          }
        }else if((newname!='')&&(newtext!=oldtext)){
          if(confirm('<?=addslashes(T_("Are you sure to change content to"))?> "' + newname + '" ,\n <?=addslashes(T_("and text to"))?> "' + newtext + '" ?')){
            xajax_modify(oldname, cat_id, cat_tag, cat_name, lng, newname, 1, newtext);
          }
        }
      }
      else alert('<?=addslashes(T_("Unknown message"))?> "' + newname + '"\n<?=addslashes(T_("Please, select a file from the list to overwrite"))?> "' + oldname + '"');
    }
    function newFile(cat_id, cat_tag, cat_name, lng){
      var messagename = '';
      while(messagename=='') messagename = prompt('<?=addslashes(T_("Enter message name:"))?>');
      if(messagename!=null) xajax_saveEmptyMessage(messagename, cat_id, cat_tag, cat_name, lng);
    }
    function deleteFile(messagename, cat_id, cat_tag, cat_name, lng){
      if(confirm('<?=addslashes(T_("Are you sure to delete"))?> "' + messagename + '" ?')) xajax_deleteMessage(messagename, cat_id, cat_tag, cat_name, lng);
    }
  </script>

  <?
  $contents=ob_get_contents();
  ob_end_clean();
  //=================== SIDEBAR ====================
  ob_start();
  ?>
  <div class="Sidebar">
    <h1><?=T_("Informations")?></h1>
    <p><?=T_("This page allows you to manage sounds used by the system. The sounds are divided by language and, in every language, in categories. Adding new sounds is permitted only for 'custom' and 'IVR' categories, but you can modify every sound in the tree below uploading a new content and overwriteing the existing one.")?></p> 
    <h1><?=T_("Asterisk sound files")?></h1><br />
  </div>
  
  <!-- Tree -->
  <div id="basic_form">
    <?=$htmllang?>
    <div id="tree"></div><br />
  </div>

  <!-- Reload -->
  <div align="right">
    <form action="<?=$PHP_SELF?>" method="get" onSubmit="">
      <input type="hidden" name="action" value="reload" />
      <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-rebuild.gif" alt="reload" />
    </form>
  </div>

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