diff --git a/app/Console/Commands/CreateBackupCommand.php b/app/Console/Commands/CreateBackupCommand.php index 4d1d095..98c8a12 100644 --- a/app/Console/Commands/CreateBackupCommand.php +++ b/app/Console/Commands/CreateBackupCommand.php @@ -11,45 +11,51 @@ class CreateBackupCommand extends Command * Nama dan signature perintah CLI. */ protected $signature = 'backup:create - {--type=database : Jenis backup: database atau full} - {--filename= : Nama kustom untuk file backup}'; + {--scope=semua : Cakupan backup: semua atau pilihan} + {--tables= : Daftar nama tabel dipisah koma (jika scope=pilihan)} + {--filename= : Nama kustom untuk file .kmh}'; /** * Deskripsi perintah. */ - protected $description = 'Buat backup database MySQL atau Full Backup (+ media upload) sistem RKM-KMH'; + protected $description = 'Buat backup terenkripsi (.kmh) untuk sistem RKM-KMH'; public function handle(DatabaseBackupService $service): int { - $type = strtolower($this->option('type') ?: 'database'); + $scope = strtolower($this->option('scope') ?: 'semua'); $customName = $this->option('filename'); + $tablesOption = $this->option('tables'); - if (!in_array($type, ['database', 'full'])) { - $this->error("Pilihan --type tidak valid. Gunakan 'database' atau 'full'."); - return Command::FAILURE; + $selectedTables = null; + $includeMedia = false; + + if ($scope === 'semua') { + $includeMedia = true; + $this->info("Memulai pembuatan [Backup Semua] sistem RKM-KMH (.kmh)..."); + } else { + if ($tablesOption) { + $selectedTables = array_map('trim', explode(',', $tablesOption)); + } else { + $selectedTables = $service->getAllTableNames(); + } + $this->info("Memulai pembuatan [Pilih Backup] (" . count($selectedTables) . " tabel) (.kmh)..."); } - $this->info("Memulai pembuatan backup sistem RKM-KMH [Tipe: " . strtoupper($type) . "]..."); - try { $startTime = microtime(true); - - if ($type === 'full') { - $filename = $service->createFullBackup($customName); - } else { - $filename = $service->createDatabaseBackup($customName); - } - + $filename = $service->createKmhBackup($selectedTables, $includeMedia, $customName); $duration = round(microtime(true) - $startTime, 2); + $fullPath = $service->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename; - $sizeHuman = FileSizeHelper::format(file_exists($fullPath) ? filesize($fullPath) : 0); + $size = file_exists($fullPath) ? filesize($fullPath) : 0; + $sizeHuman = FileSizeHelper::format($size); $this->newLine(); - $this->info("✓ Backup berhasil dibuat!"); - $this->line(" File : {$filename}"); + $this->info("✓ File backup .kmh berhasil dibuat dan terenkripsi!"); + $this->line(" File : {$filename}"); $this->line(" Lokasi : {$fullPath}"); $this->line(" Ukuran : {$sizeHuman}"); - $this->line(" Waktu : {$duration} detik"); + $this->line(" Waktu : {$duration} detik"); return Command::SUCCESS; } catch (\Throwable $e) { diff --git a/app/Http/Controllers/Admin/BackupController.php b/app/Http/Controllers/Admin/BackupController.php index 2d6ae07..fc5d86e 100644 --- a/app/Http/Controllers/Admin/BackupController.php +++ b/app/Http/Controllers/Admin/BackupController.php @@ -27,55 +27,69 @@ class BackupController extends Controller { $backups = $this->backupService->listBackups(); $stats = $this->backupService->getSystemStats(); + $tableGroups = $this->backupService->getTableGroups(); - return view('admin.backups.index', compact('backups', 'stats')); + return view('admin.backups.index', compact('backups', 'stats', 'tableGroups')); } /** - * Buat file backup baru (Database Saja atau Full Backup + Media). + * Buat file backup baru berekstensi khusus .kmh (Pilih Backup atau Backup Semua). */ public function store(Request $request): RedirectResponse { $validated = $request->validate([ - 'type' => ['required', 'in:database,full'], + 'backup_scope' => ['required', 'in:pilihan,semua'], + 'selected_tables' => ['nullable', 'array'], + 'selected_tables.*' => ['string'], + 'include_media' => ['nullable', 'in:1,0'], ], [ - 'type.required' => 'Pilih jenis backup yang ingin dibuat.', - 'type.in' => 'Jenis backup harus bernilai database atau full.', + 'backup_scope.required' => 'Pilih cakupan pencadangan: Pilih Backup atau Backup Semua.', + 'backup_scope.in' => 'Cakupan backup tidak valid.', ]); - $type = $validated['type']; + $scope = $validated['backup_scope']; + $includeMedia = false; + $selectedTables = null; + + if ($scope === 'semua') { + $includeMedia = true; + $selectedTables = null; // Semua tabel + $scopeLabel = 'Backup Semua (Database + Media Upload)'; + } else { + $selectedTables = $request->input('selected_tables', []); + if (empty($selectedTables)) { + return back()->with('error', 'Silakan centang minimal satu tabel yang ingin Anda cadangkan.'); + } + $includeMedia = (bool) $request->input('include_media', false); + $scopeLabel = 'Pilih Backup (' . count($selectedTables) . ' Tabel Terpilih)'; + } try { - if ($type === 'full') { - $filename = $this->backupService->createFullBackup(); - $typeLabel = 'Full Backup (+ Media)'; - } else { - $filename = $this->backupService->createDatabaseBackup(); - $typeLabel = 'Database SQL'; - } + $filename = $this->backupService->createKmhBackup($selectedTables, $includeMedia); - // Catat ke Log Aktivitas Super Admin + // Rekam ke Log Aktivitas Super Admin AdminActivityLog::record( actionType: 'create', module: 'Backup & Restore', - description: "Membuat {$typeLabel} baru dengan nama file: {$filename}.", + description: "Membuat file backup terenkripsi .kmh: {$filename} [Cakupan: {$scopeLabel}].", targetType: 'BackupFile', targetName: $filename, newValues: [ 'filename' => $filename, - 'type' => $type, - 'created_at' => now()->toIso8601String(), + 'scope' => $scope, + 'table_count' => is_array($selectedTables) ? count($selectedTables) : 'all', + 'include_media' => $includeMedia, ] ); - return back()->with('success', "{$typeLabel} ({$filename}) berhasil dibuat dan disimpan di server."); + return back()->with('success', "Arsip terenkripsi .kmh ({$filename}) berhasil dibuat dan diamankan di server."); } catch (\Throwable $e) { return back()->with('error', 'Gagal membuat backup: ' . $e->getMessage()); } } /** - * Unduh file backup ke penyimpanan lokal administrator. + * Unduh file backup .kmh ke penyimpanan komputer lokal. */ public function download(string $filename): BinaryFileResponse|RedirectResponse { @@ -89,7 +103,7 @@ class BackupController extends Controller AdminActivityLog::record( actionType: 'export', module: 'Backup & Restore', - description: "Mengunduh file backup: {$filename}.", + description: "Mengunduh file arsip backup: {$filename}.", targetType: 'BackupFile', targetName: $filename ); @@ -102,7 +116,7 @@ class BackupController extends Controller } /** - * Unggah file backup (.sql, .zip, .gz) dari komputer lokal ke server. + * Unggah file backup (.kmh, .sql, atau .zip) dari komputer lokal ke server. */ public function upload(Request $request): RedirectResponse { @@ -118,11 +132,10 @@ class BackupController extends Controller $originalName = basename($file->getClientOriginalName()); $ext = strtolower($file->getClientOriginalExtension()); - if (!in_array($ext, ['sql', 'zip', 'gz'])) { - return back()->with('error', 'Format file tidak didukung. File backup harus berekstensi .sql, .zip, atau .gz.'); + if (!in_array($ext, ['kmh', 'sql', 'zip', 'gz'])) { + return back()->with('error', 'Format file tidak didukung. File backup harus berekstensi .kmh, .sql, atau .zip.'); } - // Cegah nama ganda dengan menambahkan timestamp jika file sudah ada $targetDir = $this->backupService->getBackupDirectory(); $targetFilename = $originalName; @@ -142,14 +155,14 @@ class BackupController extends Controller targetName: $targetFilename ); - return back()->with('success', "File backup '{$targetFilename}' berhasil diunggah dan siap dipulihkan jika diperlukan."); + return back()->with('success', "File backup '{$targetFilename}' berhasil diunggah ke server."); } catch (\Throwable $e) { return back()->with('error', 'Gagal menyimpan file backup yang diunggah: ' . $e->getMessage()); } } /** - * Pulihkan (Restore) database & aset sistem dari file backup. + * Pulihkan (Restore) database & aset sistem dari file backup (.kmh). */ public function restore(Request $request, string $filename): RedirectResponse { @@ -160,7 +173,7 @@ class BackupController extends Controller return back()->with('error', "File backup '{$filename}' tidak ditemukan di server."); } - // Verifikasi Keamanan: Harap ketik "PULIHKAN" atau masukkan password Super Admin + // Verifikasi Keamanan: Ketik "PULIHKAN" atau masukkan password Super Admin $confirmed = false; if ($request->filled('confirmation') && trim($request->input('confirmation')) === 'PULIHKAN') { $confirmed = true; @@ -173,7 +186,6 @@ class BackupController extends Controller } try { - // Jalankan proses restore $this->backupService->restore($fullPath); // Bersihkan cache aplikasi & permission registrar Spatie @@ -188,7 +200,7 @@ class BackupController extends Controller targetName: $filename ); - return back()->with('success', "Sistem berhasil dipulihkan dari file backup '{$filename}'. Seluruh data dan tabel telah disinkronkan kembali."); + return back()->with('success', "Sistem berhasil dipulihkan dari file backup '{$filename}'. Seluruh data tabel telah disinkronkan kembali."); } catch (\Throwable $e) { return back()->with('error', 'Terjadi kesalahan saat memulihkan sistem: ' . $e->getMessage()); } diff --git a/app/Services/DatabaseBackupService.php b/app/Services/DatabaseBackupService.php index e90b68e..f8d04ad 100644 --- a/app/Services/DatabaseBackupService.php +++ b/app/Services/DatabaseBackupService.php @@ -11,6 +11,8 @@ use ZipArchive; class DatabaseBackupService { + public const KMH_MAGIC_HEADER = "KMH_ENCRYPTED_BACKUP_V1\n"; + protected string $backupDir; public function __construct() @@ -29,6 +31,61 @@ class DatabaseBackupService return $this->backupDir; } + /** + * Dapatkan kunci enkripsi 256-bit berbasis APP_KEY sistem. + * Hanya sistem ini yang bisa mendekripsi dan membaca konten file .kmh. + */ + protected function getEncryptionKey(): string + { + $appKey = config('app.key'); + if (str_starts_with((string)$appKey, 'base64:')) { + $appKey = base64_decode(substr((string)$appKey, 7)); + } + return hash('sha256', (string)$appKey . '_RKM_KMH_ENCRYPTION_SECRET', true); + } + + /** + * Enkripsi payload mentah ke dalam format kontainer aman .kmh dengan header magic bytes & HMAC. + */ + public function encryptToKmh(string $rawContent): string + { + $key = $this->getEncryptionKey(); + $iv = random_bytes(16); + $ciphertext = openssl_encrypt($rawContent, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv); + $hmac = hash_hmac('sha256', $ciphertext, $key, true); + + return self::KMH_MAGIC_HEADER . $iv . $hmac . $ciphertext; + } + + /** + * Dekripsi file .kmh kembali ke konten arsip aslinya setelah verifikasi HMAC. + */ + public function decryptFromKmh(string $kmhContent): string + { + $headerLen = strlen(self::KMH_MAGIC_HEADER); + if (substr($kmhContent, 0, $headerLen) !== self::KMH_MAGIC_HEADER) { + throw new RuntimeException("File ini bukan format arsip .kmh yang sah atau file rusak."); + } + + $iv = substr($kmhContent, $headerLen, 16); + $hmac = substr($kmhContent, $headerLen + 16, 32); + $ciphertext = substr($kmhContent, $headerLen + 48); + + $key = $this->getEncryptionKey(); + $calculatedHmac = hash_hmac('sha256', $ciphertext, $key, true); + + if (!hash_equals($hmac, $calculatedHmac)) { + throw new RuntimeException("Gagal membuka file .kmh: Kunci enkripsi tidak cocok atau file telah dimodifikasi oleh sistem luar."); + } + + $decrypted = openssl_decrypt($ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv); + if ($decrypted === false) { + throw new RuntimeException("Gagal mendekripsi payload arsip .kmh."); + } + + return $decrypted; + } + /** * Dapatkan daftar seluruh file backup yang tersedia, diurutkan dari yang terbaru. * @@ -40,7 +97,8 @@ class DatabaseBackupService * size_raw: int, * size_human: string, * created_at: Carbon, - * created_at_human: string + * created_at_human: string, + * is_kmh: bool * }> */ public function listBackups(): array @@ -50,17 +108,18 @@ class DatabaseBackupService foreach ($files as $file) { $extension = strtolower($file->getExtension()); - if (!in_array($extension, ['sql', 'zip', 'gz'])) { + if (!in_array($extension, ['kmh', 'sql', 'zip', 'gz'])) { continue; } $filename = $file->getFilename(); $size = $file->getSize(); $createdAt = Carbon::createFromTimestamp($file->getMTime()); + $isKmh = ($extension === 'kmh'); - $isFull = str_ends_with($filename, '.zip') || str_contains($filename, '_full_'); - $type = $isFull ? 'full' : 'database'; - $typeLabel = $isFull ? 'Full Backup (+ File Media)' : 'Database SQL'; + $isFull = str_contains($filename, 'semua') || str_contains($filename, '_full_') || $extension === 'zip'; + $type = $isFull ? 'semua' : 'pilihan'; + $typeLabel = $isFull ? 'Backup Semua' : 'Pilih Backup'; $backups[] = [ 'filename' => $filename, @@ -71,6 +130,7 @@ class DatabaseBackupService 'size_human' => $this->formatBytes($size), 'created_at' => $createdAt, 'created_at_human' => $createdAt->translatedFormat('d M Y, H:i') . ' WIB', + 'is_kmh' => $isKmh, ]; } @@ -80,167 +140,104 @@ class DatabaseBackupService } /** - * Buat backup database (MySQL / SQLite) ke dalam file .sql murni. - * Menggunakan PDO stream generator mandiri tanpa ketergantungan mysqldump eksternal. + * Buat backup terenkripsi .kmh (baik "Pilih Backup" tabel tertentu atau "Backup Semua" + media). + * + * @param array|null $selectedTables Tabel yang dipilih (null = semua tabel) + * @param bool $includeMedia Sertakan file media upload di storage/app/public + * @param string|null $customFilename Nama file kustom opsional */ - public function createDatabaseBackup(?string $customFilename = null): string - { - @set_time_limit(300); - @ini_set('memory_limit', '512M'); - - $driver = DB::connection()->getDriverName(); - $database = config('database.connections.' . config('database.default') . '.database', 'database'); - $cleanDbName = str_replace([':', '/', '\\'], '_', (string) $database); - $timestamp = now()->format('Ymd_His'); - $filename = $customFilename ?: "backup_db_{$cleanDbName}_{$timestamp}.sql"; - - // Amankan nama file dari traversal - $filename = basename($filename); - if (!str_ends_with($filename, '.sql')) { - $filename .= '.sql'; - } - - $fullPath = $this->backupDir . DIRECTORY_SEPARATOR . $filename; - $handle = fopen($fullPath, 'w'); - - if (!$handle) { - throw new RuntimeException("Gagal membuka file backup untuk penulisan: {$fullPath}"); - } - - try { - $pdo = DB::connection()->getPdo(); - $nowString = now()->format('Y-m-d H:i:s'); - - // Header SQL Standar - fwrite($handle, "-- ==============================================================\n"); - fwrite($handle, "-- RKM-KMH DATABASE BACKUP (PT Kerinci Merangin Hidro)\n"); - fwrite($handle, "-- Dibuat pada : {$nowString} WIB\n"); - fwrite($handle, "-- Driver : {$driver}\n"); - fwrite($handle, "-- Database : {$database}\n"); - fwrite($handle, "-- ==============================================================\n\n"); - - if ($driver === 'sqlite') { - fwrite($handle, "PRAGMA foreign_keys = OFF;\n\n"); - } else { - fwrite($handle, "SET NAMES utf8mb4;\n"); - fwrite($handle, "SET FOREIGN_KEY_CHECKS = 0;\n"); - fwrite($handle, "SET SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO';\n"); - fwrite($handle, "SET time_zone = '+00:00';\n\n"); - } - - // Ambil daftar seluruh tabel aktif - $tables = $this->getAllTableNames(); - - foreach ($tables as $tableName) { - $this->dumpTableStructureAndData($handle, $pdo, $tableName, $driver); - } - - // Footer SQL - fwrite($handle, "\n-- ==============================================================\n"); - if ($driver === 'sqlite') { - fwrite($handle, "PRAGMA foreign_keys = ON;\n"); - } else { - fwrite($handle, "SET FOREIGN_KEY_CHECKS = 1;\n"); - } - fwrite($handle, "-- END OF RKM-KMH DATABASE BACKUP\n"); - fwrite($handle, "-- ==============================================================\n"); - - fclose($handle); - return $filename; - } catch (\Throwable $e) { - if (is_resource($handle)) { - fclose($handle); - } - if (File::exists($fullPath)) { - File::delete($fullPath); - } - throw new RuntimeException("Gagal membuat backup database: " . $e->getMessage(), 0, $e); - } - } - - /** - * Buat full backup (.zip) yang mencakup file database .sql dan seluruh file upload media (storage/app/public). - */ - public function createFullBackup(?string $customFilename = null): string + public function createKmhBackup(?array $selectedTables = null, bool $includeMedia = false, ?string $customFilename = null): string { @set_time_limit(600); @ini_set('memory_limit', '512M'); if (!class_exists('ZipArchive')) { - throw new RuntimeException('Ekstensi PHP ZipArchive tidak tersedia di server ini.'); + throw new RuntimeException('Ekstensi PHP ZipArchive diperlukan untuk memaketkan arsip.'); } - $database = config('database.connections.' . config('database.default') . '.database', 'database'); + $allTables = $this->getAllTableNames(); + $targetTables = (!empty($selectedTables)) ? array_values(array_intersect($allTables, $selectedTables)) : $allTables; + + if (empty($targetTables)) { + throw new RuntimeException('Silakan pilih minimal satu tabel yang ingin dicadangkan.'); + } + + $database = config('database.connections.' . config('database.default') . '.database', 'rkm_kmh'); $cleanDbName = str_replace([':', '/', '\\'], '_', (string) $database); $timestamp = now()->format('Ymd_His'); - $zipFilename = $customFilename ?: "backup_full_{$cleanDbName}_{$timestamp}.zip"; - $zipFilename = basename($zipFilename); - if (!str_ends_with($zipFilename, '.zip')) { - $zipFilename .= '.zip'; + + $isFull = ($includeMedia || count($targetTables) === count($allTables)); + $prefix = $includeMedia ? 'backup_semua' : 'backup_pilihan'; + + $filename = $customFilename ?: "{$prefix}_{$cleanDbName}_{$timestamp}.kmh"; + $filename = basename($filename); + if (!str_ends_with($filename, '.kmh')) { + $filename .= '.kmh'; } - $zipFullPath = $this->backupDir . DIRECTORY_SEPARATOR . $zipFilename; - - // 1. Buat temporary SQL dump terlebih dahulu - $tempSqlName = "temp_db_{$timestamp}.sql"; - $this->createDatabaseBackup($tempSqlName); - $tempSqlFullPath = $this->backupDir . DIRECTORY_SEPARATOR . $tempSqlName; + // 1. Buat temporary SQL dump untuk tabel-tabel yang dipilih + $tempSqlFile = storage_path('app/temp_dump_' . uniqid() . '.sql'); + $this->dumpTablesToSqlFile($targetTables, $tempSqlFile); + // 2. Buat temporary ZIP container + $tempZipFile = storage_path('app/temp_pkg_' . uniqid() . '.zip'); $zip = new ZipArchive(); - if ($zip->open($zipFullPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) { - if (File::exists($tempSqlFullPath)) { - File::delete($tempSqlFullPath); - } - throw new RuntimeException("Gagal membuat file ZIP di: {$zipFullPath}"); + if ($zip->open($tempZipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) { + @unlink($tempSqlFile); + throw new RuntimeException('Gagal membuat paket arsip sementara.'); } try { - // Masukkan database SQL ke dalam root arsip ZIP - $zip->addFile($tempSqlFullPath, 'database.sql'); + $zip->addFile($tempSqlFile, 'database.sql'); - // Masukkan seluruh file media yang ada di storage/app/public (misal foto profil, foto kendaraan, simper) - $publicStorageDir = storage_path('app/public'); - if (File::isDirectory($publicStorageDir)) { - $files = File::allFiles($publicStorageDir); - foreach ($files as $file) { - $relativePath = 'storage/' . $file->getRelativePathname(); - $zip->addFile($file->getRealPath(), str_replace('\\', '/', $relativePath)); + // Tambahkan file media jika diminta (Backup Semua) + if ($includeMedia) { + $publicStorageDir = storage_path('app/public'); + if (File::isDirectory($publicStorageDir)) { + $files = File::allFiles($publicStorageDir); + foreach ($files as $file) { + $relativePath = 'storage/' . $file->getRelativePathname(); + $zip->addFile($file->getRealPath(), str_replace('\\', '/', $relativePath)); + } } } - // Tambahkan metadata ringkas manifest.json + // Manifest informasi arsip .kmh $manifest = [ 'system' => 'RKM-KMH (PT Kerinci Merangin Hidro)', + 'format' => 'KMH_ENCRYPTED_V1', 'created_at' => now()->toIso8601String(), - 'type' => 'full', + 'type' => $includeMedia ? 'semua' : 'pilihan', 'database' => $database, + 'table_count' => count($targetTables), + 'tables' => $targetTables, + 'has_media' => $includeMedia, 'laravel_version' => app()->version(), 'php_version' => PHP_VERSION, ]; $zip->addFromString('manifest.json', json_encode($manifest, JSON_PRETTY_PRINT)); - $zip->close(); - // Hapus file temporary SQL - if (File::exists($tempSqlFullPath)) { - File::delete($tempSqlFullPath); - } + @unlink($tempSqlFile); - return $zipFilename; + // 3. Enkripsi seluruh paket ZIP menjadi file .kmh terenkripsi + $rawZipContent = file_get_contents($tempZipFile); + @unlink($tempZipFile); + + $encryptedKmh = $this->encryptToKmh($rawZipContent); + $finalPath = $this->backupDir . DIRECTORY_SEPARATOR . $filename; + file_put_contents($finalPath, $encryptedKmh); + + return $filename; } catch (\Throwable $e) { - $zip->close(); - if (File::exists($tempSqlFullPath)) { - File::delete($tempSqlFullPath); - } - if (File::exists($zipFullPath)) { - File::delete($zipFullPath); - } - throw new RuntimeException("Gagal membuat full backup ZIP: " . $e->getMessage(), 0, $e); + if (is_file($tempSqlFile)) @unlink($tempSqlFile); + if (is_file($tempZipFile)) @unlink($tempZipFile); + throw new RuntimeException("Gagal membuat arsip terenkripsi .kmh: " . $e->getMessage(), 0, $e); } } /** - * Pulihkan (Restore) database & aset dari file backup (.sql atau .zip). + * Pulihkan (Restore) data dari file .kmh (atau .sql / .zip sebagai fallback). */ public function restore(string $backupFilenameOrPath): void { @@ -255,28 +252,107 @@ class DatabaseBackupService throw new RuntimeException("File backup tidak ditemukan: {$filePath}"); } - $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION)); + $content = file_get_contents($filePath); + $headerLen = strlen(self::KMH_MAGIC_HEADER); + // Jika file berformat .kmh terenkripsi + if (substr($content, 0, $headerLen) === self::KMH_MAGIC_HEADER) { + $this->restoreFromKmhContent($content); + return; + } + + // Fallback untuk file .sql atau .zip warisan + $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION)); if ($extension === 'zip') { $this->restoreFromZip($filePath); } elseif ($extension === 'sql') { $this->restoreFromSql($filePath); - } elseif ($extension === 'gz') { - $this->restoreFromGzip($filePath); } else { throw new RuntimeException("Format file tidak didukung untuk pemulihan: .{$extension}"); } } /** - * Pulihkan dari file SQL langsung. + * Pulihkan dari konten terenkripsi .kmh. + */ + protected function restoreFromKmhContent(string $kmhContent): void + { + $decryptedZipContent = $this->decryptFromKmh($kmhContent); + + $tempZipFile = storage_path('app/temp_restore_' . uniqid() . '.zip'); + file_put_contents($tempZipFile, $decryptedZipContent); + + try { + $this->restoreFromZip($tempZipFile); + @unlink($tempZipFile); + } catch (\Throwable $e) { + if (is_file($tempZipFile)) @unlink($tempZipFile); + throw $e; + } + } + + /** + * Pulihkan dari file arsip ZIP. + */ + public function restoreFromZip(string $zipFilePath): void + { + if (!class_exists('ZipArchive')) { + throw new RuntimeException('Ekstensi PHP ZipArchive tidak tersedia di server ini.'); + } + + $zip = new ZipArchive(); + if ($zip->open($zipFilePath) !== true) { + throw new RuntimeException("Gagal membuka file arsip ZIP: {$zipFilePath}"); + } + + $tempExtractDir = storage_path('app/temp_extract_' . uniqid()); + File::makeDirectory($tempExtractDir, 0755, true); + + try { + $zip->extractTo($tempExtractDir); + $zip->close(); + + // 1. Eksekusi file SQL database + $sqlFile = $tempExtractDir . DIRECTORY_SEPARATOR . 'database.sql'; + if (!File::exists($sqlFile)) { + $foundSql = File::glob($tempExtractDir . '/*.sql'); + if (!empty($foundSql)) { + $sqlFile = $foundSql[0]; + } else { + throw new RuntimeException('File database.sql tidak ditemukan di dalam paket arsip.'); + } + } + + $this->restoreFromSql($sqlFile); + + // 2. Pulihkan file aset media ke storage/app/public jika ada + $extractedStorageDir = $tempExtractDir . DIRECTORY_SEPARATOR . 'storage'; + $targetStorageDir = storage_path('app/public'); + + if (File::isDirectory($extractedStorageDir)) { + if (!File::isDirectory($targetStorageDir)) { + File::makeDirectory($targetStorageDir, 0755, true); + } + File::copyDirectory($extractedStorageDir, $targetStorageDir); + } + + File::deleteDirectory($tempExtractDir); + } catch (\Throwable $e) { + if (File::isDirectory($tempExtractDir)) { + File::deleteDirectory($tempExtractDir); + } + throw $e; + } + } + + /** + * Eksekusi pemulihan dari file skrip SQL. */ public function restoreFromSql(string $sqlFilePath): void { $pdo = DB::connection()->getPdo(); $driver = DB::connection()->getDriverName(); - // Nonaktifkan pemeriksaan foreign key untuk mencegah deadlock/relasi urutan if ($driver === 'sqlite') { $pdo->exec("PRAGMA foreign_keys = OFF;"); } else { @@ -303,9 +379,7 @@ class DatabaseBackupService while (($line = fgets($handle)) !== false) { $trimmed = trim($line); - // Lewati komentar baris tunggal jika tidak sedang di dalam quote if (!$inQuotes && (str_starts_with($trimmed, '--') || str_starts_with($trimmed, '/*') || str_starts_with($trimmed, '#'))) { - // Cek jika komentar multi baris if (str_starts_with($trimmed, '/*') && !str_ends_with($trimmed, '*/')) { while (($line = fgets($handle)) !== false) { if (str_contains($line, '*/')) break; @@ -341,7 +415,6 @@ class DatabaseBackupService $quoteChar = $char; $currentQuery .= $char; } elseif ($char === ';') { - // Akhir dari sebuah statement SQL $statement = trim($currentQuery); if ($statement !== '') { $pdo->exec($statement); @@ -354,7 +427,6 @@ class DatabaseBackupService } } - // Jalankan statement terakhir jika ada yang tersisa tanpa titik koma $finalStatement = trim($currentQuery); if ($finalStatement !== '') { $pdo->exec($finalStatement); @@ -379,96 +451,6 @@ class DatabaseBackupService } } - /** - * Pulihkan dari file full backup .zip (restore database.sql dan sinkronkan file media). - */ - public function restoreFromZip(string $zipFilePath): void - { - if (!class_exists('ZipArchive')) { - throw new RuntimeException('Ekstensi PHP ZipArchive tidak tersedia di server ini.'); - } - - $zip = new ZipArchive(); - if ($zip->open($zipFilePath) !== true) { - throw new RuntimeException("Gagal membuka file arsip ZIP: {$zipFilePath}"); - } - - $tempExtractDir = storage_path('app/temp_restore_' . uniqid()); - File::makeDirectory($tempExtractDir, 0755, true); - - try { - $zip->extractTo($tempExtractDir); - $zip->close(); - - // 1. Eksekusi file SQL database - $sqlFile = $tempExtractDir . DIRECTORY_SEPARATOR . 'database.sql'; - if (!File::exists($sqlFile)) { - $foundSql = File::glob($tempExtractDir . '/*.sql'); - if (!empty($foundSql)) { - $sqlFile = $foundSql[0]; - } else { - throw new RuntimeException('File database.sql tidak ditemukan di dalam paket ZIP.'); - } - } - - $this->restoreFromSql($sqlFile); - - // 2. Pulihkan file aset media ke storage/app/public jika ada - $extractedStorageDir = $tempExtractDir . DIRECTORY_SEPARATOR . 'storage'; - $targetStorageDir = storage_path('app/public'); - - if (File::isDirectory($extractedStorageDir)) { - if (!File::isDirectory($targetStorageDir)) { - File::makeDirectory($targetStorageDir, 0755, true); - } - File::copyDirectory($extractedStorageDir, $targetStorageDir); - } - - // Bersihkan temporary folder - File::deleteDirectory($tempExtractDir); - } catch (\Throwable $e) { - if (File::isDirectory($tempExtractDir)) { - File::deleteDirectory($tempExtractDir); - } - throw $e; - } - } - - /** - * Pulihkan dari file SQL terkompresi Gzip (.sql.gz). - */ - protected function restoreFromGzip(string $gzFilePath): void - { - if (!function_exists('gzopen')) { - throw new RuntimeException('Ekstensi PHP zlib tidak tersedia untuk dekompresi gzip.'); - } - - $tempSqlFile = storage_path('app/temp_restore_' . uniqid() . '.sql'); - $gz = gzopen($gzFilePath, 'rb'); - $out = fopen($tempSqlFile, 'wb'); - - if (!$gz || !$out) { - throw new RuntimeException("Gagal mengekstrak file gzip: {$gzFilePath}"); - } - - while (!gzeof($gz)) { - fwrite($out, gzread($gz, 65536)); - } - - gzclose($gz); - fclose($out); - - try { - $this->restoreFromSql($tempSqlFile); - File::delete($tempSqlFile); - } catch (\Throwable $e) { - if (File::exists($tempSqlFile)) { - File::delete($tempSqlFile); - } - throw $e; - } - } - /** * Hapus file backup tertentu dari penyimpanan. */ @@ -486,16 +468,6 @@ class DatabaseBackupService /** * Dapatkan informasi statistik penyimpanan backup dan database sistem. - * - * @return array{ - * total_backups: int, - * total_size_raw: int, - * total_size_human: string, - * database_name: string, - * table_count: int, - * estimated_db_size_human: string, - * last_backup: ?array - * } */ public function getSystemStats(): array { @@ -556,6 +528,126 @@ class DatabaseBackupService return $names; } + /** + * Kelompokkan tabel database ke dalam modul-modul fungsional untuk memudahkan pilihan backup. + * + * @return array}> + */ + public function getTableGroups(): array + { + $allTables = $this->getAllTableNames(); + + $groups = [ + 'hse' => [ + 'name' => 'K3 / HSE (Karyawan & SIMPER)', + 'description' => 'Data personil karyawan, master jenis SIMPER, dan izin mengemudi.', + 'tables' => array_values(array_intersect($allTables, [ + 'employees', 'simper_types', 'employee_simpers' + ])), + ], + 'qma' => [ + 'name' => 'QMA (Kendaraan, Alat Berat & P2H)', + 'description' => 'Master unit LV/HE, checklist P2H, transfer unit, dan log aktivitas.', + 'tables' => array_values(array_intersect($allTables, [ + 'vehicles', 'vehicle_activities', 'vehicle_location_histories', + 'unit_transfers', 'unit_support_timesheets', 'p2h_templates', + 'p2h_template_items', 'p2h_records', 'p2h_record_items' + ])), + ], + 'pg' => [ + 'name' => 'Private Guard (Satpam & Pos Gerbang)', + 'description' => 'Data personil satpam lapangan dan pos pemeriksaan gerbang.', + 'tables' => array_values(array_intersect($allTables, [ + 'gates', 'security_guards' + ])), + ], + 'rbac' => [ + 'name' => 'Pengguna & Hak Akses (RBAC)', + 'description' => 'Akun pengguna, jabatan role, direct permissions, dan log aktivitas admin.', + 'tables' => array_values(array_intersect($allTables, [ + 'users', 'roles', 'permissions', 'model_has_roles', + 'model_has_permissions', 'role_has_permissions', 'admin_activity_logs' + ])), + ], + 'system' => [ + 'name' => 'Sistem & Internal Database', + 'description' => 'Migrasi, sesi, cache, dan antrean background jobs.', + 'tables' => array_values(array_intersect($allTables, [ + 'migrations', 'sessions', 'cache', 'cache_locks', + 'jobs', 'job_batches', 'failed_jobs', 'password_reset_tokens' + ])), + ], + ]; + + // Kelompokkan tabel lain jika ada tabel kustom tambahan di database + $categorized = []; + foreach ($groups as $g) { + $categorized = array_merge($categorized, $g['tables']); + } + $otherTables = array_values(array_diff($allTables, $categorized)); + if (!empty($otherTables)) { + $groups['other'] = [ + 'name' => 'Tabel Lainnya', + 'description' => 'Tabel data tambahan sistem.', + 'tables' => $otherTables, + ]; + } + + return $groups; + } + + /** + * Dump struktur dan data dari daftar tabel tertentu ke file SQL. + * + * @param array $tables + */ + protected function dumpTablesToSqlFile(array $tables, string $targetSqlPath): void + { + $handle = fopen($targetSqlPath, 'w'); + if (!$handle) { + throw new RuntimeException("Gagal membuka file SQL sementara untuk penulisan: {$targetSqlPath}"); + } + + try { + $pdo = DB::connection()->getPdo(); + $driver = DB::connection()->getDriverName(); + $database = config('database.connections.' . config('database.default') . '.database', 'database'); + $nowString = now()->format('Y-m-d H:i:s'); + + fwrite($handle, "-- ==============================================================\n"); + fwrite($handle, "-- RKM-KMH SECURE DATABASE DUMP (PT Kerinci Merangin Hidro)\n"); + fwrite($handle, "-- Dibuat pada : {$nowString} WIB\n"); + fwrite($handle, "-- Database : {$database}\n"); + fwrite($handle, "-- ==============================================================\n\n"); + + if ($driver === 'sqlite') { + fwrite($handle, "PRAGMA foreign_keys = OFF;\n\n"); + } else { + fwrite($handle, "SET NAMES utf8mb4;\n"); + fwrite($handle, "SET FOREIGN_KEY_CHECKS = 0;\n"); + fwrite($handle, "SET SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO';\n"); + fwrite($handle, "SET time_zone = '+00:00';\n\n"); + } + + foreach ($tables as $tableName) { + $this->dumpTableStructureAndData($handle, $pdo, $tableName, $driver); + } + + fwrite($handle, "\n-- ==============================================================\n"); + if ($driver === 'sqlite') { + fwrite($handle, "PRAGMA foreign_keys = ON;\n"); + } else { + fwrite($handle, "SET FOREIGN_KEY_CHECKS = 1;\n"); + } + fwrite($handle, "-- END OF DUMP\n"); + + fclose($handle); + } catch (\Throwable $e) { + if (is_resource($handle)) fclose($handle); + throw $e; + } + } + /** * Dump struktur dan data satu tabel database. */ @@ -579,7 +671,6 @@ class DatabaseBackupService fwrite($handle, $createTableSql . ";\n\n"); } - // Dump Data Baris (chunk 200 baris untuk efisiensi RAM) fwrite($handle, "-- Dumping Data untuk `{$tableName}`\n"); $query = DB::table($tableName); diff --git a/resources/views/admin/backups/index.blade.php b/resources/views/admin/backups/index.blade.php index 74e983f..e0c0477 100644 --- a/resources/views/admin/backups/index.blade.php +++ b/resources/views/admin/backups/index.blade.php @@ -4,265 +4,173 @@ @section('content')
- -
+ +
-

- - Backup & Restore Sistem +

+ Backup & Restore Sistem

-

- Pencadangan database MySQL dan file media sistem secara berkala untuk perlindungan data dan pemulihan bencana (disaster recovery). +

+ Pencadangan terenkripsi berformat .kmh khusus untuk sistem RKM-KMH. File tidak dapat dibaca oleh sistem luar.

-
+
@if(session('success')) -
-
- - {{ session('success') }} -
- +
+ {{ session('success') }} +
@endif @if(session('error')) -
-
- - {{ session('error') }} -
- +
+ {{ session('error') }} +
@endif - -
- -
-
- Total File Backup - - - + +
+
+ Total File Backup +
+ {{ number_format($stats['total_backups']) }} + file (.kmh)
- {{ number_format($stats['total_backups']) }} - Arsip tersimpan di server + Total kapasitas: {{ $stats['total_size_human'] }}
- -
-
- Ukuran Arsip - - +
+ Backup Terakhir +
+ + {{ $stats['last_backup']['created_at_human'] ?? 'Belum ada backup' }} + + + {{ $stats['last_backup']['filename'] ?? '-' }}
- {{ $stats['total_size_human'] }} - Kapasitas folder storage/app/backups
- -
-
- Backup Terakhir - - - +
+ Database Aktif +
+ {{ $stats['database_name'] }} + ({{ $stats['table_count'] }} Tabel)
- - {{ $stats['last_backup']['created_at_human'] ?? 'Belum ada backup' }} - - - {{ $stats['last_backup']['filename'] ?? 'Klik Buat Backup Baru' }} - + Estimasi data: {{ $stats['estimated_db_size_human'] }}
- - -
-
- Database Aktif - - - -
- - {{ $stats['database_name'] }} - - - {{ $stats['table_count'] }} Tabel • Estimasi {{ $stats['estimated_db_size_human'] }} - -
-
- - -
-
-
- -
-
-

- Panduan Keamanan & Pemulihan Sistem - Rekomendasi -

-

- Disarankan untuk mengunduh arsip backup secara teratur ke perangkat fisik atau penyimpanan cloud terpisah. Sebelum melakukan pembaruan besar atau perubahan skema data, buat selalu backup terbaru sebagai cadangan darurat. -

-
-
-
-
-
-
-

- - Daftar Arsip Backup Tersimpan -

-

Seluruh file tersimpan secara aman di direktori lokal server storage/app/backups/

-
-
- {{ count($backups) }} File Tersedia -
+
+
+

+ Daftar Arsip Backup +

+ + storage/app/backups/ +
- - - - + + + + - + @forelse($backups as $b) @php - $isFull = ($b['type'] === 'full'); + $isFull = ($b['type'] === 'semua'); @endphp - + - - - - - - - @empty - @@ -274,70 +182,132 @@ - + -
Nama File BackupJenis BackupUkuran File
Nama FileTipe BackupUkuran Tanggal DibuatAksi & PemulihanAksi
-
-
- @if($isFull) - - @else - - @endif -
-
-

- {{ $b['filename'] }} -

-

- {{ $isFull ? 'Arsip ZIP (Database + Media Upload)' : 'File Skrip SQL Murni' }} -

-
+
+
+ + {{ $b['filename'] }} + + @if($b['is_kmh']) + + .kmh + + @endif
+ + @if($isFull) - - - Full Backup + Media + + Backup Semua @else - - - Database SQL + + Pilih Backup @endif + {{ $b['size_human'] }} - {{ $b['created_at_human'] }} - {{ $b['created_at']->diffForHumans() }} + + {{ $b['created_at_human'] }} -
- + +
+
- - + class="px-2.5 py-1 rounded-lg border border-slate-200 bg-white hover:bg-slate-50 text-slate-700 font-semibold text-[11px] transition"> + Unduh - -
-
- -
-

Belum Ada File Backup Tersimpan

-

- Amankan data sistem Anda dengan membuat cadangan database pertama sekarang. -

+
+

Belum ada file backup yang tersimpan di server.