UploadController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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 = uniqid();
  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 === 'text') {
  93. if ($size <= (200 * 1024)) {// less than 200 KB
  94. $media->text = $filesystem->read($media->storage_path);
  95. } else {
  96. $type = 'application';
  97. $media->mimetype = 'application/octet-stream';
  98. }
  99. }
  100. $media->size = humanFileSize($size);
  101. } catch (FileNotFoundException $e) {
  102. throw new NotFoundException($request, $response);
  103. }
  104. return $this->view->render($response, 'upload/public.twig', [
  105. 'delete_token' => isset($args['token']) ? $args['token'] : null,
  106. 'media' => $media,
  107. 'type' => $type,
  108. 'extension' => pathinfo($media->filename, PATHINFO_EXTENSION),
  109. ]);
  110. }
  111. }
  112. /**
  113. * @param Request $request
  114. * @param Response $response
  115. * @param $args
  116. * @return Response
  117. * @throws NotFoundException
  118. * @throws UnauthorizedException
  119. */
  120. public function deleteByToken(Request $request, Response $response, $args): Response
  121. {
  122. $media = $this->getMedia($args['userCode'], $args['mediaCode']);
  123. if (!$media) {
  124. throw new NotFoundException($request, $response);
  125. }
  126. $user = $this->database->query('SELECT `id`, `active` FROM `users` WHERE `token` = ? LIMIT 1', $args['token'])->fetch();
  127. if (!$user) {
  128. $this->session->alert(lang('token_not_found'), 'danger');
  129. return $response->withRedirect($request->getHeaderLine('HTTP_REFERER'));
  130. }
  131. if (!$user->active) {
  132. $this->session->alert(lang('account_disabled'), 'danger');
  133. return $response->withRedirect($request->getHeaderLine('HTTP_REFERER'));
  134. }
  135. if ($this->session->get('admin', false) || $user->id === $media->user_id) {
  136. try {
  137. $this->storage->delete($media->storage_path);
  138. } catch (FileNotFoundException $e) {
  139. throw new NotFoundException($request, $response);
  140. } finally {
  141. $this->database->query('DELETE FROM `uploads` WHERE `id` = ?', $media->mediaId);
  142. $this->logger->info('User ' . $user->username . ' deleted a media via token.', [$media->mediaId]);
  143. }
  144. } else {
  145. throw new UnauthorizedException();
  146. }
  147. return redirect($response, 'home');
  148. }
  149. /**
  150. * @param Request $request
  151. * @param Response $response
  152. * @param $args
  153. * @return Response
  154. * @throws NotFoundException
  155. * @throws FileNotFoundException
  156. */
  157. public function getRawById(Request $request, Response $response, $args): Response
  158. {
  159. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
  160. if (!$media) {
  161. throw new NotFoundException($request, $response);
  162. }
  163. return $this->streamMedia($request, $response, $this->storage, $media);
  164. }
  165. /**
  166. * @param Request $request
  167. * @param Response $response
  168. * @param $args
  169. * @return Response
  170. * @throws NotFoundException
  171. * @throws FileNotFoundException
  172. */
  173. public function showRaw(Request $request, Response $response, $args): Response
  174. {
  175. $media = $this->getMedia($args['userCode'], $args['mediaCode']);
  176. if (!$media || !$media->published && $this->session->get('user_id') !== $media->user_id && !$this->session->get('admin', false)) {
  177. throw new NotFoundException($request, $response);
  178. }
  179. return $this->streamMedia($request, $response, $this->storage, $media);
  180. }
  181. /**
  182. * @param Request $request
  183. * @param Response $response
  184. * @param $args
  185. * @return Response
  186. * @throws NotFoundException
  187. * @throws FileNotFoundException
  188. */
  189. public function download(Request $request, Response $response, $args): Response
  190. {
  191. $media = $this->getMedia($args['userCode'], $args['mediaCode']);
  192. if (!$media || !$media->published && $this->session->get('user_id') !== $media->user_id && !$this->session->get('admin', false)) {
  193. throw new NotFoundException($request, $response);
  194. }
  195. return $this->streamMedia($request, $response, $this->storage, $media, 'attachment');
  196. }
  197. /**
  198. * @param Request $request
  199. * @param Response $response
  200. * @param $args
  201. * @return Response
  202. * @throws NotFoundException
  203. */
  204. public function togglePublish(Request $request, Response $response, $args): Response
  205. {
  206. if ($this->session->get('admin')) {
  207. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
  208. } else {
  209. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? AND `user_id` = ? LIMIT 1', [$args['id'], $this->session->get('user_id')])->fetch();
  210. }
  211. if (!$media) {
  212. throw new NotFoundException($request, $response);
  213. }
  214. $this->database->query('UPDATE `uploads` SET `published`=? WHERE `id`=?', [$media->published ? 0 : 1, $media->id]);
  215. return $response->withStatus(200);
  216. }
  217. /**
  218. * @param Request $request
  219. * @param Response $response
  220. * @param $args
  221. * @return Response
  222. * @throws NotFoundException
  223. * @throws UnauthorizedException
  224. */
  225. public function delete(Request $request, Response $response, $args): Response
  226. {
  227. $media = $this->database->query('SELECT * FROM `uploads` WHERE `id` = ? LIMIT 1', $args['id'])->fetch();
  228. if (!$media) {
  229. throw new NotFoundException($request, $response);
  230. }
  231. if ($this->session->get('admin', false) || $media->user_id === $this->session->get('user_id')) {
  232. try {
  233. $this->storage->delete($media->storage_path);
  234. } catch (FileNotFoundException $e) {
  235. throw new NotFoundException($request, $response);
  236. } finally {
  237. $this->database->query('DELETE FROM `uploads` WHERE `id` = ?', $args['id']);
  238. $this->logger->info('User ' . $this->session->get('username') . ' deleted a media.', [$args['id']]);
  239. $this->session->set('used_space', humanFileSize($this->getUsedSpaceByUser($this->session->get('user_id'))));
  240. }
  241. } else {
  242. throw new UnauthorizedException();
  243. }
  244. return $response->withStatus(200);
  245. }
  246. /**
  247. * @param $userCode
  248. * @param $mediaCode
  249. * @return mixed
  250. */
  251. protected function getMedia($userCode, $mediaCode)
  252. {
  253. $mediaCode = pathinfo($mediaCode)['filename'];
  254. $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', [
  255. $userCode,
  256. $mediaCode,
  257. ])->fetch();
  258. return $media;
  259. }
  260. /**
  261. * @param Request $request
  262. * @param Response $response
  263. * @param Filesystem $storage
  264. * @param $media
  265. * @param string $disposition
  266. * @return Response
  267. * @throws FileNotFoundException
  268. */
  269. protected function streamMedia(Request $request, Response $response, Filesystem $storage, $media, string $disposition = 'inline'): Response
  270. {
  271. set_time_limit(0);
  272. $mime = $storage->getMimetype($media->storage_path);
  273. if ($request->getParam('width') !== null && explode('/', $mime)[0] === 'image') {
  274. $image = Image::make($storage->readStream($media->storage_path))
  275. ->resizeCanvas(
  276. $request->getParam('width'),
  277. $request->getParam('height'),
  278. 'center')
  279. ->encode('png');
  280. return $response
  281. ->withHeader('Content-Type', 'image/png')
  282. ->withHeader('Content-Disposition', $disposition . ';filename="scaled-' . pathinfo($media->filename)['filename'] . '.png"')
  283. ->write($image);
  284. } else {
  285. $stream = new Stream($storage->readStream($media->storage_path));
  286. if (!in_array(explode('/', $mime)[0], ['image', 'video', 'audio']) || $disposition === 'attachment') {
  287. return $response->withHeader('Content-Type', $mime)
  288. ->withHeader('Content-Disposition', $disposition . '; filename="' . $media->filename . '"')
  289. ->withHeader('Content-Length', $stream->getSize())
  290. ->withBody($stream);
  291. }
  292. $end = $stream->getSize() - 1;
  293. if ($request->getServerParam('HTTP_RANGE') !== null) {
  294. list(, $range) = explode('=', $request->getServerParam('HTTP_RANGE'), 2);
  295. if (strpos($range, ',') !== false) {
  296. return $response->withHeader('Content-Type', $mime)
  297. ->withHeader('Content-Disposition', $disposition . '; filename="' . $media->filename . '"')
  298. ->withHeader('Content-Length', $stream->getSize())
  299. ->withHeader('Accept-Ranges', 'bytes')
  300. ->withHeader('Content-Range', "0,{$stream->getSize()}")
  301. ->withStatus(416)
  302. ->withBody($stream);
  303. }
  304. if ($range === '-') {
  305. $start = $stream->getSize() - (int)substr($range, 1);
  306. } else {
  307. $range = explode('-', $range);
  308. $start = (int)$range[0];
  309. $end = (isset($range[1]) && is_numeric($range[1])) ? (int)$range[1] : $stream->getSize();
  310. }
  311. $end = ($end > $stream->getSize() - 1) ? $stream->getSize() - 1 : $end;
  312. $stream->seek($start);
  313. header("Content-Type: $mime");
  314. header('Content-Length: ' . ($end - $start + 1));
  315. header('Accept-Ranges: bytes');
  316. header("Content-Range: bytes $start-$end/{$stream->getSize()}");
  317. http_response_code(206);
  318. ob_end_clean();
  319. $buffer = 16348;
  320. $readed = $start;
  321. while ($readed < $end) {
  322. if ($readed + $buffer > $end) {
  323. $buffer = $end - $readed + 1;
  324. }
  325. echo $stream->read($buffer);
  326. $readed += $buffer;
  327. }
  328. exit(0);
  329. }
  330. return $response->withHeader('Content-Type', $mime)
  331. ->withHeader('Content-Length', $stream->getSize())
  332. ->withHeader('Accept-Ranges', 'bytes')
  333. ->withStatus(200)
  334. ->withBody($stream);
  335. }
  336. }
  337. }