api.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. /**
  3. * Admin upload endpoint used by the browser-side uploader (assets/admin.js).
  4. *
  5. * One multipart POST per image (X-CSRF-Token header, fields below); the webhost
  6. * streams the file straight to S3 and appends it to the gallery's JSON file.
  7. * Keeping it to a single file per request means each PHP process only ever
  8. * handles one image, so a multi-gigabyte gallery upload never trips
  9. * post_max_size / max_execution_time — only the largest single image does.
  10. *
  11. * Fields:
  12. * slug gallery slug
  13. * original the full-resolution file (required, stored unmodified)
  14. * thumb browser-generated JPEG thumbnail (optional; absent for RAW/video)
  15. * batch id of the selection this file came from (optional)
  16. * seq its position within that selection, so parallel uploads are
  17. * stored in the order they were picked, not the order they land
  18. *
  19. * The browser never receives an S3 URL or any credential for writing.
  20. */
  21. require dirname(__DIR__) . '/app/bootstrap.php';
  22. if (!auth_check()) {
  23. json_response(['error' => 'Not authenticated'], 401);
  24. }
  25. if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  26. json_response(['error' => 'POST only'], 405);
  27. }
  28. csrf_verify();
  29. // Release the session file before the slow S3 leg. PHP holds an exclusive lock
  30. // on it for the whole request, so without this every parallel upload from the
  31. // browser would queue behind the previous one and the uploader would be
  32. // serial again no matter how many requests it starts.
  33. session_write_close();
  34. // One image per request; a single file may still be large, so lift the time cap.
  35. @set_time_limit(0);
  36. // When a request body exceeds post_max_size, PHP discards $_POST and $_FILES
  37. // entirely — surface that as a clear 413 instead of a misleading "no file".
  38. if ((int)($_SERVER['CONTENT_LENGTH'] ?? 0) > 0 && !$_POST && !$_FILES) {
  39. json_response(['error' => 'Upload exceeds the server post_max_size limit'], 413);
  40. }
  41. $gallery = gallery_load((string)($_POST['slug'] ?? ''));
  42. if ($gallery === null) {
  43. json_response(['error' => 'Unknown gallery'], 404);
  44. }
  45. // Trusted admin path: any file type is allowed (imagesOnly stays false).
  46. [$status, $payload] = gallery_store_s3_upload(
  47. $gallery,
  48. $_FILES['original'] ?? null,
  49. $_FILES['thumb'] ?? null,
  50. false,
  51. $_POST
  52. );
  53. json_response($payload, $status);