WebOrbiton
v2.0.0.1

Publisium

84 lines · 2.5 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/site-front.php';
  10. require_once __DIR__ . '/includes/webp.php';
  11. ​
  12. Auth::boot();
  13. Auth::requireLogin();
  14. ​
  15. header('Content-Type: application/json');
  16. ​
  17. if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !Csrf::verify($_POST['csrf_token'] ?? null)) {
  18. http_response_code(403);
  19. echo json_encode(['success' => false, 'error' => 'Something went wrong. Reload the page and try again.']);
  20. exit;
  21. }
  22. ​
  23. if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
  24. http_response_code(400);
  25. echo json_encode(['success' => false, 'error' => 'The upload didn’t work. Please try again.']);
  26. exit;
  27. }
  28. ​
  29. $file = $_FILES['file'];
  30. $maxBytes = 25 * 1024 * 1024;
  31. ​
  32. if ($file['size'] > $maxBytes) {
  33. http_response_code(400);
  34. echo json_encode(['success' => false, 'error' => 'This file is too big. The limit is 25 MB.']);
  35. exit;
  36. }
  37. ​
  38. $allowedTypes = [
  39. 'image/jpeg' => ['ext' => 'jpg', 'folder' => 'img'],
  40. 'image/png' => ['ext' => 'png', 'folder' => 'img'],
  41. 'image/gif' => ['ext' => 'gif', 'folder' => 'img'],
  42. 'image/webp' => ['ext' => 'webp', 'folder' => 'img'],
  43. 'video/mp4' => ['ext' => 'mp4', 'folder' => 'videos'],
  44. 'video/webm' => ['ext' => 'webm', 'folder' => 'videos'],
  45. ];
  46. ​
  47. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  48. $mimeType = finfo_file($finfo, $file['tmp_name']);
  49. ​
  50. if (!isset($allowedTypes[$mimeType])) {
  51. http_response_code(400);
  52. echo json_encode(['success' => false, 'error' => 'This file type isn’t supported.']);
  53. exit;
  54. }
  55. ​
  56. $typeInfo = $allowedTypes[$mimeType];
  57. $targetDir = __DIR__ . '/media/' . $typeInfo['folder'];
  58. ​
  59. if (!is_dir($targetDir)) {
  60. mkdir($targetDir, 0750, true);
  61. }
  62. ​
  63. $fileName = bin2hex(random_bytes(16)) . '.' . $typeInfo['ext'];
  64. $targetPath = $targetDir . '/' . $fileName;
  65. ​
  66. if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
  67. http_response_code(500);
  68. echo json_encode(['success' => false, 'error' => 'We couldn’t save the file. Please try again.']);
  69. exit;
  70. }
  71. ​
  72. if (SiteFront::settings()['media_webp_enabled'] === '1') {
  73. $webpPath = Webp::convert($targetPath, $mimeType);
  74. if ($webpPath !== null) {
  75. @unlink($targetPath);
  76. $fileName = basename($webpPath);
  77. }
  78. }
  79. ​
  80. echo json_encode([
  81. 'success' => true,
  82. 'url' => 'media/' . $typeInfo['folder'] . '/' . $fileName,
  83. ]);
  84. ​