1 <?php
declare(strict_types
=1);
4 * This file is part of the Rapsys AirBundle package.
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Rapsys\AirBundle\Controller
;
14 use Symfony\Bridge\Twig\Mime\TemplatedEmail
;
15 use Symfony\Component\Filesystem\Exception\IOExceptionInterface
;
16 use Symfony\Component\Filesystem\Filesystem
;
17 use Symfony\Component\Form\FormError
;
18 use Symfony\Component\HttpFoundation\Request
;
19 use Symfony\Component\HttpFoundation\Response
;
20 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException
;
21 use Symfony\Component\Mailer\Exception\TransportExceptionInterface
;
22 use Symfony\Component\Mime\Address
;
23 use Symfony\Component\Security\Core\Exception\AccessDeniedException
;
25 use Rapsys\AirBundle\Entity\Dance
;
26 use Rapsys\AirBundle\Entity\Location
;
27 use Rapsys\AirBundle\Entity\Session
;
28 use Rapsys\AirBundle\Entity\Snippet
;
29 use Rapsys\AirBundle\Entity\User
;
30 use Rapsys\AirBundle\Token\AnonymousToken
;
35 class DefaultController
extends AbstractController
{
39 * Display the about informations
41 * @param Request $request The request instance
42 * @return Response The rendered view
44 public function about(Request
$request): Response
{
46 $this->context
['title']['page'] = $this->translator
->trans('About');
49 $this->context
['description'] = $this->translator
->trans('Libre Air about');
52 $this->context
['keywords'] = [
53 $this->translator
->trans('about'),
54 $this->translator
->trans('Libre Air')
58 $response = $this->render('@RapsysAir/default/about.html.twig', $this->context
);
59 $response->setEtag(md5($response->getContent()));
60 $response->setPublic();
61 $response->isNotModified($request);
70 * Send a contact mail to configured contact
72 * @param Request $request The request instance
74 * @return Response The rendered view or redirection
76 public function contact(Request
$request): Response
{
78 $this->context
['title']['page'] = $this->translator
->trans('Contact');
81 $this->context
['description'] = $this->translator
->trans('Contact Libre Air');
84 $this->context
['keywords'] = [
85 $this->translator
->trans('contact'),
86 $this->translator
->trans('Libre Air'),
87 $this->translator
->trans('outdoor'),
88 $this->translator
->trans('Argentine Tango'),
89 $this->translator
->trans('calendar')
96 if ($user = $this->security
->getUser()) {
99 'name' => $user->getRecipientName(),
100 'mail' => $user->getMail()
104 //Create the form according to the FormType created previously.
105 //And give the proper parameters
106 $form = $this->factory
->create('Rapsys\AirBundle\Form\ContactType', $data, [
107 'action' => $this->generateUrl('rapsysair_contact'),
112 if ($request->isMethod('POST')) {
113 // Refill the fields in case the form is not valid.
114 $form->handleRequest($request);
116 if ($form->isSubmitted() && $form->isValid()) {
118 $data = $form->getData();
121 $message = (new TemplatedEmail())
123 ->from(new Address($data['mail'], $data['name']))
125 ->to(new Address($this->context
['contact']['address'], $this->context
['contact']['name']))
127 ->subject($data['subject'])
129 //Set path to twig templates
130 ->htmlTemplate('@RapsysAir/mail/contact.html.twig')
131 ->textTemplate('@RapsysAir/mail/contact.text.twig')
136 'subject' => $data['subject'],
137 'message' => strip_tags($data['message']),
141 //Try sending message
142 //XXX: mail delivery may silently fail
145 $this->mailer
->send($message);
147 //Redirect on the same route with sent=1 to cleanup form
148 return $this->redirectToRoute($request->get('_route'), ['sent' => 1]+
$request->get('_route_params'));
149 //Catch obvious transport exception
150 } catch(TransportExceptionInterface
$e) {
151 if ($message = $e->getMessage()) {
152 //Add error message mail unreachable
153 $form->get('mail')->addError(new FormError($this->translator
->trans('Unable to contact: %mail%: %message%', ['%mail%' => $this->context
['contact']['address'], '%message%' => $this->translator
->trans($message)])));
155 //Add error message mail unreachable
156 $form->get('mail')->addError(new FormError($this->translator
->trans('Unable to contact: %mail%', ['%mail%' => $this->context
['contact']['address']])));
163 return $this->render('@RapsysAir/form/contact.html.twig', ['form' => $form->createView(), 'sent' => $request->query
->get('sent', 0)]+
$this->context
);
169 * Display session calendar
171 * @param Request $request The request instance
172 * @return Response The rendered view
174 public function index(Request
$request): Response
{
176 $this->context
['cities'] = $this->doctrine
->getRepository(Location
::class)->findCitiesAsArray($this->period
);
179 $this->context
['calendar'] = $this->doctrine
->getRepository(Session
::class)->findAllByPeriodAsCalendarArray($this->period
, !$this->checker
->isGranted('IS_AUTHENTICATED_REMEMBERED'));
182 $this->context
['dances'] = $this->doctrine
->getRepository(Dance
::class)->findNamesAsArray();
185 $this->modified
= max(array_map(function ($v) { return $v
['modified']; }, array_merge($this->context
['calendar'], $this->context
['cities'], $this->context
['dances'])));
188 $response = new Response();
191 if ($this->checker
->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
193 $response->setLastModified(new \
DateTime('-1 year'));
196 $response->setPrivate();
197 //Without logged user
200 //XXX: only for public to force revalidation by last modified
201 $response->setEtag(md5(serialize(array_merge($this->context
['calendar'], $this->context
['cities'], $this->context
['dances']))));
204 $response->setLastModified($this->modified
);
207 $response->setPublic();
209 //Without role and modification
210 if ($response->isNotModified($request)) {
211 //Return 304 response
217 if (!empty($this->context
['cities'])) {
221 //Iterate on each cities
222 foreach($this->context
['cities'] as $city) {
223 //Iterate on each locations
224 foreach($city['locations'] as $location) {
226 $locations[$location['id']] = $location;
231 $this->context
['multimap'] = $this->map
->getMultiMap($this->translator
->trans('Libre Air cities sector map'), $this->modified
->getTimestamp(), $locations);
234 $cities = array_map(function ($v) { return $v
['in']; }, $this->context
['cities']);
237 $dances = array_map(function ($v) { return $v
['name']; }, $this->context
['dances']);
247 //TODO: use splice instead of that shit !!!
248 //TODO: handle smartly indoor and outdoor !!!
249 $this->context
['keywords'] = array_values(
254 $this->translator
->trans('indoor'),
255 $this->translator
->trans('outdoor'),
256 $this->translator
->trans('calendar'),
257 $this->translator
->trans('Libre Air')
263 $cities = implode($this->translator
->trans(' and '), array_filter(array_merge([implode(', ', array_slice($cities, 0, -1))], array_slice($cities, -1)), 'strlen'));
266 $dances = implode($this->translator
->trans(' and '), array_filter(array_merge([implode(', ', array_slice($dances, 0, -1))], array_slice($dances, -1)), 'strlen'));
269 $this->context
['title']['page'] = $this->translator
->trans('%dances% %cities%', ['%dances%' => $dances, '%cities%' => $cities]);
272 //TODO: handle french translation when city start with a A, change à in en !
273 $this->context
['description'] = $this->translator
->trans('%dances% indoor and outdoor calendar %cities%', ['%dances%' => $dances, '%cities%' => $cities]);
276 //XXX: only valid for home page
277 $this->context
['facebook']['metas']['og:type'] = 'website';
280 return $this->render('@RapsysAir/default/index.html.twig', $this->context
, $response);
284 * The organizer regulation page
286 * Display the organizer regulation policy
288 * @param Request $request The request instance
289 * @return Response The rendered view
291 public function organizerRegulation(Request
$request): Response
{
293 $this->context
['title']['page'] = $this->translator
->trans('Organizer regulation');
296 $this->context
['description'] = $this->translator
->trans('Libre Air organizer regulation');
299 $this->context
['keywords'] = [
300 $this->translator
->trans('organizer regulation'),
301 $this->translator
->trans('Libre Air')
305 $response = $this->render('@RapsysAir/default/organizer_regulation.html.twig', $this->context
);
308 $response->setEtag(md5($response->getContent()));
309 $response->setPublic();
310 $response->isNotModified($request);
317 * The terms of service page
319 * Display the terms of service policy
321 * @param Request $request The request instance
322 * @return Response The rendered view
324 public function termsOfService(Request
$request): Response
{
326 $this->context
['title']['page'] = $this->translator
->trans('Terms of service');
329 $this->context
['description'] = $this->translator
->trans('Libre Air terms of service');
332 $this->context
['keywords'] = [
333 $this->translator
->trans('terms of service'),
334 $this->translator
->trans('Libre Air')
338 $response = $this->render('@RapsysAir/default/terms_of_service.html.twig', $this->context
);
341 $response->setEtag(md5($response->getContent()));
342 $response->setPublic();
343 $response->isNotModified($request);
350 * The frequently asked questions page
352 * Display the frequently asked questions
354 * @param Request $request The request instance
355 * @return Response The rendered view
357 public function frequentlyAskedQuestions(Request
$request): Response
{
359 $this->context
['title']['page'] = $this->translator
->trans('Frequently asked questions');
362 $this->context
['description'] = $this->translator
->trans('Libre Air frequently asked questions');
365 $this->context
['keywords'] = [
366 $this->translator
->trans('frequently asked questions'),
367 $this->translator
->trans('faq'),
368 $this->translator
->trans('Libre Air')
372 $response = $this->render('@RapsysAir/default/frequently_asked_questions.html.twig', $this->context
);
375 $response->setEtag(md5($response->getContent()));
376 $response->setPublic();
377 $response->isNotModified($request);
386 * Display all user with a group listed as users
388 * @param Request $request The request instance
390 * @return Response The rendered view
392 public function userIndex(Request
$request): Response
{
394 if ($this->checker
->isGranted('ROLE_ADMIN')) {
396 $this->context
['title']['page'] = $this->translator
->trans('Libre Air user list');
399 $this->context
['title']['section'] = $this->translator
->trans('User');
402 $this->context
['description'] = $this->translator
->trans('Lists Libre air users');
406 $this->context
['title']['page'] = $this->translator
->trans('Libre Air organizer list');
409 $this->context
['title']['section'] = $this->translator
->trans('Organizer');
412 $this->context
['description'] = $this->translator
->trans('Lists Libre air organizers');
416 $this->context
['keywords'] = [
417 $this->translator
->trans('users'),
418 $this->translator
->trans('user list'),
419 $this->translator
->trans('listing'),
420 $this->translator
->trans('Libre Air')
424 $users = $this->doctrine
->getRepository(User
::class)->findIndexByGroupId();
427 if ($this->checker
->isGranted('ROLE_ADMIN')) {
429 $this->context
['groups'] = $users;
432 //Only display senior organizers
433 $this->context
['users'] = $users[$this->translator
->trans('Senior')];
437 return $this->render('@RapsysAir/user/index.html.twig', $this->context
);
441 * List all sessions for the user
443 * Display all sessions for the user with an application or login form
445 * @param Request $request The request instance
446 * @param int $id The user id
448 * @return Response The rendered view
450 public function userView(Request
$request, int $id, ?string $user): Response
{
452 if (empty($this->context
['user'] = $this->doctrine
->getRepository(User
::class)->findOneByIdAsArray($id, $this->locale
))) {
454 throw new NotFoundHttpException($this->translator
->trans('Unable to find user: %id%', ['%id%' => $id]));
458 $token = new AnonymousToken($this->context
['user']['roles']);
460 //Prevent access when not admin, user is not guest and not currently logged user
461 if (!($isAdmin = $this->checker
->isGranted('ROLE_ADMIN')) && !($isGuest = $this->decision
->decide($token, ['ROLE_GUEST']))) {
462 //Throw access denied
463 throw new AccessDeniedException($this->translator
->trans('Unable to access user: %id%', ['%id%' => $id]));
466 //With invalid user slug
467 if ($this->context
['user']['slug'] !== $user) {
468 //Redirect to cleaned url
469 return $this->redirectToRoute('rapsysair_user_view', ['id' => $id, 'user' => $this->context
['user']['slug']]);
473 $this->context
['calendar'] = $this->doctrine
->getRepository(Session
::class)->findAllByPeriodAsCalendarArray($this->period
, !$this->checker
->isGranted('IS_AUTHENTICATED_REMEMBERED'), null, null, $id);
475 //Get locations at less than 2 km
476 $this->context
['locations'] = $this->doctrine
->getRepository(Location
::class)->findAllByUserIdAsArray($id, $this->period
, 2);
499 //Iterate on each calendar
500 foreach($this->context
['calendar'] as $date => $calendar) {
501 //Iterate on each session
502 foreach($calendar['sessions'] as $sessionId => $session) {
504 $dances[$session['application']['dance']['name']] = $session['application']['dance']['name'];
507 $types[$session['application']['dance']['type']] = lcfirst($session['application']['dance']['type']);
510 $indoors[$session['location']['indoor']?'indoor':'outdoor'] = $this->translator
->trans($session['location']['indoor']?'indoor':'outdoor');
513 $insides[$session['location']['indoor']?'inside':'outside'] = $this->translator
->trans($session['location']['indoor']?'inside':'outside');
516 $ats[$session['location']['id']] = $session['location']['at'];
519 $ins[$session['location']['id']] = $session['location']['in'];
521 //Session with application user id
522 if (!empty($session['application']['user']['id']) && $session['application']['user']['id'] == $id) {
524 $locations[$session['location']['id']] = $session['location'];
530 //XXX: dance modified is already computed inside calendar modified
531 $this->modified
= max(array_merge([$this->context
['user']['modified']], array_map(function ($v) { return $v
['modified']; }, array_merge($this->context
['calendar'], $this->context
['locations']))));
534 $response = new Response();
537 if ($this->checker
->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
539 $response->setLastModified(new \
DateTime('-1 year'));
542 $response->setPrivate();
543 //Without logged user
546 //XXX: only for public to force revalidation by last modified
547 $response->setEtag(md5(serialize(array_merge($this->context
['user'], $this->context
['calendar'], $this->context
['locations']))));
550 $response->setLastModified($this->modified
);
553 $response->setPublic();
555 //Without role and modification
556 if ($response->isNotModified($request)) {
557 //Return 304 response
563 $this->context
['multimap'] = $this->map
->getMultiMap($this->context
['user']['multimap'], $this->modified
->getTimestamp(), $this->context
['locations']);
566 $this->context
['keywords'] = [
567 $this->context
['user']['pseudonym'],
568 $this->translator
->trans('calendar'),
569 $this->translator
->trans('Libre Air')
573 $cities = array_unique(array_map(function ($v) { return $v
['city']; }, $locations));
576 $titles = array_map(function ($v) { return $v
['title']; }, $locations);
578 //Insert dances in keywords
579 array_splice($this->context
['keywords'], 1, 0, array_merge($types, $dances, $indoors, $insides, $titles, $cities));
582 $ins = array_unique($ins);
585 $dances = implode($this->translator
->trans(' and '), array_filter(array_merge([implode(', ', array_slice($dances, 0, -1))], array_slice($dances, -1)), 'strlen'));
588 $types = implode($this->translator
->trans(' and '), array_filter(array_merge([implode(', ', array_slice($types, 0, -1))], array_slice($types, -1)), 'strlen'));
590 //Get textual indoors
591 $indoors = implode($this->translator
->trans(' and '), array_filter(array_merge([implode(', ', array_slice($indoors, 0, -1))], array_slice($indoors, -1)), 'strlen'));
594 $ats = implode($this->translator
->trans(' and '), array_filter(array_merge([implode(', ', array_slice($ats, 0, -1))], array_slice($ats, -1)), 'strlen'));
597 $ins = implode($this->translator
->trans(' and '), array_filter(array_merge([implode(', ', array_slice($ins, 0, -1))], array_slice($ins, -1)), 'strlen'));
600 $this->context
['title']['page'] = $this->translator
->trans('%pseudonym% organizer', ['%pseudonym%' => $this->context
['user']['pseudonym']]);
603 $this->context
['title']['section'] = $this->translator
->trans('User');
606 if (!empty($locations)) {
608 $this->context
['description'] = ucfirst($this->translator
->trans('%dances% %types% %indoors% calendar %ats% %ins% %pseudonym%', ['%dances%' => $dances, '%types%' => $types, '%indoors%' => $indoors, '%ats%' => $ats, '%ins%' => $ins, '%pseudonym%' => $this->translator
->trans('by %pseudonym%', ['%pseudonym%' => $this->context
['user']['pseudonym']])]));
612 $this->context
['description'] = $this->translator
->trans('%pseudonym% calendar', ['%pseudonym%' => $this->context
['user']['pseudonym']]);
615 //Set user description
616 $this->context
['locations_description'] = $this->translator
->trans('Libre Air %pseudonym% location list', ['%pseudonym%' => $this->translator
->trans('by %pseudonym%', ['%pseudonym%' => $this->context
['user']['pseudonym']])]);
619 $this->context
['alternates'] +
= $this->context
['user']['alternates'];
621 //Create snippet forms for role_guest
622 //TODO: optimize this call
623 if ($isAdmin || $isGuest && $this->security
->getUser() && $this->context
['user']['id'] == $this->security
->getUser()->getId()) {
624 //Fetch all user snippet
625 $snippets = $this->doctrine
->getRepository(Snippet
::class)->findByUserIdLocaleIndexByLocationId($id, $this->locale
);
628 $user = $this->doctrine
->getRepository(User
::class)->findOneById($id);
630 //Iterate on locations
631 foreach($this->context
['locations'] as $locationId => $location) {
632 //With existing snippet
633 if (isset($snippets[$location['id']])) {
634 //Set existing in current
635 $current = $snippets[$location['id']];
636 //Without existing snippet
639 $current = new Snippet($this->locale
, $this->doctrine
->getRepository(Location
::class)->findOneById($location['id']), $user);
642 //Create SnippetType form
643 $form = $this->factory
->createNamed(
645 'snippet_'.$locationId.'_'.$id.'_'.$this->locale
,
647 'Rapsys\AirBundle\Form\SnippetType',
652 //Refill the fields in case of invalid form
653 $form->handleRequest($request);
655 //Handle submitted and valid form
656 //TODO: add a delete snippet ?
657 if ($form->isSubmitted() && $form->isValid()) {
659 $snippet = $form->getData();
662 $this->manager
->persist($snippet);
664 //Flush to get the ids
665 $this->manager
->flush();
668 $this->addFlash('notice', $this->translator
->trans('Snippet for %user% %location% updated', ['%location%' => $location['at'], '%user%' => $this->context
['user']['pseudonym']]));
670 //Redirect to cleaned url
671 return $this->redirectToRoute('rapsysair_user_view', ['id' => $id, 'user' => $this->context
['user']['slug']]);
674 //Add form to context
675 $this->context
['forms']['snippets'][$locationId] = $form->createView();
677 //With location user source image
678 if (($isFile = is_file($source = $this->config
['path'].'/location/'.$location['id'].'/'.$id.'.png')) && ($mtime = stat($source)['mtime'])) {
680 $this->context
['locations'][$locationId]['image'] = $this->image
->getThumb($location['miniature'], $mtime, $source);
683 //Create ImageType form
684 $form = $this->factory
->createNamed(
686 'image_'.$locationId.'_'.$id,
688 'Rapsys\AirBundle\Form\ImageType',
692 'location' => $location['id'],
696 //Set form attributes
698 //Enable delete with image
699 'delete' => isset($this->context
['locations'][$locationId]['image'])
703 //Refill the fields in case of invalid form
704 $form->handleRequest($request);
706 //Handle submitted and valid form
707 if ($form->isSubmitted() && $form->isValid()) {
709 if ($form->has('delete') && $form->get('delete')->isClicked()) {
710 //With source and mtime
711 if ($isFile && !empty($source) && !empty($mtime)) {
713 $this->image
->remove($mtime, $source);
716 unlink($this->config
['path'].'/location/'.$location['id'].'/'.$id.'.png');
719 $this->addFlash('notice', $this->translator
->trans('Image for %user% %location% deleted', ['%location%' => $location['at'], '%user%' => $this->context
['user']['pseudonym']]));
721 //Redirect to cleaned url
722 return $this->redirectToRoute('rapsysair_user_view', ['id' => $id, 'user' => $this->context
['user']['slug']]);
727 if ($image = $form->get('image')->getData()) {
729 if (!is_dir($dir = dirname($source))) {
730 //Create filesystem object
731 $filesystem = new Filesystem();
735 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
736 $filesystem->mkdir($dir, 0775);
737 } catch (IOExceptionInterface
$e) {
739 throw new \
Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
744 $source = realpath($dir).'/'.basename($source);
746 //Create imagick object
747 $imagick = new \
Imagick();
750 $imagick->readImage($image->getRealPath());
753 if (!$imagick->writeImage($source)) {
755 throw new \
Exception(sprintf('Unable to write image "%s"', $source));
759 $this->addFlash('notice', $this->translator
->trans('Image for %user% %location% updated', ['%location%' => $location['at'], '%user%' => $this->context
['user']['pseudonym']]));
761 //Redirect to cleaned url
762 return $this->redirectToRoute('rapsysair_user_view', ['id' => $id, 'user' => $this->context
['user']['slug']]);
766 //Add form to context
767 $this->context
['forms']['images'][$locationId] = $form->createView();
772 return $this->render('@RapsysAir/user/view.html.twig', ['id' => $id]+
$this->context
);