MediaController.php 14 KB

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