UploadController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. <?php
  2. namespace App\Controllers;
  3. use GuzzleHttp\Psr7\Stream;
  4. use Intervention\Image\Constraint;
  5. use Intervention\Image\ImageManagerStatic as Image;
  6. use League\Flysystem\FileExistsException;
  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 UploadController extends Controller
  15. {
  16. /**
  17. * @param Request $request
  18. * @param Response $response
  19. * @return Response
  20. * @throws \Twig\Error\LoaderError
  21. * @throws \Twig\Error\RuntimeError
  22. * @throws \Twig\Error\SyntaxError
  23. */
  24. public function webUpload(Request $request, Response $response): Response
  25. {
  26. $user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $this->session->get('user_id'))->fetch();
  27. if ($user->token === null || $user->token === '') {
  28. $this->session->alert(lang('no_upload_token'), 'danger');
  29. return redirect($response, $request->getHeaderLine('Referer'));
  30. }
  31. return view()->render($response, 'upload/web.twig', [
  32. 'user' => $user,
  33. ]);
  34. }
  35. /**
  36. * @param Request $request
  37. * @param Response $response
  38. * @return Response
  39. * @throws FileExistsException
  40. */
  41. public function upload(Request $request, Response $response): Response
  42. {
  43. $json = [
  44. 'message' => null,
  45. 'version' => PLATFORM_VERSION,
  46. ];
  47. if ($this->config['maintenance']) {
  48. $json['message'] = 'Endpoint under maintenance.';
  49. return json($response, $json, 503);
  50. }
  51. if ($request->getServerParams()['CONTENT_LENGTH'] > stringToBytes(ini_get('post_max_size'))) {
  52. $json['message'] = 'File too large (post_max_size too low?).';
  53. return json($response, $json, 400);
  54. }
  55. $file = array_values($request->getUploadedFiles());
  56. /** @var \Psr\Http\Message\UploadedFileInterface|null $file */
  57. $file = isset($file[0]) ? $file[0] : null;
  58. if ($file === null) {
  59. $json['message'] = 'Request without file attached.';
  60. return json($response, $json, 400);
  61. }
  62. if ($file->getError() === UPLOAD_ERR_INI_SIZE) {
  63. $json['message'] = 'File too large (upload_max_filesize too low?).';
  64. return json($response, $json, 400);
  65. }
  66. if (param($request, 'token') === null) {
  67. $json['message'] = 'Token not specified.';
  68. return json($response, $json, 400);
  69. }
  70. $user = $this->database->query('SELECT * FROM `users` WHERE `token` = ? LIMIT 1', param($request, 'token'))->fetch();
  71. if (!$user) {
  72. $json['message'] = 'Token specified not found.';
  73. return json($response, $json, 404);
  74. }
  75. if (!$user->active) {
  76. $json['message'] = 'Account disabled.';
  77. return json($response, $json, 401);
  78. }
  79. do {
  80. $code = humanRandomString();
  81. } while ($this->database->query('SELECT COUNT(*) AS `count` FROM `uploads` WHERE `code` = ?', $code)->fetch()->count > 0);
  82. $fileInfo = pathinfo($file->getClientFilename());
  83. $storagePath = "$user->user_code/$code.$fileInfo[extension]";
  84. $this->storage->writeStream($storagePath, $file->getStream()->detach());
  85. $this->database->query('INSERT INTO `uploads`(`user_id`, `code`, `filename`, `storage_path`) VALUES (?, ?, ?, ?)', [
  86. $user->id,
  87. $code,
  88. $file->getClientFilename(),
  89. $storagePath,
  90. ]);
  91. $json['message'] = 'OK.';
  92. $json['url'] = urlFor("/$user->user_code/$code.$fileInfo[extension]");
  93. $this->logger->info("User $user->username uploaded new media.", [$this->database->getPdo()->lastInsertId()]);
  94. return json($response, $json, 201);
  95. }
  96. /**
  97. * @param Request $request
  98. * @param Response $response
  99. * @param string $userCode
  100. * @param string $mediaCode
  101. * @param string|null $token
  102. * @return Response
  103. * @throws HttpNotFoundException
  104. * @throws \Twig\Error\LoaderError
  105. * @throws \Twig\Error\RuntimeError
  106. * @throws \Twig\Error\SyntaxError
  107. * @throws FileNotFoundException
  108. */
  109. public function show(Request $request, Response $response, string $userCode, string $mediaCode, string $token = null): Response
  110. {
  111. $media = $this->getMedia($userCode, $mediaCode);
  112. if (!$media || (!$media->published && $this->session->get('user_id') !== $media->user_id && !$this->session->get('admin', false))) {
  113. throw new HttpNotFoundException($request);
  114. }
  115. $filesystem = $this->storage;
  116. if (isBot($request->getHeaderLine('User-Agent'))) {
  117. return $this->streamMedia($request, $response, $filesystem, $media);
  118. } else {
  119. try {
  120. $media->mimetype = $filesystem->getMimetype($media->storage_path);
  121. $size = $filesystem->getSize($media->storage_path);
  122. $type = explode('/', $media->mimetype)[0];
  123. if ($type === 'image' && !isDisplayableImage($media->mimetype)) {
  124. $type = 'application';
  125. $media->mimetype = 'application/octet-stream';
  126. }
  127. if ($type === 'text') {
  128. if ($size <= (200 * 1024)) { // less than 200 KB
  129. $media->text = $filesystem->read($media->storage_path);
  130. } else {
  131. $type = 'application';
  132. $media->mimetype = 'application/octet-stream';
  133. }
  134. }
  135. $media->size = humanFileSize($size);
  136. } catch (FileNotFoundException $e) {
  137. throw new HttpNotFoundException($request);
  138. }
  139. return view()->render($response, 'upload/public.twig', [
  140. 'delete_token' => $token,
  141. 'media' => $media,
  142. 'type' => $type,
  143. 'extension' => pathinfo($media->filename, PATHINFO_EXTENSION),
  144. ]);
  145. }
  146. }
  147. /**
  148. * @param Request $request
  149. * @param Response $response
  150. * @param string $userCode
  151. * @param string $mediaCode
  152. * @param string $token
  153. * @return Response
  154. * @throws HttpNotFoundException
  155. * @throws HttpUnauthorizedException
  156. */
  157. public function deleteByToken(Request $request, Response $response, string $userCode, string $mediaCode, string $token): Response
  158. {
  159. $media = $this->getMedia($userCode, $mediaCode);
  160. if (!$media) {
  161. throw new HttpNotFoundException($request);
  162. }
  163. $user = $this->database->query('SELECT `id`, `active` FROM `users` WHERE `token` = ? LIMIT 1', $token)->fetch();
  164. if (!$user) {
  165. $this->session->alert(lang('token_not_found'), 'danger');
  166. return redirect($response, $request->getHeaderLine('Referer'));
  167. }
  168. if (!$user->active) {
  169. $this->session->alert(lang('account_disabled'), 'danger');
  170. return redirect($response, $request->getHeaderLine('Referer'));
  171. }
  172. if ($this->session->get('admin', false) || $user->id === $media->user_id) {
  173. try {
  174. $this->storage->delete($media->storage_path);
  175. } catch (FileNotFoundException $e) {
  176. throw new HttpNotFoundException($request);
  177. } finally {
  178. $this->database->query('DELETE FROM `uploads` WHERE `id` = ?', $media->mediaId);
  179. $this->logger->info('User '.$user->username.' deleted a media via token.', [$media->mediaId]);
  180. }
  181. } else {
  182. throw new HttpUnauthorizedException($request);
  183. }
  184. return redirect($response, route('home'));
  185. }
  186. /**
  187. * @param Request $request
  188. * @param Response $response
  189. * @param int $id
  190. * @return Response
  191. * @throws FileNotFoundException
  192. * @throws HttpNotFoundException
  193. */
  194. public function getRawById(Request $request, Response $response, int $id): Response
  195. {
  196. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $id)->fetch();
  197. if (!$media) {
  198. throw new HttpNotFoundException($request);
  199. }
  200. return $this->streamMedia($request, $response, $this->storage, $media);
  201. }
  202. /**
  203. * @param Request $request
  204. * @param Response $response
  205. * @param string $userCode
  206. * @param string $mediaCode
  207. * @param string|null $ext
  208. * @return Response
  209. * @throws FileNotFoundException
  210. * @throws HttpNotFoundException
  211. */
  212. public function showRaw(Request $request, Response $response, string $userCode, string $mediaCode, ?string $ext = null): Response
  213. {
  214. $media = $this->getMedia($userCode, $mediaCode);
  215. if (!$media || !$media->published && $this->session->get('user_id') !== $media->user_id && !$this->session->get('admin', false)) {
  216. throw new HttpNotFoundException($request);
  217. }
  218. if ($ext !== null && pathinfo($media->filename, PATHINFO_EXTENSION) !== $ext) {
  219. throw new HttpBadRequestException($request);
  220. }
  221. return $this->streamMedia($request, $response, $this->storage, $media);
  222. }
  223. /**
  224. * @param Request $request
  225. * @param Response $response
  226. * @param string $userCode
  227. * @param string $mediaCode
  228. * @return Response
  229. * @throws FileNotFoundException
  230. * @throws HttpNotFoundException
  231. */
  232. public function download(Request $request, Response $response, string $userCode, string $mediaCode): Response
  233. {
  234. $media = $this->getMedia($userCode, $mediaCode);
  235. if (!$media || !$media->published && $this->session->get('user_id') !== $media->user_id && !$this->session->get('admin', false)) {
  236. throw new HttpNotFoundException($request);
  237. }
  238. return $this->streamMedia($request, $response, $this->storage, $media, 'attachment');
  239. }
  240. /**
  241. * @param Request $request
  242. * @param Response $response
  243. * @param int $id
  244. * @return Response
  245. * @throws HttpNotFoundException
  246. */
  247. public function togglePublish(Request $request, Response $response, int $id): Response
  248. {
  249. if ($this->session->get('admin')) {
  250. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $id)->fetch();
  251. } else {
  252. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? AND `user_id` = ? LIMIT 1', [$id, $this->session->get('user_id')])->fetch();
  253. }
  254. if (!$media) {
  255. throw new HttpNotFoundException($request);
  256. }
  257. $this->database->query('UPDATE `uploads` SET `published`=? WHERE `id`=?', [$media->published ? 0 : 1, $media->id]);
  258. return $response->withStatus(200);
  259. }
  260. /**
  261. * @param Request $request
  262. * @param Response $response
  263. * @param int $id
  264. * @return Response
  265. * @throws HttpNotFoundException
  266. * @throws HttpUnauthorizedException
  267. */
  268. public function delete(Request $request, Response $response, int $id): Response
  269. {
  270. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $id)->fetch();
  271. if (!$media) {
  272. throw new HttpNotFoundException($request);
  273. }
  274. if ($this->session->get('admin', false) || $media->user_id === $this->session->get('user_id')) {
  275. try {
  276. $this->storage->delete($media->storage_path);
  277. } catch (FileNotFoundException $e) {
  278. throw new HttpNotFoundException($request);
  279. } finally {
  280. $this->database->query('DELETE FROM `uploads` WHERE `id` = ?', $id);
  281. $this->logger->info('User '.$this->session->get('username').' deleted a media.', [$id]);
  282. $this->session->set('used_space', humanFileSize($this->getUsedSpaceByUser($this->session->get('user_id'))));
  283. }
  284. } else {
  285. throw new HttpUnauthorizedException($request);
  286. }
  287. return $response->withStatus(200);
  288. }
  289. /**
  290. * @param $userCode
  291. * @param $mediaCode
  292. * @return mixed
  293. */
  294. protected function getMedia($userCode, $mediaCode)
  295. {
  296. $mediaCode = pathinfo($mediaCode)['filename'];
  297. $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', [
  298. $userCode,
  299. $mediaCode,
  300. ])->fetch();
  301. return $media;
  302. }
  303. /**
  304. * @param Request $request
  305. * @param Response $response
  306. * @param Filesystem $storage
  307. * @param $media
  308. * @param string $disposition
  309. * @return Response
  310. * @throws FileNotFoundException
  311. */
  312. protected function streamMedia(Request $request, Response $response, Filesystem $storage, $media, string $disposition = 'inline'): Response
  313. {
  314. set_time_limit(0);
  315. $mime = $storage->getMimetype($media->storage_path);
  316. if (param($request, 'width') !== null && explode('/', $mime)[0] === 'image') {
  317. $image = Image::make($storage->readStream($media->storage_path))
  318. ->resize(
  319. param($request, 'width'),
  320. param($request, 'height'),
  321. function (Constraint $constraint) {
  322. $constraint->aspectRatio();
  323. })
  324. ->resizeCanvas(param($request, 'width'),
  325. param($request, 'height'), 'center')
  326. ->stream('png');
  327. return $response
  328. ->withHeader('Content-Type', 'image/png')
  329. ->withHeader('Content-Disposition', $disposition.';filename="scaled-'.pathinfo($media->filename, PATHINFO_FILENAME).'.png"')
  330. ->withBody($image);
  331. } else {
  332. $stream = new Stream($storage->readStream($media->storage_path));
  333. if (!in_array(explode('/', $mime)[0], ['image', 'video', 'audio']) || $disposition === 'attachment') {
  334. return $response->withHeader('Content-Type', $mime)
  335. ->withHeader('Content-Disposition', $disposition.'; filename="'.$media->filename.'"')
  336. ->withHeader('Content-Length', $stream->getSize())
  337. ->withBody($stream);
  338. }
  339. $end = $stream->getSize() - 1;
  340. if (isset($request->getServerParams()['HTTP_RANGE'])) {
  341. list(, $range) = explode('=', $request->getServerParams()['HTTP_RANGE'], 2);
  342. if (strpos($range, ',') !== false) {
  343. return $response->withHeader('Content-Type', $mime)
  344. ->withHeader('Content-Disposition', $disposition.'; filename="'.$media->filename.'"')
  345. ->withHeader('Content-Length', $stream->getSize())
  346. ->withHeader('Accept-Ranges', 'bytes')
  347. ->withHeader('Content-Range', "0,{$stream->getSize()}")
  348. ->withStatus(416)
  349. ->withBody($stream);
  350. }
  351. if ($range === '-') {
  352. $start = $stream->getSize() - (int)substr($range, 1);
  353. } else {
  354. $range = explode('-', $range);
  355. $start = (int)$range[0];
  356. $end = (isset($range[1]) && is_numeric($range[1])) ? (int)$range[1] : $stream->getSize();
  357. }
  358. $end = ($end > $stream->getSize() - 1) ? $stream->getSize() - 1 : $end;
  359. $stream->seek($start);
  360. header("Content-Type: $mime");
  361. header('Content-Length: '.($end - $start + 1));
  362. header('Accept-Ranges: bytes');
  363. header("Content-Range: bytes $start-$end/{$stream->getSize()}");
  364. http_response_code(206);
  365. ob_end_clean();
  366. $buffer = 16348;
  367. $readed = $start;
  368. while ($readed < $end) {
  369. if ($readed + $buffer > $end) {
  370. $buffer = $end - $readed + 1;
  371. }
  372. echo $stream->read($buffer);
  373. $readed += $buffer;
  374. }
  375. exit(0);
  376. }
  377. return $response->withHeader('Content-Type', $mime)
  378. ->withHeader('Content-Length', $stream->getSize())
  379. ->withHeader('Accept-Ranges', 'bytes')
  380. ->withStatus(200)
  381. ->withBody($stream);
  382. }
  383. }
  384. }