[--apply] // // Ohne --apply wird nur geprüft und berichtet, es wird nichts geschrieben. // // Verhalten: // - Zuordnung über user_id, zusätzlich wird die E-Mail-Adresse verglichen. // - Leere Felder werden gefüllt; bereits gesetzte Werte werden nicht // überschrieben (der neuere Stand in der App gewinnt). // - IBANs werden mit dem Schlüssel aus IBAN_KEY verschlüsselt (App\Core\Crypto). // - Ist IBAN_KEY_OLD gesetzt, werden vorhandene, noch mit dem alten Schlüssel // verschlüsselte IBANs auf den neuen Schlüssel umgeschlüsselt. // // Beispiel (Live, Schlüsselwechsel + Import): // docker compose exec -T \ // -e DB_HOST=... -e DB_USER=... -e DB_PASS=... -e DB_NEW_NAME=... \ // -e IBAN_KEY="" -e IBAN_KEY_OLD="" \ // app php import_accounts.php export_kontodaten_20261023_130939.csv --apply $apply = false; $csvPath = null; foreach (array_slice($argv, 1) as $arg) { if ($arg === '--apply') { $apply = true; } elseif ($arg === '--help' || $arg === '-h') { echo "Aufruf: php import_accounts.php [--apply]\n"; exit(0); } elseif ($csvPath === null) { $csvPath = $arg; } else { fwrite(STDERR, "Unbekanntes Argument: $arg\n"); exit(1); } } if ($csvPath === null) { $candidates = glob(__DIR__ . '/export_kontodaten_*.csv') ?: []; sort($candidates); $csvPath = end($candidates) ?: null; } if ($csvPath === null || !is_file($csvPath)) { fwrite(STDERR, "Fehler: CSV-Datei nicht gefunden.\n"); exit(1); } $host = getenv('DB_HOST') ?: '127.0.0.1'; $port = (int)(getenv('DB_PORT') ?: 3306); $user = getenv('DB_USER') ?: 'root'; $pass = getenv('DB_PASS') ?: ''; $dbName = getenv('DB_NEW_NAME') ?: 'tippspiel2027'; // Crypto-Klasse laden (funktioniert im Container und direkt auf dem Host). $cryptoCandidates = [ __DIR__ . '/../tippspiel/src/Core/Crypto.php', __DIR__ . '/src/Core/Crypto.php', ]; $cryptoFile = null; foreach ($cryptoCandidates as $candidate) { if (file_exists($candidate)) { $cryptoFile = $candidate; break; } } if ($cryptoFile === null) { die("Fehler: Crypto.php nicht gefunden.\n"); } require_once $cryptoFile; $ibanCandidates = [ __DIR__ . '/../tippspiel/src/Core/Iban.php', __DIR__ . '/src/Core/Iban.php', ]; $ibanFile = null; foreach ($ibanCandidates as $candidate) { if (file_exists($candidate)) { $ibanFile = $candidate; break; } } if ($ibanFile === null) { die("Fehler: Iban.php nicht gefunden.\n"); } require_once $ibanFile; use App\Core\Crypto; use App\Core\Iban; function maskedIban($iban) { $iban = (string)$iban; return strlen($iban) <= 6 ? '…' : substr($iban, 0, 4) . '…' . substr($iban, -4); } try { $newKey = (string)getenv('IBAN_KEY'); if (Crypto::key() === null) { die("Fehler: IBAN_KEY ist nicht gesetzt. Schlüssel erzeugen mit: openssl rand -base64 32\n"); } $oldKey = (string)getenv('IBAN_KEY_OLD'); $pdo = new PDO("mysql:host=$host;port=$port;dbname=$dbName;charset=utf8mb4", $user, $pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo ($apply ? "MODUS: schreiben" : "MODUS: Vorschau (nichts wird geschrieben)") . "\nZiel: {$user}@{$host}:{$port}/{$dbName}\n\n"; // Bestand laden $users = []; foreach ($pdo->query("SELECT id, email, iban, mobile FROM users") as $row) { $users[(int)$row['id']] = $row; } $updateIban = $pdo->prepare( "UPDATE users SET iban = ?, updated_at = NOW() WHERE id = ? AND (iban IS NULL OR iban = '')" ); $updateMobile = $pdo->prepare( "UPDATE users SET mobile = ?, updated_at = NOW() WHERE id = ? AND (mobile IS NULL OR mobile = '')" ); $updateExistingIban = $pdo->prepare("UPDATE users SET iban = ?, updated_at = NOW() WHERE id = ?"); // 1) Vorhandene IBANs auf den neuen Schlüssel umschlüsseln $rekeyed = 0; $rekeyFailed = []; foreach ($users as $id => $row) { $iban = trim((string)$row['iban']); if ($iban === '') { continue; } if (Crypto::isEncrypted($iban)) { try { Crypto::decrypt($iban); continue; // bereits mit dem neuen Schlüssel lesbar } catch (\Throwable $e) { // mit altem Schlüssel versuchen } if ($oldKey === '') { $rekeyFailed[] = $id; continue; } putenv('IBAN_KEY=' . $oldKey); try { $plain = Crypto::decrypt($iban); } catch (\Throwable $e) { putenv('IBAN_KEY=' . $newKey); $rekeyFailed[] = $id; continue; } putenv('IBAN_KEY=' . $newKey); $cipher = Crypto::encrypt($plain); if ($apply) { $updateExistingIban->execute([$cipher, $id]); } $users[$id]['iban'] = $cipher; $rekeyed++; } else { // Klartext aus Altbestand $cipher = Crypto::encrypt($iban); if ($apply) { $updateExistingIban->execute([$cipher, $id]); } $users[$id]['iban'] = $cipher; $rekeyed++; } } // 2) CSV einlesen $fh = fopen($csvPath, 'r'); if ($fh === false) { die("Fehler: CSV kann nicht geöffnet werden: $csvPath\n"); } $header = fgetcsv($fh, 0, ';'); if ($header === false) { die("Fehler: CSV ist leer.\n"); } $header[0] = preg_replace('/^\xEF\xBB\xBF/', '', $header[0]); $columns = array_flip($header); foreach (['user_id', 'email', 'iban', 'mobile'] as $required) { if (!isset($columns[$required])) { die("Fehler: Spalte '$required' fehlt im CSV.\n"); } } $rows = 0; $missing = []; $mismatch = []; $invalid = []; $ibanSet = 0; $ibanExists = 0; $ibanDiffers = []; $mobileSet = 0; $mobileExists = 0; while (($line = fgetcsv($fh, 0, ';')) !== false) { if ($line === [null] || count($line) < count($header)) { continue; } $rows++; $id = (int)$line[$columns['user_id']]; $email = trim((string)$line[$columns['email']]); if (!isset($users[$id])) { $missing[] = $id; continue; } if (strcasecmp(trim((string)$users[$id]['email']), $email) !== 0) { $mismatch[] = $id; continue; } $rawIban = trim((string)$line[$columns['iban']]); if ($rawIban !== '') { $iban = Iban::normalize($rawIban); if (!Iban::isValid($iban)) { $invalid[] = $id . ' (' . maskedIban($iban) . ')'; } elseif (trim((string)$users[$id]['iban']) === '') { $cipher = Crypto::encrypt($iban); if ($apply) { $updateIban->execute([$cipher, $id]); } $users[$id]['iban'] = $cipher; $ibanSet++; } else { $ibanExists++; $existing = ''; try { $existing = Iban::normalize(Crypto::decrypt($users[$id]['iban'])); } catch (\Throwable $e) { $existing = null; } if ($existing !== $iban) { $ibanDiffers[] = $id; } } } $mobile = trim((string)$line[$columns['mobile']]); if ($mobile !== '') { if (trim((string)$users[$id]['mobile']) === '') { if ($apply) { $updateMobile->execute([$mobile, $id]); } $users[$id]['mobile'] = $mobile; $mobileSet++; } else { $mobileExists++; } } } fclose($fh); echo "CSV: {$rows} Zeilen aus " . basename($csvPath) . "\n"; echo "IBANs umgeschlüsselt/verschlüsselt: {$rekeyed}\n"; echo "IBANs neu gesetzt: {$ibanSet}\n"; echo "IBANs bereits vorhanden (behalten): {$ibanExists}\n"; echo "Mobilnummern neu gesetzt: {$mobileSet}\n"; echo "Mobilnummern bereits vorhanden: {$mobileExists}\n"; if ($ibanDiffers) { echo "Hinweis: abweichende vorhandene IBAN (App-Stand gewinnt), User-IDs: " . implode(', ', $ibanDiffers) . "\n"; } if ($invalid) { echo "Ungültige IBAN im CSV (übersprungen): " . implode(', ', $invalid) . "\n"; } if ($missing) { echo "Unbekannte User-IDs: " . implode(', ', $missing) . "\n"; } if ($mismatch) { echo "E-Mail passt nicht zur User-ID: " . implode(', ', $mismatch) . "\n"; } if ($rekeyFailed) { echo "WARNUNG: IBAN nicht entschlüsselbar (weder neuer noch alter Schlüssel), User-IDs: " . implode(', ', $rekeyFailed) . "\n"; } if (!$apply) { echo "\nVorschau beendet. Zum Schreiben --apply ergänzen.\n"; } else { echo "\nImport abgeschlossen.\n"; } } catch (PDOException $e) { fwrite(STDERR, "Datenbankfehler: " . $e->getMessage() . "\n"); exit(1); } catch (\Throwable $e) { fwrite(STDERR, "Fehler: " . $e->getMessage() . "\n"); exit(1); }