diff --git a/app/Console/Commands/CreateBackupCommand.php b/app/Console/Commands/CreateBackupCommand.php new file mode 100644 index 0000000..4d1d095 --- /dev/null +++ b/app/Console/Commands/CreateBackupCommand.php @@ -0,0 +1,71 @@ +option('type') ?: 'database'); + $customName = $this->option('filename'); + + if (!in_array($type, ['database', 'full'])) { + $this->error("Pilihan --type tidak valid. Gunakan 'database' atau 'full'."); + return Command::FAILURE; + } + + $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); + } + + $duration = round(microtime(true) - $startTime, 2); + $fullPath = $service->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename; + $sizeHuman = FileSizeHelper::format(file_exists($fullPath) ? filesize($fullPath) : 0); + + $this->newLine(); + $this->info("✓ Backup berhasil dibuat!"); + $this->line(" File : {$filename}"); + $this->line(" Lokasi : {$fullPath}"); + $this->line(" Ukuran : {$sizeHuman}"); + $this->line(" Waktu : {$duration} detik"); + + return Command::SUCCESS; + } catch (\Throwable $e) { + $this->error("Gagal membuat backup: " . $e->getMessage()); + return Command::FAILURE; + } + } +} + +class FileSizeHelper +{ + public static function format(int $bytes): string + { + if ($bytes <= 0) return '0 B'; + $units = ['B', 'KB', 'MB', 'GB']; + $power = min((int) floor(log($bytes, 1024)), count($units) - 1); + return round($bytes / pow(1024, $power), 2) . ' ' . $units[$power]; + } +} diff --git a/app/Http/Controllers/Admin/BackupController.php b/app/Http/Controllers/Admin/BackupController.php new file mode 100644 index 0000000..2d6ae07 --- /dev/null +++ b/app/Http/Controllers/Admin/BackupController.php @@ -0,0 +1,218 @@ +backupService->listBackups(); + $stats = $this->backupService->getSystemStats(); + + return view('admin.backups.index', compact('backups', 'stats')); + } + + /** + * Buat file backup baru (Database Saja atau Full Backup + Media). + */ + public function store(Request $request): RedirectResponse + { + $validated = $request->validate([ + 'type' => ['required', 'in:database,full'], + ], [ + 'type.required' => 'Pilih jenis backup yang ingin dibuat.', + 'type.in' => 'Jenis backup harus bernilai database atau full.', + ]); + + $type = $validated['type']; + + try { + if ($type === 'full') { + $filename = $this->backupService->createFullBackup(); + $typeLabel = 'Full Backup (+ Media)'; + } else { + $filename = $this->backupService->createDatabaseBackup(); + $typeLabel = 'Database SQL'; + } + + // Catat ke Log Aktivitas Super Admin + AdminActivityLog::record( + actionType: 'create', + module: 'Backup & Restore', + description: "Membuat {$typeLabel} baru dengan nama file: {$filename}.", + targetType: 'BackupFile', + targetName: $filename, + newValues: [ + 'filename' => $filename, + 'type' => $type, + 'created_at' => now()->toIso8601String(), + ] + ); + + return back()->with('success', "{$typeLabel} ({$filename}) berhasil dibuat dan disimpan di server."); + } catch (\Throwable $e) { + return back()->with('error', 'Gagal membuat backup: ' . $e->getMessage()); + } + } + + /** + * Unduh file backup ke penyimpanan lokal administrator. + */ + public function download(string $filename): BinaryFileResponse|RedirectResponse + { + $filename = basename($filename); + $fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename; + + if (!File::exists($fullPath)) { + return back()->with('error', "File backup '{$filename}' tidak ditemukan di server."); + } + + AdminActivityLog::record( + actionType: 'export', + module: 'Backup & Restore', + description: "Mengunduh file backup: {$filename}.", + targetType: 'BackupFile', + targetName: $filename + ); + + return response()->download($fullPath, $filename, [ + 'Cache-Control' => 'no-cache, no-store, must-revalidate', + 'Pragma' => 'no-cache', + 'Expires' => '0', + ]); + } + + /** + * Unggah file backup (.sql, .zip, .gz) dari komputer lokal ke server. + */ + public function upload(Request $request): RedirectResponse + { + $request->validate([ + 'backup_file' => ['required', 'file', 'max:204800'], // Maks. 200 MB + ], [ + 'backup_file.required' => 'Pilih file backup yang ingin diunggah.', + 'backup_file.file' => 'File yang diunggah tidak valid.', + 'backup_file.max' => 'Ukuran file backup maksimal 200 MB.', + ]); + + $file = $request->file('backup_file'); + $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.'); + } + + // Cegah nama ganda dengan menambahkan timestamp jika file sudah ada + $targetDir = $this->backupService->getBackupDirectory(); + $targetFilename = $originalName; + + if (File::exists($targetDir . DIRECTORY_SEPARATOR . $targetFilename)) { + $nameOnly = pathinfo($originalName, PATHINFO_FILENAME); + $targetFilename = $nameOnly . '_' . now()->format('Ymd_His') . '.' . $ext; + } + + try { + $file->move($targetDir, $targetFilename); + + AdminActivityLog::record( + actionType: 'create', + module: 'Backup & Restore', + description: "Mengunggah file backup eksternal: {$targetFilename}.", + targetType: 'BackupFile', + targetName: $targetFilename + ); + + return back()->with('success', "File backup '{$targetFilename}' berhasil diunggah dan siap dipulihkan jika diperlukan."); + } catch (\Throwable $e) { + return back()->with('error', 'Gagal menyimpan file backup yang diunggah: ' . $e->getMessage()); + } + } + + /** + * Pulihkan (Restore) database & aset sistem dari file backup. + */ + public function restore(Request $request, string $filename): RedirectResponse + { + $filename = basename($filename); + $fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename; + + if (!File::exists($fullPath)) { + return back()->with('error', "File backup '{$filename}' tidak ditemukan di server."); + } + + // Verifikasi Keamanan: Harap ketik "PULIHKAN" atau masukkan password Super Admin + $confirmed = false; + if ($request->filled('confirmation') && trim($request->input('confirmation')) === 'PULIHKAN') { + $confirmed = true; + } elseif ($request->filled('password') && Hash::check($request->input('password'), $request->user()->password)) { + $confirmed = true; + } + + if (!$confirmed) { + return back()->with('error', 'Konfirmasi keamanan tidak sesuai. Silakan ketik kata "PULIHKAN" atau masukkan password akun Super Admin Anda untuk melanjutkan pemulihan.'); + } + + try { + // Jalankan proses restore + $this->backupService->restore($fullPath); + + // Bersihkan cache aplikasi & permission registrar Spatie + Artisan::call('cache:clear'); + app()[PermissionRegistrar::class]->forgetCachedPermissions(); + + AdminActivityLog::record( + actionType: 'update', + module: 'Backup & Restore', + description: "Melakukan pemulihan (restore) database dan aset sistem dari file backup: {$filename}.", + targetType: 'BackupFile', + targetName: $filename + ); + + return back()->with('success', "Sistem berhasil dipulihkan dari file backup '{$filename}'. Seluruh data dan tabel telah disinkronkan kembali."); + } catch (\Throwable $e) { + return back()->with('error', 'Terjadi kesalahan saat memulihkan sistem: ' . $e->getMessage()); + } + } + + /** + * Hapus file backup dari penyimpanan server. + */ + public function destroy(string $filename): RedirectResponse + { + $filename = basename($filename); + + if ($this->backupService->deleteBackup($filename)) { + AdminActivityLog::record( + actionType: 'delete', + module: 'Backup & Restore', + description: "Menghapus file backup: {$filename}.", + targetType: 'BackupFile', + targetName: $filename + ); + + return back()->with('success', "File backup '{$filename}' berhasil dihapus dari server."); + } + + return back()->with('error', "File backup '{$filename}' tidak ditemukan atau gagal dihapus."); + } +} diff --git a/app/Services/DatabaseBackupService.php b/app/Services/DatabaseBackupService.php new file mode 100644 index 0000000..e90b68e --- /dev/null +++ b/app/Services/DatabaseBackupService.php @@ -0,0 +1,643 @@ +backupDir = storage_path('app/backups'); + if (!File::isDirectory($this->backupDir)) { + File::makeDirectory($this->backupDir, 0755, true); + } + } + + /** + * Dapatkan path direktori penyimpanan backup. + */ + public function getBackupDirectory(): string + { + return $this->backupDir; + } + + /** + * Dapatkan daftar seluruh file backup yang tersedia, diurutkan dari yang terbaru. + * + * @return array + */ + public function listBackups(): array + { + $files = File::files($this->backupDir); + $backups = []; + + foreach ($files as $file) { + $extension = strtolower($file->getExtension()); + if (!in_array($extension, ['sql', 'zip', 'gz'])) { + continue; + } + + $filename = $file->getFilename(); + $size = $file->getSize(); + $createdAt = Carbon::createFromTimestamp($file->getMTime()); + + $isFull = str_ends_with($filename, '.zip') || str_contains($filename, '_full_'); + $type = $isFull ? 'full' : 'database'; + $typeLabel = $isFull ? 'Full Backup (+ File Media)' : 'Database SQL'; + + $backups[] = [ + 'filename' => $filename, + 'path' => $file->getPathname(), + 'type' => $type, + 'type_label' => $typeLabel, + 'size_raw' => $size, + 'size_human' => $this->formatBytes($size), + 'created_at' => $createdAt, + 'created_at_human' => $createdAt->translatedFormat('d M Y, H:i') . ' WIB', + ]; + } + + usort($backups, fn ($a, $b) => $b['created_at']->timestamp <=> $a['created_at']->timestamp); + + return $backups; + } + + /** + * Buat backup database (MySQL / SQLite) ke dalam file .sql murni. + * Menggunakan PDO stream generator mandiri tanpa ketergantungan mysqldump eksternal. + */ + 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 + { + @set_time_limit(600); + @ini_set('memory_limit', '512M'); + + if (!class_exists('ZipArchive')) { + throw new RuntimeException('Ekstensi PHP ZipArchive tidak tersedia di server ini.'); + } + + $database = config('database.connections.' . config('database.default') . '.database', 'database'); + $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'; + } + + $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; + + $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}"); + } + + try { + // Masukkan database SQL ke dalam root arsip ZIP + $zip->addFile($tempSqlFullPath, '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 metadata ringkas manifest.json + $manifest = [ + 'system' => 'RKM-KMH (PT Kerinci Merangin Hidro)', + 'created_at' => now()->toIso8601String(), + 'type' => 'full', + 'database' => $database, + '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); + } + + return $zipFilename; + } 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); + } + } + + /** + * Pulihkan (Restore) database & aset dari file backup (.sql atau .zip). + */ + public function restore(string $backupFilenameOrPath): void + { + @set_time_limit(600); + @ini_set('memory_limit', '512M'); + + $filePath = File::exists($backupFilenameOrPath) + ? $backupFilenameOrPath + : $this->backupDir . DIRECTORY_SEPARATOR . basename($backupFilenameOrPath); + + if (!File::exists($filePath)) { + throw new RuntimeException("File backup tidak ditemukan: {$filePath}"); + } + + $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. + */ + 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 { + $pdo->exec("SET FOREIGN_KEY_CHECKS = 0;"); + $pdo->exec("SET SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO';"); + } + + $handle = fopen($sqlFilePath, 'r'); + if (!$handle) { + if ($driver === 'sqlite') { + $pdo->exec("PRAGMA foreign_keys = ON;"); + } else { + $pdo->exec("SET FOREIGN_KEY_CHECKS = 1;"); + } + throw new RuntimeException("Gagal membaca file SQL: {$sqlFilePath}"); + } + + $currentQuery = ''; + $inQuotes = false; + $quoteChar = ''; + $escaped = false; + + try { + 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; + } + } + continue; + } + + $len = strlen($line); + for ($i = 0; $i < $len; $i++) { + $char = $line[$i]; + + if ($escaped) { + $currentQuery .= $char; + $escaped = false; + continue; + } + + if ($char === '\\') { + $escaped = true; + $currentQuery .= $char; + continue; + } + + if ($inQuotes) { + if ($char === $quoteChar) { + $inQuotes = false; + } + $currentQuery .= $char; + } else { + if ($char === "'" || $char === '"' || $char === '`') { + $inQuotes = true; + $quoteChar = $char; + $currentQuery .= $char; + } elseif ($char === ';') { + // Akhir dari sebuah statement SQL + $statement = trim($currentQuery); + if ($statement !== '') { + $pdo->exec($statement); + } + $currentQuery = ''; + } else { + $currentQuery .= $char; + } + } + } + } + + // Jalankan statement terakhir jika ada yang tersisa tanpa titik koma + $finalStatement = trim($currentQuery); + if ($finalStatement !== '') { + $pdo->exec($finalStatement); + } + + fclose($handle); + if ($driver === 'sqlite') { + $pdo->exec("PRAGMA foreign_keys = ON;"); + } else { + $pdo->exec("SET FOREIGN_KEY_CHECKS = 1;"); + } + } catch (\Throwable $e) { + if (is_resource($handle)) { + fclose($handle); + } + if ($driver === 'sqlite') { + $pdo->exec("PRAGMA foreign_keys = ON;"); + } else { + $pdo->exec("SET FOREIGN_KEY_CHECKS = 1;"); + } + throw new RuntimeException("Gagal mengeksekusi restore SQL: " . $e->getMessage(), 0, $e); + } + } + + /** + * 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. + */ + public function deleteBackup(string $filename): bool + { + $filename = basename($filename); + $fullPath = $this->backupDir . DIRECTORY_SEPARATOR . $filename; + + if (File::exists($fullPath)) { + return File::delete($fullPath); + } + + return false; + } + + /** + * 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 + { + $backups = $this->listBackups(); + $totalSize = array_sum(array_column($backups, 'size_raw')); + + $driver = DB::connection()->getDriverName(); + $tableNames = $this->getAllTableNames(); + $tableCount = count($tableNames); + + $dbSizeBytes = 0; + $databaseName = config('database.connections.' . config('database.default') . '.database', 'database'); + + if ($driver === 'mysql') { + $sizeResult = DB::selectOne(" + SELECT SUM(data_length + index_length) AS size + FROM information_schema.TABLES + WHERE table_schema = ? + ", [$databaseName]); + $dbSizeBytes = (int) ($sizeResult->size ?? 0); + } + + return [ + 'total_backups' => count($backups), + 'total_size_raw' => $totalSize, + 'total_size_human' => $this->formatBytes($totalSize), + 'database_name' => (string) $databaseName, + 'table_count' => $tableCount, + 'estimated_db_size_human' => $this->formatBytes($dbSizeBytes), + 'last_backup' => $backups[0] ?? null, + ]; + } + + /** + * Dapatkan daftar seluruh nama tabel aktif di database. + * + * @return array + */ + public function getAllTableNames(): array + { + $driver = DB::connection()->getDriverName(); + + if ($driver === 'sqlite') { + $rows = DB::select("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"); + return array_values(array_map(fn ($r) => $r->name, $rows)); + } + + // MySQL + $database = config('database.connections.' . config('database.default') . '.database'); + $tables = DB::select("SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'"); + $tableKey = "Tables_in_{$database}"; + + $names = []; + foreach ($tables as $tRow) { + $names[] = $tRow->$tableKey ?? current((array) $tRow); + } + + return $names; + } + + /** + * Dump struktur dan data satu tabel database. + */ + protected function dumpTableStructureAndData($handle, PDO $pdo, string $tableName, string $driver): void + { + fwrite($handle, "\n-- -------------------------------------------------------------\n"); + fwrite($handle, "-- Struktur Tabel untuk `{$tableName}`\n"); + fwrite($handle, "-- -------------------------------------------------------------\n"); + fwrite($handle, "DROP TABLE IF EXISTS `{$tableName}`;\n"); + + if ($driver === 'sqlite') { + $createResult = DB::selectOne("SELECT sql FROM sqlite_master WHERE type='table' AND name = ?", [$tableName]); + $createTableSql = $createResult->sql ?? ''; + } else { + $createResult = DB::selectOne("SHOW CREATE TABLE `{$tableName}`"); + $createSqlKey = 'Create Table'; + $createTableSql = $createResult->$createSqlKey ?? current((array) $createResult); + } + + if ($createTableSql) { + 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); + $totalRows = $query->count(); + + if ($totalRows === 0) { + fwrite($handle, "-- (Tabel kosong)\n\n"); + return; + } + + $query->orderBy(DB::raw('1'))->chunk(200, function ($rows) use ($handle, $pdo, $tableName) { + if ($rows->isEmpty()) return; + + $columns = array_keys((array) $rows->first()); + $escapedColumns = array_map(fn ($c) => "`{$c}`", $columns); + $columnsStr = implode(', ', $escapedColumns); + + fwrite($handle, "INSERT INTO `{$tableName}` ({$columnsStr}) VALUES\n"); + + $rowCount = count($rows); + $i = 0; + + foreach ($rows as $row) { + $i++; + $values = []; + + foreach ((array) $row as $val) { + if (is_null($val)) { + $values[] = 'NULL'; + } elseif (is_int($val) || is_float($val)) { + $values[] = (string) $val; + } elseif (is_bool($val)) { + $values[] = $val ? '1' : '0'; + } else { + $values[] = $pdo->quote((string) $val); + } + } + + $line = ' (' . implode(', ', $values) . ')'; + $line .= ($i === $rowCount) ? ";\n" : ",\n"; + fwrite($handle, $line); + } + }); + + fwrite($handle, "\n"); + } + + /** + * Format byte ke satuan yang mudah dibaca (KB, MB, GB). + */ + protected function formatBytes(int $bytes, int $precision = 2): string + { + if ($bytes <= 0) return '0 B'; + + $units = ['B', 'KB', 'MB', 'GB', 'TB']; + $power = min((int) floor(log($bytes, 1024)), count($units) - 1); + $size = $bytes / pow(1024, $power); + + return round($size, $precision) . ' ' . $units[$power]; + } +} diff --git a/config/rbac_permissions.php b/config/rbac_permissions.php index ec05dfc..7f56d89 100644 --- a/config/rbac_permissions.php +++ b/config/rbac_permissions.php @@ -54,6 +54,32 @@ return [ ], ], ], + 'backups' => [ + 'name' => 'Backup & Restore Sistem', + 'icon' => 'fa-solid fa-database', + 'permissions' => [ + 'backups.view' => [ + 'label' => 'Melihat Daftar Backup Sistem', + 'description' => 'Melihat daftar riwayat backup database dan file media di server.', + ], + 'backups.create' => [ + 'label' => 'Membuat File Backup Baru', + 'description' => 'Mencadangkan database SQL dan file media sistem secara manual.', + ], + 'backups.download' => [ + 'label' => 'Mengunduh File Backup', + 'description' => 'Mengunduh file arsip backup (.sql / .zip) ke komputer lokal.', + ], + 'backups.restore' => [ + 'label' => 'Memulihkan (Restore) Sistem', + 'description' => 'Melakukan pemulihan bencana (disaster recovery) database dan file media.', + ], + 'backups.delete' => [ + 'label' => 'Menghapus File Backup', + 'description' => 'Menghapus arsip backup lama dari media penyimpanan server.', + ], + ], + ], 'hse' => [ 'name' => 'Modul K3 / HSE (Karyawan & SIMPER)', 'icon' => 'fa-solid fa-id-card', diff --git a/resources/views/admin/backups/index.blade.php b/resources/views/admin/backups/index.blade.php new file mode 100644 index 0000000..74e983f --- /dev/null +++ b/resources/views/admin/backups/index.blade.php @@ -0,0 +1,580 @@ +@extends('layouts.app') + +@section('title', 'Backup & Restore Sistem - Super Admin RKM') + +@section('content') +
+ +
+
+

+ + Backup & Restore Sistem +

+

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

+
+
+ + +
+
+ + + @if(session('success')) +
+
+ + {{ session('success') }} +
+ +
+ @endif + + @if(session('error')) +
+
+ + {{ session('error') }} +
+ +
+ @endif + + +
+ +
+
+ Total File Backup + + + +
+ {{ number_format($stats['total_backups']) }} + Arsip tersimpan di server +
+ + +
+
+ Ukuran Arsip + + + +
+ {{ $stats['total_size_human'] }} + Kapasitas folder storage/app/backups +
+ + +
+
+ Backup Terakhir + + + +
+ + {{ $stats['last_backup']['created_at_human'] ?? 'Belum ada backup' }} + + + {{ $stats['last_backup']['filename'] ?? 'Klik Buat Backup Baru' }} + +
+ + +
+
+ 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 +
+
+ +
+ + + + + + + + + + + + @forelse($backups as $b) + @php + $isFull = ($b['type'] === 'full'); + @endphp + + + + + + + + + + + + + + + + + @empty + + + + @endforelse + +
Nama File BackupJenis BackupUkuran FileTanggal DibuatAksi & Pemulihan
+
+
+ @if($isFull) + + @else + + @endif +
+
+

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

+

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

+
+
+
+ @if($isFull) + + + Full Backup + Media + + @else + + + Database SQL + + @endif + + {{ $b['size_human'] }} + + {{ $b['created_at_human'] }} + {{ $b['created_at']->diffForHumans() }} + +
+ + + + + + + + + + + +
+
+
+ +
+

Belum Ada File Backup Tersimpan

+

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

+ +
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +@endsection diff --git a/resources/views/layouts/app.blade.php b/resources/views/layouts/app.blade.php index 3d49e85..3c244c4 100644 --- a/resources/views/layouts/app.blade.php +++ b/resources/views/layouts/app.blade.php @@ -248,6 +248,12 @@ Log Aktivitas Admin + + + + Backup & Restore + @endif @@ -630,6 +636,10 @@ Log Aktivitas Admin + + + Backup & Restore + @endif @@ -915,6 +925,10 @@ Kelola Pengguna @elseif(request()->routeIs('admin.roles.*')) Role & Permission + @elseif(request()->routeIs('admin.backups.*')) + Backup & Restore + @elseif(request()->routeIs('admin.activity_logs.*')) + Log Aktivitas Admin @elseif(request()->routeIs('hse.dashboard') || request()->routeIs('qma.dashboard')) Dashboard @elseif(request()->routeIs('hse.employees.*')) diff --git a/routes/web.php b/routes/web.php index 1d4a41a..070d28a 100644 --- a/routes/web.php +++ b/routes/web.php @@ -1,6 +1,7 @@ group(function () { // Log Riwayat Aktivitas Super Admin Route::get('/activity-logs', [AdminActivityLogController::class, 'index'])->name('activity_logs.index'); + + // Backup & Restore Sistem (Database & Media) + Route::get('/backups', [BackupController::class, 'index'])->name('backups.index'); + Route::post('/backups', [BackupController::class, 'store'])->name('backups.store'); + Route::get('/backups/{filename}/download', [BackupController::class, 'download'])->name('backups.download'); + Route::post('/backups/upload', [BackupController::class, 'upload'])->name('backups.upload'); + Route::post('/backups/{filename}/restore', [BackupController::class, 'restore'])->name('backups.restore'); + Route::delete('/backups/{filename}', [BackupController::class, 'destroy'])->name('backups.destroy'); }); }); diff --git a/tests/Feature/BackupAndRestoreTest.php b/tests/Feature/BackupAndRestoreTest.php new file mode 100644 index 0000000..41c502f --- /dev/null +++ b/tests/Feature/BackupAndRestoreTest.php @@ -0,0 +1,224 @@ + 'super_admin']); + $this->superAdmin = User::factory()->create([ + 'username' => 'superadmin_backup_test', + 'role' => 'super_admin', + 'password' => bcrypt('password123'), + ]); + $this->superAdmin->assignRole($role); + + $this->backupService = new DatabaseBackupService(); + } + + protected function tearDown(): void + { + // Bersihkan seluruh file uji coba di storage/app/backups + $dir = $this->backupService->getBackupDirectory(); + if (File::isDirectory($dir)) { + foreach (File::files($dir) as $f) { + if (str_starts_with($f->getFilename(), 'test_') || str_starts_with($f->getFilename(), 'backup_')) { + @unlink($f->getPathname()); + } + } + } + + parent::tearDown(); + } + + public function test_super_admin_can_access_backup_page(): void + { + $response = $this->actingAs($this->superAdmin) + ->get(route('admin.backups.index')); + + $response->assertStatus(200); + $response->assertViewIs('admin.backups.index'); + $response->assertViewHas('backups'); + $response->assertViewHas('stats'); + $response->assertSee('Backup & Restore Sistem'); + $response->assertSee('Buat Backup Baru'); + $response->assertSee('Unggah File Backup'); + } + + public function test_non_super_admin_cannot_access_backup_page(): void + { + $regularUser = User::factory()->create([ + 'username' => 'regular_user_test', + 'role' => 'employee', + ]); + $employeeRole = Role::firstOrCreate(['name' => 'employee']); + $regularUser->assignRole($employeeRole); + + $response = $this->actingAs($regularUser) + ->get(route('admin.backups.index')); + + $response->assertStatus(403); + } + + public function test_super_admin_can_create_database_backup(): void + { + $response = $this->actingAs($this->superAdmin) + ->post(route('admin.backups.store'), [ + 'type' => 'database', + ]); + + $response->assertSessionHas('success'); + $response->assertRedirect(); + + $backups = $this->backupService->listBackups(); + $this->assertNotEmpty($backups); + $this->assertEquals('database', $backups[0]['type']); + $this->assertStringEndsWith('.sql', $backups[0]['filename']); + + // Verifikasi log aktivitas + $this->assertDatabaseHas('admin_activity_logs', [ + 'action_type' => 'create', + 'module' => 'Backup & Restore', + 'user_id' => $this->superAdmin->id, + ]); + } + + public function test_super_admin_can_download_backup_file(): void + { + $filename = $this->backupService->createDatabaseBackup('test_dl.sql'); + + $response = $this->actingAs($this->superAdmin) + ->get(route('admin.backups.download', $filename)); + + $response->assertStatus(200); + $response->assertHeader('content-disposition'); + } + + public function test_super_admin_can_upload_backup_file(): void + { + $file = UploadedFile::fake()->createWithContent('test_uploaded_backup.sql', '-- MySQL dump test\nSET FOREIGN_KEY_CHECKS=0;\n'); + + $response = $this->actingAs($this->superAdmin) + ->post(route('admin.backups.upload'), [ + 'backup_file' => $file, + ]); + + $response->assertSessionHas('success'); + + $targetPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . 'test_uploaded_backup.sql'; + $this->assertTrue(File::exists($targetPath)); + + $this->assertDatabaseHas('admin_activity_logs', [ + 'action_type' => 'create', + 'module' => 'Backup & Restore', + 'target_name' => 'test_uploaded_backup.sql', + ]); + } + + public function test_restore_requires_valid_confirmation_or_password(): void + { + $filename = $this->backupService->createDatabaseBackup('test_for_restore.sql'); + + // Percobaan tanpa konfirmasi yang benar + $response = $this->actingAs($this->superAdmin) + ->post(route('admin.backups.restore', $filename), [ + 'confirmation' => 'SALAH', + 'password' => 'passwordsalah', + ]); + + $response->assertSessionHas('error'); + } + + public function test_super_admin_can_restore_from_backup_with_confirmation_string(): void + { + $filename = $this->backupService->createDatabaseBackup('test_real_restore.sql'); + + $response = $this->actingAs($this->superAdmin) + ->post(route('admin.backups.restore', $filename), [ + 'confirmation' => 'PULIHKAN', + ]); + + $response->assertSessionHas('success'); + + $this->assertDatabaseHas('admin_activity_logs', [ + 'action_type' => 'update', + 'module' => 'Backup & Restore', + 'target_name' => $filename, + ]); + } + + public function test_super_admin_can_delete_backup_file(): void + { + $filename = $this->backupService->createDatabaseBackup('test_to_delete.sql'); + $fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename; + $this->assertTrue(File::exists($fullPath)); + + $response = $this->actingAs($this->superAdmin) + ->delete(route('admin.backups.destroy', $filename)); + + $response->assertSessionHas('success'); + $this->assertFalse(File::exists($fullPath)); + + $this->assertDatabaseHas('admin_activity_logs', [ + 'action_type' => 'delete', + 'module' => 'Backup & Restore', + 'target_name' => $filename, + ]); + } + + public function test_super_admin_can_create_full_backup(): void + { + $response = $this->actingAs($this->superAdmin) + ->post(route('admin.backups.store'), [ + 'type' => 'full', + ]); + + $response->assertSessionHas('success'); + $response->assertRedirect(); + + $backups = $this->backupService->listBackups(); + $this->assertNotEmpty($backups); + $this->assertEquals('full', $backups[0]['type']); + $this->assertStringEndsWith('.zip', $backups[0]['filename']); + } + + public function test_super_admin_can_restore_from_backup_with_password(): void + { + $filename = $this->backupService->createDatabaseBackup('test_pwd_restore.sql'); + + $response = $this->actingAs($this->superAdmin) + ->post(route('admin.backups.restore', $filename), [ + 'password' => 'password123', + ]); + + $response->assertSessionHas('success'); + } + + public function test_cli_artisan_backup_create_command(): void + { + $this->artisan('backup:create', [ + '--type' => 'database', + '--filename' => 'test_cli_db.sql', + ])->assertSuccessful(); + + $fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . 'test_cli_db.sql'; + $this->assertTrue(File::exists($fullPath)); + } +}