UploadController.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. <?php
  2. namespace App\Controllers;
  3. use App\Exceptions\UnauthorizedException;
  4. use App\Web\Session;
  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->getParam('token') === null) {
  24. $json['message'] = 'Token not specified.';
  25. return $response->withJson($json, 400);
  26. }
  27. $user = $this->database->query('SELECT * FROM `users` WHERE `token` = ? LIMIT 1', $request->getParam('token'))->fetch();
  28. if (!$user) {
  29. $json['message'] = 'Token specified not found.';
  30. return $response->withJson($json, 404);
  31. }
  32. if (!$user->active) {
  33. $json['message'] = 'Account disabled.';
  34. return $response->withJson($json, 401);
  35. }
  36. do {
  37. $code = uniqid();
  38. } while ($this->database->query('SELECT COUNT(*) AS `count` FROM `uploads` WHERE `code` = ?', $code)->fetch()->count > 0);
  39. /** @var \Psr\Http\Message\UploadedFileInterface $file */
  40. $file = $request->getUploadedFiles()['upload'];
  41. $fileInfo = pathinfo($file->getClientFilename());
  42. $storagePath = "$user->user_code/$code.$fileInfo[extension]";
  43. $this->getStorage()->writeStream($storagePath, $file->getStream()->detach());
  44. $this->database->query('INSERT INTO `uploads`(`user_id`, `code`, `filename`, `storage_path`) VALUES (?, ?, ?, ?)', [
  45. $user->id,
  46. $code,
  47. $file->getClientFilename(),
  48. $storagePath,
  49. ]);
  50. $json['message'] = 'OK.';
  51. $json['url'] = urlFor("/$user->user_code/$code.$fileInfo[extension]");
  52. $this->logger->info("User $user->username uploaded new media.", [$this->database->raw()->lastInsertId()]);
  53. return $response->withJson($json, 201);
  54. }
  55. /**
  56. * @param Request $request
  57. * @param Response $response
  58. * @param $args
  59. * @return Response
  60. * @throws FileNotFoundException
  61. * @throws NotFoundException
  62. */
  63. public function show(Request $request, Response $response, $args): Response
  64. {
  65. $media = $this->getMedia($args['userCode'], $args['mediaCode']);
  66. if (!$media || (!$media->published && Session::get('user_id') !== $media->user_id && !Session::get('admin', false))) {
  67. throw new NotFoundException($request, $response);
  68. }
  69. $filesystem = $this->getStorage();
  70. if (stristr($request->getHeaderLine('User-Agent'), 'TelegramBot') ||
  71. stristr($request->getHeaderLine('User-Agent'), 'facebookexternalhit/') ||
  72. stristr($request->getHeaderLine('User-Agent'), 'Discordbot/') ||
  73. stristr($request->getHeaderLine('User-Agent'), 'Facebot')) {
  74. return $this->streamMedia($request, $response, $filesystem, $media);
  75. } else {
  76. try {
  77. $mime = $filesystem->getMimetype($media->storage_path);
  78. $type = explode('/', $mime)[0];
  79. if ($type === 'text') {
  80. $media->text = $filesystem->read($media->storage_path);
  81. } else if (in_array($type, ['image', 'video'])) {
  82. $url = urlFor("/$args[userCode]/$args[mediaCode]/raw");
  83. $response = $response->withHeader('Link', "<{$url}>; rel=preload; as={$type}" . Session::get('logged', false) ? '; nopush' : '');
  84. }
  85. } catch (FileNotFoundException $e) {
  86. throw new NotFoundException($request, $response);
  87. }
  88. return $this->view->render($response, 'upload/public.twig', [
  89. 'delete_token' => isset($args['token']) ? $args['token'] : null,
  90. 'media' => $media,
  91. 'type' => $mime,
  92. 'extension' => pathinfo($media->filename, PATHINFO_EXTENSION),
  93. ]);
  94. }
  95. }
  96. /**
  97. * @param Request $request
  98. * @param Response $response
  99. * @param $args
  100. * @return Response
  101. * @throws NotFoundException
  102. * @throws UnauthorizedException
  103. */
  104. public function deleteByToken(Request $request, Response $response, $args): Response
  105. {
  106. $media = $this->getMedia($args['userCode'], $args['mediaCode']);
  107. if (!$media) {
  108. throw new NotFoundException($request, $response);
  109. }
  110. $user = $this->database->query('SELECT `id`, `active` FROM `users` WHERE `token` = ? LIMIT 1', $args['token'])->fetch();
  111. if (!$user) {
  112. Session::alert('Token specified not found.', 'danger');
  113. return $response->withRedirect($request->getHeaderLine('HTTP_REFERER'));
  114. }
  115. if (!$user->active) {
  116. Session::alert('Account disabled.', 'danger');
  117. return $response->withRedirect($request->getHeaderLine('HTTP_REFERER'));
  118. }
  119. if (Session::get('admin', false) || $user->id === $media->user_id) {
  120. $filesystem = $this->getStorage();
  121. try {
  122. $filesystem->delete($media->storage_path);
  123. } catch (FileNotFoundException $e) {
  124. throw new NotFoundException($request, $response);
  125. } finally {
  126. $this->database->query('DELETE FROM `uploads` WHERE `id` = ?', $media->mediaId);
  127. $this->logger->info('User ' . $user->username . ' deleted a media via token.', [$media->mediaId]);
  128. }
  129. } else {
  130. throw new UnauthorizedException();
  131. }
  132. return redirect($response, '/home');
  133. }
  134. /**
  135. * @param Request $request
  136. * @param Response $response
  137. * @param $args
  138. * @return Response
  139. * @throws NotFoundException
  140. * @throws FileNotFoundException
  141. */
  142. public function getRawById(Request $request, Response $response, $args): Response
  143. {
  144. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
  145. if (!$media) {
  146. throw new NotFoundException($request, $response);
  147. }
  148. return $this->streamMedia($request, $response, $this->getStorage(), $media);
  149. }
  150. /**
  151. * @param Request $request
  152. * @param Response $response
  153. * @param $args
  154. * @return Response
  155. * @throws NotFoundException
  156. * @throws FileNotFoundException
  157. */
  158. public function showRaw(Request $request, Response $response, $args): Response
  159. {
  160. $media = $this->getMedia($args['userCode'], $args['mediaCode']);
  161. if (!$media || !$media->published && Session::get('user_id') !== $media->user_id && !Session::get('admin', false)) {
  162. throw new NotFoundException($request, $response);
  163. }
  164. return $this->streamMedia($request, $response, $this->getStorage(), $media);
  165. }
  166. /**
  167. * @param Request $request
  168. * @param Response $response
  169. * @param $args
  170. * @return Response
  171. * @throws NotFoundException
  172. * @throws FileNotFoundException
  173. */
  174. public function download(Request $request, Response $response, $args): Response
  175. {
  176. $media = $this->getMedia($args['userCode'], $args['mediaCode']);
  177. if (!$media || !$media->published && Session::get('user_id') !== $media->user_id && !Session::get('admin', false)) {
  178. throw new NotFoundException($request, $response);
  179. }
  180. return $this->streamMedia($request, $response, $this->getStorage(), $media, 'attachment');
  181. }
  182. /**
  183. * @param Request $request
  184. * @param Response $response
  185. * @param $args
  186. * @return Response
  187. * @throws NotFoundException
  188. */
  189. public function togglePublish(Request $request, Response $response, $args): Response
  190. {
  191. if (Session::get('admin')) {
  192. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
  193. } else {
  194. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? AND `user_id` = ? LIMIT 1', [$args['id'], Session::get('user_id')])->fetch();
  195. }
  196. if (!$media) {
  197. throw new NotFoundException($request, $response);
  198. }
  199. $this->database->query('UPDATE `uploads` SET `published`=? WHERE `id`=?', [$media->published ? 0 : 1, $media->id]);
  200. return $response->withStatus(200);
  201. }
  202. /**
  203. * @param Request $request
  204. * @param Response $response
  205. * @param $args
  206. * @return Response
  207. * @throws NotFoundException
  208. * @throws UnauthorizedException
  209. */
  210. public function delete(Request $request, Response $response, $args): Response
  211. {
  212. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
  213. if (!$media) {
  214. throw new NotFoundException($request, $response);
  215. }
  216. if (Session::get('admin', false) || $media->user_id === Session::get('user_id')) {
  217. $filesystem = $this->getStorage();
  218. try {
  219. $filesystem->delete($media->storage_path);
  220. } catch (FileNotFoundException $e) {
  221. throw new NotFoundException($request, $response);
  222. } finally {
  223. $this->database->query('DELETE FROM `uploads` WHERE `id` = ?', $args['id']);
  224. $this->logger->info('User ' . Session::get('username') . ' deleted a media.', [$args['id']]);
  225. Session::set('used_space', humanFileSize($this->getUsedSpaceByUser(Session::get('user_id'))));
  226. }
  227. } else {
  228. throw new UnauthorizedException();
  229. }
  230. return $response->withStatus(200);
  231. }
  232. /**
  233. * @param $userCode
  234. * @param $mediaCode
  235. * @return mixed
  236. */
  237. protected function getMedia($userCode, $mediaCode)
  238. {
  239. $mediaCode = pathinfo($mediaCode)['filename'];
  240. $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', [
  241. $userCode,
  242. $mediaCode,
  243. ])->fetch();
  244. return $media;
  245. }
  246. /**
  247. * @param Request $request
  248. * @param Response $response
  249. * @param Filesystem $storage
  250. * @param $media
  251. * @param string $disposition
  252. * @return Response
  253. * @throws FileNotFoundException
  254. */
  255. protected function streamMedia(Request $request, Response $response, Filesystem $storage, $media, string $disposition = 'inline'): Response
  256. {
  257. $mime = $storage->getMimetype($media->storage_path);
  258. if ($request->getParam('width') !== null && explode('/', $mime)[0] === 'image') {
  259. $image = imagecreatefromstring($storage->read($media->storage_path));
  260. $scaled = imagescale($image, $request->getParam('width'), $request->getParam('height') !== null ? $request->getParam('height') : -1);
  261. imagedestroy($image);
  262. ob_start();
  263. imagepng($scaled, null, 9);
  264. $imagedata = ob_get_contents();
  265. ob_end_clean();
  266. imagedestroy($scaled);
  267. return $response
  268. ->withHeader('Content-Type', 'image/png')
  269. ->withHeader('Content-Disposition', $disposition . ';filename="scaled-' . pathinfo($media->filename)['filename'] . '.png"')
  270. ->write($imagedata);
  271. } else {
  272. ob_end_clean();
  273. return $response
  274. ->withHeader('Content-Type', $mime)
  275. ->withHeader('Content-Disposition', $disposition . '; filename="' . $media->filename . '"')
  276. ->withHeader('Content-Length', $storage->getSize($media->storage_path))
  277. ->withBody(new Stream($storage->readStream($media->storage_path)));
  278. }
  279. }
  280. }