api.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. *
  16. * The browser never receives an S3 URL or any credential for writing.
  17. */
  18. require dirname(__DIR__) . '/app/bootstrap.php';
  19. if (!auth_check()) {
  20. json_response(['error' => 'Not authenticated'], 401);
  21. }
  22. if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  23. json_response(['error' => 'POST only'], 405);
  24. }
  25. csrf_verify();
  26. // Release the session file before the slow S3 leg. PHP holds an exclusive lock
  27. // on it for the whole request, so without this every parallel upload from the
  28. // browser would queue behind the previous one and the uploader would be
  29. // serial again no matter how many requests it starts.
  30. session_write_close();
  31. // One image per request; a single file may still be large, so lift the time cap.
  32. @set_time_limit(0);
  33. // When a request body exceeds post_max_size, PHP discards $_POST and $_FILES
  34. // entirely — surface that as a clear 413 instead of a misleading "no file".
  35. if ((int)($_SERVER['CONTENT_LENGTH'] ?? 0) > 0 && !$_POST && !$_FILES) {
  36. json_response(['error' => 'Upload exceeds the server post_max_size limit'], 413);
  37. }
  38. $gallery = gallery_load((string)($_POST['slug'] ?? ''));
  39. if ($gallery === null) {
  40. json_response(['error' => 'Unknown gallery'], 404);
  41. }
  42. // Trusted admin path: any file type is allowed (imagesOnly stays false).
  43. [$status, $payload] = gallery_store_s3_upload(
  44. $gallery,
  45. $_FILES['original'] ?? null,
  46. $_FILES['thumb'] ?? null
  47. );
  48. json_response($payload, $status);