upstream V3 development https://www.gnusocial.rocks/v3
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

219 wiersze
7.2 KiB

  1. <?php
  2. // {{{ License
  3. // This file is part of GNU social - https://www.gnu.org/software/social
  4. //
  5. // GNU social is free software: you can redistribute it and/or modify
  6. // it under the terms of the GNU Affero General Public License as published by
  7. // the Free Software Foundation, either version 3 of the License, or
  8. // (at your option) any later version.
  9. //
  10. // GNU social is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. // GNU Affero General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU Affero General Public License
  16. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  17. // }}}
  18. /**
  19. * Base class for controllers
  20. *
  21. * @package GNUsocial
  22. * @category Controller
  23. *
  24. * @author Hugo Sales <hugo@hsal.es>
  25. * @copyright 2020-2021 Free Software Foundation, Inc http://www.fsf.org
  26. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  27. */
  28. namespace App\Core;
  29. use function App\Core\I18n\_m;
  30. use App\Util\Common;
  31. use App\Util\Exception\ClientException;
  32. use App\Util\Exception\RedirectException;
  33. use Exception;
  34. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  35. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  36. use Symfony\Component\HttpFoundation\JsonResponse;
  37. use Symfony\Component\HttpFoundation\RedirectResponse;
  38. use Symfony\Component\HttpFoundation\Request;
  39. use Symfony\Component\HttpFoundation\RequestStack;
  40. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  41. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  42. use Symfony\Component\HttpKernel\Event\ViewEvent;
  43. use Symfony\Component\HttpKernel\KernelEvents;
  44. use Symfony\Component\Validator\Exception\ValidatorException;
  45. /**
  46. * @method int int(string $param)
  47. * @method bool bool(string $param)
  48. * @method string string(string $param)
  49. * @method mixed handle(Request $request, mixed ...$extra)
  50. */
  51. abstract class Controller extends AbstractController implements EventSubscriberInterface
  52. {
  53. private array $vars = [];
  54. protected ?Request $request = null;
  55. public function __construct(RequestStack $requestStack)
  56. {
  57. $this->request = $requestStack->getCurrentRequest();
  58. }
  59. /**
  60. * TODO: Not currently used, so not tested, but should be
  61. *
  62. * @codeCoverageIgnore
  63. */
  64. public function __invoke(Request $request)
  65. {
  66. $this->request = $request;
  67. $class = static::class;
  68. $method = 'on' . ucfirst(strtolower($request->getMethod()));
  69. $attributes = array_diff_key($request->attributes->get('_route_params'), array_flip(['_format', '_fragment', '_locale', 'template', 'accept', 'is_system_path']));
  70. if (method_exists($class, $method)) {
  71. return $this->{$method}($request, ...$attributes);
  72. } else {
  73. return $this->handle($request, ...$attributes);
  74. }
  75. }
  76. /**
  77. * Symfony event when it's searching for which controller to use
  78. */
  79. public function onKernelController(ControllerEvent $event)
  80. {
  81. $controller = $event->getController();
  82. $request = $event->getRequest();
  83. $this->request = $request;
  84. $this->vars = ['controller' => $controller, 'request' => $request];
  85. $user = Common::user();
  86. if ($user !== null) {
  87. $this->vars['current_actor'] = $user->getActor();
  88. }
  89. $event->stopPropagation();
  90. return $event;
  91. }
  92. /**
  93. * Symfony event when the controller result is not a Response object
  94. */
  95. public function onKernelView(ViewEvent $event)
  96. {
  97. $request = $event->getRequest();
  98. $response = $event->getControllerResult();
  99. if (!is_array($response)) {
  100. // This means it's not one of our custom format responses, nothing to do
  101. // @codeCoverageIgnoreStart
  102. return $event;
  103. // @codeCoverageIgnoreEnd
  104. }
  105. $this->vars = array_merge_recursive($this->vars, $response);
  106. $template = $this->vars['_template'];
  107. unset($this->vars['_template'], $response['_template']);
  108. // Respond in the most preferred acceptable content type
  109. $accept = $request->getAcceptableContentTypes() ?: ['text/html'];
  110. $format = $request->getFormat($accept[0]);
  111. $potential_response = null;
  112. if (Event::handle('ControllerResponseInFormat', [
  113. 'route' => $request->get('_route'),
  114. 'accept_header' => $accept,
  115. 'vars' => $this->vars,
  116. 'response' => &$potential_response,
  117. ]) !== Event::stop) {
  118. switch ($format) {
  119. case 'html':
  120. $event->setResponse($this->render($template, $this->vars));
  121. break;
  122. case 'json':
  123. $event->setResponse(new JsonResponse($response));
  124. break;
  125. default:
  126. throw new ClientException(_m('Unsupported format: {format}', ['format' => $format]), 406); // 406 Not Acceptable
  127. }
  128. } else {
  129. $event->setResponse($potential_response);
  130. }
  131. Event::handle('CleanupModule');
  132. return $event;
  133. }
  134. /**
  135. * Symfony event when the controller throws an exception
  136. *
  137. * @codeCoverageIgnore
  138. */
  139. public function onKernelException(ExceptionEvent $event)
  140. {
  141. $except = $event->getThrowable();
  142. if ($_ENV['APP_ENV'] !== 'dev') {
  143. // TODO: This is where our custom exception pages could go
  144. // $event->setResponse((new Response())->setStatusCode(455));
  145. }
  146. do {
  147. if ($except instanceof RedirectException) {
  148. if (($redir = $except->redirect_response) != null) {
  149. $event->setResponse($redir);
  150. } else {
  151. $event->setResponse(new RedirectResponse($event->getRequest()->getPathInfo()));
  152. }
  153. }
  154. } while ($except != null && ($except = $except->getPrevious()) != null);
  155. Event::handle('CleanupModule');
  156. return $event;
  157. }
  158. /**
  159. * @codeCoverageIgnore
  160. */
  161. public static function getSubscribedEvents()
  162. {
  163. return [
  164. KernelEvents::CONTROLLER => 'onKernelController',
  165. KernelEvents::EXCEPTION => 'onKernelException',
  166. KernelEvents::VIEW => 'onKernelView',
  167. ];
  168. }
  169. /**
  170. * Get and convert GET parameters. Can be called with `int`, `bool`, `string`, etc
  171. *
  172. * @throws ValidatorException
  173. * @throws Exception
  174. *
  175. * @return null|mixed the value or null if no paramter exists
  176. */
  177. public function __call(string $method, array $args)
  178. {
  179. $name = $args[0];
  180. $value = $this->request->query->get($name);
  181. switch ($method) {
  182. case 'int':
  183. return (int) $value;
  184. case 'bool':
  185. return (bool) $value;
  186. case 'string':
  187. return (string) $value;
  188. default:
  189. // @codeCoverageIgnoreStart
  190. Log::critical($m = "Method '{$method}' on class App\\Core\\Controller not found (__call)");
  191. throw new Exception($m);
  192. // @codeCoverageIgnoreEnd
  193. }
  194. }
  195. }