submit.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. <?php
  2. declare(strict_types=1);
  3. use App\App\Bootstrap;
  4. use App\Form\FormSchema;
  5. use App\Form\Validator;
  6. use App\Mail\Mailer;
  7. use App\Storage\FileUploadStore;
  8. use App\Storage\JsonStore;
  9. use App\Security\Csrf;
  10. use App\Security\FormAccess;
  11. use App\Security\RateLimiter;
  12. require dirname(__DIR__) . '/src/autoload.php';
  13. Bootstrap::init();
  14. /** @param array<string, mixed> $app */
  15. function resolveSubmitSuccessMessage(array $app): string
  16. {
  17. $fallback = 'Ihr Antrag wurde erfolgreich empfangen. Bei Fragen kontaktieren Sie %contact_email%.';
  18. $configured = trim((string) ($app['submission_success_message'] ?? $fallback));
  19. if ($configured === '') {
  20. $configured = $fallback;
  21. }
  22. $contactEmail = trim((string) ($app['contact_email'] ?? ''));
  23. $message = str_replace(
  24. ['%contact_email%', '{{contact_email}}'],
  25. $contactEmail !== '' ? $contactEmail : 'uns',
  26. $configured
  27. );
  28. return trim($message);
  29. }
  30. if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  31. Bootstrap::jsonResponse(['ok' => false, 'message' => 'Method not allowed'], 405);
  32. }
  33. $csrf = $_POST['csrf'] ?? '';
  34. if (!Csrf::validate(is_string($csrf) ? $csrf : null)) {
  35. Bootstrap::jsonResponse(['ok' => false, 'message' => 'Ungültiges CSRF-Token.'], 419);
  36. }
  37. if (trim((string) ($_POST['website'] ?? '')) !== '') {
  38. Bootstrap::jsonResponse(['ok' => false, 'message' => 'Anfrage blockiert.'], 400);
  39. }
  40. $email = strtolower(trim((string) ($_POST['email'] ?? '')));
  41. if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
  42. Bootstrap::jsonResponse(['ok' => false, 'message' => 'Bitte gültige E-Mail eingeben.'], 422);
  43. }
  44. $activityRaw = $_POST['last_user_activity_at'] ?? null;
  45. $lastUserActivityAt = is_scalar($activityRaw) ? (int) $activityRaw : null;
  46. $formAccess = new FormAccess();
  47. $auth = $formAccess->assertVerifiedForEmail($email, $lastUserActivityAt);
  48. if (($auth['ok'] ?? false) !== true) {
  49. $reason = (string) ($auth['reason'] ?? '');
  50. Bootstrap::jsonResponse([
  51. 'ok' => false,
  52. 'message' => (string) ($auth['message'] ?? 'Bitte E-Mail erneut verifizieren.'),
  53. 'auth_required' => $reason === 'auth_required',
  54. 'auth_expired' => $reason === 'auth_expired',
  55. ], (int) ($auth['status_code'] ?? 401));
  56. }
  57. $app = Bootstrap::config('app');
  58. $limiter = new RateLimiter();
  59. $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
  60. $rateKey = sprintf('submit:%s:%s', $ip, $email);
  61. if (!$limiter->allow($rateKey, (int) $app['rate_limit']['requests'], (int) $app['rate_limit']['window_seconds'])) {
  62. Bootstrap::jsonResponse(['ok' => false, 'message' => 'Zu viele Anfragen.'], 429);
  63. }
  64. $formDataRaw = $_POST['form_data'] ?? [];
  65. $formData = [];
  66. if (is_array($formDataRaw)) {
  67. foreach ($formDataRaw as $key => $value) {
  68. if (!is_string($key)) {
  69. continue;
  70. }
  71. $formData[$key] = is_array($value) ? '' : trim((string) $value);
  72. }
  73. }
  74. $store = new JsonStore();
  75. $schema = new FormSchema();
  76. $uploadStore = new FileUploadStore();
  77. $validator = new Validator($schema);
  78. // Fast fail before upload processing to avoid writing files for known duplicates.
  79. if ($store->hasSubmission($email)) {
  80. Bootstrap::jsonResponse([
  81. 'ok' => false,
  82. 'already_submitted' => true,
  83. 'message' => 'Für diese E-Mail liegt bereits ein abgeschlossener Antrag vor.',
  84. ], 409);
  85. }
  86. try {
  87. $submitResult = $store->withEmailLock($email, static function () use ($store, $email, $formData, $validator, $uploadStore, $schema): array {
  88. if ($store->hasSubmission($email)) {
  89. return [
  90. 'ok' => false,
  91. 'already_submitted' => true,
  92. 'message' => 'Für diese E-Mail liegt bereits ein abgeschlossener Antrag vor.',
  93. ];
  94. }
  95. $uploadResult = $uploadStore->processUploads($_FILES, $schema->getUploadFields(), $store->emailKey($email));
  96. if (!empty($uploadResult['errors'])) {
  97. return [
  98. 'ok' => false,
  99. 'already_submitted' => false,
  100. 'message' => 'Fehler bei Uploads.',
  101. 'errors' => $uploadResult['errors'],
  102. ];
  103. }
  104. $draft = $store->getDraft($email) ?? [];
  105. $mergedFormData = array_merge((array) ($draft['form_data'] ?? []), $formData);
  106. $mergedUploads = (array) ($draft['uploads'] ?? []);
  107. foreach ($uploadResult['uploads'] as $field => $items) {
  108. $mergedUploads[$field] = array_values(array_merge((array) ($mergedUploads[$field] ?? []), $items));
  109. }
  110. $errors = $validator->validateSubmit($mergedFormData, $mergedUploads);
  111. if (!empty($errors)) {
  112. $store->saveDraft($email, [
  113. 'step' => 4,
  114. 'form_data' => $mergedFormData,
  115. 'uploads' => $uploadResult['uploads'],
  116. ]);
  117. return [
  118. 'ok' => false,
  119. 'already_submitted' => false,
  120. 'message' => 'Bitte Pflichtfelder prüfen.',
  121. 'errors' => $errors,
  122. ];
  123. }
  124. $submission = $store->saveSubmission($email, [
  125. 'step' => 4,
  126. 'form_data' => $mergedFormData,
  127. 'uploads' => $mergedUploads,
  128. ]);
  129. return [
  130. 'ok' => true,
  131. 'submission' => $submission,
  132. ];
  133. });
  134. } catch (Throwable $e) {
  135. Bootstrap::log('app', 'submit lock error: ' . $e->getMessage());
  136. Bootstrap::jsonResponse(['ok' => false, 'message' => 'Abschluss derzeit nicht möglich.'], 500);
  137. }
  138. if (($submitResult['ok'] ?? false) !== true) {
  139. $status = ($submitResult['already_submitted'] ?? false) ? 409 : 422;
  140. Bootstrap::jsonResponse([
  141. 'ok' => false,
  142. 'already_submitted' => (bool) ($submitResult['already_submitted'] ?? false),
  143. 'message' => (string) ($submitResult['message'] ?? 'Abschluss fehlgeschlagen.'),
  144. 'errors' => $submitResult['errors'] ?? [],
  145. ], $status);
  146. }
  147. $submission = $submitResult['submission'];
  148. $mailer = new Mailer();
  149. $mailer->sendSubmissionMails($submission);
  150. Bootstrap::jsonResponse([
  151. 'ok' => true,
  152. 'message' => resolveSubmitSuccessMessage($app),
  153. 'application_key' => $submission['application_key'] ?? null,
  154. ]);