UploadController.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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'])) {
  83. $url = urlFor("/$args[userCode]/$args[mediaCode]/raw");
  84. $response = $response->withHeader('Link', "<{$url}>; rel=preload; as={$type}");
  85. }
  86. } catch (FileNotFoundException $e) {
  87. throw $e;
  88. }
  89. return $this->view->render($response, 'upload/public.twig', [
  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 FileNotFoundException
  103. */
  104. public function getRawById(Request $request, Response $response, $args): Response
  105. {
  106. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
  107. if (!$media) {
  108. throw new NotFoundException($request, $response);
  109. }
  110. return $this->streamMedia($request, $response, $this->getStorage(), $media);
  111. }
  112. /**
  113. * @param Request $request
  114. * @param Response $response
  115. * @param $args
  116. * @return Response
  117. * @throws NotFoundException
  118. * @throws FileNotFoundException
  119. */
  120. public function showRaw(Request $request, Response $response, $args): Response
  121. {
  122. $media = $this->getMedia($args['userCode'], $args['mediaCode']);
  123. if (!$media || !$media->published && Session::get('user_id') !== $media->user_id && !Session::get('admin', false)) {
  124. throw new NotFoundException($request, $response);
  125. }
  126. return $this->streamMedia($request, $response, $this->getStorage(), $media);
  127. }
  128. /**
  129. * @param Request $request
  130. * @param Response $response
  131. * @param $args
  132. * @return Response
  133. * @throws NotFoundException
  134. * @throws FileNotFoundException
  135. */
  136. public function download(Request $request, Response $response, $args): Response
  137. {
  138. $media = $this->getMedia($args['userCode'], $args['mediaCode']);
  139. if (!$media || !$media->published && Session::get('user_id') !== $media->user_id && !Session::get('admin', false)) {
  140. throw new NotFoundException($request, $response);
  141. }
  142. return $this->streamMedia($request, $response, $this->getStorage(), $media, 'attachment');
  143. }
  144. /**
  145. * @param Request $request
  146. * @param Response $response
  147. * @param $args
  148. * @return Response
  149. * @throws NotFoundException
  150. */
  151. public function togglePublish(Request $request, Response $response, $args): Response
  152. {
  153. if (Session::get('admin')) {
  154. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
  155. } else {
  156. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? AND `user_id` = ? LIMIT 1', [$args['id'], Session::get('user_id')])->fetch();
  157. }
  158. if (!$media) {
  159. throw new NotFoundException($request, $response);
  160. }
  161. $this->database->query('UPDATE `uploads` SET `published`=? WHERE `id`=?', [$media->published ? 0 : 1, $media->id]);
  162. return $response->withStatus(200);
  163. }
  164. /**
  165. * @param Request $request
  166. * @param Response $response
  167. * @param $args
  168. * @return Response
  169. * @throws NotFoundException
  170. * @throws UnauthorizedException
  171. */
  172. public function delete(Request $request, Response $response, $args): Response
  173. {
  174. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
  175. if (Session::get('admin', false) || $media->user_id === Session::get('user_id')) {
  176. $filesystem = $this->getStorage();
  177. try {
  178. $filesystem->delete($media->storage_path);
  179. } catch (FileNotFoundException $e) {
  180. throw new NotFoundException($request, $response);
  181. } finally {
  182. $this->database->query('DELETE FROM `uploads` WHERE `id` = ?', $args['id']);
  183. $this->logger->info('User ' . Session::get('username') . ' deleted a media.', [$args['id']]);
  184. Session::set('used_space', humanFileSize($this->getUsedSpaceByUser(Session::get('user_id'))));
  185. }
  186. } else {
  187. throw new UnauthorizedException();
  188. }
  189. return $response->withStatus(200);
  190. }
  191. /**
  192. * @param $userCode
  193. * @param $mediaCode
  194. * @return mixed
  195. */
  196. protected function getMedia($userCode, $mediaCode)
  197. {
  198. $mediaCode = pathinfo($mediaCode)['filename'];
  199. $media = $this->database->query('SELECT * FROM `uploads` INNER JOIN `users` ON `uploads`.`user_id` = `users`.`id` WHERE `user_code` = ? AND `uploads`.`code` = ? LIMIT 1', [
  200. $userCode,
  201. $mediaCode,
  202. ])->fetch();
  203. return $media;
  204. }
  205. /**
  206. * @param Request $request
  207. * @param Response $response
  208. * @param Filesystem $storage
  209. * @param $media
  210. * @param string $disposition
  211. * @return Response
  212. * @throws FileNotFoundException
  213. */
  214. protected function streamMedia(Request $request, Response $response, Filesystem $storage, $media, string $disposition = 'inline'): Response
  215. {
  216. $mime = $storage->getMimetype($media->storage_path);
  217. if ($request->getParam('width') !== null && explode('/', $mime)[0] === 'image') {
  218. $image = imagecreatefromstring($storage->read($media->storage_path));
  219. $scaled = imagescale($image, $request->getParam('width'), $request->getParam('height') !== null ? $request->getParam('height') : -1);
  220. imagedestroy($image);
  221. ob_start();
  222. imagepng($scaled, null, 9);
  223. $imagedata = ob_get_contents();
  224. ob_end_clean();
  225. imagedestroy($scaled);
  226. return $response
  227. ->withHeader('Content-Type', 'image/png')
  228. ->withHeader('Content-Disposition', $disposition . ';filename="scaled-' . pathinfo($media->filename)['filename'] . '.png"')
  229. ->write($imagedata);
  230. } else {
  231. ob_end_clean();
  232. return $response
  233. ->withHeader('Content-Type', $mime)
  234. ->withHeader('Content-Disposition', $disposition . ';filename="' . $media->filename . '"')
  235. ->withHeader('Content-Length', $storage->getSize($media->storage_path))
  236. ->withBody(new Stream($storage->readStream($media->storage_path)));
  237. }
  238. }
  239. }