X-Git-Url: https://git.rapsys.eu/.gitweb.cgi/airbundle/blobdiff_plain/8f0170592aae8d14079f332538767b0e9633c3e1..e9efd1dbb1ba121c3ba1cd6c63bc3b7a06fe093d:/Controller/DefaultController.php?ds=inline diff --git a/Controller/DefaultController.php b/Controller/DefaultController.php index 49ad3c3..e28e661 100644 --- a/Controller/DefaultController.php +++ b/Controller/DefaultController.php @@ -1,112 +1,32 @@ - + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ namespace Rapsys\AirBundle\Controller; use Symfony\Bridge\Twig\Mime\TemplatedEmail; -use Symfony\Component\DependencyInjection\ContainerAwareTrait; -use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Form\FormError; use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Mailer\Exception\TransportExceptionInterface; use Symfony\Component\Mailer\MailerInterface; use Symfony\Component\Mime\Address; -use Symfony\Component\Routing\RouterInterface; -use Symfony\Component\Translation\TranslatorInterface; use Rapsys\AirBundle\Entity\Location; use Rapsys\AirBundle\Entity\Session; use Rapsys\AirBundle\Pdf\DisputePdf; +/** + * {@inheritdoc} + */ class DefaultController extends AbstractController { - ///Config array - protected $config; - - ///ContainerInterface instance - protected $container; - - ///Context array - protected $context; - - ///Router instance - protected $router; - - ///Translator instance - protected $translator; - - ///Request instance - protected $request; - - ///Locale instance - protected $locale; - - /** - * Inject container, router and translator interface - * - * @param ContainerInterface $container The container instance - * @param RouterInterface $router The router instance - * @param TranslatorInterface $translator The translator instance - */ - public function __construct(ContainerInterface $container, RouterInterface $router, TranslatorInterface $translator) { - //Retrieve config - $this->config = $container->getParameter(self::getAlias()); - - //Set the container - $this->container = $container; - - //Set the router - $this->router = $router; - - //Set the translator - $this->translator = $translator; - - //Set the context - $this->context = [ - 'contact' => [ - 'title' => $translator->trans($this->config['contact']['title']), - 'mail' => $this->config['contact']['mail'] - ], - 'copy' => [ - 'by' => $translator->trans($this->config['copy']['by']), - 'link' => $this->config['copy']['link'], - 'long' => $translator->trans($this->config['copy']['long']), - 'short' => $translator->trans($this->config['copy']['short']), - 'title' => $this->config['copy']['title'] - ], - 'page' => [ - 'description' => null, - 'section' => null, - 'title' => null - ], - 'site' => [ - 'donate' => $this->config['site']['donate'], - 'ico' => $this->config['site']['ico'], - 'logo' => $this->config['site']['logo'], - 'png' => $this->config['site']['png'], - 'svg' => $this->config['site']['svg'], - 'title' => $translator->trans($this->config['site']['title']), - 'url' => $router->generate($this->config['site']['url']) - ], - 'canonical' => null, - 'alternates' => [], - 'facebook' => [ - 'heads' => [ - 'og' => 'http://ogp.me/ns#', - 'fb' => 'http://ogp.me/ns/fb#' - ], - 'metas' => [ - 'og:type' => 'article', - 'og:site_name' => $this->translator->trans($this->config['site']['title']), - #'fb:admins' => $this->config['facebook']['admins'], - 'fb:app_id' => $this->config['facebook']['apps'] - ], - 'texts' => [] - ], - 'forms' => [] - ]; - } - /** * The about page * @@ -117,10 +37,10 @@ class DefaultController extends AbstractController { */ public function about(Request $request): Response { //Set page - $this->context['page']['title'] = $this->translator->trans('About'); + $this->context['title'] = $this->translator->trans('About'); //Set description - $this->context['page']['description'] = $this->translator->trans('Libre Air about'); + $this->context['description'] = $this->translator->trans('Libre Air about'); //Set keywords $this->context['keywords'] = [ @@ -150,10 +70,10 @@ class DefaultController extends AbstractController { */ public function contact(Request $request, MailerInterface $mailer): Response { //Set page - $this->context['page']['title'] = $this->translator->trans('Contact'); + $this->context['title'] = $this->translator->trans('Contact'); //Set description - $this->context['page']['description'] = $this->translator->trans('Contact Libre Air'); + $this->context['description'] = $this->translator->trans('Contact Libre Air'); //Set keywords $this->context['keywords'] = [ @@ -240,10 +160,10 @@ class DefaultController extends AbstractController { $this->denyAccessUnlessGranted('ROLE_USER', null, $this->translator->trans('Unable to access this page without role %role%!', ['%role%' => $this->translator->trans('User')])); //Set page - $this->context['page']['title'] = $this->translator->trans('Dispute'); + $this->context['title'] = $this->translator->trans('Dispute'); //Set description - $this->context['page']['description'] = $this->translator->trans('Libre Air dispute'); + $this->context['description'] = $this->translator->trans('Libre Air dispute'); //Set keywords $this->context['keywords'] = [ @@ -360,10 +280,10 @@ class DefaultController extends AbstractController { $doctrine = $this->getDoctrine(); //Set page - $this->context['page']['title'] = $this->translator->trans('Argentine Tango in Paris'); + $this->context['title'] = $this->translator->trans('Argentine Tango in Paris'); //Set description - $this->context['page']['description'] = $this->translator->trans('Outdoor Argentine Tango session calendar in Paris'); + $this->context['description'] = $this->translator->trans('Outdoor Argentine Tango session calendar in Paris'); //Set keywords $this->context['keywords'] = [ @@ -391,7 +311,7 @@ class DefaultController extends AbstractController { ); //Fetch calendar - $calendar = $doctrine->getRepository(Session::class)->fetchCalendarByDatePeriod($this->translator, $period, null, $request->get('session'), !$this->isGranted('IS_AUTHENTICATED_REMEMBERED')); + $calendar = $doctrine->getRepository(Session::class)->fetchCalendarByDatePeriod($this->translator, $period, null, $request->get('session'), !$this->isGranted('IS_AUTHENTICATED_REMEMBERED'), $request->getLocale()); //Fetch locations //XXX: we want to display all active locations anyway @@ -421,10 +341,10 @@ class DefaultController extends AbstractController { */ public function organizerRegulation(Request $request): Response { //Set page - $this->context['page']['title'] = $this->translator->trans('Organizer regulation'); + $this->context['title'] = $this->translator->trans('Organizer regulation'); //Set description - $this->context['page']['description'] = $this->translator->trans('Libre Air organizer regulation'); + $this->context['description'] = $this->translator->trans('Libre Air organizer regulation'); //Set keywords $this->context['keywords'] = [ @@ -454,10 +374,10 @@ class DefaultController extends AbstractController { */ public function termsOfService(Request $request): Response { //Set page - $this->context['page']['title'] = $this->translator->trans('Terms of service'); + $this->context['title'] = $this->translator->trans('Terms of service'); //Set description - $this->context['page']['description'] = $this->translator->trans('Libre Air terms of service'); + $this->context['description'] = $this->translator->trans('Libre Air terms of service'); //Set keywords $this->context['keywords'] = [ @@ -487,10 +407,10 @@ class DefaultController extends AbstractController { */ public function frequentlyAskedQuestions(Request $request): Response { //Set page - $this->context['page']['title'] = $this->translator->trans('Frequently asked questions'); + $this->context['title'] = $this->translator->trans('Frequently asked questions'); //Set description - $this->context['page']['description'] = $this->translator->trans('Libre Air frequently asked questions'); + $this->context['description'] = $this->translator->trans('Libre Air frequently asked questions'); //Set keywords $this->context['keywords'] = [ @@ -512,21 +432,300 @@ class DefaultController extends AbstractController { } /** - * Return the bundle alias + * List all users + * + * @desc Display all user with a group listed as users + * + * @param Request $request The request instance * - * {@inheritdoc} + * @return Response The rendered view */ - public function getAlias(): string { - return 'rapsys_air'; + public function userIndex(Request $request): Response { + //Fetch doctrine + $doctrine = $this->getDoctrine(); + + //With admin role + if ($this->isGranted('ROLE_ADMIN')) { + //Set section + $section = $this->translator->trans('Libre Air users'); + + //Set description + $this->context['description'] = $this->translator->trans('Libre Air user list'); + //Without admin role + } else { + //Set section + $section = $this->translator->trans('Libre Air organizers'); + + //Set description + $this->context['description'] = $this->translator->trans('Libre Air organizers list'); + } + + //Set keywords + $this->context['keywords'] = [ + $this->translator->trans('users'), + $this->translator->trans('user list'), + $this->translator->trans('listing'), + $this->translator->trans('Libre Air') + ]; + + //Set title + $title = $this->translator->trans($this->config['site']['title']).' - '.$section; + + //Fetch users + $users = $doctrine->getRepository(User::class)->findUserGroupedByTranslatedGroup($this->translator); + + //Compute period + $period = new \DatePeriod( + //Start from first monday of week + new \DateTime('Monday this week'), + //Iterate on each day + new \DateInterval('P1D'), + //End with next sunday and 4 weeks + new \DateTime( + $this->isGranted('IS_AUTHENTICATED_REMEMBERED')?'Monday this week + 3 week':'Monday this week + 2 week' + ) + ); + + //With admin role + if ($this->isGranted('ROLE_ADMIN')) { + //Display all users + $this->context['groups'] = $users; + //Without admin role + } else { + //Only display senior organizers + $this->context['users'] = $users[$this->translator->trans('Senior')]; + } + + //Fetch locations + //XXX: we want to display all active locations anyway + $locations = $doctrine->getRepository(Location::class)->findTranslatedSortedByPeriod($this->translator, $period); + + //Render the view + return $this->render('@RapsysAir/user/index.html.twig', ['title' => $title, 'section' => $section, 'locations' => $locations]+$this->context); } /** - * Renders a view + * List all sessions for the user * - * {@inheritdoc} + * @desc Display all sessions for the user with an application or login form + * + * @param Request $request The request instance + * @param int $id The user id + * + * @return Response The rendered view */ - /*protected function render(string $view, array $parameters = [], Response $response = null): Response { - //Call parent render - return parent::render($view, $parameters, $response); - }*/ + public function userView(Request $request, $id): Response { + //Fetch doctrine + $doctrine = $this->getDoctrine(); + + //Fetch user + if (empty($user = $doctrine->getRepository(User::class)->findOneById($id))) { + throw $this->createNotFoundException($this->translator->trans('Unable to find user: %id%', ['%id%' => $id])); + } + + //Get user token + $token = new UsernamePasswordToken($user, null, 'none', $user->getRoles()); + + //Check if guest + $isGuest = $this->get('rapsys_user.access_decision_manager')->decide($token, ['ROLE_GUEST']); + + //Prevent access when not admin, user is not guest and not currently logged user + if (!$this->isGranted('ROLE_ADMIN') && empty($isGuest) && $user != $this->getUser()) { + throw $this->createAccessDeniedException($this->translator->trans('Unable to access user: %id%', ['%id%' => $id])); + } + + //Set section + $section = $user->getPseudonym(); + + //Set title + $title = $this->translator->trans($this->config['site']['title']).' - '.$section; + + //Set description + $this->context['description'] = $this->translator->trans('%pseudonym% outdoor Argentine Tango session calendar', [ '%pseudonym%' => $user->getPseudonym() ]); + + //Set keywords + $this->context['keywords'] = [ + $user->getPseudonym(), + $this->translator->trans('outdoor'), + $this->translator->trans('Argentine Tango'), + $this->translator->trans('calendar') + ]; + + //Compute period + $period = new \DatePeriod( + //Start from first monday of week + new \DateTime('Monday this week'), + //Iterate on each day + new \DateInterval('P1D'), + //End with next sunday and 4 weeks + new \DateTime( + $this->isGranted('IS_AUTHENTICATED_REMEMBERED')?'Monday this week + 3 week':'Monday this week + 2 week' + ) + ); + + //Fetch calendar + //TODO: highlight with current session route parameter + $calendar = $doctrine->getRepository(Session::class)->fetchUserCalendarByDatePeriod($this->translator, $period, $isGuest?$id:null, $request->get('session'), $request->getLocale()); + + //Fetch locations + //XXX: we want to display all active locations anyway + $locations = $doctrine->getRepository(Location::class)->findTranslatedSortedByPeriod($this->translator, $period, $id); + + //Create user form for admin or current user + if ($this->isGranted('ROLE_ADMIN') || $user == $this->getUser()) { + //Create SnippetType form + $userForm = $this->createForm('Rapsys\AirBundle\Form\RegisterType', $user, [ + //Set action + 'action' => $this->generateUrl('rapsys_air_user_view', ['id' => $id]), + //Set the form attribute + 'attr' => [ 'class' => 'col' ], + //Set civility class + 'civility_class' => Civility::class, + //Disable mail + 'mail' => $this->isGranted('ROLE_ADMIN'), + //Disable password + 'password' => false + ]); + + //Init user to context + $this->context['forms']['user'] = $userForm->createView(); + + //Check if submitted + if ($request->isMethod('POST')) { + //Refill the fields in case the form is not valid. + $userForm->handleRequest($request); + + //Handle invalid form + if (!$userForm->isSubmitted() || !$userForm->isValid()) { + //Render the view + return $this->render('@RapsysAir/user/view.html.twig', ['id' => $id, 'title' => $title, 'section' => $section, 'calendar' => $calendar, 'locations' => $locations]+$this->context); + } + + //Get data + $data = $userForm->getData(); + + //Get manager + $manager = $doctrine->getManager(); + + //Queue snippet save + $manager->persist($data); + + //Flush to get the ids + $manager->flush(); + + //Add notice + $this->addFlash('notice', $this->translator->trans('User %id% updated', ['%id%' => $id])); + + //Extract and process referer + if ($referer = $request->headers->get('referer')) { + //Create referer request instance + $req = Request::create($referer); + + //Get referer path + $path = $req->getPathInfo(); + + //Get referer query string + $query = $req->getQueryString(); + + //Remove script name + $path = str_replace($request->getScriptName(), '', $path); + + //Try with referer path + try { + //Save old context + $oldContext = $this->router->getContext(); + + //Force clean context + //XXX: prevent MethodNotAllowedException because current context method is POST in onevendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php+42 + $this->router->setContext(new RequestContext()); + + //Retrieve route matching path + $route = $this->router->match($path); + + //Reset context + $this->router->setContext($oldContext); + + //Clear old context + unset($oldContext); + + //Extract name + $name = $route['_route']; + + //Remove route and controller from route defaults + unset($route['_route'], $route['_controller']); + + //Check if user view route + if ($name == 'rapsys_air_user_view' && !empty($route['id'])) { + //Replace id + $route['id'] = $data->getId(); + //Other routes + } else { + //Set user + $route['user'] = $data->getId(); + } + + //Generate url + return $this->redirectToRoute($name, $route); + //No route matched + } catch(MethodNotAllowedException|ResourceNotFoundException $e) { + //Unset referer to fallback to default route + unset($referer); + } + } + + //Redirect to cleanup the form + return $this->redirectToRoute('rapsys_air', ['user' => $data->getId()]); + } + } + + //Create snippet forms for role_guest + if ($this->isGranted('ROLE_ADMIN') || ($this->isGranted('ROLE_GUEST') && $user == $this->getUser())) { + //Fetch all user snippet + $snippets = $doctrine->getRepository(Snippet::class)->findByLocaleUserId($request->getLocale(), $id); + + //Rekey by location id + $snippets = array_reduce($snippets, function($carry, $item){$carry[$item->getLocation()->getId()] = $item; return $carry;}, []); + + //Init snippets to context + $this->context['forms']['snippets'] = []; + + //Iterate on locations + foreach($locations as $locationId => $location) { + //Init snippet + $snippet = new Snippet(); + + //Set default locale + $snippet->setLocale($request->getLocale()); + + //Set default user + $snippet->setUser($user); + + //Set default location + $snippet->setLocation($doctrine->getRepository(Location::class)->findOneById($locationId)); + + //With existing snippet + if (!empty($snippets[$locationId])) { + $snippet = $snippets[$locationId]; + $action = $this->generateUrl('rapsys_air_snippet_edit', ['id' => $snippet->getId()]); + //Without snippet + } else { + $action = $this->generateUrl('rapsys_air_snippet_add', ['location' => $locationId]); + } + + //Create SnippetType form + $form = $this->container->get('form.factory')->createNamed('snipped_'.$request->getLocale().'_'.$locationId, 'Rapsys\AirBundle\Form\SnippetType', $snippet, [ + //Set the action + 'action' => $action, + //Set the form attribute + 'attr' => [] + ]); + + //Add form to context + $this->context['forms']['snippets'][$locationId] = $form->createView(); + } + } + + //Render the view + return $this->render('@RapsysAir/user/view.html.twig', ['id' => $id, 'title' => $title, 'section' => $section, 'calendar' => $calendar, 'locations' => $locations]+$this->context); + } }