UploadController.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. $base_url = $this->settings['base_url'];
  51. $json['message'] = 'OK.';
  52. $json['url'] = "$base_url/$user->user_code/$code.$fileInfo[extension]";
  53. $this->logger->info("User $user->username uploaded new media.", [$this->database->raw()->lastInsertId()]);
  54. return $response->withJson($json, 201);
  55. }
  56. /**
  57. * @param Request $request
  58. * @param Response $response
  59. * @param $args
  60. * @return Response
  61. * @throws FileNotFoundException
  62. * @throws NotFoundException
  63. */
  64. public function show(Request $request, Response $response, $args): Response
  65. {
  66. $media = $this->getMedia($args['userCode'], $args['mediaCode']);
  67. if (!$media || !$media->published && Session::get('user_id') !== $media->user_id && !Session::get('admin', false)) {
  68. throw new NotFoundException($request, $response);
  69. }
  70. $filesystem = $this->getStorage();
  71. if (stristr($request->getHeaderLine('User-Agent'), 'TelegramBot') ||
  72. stristr($request->getHeaderLine('User-Agent'), 'facebookexternalhit/') ||
  73. stristr($request->getHeaderLine('User-Agent'), 'Discordbot/') ||
  74. stristr($request->getHeaderLine('User-Agent'), 'Facebot')) {
  75. return $this->streamMedia($request, $response, $filesystem, $media);
  76. } else {
  77. try {
  78. $mime = $filesystem->getMimetype($media->storage_path);
  79. $type = explode('/', $mime)[0];
  80. if ($type === 'text') {
  81. $media->text = $filesystem->read($media->storage_path);
  82. } else if (in_array($type, ['image', 'video']) && $request->getHeaderLine('Scheme') === 'HTTP/2.0') {
  83. $response = $response->withHeader('Link', "<{$this->settings['base_url']}/$args[userCode]/$args[mediaCode]/raw>; rel=preload; as={$type}");
  84. }
  85. } catch (FileNotFoundException $e) {
  86. throw $e;
  87. }
  88. return $this->view->render($response, 'upload/public.twig', [
  89. 'media' => $media,
  90. 'type' => $mime,
  91. 'extension' => pathinfo($media->filename, PATHINFO_EXTENSION),
  92. ]);
  93. }
  94. }
  95. /**
  96. * @param Request $request
  97. * @param Response $response
  98. * @param $args
  99. * @return Response
  100. * @throws NotFoundException
  101. * @throws FileNotFoundException
  102. */
  103. public function getRawById(Request $request, Response $response, $args): Response
  104. {
  105. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
  106. if (!$media) {
  107. throw new NotFoundException($request, $response);
  108. }
  109. return $this->streamMedia($request, $response, $this->getStorage(), $media);
  110. }
  111. /**
  112. * @param Request $request
  113. * @param Response $response
  114. * @param $args
  115. * @return Response
  116. * @throws NotFoundException
  117. * @throws FileNotFoundException
  118. */
  119. public function showRaw(Request $request, Response $response, $args): Response
  120. {
  121. $media = $this->getMedia($args['userCode'], $args['mediaCode']);
  122. if (!$media || !$media->published && Session::get('user_id') !== $media->user_id && !Session::get('admin', false)) {
  123. throw new NotFoundException($request, $response);
  124. }
  125. return $this->streamMedia($request, $response, $this->getStorage(), $media);
  126. }
  127. /**
  128. * @param Request $request
  129. * @param Response $response
  130. * @param $args
  131. * @return Response
  132. * @throws NotFoundException
  133. * @throws FileNotFoundException
  134. */
  135. public function download(Request $request, Response $response, $args): Response
  136. {
  137. $media = $this->getMedia($args['userCode'], $args['mediaCode']);
  138. if (!$media || !$media->published && Session::get('user_id') !== $media->user_id && !Session::get('admin', false)) {
  139. throw new NotFoundException($request, $response);
  140. }
  141. return $this->streamMedia($request, $response, $this->getStorage(), $media, 'attachment');
  142. }
  143. /**
  144. * @param Request $request
  145. * @param Response $response
  146. * @param $args
  147. * @return Response
  148. * @throws NotFoundException
  149. */
  150. public function togglePublish(Request $request, Response $response, $args): Response
  151. {
  152. if (Session::get('admin')) {
  153. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
  154. } else {
  155. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? AND `user_id` = ? LIMIT 1', [$args['id'], Session::get('user_id')])->fetch();
  156. }
  157. if (!$media) {
  158. throw new NotFoundException($request, $response);
  159. }
  160. $this->database->query('UPDATE `uploads` SET `published`=? WHERE `id`=?', [$media->published ? 0 : 1, $media->id]);
  161. return $response->withStatus(200);
  162. }
  163. /**
  164. * @param Request $request
  165. * @param Response $response
  166. * @param $args
  167. * @return Response
  168. * @throws NotFoundException
  169. * @throws UnauthorizedException
  170. */
  171. public function delete(Request $request, Response $response, $args): Response
  172. {
  173. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
  174. if (Session::get('admin', false) || $media->user_id === Session::get('user_id')) {
  175. $filesystem = $this->getStorage();
  176. try {
  177. $filesystem->delete($media->storage_path);
  178. } catch (FileNotFoundException $e) {
  179. throw new NotFoundException($request, $response);
  180. } finally {
  181. $this->database->query('DELETE FROM `uploads` WHERE `id` = ?', $args['id']);
  182. $this->logger->info('User ' . Session::get('username') . ' deleted a media.', [$args['id']]);
  183. Session::set('used_space', $this->humanFilesize($this->getUsedSpaceByUser(Session::get('user_id'))));
  184. }
  185. } else {
  186. throw new UnauthorizedException();
  187. }
  188. return $response->withStatus(200);
  189. }
  190. /**
  191. * @param $userCode
  192. * @param $mediaCode
  193. * @return mixed
  194. */
  195. protected function getMedia($userCode, $mediaCode)
  196. {
  197. $mediaCode = pathinfo($mediaCode)['filename'];
  198. $media = $this->database->query('SELECT * FROM `uploads` INNER JOIN `users` ON `uploads`.`user_id` = `users`.`id` WHERE `user_code` = ? AND `uploads`.`code` = ? LIMIT 1', [
  199. $userCode,
  200. $mediaCode,
  201. ])->fetch();
  202. return $media;
  203. }
  204. /**
  205. * @param Request $request
  206. * @param Response $response
  207. * @param Filesystem $storage
  208. * @param $media
  209. * @param string $disposition
  210. * @return Response
  211. * @throws FileNotFoundException
  212. */
  213. protected function streamMedia(Request $request, Response $response, Filesystem $storage, $media, string $disposition = 'inline'): Response
  214. {
  215. $mime = $storage->getMimetype($media->storage_path);
  216. if ($request->getParam('width') !== null && explode('/', $mime)[0] === 'image') {
  217. $image = imagecreatefromstring($storage->read($media->storage_path));
  218. $scaled = imagescale($image, $request->getParam('width'), $request->getParam('height') !== null ? $request->getParam('height') : -1);
  219. imagedestroy($image);
  220. ob_start();
  221. imagepng($scaled, null, 9);
  222. $imagedata = ob_get_contents();
  223. ob_end_clean();
  224. imagedestroy($scaled);
  225. return $response
  226. ->withHeader('Content-Type', 'image/png')
  227. ->withHeader('Content-Disposition', $disposition . ';filename="scaled-' . pathinfo($media->filename)['filename'] . '.png"')
  228. ->write($imagedata);
  229. } else {
  230. ob_end_clean();
  231. return $response
  232. ->withHeader('Content-Type', $mime)
  233. ->withHeader('Content-Disposition', $disposition . ';filename="' . $media->filename . '"')
  234. ->withHeader('Content-Length', $storage->getSize($media->storage_path))
  235. ->withBody(new Stream($storage->readStream($media->storage_path)));
  236. }
  237. }
  238. }