api_monitor/vendor/action/log/log_save.php

509 lines
19 KiB
PHP

<?php
/** Carregamento da classe de gerar PDF */
require_once('vendor/library/mpdf/vendor/autoload.php');
/** Importação de classes */
use vendor\model\Log;
use vendor\model\Client;
use vendor\model\Backup;
use vendor\model\Station;
use vendor\model\StationDisk;
use vendor\model\StationFolder;
use vendor\model\Database;
use vendor\controller\log\LogValidate;
try {
/** Instânciamento de classes */
$Log = new Log();
$Client = new Client();
$Backup = new Backup();
$Station = new Station();
$Database = new Database();
$StationDisk = new StationDisk();
$LogValidate = new LogValidate();
$StationFolder = new StationFolder();
/** Parametros de entrada */
$key = isset($_POST['key']) ? (string)filter_input(INPUT_POST, 'key', FILTER_SANITIZE_SPECIAL_CHARS) : '';
$file = isset($_POST['file']) ? (string)filter_input(INPUT_POST, 'file', FILTER_SANITIZE_SPECIAL_CHARS) : '';
$dir = 'rel/';
$header = '';
$body = '';
$i = 0;
$robot = 0;
$color = 0;
$serverName = null;
$urlRel = $_SERVER['HTTP_HOST'];
/** Efetua a verificação dos campos de entrada */
$LogValidate->setKey($key);
$LogValidate->setFile($file);
/** Verifica se não existem erros a serem informados,
* caso não haja erro(s) salvo os dados ou
* efetua o cadastro de um novo*/
/** Verifico a existência de erros */
if (!empty($LogValidate->getErrors())) {
/** Informo */
throw new InvalidArgumentException($LogValidate->getErrors(), 0);
} else {
/** Converte o json em objeto para manipular o mesmo */
$jsonLog = json_decode($LogValidate->getFile());
/** Verifica se o cliente informado existe */
$ClientResult = $Client->GetCns($jsonLog->cns);
/** Caso o cliente não exista, cadastro o mesmo */
if ($ClientResult->client_id == 0) {
/** Caso o cliente não exista, cadastra o novo */
if (!$Client->Save(
null,
$jsonLog->cns,
$jsonLog->cartorio,
null,
null,
null,
null,
null
)) {
/** Informo */
throw new InvalidArgumentException('Não foi possível cadastrar o cartório', 0);
}
}
/** Id do cliente */
$clientId = $ClientResult->client_id > 0 ? $ClientResult->client_id : $Client->getId();
/** Exclui antigas unidades */
$StationDisk->Delete($clientId);
/** Exclui todas as estações de um determinado cliente */
$Station->Delete($clientId);
/** Cadastra a estação novamente */
if (!$Station->Save(
null,
$clientId,
null,
trim($jsonLog->estacao),
null,
null,
null,
null,
null,
null,
null,
null,
1,
trim($jsonLog->server->sistema_operacional),
trim($jsonLog->server->cpu),
trim($jsonLog->server->memory)
)) {
/** Informo */
throw new InvalidArgumentException($Station->getErrors(), 0);
}
/** Id da estação */
$stationId = $Station->getId();
// Percorre cada disco (C:, D:, etc.)
foreach ($jsonLog->disk as $drive => $details) {
// Percorre cada atributo do disco
$i = 0;
foreach ($details as $key => $value) {
if ($i == 0) {
$capacidade = $value;
}
if ($i == 1) {
$utilizados = $value;
}
if ($i == 2) {
$disponivel = $value;
}
if ($i == 3) {
$disponivel_percentual = $value;
}
$i++;
}
/** Grava o novo disco ou atualiza o atual */
if (!$StationDisk->Save(
0,
$clientId,
$stationId,
$drive,
$capacidade,
$utilizados,
$disponivel,
$disponivel_percentual
)) {
/** Informo */
throw new InvalidArgumentException($StationDisk->getErrors(), 0);
}
}
/** Exclui as antigas pastas */
$StationFolder->Delete($stationId);
// Percorre a pasta Ged
foreach ($jsonLog->ged as $path => $details) {
/** Verifica se não é informação da partição */
if($path !== 'partition'){
// Percorre cada atributo da pasta
foreach ($details as $key => $value) {
/** Grava uma nova pasta ou atualiza o atual */
if (!$StationFolder->Save(
0,
$stationId,
$path,
$value,
$value
)) {
/** Informo */
throw new InvalidArgumentException($StationDisk->getErrors(), 0);
}
}
}
}
/** Deleta os dados da partição */
$StationFolder->DeletePartition($clientId);
/** Grava os detalhes da partição GED */
$StationFolder->SavePartition($jsonLog->ged->{'partition'},
$clientId,
$stationId);
/** Exclui os registros anteriores */
$Backup->Delete($clientId, $stationId);
// Percorre a pasta Backup
foreach ($jsonLog->backup as $file => $details) {
// Percorre cada atributo da pasta
$i = 0;
foreach ($details as $key => $value) {
if ($i == 0) {
$fileDate = $Main->DataDB($value);
}
if ($i == 1) {
$fileHour = $value;
}
if ($i == 2) {
$period = $value;
}
if ($i == 3) {
$day = $value;
}
if ($i == 4) {
$size = $value;
}
if ($i == 5) {
$path = $value;
}
$i++;
}
/** Grava o arquivo de backup */
$Backup->Save(
$clientId,
$stationId,
$file,
$fileDate,
$fileHour,
$period,
$day,
$size,
$path
);
}
/** Exclui o registro anterior sobre o banco de dados */
$Database->Delete($clientId);
/** Grava os novos dados do banco de dados */
if(!$Database->Save($clientId,
$jsonLog->database->file_size_mb,
$jsonLog->database->last_modified,
$jsonLog->database->db_accessible,
json_encode($jsonLog->database->partition))){
/** Informo */
throw new InvalidArgumentException('Não foi possível atualizar as informações de banco de dados', 0);
}
/** Exclui o log anterior da estação correspondente */
$Log->Delete($clientId, $stationId);
/** Grava o arquivo de log */
if (!$Log->Save($clientId, $stationId, $LogValidate->getFile())) {
/** Informo */
throw new InvalidArgumentException('Não foi possível cadastrar o arquivo de log', 0);
}
/** Gera o PDF com o resumo do cartório */
/** Aumenta o uso de memória */
ini_set('memory_limit', '512M');
/** Inicio do relatório */
/** Instancia da classe Mpdf */
$mpdf = new \Mpdf\Mpdf([
'mode' => 'utf-8',
'orientation' => 'L'
]);
/** Prepara o cabeçalho */
$header = ' <table width="100%" style="margin:none; font-size:11px; font-family:Arial, Helvetica, sans-serif; border-collapse: collapse">';
$header .= ' <tr>';
$header .= ' <td style="text-align: center; width: 95px"><img src="img/logo2.png" style="max-width:140px; padding: 2px; margin-right:30px"/></td>';
$header .= ' <td colspan="6">';
$header .= ' <h1>' . $ClientResult->name . '</h1>';
$header .= ' </td>';
$header .= ' </tr>';
$header .= ' </table>';
/** Define i cabeçalho do relatório */
$mpdf->SetHTMLHeader($header);
/** Define o rodapé do relatório */
$mpdf->SetHTMLFooter('
<table width="100%">
<tr>
<td width="100%" align="center">{PAGENO}/{nbpg}</td>
</tr>
</table>');
/** Adicionar as margens da página */
$mpdf->AddPageByArray([
'margin-top' => 28
]);
/** Consulta a quantidade de registros */
$StationResult = $Station->All($clientId);
/** Lista as estações do cliente */
foreach ($StationResult as $StationKey => $Result) {
/** Inicio do corpo do relatório */
/** Dados do servidor */
$body .= ' <table width="100%" style="margin:none; font-size:11px; font-family:Arial, Helvetica, sans-serif; border-collapse: collapse;">';
$body .= ' <tr>';
$body .= ' <td colspan="4"><h3>Detalhes Servidor</h3></td>';
$body .= ' <tr/> ';
$body .= ' <tr style="background-color: #333;">';
$body .= ' <td style="color: #FFF; padding: 4px; text-align: center;">DESCRIÇÃO</td>';
$body .= ' <td style="color: #FFF; padding: 4px; text-align: center;">SO</td>';
// $body .= ' <td style="color: #FFF; padding: 4px; text-align: center; width: 90px">CPU</td>';
$body .= ' <td style="color: #FFF; padding: 4px; text-align: center">MEMÓRIA</td>';
$body .= ' </tr>';
$body .= ' <tr style="background-color: #EEEEEE;">';
$body .= ' <td style="text-align: center; width: 33%">' . $Result->description . '</td>';
$body .= ' <td style="text-align: center; width: 33%">' . $Result->operating_system . '</td>';
// $body .= ' <td style="text-align: center; width: 90px">'.htmlspecialchars($Result->cpu).'</td>';
$body .= ' <td style="text-align: center; width: 33%">' . $Result->memory . '</td>';
$body .= ' </tr>';
$body .= ' </table>';
/** Discos */
$body .= ' <table width="100%" style="margin:none; margin-top:40px; font-size:11px; font-family:Arial, Helvetica, sans-serif; border-collapse: collapse;">';
$body .= ' <tr>';
$body .= ' <td colspan="4"><h3>Discos</h3></td>';
$body .= ' <tr/> ';
$body .= ' <tr style="background-color: #333;">';
$body .= ' <td style="color: #FFF; padding: 4px; text-align: center;">DESCRIÇÃO</td>';
$body .= ' <td style="color: #FFF; padding: 4px; text-align: center;">CAPACIDADE</td>';
$body .= ' <td style="color: #FFF; padding: 4px; text-align: center;">UTILIZADOS</td>';
$body .= ' <td style="color: #FFF; padding: 4px; text-align: center">DISPONÍVEL</td>';
$body .= ' <td style="color: #FFF; padding: 4px; text-align: center">DISPONÍVEL %</td>';
$body .= ' </tr>';
/** Consulta a quantidade de registros */
$StationDiskResult = $StationDisk->All($Result->station_id);
/** Lista as estações do cliente */
foreach ($StationDiskResult as $StationDiskKey => $ResultDisk) {
$body .= ' <tr ' . ($i % 2 == 0 ? 'style="background-color: #EEEEEE;"' : '') . '>';
$body .= ' <td width="160" align="center">' . $ResultDisk->description . '</td>';
$body .= ' <td width="160" align="center">' . $ResultDisk->capacity . '</td>';
$body .= ' <td width="160" align="center">' . $ResultDisk->used . '</td>';
$body .= ' <td width="160" align="center">' . $ResultDisk->available . '</td>';
$body .= ' <td width="160" align="center">' . $ResultDisk->available_percentage . '%</td>';
$body .= ' </tr>';
$i++;
}
$body .= ' </table>';
/** Ged */
$body .= ' <table width="100%" style="margin:none; font-size:11px; margin-top:40px; font-family:Arial, Helvetica, sans-serif; border-collapse: collapse;">';
$body .= ' <tr>';
$body .= ' <td colspan="4"><h3>Ged</h3></td>';
$body .= ' <tr/> ';
$body .= ' <tr style="background-color: #333;">';
$body .= ' <td style="color: #FFF; padding: 4px; text-align: center;">ATUALIZADO</td>';
$body .= ' <td style="color: #FFF; padding: 4px; text-align: center;">PATH</td>';
$body .= ' <td style="color: #FFF; padding: 4px; text-align: center;">QTDE</td>';
$body .= ' <td style="color: #FFF; padding: 4px; text-align: center">QTDE ATUAL</td>';
$body .= ' </tr>';
/** Consulta a quantidade de registros */
$StationFolderResult = $StationFolder->All($Result->station_id);
/** Lista as estações do cliente */
foreach ($StationFolderResult as $StationFolderKey => $ResultFolder) {
$body .= ' <tr ' . ($i % 2 == 0 ? 'style="background-color: #EEEEEE;"' : '') . '>';
$body .= ' <td width="160" align="center">' . (!empty($ResultFolder->last_update) ? date('d/m/Y H:i:s', strtotime($ResultFolder->last_update)) : null) . '</td>';
$body .= ' <td width="160">' . $ResultFolder->folder_path . '</td>';
$body .= ' <td width="160" align="center">' . $ResultFolder->amount_of_files . '</td>';
$body .= ' <td width="160" align="center">' . $ResultFolder->amount_of_files_current . '</td>';
$body .= ' </tr>';
$i++;
}
$body .= ' </table>';
/** Backup */
$body .= ' <table width="100%" style="margin:none; font-size:11px; margin-top:40px; font-family:Arial, Helvetica, sans-serif; border-collapse: collapse;">';
$body .= ' <tr>';
$body .= ' <td colspan="4"><h3>Backup</h3></td>';
$body .= ' <tr/> ';
$body .= ' <tr style="background-color: #333;">';
$body .= ' <td style="color: #FFF; padding: 4px; text-align: center;">ARQUIVO</td>';
$body .= ' <td style="color: #FFF; padding: 4px; text-align: center;">DATA</td>';
$body .= ' <td style="color: #FFF; padding: 4px; text-align: center;">HORA</td>';
$body .= ' <td style="color: #FFF; padding: 4px; text-align: center;">DIA</td>';
$body .= ' <td style="color: #FFF; padding: 4px; text-align: center">TAMANHO</td>';
$body .= ' <td style="color: #FFF; padding: 4px; text-align: center">CAMINHO</td>';
$body .= ' </tr>';
/** Consulta a quantidade de registros */
$BackupResult = $Backup->All($Result->client_id, $Result->station_id);
/** Lista as estações do cliente */
foreach ($BackupResult as $BackupKey => $ResultBackup) {
/** Verifica se existe arquivo com arquivo menor que 1kb */
if (strpos($ResultBackup->size, "B") !== false) {
/** Limpa o nome do tamanho do arquivo */
$size = str_replace('B', '', $ResultBackup->size);
$size = str_replace('.', '', $size);
if ((int)$size < 1024) {
$robot++;
$color++;
}
}
$body .= ' <tr style="' . ($color > 0 ? 'background-color: #FFD7AE;' : ($i % 2 == 0 ? 'background-color: #EEEEEE;' : '')) . '">';
$body .= ' <td width="160">' . $ResultBackup->file . '</td>';
$body .= ' <td width="160" align="center">' . date('d/m/Y', strtotime($ResultBackup->file_date)) . '</td>';
$body .= ' <td width="160" align="center">' . date('H:i:s', strtotime($ResultBackup->file_hour)) . '</td>';
$body .= ' <td width="160" align="center">' . $ResultBackup->day . '</td>';
$body .= ' <td width="160" align="center">' . $ResultBackup->size . '</td>';
$body .= ' <td width="160" align="center">' . $ResultBackup->path . '</td>';
$body .= ' </tr>';
$i++;
$color = 0;
}
$body .= ' </table>';
$serverName = $Result->description;
}
/** Acrescenta os dados ao corpo do relatório */
$mpdf->WriteHTML($body);
/** Nome que será dado ao relatório */
$nameFile = $ClientResult->cns . '.pdf';
/** Salva o relatório em uma pasta temporária */
$mpdf->Output($dir . $nameFile);
/** Verifica se o arquivo PDF foi gerado */
if (is_file($dir . $nameFile)) {
/** Verifica se é para enviar a notificação para o Telegram */
if ($robot > 0) {
/** Monta a mensagem de envio */
$message = "(" . $ClientResult->cns . ")" . $ClientResult->name . "\n";
$message .= "Data: " . date('d/m/Y') . "\n";
$message .= "Hora: " . date('H:i:s') . "\n";
$message .= "Estação: " . $Result->description . "\n\n";
$message .= "Para gerenciamento completo, acesse:\n";
$message .= $urlRel."\n\n";
$message .= "Acesse o relatório detalhado no link abaixo:\n";
$message .= $urlRel . $dir . $nameFile . "\n\n";
/** Envia o log para o bot */
$Log->sendMessage($message, $ClientResult->cns);
}
}
}
} catch (Exception $exception) {
/** Preparo o formulario para retorno **/
$result = [
'cod' => 0,
'message' => '<div class="alert alert-danger" role="alert">' . $exception->getMessage() . '</div>',
'title' => 'Atenção',
'type' => 'exception'
];
/** Envio **/
echo json_encode($result);
/** Paro o procedimento **/
exit;
}