<?
/**
 * VoiceOne Settings/System/CLI
 *
 * Frontend to provide access to the backup
 * @package voiceone
 * @subpackage  settings_system_backup
 */
 
  include ("../../../admin/config/cfg.php");
  global $cwlang, $cwLanguage;
  require_once("$absBasePath/lib/xajax/xajax.inc.php");
  
  //================ XAJAX ================
  function processFormCreate($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    //extract form params
    $label=trim($formData["label"]);
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">";
    // Check label ((not null)&&(alphanumeric))
    $labelErr=false;
    if($label==""){
      //label cannot be null
      $errOut[]= T_("Label cannot be null");
      $objResponse->addAssign("labelErr","innerHTML",$imgErr);
      $labelErr=true;
    }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)) )){
          $errOut[]= T_("Label allow only alphanumeric characters. Please change it");
          $objResponse->addAssign("labelErr","innerHTML",$imgErr);
          $labelErr=true;
          break;
        }
      }
    }
    if($labelErr===false) $objResponse->addAssign("labelErr","innerHTML","");
    // Process Form
    if(isset($errOut)){
      $error="<div class=\"AlertBad\"><ul>";
      foreach($errOut as $err) $error.="<li>".$err."</li>";
      $error.="</ul></div>";
      $objResponse->addAssign("alert","innerHTML",$error);
      $objResponse->addAssign("loading","innerHTML","");
    }else{
      $objResponse->addAssign("loading","innerHTML","");
      $objResponse->addScript(" document.getElementById('form_create').submit(); ");
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();
  }
  function processFormUpload($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    //extract form params
    $file=trim($formData["upload"]);
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">";
    // Check File (not null)
    $fileErr=false;
    if($file==""){
      //file cannot be null
      $errOut[]= T_("Select backup file to upload");
      $objResponse->addAssign("fileErr","innerHTML",$imgErr);
      $fileErr=true;
  	}
    if($fileErr===false) $objResponse->addAssign("fileErr","innerHTML","");
    // Process Form
    if(isset($errOut)){
      $error="<div class=\"AlertBad\"><ul>";
      foreach($errOut as $err) $error.="<li>".$err."</li>";
      $error.="</ul></div>";
      $objResponse->addAssign("alert","innerHTML",$error);
      $objResponse->addAssign("loading","innerHTML","");
    }else{
      $objResponse->addAssign("loading","innerHTML","");
      $objResponse->addScript(" document.getElementById('form_upload').submit(); ");
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();
  }
  $xajax = new xajax();
  $xajax->registerFunction("processFormCreate");
  $xajax->registerFunction("processFormUpload");
  $xajax->processRequests();
  
  //================= POST & GET ==================
  $alert=getAlert();
  //DELETE Backup
  if((isset($_GET["del"]))&&(trim($_GET["del"])!="")){
    $ret=$asterisk->delBackup($_GET["del"]);
    if($ret>0) $alert="<div class=\"AlertGood\">".T_("Backup has been deleted")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("Backup hasn't been deleted")."</div>";
    //go to main page
    goToMainPage($alert,"./");
  }
  //RESTORE Backup
  if((isset($_GET["restore"]))&&(trim($_GET["restore"])!="")){
    $ret=$asterisk->restoreBackup($_GET["restore"]);
    if($ret>0) $alert="<div class=\"AlertGood\">".T_("Backup has been restored")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("Backup hasn't been restored")."</div>";
    unset($_SESSION["voiceone_release"]);
    unset($_SESSION["voiceone_version"]);
    //go to main page
    goToMainPage($alert,"./");
  }
  //CREATE Backup
  if((isset($_POST["label"]))&&(trim($_POST["label"])!="")){
  	$ret=$asterisk->createBackup($_POST["label"]);
    if($ret>0) $alert="<div class=\"AlertGood\">".T_("Backup has been created")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("Backup hasn't been created")."</div>";
    //go to main page
    goToMainPage($alert,"./");
  }
  //UPLOAD Backup
	if((isset($_FILES["upload"]))&&(is_array($_FILES["upload"]))){
    $file=$_FILES["upload"];
    if($file["error"]==0){
    	if(substr(trim($file["name"]),-7)==".tar.gz"){
				$name=substr(trim($file["name"]),0,-7);
        $is_alphanumeric=true;
        for($i=0;$i<strlen($name);$i++){
          $ch=ord($name[$i]);
          if(!( (($ch>47)&&($ch<58))||(($ch>64)&&($ch<91))||(($ch>96)&&($ch<123))||($ch==45) )){
            $is_alphanumeric=false;
            break;
          }
        }
        if((trim($name)!="")&&($is_alphanumeric)){
       		$ret=$asterisk->getBackup($file["name"]);
          if(count($ret)==0){
            //upload file
            $handle=fopen($file['tmp_name'],"rb");
            $file_content=fread($handle,filesize($file['tmp_name']));
            $ret=$asterisk->uploadBackup($file["name"],$file_content);
            //return message
            if($ret>0) $alert="<div class=\"AlertGood\">".T_("Backup has been uploaded")."</div>";
  					else $alert="<div class=\"AlertBad\">".T_("Unable to tranfer backup to the server")."</div>";
        	}else $alert="<div class=\"AlertBad\">".T_("Backup file already exsists")."</div>";
        }else $alert="<div class=\"AlertBad\">".T_("Invalid name of file")."</div>";
      }else $alert="<div class=\"AlertBad\">".T_("Invalid type of file")."</div>";
    }else $alert="<div class=\"AlertBad\">".T_("Backup hasn't been uploaded")."</div>";
    //go to main page
    goToMainPage($alert,"./?rnd=".rand(0,99999));
  }
  //================= PAGE LOGIC ==================
  $html="";
  $ret=$asterisk->getBackup("");
  if((is_array($ret))&&(count($ret)>0)){
    foreach($ret as $v){
    	$name=$v["name"];
    	$label=$v["label"];
      $revision=$v["revision"];
    	$size=$v["size"];
      $date=$v["date"];
      $html.="<tr>\n";
      $html.="	<td width=\"25%\" class=\"first\">".date("d-m-Y H:i:s",$date)."</td>\n";
      $html.="	<td width=\"17%\">".$revision."</td>\n";
      $html.="	<td width=\"17%\">".$label."</td>\n";
      $html.="	<td width=\"17%\">".$size." Kb</td>\n";
      $html.="	<td><a title=\"download ".$label."\"href=\"stream.php?label=".$label."&filename=".$name."\"><img src=\"$relBasePath/public/img/download.gif\" /></a></td>\n";
      $html.="	<td><a title=\"restore ".$label."\" href=\"$PHP_SELF?restore=".$name."\" onclick=\"if (confirm('".sprintf(T_("Are you sure you want to restore backup %1\$s"),$label )."')) return true; else return false;\"><img src=\"$relBasePath/public/img/continue.gif\" /></a></td>\n";
      $html.="	<td><a title=\"delete ".$label."\" href=\"$PHP_SELF?del=".$name."\" onclick=\"if (confirm('".sprintf(T_("Are you sure you want to remove backup %1\$s"),$label )."')) return true; else return false;\"><img src=\"$relBasePath/public/img/trash.gif\" /></a></td>\n";
      $html.="</tr>\n";
    }
  }else{ 
    $html="<tr><td class=\"first\" align=\"center\" colspan=\"7\"><span style=\"font-size: 10px;\">".T_("There are no stored backups")."</span></td></tr>\n"; 
  }
  //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();
  $xajax->printJavascript("../../../admin/lib/xajax/");
  ?>
    <?$sel="backup";include("../navigation.php");?>
    <div class="SectionHeader">
      <?=$alert?>
      <h1><?=T_("Backup")?></h1>
    </div>
    <div id="alert"></div>
    <div id="basic_form">  
      <table style="margin-bottom:20px;" cellpadding="0" cellspacing="0" width="100%">
      	<tr>
        	<td valign="top">
          	<!-- Create -->
          	<form id="form_create" action="<?=$PHP_SELF?>" method="post">
            	<h2 style="margin:0;padding:0;"><?=T_("Create New Backup")?></h2>
              <div class="block">
              	<dl>
                	<dt class="required" style="width:60px;">
                  	<span id="labelErr"></span>
                    <label for="label"><?=T_("Label")?>:</label>
                  </dt>
                  <dd>
                		<input type="text" name="label" id="label" value=""/>&nbsp;&nbsp;
                		<input type="image" title="<?=T_("Create New Backup")?>" alt="<?=T_("Create New Backup")?>" src="<?=$relBasePath?>/public/img/add.gif" onclick="document.getElementById('alert').innerHTML=''; xajax_processFormCreate(xajax.getFormValues('form_create')); return false;"/>
                    <div>&nbsp;</div>   
                  </dd>
                </dl>
              </div>
            </form>
          </td>
          <td>
        		<!-- Upload -->
          	<form id="form_upload" action="<?=$PHP_SELF?>" method="post" enctype="multipart/form-data">
            	<h2 style="margin:0;padding:0;"><?=T_("Import Backup Archive")?></h2>
              <div class="block">
              	<dl>
                	<dt class="required" style="width:60px;">
                  	<span id="fileErr"></span>
                    <label for="label"><?=T_("File")?>:</label>
                  </dt>
                  <dd>
                		<input type="file" name="upload" id="upload" value=""/>&nbsp;&nbsp;
                		<input type="image" title="<?=T_("Upload File")?>" alt="<?=T_("Upload File")?>" src="<?=$relBasePath?>/public/img/add.gif" onclick="document.getElementById('alert').innerHTML=''; xajax_processFormUpload(xajax.getFormValues('form_upload')); return false;"/>
                    <div style="margin-left:70px;">(<?=T_("upload limit")?>: <?=byte_converter($uploadlimit)?>)</div>
                  </dd>
                </dl>
              </div>
            </form>
          </td>
        </tr>
      </table>
    </div>
    <table id="ext_table" cellpadding="0" cellspacing="0" width="100%">
  		<tr>
        <th class="first bordered"><?=T_("Date")?></th>
        <th class="bordered"><?=T_("Release")?></th>
        <th class="bordered"><?=T_("Label")?></th>
        <th class="bordered"><?=T_("Size")?></th>
        <th class="small bordered" width="10%"><?=T_("Download")?></th>
        <th class="small bordered" width="10%"><?=T_("Restore")?></th>
        <th class="small bordered" width="10%"><?=T_("Delete")?></th>
      </tr>
      <?=$html?>
    </table>
  <?
  $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 system backups. VoiceOne backup saves system configuration, sounds file of IVR and custom categories and registered g729 licences. Backup don't save mousic on hold files, sounds of categories different to IVR and custom, voicemail messages and call detail report. In this page you can create a new backup for the runtime configuration, upload a previously exported backup or manage existing backups.")?></p>
    </div>         
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();
  //================ SETTINGS ================
  $smarty->assign("section", "system");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->display('settings.tpl');
?>