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 = ""; $imgNovo = "$imgNovo"; $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 = ""; $imgDelete = "" . $imgDelete . ""; $imgDelete = sprintf($imgDelete, $idProg, $regId, $regDescricao, FORM_DELETE, $nomeRegId); } else { $titleErro = $regErro ? 'Erro ao realizar Backup! Erro: ' . $dados["bkp_log"] : "Backup Excluido: $regDescricao"; $imgDelete = ""; } $msgExclui = ($regExluido || $regErro) ? (($status == 4) ? "Backup excluido por ter expirado o tempo!" : $dados["bkp_log"]) : ''; $status = GetStatusMonitorBkp($status, $msgExclui); $imgDownload = ""; $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 : ""; //Id Nome Protocolo Host Port Diretório (idProg, id, param) /* * Componha a linha de retorno de acordo om sua consulta */ $linhas .= " $regId $regDescricao $destino $arquivo $tamanho $data $hora $tipo $status $imgDownload $imgDelete "; } if (!$linhas) { $linhas .= " Nenhum $nomeProg encontrado! $imgNovo"; } } 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 = ""; } else { if (($status == 2) || ($status == 3) || ($status == 4)) { if (!$msg) { $msg = ($status == 4) ? "Backup excluído por tempo!" : "Backup excluido pelo usuário!"; } $img = ""; } else { if (empty($msg)) { $msg = "Erro ao raalizar o Backup!"; } $img = ""; } } 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 = ""; $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 .= ""; } return $item; } ?>