topics-api.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. /**
  3. * Admin JSON API for putting one image into a topic (or back into none).
  4. *
  5. * Creating, renaming, reordering and deleting topics are plain form posts on
  6. * gallery-edit.php — they change the page anyway. Assignment is the exception:
  7. * dragging a photo from one section to another has to happen without a reload,
  8. * or organising a few hundred images would be a few hundred page loads.
  9. *
  10. * Fields: slug, action (assign), key (the image's S3 key), topic (a topic id,
  11. * or empty for no topic).
  12. */
  13. require dirname(__DIR__) . '/app/bootstrap.php';
  14. if (!auth_check()) {
  15. json_response(['error' => 'Not authenticated'], 401);
  16. }
  17. if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  18. json_response(['error' => 'POST only'], 405);
  19. }
  20. csrf_verify();
  21. // Nothing here is slow, but a drag over many images fires these back to back
  22. // and PHP holds the session file exclusively for the whole request.
  23. session_write_close();
  24. $slug = (string)($_POST['slug'] ?? '');
  25. $gallery = gallery_load($slug);
  26. if ($gallery === null) {
  27. json_response(['error' => 'Unknown gallery'], 404);
  28. }
  29. if (($_POST['action'] ?? '') !== 'assign') {
  30. json_response(['error' => 'Unknown action'], 400);
  31. }
  32. $topic = (string)($_POST['topic'] ?? '');
  33. // Checked against this gallery's topics, so a stale page cannot write a
  34. // reference to one that has since been deleted. gallery_assign_topic() checks
  35. // again under its lock, where the answer is authoritative.
  36. if ($topic !== '' && !isset(gallery_topic_map($gallery)[$topic])) {
  37. json_response(['error' => 'Unknown topic'], 400);
  38. }
  39. if (!gallery_assign_topic($slug, (string)($_POST['key'] ?? ''), $topic)) {
  40. json_response(['error' => 'Unknown image'], 404);
  41. }
  42. json_response(['ok' => true]);