]> Raphaƫl G. Git Repositories - airbundle/blob - Controller/DefaultController.php
Add date field
[airbundle] / Controller / DefaultController.php
1 <?php
2
3 namespace Rapsys\AirBundle\Controller;
4
5 use Symfony\Bridge\Twig\Mime\TemplatedEmail;
6 use Symfony\Component\DependencyInjection\ContainerAwareTrait;
7 use Symfony\Component\DependencyInjection\ContainerInterface;
8 use Symfony\Component\Form\FormError;
9 use Symfony\Component\HttpFoundation\Request;
10 use Symfony\Component\HttpFoundation\RequestStack;
11 use Symfony\Component\HttpFoundation\Response;
12 use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
13 use Symfony\Component\Mailer\MailerInterface;
14 use Symfony\Component\Mime\Address;
15 use Symfony\Component\Routing\RouterInterface;
16 use Symfony\Component\Translation\TranslatorInterface;
17
18 use Rapsys\AirBundle\Entity\Location;
19 use Rapsys\AirBundle\Entity\Session;
20 use Rapsys\AirBundle\Pdf\DisputePdf;
21
22 class DefaultController extends AbstractController {
23 ///Config array
24 protected $config;
25
26 ///ContainerInterface instance
27 protected $container;
28
29 ///Context array
30 protected $context;
31
32 ///Router instance
33 protected $router;
34
35 ///Translator instance
36 protected $translator;
37
38 ///Request instance
39 protected $request;
40
41 ///Locale instance
42 protected $locale;
43
44 /**
45 * Inject container, router and translator interface
46 *
47 * @param ContainerInterface $container The container instance
48 * @param RouterInterface $router The router instance
49 * @param TranslatorInterface $translator The translator instance
50 */
51 public function __construct(ContainerInterface $container, RouterInterface $router, TranslatorInterface $translator) {
52 //Retrieve config
53 $this->config = $container->getParameter(self::getAlias());
54
55 //Set the container
56 $this->container = $container;
57
58 //Set the router
59 $this->router = $router;
60
61 //Set the translator
62 $this->translator = $translator;
63
64 //Set the context
65 $this->context = [
66 'contact' => [
67 'title' => $translator->trans($this->config['contact']['title']),
68 'mail' => $this->config['contact']['mail']
69 ],
70 'copy' => [
71 'by' => $translator->trans($this->config['copy']['by']),
72 'link' => $this->config['copy']['link'],
73 'long' => $translator->trans($this->config['copy']['long']),
74 'short' => $translator->trans($this->config['copy']['short']),
75 'title' => $this->config['copy']['title']
76 ],
77 'page' => [
78 'description' => null,
79 'section' => null,
80 'title' => null
81 ],
82 'site' => [
83 'donate' => $this->config['site']['donate'],
84 'ico' => $this->config['site']['ico'],
85 'logo' => $this->config['site']['logo'],
86 'png' => $this->config['site']['png'],
87 'svg' => $this->config['site']['svg'],
88 'title' => $translator->trans($this->config['site']['title']),
89 'url' => $router->generate($this->config['site']['url'])
90 ],
91 'canonical' => null,
92 'alternates' => [],
93 'facebook' => [
94 'heads' => [
95 'og' => 'http://ogp.me/ns#',
96 'fb' => 'http://ogp.me/ns/fb#'
97 ],
98 'metas' => [
99 'og:type' => 'article',
100 'og:site_name' => $this->translator->trans($this->config['site']['title']),
101 #'fb:admins' => $this->config['facebook']['admins'],
102 'fb:app_id' => $this->config['facebook']['apps']
103 ],
104 'texts' => []
105 ],
106 'forms' => []
107 ];
108 }
109
110 /**
111 * The about page
112 *
113 * @desc Display the about informations
114 *
115 * @param Request $request The request instance
116 * @return Response The rendered view
117 */
118 public function about(Request $request): Response {
119 //Set page
120 $this->context['page']['title'] = $this->translator->trans('About');
121
122 //Set description
123 $this->context['page']['description'] = $this->translator->trans('Libre Air about');
124
125 //Set keywords
126 $this->context['keywords'] = [
127 $this->translator->trans('about'),
128 $this->translator->trans('Libre Air')
129 ];
130
131 //Render template
132 $response = $this->render('@RapsysAir/default/about.html.twig', $this->context);
133 $response->setEtag(md5($response->getContent()));
134 $response->setPublic();
135 $response->isNotModified($request);
136
137 //Return response
138 return $response;
139 }
140
141 /**
142 * The contact page
143 *
144 * @desc Send a contact mail to configured contact
145 *
146 * @param Request $request The request instance
147 * @param MailerInterface $mailer The mailer instance
148 *
149 * @return Response The rendered view or redirection
150 */
151 public function contact(Request $request, MailerInterface $mailer): Response {
152 //Set page
153 $this->context['page']['title'] = $this->translator->trans('Contact');
154
155 //Set description
156 $this->context['page']['description'] = $this->translator->trans('Contact Libre Air');
157
158 //Set keywords
159 $this->context['keywords'] = [
160 $this->translator->trans('contact'),
161 $this->translator->trans('Libre Air'),
162 $this->translator->trans('outdoor'),
163 $this->translator->trans('Argentine Tango'),
164 $this->translator->trans('calendar')
165 ];
166
167 //Create the form according to the FormType created previously.
168 //And give the proper parameters
169 $form = $this->createForm('Rapsys\AirBundle\Form\ContactType', null, [
170 'action' => $this->generateUrl('rapsys_air_contact'),
171 'method' => 'POST'
172 ]);
173
174 if ($request->isMethod('POST')) {
175 // Refill the fields in case the form is not valid.
176 $form->handleRequest($request);
177
178 if ($form->isValid()) {
179 //Get data
180 $data = $form->getData();
181
182 //Create message
183 $message = (new TemplatedEmail())
184 //Set sender
185 ->from(new Address($data['mail'], $data['name']))
186 //Set recipient
187 ->to(new Address($this->context['contact']['mail'], $this->context['contact']['title']))
188 //Set subject
189 ->subject($data['subject'])
190
191 //Set path to twig templates
192 ->htmlTemplate('@RapsysAir/mail/contact.html.twig')
193 ->textTemplate('@RapsysAir/mail/contact.text.twig')
194
195 //Set context
196 ->context(
197 [
198 'subject' => $data['subject'],
199 'message' => strip_tags($data['message']),
200 ]+$this->context
201 );
202
203 //Try sending message
204 //XXX: mail delivery may silently fail
205 try {
206 //Send message
207 $mailer->send($message);
208
209 //Redirect on the same route with sent=1 to cleanup form
210 return $this->redirectToRoute($request->get('_route'), ['sent' => 1]+$request->get('_route_params'));
211 //Catch obvious transport exception
212 } catch(TransportExceptionInterface $e) {
213 if ($message = $e->getMessage()) {
214 //Add error message mail unreachable
215 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to contact: %mail%: %message%', ['%mail%' => $this->context['contact']['mail'], '%message%' => $this->translator->trans($message)])));
216 } else {
217 //Add error message mail unreachable
218 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to contact: %mail%', ['%mail%' => $this->context['contact']['mail']])));
219 }
220 }
221 }
222 }
223
224 //Render template
225 return $this->render('@RapsysAir/form/contact.html.twig', ['form' => $form->createView(), 'sent' => $request->query->get('sent', 0)]+$this->context);
226 }
227
228 /**
229 * The dispute page
230 *
231 * @desc Generate a dispute document
232 *
233 * @param Request $request The request instance
234 * @param MailerInterface $mailer The mailer instance
235 *
236 * @return Response The rendered view or redirection
237 */
238 public function dispute(Request $request, MailerInterface $mailer): Response {
239 //Prevent non-guest to access here
240 $this->denyAccessUnlessGranted('ROLE_USER', null, $this->translator->trans('Unable to access this page without role %role%!', ['%role%' => $this->translator->trans('User')]));
241
242 //Set page
243 $this->context['page']['title'] = $this->translator->trans('Dispute');
244
245 //Set description
246 $this->context['page']['description'] = $this->translator->trans('Libre Air dispute');
247
248 //Set keywords
249 $this->context['keywords'] = [
250 $this->translator->trans('dispute'),
251 $this->translator->trans('Libre Air'),
252 $this->translator->trans('outdoor'),
253 $this->translator->trans('Argentine Tango'),
254 $this->translator->trans('calendar')
255 ];
256
257 //Create the form according to the FormType created previously.
258 //And give the proper parameters
259 $form = $this->createForm('Rapsys\AirBundle\Form\DisputeType', ['court' => 'Paris', 'abstract' => 'Pour constater cette prĆ©tendue infraction, les agents verbalisateurs ont pĆ©nĆ©trĆ© dans un jardin privatif, sans visibilitĆ© depuis la voie publique, situĆ© derriĆØre un batiment privĆ©, pour ce faire ils ont franchi au moins un grillage de chantier ou des potteaux mĆ©talliques sĆ©parant le terrain privĆ© de la voie publique de l\'autre cĆ“tĆ© du batiment.'], [
260 'action' => $this->generateUrl('rapsys_air_dispute'),
261 'method' => 'POST'
262 ]);
263
264 if ($request->isMethod('POST')) {
265 // Refill the fields in case the form is not valid.
266 $form->handleRequest($request);
267
268 if ($form->isValid()) {
269 //Get data
270 $data = $form->getData();
271
272 //Gathering offense
273 if (!empty($data['offense']) && $data['offense'] == 'gathering') {
274 //Add gathering
275 $output = DisputePdf::genGathering($data['court'], $data['notice'], $data['agent'], $data['service'], $data['abstract'], $this->translator->trans($this->getUser()->getCivility()->getTitle()), $this->getUser()->getForename(), $this->getUser()->getSurname());
276 //Traffic offense
277 } elseif (!empty($data['offense'] && $data['offense'] == 'traffic')) {
278 //Add traffic
279 $output = DisputePdf::genTraffic($data['court'], $data['notice'], $data['agent'], $data['service'], $data['abstract'], $this->translator->trans($this->getUser()->getCivility()->getTitle()), $this->getUser()->getForename(), $this->getUser()->getSurname());
280 //Unsupported offense
281 } else {
282 header('Content-Type: text/plain');
283 die('TODO');
284 exit;
285 }
286
287 //Send common headers
288 header('Content-Type: application/pdf');
289
290 //Send remaining headers
291 header('Cache-Control: private, max-age=0, must-revalidate');
292 header('Pragma: public');
293
294 //Send content-length
295 header('Content-Length: '.strlen($output));
296
297 //Display the pdf
298 echo $output;
299
300 //Die for now
301 exit;
302
303 # //Create message
304 # $message = (new TemplatedEmail())
305 # //Set sender
306 # ->from(new Address($data['mail'], $data['name']))
307 # //Set recipient
308 # //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
309 # ->to(new Address($this->config['contact']['mail'], $this->config['contact']['title']))
310 # //Set subject
311 # ->subject($data['subject'])
312 #
313 # //Set path to twig templates
314 # ->htmlTemplate('@RapsysAir/mail/contact.html.twig')
315 # ->textTemplate('@RapsysAir/mail/contact.text.twig')
316 #
317 # //Set context
318 # ->context(
319 # [
320 # 'subject' => $data['subject'],
321 # 'message' => strip_tags($data['message']),
322 # ]+$this->context
323 # );
324 #
325 # //Try sending message
326 # //XXX: mail delivery may silently fail
327 # try {
328 # //Send message
329 # $mailer->send($message);
330 #
331 # //Redirect on the same route with sent=1 to cleanup form
332 # return $this->redirectToRoute($request->get('_route'), ['sent' => 1]+$request->get('_route_params'));
333 # //Catch obvious transport exception
334 # } catch(TransportExceptionInterface $e) {
335 # if ($message = $e->getMessage()) {
336 # //Add error message mail unreachable
337 # $form->get('mail')->addError(new FormError($this->translator->trans('Unable to contact: %mail%: %message%', ['%mail%' => $this->config['contact']['mail'], '%message%' => $this->translator->trans($message)])));
338 # } else {
339 # //Add error message mail unreachable
340 # $form->get('mail')->addError(new FormError($this->translator->trans('Unable to contact: %mail%', ['%mail%' => $this->config['contact']['mail']])));
341 # }
342 # }
343 }
344 }
345
346 //Render template
347 return $this->render('@RapsysAir/default/dispute.html.twig', ['form' => $form->createView(), 'sent' => $request->query->get('sent', 0)]+$this->context);
348 }
349
350 /**
351 * The index page
352 *
353 * @desc Display all granted sessions with an application or login form
354 *
355 * @param Request $request The request instance
356 * @return Response The rendered view
357 */
358 public function index(Request $request): Response {
359 //Fetch doctrine
360 $doctrine = $this->getDoctrine();
361
362 //Set page
363 $this->context['page']['title'] = $this->translator->trans('Argentine Tango in Paris');
364
365 //Set description
366 $this->context['page']['description'] = $this->translator->trans('Outdoor Argentine Tango session calendar in Paris');
367
368 //Set keywords
369 $this->context['keywords'] = [
370 $this->translator->trans('Argentine Tango'),
371 $this->translator->trans('Paris'),
372 $this->translator->trans('outdoor'),
373 $this->translator->trans('calendar'),
374 $this->translator->trans('Libre Air')
375 ];
376
377 //Set facebook type
378 //XXX: only valid for home page
379 $this->context['facebook']['metas']['og:type'] = 'website';
380
381 //Compute period
382 $period = new \DatePeriod(
383 //Start from first monday of week
384 new \DateTime('Monday this week'),
385 //Iterate on each day
386 new \DateInterval('P1D'),
387 //End with next sunday and 4 weeks
388 new \DateTime(
389 $this->isGranted('IS_AUTHENTICATED_REMEMBERED')?'Monday this week + 3 week':'Monday this week + 2 week'
390 )
391 );
392
393 //Fetch calendar
394 $calendar = $doctrine->getRepository(Session::class)->fetchCalendarByDatePeriod($this->translator, $period, null, $request->get('session'), !$this->isGranted('IS_AUTHENTICATED_REMEMBERED'));
395
396 //Fetch locations
397 //XXX: we want to display all active locations anyway
398 $locations = $doctrine->getRepository(Location::class)->findTranslatedSortedByPeriod($this->translator, $period);
399
400 //Render the view
401 return $this->render('@RapsysAir/default/index.html.twig', ['calendar' => $calendar, 'locations' => $locations]+$this->context);
402
403 //Set Cache-Control must-revalidate directive
404 //TODO: add a javascript forced refresh after 1h ? or header refresh ?
405 #$response->setPublic(true);
406 #$response->setMaxAge(300);
407 #$response->mustRevalidate();
408 ##$response->setCache(['public' => true, 'max_age' => 300]);
409
410 //Return the response
411 #return $response;
412 }
413
414 /**
415 * The organizer regulation page
416 *
417 * @desc Display the organizer regulation policy
418 *
419 * @param Request $request The request instance
420 * @return Response The rendered view
421 */
422 public function organizerRegulation(Request $request): Response {
423 //Set page
424 $this->context['page']['title'] = $this->translator->trans('Organizer regulation');
425
426 //Set description
427 $this->context['page']['description'] = $this->translator->trans('Libre Air organizer regulation');
428
429 //Set keywords
430 $this->context['keywords'] = [
431 $this->translator->trans('organizer regulation'),
432 $this->translator->trans('Libre Air')
433 ];
434
435 //Render template
436 $response = $this->render('@RapsysAir/default/organizer_regulation.html.twig', $this->context);
437
438 //Set as cachable
439 $response->setEtag(md5($response->getContent()));
440 $response->setPublic();
441 $response->isNotModified($request);
442
443 //Return response
444 return $response;
445 }
446
447 /**
448 * The terms of service page
449 *
450 * @desc Display the terms of service policy
451 *
452 * @param Request $request The request instance
453 * @return Response The rendered view
454 */
455 public function termsOfService(Request $request): Response {
456 //Set page
457 $this->context['page']['title'] = $this->translator->trans('Terms of service');
458
459 //Set description
460 $this->context['page']['description'] = $this->translator->trans('Libre Air terms of service');
461
462 //Set keywords
463 $this->context['keywords'] = [
464 $this->translator->trans('terms of service'),
465 $this->translator->trans('Libre Air')
466 ];
467
468 //Render template
469 $response = $this->render('@RapsysAir/default/terms_of_service.html.twig', $this->context);
470
471 //Set as cachable
472 $response->setEtag(md5($response->getContent()));
473 $response->setPublic();
474 $response->isNotModified($request);
475
476 //Return response
477 return $response;
478 }
479
480 /**
481 * The frequently asked questions page
482 *
483 * @desc Display the frequently asked questions
484 *
485 * @param Request $request The request instance
486 * @return Response The rendered view
487 */
488 public function frequentlyAskedQuestions(Request $request): Response {
489 //Set page
490 $this->context['page']['title'] = $this->translator->trans('Frequently asked questions');
491
492 //Set description
493 $this->context['page']['description'] = $this->translator->trans('Libre Air frequently asked questions');
494
495 //Set keywords
496 $this->context['keywords'] = [
497 $this->translator->trans('frequently asked questions'),
498 $this->translator->trans('faq'),
499 $this->translator->trans('Libre Air')
500 ];
501
502 //Render template
503 $response = $this->render('@RapsysAir/default/frequently_asked_questions.html.twig', $this->context);
504
505 //Set as cachable
506 $response->setEtag(md5($response->getContent()));
507 $response->setPublic();
508 $response->isNotModified($request);
509
510 //Return response
511 return $response;
512 }
513
514 /**
515 * Return the bundle alias
516 *
517 * {@inheritdoc}
518 */
519 public function getAlias(): string {
520 return 'rapsys_air';
521 }
522
523 /**
524 * Renders a view
525 *
526 * {@inheritdoc}
527 */
528 /*protected function render(string $view, array $parameters = [], Response $response = null): Response {
529 //Call parent render
530 return parent::render($view, $parameters, $response);
531 }*/
532 }