upload-api.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. // One image per request; a single file may still be large, so lift the time cap.
  21. @set_time_limit(0);
  22. // When a request body exceeds post_max_size, PHP discards $_POST and $_FILES
  23. // entirely — surface that as a clear 413 instead of a misleading "no file".
  24. if ((int)($_SERVER['CONTENT_LENGTH'] ?? 0) > 0 && !$_POST && !$_FILES) {
  25. json_response(['error' => 'Upload exceeds the server post_max_size limit'], 413);
  26. }
  27. $gallery = gallery_load((string)($_POST['slug'] ?? ''));
  28. // Uniform 403 for every access failure (no key, wrong key, expired, locked) so
  29. // the endpoint reveals nothing a guest shouldn't already know from the link.
  30. $authorized = $gallery !== null
  31. && !empty($gallery['upload_key'])
  32. && hash_equals((string)$gallery['upload_key'], (string)($_POST['key'] ?? ''))
  33. && !gallery_is_expired($gallery)
  34. && (empty($gallery['password_hash']) || !empty($_SESSION['gallery_unlocked'][$gallery['slug']]));
  35. if (!$authorized) {
  36. json_response(['error' => 'Not authorized'], 403);
  37. }
  38. // Image-only: a public link must not be usable to store arbitrary file types.
  39. [$status, $payload] = gallery_store_s3_upload(
  40. $gallery,
  41. $_FILES['original'] ?? null,
  42. $_FILES['thumb'] ?? null,
  43. true
  44. );
  45. json_response($payload, $status);