UploadController.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. <?php
  2. namespace App\Controllers;
  3. use GuzzleHttp\Psr7\Stream;
  4. use Intervention\Image\ImageManagerStatic as Image;
  5. use League\Flysystem\FileExistsException;
  6. use League\Flysystem\FileNotFoundException;
  7. use League\Flysystem\Filesystem;
  8. use Psr\Http\Message\ResponseInterface as Response;
  9. use Psr\Http\Message\ServerRequestInterface as Request;
  10. use Slim\Exception\HttpNotFoundException;
  11. use Slim\Exception\HttpUnauthorizedException;
  12. class UploadController extends Controller
  13. {
  14. /**
  15. * @param Request $request
  16. * @param Response $response
  17. * @return Response
  18. * @throws FileExistsException
  19. */
  20. public function upload(Request $request, Response $response): Response
  21. {
  22. $json = [
  23. 'message' => null,
  24. 'version' => PLATFORM_VERSION,
  25. ];
  26. if ($this->config['maintenance']) {
  27. $json['message'] = 'Endpoint under maintenance.';
  28. return json($response, $json, 503);
  29. }
  30. if ($request->getServerParams()['CONTENT_LENGTH'] > stringToBytes(ini_get('post_max_size'))) {
  31. $json['message'] = 'File too large (post_max_size too low?).';
  32. return json($response, $json, 400);
  33. }
  34. if (isset($request->getUploadedFiles()['upload']) && $request->getUploadedFiles()['upload']->getError() === UPLOAD_ERR_INI_SIZE) {
  35. $json['message'] = 'File too large (upload_max_filesize too low?).';
  36. return json($response, $json, 400);
  37. }
  38. if (param($request, 'token') === null) {
  39. $json['message'] = 'Token not specified.';
  40. return json($response, $json, 400);
  41. }
  42. $user = $this->database->query('SELECT * FROM `users` WHERE `token` = ? LIMIT 1', param($request, 'token'))->fetch();
  43. if (!$user) {
  44. $json['message'] = 'Token specified not found.';
  45. return json($response, $json, 404);
  46. }
  47. if (!$user->active) {
  48. $json['message'] = 'Account disabled.';
  49. return json($response, $json, 401);
  50. }
  51. do {
  52. $code = humanRandomString();
  53. } while ($this->database->query('SELECT COUNT(*) AS `count` FROM `uploads` WHERE `code` = ?', $code)->fetch()->count > 0);
  54. /** @var \Psr\Http\Message\UploadedFileInterface $file */
  55. $file = $request->getUploadedFiles()['upload'];
  56. $fileInfo = pathinfo($file->getClientFilename());
  57. $storagePath = "$user->user_code/$code.$fileInfo[extension]";
  58. $this->storage->writeStream($storagePath, $file->getStream()->detach());
  59. $this->database->query('INSERT INTO `uploads`(`user_id`, `code`, `filename`, `storage_path`) VALUES (?, ?, ?, ?)', [
  60. $user->id,
  61. $code,
  62. $file->getClientFilename(),
  63. $storagePath,
  64. ]);
  65. $json['message'] = 'OK.';
  66. $json['url'] = urlFor("/$user->user_code/$code.$fileInfo[extension]");
  67. $this->logger->info("User $user->username uploaded new media.", [$this->database->raw()->lastInsertId()]);
  68. return json($response, $json, 201);
  69. }
  70. /**
  71. * @param Request $request
  72. * @param Response $response
  73. * @param string $userCode
  74. * @param string $mediaCode
  75. * @param string|null $token
  76. * @return Response
  77. * @throws HttpNotFoundException
  78. * @throws \Twig\Error\LoaderError
  79. * @throws \Twig\Error\RuntimeError
  80. * @throws \Twig\Error\SyntaxError
  81. * @throws FileNotFoundException
  82. */
  83. public function show(Request $request, Response $response, string $userCode, string $mediaCode, string $token = null): Response
  84. {
  85. $media = $this->getMedia($userCode, $mediaCode);
  86. if (!$media || (!$media->published && $this->session->get('user_id') !== $media->user_id && !$this->session->get('admin', false))) {
  87. throw new HttpNotFoundException($request);
  88. }
  89. $filesystem = $this->storage;
  90. if (isBot($request->getHeaderLine('User-Agent'))) {
  91. return $this->streamMedia($request, $response, $filesystem, $media);
  92. } else {
  93. try {
  94. $media->mimetype = $filesystem->getMimetype($media->storage_path);
  95. $size = $filesystem->getSize($media->storage_path);
  96. $type = explode('/', $media->mimetype)[0];
  97. if ($type === 'image' && !isDisplayableImage($media->mimetype)) {
  98. $type = 'application';
  99. $media->mimetype = 'application/octet-stream';
  100. }
  101. if ($type === 'text') {
  102. if ($size <= (200 * 1024)) { // less than 200 KB
  103. $media->text = $filesystem->read($media->storage_path);
  104. } else {
  105. $type = 'application';
  106. $media->mimetype = 'application/octet-stream';
  107. }
  108. }
  109. $media->size = humanFileSize($size);
  110. } catch (FileNotFoundException $e) {
  111. throw new HttpNotFoundException($request);
  112. }
  113. return view()->render($response, 'upload/public.twig', [
  114. 'delete_token' => $token,
  115. 'media' => $media,
  116. 'type' => $type,
  117. 'extension' => pathinfo($media->filename, PATHINFO_EXTENSION),
  118. ]);
  119. }
  120. }
  121. /**
  122. * @param Request $request
  123. * @param Response $response
  124. * @param string $userCode
  125. * @param string $mediaCode
  126. * @param string $token
  127. * @return Response
  128. * @throws HttpNotFoundException
  129. * @throws HttpUnauthorizedException
  130. */
  131. public function deleteByToken(Request $request, Response $response, string $userCode, string $mediaCode, string $token): Response
  132. {
  133. $media = $this->getMedia($userCode, $mediaCode);
  134. if (!$media) {
  135. throw new HttpNotFoundException($request);
  136. }
  137. $user = $this->database->query('SELECT `id`, `active` FROM `users` WHERE `token` = ? LIMIT 1', $token)->fetch();
  138. if (!$user) {
  139. $this->session->alert(lang('token_not_found'), 'danger');
  140. return redirect($response, $request->getHeaderLine('HTTP_REFERER'));
  141. }
  142. if (!$user->active) {
  143. $this->session->alert(lang('account_disabled'), 'danger');
  144. return redirect($response, $request->getHeaderLine('HTTP_REFERER'));
  145. }
  146. if ($this->session->get('admin', false) || $user->id === $media->user_id) {
  147. try {
  148. $this->storage->delete($media->storage_path);
  149. } catch (FileNotFoundException $e) {
  150. throw new HttpNotFoundException($request);
  151. } finally {
  152. $this->database->query('DELETE FROM `uploads` WHERE `id` = ?', $media->mediaId);
  153. $this->logger->info('User '.$user->username.' deleted a media via token.', [$media->mediaId]);
  154. }
  155. } else {
  156. throw new HttpUnauthorizedException($request);
  157. }
  158. return redirect($response, route('home'));
  159. }
  160. /**
  161. * @param Request $request
  162. * @param Response $response
  163. * @param int $id
  164. * @return Response
  165. * @throws FileNotFoundException
  166. * @throws HttpNotFoundException
  167. */
  168. public function getRawById(Request $request, Response $response, int $id): Response
  169. {
  170. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $id)->fetch();
  171. if (!$media) {
  172. throw new HttpNotFoundException($request);
  173. }
  174. return $this->streamMedia($request, $response, $this->storage, $media);
  175. }
  176. /**
  177. * @param Request $request
  178. * @param Response $response
  179. * @param string $userCode
  180. * @param string $mediaCode
  181. * @return Response
  182. * @throws FileNotFoundException
  183. * @throws HttpNotFoundException
  184. */
  185. public function showRaw(Request $request, Response $response, string $userCode, string $mediaCode): Response
  186. {
  187. $media = $this->getMedia($userCode, $mediaCode);
  188. if (!$media || !$media->published && $this->session->get('user_id') !== $media->user_id && !$this->session->get('admin', false)) {
  189. throw new HttpNotFoundException($request);
  190. }
  191. return $this->streamMedia($request, $response, $this->storage, $media);
  192. }
  193. /**
  194. * @param Request $request
  195. * @param Response $response
  196. * @param string $userCode
  197. * @param string $mediaCode
  198. * @return Response
  199. * @throws FileNotFoundException
  200. * @throws HttpNotFoundException
  201. */
  202. public function download(Request $request, Response $response, string $userCode, string $mediaCode): Response
  203. {
  204. $media = $this->getMedia($userCode, $mediaCode);
  205. if (!$media || !$media->published && $this->session->get('user_id') !== $media->user_id && !$this->session->get('admin', false)) {
  206. throw new HttpNotFoundException($request);
  207. }
  208. return $this->streamMedia($request, $response, $this->storage, $media, 'attachment');
  209. }
  210. /**
  211. * @param Request $request
  212. * @param Response $response
  213. * @param int $id
  214. * @return Response
  215. * @throws HttpNotFoundException
  216. */
  217. public function togglePublish(Request $request, Response $response, int $id): Response
  218. {
  219. if ($this->session->get('admin')) {
  220. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $id)->fetch();
  221. } else {
  222. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? AND `user_id` = ? LIMIT 1', [$id, $this->session->get('user_id')])->fetch();
  223. }
  224. if (!$media) {
  225. throw new HttpNotFoundException($request);
  226. }
  227. $this->database->query('UPDATE `uploads` SET `published`=? WHERE `id`=?', [$media->published ? 0 : 1, $media->id]);
  228. return $response->withStatus(200);
  229. }
  230. /**
  231. * @param Request $request
  232. * @param Response $response
  233. * @param int $id
  234. * @return Response
  235. * @throws HttpNotFoundException
  236. * @throws HttpUnauthorizedException
  237. */
  238. public function delete(Request $request, Response $response, int $id): Response
  239. {
  240. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $id)->fetch();
  241. if (!$media) {
  242. throw new HttpNotFoundException($request);
  243. }
  244. if ($this->session->get('admin', false) || $media->user_id === $this->session->get('user_id')) {
  245. try {
  246. $this->storage->delete($media->storage_path);
  247. } catch (FileNotFoundException $e) {
  248. throw new HttpNotFoundException($request);
  249. } finally {
  250. $this->database->query('DELETE FROM `uploads` WHERE `id` = ?', $id);
  251. $this->logger->info('User '.$this->session->get('username').' deleted a media.', [$id]);
  252. $this->session->set('used_space', humanFileSize($this->getUsedSpaceByUser($this->session->get('user_id'))));
  253. }
  254. } else {
  255. throw new HttpUnauthorizedException($request);
  256. }
  257. return $response->withStatus(200);
  258. }
  259. /**
  260. * @param $userCode
  261. * @param $mediaCode
  262. * @return mixed
  263. */
  264. protected function getMedia($userCode, $mediaCode)
  265. {
  266. $mediaCode = pathinfo($mediaCode)['filename'];
  267. $media = $this->database->query('SELECT `uploads`.*, `users`.*, `users`.`id` AS `userId`, `uploads`.`id` AS `mediaId` FROM `uploads` INNER JOIN `users` ON `uploads`.`user_id` = `users`.`id` WHERE `user_code` = ? AND `uploads`.`code` = ? LIMIT 1', [
  268. $userCode,
  269. $mediaCode,
  270. ])->fetch();
  271. return $media;
  272. }
  273. /**
  274. * @param Request $request
  275. * @param Response $response
  276. * @param Filesystem $storage
  277. * @param $media
  278. * @param string $disposition
  279. * @return Response
  280. * @throws FileNotFoundException
  281. */
  282. protected function streamMedia(Request $request, Response $response, Filesystem $storage, $media, string $disposition = 'inline'): Response
  283. {
  284. set_time_limit(0);
  285. $mime = $storage->getMimetype($media->storage_path);
  286. if (param($request, 'width') !== null && explode('/', $mime)[0] === 'image') {
  287. $image = Image::make($storage->readStream($media->storage_path))
  288. ->resizeCanvas(
  289. param($request, 'width'),
  290. param($request, 'height'),
  291. 'center')
  292. ->encode('png');
  293. $response->getBody()->write($image);
  294. return $response
  295. ->withHeader('Content-Type', 'image/png')
  296. ->withHeader('Content-Disposition', $disposition.';filename="scaled-'.pathinfo($media->filename)['filename'].'.png"');
  297. } else {
  298. $stream = new Stream($storage->readStream($media->storage_path));
  299. if (!in_array(explode('/', $mime)[0], ['image', 'video', 'audio']) || $disposition === 'attachment') {
  300. return $response->withHeader('Content-Type', $mime)
  301. ->withHeader('Content-Disposition', $disposition.'; filename="'.$media->filename.'"')
  302. ->withHeader('Content-Length', $stream->getSize())
  303. ->withBody($stream);
  304. }
  305. $end = $stream->getSize() - 1;
  306. if (isset($request->getServerParams()['HTTP_RANGE'])) {
  307. list(, $range) = explode('=', $request->getServerParams()['HTTP_RANGE'], 2);
  308. if (strpos($range, ',') !== false) {
  309. return $response->withHeader('Content-Type', $mime)
  310. ->withHeader('Content-Disposition', $disposition.'; filename="'.$media->filename.'"')
  311. ->withHeader('Content-Length', $stream->getSize())
  312. ->withHeader('Accept-Ranges', 'bytes')
  313. ->withHeader('Content-Range', "0,{$stream->getSize()}")
  314. ->withStatus(416)
  315. ->withBody($stream);
  316. }
  317. if ($range === '-') {
  318. $start = $stream->getSize() - (int)substr($range, 1);
  319. } else {
  320. $range = explode('-', $range);
  321. $start = (int)$range[0];
  322. $end = (isset($range[1]) && is_numeric($range[1])) ? (int)$range[1] : $stream->getSize();
  323. }
  324. $end = ($end > $stream->getSize() - 1) ? $stream->getSize() - 1 : $end;
  325. $stream->seek($start);
  326. header("Content-Type: $mime");
  327. header('Content-Length: '.($end - $start + 1));
  328. header('Accept-Ranges: bytes');
  329. header("Content-Range: bytes $start-$end/{$stream->getSize()}");
  330. http_response_code(206);
  331. ob_end_clean();
  332. $buffer = 16348;
  333. $readed = $start;
  334. while ($readed < $end) {
  335. if ($readed + $buffer > $end) {
  336. $buffer = $end - $readed + 1;
  337. }
  338. echo $stream->read($buffer);
  339. $readed += $buffer;
  340. }
  341. exit(0);
  342. }
  343. return $response->withHeader('Content-Type', $mime)
  344. ->withHeader('Content-Length', $stream->getSize())
  345. ->withHeader('Accept-Ranges', 'bytes')
  346. ->withStatus(200)
  347. ->withBody($stream);
  348. }
  349. }
  350. }