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'])) {
224 //Iterate on each cities
225 foreach($this->context
['cities'] as $city) {
226 //Iterate on each locations
227 foreach($city['locations'] as $location) {
229 $locations[$location['id']] = $location;
231 $coordinates[] = [ $location['latitude'], $location['longitude'] ];
236 $this->context
['multimap'] = $this->image
->getMulti($coordinates);
237 #$this->translator->trans('Libre Air cities sector map'), $this->modified->getTimestamp(), $locations
240 $cities = array_map(function ($v) { return $v
['in']; }, $this->context
['cities']);
243 $dances = array_map(function ($v) { return $v
['name']; }, $this->context
['dances']);
253 //TODO: use splice instead of that shit !!!
254 //TODO: handle smartly indoor and outdoor !!!
255 $this->context
['keywords'] = array_values(
260 $this->translator
->trans('indoor'),
261 $this->translator
->trans('outdoor'),
262 $this->translator
->trans('calendar'),
263 $this->translator
->trans('Libre Air')
269 $cities = implode($this->translator
->trans(' and '), array_filter(array_merge([implode(', ', array_slice($cities, 0, -1))], array_slice($cities, -1)), 'strlen'));
272 $dances = implode($this->translator
->trans(' and '), array_filter(array_merge([implode(', ', array_slice($dances, 0, -1))], array_slice($dances, -1)), 'strlen'));
275 $this->context
['title']['page'] = $this->translator
->trans('%dances% %cities%', ['%dances%' => $dances, '%cities%' => $cities]);
278 //TODO: handle french translation when city start with a A, change à in en !
279 $this->context
['description'] = $this->translator
->trans('%dances% indoor and outdoor calendar %cities%', ['%dances%' => $dances, '%cities%' => $cities]);
282 //XXX: only valid for home page
283 $this->context
['facebook']['metas']['og:type'] = 'website';
286 return $this->render('@RapsysAir/default/index.html.twig', $this->context
, $response);
290 * The organizer regulation page
292 * Display the organizer regulation policy
294 * @param Request $request The request instance
295 * @return Response The rendered view
297 public function organizerRegulation(Request
$request): Response
{
299 $this->context
['title']['page'] = $this->translator
->trans('Organizer regulation');
302 $this->context
['description'] = $this->translator
->trans('Libre Air organizer regulation');
305 $this->context
['keywords'] = [
306 $this->translator
->trans('organizer regulation'),
307 $this->translator
->trans('Libre Air')
311 $response = $this->render('@RapsysAir/default/organizer_regulation.html.twig', $this->context
);
314 $response->setEtag(md5($response->getContent()));
315 $response->setPublic();
316 $response->isNotModified($request);
323 * The terms of service page
325 * Display the terms of service policy
327 * @param Request $request The request instance
328 * @return Response The rendered view
330 public function termsOfService(Request
$request): Response
{
332 $this->context
['title']['page'] = $this->translator
->trans('Terms of service');
335 $this->context
['description'] = $this->translator
->trans('Libre Air terms of service');
338 $this->context
['keywords'] = [
339 $this->translator
->trans('terms of service'),
340 $this->translator
->trans('Libre Air')
344 $response = $this->render('@RapsysAir/default/terms_of_service.html.twig', $this->context
);
347 $response->setEtag(md5($response->getContent()));
348 $response->setPublic();
349 $response->isNotModified($request);
356 * The frequently asked questions page
358 * Display the frequently asked questions
360 * @param Request $request The request instance
361 * @return Response The rendered view
363 public function frequentlyAskedQuestions(Request
$request): Response
{
365 $this->context
['title']['page'] = $this->translator
->trans('Frequently asked questions');
368 $this->context
['description'] = $this->translator
->trans('Libre Air frequently asked questions');
371 $this->context
['keywords'] = [
372 $this->translator
->trans('frequently asked questions'),
373 $this->translator
->trans('faq'),
374 $this->translator
->trans('Libre Air')
378 $response = $this->render('@RapsysAir/default/frequently_asked_questions.html.twig', $this->context
);
381 $response->setEtag(md5($response->getContent()));
382 $response->setPublic();
383 $response->isNotModified($request);
392 * Display all user with a group listed as users
394 * @param Request $request The request instance
396 * @return Response The rendered view
398 public function userIndex(Request
$request): Response
{
400 if ($this->checker
->isGranted('ROLE_ADMIN')) {
402 $this->context
['title']['page'] = $this->translator
->trans('Libre Air user list');
405 $this->context
['title']['section'] = $this->translator
->trans('User');
408 $this->context
['description'] = $this->translator
->trans('Lists Libre air users');
412 $this->context
['title']['page'] = $this->translator
->trans('Libre Air organizer list');
415 $this->context
['title']['section'] = $this->translator
->trans('Organizer');
418 $this->context
['description'] = $this->translator
->trans('Lists Libre air organizers');
422 $this->context
['keywords'] = [
423 $this->translator
->trans('users'),
424 $this->translator
->trans('user list'),
425 $this->translator
->trans('listing'),
426 $this->translator
->trans('Libre Air')
430 $users = $this->doctrine
->getRepository(User
::class)->findIndexByGroupId();
433 if ($this->checker
->isGranted('ROLE_ADMIN')) {
435 $this->context
['groups'] = $users;
438 //Only display senior organizers
439 $this->context
['users'] = $users[$this->translator
->trans('Senior')];
443 return $this->render('@RapsysAir/user/index.html.twig', $this->context
);
447 * List all sessions for the user
449 * Display all sessions for the user with an application or login form
451 * @param Request $request The request instance
452 * @param int $id The user id
454 * @return Response The rendered view
456 public function userView(Request
$request, int $id, ?string $user): Response
{
458 if (empty($this->context
['user'] = $this->doctrine
->getRepository(User
::class)->findOneByIdAsArray($id, $this->locale
))) {
460 throw new NotFoundHttpException($this->translator
->trans('Unable to find user: %id%', ['%id%' => $id]));
464 $token = new AnonymousToken($this->context
['user']['roles']);
466 //Prevent access when not admin, user is not guest and not currently logged user
467 if (!($isAdmin = $this->checker
->isGranted('ROLE_ADMIN')) && !($isGuest = $this->decision
->decide($token, ['ROLE_GUEST']))) {
468 //Throw access denied
469 throw new AccessDeniedException($this->translator
->trans('Unable to access user: %id%', ['%id%' => $id]));
472 //With invalid user slug
473 if ($this->context
['user']['slug'] !== $user) {
474 //Redirect to cleaned url
475 return $this->redirectToRoute('rapsysair_user_view', ['id' => $id, 'user' => $this->context
['user']['slug']]);
479 $this->context
['calendar'] = $this->doctrine
->getRepository(Session
::class)->findAllByPeriodAsCalendarArray($this->period
, !$this->checker
->isGranted('IS_AUTHENTICATED_REMEMBERED'), null, null, $id);
481 //Get locations at less than 2 km
482 $this->context
['locations'] = $this->doctrine
->getRepository(Location
::class)->findAllByUserIdAsArray($id, $this->period
, 2);
505 //Iterate on each calendar
506 foreach($this->context
['calendar'] as $date => $calendar) {
507 //Iterate on each session
508 foreach($calendar['sessions'] as $sessionId => $session) {
510 $dances[$session['application']['dance']['name']] = $session['application']['dance']['name'];
513 $types[$session['application']['dance']['type']] = lcfirst($session['application']['dance']['type']);
516 $indoors[$session['location']['indoor']?'indoor':'outdoor'] = $this->translator
->trans($session['location']['indoor']?'indoor':'outdoor');
519 $insides[$session['location']['indoor']?'inside':'outside'] = $this->translator
->trans($session['location']['indoor']?'inside':'outside');
522 $ats[$session['location']['id']] = $session['location']['at'];
525 $ins[$session['location']['id']] = $session['location']['in'];
527 //Session with application user id
528 if (!empty($session['application']['user']['id']) && $session['application']['user']['id'] == $id) {
530 $locations[$session['location']['id']] = $session['location'];
536 //XXX: dance modified is already computed inside calendar modified
537 $this->modified
= max(array_merge([$this->context
['user']['modified']], array_map(function ($v) { return $v
['modified']; }, array_merge($this->context
['calendar'], $this->context
['locations']))));
540 $response = new Response();
543 if ($this->checker
->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
545 $response->setLastModified(new \
DateTime('-1 year'));
548 $response->setPrivate();
549 //Without logged user
552 //XXX: only for public to force revalidation by last modified
553 $response->setEtag(md5(serialize(array_merge($this->context
['user'], $this->context
['calendar'], $this->context
['locations']))));
556 $response->setLastModified($this->modified
);
559 $response->setPublic();
561 //Without role and modification
562 if ($response->isNotModified($request)) {
563 //Return 304 response
569 $this->context
['multimap'] = $this->map
->getMultiMap($this->context
['user']['multimap'], $this->modified
->getTimestamp(), $this->context
['locations']);
572 $this->context
['keywords'] = [
573 $this->context
['user']['pseudonym'],
574 $this->translator
->trans('calendar'),
575 $this->translator
->trans('Libre Air')
579 $cities = array_unique(array_map(function ($v) { return $v
['city']; }, $locations));
582 $titles = array_map(function ($v) { return $v
['title']; }, $locations);
584 //Insert dances in keywords
585 array_splice($this->context
['keywords'], 1, 0, array_merge($types, $dances, $indoors, $insides, $titles, $cities));
588 $ins = array_unique($ins);
591 $dances = implode($this->translator
->trans(' and '), array_filter(array_merge([implode(', ', array_slice($dances, 0, -1))], array_slice($dances, -1)), 'strlen'));
594 $types = implode($this->translator
->trans(' and '), array_filter(array_merge([implode(', ', array_slice($types, 0, -1))], array_slice($types, -1)), 'strlen'));
596 //Get textual indoors
597 $indoors = implode($this->translator
->trans(' and '), array_filter(array_merge([implode(', ', array_slice($indoors, 0, -1))], array_slice($indoors, -1)), 'strlen'));
600 $ats = implode($this->translator
->trans(' and '), array_filter(array_merge([implode(', ', array_slice($ats, 0, -1))], array_slice($ats, -1)), 'strlen'));
603 $ins = implode($this->translator
->trans(' and '), array_filter(array_merge([implode(', ', array_slice($ins, 0, -1))], array_slice($ins, -1)), 'strlen'));
606 $this->context
['title']['page'] = $this->translator
->trans('%pseudonym% organizer', ['%pseudonym%' => $this->context
['user']['pseudonym']]);
609 $this->context
['title']['section'] = $this->translator
->trans('User');
612 if (!empty($locations)) {
614 $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']])]));
618 $this->context
['description'] = $this->translator
->trans('%pseudonym% calendar', ['%pseudonym%' => $this->context
['user']['pseudonym']]);
621 //Set user description
622 $this->context
['locations_description'] = $this->translator
->trans('Libre Air %pseudonym% location list', ['%pseudonym%' => $this->translator
->trans('by %pseudonym%', ['%pseudonym%' => $this->context
['user']['pseudonym']])]);
625 $this->context
['alternates'] +
= $this->context
['user']['alternates'];
627 //Create snippet forms for role_guest
628 //TODO: optimize this call
629 if ($isAdmin || $isGuest && $this->security
->getUser() && $this->context
['user']['id'] == $this->security
->getUser()->getId()) {
630 //Fetch all user snippet
631 $snippets = $this->doctrine
->getRepository(Snippet
::class)->findByUserIdLocaleIndexByLocationId($id, $this->locale
);
634 $user = $this->doctrine
->getRepository(User
::class)->findOneById($id);
636 //Iterate on locations
637 foreach($this->context
['locations'] as $locationId => $location) {
638 //With existing snippet
639 if (isset($snippets[$location['id']])) {
640 //Set existing in current
641 $current = $snippets[$location['id']];
642 //Without existing snippet
645 $current = new Snippet($this->locale
, $this->doctrine
->getRepository(Location
::class)->findOneById($location['id']), $user);
648 //Create SnippetType form
649 $form = $this->factory
->createNamed(
651 'snippet_'.$locationId.'_'.$id.'_'.$this->locale
,
653 'Rapsys\AirBundle\Form\SnippetType',
658 //Refill the fields in case of invalid form
659 $form->handleRequest($request);
661 //Handle submitted and valid form
662 //TODO: add a delete snippet ?
663 if ($form->isSubmitted() && $form->isValid()) {
665 $snippet = $form->getData();
668 $this->manager
->persist($snippet);
670 //Flush to get the ids
671 $this->manager
->flush();
674 $this->addFlash('notice', $this->translator
->trans('Snippet for %user% %location% updated', ['%location%' => $location['at'], '%user%' => $this->context
['user']['pseudonym']]));
676 //Redirect to cleaned url
677 return $this->redirectToRoute('rapsysair_user_view', ['id' => $id, 'user' => $this->context
['user']['slug']]);
680 //Add form to context
681 $this->context
['forms']['snippets'][$locationId] = $form->createView();
683 //With location user source image
684 if (($isFile = is_file($source = $this->config
['path'].'/location/'.$location['id'].'/'.$id.'.png')) && ($mtime = stat($source)['mtime'])) {
686 $this->context
['locations'][$locationId]['image'] = $this->image
->getThumb($location['miniature'], $mtime, $source);
689 //Create ImageType form
690 $form = $this->factory
->createNamed(
692 'image_'.$locationId.'_'.$id,
694 'Rapsys\AirBundle\Form\ImageType',
698 'location' => $location['id'],
702 //Set form attributes
704 //Enable delete with image
705 'delete' => isset($this->context
['locations'][$locationId]['image'])
709 //Refill the fields in case of invalid form
710 $form->handleRequest($request);
712 //Handle submitted and valid form
713 if ($form->isSubmitted() && $form->isValid()) {
715 if ($form->has('delete') && $form->get('delete')->isClicked()) {
716 //With source and mtime
717 if ($isFile && !empty($source) && !empty($mtime)) {
719 $this->image
->remove($mtime, $source);
722 unlink($this->config
['path'].'/location/'.$location['id'].'/'.$id.'.png');
725 $this->addFlash('notice', $this->translator
->trans('Image for %user% %location% deleted', ['%location%' => $location['at'], '%user%' => $this->context
['user']['pseudonym']]));
727 //Redirect to cleaned url
728 return $this->redirectToRoute('rapsysair_user_view', ['id' => $id, 'user' => $this->context
['user']['slug']]);
733 if ($image = $form->get('image')->getData()) {
735 if (!is_dir($dir = dirname($source))) {
736 //Create filesystem object
737 $filesystem = new Filesystem();
741 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
742 $filesystem->mkdir($dir, 0775);
743 } catch (IOExceptionInterface
$e) {
745 throw new \
Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
750 $source = realpath($dir).'/'.basename($source);
752 //Create imagick object
753 $imagick = new \
Imagick();
756 $imagick->readImage($image->getRealPath());
759 if (!$imagick->writeImage($source)) {
761 throw new \
Exception(sprintf('Unable to write image "%s"', $source));
765 $this->addFlash('notice', $this->translator
->trans('Image for %user% %location% updated', ['%location%' => $location['at'], '%user%' => $this->context
['user']['pseudonym']]));
767 //Redirect to cleaned url
768 return $this->redirectToRoute('rapsysair_user_view', ['id' => $id, 'user' => $this->context
['user']['slug']]);
772 //Add form to context
773 $this->context
['forms']['images'][$locationId] = $form->createView();
778 return $this->render('@RapsysAir/user/view.html.twig', ['id' => $id]+
$this->context
);