<?
/**
 * VoiceOne Webservices Interface
 *
 * @package voiceone_webservices
 * @subpackage  moh
 */ 

//******************************************************************************
//******************             MUSIC ON HOLD             *********************
//******************************************************************************

/**
 * Get params of music on hold classes.
 *
 * @param int $classname the name of the class (if null get all classes)
 * @return array $ret tns:MohClassesStructureArray with description of moh classes
 * @see createMohClass
 * @see modifyMohClass
 * @see delMohClass
 * @see getMohSongs
 * @see uploadMohSongs
 * @see deleteMohSong
 */
function getMohClass($classname) {
  global $db;
  //extract all classes from db
  if($classname=="") $qry="SELECT `category` , `var_name` , `var_val` FROM `ast_config` WHERE `filename`='musiconhold.conf' AND `category`!='general' ORDER BY `category` ASC";
  else $qry="SELECT `category` , `var_name` , `var_val` FROM `ast_config` WHERE `filename`='musiconhold.conf' AND `category`='".$classname."' ORDER BY `category` ASC";
  $res=$db->Execute($qry);
  $oldcategory="";
  $i=-1;
  while ($arr=$res->FetchRow()) {
    if($arr["category"] != $oldcategory){
      $i++;
      $ret[$i]["name"]=$arr["category"];
    }
    $oldcategory=$arr["category"];
    if($arr["var_name"] == "application") $ret[$i]["application"]=$arr["var_val"];
    else if($arr["var_name"] == "mode") $ret[$i]["mode"]=$arr["var_val"];
  }
  return $ret;
}

/**
 * Create a new moh class.
 *
 * @param MohClassDefinitionArray $definition setting param and selected songs
 * @return array $ret xsd:int 1 if ok, 0 if not
 * @see getMohClass
 * @see modifyMohClass
 * @see delMohClass
 * @see getMohSongs
 * @see uploadMohSongs
 * @see deleteMohSong
 */
function createMohClass($def){
  global $db, $voTools;
  // check class definition 
  if(($def["name"]=="")||($def["mode"]=="")||
     ($def["application"]=="")||(count($def["songs"])<1)) return 0; // incomplete definition 
  for($i=0; $i<strlen($def["name"]) ; $i++) {
    $ch=ord($def["name"][$i]);
    if (!((($ch>96)&&($ch<123))||(($ch>64)&&($ch<91))||(($ch>47)&&($ch<58))||($ch==95))) return 0; //character not permitted
  }
  // check class name
  $classes=getMohClass("");
  if (is_array($classes)){
    foreach($classes as $class){
      if($def["name"]==$class["name"]) return 0; // name duplicated
    }
  }
  // extract class dir from default dir
  exec("sudo $voTools getMohDir",$output,$retScript);
  $dir=$output[0]."/voiceone/".$def["name"];
  // write ast_config
  $category=$def["name"];
  if($def["mode"]=="files") $app_commented=1; else $app_commented=0;
  $res1=putAstConfig('musiconhold.conf', $category, 'mode',         $def["mode"],         "", 0);
  $res2=putAstConfig('musiconhold.conf', $category, 'directory',    $dir,                 "", 0);
  $res3=putAstConfig('musiconhold.conf', $category, 'application',  $def["application"],  "", $app_commented);
  // write songs in folder
  if((res1!==false)&&(res2!==false)&&(res3!==false)){ // insert in ast_config right
    $count=0;
    foreach($def["songs"] as $song){
      $class=$def["name"];
      if($count > 999) $linkname="song".$count;
      else if($count > 99) $linkname="song0".$count;
      else if($count > 9) $linkname="song00".$count;
      else $linkname="song000".$count;
      $songext=substr($song, -4);
      $linkname.=$songext;
      $count++;
      exec("sudo $voTools mohSetSong \"$class\" \"$song\" \"$linkname\" ",$output,$retScript);
    }
    //reload moh
    $ret=sendCommand("moh reload");
    return 1;
  }   
  else return 0;  
}

/**
 * Modify a moh class.
 *
 * @param MohClassDefinitionArray $definition setting param and selected songs
 * @return array $ret xsd:int 1 if ok, 0 if not
 * @see getMohClass
 * @see createMohClass
 * @see delMohClass
 * @see getMohSongs
 * @see uploadMohSongs
 * @see deleteMohSong
 */
function modifyMohClass($def){
  global $db, $voTools;
  // check class definition 
  if(($def["name"]=="")||($def["mode"]=="")||($def["application"]=="")||(count($def["songs"])<1)) return 0; // incomplete definition
  for($i=0; $i<strlen($def["name"]) ; $i++) {
    $ch=ord($def["name"][$i]);
    if (!((($ch>96)&&($ch<123))||(($ch>64)&&($ch<91))||(($ch>47)&&($ch<58))||($ch==95))) return 0; //character not permitted
  }
  // check class existence
  $exist=false;
  $classes=getMohClass("");
  if (is_array($classes)){
    foreach($classes as $class){
      if($def["name"]==$class["name"]) {
        $exist=true; // class exist
        break;
      }
    }
  }
  if($exist===true){
    // delete class
    $classname=$def["name"];
    exec("sudo $voTools mohDelFolder \"$classname\" ",$output,$retScript);
    $res=delAstConfig('musiconhold.conf', $classname);
    if($res!==false){
      // create class
      $ret=createMohClass($def);
      if($ret>0){ 
        //reload moh
  			$ret=sendCommand("moh reload");
        return 1;
      }else return 0; // create go wrong
    }else return 0; // delete go wrong
  }else return 0;  //class don't exist
}
  
/**
 * Delete a music on hold class.
 *
 * @param int $classname the name of the class (default is not deletable)
 * @return array $ret xsd:int 1 if ok, 0 if not
 * @see getMohClass
 * @see createMohClass
 * @see modifyMohClass
 * @see getMohSongs
 * @see uploadMohSongs
 * @see deleteMohSong
 */
function delMohClass($classname) {
  global $db, $voTools;
  if($classname=="default") return 0;
  // delete class folder
  exec("sudo $voTools mohDelFolder \"$classname\" ",$output,$retScript);
  // delete from ast_config
  $res=delAstConfig('musiconhold.conf', $classname);
  if($res!==false){
  	//reload moh
    $ret=sendCommand("moh reload");
    return 1;
  }else return 0;
}

/**
 * Get class songs name.
 *
 * @param string $classname the name of the class (if null get all songs)
 * @return array $ret tns:stringArray with name of moh songs
 * @see getMohClass
 * @see createMohClass
 * @see modifyMohClass
 * @see delMohClass
 * @see uploadMohSongs
 * @see deleteMohSong
 */
function getMohSongs($classname) {
  global $voTools, $voiceoneWSDocumentRoot;
  // Edit a .txt file with songs name
  $topath = $voiceoneWSDocumentRoot."/sandbox";
  $class = "voiceone/".$classname;
  exec("sudo $voTools mohMakeSongsList \"$class\" \"$topath\" ",$output,$retScript);
  // Build response
  $file_list = $topath."/moh/songsList.txt";
  if (is_file($file_list)) {
    $lines = file($file_list);
    foreach($lines as $line){
      // Skip Directory
      if(substr($line,0,1)=='d') continue;
      // Symbolic Link
      else if(substr($line,0,1)=='l'){
        $div1=explode(" -> ",$line);
        //$tmp=ereg(".*/(.*)", $div1[1], $div2); //DEPRECATED IN PHP 5.3
        //$filename=$div2[1];                    //
        if(trim($div1[1])!=''){
          $filename=basename($div1[1]);
        }else $filename='';
      }
      // File
      else if(substr($line,0,1)=='-'){
        //$tmp=ereg(".* (.*)", $line, $div1);   //DEPRECATED IN PHP 5.3
        //$filename=$div1[1];                   //
        $tmp=preg_match("/^.*(\s)(.*)$/i", trim($line), $div1);
        $filename=$div1[2];
      }
      // Skip else
      else continue;
      $ret[]=$filename;
    } 
  }
  return $ret;
}

/**
 * Upload an audio file to asterisk's moh folder.
 *
 * @param string $file_name the name of the audio file
 * @param base64Binary $file_content audio file's binary stream
 * @return array $ret xsd:int 1 if ok, 0 if not
 * @see getMohClass
 * @see createMohClass
 * @see modifyMohClass
 * @see delMohClass
 * @see getMohSongs
 * @see deleteMohSong
 */
function uploadMohSongs($file_name, $file_content) {
  global $voTools, $voiceoneWSDocumentRoot;
	// replace spaces with underscore " " --> "_"
	while(strstr($file_name," ")) $file_name=str_replace(" ","_",$file_name);
  $filepath=$voiceoneWSDocumentRoot."/sandbox/";
  $file_temp_name = "testFile.txt";
  // if web service is emulated the file_content have to be decoded
  if($soapWrapper===true){
    $file_content=base64_decode($file_content);
  }
  // open file, if file doesn't exist crete it 
  $filehandle = fopen($filepath.$file_temp_name, 'w');
  // write temp file
  if(fwrite($filehandle, $file_content)>0){
    if(fclose($filehandle)===true) {
      // move file to moh folder
      $frompath=$filepath.$file_temp_name;
      exec("sudo $voTools mohMoveSong \"$frompath\" \"$file_name\" ",$output,$retScript);
      if(@unlink($filepath.$file_temp_name)===false) return 0;
      else return 1;
    }
    else return 0;
  }
  else {
    fclose($filehandle);
    return 0;
  }
}

/**
 * Delete an audio file from asterisk's moh folder.
 *
 * @param string $file_name the name of the audio file to delete
 * @return array $ret xsd:int 1 if ok, 0 if not
 * @see getMohClass
 * @see createMohClass
 * @see modifyMohClass
 * @see delMohClass
 * @see getMohSongs
 * @see uploadMohSongs
 */
function deleteMohSong($file_name) {
  global $voTools, $voiceoneWSDocumentRoot;
  //remove file and links
  exec("sudo $voTools mohDelSong \"$file_name\" ",$output,$retScript);
  //reload moh
  $ret=sendCommand("moh reload");
  return 1;
}