MediaController.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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 HttpNotFoundException
  164. * @throws HttpUnauthorizedException
  165. */
  166. public function delete(Request $request, Response $response, int $id): Response
  167. {
  168. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $id)->fetch();
  169. if (!$media) {
  170. throw new HttpNotFoundException($request);
  171. }
  172. if ($this->session->get('admin', false) || $media->user_id === $this->session->get('user_id')) {
  173. $this->deleteMedia($request, $media->storage_path, $id, $media->user_id);
  174. $this->logger->info('User '.$this->session->get('username').' deleted a media.', [$id]);
  175. if ($media->user_id === $this->session->get('user_id')) {
  176. $user = make(UserQuery::class)->get($request, $media->user_id, true);
  177. $this->setSessionQuotaInfo($user->current_disk_quota, $user->max_disk_quota);
  178. }
  179. } else {
  180. throw new HttpUnauthorizedException($request);
  181. }
  182. if ($request->getMethod() === 'GET') {
  183. return redirect($response, route('home'));
  184. }
  185. return $response;
  186. }
  187. /**
  188. * @param Request $request
  189. * @param Response $response
  190. * @param string $userCode
  191. * @param string $mediaCode
  192. * @param string $token
  193. *
  194. * @return Response
  195. * @throws HttpUnauthorizedException
  196. *
  197. * @throws HttpNotFoundException
  198. */
  199. public function deleteByToken(Request $request, Response $response, string $userCode, string $mediaCode, string $token): Response
  200. {
  201. $media = $this->getMedia($userCode, $mediaCode);
  202. if (!$media) {
  203. throw new HttpNotFoundException($request);
  204. }
  205. $user = $this->database->query('SELECT `id`, `active` FROM `users` WHERE `token` = ? LIMIT 1', $token)->fetch();
  206. if (!$user) {
  207. $this->session->alert(lang('token_not_found'), 'danger');
  208. return redirect($response, $request->getHeaderLine('Referer'));
  209. }
  210. if (!$user->active) {
  211. $this->session->alert(lang('account_disabled'), 'danger');
  212. return redirect($response, $request->getHeaderLine('Referer'));
  213. }
  214. if ($this->session->get('admin', false) || $user->id === $media->user_id) {
  215. $this->deleteMedia($request, $media->storage_path, $media->mediaId, $user->id);
  216. $this->logger->info('User '.$user->username.' deleted a media via token.', [$media->mediaId]);
  217. } else {
  218. throw new HttpUnauthorizedException($request);
  219. }
  220. return redirect($response, route('home'));
  221. }
  222. /**
  223. * @param Request $request
  224. * @param string $storagePath
  225. * @param int $id
  226. *
  227. * @param int $userId
  228. * @return void
  229. * @throws HttpNotFoundException
  230. */
  231. protected function deleteMedia(Request $request, string $storagePath, int $id, int $userId)
  232. {
  233. try {
  234. $size = $this->storage->getSize($storagePath);
  235. $this->storage->delete($storagePath);
  236. $this->updateUserQuota($request, $userId, $size, true);
  237. } catch (FileNotFoundException $e) {
  238. throw new HttpNotFoundException($request);
  239. } finally {
  240. $this->database->query('DELETE FROM `uploads` WHERE `id` = ?', $id);
  241. }
  242. }
  243. /**
  244. * @param $userCode
  245. * @param $mediaCode
  246. *
  247. * @return mixed
  248. */
  249. protected function getMedia($userCode, $mediaCode)
  250. {
  251. $mediaCode = pathinfo($mediaCode)['filename'];
  252. return $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', [
  253. $userCode,
  254. $mediaCode,
  255. ])->fetch();
  256. }
  257. /**
  258. * @param Request $request
  259. * @param Response $response
  260. * @param Filesystem $storage
  261. * @param $media
  262. * @param string $disposition
  263. *
  264. * @return Response
  265. * @throws FileNotFoundException
  266. *
  267. */
  268. protected function streamMedia(Request $request, Response $response, Filesystem $storage, $media, string $disposition = 'inline'): Response
  269. {
  270. set_time_limit(0);
  271. $mime = $storage->getMimetype($media->storage_path);
  272. if (param($request, 'width') !== null && explode('/', $mime)[0] === 'image') {
  273. return $this->makeThumbnail($storage, $media, param($request, 'width'), param($request, 'height'), $disposition);
  274. } else {
  275. $stream = new Stream($storage->readStream($media->storage_path));
  276. if (!in_array(explode('/', $mime)[0], ['image', 'video', 'audio']) || $disposition === 'attachment') {
  277. return $response->withHeader('Content-Type', $mime)
  278. ->withHeader('Content-Disposition', $disposition.'; filename="'.$media->filename.'"')
  279. ->withHeader('Content-Length', $stream->getSize())
  280. ->withBody($stream);
  281. }
  282. if (isset($request->getServerParams()['HTTP_RANGE'])) {
  283. return $this->handlePartialRequest($response, $stream, $request->getServerParams()['HTTP_RANGE'], $disposition, $media, $mime);
  284. }
  285. return $response->withHeader('Content-Type', $mime)
  286. ->withHeader('Content-Length', $stream->getSize())
  287. ->withHeader('Accept-Ranges', 'bytes')
  288. ->withBody($stream);
  289. }
  290. }
  291. /**
  292. * @param Filesystem $storage
  293. * @param $media
  294. * @param null $width
  295. * @param null $height
  296. * @param string $disposition
  297. *
  298. * @return Response
  299. * @throws FileNotFoundException
  300. *
  301. */
  302. protected function makeThumbnail(Filesystem $storage, $media, $width = null, $height = null, string $disposition = 'inline')
  303. {
  304. return Image::make($storage->readStream($media->storage_path))
  305. ->resize($width, $height, function (Constraint $constraint) {
  306. $constraint->aspectRatio();
  307. })
  308. ->resizeCanvas($width, $height, 'center')
  309. ->psrResponse('png')
  310. ->withHeader('Content-Disposition', $disposition.';filename="scaled-'.pathinfo($media->filename, PATHINFO_FILENAME).'.png"');
  311. }
  312. /**
  313. * @param Response $response
  314. * @param Stream $stream
  315. * @param string $range
  316. * @param string $disposition
  317. * @param $media
  318. * @param $mime
  319. *
  320. * @return Response
  321. */
  322. protected function handlePartialRequest(Response $response, Stream $stream, string $range, string $disposition, $media, $mime)
  323. {
  324. $end = $stream->getSize() - 1;
  325. [, $range] = explode('=', $range, 2);
  326. if (strpos($range, ',') !== false) {
  327. return $response->withHeader('Content-Type', $mime)
  328. ->withHeader('Content-Disposition', $disposition.'; filename="'.$media->filename.'"')
  329. ->withHeader('Content-Length', $stream->getSize())
  330. ->withHeader('Accept-Ranges', 'bytes')
  331. ->withHeader('Content-Range', "0,{$stream->getSize()}")
  332. ->withStatus(416)
  333. ->withBody($stream);
  334. }
  335. if ($range === '-') {
  336. $start = $stream->getSize() - (int) substr($range, 1);
  337. } else {
  338. $range = explode('-', $range);
  339. $start = (int) $range[0];
  340. $end = (isset($range[1]) && is_numeric($range[1])) ? (int) $range[1] : $stream->getSize();
  341. }
  342. $end = ($end > $stream->getSize() - 1) ? $stream->getSize() - 1 : $end;
  343. $stream->seek($start);
  344. header("Content-Type: $mime");
  345. header('Content-Length: '.($end - $start + 1));
  346. header('Accept-Ranges: bytes');
  347. header("Content-Range: bytes $start-$end/{$stream->getSize()}");
  348. http_response_code(206);
  349. ob_end_clean();
  350. $buffer = 16348;
  351. $readed = $start;
  352. while ($readed < $end) {
  353. if ($readed + $buffer > $end) {
  354. $buffer = $end - $readed + 1;
  355. }
  356. echo $stream->read($buffer);
  357. $readed += $buffer;
  358. }
  359. exit(0);
  360. }
  361. }