<?
/*********************** INCLUDES *********************************************/
  $includePath=realpath(dirname(__FILE__).'/../');
  require_once ($includePath.'/config/cfg.php');
  require_once ($includePath.'/lib/phpagi/phpagi.php');
/*********************** INITIALIZATION ***************************************/
  global $voTools;
  $agi = new AGI();

  //extract the filename from the callerid
  $callerid=$agi->get_variable("CALLERID");
  $callerid=preg_match("/[^<]*<([^>]*)>/",$callerid["data"],$result);
  $filename=$result[1];
  
  //extract application name
  $splitted=explode('"',$result[0]);
  $application=$splitted[1];
  if($application=="IVR Audio Recorder") $filepath = $ivrStartingDir;
  else if($application=="VoiceMail Audio Recorder") {
    $filepath = $voicemailStartingDir;
    //extract callee exten
    $channel = $agi->get_variable("CHANNEL");
    //$ret =ereg("/(.*)-", $channel["data"], $exten_arr);  // DEPRECATED IN PHP 5.3
    $ret=preg_match("/(.*)-/", $channel["data"], $exten_arr);
    $exten = $exten_arr[1];
  }
  else if($application=="Sounds Audio Recorder") {
    $filepath = $soundsStartingDir;
    //extract callee exten
    $channel = $agi->get_variable("CHANNEL");
    //$ret =ereg("/(.*)-", $channel["data"], $exten_arr);  // DEPRECATED IN PHP 5.3
    $ret=preg_match("/(.*)-/", $channel["data"], $exten_arr);
    $exten = $exten_arr[1];
  }
  
  //answer the call
  $agi->answer();
   
  //play or record?
  if (substr($filename,-3)=="gsm") {
    $filename=substr($filename,0,-4);
    error_log("FILE TO PLAY: ".$filename);
    $agi->stream_file($filename);    
  } else if ($filename!="")  {
    //$agi->text2wav("You can stop recording by pressing any digit");
    //$agi->text2wav("5-4-3-2-1- Start!");
    //$arr=$agi->record_file (string $file, string $format, [string $escape_digits = ''], [integer $timeout = -1], [integer $offset = NULL], [boolean $beep = false], [integer $silence = NULL])
    $arr=$agi->record_file ($filepath.$filename, "gsm", "0123456789", "30000", null, true);
    //$agi->text2wav('Ok, voice recorded. Thanks, Goodbye');
  } else {
    $agi->text2wav('No file name specified, sorry.');
  }
  
  if($application=="VoiceMail Audio Recorder") {
    //move audio message from asterisk folder to user sandbox
    exec("sudo $voTools transferVoiceMailAnswer $exten $filename",$output,$retScript);
  }
  
  $agi->hangup();
  
?>