Controller.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace App\Controllers;
  3. use App\Database\DB;
  4. use App\Web\Lang;
  5. use App\Web\Session;
  6. use DI\Container;
  7. use DI\DependencyException;
  8. use DI\NotFoundException;
  9. use League\Flysystem\FileNotFoundException;
  10. use League\Flysystem\Filesystem;
  11. use Monolog\Logger;
  12. use Psr\Http\Message\ServerRequestInterface as Request;
  13. use Slim\Exception\HttpNotFoundException;
  14. use Slim\Exception\HttpUnauthorizedException;
  15. use Twig\Environment;
  16. /**
  17. * @property Session|null session
  18. * @property Environment view
  19. * @property DB|null database
  20. * @property Logger|null logger
  21. * @property Filesystem|null storage
  22. * @property Lang lang
  23. * @property array config
  24. */
  25. abstract class Controller
  26. {
  27. /** @var Container */
  28. protected $container;
  29. public function __construct(Container $container)
  30. {
  31. $this->container = $container;
  32. }
  33. /**
  34. * @param $name
  35. * @return mixed|null
  36. * @throws DependencyException
  37. * @throws NotFoundException
  38. */
  39. public function __get($name)
  40. {
  41. if ($this->container->has($name)) {
  42. return $this->container->get($name);
  43. }
  44. return null;
  45. }
  46. /**
  47. * @param $id
  48. * @return int
  49. */
  50. protected function getUsedSpaceByUser($id): int
  51. {
  52. $medias = $this->database->query('SELECT `uploads`.`storage_path` FROM `uploads` WHERE `user_id` = ?', $id);
  53. $totalSize = 0;
  54. $filesystem = $this->storage;
  55. foreach ($medias as $media) {
  56. try {
  57. $totalSize += $filesystem->getSize($media->storage_path);
  58. } catch (FileNotFoundException $e) {
  59. $this->logger->error('Error calculating file size', ['exception' => $e]);
  60. }
  61. }
  62. return $totalSize;
  63. }
  64. /**
  65. * @param Request $request
  66. * @param $id
  67. * @param bool $authorize
  68. * @return mixed
  69. * @throws HttpNotFoundException
  70. * @throws HttpUnauthorizedException
  71. */
  72. protected function getUser(Request $request, $id, $authorize = false)
  73. {
  74. $user = $this->database->query('SELECT * FROM `users` WHERE `id` = ? LIMIT 1', $id)->fetch();
  75. if (!$user) {
  76. throw new HttpNotFoundException($request);
  77. }
  78. if ($authorize && $user->id !== $this->session->get('user_id') && !$this->session->get('admin', false)) {
  79. throw new HttpUnauthorizedException($request);
  80. }
  81. return $user;
  82. }
  83. }