UploadController.php 13 KB

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