upload-api.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. /**
  3. * Public guest upload endpoint used by the browser-side uploader (assets/admin.js)
  4. * on upload.php. Same one-multipart-POST-per-image contract as admin/api.php, but
  5. * authenticated by the per-gallery upload key instead of an admin session.
  6. *
  7. * Fields: slug, key, original (required), thumb (optional). Access requires the
  8. * gallery to have guest uploads enabled, the key to match, the gallery to be
  9. * unexpired, and — if the gallery has a password — the visitor to have unlocked
  10. * it in this session (via upload.php). Any failure returns a uniform 403.
  11. *
  12. * Uploads are image-only here, so a public link cannot store arbitrary files.
  13. */
  14. require __DIR__ . '/app/bootstrap.php';
  15. session_boot();
  16. if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  17. json_response(['error' => 'POST only'], 405);
  18. }
  19. csrf_verify();
  20. // Take the session-held facts now, then release the session file before the slow
  21. // S3 leg. PHP locks it exclusively for the whole request, so without this every
  22. // parallel upload from the browser would queue behind the previous one and the
  23. // uploader would be serial again no matter how many requests it starts.
  24. $unlockedGalleries = (array)($_SESSION['gallery_unlocked'] ?? []);
  25. session_write_close();
  26. // One image per request; a single file may still be large, so lift the time cap.
  27. @set_time_limit(0);
  28. // When a request body exceeds post_max_size, PHP discards $_POST and $_FILES
  29. // entirely — surface that as a clear 413 instead of a misleading "no file".
  30. if ((int)($_SERVER['CONTENT_LENGTH'] ?? 0) > 0 && !$_POST && !$_FILES) {
  31. json_response(['error' => 'Upload exceeds the server post_max_size limit'], 413);
  32. }
  33. $gallery = gallery_load((string)($_POST['slug'] ?? ''));
  34. // Uniform 403 for every access failure (no key, wrong key, expired, locked) so
  35. // the endpoint reveals nothing a guest shouldn't already know from the link.
  36. $authorized = $gallery !== null
  37. && !empty($gallery['upload_key'])
  38. && hash_equals((string)$gallery['upload_key'], (string)($_POST['key'] ?? ''))
  39. && !gallery_is_expired($gallery)
  40. && (empty($gallery['password_hash']) || !empty($unlockedGalleries[$gallery['slug']]));
  41. if (!$authorized) {
  42. json_response(['error' => 'Not authorized'], 403);
  43. }
  44. // Image-only: a public link must not be usable to store arbitrary file types.
  45. [$status, $payload] = gallery_store_s3_upload(
  46. $gallery,
  47. $_FILES['original'] ?? null,
  48. $_FILES['thumb'] ?? null,
  49. true
  50. );
  51. json_response($payload, $status);