WebOrbiton
v2.0.0.0

Publisium

57 lines · 1.8 KB
  1. <?php
  2. ​
  3. declare(strict_types=1);
  4. ​
  5. require_once __DIR__ . '/includes/config.php';
  6. require_once __DIR__ . '/includes/database.php';
  7. require_once __DIR__ . '/includes/auth.php';
  8. require_once __DIR__ . '/includes/csrf.php';
  9. require_once __DIR__ . '/includes/read-aloud.php';
  10. ​
  11. Auth::boot();
  12. Auth::requireLogin();
  13. ​
  14. header('Content-Type: application/json');
  15. ​
  16. function audioUploadFail(int $status, string $message): never
  17. {
  18. http_response_code($status);
  19. echo json_encode(['success' => false, 'error' => $message]);
  20. exit;
  21. }
  22. ​
  23. if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !Csrf::verify($_POST['csrf_token'] ?? null)) {
  24. audioUploadFail(403, 'Something went wrong. Reload the page and try again.');
  25. }
  26. ​
  27. $kind = (string) ($_POST['kind'] ?? 'article');
  28. ​
  29. if (in_array($kind, ['intro', 'outro'], true)) {
  30. if (!Auth::hasRoleAtLeast(Auth::ROLE_EDITOR_IN_CHIEF)) {
  31. audioUploadFail(403, 'Only editors in chief can change the intro and outro.');
  32. }
  33. $maxBytes = ReadAloud::MAX_FRAME_AUDIO_BYTES;
  34. } elseif ($kind === 'article') {
  35. if (!ReadAloud::isEnabled()) {
  36. audioUploadFail(403, 'Read aloud is switched off in Settings.');
  37. }
  38. if (!Auth::hasRoleAtLeast(Auth::ROLE_WRITER)) {
  39. audioUploadFail(403, 'You can’t upload audio for this article.');
  40. }
  41. $maxBytes = ReadAloud::MAX_ARTICLE_AUDIO_BYTES;
  42. } else {
  43. audioUploadFail(400, 'Something went wrong. Reload the page and try again.');
  44. }
  45. ​
  46. if (!isset($_FILES['file']) || !is_array($_FILES['file'])) {
  47. audioUploadFail(400, 'The upload didn’t work. Please try again.');
  48. }
  49. ​
  50. [$stored, $result] = ReadAloud::storeUpload($_FILES['file'], $maxBytes);
  51. ​
  52. if (!$stored) {
  53. audioUploadFail(400, $result);
  54. }
  55. ​
  56. echo json_encode(['success' => true, 'path' => $result, 'url' => ReadAloud::publicUrl($result)]);
  57. ​