mirror of
https://gitlab.com/DanLegoff/mgap.git
synced 2026-11-16 14:12:39 +00:00
316 lines
10 KiB
PHP
316 lines
10 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\Backup;
|
|
use App\Support\BackupRetention;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Artisan;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Str;
|
|
use Inertia\Inertia;
|
|
|
|
class BackupController extends Controller
|
|
{
|
|
public function index()
|
|
{
|
|
$backups = Backup::with('user')
|
|
->orderByDesc('id')
|
|
->paginate(15);
|
|
|
|
$settings = DB::table('backup_settings')->first();
|
|
|
|
$stats = [
|
|
'total' => Backup::count(),
|
|
'completed' => Backup::where('status', 'completed')->count(),
|
|
'failed' => Backup::where('status', 'failed')->count(),
|
|
'total_size' => Backup::where('status', 'completed')->sum('compressed_size'),
|
|
'last_backup' => Backup::where('status', 'completed')
|
|
->latest('id')
|
|
->value('completed_at'),
|
|
];
|
|
|
|
return Inertia::render('Backups/Index', [
|
|
'backups' => $backups,
|
|
'settings' => $settings,
|
|
'stats' => $stats,
|
|
'retention' => config('backup.retention'),
|
|
]);
|
|
}
|
|
|
|
public function store(Request $request)
|
|
{
|
|
$validated = $request->validate([
|
|
'frequency' => ['nullable', 'string', 'in:daily,weekly,monthly,manual'],
|
|
]);
|
|
|
|
$frequency = $validated['frequency'] ?? 'manual';
|
|
|
|
$exitCode = Artisan::call('backup:create', ['--frequency' => $frequency]);
|
|
|
|
$output = Artisan::output();
|
|
|
|
if ($exitCode !== 0) {
|
|
return back()->withErrors(['backup' => 'Error al crear el backup: '.$output]);
|
|
}
|
|
|
|
return back()->with('success', 'Backup creado exitosamente.');
|
|
}
|
|
|
|
public function upload(Request $request)
|
|
{
|
|
$request->validate([
|
|
'file' => 'required|file|mimes:zip|max:102400',
|
|
]);
|
|
|
|
$file = $request->file('file');
|
|
$timestamp = now()->format('Y-m-d_His');
|
|
$filename = "uploaded_{$timestamp}_".Str::uuid().'.zip';
|
|
$destination = storage_path("app/private/backups/{$filename}");
|
|
|
|
$backupDir = storage_path('app/private/backups');
|
|
if (! is_dir($backupDir)) {
|
|
mkdir($backupDir, 0755, true);
|
|
}
|
|
|
|
$file->move($backupDir, $filename);
|
|
|
|
$config = config('backup');
|
|
$listCommand = sprintf(
|
|
'%s l -ba %s 2>&1',
|
|
escapeshellarg($config['seven_zip_path']),
|
|
escapeshellarg($destination)
|
|
);
|
|
exec($listCommand, $output, $exitCode);
|
|
|
|
if ($exitCode !== 0) {
|
|
@unlink($destination);
|
|
|
|
return back()->withErrors(['file' => 'No se pudo abrir el archivo ZIP. Asegúrese de que no esté corrupto y que sea un archivo ZIP válido.']);
|
|
}
|
|
|
|
$hasSql = false;
|
|
foreach ($output as $line) {
|
|
$trimmed = trim($line);
|
|
if (strtolower(pathinfo($trimmed, PATHINFO_EXTENSION)) === 'sql') {
|
|
$hasSql = true;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (! $hasSql) {
|
|
@unlink($destination);
|
|
|
|
return back()->withErrors(['file' => 'El archivo ZIP no contiene ningún archivo .sql.']);
|
|
}
|
|
|
|
Backup::create([
|
|
'filename' => $filename,
|
|
'original_size' => 0,
|
|
'compressed_size' => filesize($destination),
|
|
'status' => 'completed',
|
|
'frequency' => 'manual',
|
|
'created_by' => auth()->id(),
|
|
'started_at' => now(),
|
|
'completed_at' => now(),
|
|
]);
|
|
|
|
BackupRetention::prune($config['retention']);
|
|
|
|
return back()->with('success', 'Backup subido exitosamente.');
|
|
}
|
|
|
|
public function restore(Request $request, Backup $backup)
|
|
{
|
|
$request->validate([
|
|
'confirmation' => 'required|in:RESTAURAR',
|
|
'understood' => 'required|accepted',
|
|
]);
|
|
|
|
if ($backup->status !== 'completed') {
|
|
return back()->withErrors(['restore' => 'Este backup no está completado.']);
|
|
}
|
|
|
|
$config = config('backup');
|
|
$db = $config['database'];
|
|
$password = $config['password'];
|
|
|
|
if (empty($password)) {
|
|
return back()->withErrors(['restore' => 'BACKUP_PASSWORD no está configurada en el .env. Agregá BACKUP_PASSWORD=<clave> y volvé a intentar.']);
|
|
}
|
|
|
|
$zipPath = storage_path("app/private/backups/{$backup->filename}");
|
|
if (! file_exists($zipPath)) {
|
|
return back()->withErrors(['restore' => 'Archivo de backup no encontrado en disco.']);
|
|
}
|
|
|
|
$tempDir = storage_path('app/private/temp_restore_'.Str::uuid());
|
|
mkdir($tempDir, 0755, true);
|
|
|
|
try {
|
|
$safetyFile = $tempDir.'/pre_restore.sql';
|
|
$dumpCommand = sprintf(
|
|
'%s --host=%s --port=%s --user=%s --password=%s --single-transaction --result-file=%s %s 2>&1',
|
|
escapeshellarg($config['mysqldump_path']),
|
|
escapeshellarg($db['host']),
|
|
escapeshellarg($db['port']),
|
|
escapeshellarg($db['username']),
|
|
escapeshellarg($db['password']),
|
|
escapeshellarg($safetyFile),
|
|
escapeshellarg($db['database'])
|
|
);
|
|
exec($dumpCommand, $output, $exitCode);
|
|
|
|
$extractCommand = sprintf(
|
|
'%s x -p%s -o%s -y %s 2>&1',
|
|
escapeshellarg($config['seven_zip_path']),
|
|
escapeshellarg($password),
|
|
escapeshellarg($tempDir),
|
|
escapeshellarg($zipPath)
|
|
);
|
|
exec($extractCommand, $output, $exitCode);
|
|
if ($exitCode !== 0) {
|
|
throw new \RuntimeException('Error al desencriptar el backup: '.implode("\n", $output));
|
|
}
|
|
|
|
$sqlFiles = glob($tempDir.'/*.sql');
|
|
if (empty($sqlFiles)) {
|
|
throw new \RuntimeException('No se encontró archivo .sql en el backup desencriptado.');
|
|
}
|
|
$sqlFile = $sqlFiles[0];
|
|
|
|
DB::unprepared('SET FOREIGN_KEY_CHECKS = 0');
|
|
|
|
$tables = DB::select('SHOW TABLES');
|
|
$dbName = DB::getDatabaseName();
|
|
$tableKey = "Tables_in_{$dbName}";
|
|
|
|
foreach ($tables as $table) {
|
|
$tableName = $table->$tableKey;
|
|
DB::statement("DROP TABLE IF EXISTS `{$tableName}`");
|
|
}
|
|
|
|
DB::unprepared('SET FOREIGN_KEY_CHECKS = 1');
|
|
|
|
$passwordArg = $db['password'] !== '' ? '--password='.escapeshellarg($db['password']) : '--password=""';
|
|
$restoreCommand = sprintf(
|
|
'%s --host=%s --port=%s --user=%s %s %s',
|
|
escapeshellarg($config['mysql_path']),
|
|
escapeshellarg($db['host']),
|
|
escapeshellarg($db['port']),
|
|
escapeshellarg($db['username']),
|
|
$passwordArg,
|
|
escapeshellarg($db['database'])
|
|
);
|
|
|
|
$descriptors = [
|
|
0 => ['pipe', 'r'],
|
|
1 => ['pipe', 'w'],
|
|
2 => ['pipe', 'w'],
|
|
];
|
|
|
|
$process = proc_open($restoreCommand, $descriptors, $pipes);
|
|
|
|
if (! is_resource($process)) {
|
|
throw new \RuntimeException('No se pudo iniciar mysql.exe para la restauración.');
|
|
}
|
|
|
|
fwrite($pipes[0], file_get_contents($sqlFile));
|
|
fclose($pipes[0]);
|
|
|
|
$stdout = stream_get_contents($pipes[1]);
|
|
$stderr = stream_get_contents($pipes[2]);
|
|
fclose($pipes[1]);
|
|
fclose($pipes[2]);
|
|
|
|
$exitCode = proc_close($process);
|
|
|
|
if ($exitCode !== 0) {
|
|
throw new \RuntimeException('Error al restaurar la base de datos: '.($stderr ?: $stdout));
|
|
}
|
|
|
|
$this->cleanupTempDir($tempDir);
|
|
|
|
return back()->with('success', "Base de datos restaurada exitosamente desde: {$backup->filename}");
|
|
|
|
} catch (\Throwable $e) {
|
|
$this->cleanupTempDir($tempDir);
|
|
|
|
return back()->withErrors(['restore' => 'Error durante la restauración: '.$e->getMessage()]);
|
|
}
|
|
}
|
|
|
|
public function download(Backup $backup)
|
|
{
|
|
if ($backup->status !== 'completed') {
|
|
return back()->withErrors(['backup' => 'Este backup no está completado.']);
|
|
}
|
|
|
|
$path = "backups/{$backup->filename}";
|
|
$fullPath = storage_path("app/private/{$path}");
|
|
|
|
if (! file_exists($fullPath)) {
|
|
return back()->withErrors(['backup' => 'Archivo de backup no encontrado en disco.']);
|
|
}
|
|
|
|
return response()->download($fullPath, $backup->filename, [
|
|
'Content-Type' => 'application/zip',
|
|
]);
|
|
}
|
|
|
|
public function destroy(Backup $backup)
|
|
{
|
|
$path = "backups/{$backup->filename}";
|
|
$fullPath = storage_path("app/private/{$path}");
|
|
|
|
if (file_exists($fullPath)) {
|
|
@unlink($fullPath);
|
|
}
|
|
|
|
$backup->delete();
|
|
|
|
return back()->with('success', 'Backup eliminado.');
|
|
}
|
|
|
|
public function updateSettings(Request $request)
|
|
{
|
|
$frequency = $request->input('frequency');
|
|
|
|
$validated = $request->validate([
|
|
'frequency' => 'required|in:daily,weekly,monthly,manual',
|
|
'is_active' => 'required|boolean',
|
|
'run_time' => match ($frequency) {
|
|
'manual' => 'nullable',
|
|
default => 'required|date_format:H:i',
|
|
},
|
|
'run_day' => match ($frequency) {
|
|
'weekly' => 'required|integer|between:0,6',
|
|
'monthly' => 'required|integer|between:1,31',
|
|
default => 'nullable|integer',
|
|
},
|
|
]);
|
|
|
|
DB::table('backup_settings')->update([
|
|
'frequency' => $validated['frequency'],
|
|
'is_active' => $validated['is_active'],
|
|
'run_time' => $validated['run_time'] ?? '02:00',
|
|
'run_day' => $validated['run_day'] ?? null,
|
|
'last_run_at' => null,
|
|
'updated_at' => now(),
|
|
]);
|
|
|
|
return back()->with('success', 'Configuración de backup actualizada.');
|
|
}
|
|
|
|
private function cleanupTempDir(string $dir): void
|
|
{
|
|
$files = glob($dir.'/*');
|
|
foreach ($files as $file) {
|
|
if (is_file($file)) {
|
|
@unlink($file);
|
|
}
|
|
}
|
|
@rmdir($dir);
|
|
}
|
|
}
|