From a32e9967805b74aa1c720cf7a5c4cf6b6d6efe8c Mon Sep 17 00:00:00 2001
From: Ray1111-aa
Date: Fri, 30 Oct 2026 10:29:04 +0700
Subject: [PATCH] feat(backup): add standalone in-portal .kmh converter to
Excel, CSV, and SQL with zero storage retention
---
.../Controllers/Admin/BackupController.php | 95 ++-
app/Services/KmhConverterService.php | 577 ++++++++++++++++++
app/Services/SimpleXlsxExporter.php | 5 +-
resources/views/admin/backups/index.blade.php | 407 ++++++++++++
routes/web.php | 2 +
tests/Feature/BackupConverterTest.php | 225 +++++++
6 files changed, 1308 insertions(+), 3 deletions(-)
create mode 100644 app/Services/KmhConverterService.php
create mode 100644 tests/Feature/BackupConverterTest.php
diff --git a/app/Http/Controllers/Admin/BackupController.php b/app/Http/Controllers/Admin/BackupController.php
index 465500d..1cc77e8 100644
--- a/app/Http/Controllers/Admin/BackupController.php
+++ b/app/Http/Controllers/Admin/BackupController.php
@@ -6,6 +6,8 @@ use App\Http\Controllers\Controller;
use App\Models\AdminActivityLog;
use App\Models\BackupLog;
use App\Services\DatabaseBackupService;
+use App\Services\KmhConverterService;
+use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
@@ -18,7 +20,8 @@ use Symfony\Component\HttpFoundation\BinaryFileResponse;
class BackupController extends Controller
{
public function __construct(
- protected DatabaseBackupService $backupService
+ protected DatabaseBackupService $backupService,
+ protected KmhConverterService $converterService
) {}
/**
@@ -409,4 +412,94 @@ class BackupController extends Controller
return back()->with('error', "File backup '{$filename}' tidak ditemukan di server atau sudah pernah dihapus.");
}
+
+ /**
+ * Periksa metadata & daftar tabel dari berkas .kmh yang diunggah dari komputer.
+ * Mengembalikan informasi file dan tabel dalam format JSON tanpa menyimpan data di server (0 Byte retained).
+ */
+ public function converterInspect(Request $request): JsonResponse
+ {
+ $request->validate([
+ 'backup_file' => 'required|file',
+ ]);
+
+ $file = $request->file('backup_file');
+ $originalName = $file->getClientOriginalName();
+
+ if (!str_ends_with(strtolower($originalName), '.kmh')) {
+ return response()->json([
+ 'success' => false,
+ 'message' => 'Berkas yang dipilih harus berekstensi .kmh.',
+ ], 422);
+ }
+
+ try {
+ $metadata = $this->converterService->inspectUploadedFile($file);
+
+ return response()->json([
+ 'success' => true,
+ 'data' => $metadata,
+ ]);
+ } catch (\Throwable $e) {
+ return response()->json([
+ 'success' => false,
+ 'message' => $e->getMessage(),
+ ], 422);
+ }
+ }
+
+ /**
+ * Konversi berkas .kmh yang diunggah ke format pilihan (xlsx, csv, sql) untuk tabel-tabel yang dicentang.
+ * Mengalirkan file hasil langsung ke browser dan segera menghapus semua file sementara (Zero Disk Retention).
+ */
+ public function converterExecute(Request $request): BinaryFileResponse|JsonResponse
+ {
+ $request->validate([
+ 'backup_file' => 'required|file',
+ 'tables' => 'required|array|min:1',
+ 'tables.*' => 'required|string',
+ 'format' => 'required|in:xlsx,csv,sql',
+ ]);
+
+ $file = $request->file('backup_file');
+ $selectedTables = $request->input('tables');
+ $format = $request->input('format');
+ $originalName = $file->getClientOriginalName();
+
+ if (!str_ends_with(strtolower($originalName), '.kmh')) {
+ return response()->json([
+ 'success' => false,
+ 'message' => 'Berkas yang dipilih harus berekstensi .kmh.',
+ ], 422);
+ }
+
+ try {
+ $result = $this->converterService->convertUploadedFile($file, $selectedTables, $format);
+
+ AdminActivityLog::record(
+ actionType: 'export',
+ module: 'Backup & Restore',
+ description: "Mengonversi arsip .kmh '{$originalName}' ke format " . strtoupper($format) . " untuk " . count($selectedTables) . " tabel.",
+ targetType: 'BackupFile',
+ targetName: $originalName
+ );
+
+ $workDir = $result['work_dir'];
+ register_shutdown_function(function () use ($workDir) {
+ if (is_dir($workDir)) {
+ File::deleteDirectory($workDir);
+ }
+ });
+
+ return response()->download($result['path'], $result['filename'], [
+ 'Content-Type' => $result['mime'],
+ 'Access-Control-Expose-Headers' => 'Content-Disposition',
+ ])->deleteFileAfterSend(true);
+ } catch (\Throwable $e) {
+ return response()->json([
+ 'success' => false,
+ 'message' => 'Gagal melakukan konversi arsip: ' . $e->getMessage(),
+ ], 422);
+ }
+ }
}
diff --git a/app/Services/KmhConverterService.php b/app/Services/KmhConverterService.php
new file mode 100644
index 0000000..b14a90d
--- /dev/null
+++ b/app/Services/KmhConverterService.php
@@ -0,0 +1,577 @@
+,
+ * database: string,
+ * has_media: bool
+ * }
+ */
+ public function inspectUploadedFile(UploadedFile $file): array
+ {
+ $realPath = $file->getRealPath();
+ if (!$realPath || !is_file($realPath)) {
+ throw new RuntimeException("Berkas unggahan tidak ditemukan atau korup.");
+ }
+
+ $kmhContent = file_get_contents($realPath);
+ if ($kmhContent === false) {
+ throw new RuntimeException("Gagal membaca berkas .kmh yang diunggah.");
+ }
+
+ // Dekripsi arsip .kmh menggunakan kunci sistem
+ $decryptedZipContent = $this->backupService->decryptFromKmh($kmhContent);
+ unset($kmhContent);
+
+ $tempZipPath = storage_path('app/temp_inspect_' . uniqid() . '.zip');
+ file_put_contents($tempZipPath, $decryptedZipContent);
+ unset($decryptedZipContent);
+
+ $zip = new ZipArchive();
+ if ($zip->open($tempZipPath) !== true) {
+ @unlink($tempZipPath);
+ throw new RuntimeException("Konten terdekripsi bukan merupakan arsip ZIP yang sah.");
+ }
+
+ try {
+ $manifestJson = $zip->getFromName('manifest.json');
+ $manifest = $manifestJson ? json_decode($manifestJson, true) : [];
+
+ $tables = $manifest['tables'] ?? [];
+
+ // Jika manifest tidak memiliki daftar tabel, baca cepat dari struktur database.sql
+ if (empty($tables)) {
+ $sqlContent = $zip->getFromName('database.sql');
+ if ($sqlContent) {
+ preg_match_all('/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?`?([a-zA-Z0-9_]+)`?/i', $sqlContent, $matches);
+ $tables = array_values(array_unique($matches[1] ?? []));
+ }
+ }
+
+ sort($tables);
+
+ $createdAt = isset($manifest['created_at'])
+ ? Carbon::parse($manifest['created_at'])
+ : Carbon::createFromTimestamp($file->getMTime());
+
+ return [
+ 'filename' => $file->getClientOriginalName(),
+ 'size_human' => $this->backupService->formatBytes($file->getSize()),
+ 'created_at_human' => $createdAt->translatedFormat('d F Y, H:i') . ' WIB',
+ 'created_at_diff' => $createdAt->diffForHumans(),
+ 'table_count' => count($tables),
+ 'tables' => $tables,
+ 'database' => $manifest['database'] ?? 'rkm_kmh',
+ 'has_media' => (bool) ($manifest['has_media'] ?? false),
+ ];
+ } finally {
+ $zip->close();
+ if (is_file($tempZipPath)) {
+ @unlink($tempZipPath);
+ }
+ }
+ }
+
+ /**
+ * Konversi berkas .kmh yang diunggah ke format pilihan (xlsx, csv, sql) untuk tabel-tabel terpilih.
+ *
+ * @param UploadedFile $file
+ * @param array $selectedTables
+ * @param string $format 'xlsx' | 'csv' | 'sql'
+ * @return array{
+ * path: string,
+ * filename: string,
+ * mime: string,
+ * work_dir: string
+ * }
+ */
+ public function convertUploadedFile(UploadedFile $file, array $selectedTables, string $format): array
+ {
+ $realPath = $file->getRealPath();
+ if (!$realPath || !is_file($realPath)) {
+ throw new RuntimeException("Berkas unggahan tidak ditemukan.");
+ }
+
+ if (empty($selectedTables)) {
+ throw new RuntimeException("Silakan pilih minimal 1 tabel untuk dikonversi.");
+ }
+
+ $format = strtolower($format);
+ if (!in_array($format, ['xlsx', 'csv', 'sql'], true)) {
+ throw new RuntimeException("Format konversi tidak didukung: {$format}");
+ }
+
+ $workDir = storage_path('app/temp_kmh_conv_' . uniqid());
+ File::ensureDirectoryExists($workDir);
+
+ $tempZipPath = $workDir . '/package.zip';
+ $sqlPath = $workDir . '/database.sql';
+
+ try {
+ // 1. Dekripsi payload .kmh
+ $kmhContent = file_get_contents($realPath);
+ $decryptedZipContent = $this->backupService->decryptFromKmh($kmhContent);
+ unset($kmhContent);
+
+ file_put_contents($tempZipPath, $decryptedZipContent);
+ unset($decryptedZipContent);
+
+ // 2. Ekstrak database.sql saja
+ $zip = new ZipArchive();
+ if ($zip->open($tempZipPath) !== true) {
+ throw new RuntimeException("Gagal membuka arsip kontainer backup.");
+ }
+
+ $zip->extractTo($workDir, ['database.sql']);
+ $zip->close();
+ @unlink($tempZipPath);
+
+ if (!is_file($sqlPath)) {
+ throw new RuntimeException("Berkas database.sql tidak ditemukan di dalam arsip .kmh.");
+ }
+
+ $timestamp = now()->format('Ymd_His');
+
+ // 3. Proses berdasarkan format
+ if ($format === 'sql') {
+ $outputFilename = 'Arsip_KMH_SQL_' . $timestamp . '.sql';
+ $outputPath = $workDir . '/' . $outputFilename;
+ $this->extractFilteredSql($sqlPath, $selectedTables, $outputPath);
+ @unlink($sqlPath);
+
+ return [
+ 'path' => $outputPath,
+ 'filename' => $outputFilename,
+ 'mime' => 'application/sql',
+ 'work_dir' => $workDir,
+ ];
+ }
+
+ // Ekstrak data tabel ke bentuk CSV sementara di disk
+ $csvDir = $workDir . '/csv_tables';
+ File::ensureDirectoryExists($csvDir);
+ $extractedTables = $this->streamSqlToCsvFiles($sqlPath, $selectedTables, $csvDir);
+ @unlink($sqlPath);
+
+ if ($format === 'csv') {
+ $outputFilename = 'Arsip_KMH_CSV_' . $timestamp . '.zip';
+ $outputPath = $workDir . '/' . $outputFilename;
+
+ $zipOut = new ZipArchive();
+ if ($zipOut->open($outputPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
+ throw new RuntimeException("Gagal membuat arsip ZIP untuk file CSV.");
+ }
+
+ foreach ($extractedTables as $tbl => $csvFile) {
+ if (is_file($csvFile)) {
+ $zipOut->addFile($csvFile, $tbl . '.csv');
+ }
+ }
+ $zipOut->close();
+ File::deleteDirectory($csvDir);
+
+ return [
+ 'path' => $outputPath,
+ 'filename' => $outputFilename,
+ 'mime' => 'application/zip',
+ 'work_dir' => $workDir,
+ ];
+ }
+
+ // Format XLSX
+ if (count($selectedTables) === 1) {
+ // Single table -> langsung 1 file .xlsx
+ $tbl = $selectedTables[0];
+ $outputFilename = 'Tabel_' . $tbl . '_' . $timestamp . '.xlsx';
+ $outputPath = $workDir . '/' . $outputFilename;
+
+ $csvFile = $csvDir . '/' . $tbl . '.csv';
+ $this->convertCsvToXlsx($csvFile, $tbl, $outputPath);
+ File::deleteDirectory($csvDir);
+
+ return [
+ 'path' => $outputPath,
+ 'filename' => $outputFilename,
+ 'mime' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ 'work_dir' => $workDir,
+ ];
+ } else {
+ // Multiple tables -> dikemas dalam 1 file .zip berisi masing-masing .xlsx
+ $outputFilename = 'Arsip_KMH_Excel_' . $timestamp . '.zip';
+ $outputPath = $workDir . '/' . $outputFilename;
+
+ $zipOut = new ZipArchive();
+ if ($zipOut->open($outputPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
+ throw new RuntimeException("Gagal membuat paket ZIP Excel.");
+ }
+
+ foreach ($extractedTables as $tbl => $csvFile) {
+ if (is_file($csvFile)) {
+ $tblXlsxPath = $workDir . '/' . $tbl . '.xlsx';
+ $this->convertCsvToXlsx($csvFile, $tbl, $tblXlsxPath);
+ $zipOut->addFile($tblXlsxPath, $tbl . '.xlsx');
+ }
+ }
+ $zipOut->close();
+ File::deleteDirectory($csvDir);
+
+ return [
+ 'path' => $outputPath,
+ 'filename' => $outputFilename,
+ 'mime' => 'application/zip',
+ 'work_dir' => $workDir,
+ ];
+ }
+ } catch (\Throwable $e) {
+ $this->cleanDirectory($workDir);
+ throw $e;
+ }
+ }
+
+ /**
+ * Memfilter isi database.sql hanya untuk tabel terpilih dan menulis ke file output SQL.
+ */
+ protected function extractFilteredSql(string $inputSqlPath, array $selectedTables, string $outputSqlPath): void
+ {
+ $inHandle = fopen($inputSqlPath, 'r');
+ $outHandle = fopen($outputSqlPath, 'w');
+
+ if (!$inHandle || !$outHandle) {
+ if ($inHandle) fclose($inHandle);
+ if ($outHandle) fclose($outHandle);
+ throw new RuntimeException("Gagal membuka berkas SQL untuk operasi filter.");
+ }
+
+ try {
+ $nowStr = now()->format('Y-m-d H:i:s');
+ $tablesStr = implode(', ', $selectedTables);
+ fwrite($outHandle, "-- ==============================================================\n");
+ fwrite($outHandle, "-- RKM-KMH SECURE DATABASE DUMP - HASIL FILTER KONVERSI\n");
+ fwrite($outHandle, "-- Waktu Ekstrak : {$nowStr} WIB\n");
+ fwrite($outHandle, "-- Tabel Terpilih: {$tablesStr}\n");
+ fwrite($outHandle, "-- ==============================================================\n\n");
+ fwrite($outHandle, "SET NAMES utf8mb4;\n");
+ fwrite($outHandle, "SET FOREIGN_KEY_CHECKS = 0;\n\n");
+
+ $selectedMap = array_fill_keys($selectedTables, true);
+ $currentTable = null;
+ $writing = false;
+
+ while (($line = fgets($inHandle)) !== false) {
+ // Deteksi nama tabel pada komentar, DROP TABLE, CREATE TABLE, atau INSERT INTO
+ if (preg_match('/(?:DROP\s+TABLE\s+IF\s+EXISTS|CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?|INSERT\s+INTO)\s+`?([a-zA-Z0-9_]+)`?/i', $line, $m)) {
+ $tbl = $m[1];
+ $currentTable = $tbl;
+ $writing = isset($selectedMap[$tbl]);
+ } elseif (preg_match('/^--\s+(?:Struktur|Dumping\s+Data)\s+untuk\s+`?([a-zA-Z0-9_]+)`?/i', $line, $m)) {
+ $tbl = $m[1];
+ $currentTable = $tbl;
+ $writing = isset($selectedMap[$tbl]);
+ }
+
+ if ($writing) {
+ fwrite($outHandle, $line);
+ }
+ }
+
+ fwrite($outHandle, "\nSET FOREIGN_KEY_CHECKS = 1;\n");
+ fwrite($outHandle, "-- END OF FILTERED DUMP\n");
+ } finally {
+ fclose($inHandle);
+ fclose($outHandle);
+ }
+ }
+
+ /**
+ * Membaca stream SQL dan mengekstrak tabel-tabel yang dipilih ke file CSV terpisah.
+ * Sangat hemat memori (RAM usage < 5MB).
+ *
+ * @return array Map tableName => csvFilePath
+ */
+ protected function streamSqlToCsvFiles(string $sqlPath, array $selectedTables, string $csvOutputDir): array
+ {
+ $handle = fopen($sqlPath, 'r');
+ if (!$handle) {
+ throw new RuntimeException("Gagal membuka file database.sql untuk pembacaan stream.");
+ }
+
+ $selectedMap = array_fill_keys($selectedTables, true);
+ $csvHandles = [];
+ $headerWritten = [];
+ $activeTable = null;
+ $activeColumns = [];
+
+ try {
+ while (($line = fgets($handle)) !== false) {
+ $trimmed = trim($line);
+ if ($trimmed === '' || str_starts_with($trimmed, '--') || str_starts_with($trimmed, '/*')) {
+ continue;
+ }
+
+ // Cek baris INSERT INTO `tableName` (`col1`, `col2`, ...) VALUES
+ if (preg_match('/^INSERT\s+INTO\s+`?([a-zA-Z0-9_]+)`?\s*(?:\(([^)]+)\))?\s*VALUES/i', $trimmed, $m)) {
+ $tbl = $m[1];
+ if (isset($selectedMap[$tbl])) {
+ $activeTable = $tbl;
+ if (!isset($csvHandles[$tbl])) {
+ $csvPath = $csvOutputDir . '/' . $tbl . '.csv';
+ $csvHandles[$tbl] = fopen($csvPath, 'w');
+ // Tulis UTF-8 BOM agar Excel membukanya dengan karakter yang sempurna
+ fwrite($csvHandles[$tbl], "\xEF\xBB\xBF");
+ }
+
+ if (!empty($m[2]) && empty($headerWritten[$tbl])) {
+ preg_match_all('/`?([a-zA-Z0-9_]+)`?/', $m[2], $colMatches);
+ $activeColumns = array_values(array_filter(array_map('trim', $colMatches[1] ?? [])));
+ if (!empty($activeColumns)) {
+ fputcsv($csvHandles[$tbl], $activeColumns);
+ $headerWritten[$tbl] = true;
+ }
+ }
+ } else {
+ $activeTable = null;
+ }
+ continue;
+ }
+
+ // Jika sedang membaca baris data dari activeTable
+ if ($activeTable && isset($csvHandles[$activeTable])) {
+ $tuples = $this->extractTuplesFromSqlLine($trimmed);
+ foreach ($tuples as $tupleStr) {
+ $values = $this->parseTupleValues($tupleStr);
+ fputcsv($csvHandles[$activeTable], $values);
+ }
+
+ if (str_ends_with($trimmed, ';')) {
+ $activeTable = null;
+ }
+ }
+ }
+
+ // Pastikan semua tabel terpilih memiliki file CSV, meskipun kosong
+ foreach ($selectedTables as $tbl) {
+ if (!isset($csvHandles[$tbl])) {
+ $csvPath = $csvOutputDir . '/' . $tbl . '.csv';
+ $h = fopen($csvPath, 'w');
+ fwrite($h, "\xEF\xBB\xBF");
+ fputcsv($h, ['(Tabel kosong / Tidak ada data)']);
+ fclose($h);
+ }
+ }
+ } finally {
+ fclose($handle);
+ foreach ($csvHandles as $h) {
+ if (is_resource($h)) fclose($h);
+ }
+ }
+
+ $result = [];
+ foreach ($selectedTables as $tbl) {
+ $csvPath = $csvOutputDir . '/' . $tbl . '.csv';
+ if (is_file($csvPath)) {
+ $result[$tbl] = $csvPath;
+ }
+ }
+
+ return $result;
+ }
+
+ /**
+ * Mengonversi berkas CSV tabel menjadi berkas OpenXML .xlsx menggunakan SimpleXlsxExporter.
+ */
+ protected function convertCsvToXlsx(string $csvPath, string $tableName, string $targetXlsxPath): void
+ {
+ if (!is_file($csvPath)) {
+ return;
+ }
+
+ $h = fopen($csvPath, 'r');
+ if (!$h) return;
+
+ // Skip UTF-8 BOM jika ada
+ $bom = fread($h, 3);
+ if ($bom !== "\xEF\xBB\xBF") {
+ rewind($h);
+ }
+
+ $headers = [];
+ $rows = [];
+ $rowCount = 0;
+
+ $firstRow = fgetcsv($h);
+ if ($firstRow && !empty($firstRow)) {
+ $headerMap = [];
+ foreach ($firstRow as $idx => $colName) {
+ $headerMap[$colName ?: ('Kolom_' . ($idx + 1))] = 18;
+ }
+ $headers = $headerMap;
+
+ // Baca baris data (maksimal 50.000 baris untuk kenyamanan memori sheet tunggal)
+ while (($row = fgetcsv($h)) !== false && $rowCount < 50000) {
+ $rowCount++;
+ $rows[] = $row;
+ }
+ }
+ fclose($h);
+
+ if (empty($headers)) {
+ $headers = ['Kolom' => 20];
+ $rows = [['(Tabel kosong)']];
+ }
+
+ $title = 'DATA ARSIP TABEL: ' . strtoupper($tableName);
+ $metaLines = [
+ 'Total Data: ' . count($rows) . ' Baris Data',
+ 'Diekstrak dari Arsip .kmh pada: ' . now()->translatedFormat('d F Y, H:i') . ' WIB',
+ ];
+
+ $xlsxBinary = SimpleXlsxExporter::create($title, $metaLines, $headers, $rows, [], $tableName);
+ file_put_contents($targetXlsxPath, $xlsxBinary);
+ }
+
+ /**
+ * Ekstrak potongan tuple tuple '(val1, val2, ...)' dari satu baris SQL.
+ *
+ * @return array
+ */
+ protected function extractTuplesFromSqlLine(string $content): array
+ {
+ $tuples = [];
+ $inQuotes = false;
+ $quoteChar = "'";
+ $inTuple = false;
+ $tupleBuffer = '';
+ $len = strlen($content);
+
+ for ($i = 0; $i < $len; $i++) {
+ $c = $content[$i];
+
+ if ($inQuotes) {
+ $tupleBuffer .= $c;
+ if ($c === '\\') {
+ $i++;
+ if ($i < $len) {
+ $tupleBuffer .= $content[$i];
+ }
+ } elseif ($c === $quoteChar) {
+ if ($i + 1 < $len && $content[$i + 1] === $quoteChar) {
+ $tupleBuffer .= $content[$i + 1];
+ $i++;
+ } else {
+ $inQuotes = false;
+ }
+ }
+ } else {
+ if ($c === "'" || $c === '"') {
+ $inQuotes = true;
+ $quoteChar = $c;
+ if ($inTuple) {
+ $tupleBuffer .= $c;
+ }
+ } elseif ($c === '(') {
+ $inTuple = true;
+ $tupleBuffer = '';
+ } elseif ($c === ')' && $inTuple) {
+ $inTuple = false;
+ $tuples[] = $tupleBuffer;
+ $tupleBuffer = '';
+ } elseif ($inTuple) {
+ $tupleBuffer .= $c;
+ }
+ }
+ }
+
+ return $tuples;
+ }
+
+ /**
+ * Parsing nilai-nilai di dalam satu tuple SQL menjadi array PHP yang bersih.
+ *
+ * @return array
+ */
+ protected function parseTupleValues(string $tupleStr): array
+ {
+ $values = [];
+ $len = strlen($tupleStr);
+ $inQuotes = false;
+ $curr = '';
+ $quoteChar = "'";
+
+ for ($i = 0; $i < $len; $i++) {
+ $char = $tupleStr[$i];
+
+ if ($inQuotes) {
+ if ($char === '\\') {
+ $next = $tupleStr[$i + 1] ?? '';
+ $curr .= match($next) {
+ 'n' => "\n",
+ 'r' => "\r",
+ 't' => "\t",
+ "'" => "'",
+ '"' => '"',
+ '\\' => '\\',
+ default => $next
+ };
+ $i++;
+ } elseif ($char === $quoteChar) {
+ if (($tupleStr[$i + 1] ?? '') === $quoteChar) {
+ $curr .= $quoteChar;
+ $i++;
+ } else {
+ $inQuotes = false;
+ }
+ } else {
+ $curr .= $char;
+ }
+ } else {
+ if ($char === "'" || $char === '"') {
+ $inQuotes = true;
+ $quoteChar = $char;
+ } elseif ($char === ',') {
+ $val = trim($curr);
+ $values[] = (strcasecmp($val, 'NULL') === 0) ? null : $val;
+ $curr = '';
+ } else {
+ $curr .= $char;
+ }
+ }
+ }
+
+ $val = trim($curr);
+ $values[] = (strcasecmp($val, 'NULL') === 0) ? null : $val;
+
+ return $values;
+ }
+
+ /**
+ * Hapus direktori kerja sementara secara menyeluruh.
+ */
+ public function cleanDirectory(?string $directory): void
+ {
+ if ($directory && File::isDirectory($directory)) {
+ File::deleteDirectory($directory);
+ }
+ }
+}
diff --git a/app/Services/SimpleXlsxExporter.php b/app/Services/SimpleXlsxExporter.php
index 7d846b3..07dd28c 100644
--- a/app/Services/SimpleXlsxExporter.php
+++ b/app/Services/SimpleXlsxExporter.php
@@ -16,7 +16,7 @@ class SimpleXlsxExporter
* @param array $alignments Optional per-column alignment: 'center' or 'left'
* @return string Raw zip content
*/
- public static function create(string $title, array $metaLines, array $headers, array $rows, array $alignments = []): string
+ public static function create(string $title, array $metaLines, array $headers, array $rows, array $alignments = [], ?string $sheetName = null): string
{
$numCols = count($headers);
$lastColLetter = self::colLetter($numCols);
@@ -143,10 +143,11 @@ class SimpleXlsxExporter
';
+ $cleanSheetName = htmlspecialchars(mb_substr($sheetName ?: 'Data', 0, 31), ENT_XML1);
$workbookXml = '
-
+
';
diff --git a/resources/views/admin/backups/index.blade.php b/resources/views/admin/backups/index.blade.php
index 5719bdd..5f66332 100644
--- a/resources/views/admin/backups/index.blade.php
+++ b/resources/views/admin/backups/index.blade.php
@@ -15,6 +15,11 @@
+
+ Konversi Berkas .kmh
+
@@ -632,6 +637,163 @@
+
+
+
+
+
+
+
+
+
+ KMH CONVERTER
+
+
+
Konversi Berkas .kmh ke Excel / CSV / SQL
+
Unggah berkas .kmh dari komputer untuk dikonversi menjadi format siap olah tanpa menyentuh database aktif.
+
+
+
×
+
+
+
+
+
+
+
+ Keamanan Total & Bebas Kapasitas Server:
+ Proses konversi bersifat read-only dan sama sekali tidak menyentuh database aktif MySQL . Berkas yang diunggah hanya diproses sementara di memori dan langsung dihapus otomatis seketika setelah unduhan dimulai (0 Byte tertinggal di VPS).
+
+
+
+
+
+
+
+
+
+
+
+
Tarik & Letakkan berkas .kmh di sini
+
atau klik untuk memilih dari komputer Anda
+
Mendukung berkas arsip .kmh terenkripsi (Maks. 500 MB)
+
+
+
+
+
+
+
+
Mendekripsi & memeriksa integritas berkas .kmh...
+
Verifikasi tanda tangan HMAC SHA-256 & membaca daftar tabel
+
+
+
+
+
+
+
+ Nama Berkas
+ -
+
+
+ Ukuran Arsip
+ -
+
+
+ Tanggal Dibuat
+ -
+
+
+ Database Asal
+ -
+
+
+
+
+
+
Pilih Format Hasil Konversi:
+
+
+
+
+
+
+
+
+ Pilih Tabel yang Ingin Dikonversi:
+
+
+ Terpilih: 0 dari 0 tabel
+
+
+
+
+
+ Pilih Semua
+
+
+ Bersihkan
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Ganti Berkas .kmh
+
+
+ Mulai Konversi & Unduh
+
+
+
+
+
+
+
+ Tutup
+
+
+
+
+
@if(session('auto_download'))
@endsection
diff --git a/routes/web.php b/routes/web.php
index 3d5648b..7d1d548 100644
--- a/routes/web.php
+++ b/routes/web.php
@@ -219,6 +219,8 @@ Route::middleware('auth')->group(function () {
Route::get('/backups', [BackupController::class, 'index'])->name('backups.index');
Route::post('/backups', [BackupController::class, 'store'])->name('backups.store');
Route::post('/backups/restore-file', [BackupController::class, 'restoreFromFile'])->name('backups.restore_file')->middleware('throttle:5,1');
+ Route::post('/backups/converter/inspect', [BackupController::class, 'converterInspect'])->name('backups.converter.inspect');
+ Route::post('/backups/converter/execute', [BackupController::class, 'converterExecute'])->name('backups.converter.execute');
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')->middleware('throttle:5,1');
diff --git a/tests/Feature/BackupConverterTest.php b/tests/Feature/BackupConverterTest.php
new file mode 100644
index 0000000..0f0d8f2
--- /dev/null
+++ b/tests/Feature/BackupConverterTest.php
@@ -0,0 +1,225 @@
+ 'super_admin']);
+ $this->superAdmin = User::factory()->create([
+ 'username' => 'superadmin_conv_test',
+ 'role' => 'super_admin',
+ 'password' => bcrypt('password123'),
+ ]);
+ $this->superAdmin->assignRole($role);
+
+ $this->backupService = new DatabaseBackupService();
+ }
+
+ protected function tearDown(): void
+ {
+ $dir = $this->backupService->getBackupDirectory();
+ if (File::isDirectory($dir)) {
+ foreach (File::files($dir) as $f) {
+ if (str_starts_with($f->getFilename(), 'test_conv_')) {
+ @unlink($f->getPathname());
+ }
+ }
+ }
+
+ parent::tearDown();
+ }
+
+ protected function createSampleKmhFile(string $name = 'test_conv_sample.kmh'): UploadedFile
+ {
+ $filename = $this->backupService->createKmhBackup(['users', 'roles'], false, $name);
+ $fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename;
+ $content = file_get_contents($fullPath);
+ @unlink($fullPath);
+
+ return UploadedFile::fake()->createWithContent($name, $content);
+ }
+
+ public function test_super_admin_can_inspect_uploaded_kmh_backup(): void
+ {
+ $uploadedFile = $this->createSampleKmhFile('test_conv_inspect.kmh');
+
+ $response = $this->actingAs($this->superAdmin)
+ ->postJson(route('admin.backups.converter.inspect'), [
+ 'backup_file' => $uploadedFile,
+ ]);
+
+ $response->assertStatus(200);
+ $response->assertJson([
+ 'success' => true,
+ 'data' => [
+ 'filename' => 'test_conv_inspect.kmh',
+ ],
+ ]);
+
+ $this->assertContains('users', $response->json('data.tables'));
+ $this->assertContains('roles', $response->json('data.tables'));
+ }
+
+ public function test_inspect_rejects_non_kmh_file(): void
+ {
+ $fakeFile = UploadedFile::fake()->create('document.pdf', 100);
+
+ $response = $this->actingAs($this->superAdmin)
+ ->postJson(route('admin.backups.converter.inspect'), [
+ 'backup_file' => $fakeFile,
+ ]);
+
+ $response->assertStatus(422);
+ $response->assertJson([
+ 'success' => false,
+ 'message' => 'Berkas yang dipilih harus berekstensi .kmh.',
+ ]);
+ }
+
+ public function test_inspect_rejects_corrupted_kmh_content(): void
+ {
+ $corruptFile = UploadedFile::fake()->createWithContent('corrupted.kmh', "KMH_ENCRYPTED_BACKUP_V1\nCorruptedHMACandPayload12345");
+
+ $response = $this->actingAs($this->superAdmin)
+ ->postJson(route('admin.backups.converter.inspect'), [
+ 'backup_file' => $corruptFile,
+ ]);
+
+ $response->assertStatus(422);
+ $response->assertJson([
+ 'success' => false,
+ ]);
+ }
+
+ public function test_super_admin_can_convert_single_table_to_xlsx(): void
+ {
+ $uploadedFile = $this->createSampleKmhFile('test_conv_single.kmh');
+
+ $response = $this->actingAs($this->superAdmin)
+ ->post(route('admin.backups.converter.execute'), [
+ 'backup_file' => $uploadedFile,
+ 'tables' => ['users'],
+ 'format' => 'xlsx',
+ ]);
+
+ $response->assertStatus(200);
+ $response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
+ $disposition = $response->headers->get('Content-Disposition');
+ $this->assertStringContainsString('Tabel_users_', $disposition);
+ $this->assertStringEndsWith('.xlsx', $disposition);
+ }
+
+ public function test_super_admin_can_convert_multiple_tables_to_xlsx_zip(): void
+ {
+ $uploadedFile = $this->createSampleKmhFile('test_conv_multi_xlsx.kmh');
+
+ $response = $this->actingAs($this->superAdmin)
+ ->post(route('admin.backups.converter.execute'), [
+ 'backup_file' => $uploadedFile,
+ 'tables' => ['users', 'roles'],
+ 'format' => 'xlsx',
+ ]);
+
+ $response->assertStatus(200);
+ $response->assertHeader('Content-Type', 'application/zip');
+ $disposition = $response->headers->get('Content-Disposition');
+ $this->assertStringContainsString('Arsip_KMH_Excel_', $disposition);
+ $this->assertStringEndsWith('.zip', $disposition);
+ }
+
+ public function test_super_admin_can_convert_tables_to_csv_zip(): void
+ {
+ $uploadedFile = $this->createSampleKmhFile('test_conv_csv.kmh');
+
+ $response = $this->actingAs($this->superAdmin)
+ ->post(route('admin.backups.converter.execute'), [
+ 'backup_file' => $uploadedFile,
+ 'tables' => ['users', 'roles'],
+ 'format' => 'csv',
+ ]);
+
+ $response->assertStatus(200);
+ $response->assertHeader('Content-Type', 'application/zip');
+ $disposition = $response->headers->get('Content-Disposition');
+ $this->assertStringContainsString('Arsip_KMH_CSV_', $disposition);
+ $this->assertStringEndsWith('.zip', $disposition);
+ }
+
+ public function test_super_admin_can_convert_tables_to_sql(): void
+ {
+ $uploadedFile = $this->createSampleKmhFile('test_conv_sql.kmh');
+
+ $response = $this->actingAs($this->superAdmin)
+ ->post(route('admin.backups.converter.execute'), [
+ 'backup_file' => $uploadedFile,
+ 'tables' => ['users'],
+ 'format' => 'sql',
+ ]);
+
+ $response->assertStatus(200);
+ $response->assertHeader('Content-Type', 'application/sql');
+ $disposition = $response->headers->get('Content-Disposition');
+ $this->assertStringContainsString('Arsip_KMH_SQL_', $disposition);
+ $this->assertStringEndsWith('.sql', $disposition);
+ }
+
+ public function test_convert_validates_required_fields(): void
+ {
+ $uploadedFile = $this->createSampleKmhFile('test_conv_val.kmh');
+
+ // Tanpa tabel
+ $response1 = $this->actingAs($this->superAdmin)
+ ->postJson(route('admin.backups.converter.execute'), [
+ 'backup_file' => $uploadedFile,
+ 'tables' => [],
+ 'format' => 'xlsx',
+ ]);
+ $response1->assertStatus(422);
+
+ // Format tidak valid
+ $response2 = $this->actingAs($this->superAdmin)
+ ->postJson(route('admin.backups.converter.execute'), [
+ 'backup_file' => $uploadedFile,
+ 'tables' => ['users'],
+ 'format' => 'invalid_format',
+ ]);
+ $response2->assertStatus(422);
+ }
+
+ public function test_active_database_remains_unaffected_after_conversion(): void
+ {
+ $initialUserCount = User::count();
+ $this->assertGreaterThan(0, $initialUserCount);
+
+ $uploadedFile = $this->createSampleKmhFile('test_conv_safety.kmh');
+
+ $response = $this->actingAs($this->superAdmin)
+ ->post(route('admin.backups.converter.execute'), [
+ 'backup_file' => $uploadedFile,
+ 'tables' => ['users'],
+ 'format' => 'xlsx',
+ ]);
+
+ $response->assertStatus(200);
+
+ // Pastikan jumlah user di database aktif tetap sama persis
+ $this->assertEquals($initialUserCount, User::count());
+ }
+}