MediaController.php 15 KB

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