MediaController.php 14 KB

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