UploadController.php 12 KB

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