]> Raphaƫl G. Git Repositories - airbundle/blob - Controller/DefaultController.php
Add preUpdate life cycle callback
[airbundle] / Controller / DefaultController.php
1 <?php
2
3 namespace Rapsys\AirBundle\Controller;
4
5 use Rapsys\AirBundle\Entity\Application;
6 use Rapsys\AirBundle\Entity\Location;
7 use Rapsys\AirBundle\Entity\Session;
8 use Rapsys\AirBundle\Entity\Slot;
9 use Rapsys\AirBundle\Entity\User;
10 use Symfony\Bridge\Twig\Mime\TemplatedEmail;
11 use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
12 use Symfony\Component\DependencyInjection\ContainerInterface;
13 use Symfony\Component\Form\FormError;
14 use Symfony\Component\HttpFoundation\Request;
15 use Symfony\Component\HttpFoundation\RequestStack;
16 use Symfony\Component\HttpFoundation\Response;
17 use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
18 use Symfony\Component\Mailer\MailerInterface;
19 use Symfony\Component\Mime\Address;
20 use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
21 use Symfony\Component\Routing\RouterInterface;
22 use Symfony\Component\Translation\TranslatorInterface;
23 use Rapsys\UserBundle\Utils\Slugger;
24 use Symfony\Bundle\FrameworkBundle\Controller\ControllerTrait;
25 use Symfony\Component\DependencyInjection\ContainerAwareTrait;
26
27
28 class DefaultController {
29 use ControllerTrait {
30 //Rename render as _render
31 render as protected _render;
32 }
33
34 ///Config array
35 protected $config;
36
37 ///Context array
38 protected $context;
39
40 ///Router instance
41 protected $router;
42
43 ///Translator instance
44 protected $translator;
45
46 /**
47 * @var ContainerInterface
48 */
49 protected $container;
50
51 /**
52 * Inject container and translator interface
53 *
54 * @param ContainerInterface $container The container instance
55 * @param RouterInterface $router The router instance
56 * @param TranslatorInterface $translator The translator instance
57 */
58 public function __construct(ContainerInterface $container, RouterInterface $router, RequestStack $requestStack, TranslatorInterface $translator) {
59 //Retrieve config
60 $this->config = $container->getParameter($this->getAlias());
61
62 //Set the container
63 $this->container = $container;
64
65 //Set the router
66 $this->router = $router;
67
68 //Set the translator
69 $this->translator = $translator;
70
71 //Set the context
72 $this->context = [
73 'copy' => [
74 'by' => $translator->trans($this->config['copy']['by']),
75 'link' => $this->config['copy']['link'],
76 'long' => $translator->trans($this->config['copy']['long']),
77 'short' => $translator->trans($this->config['copy']['short']),
78 'title' => $this->config['copy']['title']
79 ],
80 'site' => [
81 'ico' => $this->config['site']['ico'],
82 'logo' => $this->config['site']['logo'],
83 'png' => $this->config['site']['png'],
84 'svg' => $this->config['site']['svg'],
85 'title' => $translator->trans($this->config['site']['title']),
86 'url' => $router->generate($this->config['site']['url']),
87 ],
88 'canonical' => null,
89 'alternates' => [],
90 'forms' => []
91 ];
92
93 //Get current locale
94 #$currentLocale = $router->getContext()->getParameters()['_locale'];
95 $currentLocale = $requestStack->getCurrentRequest()->getLocale();
96
97 //Set translator locale
98 //XXX: allow LocaleSubscriber on the fly locale change for first page
99 $this->translator->setLocale($currentLocale);
100
101 //Iterate on locales excluding current one
102 foreach($this->config['locales'] as $locale) {
103 //Set titles
104 $titles = [];
105
106 //Iterate on other locales
107 foreach(array_diff($this->config['locales'], [$locale]) as $other) {
108 $titles[$other] = $translator->trans($this->config['languages'][$locale], [], null, $other);
109 }
110
111 //Get context path
112 $path = $router->getContext()->getPathInfo();
113
114 //Retrieve route matching path
115 $route = $router->match($path);
116
117 //Get route name
118 $name = $route['_route'];
119
120 //Unset route name
121 unset($route['_route']);
122
123 //With current locale
124 if ($locale == $currentLocale) {
125 //Set locale locales context
126 $this->context['canonical'] = $router->generate($name, ['_locale' => $locale]+$route, UrlGeneratorInterface::ABSOLUTE_URL);
127 } else {
128 //Set locale locales context
129 $this->context['alternates'][] = [
130 'lang' => $locale,
131 'absolute' => $router->generate($name, ['_locale' => $locale]+$route, UrlGeneratorInterface::ABSOLUTE_URL),
132 'relative' => $router->generate($name, ['_locale' => $locale]+$route),
133 'title' => implode('/', $titles),
134 'translated' => $translator->trans($this->config['languages'][$locale], [], null, $locale)
135 ];
136 }
137 }
138 }
139
140 /**
141 * The contact page
142 *
143 * @desc Send a contact mail to configured contact
144 *
145 * @param Request $request The request instance
146 * @param MailerInterface $mailer The mailer instance
147 *
148 * @return Response The rendered view or redirection
149 */
150 public function contact(Request $request, MailerInterface $mailer): Response {
151 //Set section
152 $section = $this->translator->trans('Contact');
153
154 //Set description
155 $this->context['description'] = $this->translator->trans('Contact Libre Air');
156
157 //Set keywords
158 $this->context['keywords'] = [
159 $this->translator->trans('contact'),
160 $this->translator->trans('Libre Air'),
161 $this->translator->trans('outdoor'),
162 $this->translator->trans('Argentine Tango'),
163 $this->translator->trans('calendar')
164 ];
165
166 //Set title
167 $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
168
169 //Create the form according to the FormType created previously.
170 //And give the proper parameters
171 $form = $this->createForm('Rapsys\AirBundle\Form\ContactType', null, [
172 'action' => $this->generateUrl('rapsys_air_contact'),
173 'method' => 'POST'
174 ]);
175
176 if ($request->isMethod('POST')) {
177 // Refill the fields in case the form is not valid.
178 $form->handleRequest($request);
179
180 if ($form->isValid()) {
181 //Get data
182 $data = $form->getData();
183
184 //Create message
185 $message = (new TemplatedEmail())
186 //Set sender
187 ->from(new Address($data['mail'], $data['name']))
188 //Set recipient
189 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
190 ->to(new Address($this->config['contact']['mail'], $this->config['contact']['name']))
191 //Set subject
192 ->subject($data['subject'])
193
194 //Set path to twig templates
195 ->htmlTemplate('@RapsysAir/mail/contact.html.twig')
196 ->textTemplate('@RapsysAir/mail/contact.text.twig')
197
198 //Set context
199 ->context(
200 [
201 'subject' => $data['subject'],
202 'message' => strip_tags($data['message']),
203 ]+$this->context
204 );
205
206 //Try sending message
207 //XXX: mail delivery may silently fail
208 try {
209 //Send message
210 $mailer->send($message);
211
212 //Redirect on the same route with sent=1 to cleanup form
213 return $this->redirectToRoute($request->get('_route'), ['sent' => 1]+$request->get('_route_params'));
214 //Catch obvious transport exception
215 } catch(TransportExceptionInterface $e) {
216 if ($message = $e->getMessage()) {
217 //Add error message mail unreachable
218 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to contact: %mail%: %message%', ['%mail%' => $this->config['contact']['mail'], '%message%' => $this->translator->trans($message)])));
219 } else {
220 //Add error message mail unreachable
221 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to contact: %mail%', ['%mail%' => $this->config['contact']['mail']])));
222 }
223 }
224 }
225 }
226
227 //Render template
228 return $this->render('@RapsysAir/form/contact.html.twig', ['title' => $title, 'section' => $section, 'form' => $form->createView(), 'sent' => $request->query->get('sent', 0)]+$this->context);
229 }
230
231
232 /**
233 * The dispute page
234 *
235 * @desc Generate a dispute document
236 *
237 * @param Request $request The request instance
238 * @param MailerInterface $mailer The mailer instance
239 *
240 * @return Response The rendered view or redirection
241 */
242 public function dispute(Request $request, MailerInterface $mailer): Response {
243 //Prevent non-guest to access here
244 $this->denyAccessUnlessGranted('ROLE_USER', null, $this->translator->trans('Unable to access this page without role %role%!', ['%role%' => $this->translator->trans('User')]));
245 //Set section
246 $section = $this->translator->trans('Dispute');
247
248 //Set description
249 $this->context['description'] = $this->translator->trans('Libre Air dispute');
250
251 //Set keywords
252 $this->context['keywords'] = [
253 $this->translator->trans('dispute'),
254 $this->translator->trans('Libre Air'),
255 $this->translator->trans('outdoor'),
256 $this->translator->trans('Argentine Tango'),
257 $this->translator->trans('calendar')
258 ];
259
260 //Set title
261 $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
262
263 //Create the form according to the FormType created previously.
264 //And give the proper parameters
265 $form = $this->createForm('Rapsys\AirBundle\Form\DisputeType', null, [
266 'action' => $this->generateUrl('rapsys_air_dispute'),
267 'method' => 'POST'
268 ]);
269
270 if ($request->isMethod('POST')) {
271 // Refill the fields in case the form is not valid.
272 $form->handleRequest($request);
273
274 if ($form->isValid()) {
275 //Get data
276 $data = $form->getData();
277
278 header('Content-Type: text/plain');
279
280 //Infraction
281 var_dump($data['offense']);
282
283 //NumƩro d'avis
284 var_dump($data['notice']);
285
286 //NumƩro d'agent
287 var_dump($data['agent']);
288
289 //Code service
290 var_dump($data['service']);
291
292 //Masque portƩ
293 var_dump($data['mask']);
294
295 //CivilitƩ
296 var_dump($this->translator->trans($this->getUser()->getCivility()->getTitle()));
297
298 //PrƩnom
299 var_dump($this->getUser()->getForename());
300
301 //Nom
302 var_dump($this->getUser()->getSurname());
303
304 //Mail
305 var_dump($this->getUser()->getMail());
306
307 exit;
308
309 # //Create message
310 # $message = (new TemplatedEmail())
311 # //Set sender
312 # ->from(new Address($data['mail'], $data['name']))
313 # //Set recipient
314 # //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
315 # ->to(new Address($this->config['contact']['mail'], $this->config['contact']['name']))
316 # //Set subject
317 # ->subject($data['subject'])
318 #
319 # //Set path to twig templates
320 # ->htmlTemplate('@RapsysAir/mail/contact.html.twig')
321 # ->textTemplate('@RapsysAir/mail/contact.text.twig')
322 #
323 # //Set context
324 # ->context(
325 # [
326 # 'subject' => $data['subject'],
327 # 'message' => strip_tags($data['message']),
328 # ]+$this->context
329 # );
330 #
331 # //Try sending message
332 # //XXX: mail delivery may silently fail
333 # try {
334 # //Send message
335 # $mailer->send($message);
336 #
337 # //Redirect on the same route with sent=1 to cleanup form
338 # return $this->redirectToRoute($request->get('_route'), ['sent' => 1]+$request->get('_route_params'));
339 # //Catch obvious transport exception
340 # } catch(TransportExceptionInterface $e) {
341 # if ($message = $e->getMessage()) {
342 # //Add error message mail unreachable
343 # $form->get('mail')->addError(new FormError($this->translator->trans('Unable to contact: %mail%: %message%', ['%mail%' => $this->config['contact']['mail'], '%message%' => $this->translator->trans($message)])));
344 # } else {
345 # //Add error message mail unreachable
346 # $form->get('mail')->addError(new FormError($this->translator->trans('Unable to contact: %mail%', ['%mail%' => $this->config['contact']['mail']])));
347 # }
348 # }
349 }
350 }
351
352 //Render template
353 return $this->render('@RapsysAir/form/dispute.html.twig', ['title' => $title, 'section' => $section, 'form' => $form->createView(), 'sent' => $request->query->get('sent', 0)]+$this->context);
354 }
355
356 /**
357 * The index page
358 *
359 * @desc Display all granted sessions with an application or login form
360 *
361 * @param Request $request The request instance
362 *
363 * @return Response The rendered view
364 */
365 public function index(Request $request): Response {
366 //Fetch doctrine
367 $doctrine = $this->getDoctrine();
368
369 //Set section
370 $section = $this->translator->trans('Argentine Tango in Paris');
371
372 //Set description
373 $this->context['description'] = $this->translator->trans('Outdoor Argentine Tango session calendar in Paris');
374
375 //Set keywords
376 $this->context['keywords'] = [
377 $this->translator->trans('Argentine Tango'),
378 $this->translator->trans('Paris'),
379 $this->translator->trans('outdoor'),
380 $this->translator->trans('calendar'),
381 $this->translator->trans('Libre Air')
382 ];
383
384 //Set title
385 $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
386
387 //Compute period
388 $period = new \DatePeriod(
389 //Start from first monday of week
390 new \DateTime('Monday this week'),
391 //Iterate on each day
392 new \DateInterval('P1D'),
393 //End with next sunday and 4 weeks
394 new \DateTime(
395 $this->isGranted('IS_AUTHENTICATED_REMEMBERED')?'Monday this week + 3 week':'Monday this week + 2 week'
396 )
397 );
398
399 //Fetch calendar
400 $calendar = $doctrine->getRepository(Session::class)->fetchCalendarByDatePeriod($this->translator, $period, null, $request->get('session'), !$this->isGranted('IS_AUTHENTICATED_REMEMBERED'));
401
402 //Fetch locations
403 //XXX: we want to display all active locations anyway
404 $locations = $doctrine->getRepository(Location::class)->findTranslatedSortedByPeriod($this->translator, $period);
405
406 //Render the view
407 return $this->render('@RapsysAir/default/index.html.twig', ['title' => $title, 'section' => $section, 'calendar' => $calendar, 'locations' => $locations]+$this->context);
408
409 //Set Cache-Control must-revalidate directive
410 //TODO: add a javascript forced refresh after 1h ? or header refresh ?
411 #$response->setPublic(true);
412 #$response->setMaxAge(300);
413 #$response->mustRevalidate();
414 ##$response->setCache(['public' => true, 'max_age' => 300]);
415
416 //Return the response
417 #return $response;
418 }
419
420 /**
421 * The organizer regulation page
422 *
423 * @desc Display the organizer regulation policy
424 *
425 * @return Response The rendered view
426 */
427 public function organizerRegulation(): Response {
428 //Set section
429 $section = $this->translator->trans('Organizer regulation');
430
431 //Set description
432 $this->context['description'] = $this->translator->trans('Libre Air organizer regulation');
433
434 //Set keywords
435 $this->context['keywords'] = [
436 $this->translator->trans('organizer regulation'),
437 $this->translator->trans('Libre Air')
438 ];
439
440 //Set title
441 $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
442
443 //Render template
444 return $this->render('@RapsysAir/default/organizer_regulation.html.twig', ['title' => $title, 'section' => $section]+$this->context);
445 }
446
447 /**
448 * The terms of service page
449 *
450 * @desc Display the terms of service policy
451 *
452 * @return Response The rendered view
453 */
454 public function termsOfService(): Response {
455 //Set section
456 $section = $this->translator->trans('Terms of service');
457
458 //Set description
459 $this->context['description'] = $this->translator->trans('Libre Air terms of service');
460
461 //Set keywords
462 $this->context['keywords'] = [
463 $this->translator->trans('terms of service'),
464 $this->translator->trans('Libre Air')
465 ];
466
467 //Set title
468 $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
469
470 //Render template
471 return $this->render('@RapsysAir/default/terms_of_service.html.twig', ['title' => $title, 'section' => $section]+$this->context);
472 }
473
474 /**
475 * The frequently asked questions page
476 *
477 * @desc Display the frequently asked questions
478 *
479 * @return Response The rendered view
480 */
481 public function frequentlyAskedQuestions(): Response {
482 //Set section
483 $section = $this->translator->trans('Frequently asked questions');
484
485 //Set description
486 $this->context['description'] = $this->translator->trans('Libre Air frequently asked questions');
487
488 //Set keywords
489 $this->context['keywords'] = [
490 $this->translator->trans('frequently asked questions'),
491 $this->translator->trans('faq'),
492 $this->translator->trans('Libre Air')
493 ];
494
495 //Set title
496 $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
497
498 //Render template
499 return $this->render('@RapsysAir/default/frequently_asked_questions.html.twig', ['title' => $title, 'section' => $section]+$this->context);
500 }
501
502 /**
503 * Return the bundle alias
504 *
505 * {@inheritdoc}
506 */
507 public function getAlias(): string {
508 return 'rapsys_air';
509 }
510
511 /**
512 * Renders a view
513 *
514 * {@inheritdoc}
515 */
516 protected function render(string $view, array $parameters = [], Response $response = null): Response {
517 //Create application form for role_guest
518 if ($this->isGranted('ROLE_GUEST')) {
519 //Without application form
520 if (empty($parameters['forms']['application'])) {
521 //Fetch doctrine
522 $doctrine = $this->getDoctrine();
523
524 //Create ApplicationType form
525 $application = $this->createForm('Rapsys\AirBundle\Form\ApplicationType', null, [
526 //Set the action
527 'action' => $this->generateUrl('rapsys_air_application_add'),
528 //Set the form attribute
529 'attr' => [ 'class' => 'col' ],
530 //Set admin
531 'admin' => $this->isGranted('ROLE_ADMIN'),
532 //Set default user to current
533 'user' => $this->getUser()->getId(),
534 //Set default slot to evening
535 //XXX: default to Evening (3)
536 'slot' => $doctrine->getRepository(Slot::class)->findOneById(3)
537 ]);
538
539 //Add form to context
540 $parameters['forms']['application'] = $application->createView();
541 }
542 //Create login form for anonymous
543 } elseif (!$this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
544 //Create ApplicationType form
545 $login = $this->createForm('Rapsys\UserBundle\Form\LoginType', null, [
546 //Set the action
547 'action' => $this->generateUrl('rapsys_user_login'),
548 //Set the form attribute
549 'attr' => [ 'class' => 'col' ]
550 ]);
551
552 //Add form to context
553 $parameters['forms']['login'] = $login->createView();
554 }
555
556 //Call parent method
557 return $this->_render($view, $parameters, $response);
558 }
559 }