feat(backup): add dedicated .kmh archive reader with zero-storage file inspection and CLI command
This commit is contained in:
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\DatabaseBackupService;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
class InspectKmhBackupCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'kmh:inspect
|
||||
{file? : Nama file .kmh di folder backup atau path absolut ke file .kmh}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = 'Inspeksi dan baca isi metadata file backup .kmh terenkripsi tanpa mengubah database';
|
||||
|
||||
public function handle(DatabaseBackupService $service): int
|
||||
{
|
||||
$input = $this->argument('file');
|
||||
$backupDir = $service->getBackupDirectory();
|
||||
|
||||
if (!$input) {
|
||||
$files = collect(File::glob($backupDir . '/*.kmh'))
|
||||
->map(fn($f) => basename($f))
|
||||
->values()
|
||||
->all();
|
||||
|
||||
if (empty($files)) {
|
||||
$this->warn("Tidak ada file .kmh di direktori backup ({$backupDir}).");
|
||||
$this->line("Gunakan: php artisan kmh:inspect /path/ke/file.kmh");
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$input = $this->choice('Pilih file .kmh yang ingin diinspeksi:', $files);
|
||||
}
|
||||
|
||||
// Tentukan path lengkap
|
||||
$targetPath = File::exists($input)
|
||||
? $input
|
||||
: $backupDir . DIRECTORY_SEPARATOR . basename($input);
|
||||
|
||||
if (!File::exists($targetPath)) {
|
||||
$this->error("Berkas .kmh tidak ditemukan pada: {$targetPath}");
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$this->info("Sedang memeriksa & membaca arsip: " . basename($targetPath) . " ...");
|
||||
|
||||
try {
|
||||
$data = $service->inspectKmhFile($targetPath);
|
||||
|
||||
$this->newLine();
|
||||
$this->line("=====================================================================");
|
||||
$this->info(" 🔍 HASIL INSPEKSI ARSIP KMH (RKM BACKUP READER)");
|
||||
$this->line("=====================================================================");
|
||||
|
||||
$this->table(
|
||||
['Parameter', 'Keterangan'],
|
||||
[
|
||||
['Nama File', $data['filename']],
|
||||
['Ukuran Berkas', $data['file_size_human'] . " ({$data['file_size']} bytes)"],
|
||||
['Format Arsip', $data['format']],
|
||||
['Sistem Asal', $data['system']],
|
||||
['Waktu Pembuatan', $data['created_at_human'] . " ({$data['created_at_diff']})"],
|
||||
['Tipe Backup', $data['type_label']],
|
||||
['Database Asal', $data['database']],
|
||||
['Enkripsi & Keamanan', $data['encryption_cipher'] . ' (' . $data['hmac_verification'] . ')'],
|
||||
['Ukuran SQL Database', $data['sql_size_human']],
|
||||
['File Media (storage/)', $data['has_media'] ? "{$data['media_file_count']} berkas media" : 'Tidak disertakan'],
|
||||
['Versi Environment', "Laravel {$data['laravel_version']} / PHP {$data['php_version']}"],
|
||||
]
|
||||
);
|
||||
|
||||
if (!empty($data['tables'])) {
|
||||
$this->newLine();
|
||||
$this->comment(" Daftar Tabel Terdaftar (" . count($data['tables']) . " tabel):");
|
||||
$chunks = array_chunk($data['tables'], 4);
|
||||
$rows = array_map(function ($chunk) {
|
||||
return array_pad($chunk, 4, '');
|
||||
}, $chunks);
|
||||
$this->table(['Kolom 1', 'Kolom 2', 'Kolom 3', 'Kolom 4'], $rows);
|
||||
}
|
||||
|
||||
if (!empty($data['media_samples'])) {
|
||||
$this->newLine();
|
||||
$this->comment(" Sampel Berkas Media:");
|
||||
foreach ($data['media_samples'] as $sample) {
|
||||
$this->line(" - {$sample}");
|
||||
}
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
$this->info("✓ Berkas sah, terenkripsi valid, dan siap dipulihkan jika diperlukan.");
|
||||
$this->line("=====================================================================");
|
||||
|
||||
return Command::SUCCESS;
|
||||
} catch (\Throwable $e) {
|
||||
$this->error("Gagal membaca arsip .kmh: " . $e->getMessage());
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use App\Http\Controllers\Controller;
|
||||
use App\Models\AdminActivityLog;
|
||||
use App\Models\BackupLog;
|
||||
use App\Services\DatabaseBackupService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
@@ -382,6 +383,75 @@ class BackupController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Inspeksi dan baca metadata isi file .kmh yang sudah ada di penyimpanan server.
|
||||
*/
|
||||
public function inspect(string $filename): JsonResponse
|
||||
{
|
||||
$filename = basename($filename);
|
||||
$fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename;
|
||||
|
||||
if (!File::exists($fullPath)) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => "Berkas backup '{$filename}' tidak ditemukan di penyimpanan server VPS.",
|
||||
], 404);
|
||||
}
|
||||
|
||||
try {
|
||||
$data = $this->backupService->inspectKmhFile($fullPath);
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $data,
|
||||
]);
|
||||
} catch (\Throwable $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => $e->getMessage(),
|
||||
], 422);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Inspeksi dan baca metadata isi file .kmh yang diunggah dari komputer lokal.
|
||||
* File sementara langsung dihapus otomatis setelah dibaca (Zero Storage Retention).
|
||||
*/
|
||||
public function inspectUpload(Request $request): JsonResponse
|
||||
{
|
||||
$request->validate([
|
||||
'backup_file' => ['required', 'file', 'max:512000'],
|
||||
], [
|
||||
'backup_file.required' => 'Pilih atau letakkan berkas file .kmh yang ingin dibaca.',
|
||||
'backup_file.file' => 'Berkas yang diunggah tidak valid.',
|
||||
'backup_file.max' => 'Ukuran file melebihi batas maksimal upload 500 MB.',
|
||||
]);
|
||||
|
||||
$uploaded = $request->file('backup_file');
|
||||
$tempPath = tempnam(sys_get_temp_dir(), 'kmh_upload_inspect_');
|
||||
|
||||
try {
|
||||
$uploaded->move(dirname($tempPath), basename($tempPath));
|
||||
|
||||
$data = $this->backupService->inspectKmhFile($tempPath);
|
||||
// Ganti nama file dengan nama asli dari komputer pengguna
|
||||
$data['filename'] = $uploaded->getClientOriginalName();
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $data,
|
||||
]);
|
||||
} catch (\Throwable $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => $e->getMessage(),
|
||||
], 422);
|
||||
} finally {
|
||||
if (is_file($tempPath)) {
|
||||
@unlink($tempPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hapus file backup dari penyimpanan server untuk menghemat kapasitas disk VPS.
|
||||
* Riwayat log backup tetap tersimpan di sistem.
|
||||
|
||||
@@ -237,6 +237,105 @@ class DatabaseBackupService
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Inspeksi dan baca metadata isi file arsip .kmh tanpa melakukan restore atau manipulasi database.
|
||||
* Mengembalikan manifest, daftar tabel terarsip, metrik data, dan status integritas enkripsi.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function inspectKmhFile(string $filePath): array
|
||||
{
|
||||
@set_time_limit(180);
|
||||
@ini_set('memory_limit', '512M');
|
||||
|
||||
if (!File::exists($filePath)) {
|
||||
throw new RuntimeException("Berkas file backup tidak ditemukan: {$filePath}");
|
||||
}
|
||||
|
||||
$content = file_get_contents($filePath);
|
||||
$headerLen = strlen(self::KMH_MAGIC_HEADER);
|
||||
|
||||
if (substr($content, 0, $headerLen) !== self::KMH_MAGIC_HEADER) {
|
||||
throw new RuntimeException("Berkas bukan format arsip .kmh yang sah atau file rusak (Magic Header tidak cocok).");
|
||||
}
|
||||
|
||||
// Dekripsi payload (verifikasi HMAC & kunci enkripsi)
|
||||
$decryptedZip = $this->decryptFromKmh($content);
|
||||
|
||||
// Buka zip sementara untuk membaca manifest dan statistik file
|
||||
$tempZip = tempnam(sys_get_temp_dir(), 'kmh_inspect_');
|
||||
file_put_contents($tempZip, $decryptedZip);
|
||||
|
||||
try {
|
||||
$zip = new ZipArchive();
|
||||
if ($zip->open($tempZip) !== true) {
|
||||
throw new RuntimeException("Gagal membuka struktur arsip ZIP internal di dalam berkas .kmh.");
|
||||
}
|
||||
|
||||
$manifestJson = $zip->getFromName('manifest.json');
|
||||
$manifest = $manifestJson ? json_decode($manifestJson, true) : [];
|
||||
|
||||
$filesCount = $zip->numFiles;
|
||||
$mediaCount = 0;
|
||||
$sqlSize = 0;
|
||||
$mediaSamples = [];
|
||||
|
||||
for ($i = 0; $i < $filesCount; $i++) {
|
||||
$stat = $zip->statIndex($i);
|
||||
$name = $stat['name'] ?? '';
|
||||
$size = $stat['size'] ?? 0;
|
||||
|
||||
if (str_starts_with($name, 'storage/')) {
|
||||
$mediaCount++;
|
||||
if (count($mediaSamples) < 5) {
|
||||
$mediaSamples[] = basename($name);
|
||||
}
|
||||
} elseif (str_ends_with($name, '.sql') || $name === 'database.sql') {
|
||||
$sqlSize = $size;
|
||||
}
|
||||
}
|
||||
|
||||
$zip->close();
|
||||
|
||||
$tables = $manifest['tables'] ?? [];
|
||||
$tableCount = count($tables);
|
||||
$hasMedia = (bool) ($manifest['has_media'] ?? ($mediaCount > 0));
|
||||
$createdAt = isset($manifest['created_at']) ? Carbon::parse($manifest['created_at']) : Carbon::createFromTimestamp(filemtime($filePath));
|
||||
|
||||
return [
|
||||
'is_valid' => true,
|
||||
'filename' => basename($filePath),
|
||||
'file_size' => filesize($filePath),
|
||||
'file_size_human' => $this->formatBytes(filesize($filePath)),
|
||||
'format' => $manifest['format'] ?? 'KMH_ENCRYPTED_V1',
|
||||
'system' => $manifest['system'] ?? 'PT Kerinci Merangin Hidro (RKM)',
|
||||
'created_at' => $createdAt->toIso8601String(),
|
||||
'created_at_human' => $createdAt->translatedFormat('d F Y, H:i:s') . ' WIB',
|
||||
'created_at_diff' => $createdAt->diffForHumans(),
|
||||
'type' => $manifest['type'] ?? ($hasMedia ? 'semua' : 'pilihan'),
|
||||
'type_label' => ($manifest['type'] ?? '') === 'semua' || $hasMedia
|
||||
? 'Backup Semua (Database + Media Foto)'
|
||||
: 'Pilih Backup (Tabel Tertentu)',
|
||||
'database' => $manifest['database'] ?? config('database.connections.mysql.database', 'rkm_kmh'),
|
||||
'table_count' => $tableCount,
|
||||
'tables' => $tables,
|
||||
'has_media' => $hasMedia,
|
||||
'media_file_count' => $mediaCount,
|
||||
'media_samples' => $mediaSamples,
|
||||
'sql_size' => $sqlSize,
|
||||
'sql_size_human' => $this->formatBytes($sqlSize),
|
||||
'laravel_version' => $manifest['laravel_version'] ?? app()->version(),
|
||||
'php_version' => $manifest['php_version'] ?? PHP_VERSION,
|
||||
'encryption_cipher' => 'AES-256-CBC',
|
||||
'hmac_verification' => 'SHA-256 Terverifikasi Sah',
|
||||
];
|
||||
} finally {
|
||||
if (is_file($tempZip)) {
|
||||
@unlink($tempZip);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pulihkan (Restore) data dari file .kmh (atau .sql / .zip sebagai fallback).
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user