<?
/**
 * VoiceOne Settings/MOH
 *
 * Frontend to manage music on hold in voiceone.
 * @package voiceone
 * @subpackage  settings_moh
 */
  include ("../../admin/config/cfg.php");
  global $cwlang;
  
  //=============== POST and GET ===============
  $alert=getAlert();  
  //delete a class
  if(count($_GET)>0){
    if (($_GET["cmd"]=="delclass")&&(isset($_GET["name"]))){
      $ret=$asterisk->delMohClass($_GET["name"]);
      if ($ret==1) $alert="<div class=\"AlertGood\">".T_("The class has been deleted")."</div>";
      else $alert="<div class=\"AlertBad\">".T_("The class hasn't been deleted")."</div>";
      goToMainPage($alert,"./");
    }   
  }
  else if(count($_FILES)>0){
    // File upload check
    if (!is_uploaded_file($_FILES['uploadedfile']['tmp_name'])) {
      if($_FILES['uploadedfile']['error']==1) $alert="<div class=\"AlertBad\">".T_("The uploaded file exceeds the max php filesize")."</div>";
      else if($_FILES['uploadedfile']['error']==2) $alert="<div class=\"AlertBad\">".T_("The uploaded file exceeds the max html filesize")."</div>";
      else $alert="<div class=\"AlertBad\">".T_("The file hasn't been uploaded")."</div>";
      unlink($_FILES['uploadedfile']['tmp_name']);  
      goToMainPage($alert,"./");
    } 
    else { // File correctly uploaded
      $songsList=$asterisk->getMohSongs("");
      $file_name=$_FILES['uploadedfile']['name'];
      $new_file_name=$file_name;
      //error_log("Temporary file name: $file_name");
      $go=false;
      $count=2;
      while($go!==true){
        $go=true;
        foreach($songsList as $song){
          $song=substr($song, 0, -1);
          if($song==$new_file_name) {
            $new_file_name=$count."_".$file_name;
            $go=false;
            break;   
          }    
        }
        $count++;
      }
      $handle = fopen($_FILES['uploadedfile']['tmp_name'],"rb");
      $file_content = fread($handle,filesize($_FILES['uploadedfile']['tmp_name']));
      $ret=$asterisk->uploadMohSongs($new_file_name, $file_content);
      if ($ret>0) {$alert="<div class=\"AlertGood\">".T_("The file has been uploaded")."</div>";
      } else $alert="<div class=\"AlertBad\">".T_("The file hasn't been uploaded")."</div>";
      goToMainPage($alert,"./");
    }
  }
  else if(count($_POST)>0){
    //delete a songs list
    if(($_POST["cmd"]=="delsong")&&(is_array($_POST["songsList"]))){
      if(count($_POST["songsList"])==0) goToMainPage("", "./");
      else {
        foreach($_POST["songsList"] as $song){
          $ret=$asterisk->deleteMohSong($song);
          if($ret==0){
            $alert="<div class=\"AlertBad\">".T_("The file hasn't been deleted")."</div>";
            goToMainPage($alert,"./");
          }
        }
        $alert="<div class=\"AlertGood\">".T_("The file has been deleted")."</div>";
        goToMainPage($alert,"./");
      }
    }
  }
  //================ PAGE LOGIC ================
  //create a visual list of classes
  $ret=$asterisk->getMohClass("");
  $count=1;
  if (is_array($ret)){
    foreach($ret as $class){
      $id=$class["id"];
      $name=$class["name"];
      if($name=="default") $html_def.="<td><img src=\"$relBasePath/public/img/music_note.gif\" />$prot <a href=\"edit/?name=$name\">$name</a></td>\n";
      else {
        $html.="<td><img src=\"$relBasePath/public/img/music_note.gif\" />$prot <a href=\"edit/?name=$name\">$name</a> <a href=\"$PHP_SELF?cmd=delclass&name=$name\" onclick=\"if (confirm('".sprintf(T_("Are you sure you want to remove the MOH class : %1\$s"),$name )."')) return true; else return false;\"><img src=\"$relBasePath/public/img/trash.gif\" /></a></td>\n";
        if((++$count)%2==0) $html.="</tr><tr>\n";  
      }
    }
  }
  $html=$html_def.$html;
  //create a visual list of songs
	$tooltip="";$num=0;
  $ret=$asterisk->getMohSongs("");
  if(is_array($ret))
    foreach($ret as $song){
		  $song=trim($song);
		  if(strlen($song)>20) $song_visual="[".strtoupper(substr($song,-3))."] ".substr($song,0,17)."...";
			else $song_visual="[".strtoupper(substr($song,-3))."] ".substr($song,0,-4);
      $songsList.="<option value=\"$song\" onmouseout=\"document.getElementById('tt_id".$num."').style.display='none';\" onmouseover=\"document.getElementById('tt_id".$num."').style.display='block';\">$song_visual</option>";  
			$tooltip.="<span id=\"tt_id".$num."\" style=\"display: none; padding: 3;\">$song</span>\n";
			$num++;
	}
  //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")));
    
  //================ MAIN CONTENTS ================
  ob_start();
  ?>
    <div class="SectionHeader">
      <?=$alert?>
      <h1><?=T_("Music On Hold")?></h1>
      <h3>
        <a href="edit/" class="admin" ><?=T_("New class")?></a> 
      </h3>
    </div>
    <table class="todolist">
      <tr>
        <?=$html?>
      </tr>
    </table>
  <?
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start(); 
  ?>
    <div class="Sidebar">
      <h1><?=T_("Informations")?></h1>
      <p><?=T_("This page shows the MOH (Music On Hold) classes configured on the system. To create a new class follow the link under the section title, otherwise click on an existing class to edit it or on the basket on the right of the name to delete it. The calss 'default' is active for default in all lines and is not possible to remove it. You can upload your own mp3 files using the panel below and add them to classes to reproduce on hold.")?></p>               
      <h1><?=T_("Songs Uploader")?></h1>
      <p><?=T_("Upload and manage your music on hold songs")?></p>
    </div>
		
    <!-- Upload audio files --> 
    <div id="basic_form">
      <div class="block">
        <form action="<?=$PHP_SELF?>" method="post" enctype="multipart/form-data">
          <input type="hidden" name="MAX_FILE_SIZE" value="<?=$uploadlimit?>">          
          <table >
            <tr><td colspan="2"><?=T_("Upload a File")?>:</td></tr>
            <tr>
              <td><input type="file" id="uploadedfile" name="uploadedfile" size="14" value="" /></td>
              <td><input type="image" src="<?=$relBasePath?>/public/img/add.gif" alt="Upload" onclick="return checkUpload()" /></td>  
            </tr>
            <tr><td>(<?=T_("upload limit")?>: <?=byte_converter($uploadlimit)?>)</td></tr>
          </table>
        </form>
        <hr/>
        <form action="<?=$PHP_SELF?>" method="post">
          <input type="hidden" name="cmd" value="delsong">
          <table>
            <tr><td colspan="2"><?=T_("File Library")?>:</td></tr>
            <tr>
              <td style="width: 100%; " ><select multiple style="width: 100%; " size="10"  name="songsList[]" id="songsList"><?=$songsList?></select></td>
              <td><input type="image" src="<?=$relBasePath?>/public/img/trash.gif" alt="Upload" onclick="if (confirm('<?=T_("Are you sure to delete audio file")?>?')) return true; else return false;"></td>
            </tr>
          </table>  
        </form>
      </div> 
    </div>	
		
  <script>
  function checkUpload(){
    var filename = document.getElementById("uploadedfile").value;
    if(filename==""){
      alert('Please insert filepath first');
      return false;
    }
    else return true
  }
  </script>
        
     
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();

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