save-draft.php 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. <?php
  2. declare(strict_types=1);
  3. use App\App\Bootstrap;
  4. use App\Form\FormSchema;
  5. use App\Storage\FileUploadStore;
  6. use App\Storage\JsonStore;
  7. use App\Security\Csrf;
  8. use App\Security\FormAccess;
  9. use App\Security\RateLimiter;
  10. require dirname(__DIR__) . '/src/autoload.php';
  11. Bootstrap::init();
  12. if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  13. Bootstrap::jsonResponse(['ok' => false, 'message' => 'Method not allowed'], 405);
  14. }
  15. $csrf = $_POST['csrf'] ?? '';
  16. if (!Csrf::validate(is_string($csrf) ? $csrf : null)) {
  17. Bootstrap::jsonResponse(['ok' => false, 'message' => 'Ungültiges CSRF-Token.'], 419);
  18. }
  19. if (trim((string) ($_POST['website'] ?? '')) !== '') {
  20. Bootstrap::jsonResponse(['ok' => false, 'message' => 'Anfrage blockiert.'], 400);
  21. }
  22. $email = strtolower(trim((string) ($_POST['email'] ?? '')));
  23. if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
  24. Bootstrap::jsonResponse(['ok' => false, 'message' => 'Bitte gültige E-Mail eingeben.'], 422);
  25. }
  26. $activityRaw = $_POST['last_user_activity_at'] ?? null;
  27. $lastUserActivityAt = is_scalar($activityRaw) ? (int) $activityRaw : null;
  28. $formAccess = new FormAccess();
  29. $auth = $formAccess->assertVerifiedForEmail($email, $lastUserActivityAt);
  30. if (($auth['ok'] ?? false) !== true) {
  31. $reason = (string) ($auth['reason'] ?? '');
  32. Bootstrap::jsonResponse([
  33. 'ok' => false,
  34. 'message' => (string) ($auth['message'] ?? 'Bitte E-Mail erneut verifizieren.'),
  35. 'auth_required' => $reason === 'auth_required',
  36. 'auth_expired' => $reason === 'auth_expired',
  37. ], (int) ($auth['status_code'] ?? 401));
  38. }
  39. $app = Bootstrap::config('app');
  40. $limiter = new RateLimiter();
  41. $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
  42. $rateKey = sprintf('save:%s:%s', $ip, $email);
  43. if (!$limiter->allow($rateKey, (int) $app['rate_limit']['requests'], (int) $app['rate_limit']['window_seconds'])) {
  44. Bootstrap::jsonResponse(['ok' => false, 'message' => 'Zu viele Speicheranfragen.'], 429);
  45. }
  46. $step = (int) ($_POST['step'] ?? 1);
  47. $formDataRaw = $_POST['form_data'] ?? [];
  48. $formData = [];
  49. if (is_array($formDataRaw)) {
  50. foreach ($formDataRaw as $key => $value) {
  51. if (!is_string($key)) {
  52. continue;
  53. }
  54. $formData[$key] = is_array($value) ? '' : trim((string) $value);
  55. }
  56. }
  57. $store = new JsonStore();
  58. try {
  59. $result = $store->withEmailLock($email, static function () use ($store, $email, $step, $formData): array {
  60. if ($store->hasSubmission($email)) {
  61. return [
  62. 'blocked' => true,
  63. 'message' => 'Für diese E-Mail wurde bereits ein Antrag abgeschlossen.',
  64. ];
  65. }
  66. return [
  67. 'blocked' => false,
  68. 'draft' => $store->saveDraft($email, [
  69. 'step' => max(1, $step),
  70. 'form_data' => $formData,
  71. 'uploads' => [],
  72. ]),
  73. ];
  74. });
  75. } catch (Throwable $e) {
  76. Bootstrap::log('app', 'save-draft lock error: ' . $e->getMessage());
  77. Bootstrap::jsonResponse(['ok' => false, 'message' => 'Speichern derzeit nicht möglich.'], 500);
  78. }
  79. if (($result['blocked'] ?? false) === true) {
  80. Bootstrap::jsonResponse([
  81. 'ok' => false,
  82. 'already_submitted' => true,
  83. 'message' => (string) ($result['message'] ?? 'Bereits abgeschlossen.'),
  84. ], 409);
  85. }
  86. $schema = new FormSchema();
  87. $uploadStore = new FileUploadStore();
  88. $uploadResult = $uploadStore->processUploads($_FILES, $schema->getUploadFields(), $store->emailKey($email));
  89. if (!empty($uploadResult['uploads'])) {
  90. try {
  91. $store->withEmailLock($email, static function () use ($store, $email, $step, $formData, $uploadResult): void {
  92. if ($store->hasSubmission($email)) {
  93. return;
  94. }
  95. $store->saveDraft($email, [
  96. 'step' => max(1, $step),
  97. 'form_data' => $formData,
  98. 'uploads' => $uploadResult['uploads'],
  99. ]);
  100. });
  101. } catch (Throwable $e) {
  102. Bootstrap::log('app', 'save-draft upload merge error: ' . $e->getMessage());
  103. }
  104. }
  105. $draft = $store->getDraft($email);
  106. Bootstrap::jsonResponse([
  107. 'ok' => true,
  108. 'message' => 'Entwurf gespeichert.',
  109. 'updated_at' => $draft['updated_at'] ?? null,
  110. 'upload_errors' => $uploadResult['errors'],
  111. 'uploads' => $draft['uploads'] ?? [],
  112. ]);