submit.php 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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\Security\Csrf;
  8. use App\Security\FormAccess;
  9. use App\Security\RateLimiter;
  10. use App\Storage\FileUploadStore;
  11. use App\Storage\JsonStore;
  12. require dirname(__DIR__) . '/src/autoload.php';
  13. Bootstrap::init();
  14. /** @param array<string, mixed> $app */
  15. function resolveSubmitSuccessMessage(array $app): string
  16. {
  17. $configured = Bootstrap::appMessage('submit.success');
  18. $contactEmail = trim((string) ($app['contact_email'] ?? ''));
  19. $message = str_replace(
  20. ['%contact_email%', '{{contact_email}}'],
  21. $contactEmail !== '' ? $contactEmail : 'uns',
  22. $configured
  23. );
  24. return trim($message);
  25. }
  26. if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  27. Bootstrap::jsonResponse([
  28. 'ok' => false,
  29. 'message' => Bootstrap::appMessage('common.method_not_allowed'),
  30. ], 405);
  31. }
  32. $csrf = $_POST['csrf'] ?? '';
  33. if (!Csrf::validate(is_string($csrf) ? $csrf : null)) {
  34. Bootstrap::jsonResponse([
  35. 'ok' => false,
  36. 'message' => Bootstrap::appMessage('common.invalid_csrf'),
  37. ], 419);
  38. }
  39. if (trim((string) ($_POST['website'] ?? '')) !== '') {
  40. Bootstrap::jsonResponse([
  41. 'ok' => false,
  42. 'message' => Bootstrap::appMessage('common.request_blocked'),
  43. ], 400);
  44. }
  45. $email = strtolower(trim((string) ($_POST['email'] ?? '')));
  46. if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
  47. Bootstrap::jsonResponse([
  48. 'ok' => false,
  49. 'message' => Bootstrap::appMessage('common.invalid_email'),
  50. ], 422);
  51. }
  52. $activityRaw = $_POST['last_user_activity_at'] ?? null;
  53. $lastUserActivityAt = is_scalar($activityRaw) ? (int) $activityRaw : null;
  54. $formAccess = new FormAccess();
  55. $auth = $formAccess->assertVerifiedForEmail($email, $lastUserActivityAt);
  56. if (($auth['ok'] ?? false) !== true) {
  57. $reason = (string) ($auth['reason'] ?? '');
  58. Bootstrap::jsonResponse([
  59. 'ok' => false,
  60. 'message' => (string) ($auth['message'] ?? 'Bitte E-Mail erneut verifizieren.'),
  61. 'auth_required' => $reason === 'auth_required',
  62. 'auth_expired' => $reason === 'auth_expired',
  63. ], (int) ($auth['status_code'] ?? 401));
  64. }
  65. $app = Bootstrap::config('app');
  66. $limiter = new RateLimiter();
  67. $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
  68. $rateKey = sprintf('submit:%s:%s', $ip, $email);
  69. if (!$limiter->allow($rateKey, (int) $app['rate_limit']['requests'], (int) $app['rate_limit']['window_seconds'])) {
  70. Bootstrap::jsonResponse([
  71. 'ok' => false,
  72. 'message' => Bootstrap::appMessage('submit.rate_limited'),
  73. ], 429);
  74. }
  75. $formDataRaw = $_POST['form_data'] ?? [];
  76. $formData = [];
  77. if (is_array($formDataRaw)) {
  78. foreach ($formDataRaw as $key => $value) {
  79. if (!is_string($key)) {
  80. continue;
  81. }
  82. $formData[$key] = is_array($value) ? '' : trim((string) $value);
  83. }
  84. }
  85. $store = new JsonStore();
  86. $schema = new FormSchema();
  87. $uploadStore = new FileUploadStore();
  88. $validator = new Validator($schema);
  89. // Fast fail before upload processing to avoid writing files for known duplicates.
  90. if ($store->hasSubmission($email)) {
  91. Bootstrap::jsonResponse([
  92. 'ok' => false,
  93. 'already_submitted' => true,
  94. 'message' => Bootstrap::appMessage('submit.already_submitted'),
  95. ], 409);
  96. }
  97. try {
  98. $submitResult = $store->withEmailLock($email, static function () use ($store, $email, $formData, $validator, $uploadStore, $schema): array {
  99. if ($store->hasSubmission($email)) {
  100. return [
  101. 'ok' => false,
  102. 'already_submitted' => true,
  103. 'message' => Bootstrap::appMessage('submit.already_submitted'),
  104. ];
  105. }
  106. $uploadResult = $uploadStore->processUploads($_FILES, $schema->getUploadFields(), $store->emailKey($email));
  107. if (!empty($uploadResult['errors'])) {
  108. return [
  109. 'ok' => false,
  110. 'already_submitted' => false,
  111. 'message' => Bootstrap::appMessage('submit.upload_error'),
  112. 'errors' => $uploadResult['errors'],
  113. ];
  114. }
  115. $draft = $store->getDraft($email) ?? [];
  116. $mergedFormData = array_merge((array) ($draft['form_data'] ?? []), $formData);
  117. $mergedUploads = (array) ($draft['uploads'] ?? []);
  118. foreach ($uploadResult['uploads'] as $field => $items) {
  119. $mergedUploads[$field] = array_values(array_merge((array) ($mergedUploads[$field] ?? []), $items));
  120. }
  121. $errors = $validator->validateSubmit($mergedFormData, $mergedUploads);
  122. if (!empty($errors)) {
  123. $store->saveDraft($email, [
  124. 'step' => 4,
  125. 'form_data' => $mergedFormData,
  126. 'uploads' => $uploadResult['uploads'],
  127. ]);
  128. return [
  129. 'ok' => false,
  130. 'already_submitted' => false,
  131. 'message' => Bootstrap::appMessage('submit.validation_error'),
  132. 'errors' => $errors,
  133. ];
  134. }
  135. $submission = $store->saveSubmission($email, [
  136. 'step' => 4,
  137. 'form_data' => $mergedFormData,
  138. 'uploads' => $mergedUploads,
  139. ]);
  140. return [
  141. 'ok' => true,
  142. 'submission' => $submission,
  143. ];
  144. });
  145. } catch (Throwable $e) {
  146. Bootstrap::log('app', 'submit lock error: ' . $e->getMessage());
  147. Bootstrap::jsonResponse([
  148. 'ok' => false,
  149. 'message' => Bootstrap::appMessage('submit.lock_error'),
  150. ], 500);
  151. }
  152. if (($submitResult['ok'] ?? false) !== true) {
  153. $status = ($submitResult['already_submitted'] ?? false) ? 409 : 422;
  154. Bootstrap::jsonResponse([
  155. 'ok' => false,
  156. 'already_submitted' => (bool) ($submitResult['already_submitted'] ?? false),
  157. 'message' => (string) ($submitResult['message'] ?? Bootstrap::appMessage('submit.failure')),
  158. 'errors' => $submitResult['errors'] ?? [],
  159. ], $status);
  160. }
  161. $submission = $submitResult['submission'];
  162. $mailer = new Mailer();
  163. $mailer->sendSubmissionMails($submission);
  164. Bootstrap::jsonResponse([
  165. 'ok' => true,
  166. 'message' => resolveSubmitSuccessMessage($app),
  167. 'application_key' => $submission['application_key'] ?? null,
  168. ]);