PABX da Simples IP
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

358 lines
13 KiB

<?php
/*
* Apresenta mensagens ao cliente.
*/
$msg = 'Monitor do Backup';
/*
* Indica que será apresentda uma mensagem de erro.
*/
$erro = 0;
/*
* Template para conslta
*/
$nomeTpl = "cadastros/backup/bkpMonitor.htm";
/*
* Indique o nome do sistema, este nome será usado para compor mensagens ao usuários.ex:
* $nomeProg = "Cliente";
* $msg = "Não foi possível excuir o $nomeProg selecionado!";
*/
$nomeProg = "\"Registro\"";
/*
* Indique o nome do campo que representa a chave primaria na tabela ou outro uniquekey que possa
* ser usado para editar um excluir um registro.
*/
$nomeRegId = 'bkp_id';
/*
* Informe o id do script que será chamadado para insserção e edicao de dados.
*/
$idProgEdit = 0;
/*
* Informe um nome para janela de edição
*/
$nomeJanEdit = 'jnMonitorBkp';
/*
* Tamanho das janelas de edição
*/
$janW = 600;
$janH = 340;
$colspan = 12;
/*
* Ações
* FORM_UNDEF = 0 -> Quando a consulta é chamada.
* FORM_SELECT = 1 -> Indica que será selecionado um registro.
* FORM_INSERT = 3 -> Insere um novo registro.
* FORM_UPDATE = 4 -> Atualiza um registro existente.
* FORM_DELETE = 6 -> Apaga um registro.
*/
$acaoUser = isset($_REQUEST['acaoUser']) ? $_REQUEST['acaoUser'] : FORM_UNDEF;
$mostraExcluido = isset($_REQUEST['mostraExcluido']) ? 1 : 0;
$data = new CalcDataHora();
$data->somaDia(-7);
$dataIni = trim($data->getData());
$data = null;
$dataIni = isset($_REQUEST['dataIni']) ? $_REQUEST['dataIni'] : $dataIni;
$dataFim = isset($_REQUEST['dataFim']) ? $_REQUEST['dataFim'] : date('d/m/Y');
$bkp_id = isset($_REQUEST['lstBkp']) ? $_REQUEST['lstBkp'] : '-1';
try {
$result = is_date($dataIni);
if (!$result) {
$erro++;
throw new Exception("Data inicial inválida!");
}
$result = is_date($dataFim);
if (!$result) {
$erro++;
throw new Exception("Data final inválida!");
}
if ($acaoUser == FORM_DOWNLOAD) {
$statusDownload = DownloadBkp($dbcon);
if ($statusDownload) {
exit;
}
}
if ($acaoUser == FORM_DELETE) {
ApagaBkp($dbcon);
if (IsAjax()) {
exit;
}
}
/*
* Captura parametros de conslta
*/
$paramEntrada = $_REQUEST["txtConsulta"];
/*
* Query para Selecionar Registros
*/
$query = "select a.bkp_id, a.cfg_id, a.bkp_data, a.bkp_hora, b.cfg_descricao, c.dst_nome, dst_host, d.prt_descricao, a.bkp_arquivo, a.bkp_tamanho, a.bkp_status, e.frq_descricao,
f.tp_desc, case when(coalesce(a.bkp_log, '') = '')then a.bkp_log_erro else a.bkp_log end as bkp_log
from pbx_backup a, pbx_backup_configuracao b, pbx_backup_destino c, pbx_backup_protocolo d, pbx_backup_frequencia e, pbx_backup_tipo f
where b.cfg_id = a.cfg_id
and c.dst_id = b.dst_id
and d.prt_id = c.prt_id
and e.frq_id = b.frq_id
and f.tp_id = a.tp_id\n";
if ($bkp_id >= 0) {
$query .= "and a.cfg_id = '$bkp_id'\n";
}
if (!$mostraExcluido) {
$query .= "and a.bkp_status in('0', '1')\n";
}
if ($dataIni) {
$data = FormatDtMssql($dataIni);
$query .= "and a.bkp_data >= '$data'\n";
}
if ($dataFim) {
$data = FormatDtMssql($dataFim);
$query .= "and a.bkp_data <= '$data'\n";
}
$query .= "order by a.bkp_id desc";
//if(IsAdmin())echo $query;
$result = pg_query($dbcon, $query);
if (!$result) {
$erro++;
throw new Exception("Erro ao consultar registros!");
}
$imgNovo = "<img src=\"imgSite/novoUser.png\" width=\"16\" height=\"16\" border=\"0\" title=\"Inclui novo registro!\">";
$imgNovo = "<a href=\"javaScript:NovaJanela('index.php?idProg=$idProgEdit&acaoUser=3&$nomeRegId=0', '$nomeJanEdit', '$janW', '$janH', 'resizable=NO,scrollbars=NO');\">$imgNovo</a>";
$linhas = '';
while ($dados = pg_fetch_array($result)) {
/*
* Modifique os valores das chaves do array dados pelos correspondentes retornados da query.
*/
$regId = $dados["bkp_id"];
$regDescricao = $dados["cfg_descricao"];
//$destino = sprintf("%s/%s/%s", $dados["prt_descricao"], $dados["dst_nome"], $dados["dst_host"]);
$destino = $dados["cfg_id"] == 0 ? "Manual" : sprintf("%s [%s]", $dados["dst_nome"], $dados["prt_descricao"]);
$arquivo = $dados["cfg_id"] == 0 ? "Manual" : $dados["bkp_arquivo"];
$tamanho = byteConvert($dados["bkp_tamanho"]);
$data = FormataDBDataHora($dados["bkp_data"]);
$tipo = $dados["tp_desc"];
$hora = $dados["bkp_hora"];
$status = $dados["bkp_status"];
$regExluido = ($status == 2) || ($status == 3) || ($status == 4);
$regErro = ($status == 1) || ($status > 3);
if (!$regExluido) {
$imgDelete = "<img src=\"imgSite/deletaUser.png\" width=\"16\" height=\"16\" border=\"0\" title=\"Apaga o backup: $regDescricao\">";
$imgDelete = "<a href=\"javaScript:DeletaRegistro('%s', '%s', '&regDescricao=%s&acaoUser=%s', '%s');\">" . $imgDelete . "</a>";
$imgDelete = sprintf($imgDelete, $idProg, $regId, $regDescricao, FORM_DELETE, $nomeRegId);
} else {
$titleErro = $regErro ? 'Erro ao realizar Backup! Erro: ' . $dados["bkp_log"] : "Backup Excluido: $regDescricao";
$imgDelete = "<img src=\"imgSite/lock_close_16.png\" width=\"16\" height=\"16\" border=\"0\" title=\"$titleErro\">";
}
$msgExclui = ($regExluido || $regErro) ? (($status == 4) ? "Backup excluido por ter expirado o tempo!" : $dados["bkp_log"]) : '';
$status = GetStatusMonitorBkp($status, $msgExclui);
$imgDownload = "<img src=\"imgSite/download_block_16.png\" width=\"16\" height=\"16\" border=\"0\" title=\"Download Indisponível!\">";
$linkDownload = (strtolower($dados["prt_descricao"]) === 'local' ? "index.php?idProg=223&acaoUser=7&bkp_id=$regId" : "javascript:alert('Download disponível apenas para backups locais')");
$imgDownload = ($regExluido || $regErro || (strtolower($dados["prt_descricao"]) !== 'local')) ? $imgDownload : "<a href=\"{$linkDownload}\"><img src=\"imgSite/download_16.png\" width=\"16\" height=\"16\" border=\"0\" title=\"Download!\"></a>";
//Id Nome Protocolo Host Port Diretório (idProg, id, param)
/*
* Componha a linha de retorno de acordo om sua consulta
*/
$linhas .= "<tr>
<td align=\"right\">$regId</td>
<td align=\"left\">$regDescricao</td>
<td align=\"left\">$destino</td>
<td align=\"left\">$arquivo</td>
<td align=\"right\">$tamanho</td>
<td align=\"center\">$data</td>
<td align=\"center\">$hora</td>
<td align=\"center\">$tipo</td>
<td align=\"center\">$status</td>
<td align=\"center\">$imgDownload</td>
<td align=\"center\">$imgDelete</td>
</tr>";
}
if (!$linhas) {
$linhas .= " <tr><td align=\"center\" colspan=\"$colspan\">Nenhum $nomeProg encontrado! $imgNovo</td></tr>";
}
} catch (Exception $ex) {
$msg = $ex->getMessage();
if (IsAjax()) {
echo $msg;
exit;
}
}
$bkp = GetBkp($dbcon, $bkp_id);
$smarty->assign('erro', $erro);
$smarty->assign('msg', $msg);
$smarty->assign('bkp', $bkp);
$smarty->assign('dataIni', $dataIni);
$smarty->assign('dataFim', $dataFim);
$smarty->assign('mostraExcluido', $mostraExcluido);
$smarty->assign('linhas', $linhas);
GetTemplate($smarty, $nomeTpl);
function byteConvert($bytes) {
$s = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
$e = floor(log($bytes) / log(1024));
return @sprintf('%.2f ' . $s[$e], ($bytes / pow(1024, floor($e))));
}
function GetStatusMonitorBkp($status, $msg = '') {
if (!$status) {
$img = "<img src=\"imgSite/ok16.gif\" width=\"16\" height=\"16\" border=\"0\" title=\"Backup Realizado com sucesso!\">";
} else {
if (($status == 2) || ($status == 3) || ($status == 4)) {
if (!$msg) {
$msg = ($status == 4) ? "Backup excluído por tempo!" : "Backup excluido pelo usuário!";
}
$img = "<img src=\"imgSite/fechaOff16.png\" width=\"16\" height=\"16\" border=\"0\" title=\"$msg\">";
} else {
if (empty($msg)) {
$msg = "Erro ao raalizar o Backup!";
}
$img = "<img src=\"imgSite/no_check.png\" width=\"16\" height=\"16\" border=\"0\" title=\"$msg\">";
}
}
return $img;
}
function DownloadBkp($db) {
global $jsStartup;
$erro = 0;
$bkpId = $_REQUEST["bkp_id"];
$fileInTmp = 0;
$query = "select a.arq_nome, c.cfg_descricao, b.bkp_data, a.arq_size, a.arq_hash
from pbx_backup_arquivos a, pbx_backup b, pbx_backup_configuracao c
where b.bkp_id = a.bkp_id
and c.cfg_id = b.cfg_id
and a.bkp_id = '$bkpId' ";
$result = pg_query($db, $query);
if (!$result) {
$msg = "Erro ao consultar arquivos!";
$erro++;
}
$numArq = pg_num_rows($result);
if (!$numArq) {
$msg = "Arquivo não encontrado!";
$erro++;
}
if ($numArq == 1) {
$dados = pg_fetch_array($result);
$filepath = $dados["arq_nome"];
$fsize = $dados['arq_size'];
$fhash = $dados['arq_hash'];
if ($fhash != hash_file('sha1', $filepath)) {
$msg = "O arquivo não passou na verificação de integridade";
$erro++;
}
} else {
$files = '';
$baseFiles = '';
$filepath = '';
while ($dados = pg_fetch_array($result)) {
$nomeFile = basename($dados["arq_nome"]);
if (!$filepath) {
$filepath = str_replace(' ', '_', strtolower(RemoveAcentos($dados["cfg_descricao"])) . $dados["bkp_data"]);
}
$files .= ' ' . $nomeFile;
if (!$baseFiles) {
$baseFiles = str_replace($nomeFile, '', $dados["arq_nome"]);
}
}
$filepath = sprintf("/tmp/%s.tar.gz", trim($filepath));
$cmd = sprintf("tar -czf %s -C %s %s ", $filepath, $baseFiles, $files);
//echo $cmd; exit;
system($cmd, $ret);
if (!file_exists($filepath)) {
$msg = "Não foi possível gerar o arquivo para download!";
$erro++;
} else {
$fileInTmp = 1;
}
}
if ($erro) {
$jsStartup[] = "alert('$msg');";
} else {
ob_clean();
$file = basename($filepath);
$fsize = filesize($filepath);
header('Content-Description: File Transfer');
header('Content-Transfer-Encoding: binary');
header('Content-Type: ' . GetMimeContentType($file));
if ($fsize) {
header('Content-Length: ' . $fsize);
}
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Connection: close');
readfile($filepath);
if ($fileInTmp) {
@unlink($filepath);
}
}
return ($erro === 0);
}
function ApagaBkp($db) {
$bkpId = $_REQUEST["bkp_id"];
$user = GetLogin();
$data = date('d/m/Y H:i:s');
try {
$query = "update pbx_backup set bkp_status = '2', bkp_log = 'Backup excluido pelo usuário: $user Data: $data' where bkp_id = '$bkpId'";
$result = pg_query($db, $query);
if (!$result) {
throw new Exception("Erro ao apagar Backup!");
}
echo "OK;Backup excluido com sucesso!";
} catch (Exception $ex) {
echo "Erro; " . $ex->getMessage();
}
}
function GetBkp($db, $id) {
if ($id == -1) {
$sel = "selected";
}
$item = "<option value=\"-1\" $sel>------------</option>";
$query = "select cfg_id as id, cfg_descricao as desc from pbx_backup_configuracao a where exists(select '' from pbx_backup where cfg_id = a.cfg_id) order by 2";
$result = @pg_query($db, $query);
$sel = '';
while ($row = pg_fetch_array($result)) {
$spid = $row["id"];
$desc = $row["desc"];
if ($spid == $id) {
$sel = "selected";
} else {
$sel = "";
}
$item .= "<option value=\"$spid\" $sel>$desc</option>";
}
return $item;
}
?>