<?
/**
 * VoiceOne Webservices Methods
 *  
 * @package voiceone_webservices
 * @subpackage Backup
 */
//******************************************************************************
//******************           PUBLIC FUNCTIONS            *********************
//******************************************************************************
/**
* FUNCTION: getBackup
* Get backup database entry created on the system that match to id. If no id is passed
* to the function, it returns all backup entry.
* @param filename:string -> Name of the backup file to retireve info, all if empty
* @return:BackupArray -> Array of structure contains entities data
*/
function getBackup($filename){
	global $voiceoneWSDocumentRoot;
	//get all backup files
  $ret=array();
  $sandboxDir=$voiceoneWSDocumentRoot."/sandbox";
  $dh=opendir($sandboxDir);
  while(false!==($document=readdir($dh))){
  	//skip folders and files that aren't *.tar.gz
    if($document=="." or $document==".." or is_dir($folderPath."/".$document)===true) continue;
    if(substr($document,-7)!=".tar.gz") continue;
    if((trim($filename)!="")&&($document!=$filename)) continue;
    //get file info
    $info=stat($sandboxDir."/".$document);
    $size=round($info["size"]/1024);
    if(($info["size"]>0)&&($size==0)) $size=1;
    if(strpos($document,"-")!==false){
      $revision=substr($document,0,strpos($document,"-"));
      $label=substr($document,(strpos($document,"-")+1),-7);
    }else{
      $revision="";
      $label=substr($document,0,-7);
    }
    $file[intval($info["mtime"])]=array(
        "revision"  => $revision,
    		"filename" 	=> $document,
        "label" 		=> $label,
      	"size" 			=> $size
      );
  }
  //create return structure
 	if(is_array($file)){
    krsort($file);
    foreach($file as $k=>$v){
      $ret[]=array(
      		"name" 	=> $v["filename"],
          "label" => $v["label"],
          "revision" => $v["revision"],
      		"date" 	=> $k,
      		"size" 	=> $v["size"]
      	);
    }
  }
  //return structure
  return $ret;
}
/**
* FUNCTION: createBackup
* Create a new backup of voiceone configuration
* @param label:string -> backup's label
* @return:int -> If success method returns 1, else it returns zero
*/
function createBackup($label){
	global $db,$voTools,$voiceoneWSDocumentRoot,$synDbUser,$synDbPassword,$synDbName;
  //check input values
  $label=trim($label);
  if($label=="") return 0;
  else{
    //label must be alphanumeric
    for($i=0; $i<strlen($label); $i++){
      $ch=ord($label[$i]);
      if(!( (($ch>47)&&($ch<58))||(($ch>64)&&($ch<91))||(($ch>96)&&($ch<123)) )){
        return 0;
      }
    }
  }
  //get revision number
  $revision="150";
  $systemOptionArr=getOptionByName("voiceone_release","SYSTEM");
  if((is_array($systemOptionArr))&&(is_array($systemOptionArr[0]))){
    $revision=$systemOptionArr[0]["value"];
  }
  //define path
  $sandboxDir=$voiceoneWSDocumentRoot."/sandbox";
  //create database dump
  $label=$revision."-".$label;
  exec("sudo $voTools createBackup $sandboxDir $label $synDbUser $synDbPassword $synDbName",$output,$retScript);
  //check creation result
  if(is_file($sandboxDir."/".$label.".tar.gz")){
  	return 1;
  }else{
  	return 0;
  }
}
/**
* FUNCTION: delVirtualExtension
* Delete a Backup entry and the relative files
* @param filename:string -> Name of the backup file to delete
* @return:int -> If success it return 1, else return zero
*/
function delBackup($filename){
	global $voiceoneWSDocumentRoot;
  //define path
  $sandboxDir=$voiceoneWSDocumentRoot."/sandbox";
  //check input values
  if(is_file($sandboxDir."/".$filename)){
  	//delete backup
  	if(@unlink($sandboxDir."/".$filename)===true) return 1;
  }
  return 0;
}
/**
* FUNCTION: restoreBackup
* Restore a backup archive
* @param filename:string -> Name of the backup file to restore
* @return:int -> If success it return 1, else return zero
*/
function restoreBackup($filename){
	 global $db,$voTools,$voiceoneWSDocumentRoot,$synDbUser,$synDbPassword,$synDbName;
  //if asterisk is ON, turn off it
  $status=pbxSwitch("status");
  if($status=="ON"){
    pbxSwitch("stop");
    sleep(2);
    $status=pbxSwitch("status");
    if($status=="ON") return 0;
  }
  //get voiceone version and release
  $systemOptionArr=getOptionByName("voiceone_version","SYSTEM");
  $voiceone_version=$systemOptionArr[0]["value"];
  $systemOptionArr=getOptionByName("voiceone_release","SYSTEM");
  $voiceone_release=$systemOptionArr[0]["value"];
  //define file path
  $sandboxDir=$voiceoneWSDocumentRoot."/sandbox";
  $label=substr(trim($filename),0,-7);
  //check input values
  if(is_file($sandboxDir."/".$filename)){
  	//restore backup
    exec("sudo $voTools restoreBackup $sandboxDir $label $synDbUser $synDbPassword $synDbName",$output,$retScript);
    if(is_file($sandboxDir."/restored.ok")){
    	@unlink($sandboxDir."/restored.ok");
      //update db to actual revision
      $backup_rev=intval(substr($label,0,strpos($label,"-")));
      if($backup_rev==0) $backup_rev=150;
      //insert database upgrade
      $db_dir=$voiceoneWSDocumentRoot."/modules/backup/db";
      if($handle=@opendir($db_dir)) {
        while(false!==($file=@readdir($handle))){
          if(($file!=".")&&($file!="..")&&($file!="dump.sql")){
          	$file_rev=intval(substr($file,0,strpos($file,"-")));
            if($file_rev > $backup_rev){
              $filePath=$db_dir."/".$file;
              exec("cat $filePath | mysql --user=$synDbUser --password=$synDbPassword --host=$synDbHost $synDbName",$out);
            }
          }
        }
        closedir($handle);
      }
      //init sounds
    	$ret=soundsInit(1);
      if($ret==0) return 0;
      //write zapata conf file
      if(function_exists("writeZaptelInitConfFile")){
        writeZaptelInitConfFile();
      }
      //write mISDN conf file
      if(function_exists("writeMisdnConfFile")){
        writeMisdnConfFile();
      }
      //refresh asterisk-stat users
      if(function_exists(ast_writeStatUsers)){
        ast_writeStatUsers();
      }
      //refresh LDAP data
      if(function_exists("initLdapService")){
        initLdapService();
      }
      //refresh FAX data
      if(function_exists("initFaxService")){
        initFaxService();
      }
      //write net conf and reload configuration
      if(function_exists("writeSmtpConf")){
        $ret=writeSmtpConf(true);
        if($ret==0) return 0;
      }
      if(function_exists("writeNetConf")){
    	  $ret=writeNetConf(true);
        if($ret==0) return 0;
      }
      //restore voiceone version and release
      $db->Execute("UPDATE cw_option SET value = '".$voiceone_version."' WHERE category='SYSTEM' AND name='voiceone_version' LIMIT 1");
      $db->Execute("UPDATE cw_option SET value = '".$voiceone_release."' WHERE category='SYSTEM' AND name='voiceone_release' LIMIT 1");
      //return
    	return 1;
    }
  }
  return 0;
}
/**
* FUNCTION: uploadBackup
* Upload a backup file to voiceone sandbox folder.
* @param file_name:string -> Name of the backup file to retireve data
* @param file_content:base64Binary -> backup file's binary stream
* @return:int -> If success it return 1, else return zero
*/
function uploadBackup($file_name,$file_content){
	global $voTools, $voiceoneWSDocumentRoot;
  // open file, if file doesn't exist crete it
  $filepath=$voiceoneWSDocumentRoot."/sandbox/".$file_name;
  $filehandle = fopen($filepath, 'w');
  // if web service is emulated the file_content have to be decoded
  if($soapWrapper===true){
    $file_content=base64_decode($file_content);
  }
  // write temp file
  if(@fwrite($filehandle, $file_content)>0){
    if(@fclose($filehandle)===true){
    	return 1;
    }else{
  		return 0;
    }
  }else{
    @fclose($filehandle);
 		return 0;
  }
}
//******************************************************************************
//*****************           PRIVATE FUNCTIONS            *********************
//******************************************************************************
?>