Remove application form
[airbundle] / Controller / SessionController.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys AirBundle package.
5 *
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Rapsys\AirBundle\Controller;
13
14 use Symfony\Component\Asset\Packages;
15 use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
16 use Symfony\Component\Filesystem\Filesystem;
17 use Symfony\Component\HttpFoundation\BinaryFileResponse;
18 use Symfony\Component\HttpFoundation\Request;
19 use Symfony\Component\HttpFoundation\Response;
20 use Symfony\Component\Routing\Exception\MethodNotAllowedException;
21 use Symfony\Component\Routing\Exception\ResourceNotFoundException;
22 use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
23 use Symfony\Component\Routing\RequestContext;
24
25 use Rapsys\AirBundle\Entity\Application;
26 use Rapsys\AirBundle\Entity\User;
27 use Rapsys\AirBundle\Entity\Slot;
28 use Rapsys\AirBundle\Entity\Session;
29 use Rapsys\AirBundle\Entity\Location;
30
31 class SessionController extends AbstractController {
32 /**
33 * Edit session
34 *
35 * @desc Persist session and all required dependencies in database
36 *
37 * @param Request $request The request instance
38 *
39 * @return Response The rendered view or redirection
40 *
41 * @throws \RuntimeException When user has not at least guest role
42 */
43 public function edit(Request $request, $id): Response {
44 //Prevent non-guest to access here
45 $this->denyAccessUnlessGranted('ROLE_GUEST', null, $this->translator->trans('Unable to access this page without role %role%!', ['%role%' => $this->translator->trans('Guest')]));
46
47 //Reject non post requests
48 if (!$request->isMethod('POST')) {
49 throw new \RuntimeException('Request method MUST be POST');
50 }
51
52 //Get doctrine
53 $doctrine = $this->getDoctrine();
54
55 //Set locale
56 $locale = $request->getLocale();
57
58 //Fetch session
59 $session = $doctrine->getRepository(Session::class)->fetchOneById($id, $locale);
60
61 //Check if
62 if (
63 //we are admin
64 !$this->isGranted('ROLE_ADMIN') &&
65 //or attributed user
66 $this->getUser()->getId() != $session['au_id'] &&
67 //or application without attributed user
68 $session['au_id'] !== null && !in_array($this->getUser()->getId(), explode("\n", $session['sau_id']))
69 ) {
70 //Prevent non admin and non attributed user access
71 throw $this->createAccessDeniedException();
72 }
73
74 //Set now
75 $now = new \DateTime('now');
76
77 //Create SessionType form
78 $form = $this->createForm('Rapsys\AirBundle\Form\SessionType', null, [
79 //Set the action
80 'action' => $this->generateUrl('rapsys_air_session_edit', [ 'id' => $id ]),
81 //Set the form attribute
82 'attr' => [],
83 //Set admin
84 'admin' => $this->isGranted('ROLE_ADMIN'),
85 //Set default user to current
86 'user' => $this->getUser()->getId(),
87 //Set date
88 'date' => $session['date'],
89 //Set begin
90 'begin' => $session['begin'],
91 //Set length
92 'length' => $session['length'],
93 //Set raincancel
94 'raincancel' => ($this->isGranted('ROLE_ADMIN') || $this->getUser()->getId() == $session['au_id']) && $session['rainfall'] >= 2,
95 //Set cancel
96 'cancel' => $this->isGranted('ROLE_ADMIN') || in_array($this->getUser()->getId(), explode("\n", $session['sau_id'])),
97 //Set modify
98 'modify' => $this->isGranted('ROLE_ADMIN') || $this->getUser()->getId() == $session['au_id'] && $session['stop'] >= $now && $this->isGranted('ROLE_REGULAR'),
99 //Set move
100 'move' => $this->isGranted('ROLE_ADMIN') || $this->getUser()->getId() == $session['au_id'] && $session['stop'] >= $now && $this->isGranted('ROLE_SENIOR'),
101 //Set attribute
102 'attribute' => $this->isGranted('ROLE_ADMIN') && $session['locked'] === null,
103 //Set session
104 'session' => $session['id']
105 ]);
106
107 //Refill the fields in case of invalid form
108 $form->handleRequest($request);
109
110 //Handle invalid data
111 if (!$form->isSubmitted() || !$form->isValid()) {
112 //Set page
113 $this->context['title'] = $this->translator->trans(!empty($session['au_id'])?'Session %id% by %pseudonym%':'Session %id%', ['%id%' => $id, '%pseudonym%' => $session['au_pseudonym']]);
114
115 //Set facebook title
116 $this->context['facebook']['metas']['og:title'] = $this->context['title'].' '.$this->translator->trans('at '.$session['l_title']);
117
118 //Set section
119 $this->context['section'] = $this->translator->trans($session['l_title']);
120
121 //Set localization date formater
122 $intl = new \IntlDateFormatter($locale, \IntlDateFormatter::GREGORIAN, \IntlDateFormatter::SHORT);
123
124 //Set description
125 $this->context['description'] = $this->translator->trans('Outdoor Argentine Tango session the %date%', [ '%date%' => $intl->format($session['start']) ]);
126
127 //Set localization date formater
128 $intlDate = new \IntlDateFormatter($locale, \IntlDateFormatter::TRADITIONAL, \IntlDateFormatter::NONE);
129
130 //Set localization time formater
131 $intlTime = new \IntlDateFormatter($locale, \IntlDateFormatter::NONE, \IntlDateFormatter::SHORT);
132
133 //Set facebook image
134 $this->context['facebook'] += [
135 'texts' => [
136 $session['au_pseudonym'] => [
137 'font' => 'irishgrover',
138 'size' => 110
139 ],
140 ucfirst($intlDate->format($session['start']))."\n".$this->translator->trans('From %start% to %stop%', ['%start%' => $intlTime->format($session['start']), '%stop%' => $intlTime->format($session['stop'])]) => [
141 'align' => 'left'
142 ],
143 $this->translator->trans('at '.$session['l_title']) => [
144 'align' => 'right',
145 'font' => 'labelleaurore',
146 'size' => 75
147 ]
148 ],
149 'updated' => $session['updated']->format('U')
150 ];
151
152 //Add session in context
153 $this->context['session'] = [
154 'id' => $id,
155 'title' => $this->translator->trans('Session %id%', ['%id%' => $id]),
156 'location' => [
157 'id' => $session['l_id'],
158 'at' => $this->translator->trans('at '.$session['l_title'])
159 ]
160 ];
161
162 //Render the view
163 return $this->render('@RapsysAir/session/edit.html.twig', ['form' => $form->createView()]+$this->context);
164 }
165
166 //Get manager
167 $manager = $doctrine->getManager();
168
169 //Get data
170 $data = $form->getData();
171
172 //Fetch session
173 $session = $doctrine->getRepository(Session::class)->findOneById($id);
174
175 //Set user
176 $user = $this->getUser();
177
178 //Replace with requested user for admin
179 if ($this->isGranted('ROLE_ADMIN') && !empty($data['user'])) {
180 $user = $doctrine->getRepository(User::class)->findOneById($data['user']);
181 }
182
183 //Set datetime
184 $datetime = new \DateTime('now');
185
186 //Set canceled time at start minus one day
187 $canceled = (clone $session->getStart())->sub(new \DateInterval('P1D'));
188
189 //Set action
190 $action = [
191 'raincancel' => $form->has('raincancel') && $form->get('raincancel')->isClicked(),
192 'modify' => $form->has('modify') && $form->get('modify')->isClicked(),
193 'move' => $form->has('move') && $form->get('move')->isClicked(),
194 'cancel' => $form->has('cancel') && $form->get('cancel')->isClicked(),
195 'forcecancel' => $form->has('forcecancel') && $form->get('forcecancel')->isClicked(),
196 'attribute' => $form->has('attribute') && $form->get('attribute')->isClicked(),
197 'autoattribute' => $form->has('autoattribute') && $form->get('autoattribute')->isClicked(),
198 'lock' => $form->has('lock') && $form->get('lock')->isClicked(),
199 ];
200
201 //With raincancel and application and (rainfall or admin)
202 if ($action['raincancel'] && ($application = $session->getApplication()) && ($session->getRainfall() >= 2 || $this->isGranted('ROLE_ADMIN'))) {
203 //Cancel application at start minus one day
204 $application->setCanceled($canceled);
205
206 //Update time
207 $application->setUpdated($datetime);
208
209 //Insufficient rainfall
210 //XXX: is admin
211 if ($session->getRainfall() < 2) {
212 //Set score
213 //XXX: magic cheat score 42
214 $application->setScore(42);
215 }
216
217 //Queue application save
218 $manager->persist($application);
219
220 //Add notice in flash message
221 $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()]));
222
223 //Update time
224 $session->setUpdated($datetime);
225
226 //Queue session save
227 $manager->persist($session);
228
229 //Add notice in flash message
230 $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id]));
231 //With modify
232 } elseif ($action['modify']) {
233 //With admin
234 if ($this->isGranted('ROLE_ADMIN')) {
235 //Set date
236 $session->setDate($data['date']);
237 }
238
239 //Set begin
240 $session->setBegin($data['begin']);
241
242 //Set length
243 $session->setLength($data['length']);
244
245 //Update time
246 $session->setUpdated($datetime);
247
248 //Queue session save
249 $manager->persist($session);
250
251 //Add notice in flash message
252 $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id]));
253 //With move
254 } elseif ($action['move']) {
255 //Set location
256 $session->setLocation($doctrine->getRepository(Location::class)->findOneById($data['location']));
257
258 //Update time
259 $session->setUpdated($datetime);
260
261 //Queue session save
262 $manager->persist($session);
263
264 //Add notice in flash message
265 $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id]));
266 //With cancel or forcecancel
267 } elseif ($action['cancel'] || $action['forcecancel']) {
268 //Get application
269 $application = $doctrine->getRepository(Application::class)->findOneBySessionUser($session, $user);
270
271 //Not already canceled
272 if ($application->getCanceled() === null) {
273 //Cancel application
274 $application->setCanceled($datetime);
275
276 //Check if application is session application and (canceled 24h before start or forcecancel (as admin))
277 #if ($session->getApplication() == $application && ($datetime < $canceled || $action['forcecancel'])) {
278 if ($session->getApplication() == $application && $action['forcecancel']) {
279 //Set score
280 //XXX: magic cheat score 42
281 $application->setScore(42);
282
283 //Unattribute session
284 $session->setApplication(null);
285
286 //Update time
287 $session->setUpdated($datetime);
288
289 //Queue session save
290 $manager->persist($session);
291
292 //Add notice in flash message
293 $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id]));
294 }
295 //Already canceled
296 } else {
297 //Uncancel application
298 $application->setCanceled(null);
299 }
300
301 //Update time
302 $application->setUpdated($datetime);
303
304 //Queue application save
305 $manager->persist($application);
306
307 //Add notice in flash message
308 $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()]));
309 //With attribute
310 } elseif ($action['attribute']) {
311 //Get application
312 $application = $doctrine->getRepository(Application::class)->findOneBySessionUser($session, $user);
313
314 //Already canceled
315 if ($application->getCanceled() !== null) {
316 //Uncancel application
317 $application->setCanceled(null);
318 }
319
320 //Set score
321 //XXX: magic cheat score 42
322 $application->setScore(42);
323
324 //Update time
325 $application->setUpdated($datetime);
326
327 //Queue application save
328 $manager->persist($application);
329
330 //Add notice in flash message
331 $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()]));
332
333 //Unattribute session
334 $session->setApplication($application);
335
336 //Update time
337 $session->setUpdated($datetime);
338
339 //Queue session save
340 $manager->persist($session);
341
342 //Add notice in flash message
343 $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id]));
344 //With autoattribute
345 } elseif ($action['autoattribute']) {
346 //Get best application
347 //XXX: best application may not issue result while grace time or bad behaviour
348 if (!empty($application = $doctrine->getRepository(Session::class)->findBestApplicationById($id))) {
349 //Attribute session
350 $session->setApplication($application);
351
352 //Update time
353 $session->setUpdated($datetime);
354
355 //Queue session save
356 $manager->persist($session);
357
358 //Add notice in flash message
359 $this->addFlash('notice', $this->translator->trans('Session %id% auto attributed', ['%id%' => $id]));
360 //No application
361 } else {
362 //Add warning in flash message
363 $this->addFlash('warning', $this->translator->trans('Session %id% not auto attributed', ['%id%' => $id]));
364 }
365 //With lock
366 } elseif ($action['lock']) {
367 //Already locked
368 if ($session->getLocked() !== null) {
369 //Set uncanceled
370 $canceled = null;
371
372 //Unlock session
373 $session->setLocked(null);
374 //Not locked
375 } else {
376 //Get application
377 if ($application = $session->getApplication()) {
378 //Set score
379 //XXX: magic cheat score 42
380 $application->setScore(42);
381
382 //Update time
383 $application->setUpdated($datetime);
384
385 //Queue application save
386 $manager->persist($application);
387
388 //Add notice in flash message
389 $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()]));
390 }
391
392 //Unattribute session
393 $session->setApplication(null);
394
395 //Lock session
396 $session->setLocked($datetime);
397 }
398
399 //Update time
400 $session->setUpdated($datetime);
401
402 //Queue session save
403 $manager->persist($session);
404
405 //Add notice in flash message
406 $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id]));
407 //Unknown action
408 } else {
409 //Add warning in flash message
410 $this->addFlash('warning', $this->translator->trans('Session %id% not updated', ['%id%' => $id]));
411 }
412
413 //Flush to get the ids
414 $manager->flush();
415
416 //Extract and process referer
417 if ($referer = $request->headers->get('referer')) {
418 //Create referer request instance
419 $req = Request::create($referer);
420
421 //Get referer path
422 $path = $req->getPathInfo();
423
424 //Get referer query string
425 $query = $req->getQueryString();
426
427 //Remove script name
428 $path = str_replace($request->getScriptName(), '', $path);
429
430 //Try with referer path
431 try {
432 //Save old context
433 $oldContext = $this->router->getContext();
434
435 //Force clean context
436 //XXX: prevent MethodNotAllowedException because current context method is POST in onevendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php+42
437 $this->router->setContext(new RequestContext());
438
439 //Retrieve route matching path
440 $route = $this->router->match($path);
441
442 //Reset context
443 $this->router->setContext($oldContext);
444
445 //Clear old context
446 unset($oldContext);
447
448 //Extract name
449 $name = $route['_route'];
450
451 //Remove route and controller from route defaults
452 unset($route['_route'], $route['_controller']);
453
454 //Generate url
455 return $this->redirectToRoute($name, $route);
456 //No route matched
457 } catch(MethodNotAllowedException|ResourceNotFoundException $e) {
458 //Unset referer to fallback to default route
459 unset($referer);
460 }
461 }
462
463 //Redirect to cleanup the form
464 return $this->redirectToRoute('rapsys_air_session_view', ['id' => $id]);
465 }
466
467 /**
468 * List all sessions
469 *
470 * @desc Display all sessions with an application or login form
471 *
472 * @param Request $request The request instance
473 *
474 * @return Response The rendered view
475 */
476 public function index(Request $request): Response {
477 //Fetch doctrine
478 $doctrine = $this->getDoctrine();
479
480 //Set section
481 $section = $this->translator->trans('Sessions');
482
483 //Set description
484 $this->context['description'] = $this->translator->trans('Libre Air session list');
485
486 //Set keywords
487 $this->context['keywords'] = [
488 $this->translator->trans('sessions'),
489 $this->translator->trans('session list'),
490 $this->translator->trans('listing'),
491 $this->translator->trans('Libre Air')
492 ];
493
494 //Set title
495 $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
496
497 //Compute period
498 $period = new \DatePeriod(
499 //Start from first monday of week
500 new \DateTime('Monday this week'),
501 //Iterate on each day
502 new \DateInterval('P1D'),
503 //End with next sunday and 4 weeks
504 new \DateTime(
505 $this->isGranted('IS_AUTHENTICATED_REMEMBERED')?'Monday this week + 3 week':'Monday this week + 2 week'
506 )
507 );
508
509 //Fetch calendar
510 //TODO: highlight with current session route parameter
511 $calendar = $doctrine->getRepository(Session::class)->fetchCalendarByDatePeriod($this->translator, $period, null, $request->get('session'), !$this->isGranted('IS_AUTHENTICATED_REMEMBERED'), $request->getLocale());
512
513 //Fetch locations
514 //XXX: we want to display all active locations anyway
515 $locations = $doctrine->getRepository(Location::class)->findTranslatedSortedByPeriod($this->translator, $period);
516
517 //Render the view
518 return $this->render('@RapsysAir/session/index.html.twig', ['title' => $title, 'section' => $section, 'calendar' => $calendar, 'locations' => $locations]+$this->context);
519 }
520
521 /**
522 * List all sessions for tango argentin
523 *
524 * @desc Display all sessions in tango argentin json format
525 *
526 * @todo Drop it if unused by tangoargentin ???
527 *
528 * @param Request $request The request instance
529 *
530 * @return Response The rendered view or redirection
531 */
532 public function tangoargentin(Request $request): Response {
533 //Fetch doctrine
534 $doctrine = $this->getDoctrine();
535
536 //Compute period
537 $period = new \DatePeriod(
538 //Start from first monday of week
539 new \DateTime('today'),
540 //Iterate on each day
541 new \DateInterval('P1D'),
542 //End with next sunday and 4 weeks
543 new \DateTime('+2 week')
544 );
545
546 //Retrieve events to update
547 $sessions = $doctrine->getRepository(Session::class)->fetchAllByDatePeriod($period, $request->getLocale());
548
549 //Init return array
550 $ret = [];
551
552 //Iterate on sessions
553 foreach($sessions as $sessionId => $session) {
554 //Set title
555 $title = $session['au_pseudonym'].' '.$this->translator->trans('at '.$session['l_title']);
556
557 //Use Transliterator if available
558 if (class_exists('Transliterator')) {
559 $trans = \Transliterator::create('Any-Latin; Latin-ASCII; Upper()');
560 $title = $trans->transliterate($title);
561 } else {
562 $title = strtoupper($title);
563 }
564
565 //Set rate
566 $rate = 'Au chapeau';
567
568 //Without hat
569 if ($session['p_hat'] === null) {
570 //Set rate
571 $rate = 'Gratuit';
572
573 //With rate
574 if ($session['p_rate'] !== null) {
575 //Set rate
576 $rate = $session['p_rate'].' €';
577 }
578 //With hat
579 } else {
580 //With rate
581 if ($session['p_rate'] !== null) {
582 //Set rate
583 $rate .= ', idéalement '.$session['p_rate'].' €';
584 }
585 }
586
587 //Store session data
588 $ret[$sessionId] = [
589 'start' => $session['start']->format(\DateTime::ISO8601),
590 'stop' => $session['start']->format(\DateTime::ISO8601),
591 'title' => $title,
592 'short' => $session['p_short'],
593 'rate' => $rate,
594 'location' => implode(' ', [$session['l_address'], $session['l_zipcode'], $session['l_city']]),
595 'status' => (empty($session['a_canceled']) && empty($session['locked']))?'confirmed':'cancelled',
596 'updated' => $session['updated']->format(\DateTime::ISO8601),
597 'organizer' => $session['au_forename'],
598 'source' => $this->router->generate('rapsys_air_session_view', ['id' => $sessionId], UrlGeneratorInterface::ABSOLUTE_URL)
599 ];
600 }
601
602 //Set response
603 $response = new Response(json_encode($ret));
604
605 //Set header
606 $response->headers->set('Content-Type', 'application/json');
607
608 //Send response
609 return $response;
610 }
611
612 /**
613 * Display session
614 *
615 * @todo XXX: TODO: add <link rel="prev|next" for sessions or classes ? />
616 * @todo XXX: TODO: like described in: https://www.alsacreations.com/article/lire/1400-attribut-rel-relations.html#xnf-rel-attribute
617 * @todo XXX: TODO: or here: http://microformats.org/wiki/existing-rel-values#HTML5_link_type_extensions
618 *
619 * @desc Display session by id with an application or login form
620 *
621 * @param Request $request The request instance
622 * @param int $id The session id
623 *
624 * @return Response The rendered view
625 */
626 public function view(Request $request, $id): Response {
627 //Fetch doctrine
628 $doctrine = $this->getDoctrine();
629
630 //Set locale
631 $locale = $request->getLocale();
632
633 //Fetch session
634 if (empty($session = $doctrine->getRepository(Session::class)->fetchOneById($id, $locale))) {
635 throw $this->createNotFoundException($this->translator->trans('Unable to find session: %id%', ['%id%' => $id]));
636 }
637
638 //Create response
639 $response = new Response();
640
641 //Set etag
642 $response->setEtag(md5(serialize($session)));
643
644 //With logged user
645 if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
646 //Set last modified
647 $response->setLastModified(new \DateTime('-1 year'));
648
649 //Set as private
650 $response->setPrivate();
651 //Without logged user
652 } else {
653 //Extract applications updated
654 $session['sa_updated'] = array_map(function($v){return new \DateTime($v);}, explode("\n", $session['sa_updated']));
655
656 //Get last modified
657 $lastModified = max(array_merge([$session['updated'], $session['l_updated'], $session['t_updated'], $session['p_updated']], $session['sa_updated']));
658
659 //Set last modified
660 $response->setLastModified($lastModified);
661
662 //Set as public
663 $response->setPublic();
664
665 //Without role and modification
666 if ($response->isNotModified($request)) {
667 //Return 304 response
668 return $response;
669 }
670 }
671
672 //Set localization date formater
673 $intl = new \IntlDateFormatter($locale, \IntlDateFormatter::GREGORIAN, \IntlDateFormatter::SHORT);
674
675 //Set section
676 $this->context['section'] = $this->translator->trans($session['l_title']);
677
678 //Set description
679 $this->context['description'] = $this->translator->trans('Outdoor Argentine Tango session the %date%', [ '%date%' => $intl->format($session['start']) ]);
680
681 //Set keywords
682 $this->context['keywords'] = [
683 $this->translator->trans('outdoor'),
684 $this->translator->trans('Argentine Tango'),
685 ];
686
687 //Set localization date formater
688 $intlDate = new \IntlDateFormatter($locale, \IntlDateFormatter::TRADITIONAL, \IntlDateFormatter::NONE);
689
690 //Set localization time formater
691 $intlTime = new \IntlDateFormatter($locale, \IntlDateFormatter::NONE, \IntlDateFormatter::SHORT);
692
693 //Set facebook image
694 $this->context['facebook'] = [
695 'texts' => [
696 $session['au_pseudonym'] => [
697 'font' => 'irishgrover',
698 'size' => 110
699 ],
700 ucfirst($intlDate->format($session['start']))."\n".$this->translator->trans('From %start% to %stop%', ['%start%' => $intlTime->format($session['start']), '%stop%' => $intlTime->format($session['stop'])]) => [
701 'align' => 'left'
702 ],
703 $this->translator->trans('at '.$session['l_title']) => [
704 'align' => 'right',
705 'font' => 'labelleaurore',
706 'size' => 75
707 ]
708 ],
709 'updated' => $session['updated']->format('U')
710 ]+$this->context['facebook'];
711
712 //With granted session
713 if (!empty($session['au_id'])) {
714 array_unshift($this->context['keywords'], $session['au_pseudonym']);
715 }
716
717 //Set page
718 $this->context['title'] = $this->translator->trans(!empty($session['au_id'])?'Session %id% by %pseudonym%':'Session %id%', ['%id%' => $id, '%pseudonym%' => $session['au_pseudonym']]);
719
720 //Set facebook title
721 $this->context['facebook']['metas']['og:title'] = $this->context['title'].' '.$this->translator->trans('at '.$session['l_title']);
722
723 //Create application form for role_guest
724 if ($this->isGranted('ROLE_GUEST')) {
725 //Set now
726 $now = new \DateTime('now');
727
728 //Create SessionType form
729 $sessionForm = $this->createForm('Rapsys\AirBundle\Form\SessionType', null, [
730 //Set the action
731 'action' => $this->generateUrl('rapsys_air_session_edit', [ 'id' => $id ]),
732 //Set the form attribute
733 'attr' => [ 'class' => 'col' ],
734 //Set admin
735 'admin' => $this->isGranted('ROLE_ADMIN'),
736 //Set default user to current
737 'user' => $this->getUser()->getId(),
738 //Set date
739 'date' => $session['date'],
740 //Set begin
741 'begin' => $session['begin'],
742 //Set length
743 'length' => $session['length'],
744 //Set raincancel
745 'raincancel' => ($this->isGranted('ROLE_ADMIN') || $this->getUser()->getId() == $session['au_id']) && $session['rainfall'] >= 2,
746 //Set cancel
747 'cancel' => $this->isGranted('ROLE_ADMIN') || in_array($this->getUser()->getId(), explode("\n", $session['sau_id'])),
748 //Set modify
749 'modify' => $this->isGranted('ROLE_ADMIN') || $this->getUser()->getId() == $session['au_id'] && $session['stop'] >= $now && $this->isGranted('ROLE_REGULAR'),
750 //Set move
751 'move' => $this->isGranted('ROLE_ADMIN') || $this->getUser()->getId() == $session['au_id'] && $session['stop'] >= $now && $this->isGranted('ROLE_SENIOR'),
752 //Set attribute
753 'attribute' => $this->isGranted('ROLE_ADMIN') && $session['locked'] === null,
754 //Set session
755 'session' => $session['id']
756 ]);
757
758 //Add form to context
759 $this->context['forms']['session'] = $sessionForm->createView();
760 }
761
762 //Add session in context
763 $this->context['session'] = [
764 'id' => $id,
765 'date' => $session['date'],
766 'begin' => $session['begin'],
767 'start' => $session['start'],
768 'length' => $session['length'],
769 'stop' => $session['stop'],
770 'rainfall' => $session['rainfall'] !== null ? $session['rainfall'].' mm' : $session['rainfall'],
771 'rainrisk' => $session['rainrisk'] !== null ? ($session['rainrisk']*100).' %' : $session['rainrisk'],
772 'realfeel' => $session['realfeel'] !== null ? $session['realfeel'].' °C' : $session['realfeel'],
773 'realfeelmin' => $session['realfeelmin'] !== null ? $session['realfeelmin'].' °C' : $session['realfeelmin'],
774 'realfeelmax' => $session['realfeelmax'] !== null ? $session['realfeelmax'].' °C' : $session['realfeelmax'],
775 'temperature' => $session['temperature'] !== null ? $session['temperature'].' °C' : $session['temperature'],
776 'temperaturemin' => $session['temperaturemin'] !== null ? $session['temperaturemin'].' °C' : $session['temperaturemin'],
777 'temperaturemax' => $session['temperaturemax'] !== null ? $session['temperaturemax'].' °C' : $session['temperaturemax'],
778 'locked' => $session['locked'],
779 'created' => $session['created'],
780 'updated' => $session['updated'],
781 'title' => $this->translator->trans('Session %id%', ['%id%' => $id]),
782 'application' => null,
783 'location' => [
784 'id' => $session['l_id'],
785 'at' => $this->translator->trans('at '.$session['l_title']),
786 'title' => $this->translator->trans($session['l_title']),
787 'address' => $session['l_address'],
788 'zipcode' => $session['l_zipcode'],
789 'city' => $session['l_city'],
790 'latitude' => $session['l_latitude'],
791 'longitude' => $session['l_longitude']
792 ],
793 'slot' => [
794 'id' => $session['t_id'],
795 'title' => $this->translator->trans($session['t_title'])
796 ],
797 'snippet' => [
798 'id' => $session['p_id'],
799 'description' => $session['p_description'],
800 'class' => $session['p_class'],
801 'contact' => $session['p_contact'],
802 'donate' => $session['p_donate'],
803 'link' => $session['p_link'],
804 'profile' => $session['p_profile'],
805 'rate' => $session['p_rate'],
806 'hat' => $session['p_hat']
807 ],
808 'applications' => null
809 ];
810
811 //With application
812 if (!empty($session['a_id'])) {
813 $this->context['session']['application'] = [
814 'user' => [
815 'id' => $session['au_id'],
816 'by' => $this->translator->trans('by %pseudonym%', [ '%pseudonym%' => $session['au_pseudonym'] ]),
817 'title' => $session['au_pseudonym']
818 ],
819 'id' => $session['a_id'],
820 'canceled' => $session['a_canceled'],
821 'title' => $this->translator->trans('Application %id%', [ '%id%' => $session['a_id'] ]),
822 ];
823 }
824
825 //With applications
826 if (!empty($session['sa_id'])) {
827 //Extract applications id
828 $session['sa_id'] = explode("\n", $session['sa_id']);
829 //Extract applications score
830 //XXX: score may be null before grant or for bad behaviour, replace NULL with 'NULL' to avoid silent drop in mysql
831 $session['sa_score'] = array_map(function($v){return $v==='NULL'?null:$v;}, explode("\n", $session['sa_score']));
832 //Extract applications created
833 $session['sa_created'] = array_map(function($v){return new \DateTime($v);}, explode("\n", $session['sa_created']));
834 //Extract applications updated
835 //XXX: done earlied when computing last modified
836 #$session['sa_updated'] = array_map(function($v){return new \DateTime($v);}, explode("\n", $session['sa_updated']));
837 //Extract applications canceled
838 //XXX: canceled is null before cancelation, replace NULL with 'NULL' to avoid silent drop in mysql
839 $session['sa_canceled'] = array_map(function($v){return $v==='NULL'?null:new \DateTime($v);}, explode("\n", $session['sa_canceled']));
840
841 //Extract applications user id
842 $session['sau_id'] = explode("\n", $session['sau_id']);
843 //Extract applications user pseudonym
844 $session['sau_pseudonym'] = explode("\n", $session['sau_pseudonym']);
845
846 //Init applications
847 $this->context['session']['applications'] = [];
848 foreach($session['sa_id'] as $i => $sa_id) {
849 $this->context['session']['applications'][$sa_id] = [
850 'user' => null,
851 'score' => $session['sa_score'][$i],
852 'created' => $session['sa_created'][$i],
853 'updated' => $session['sa_updated'][$i],
854 'canceled' => $session['sa_canceled'][$i]
855 ];
856 if (!empty($session['sau_id'][$i])) {
857 $this->context['session']['applications'][$sa_id]['user'] = [
858 'id' => $session['sau_id'][$i],
859 'title' => $session['sau_pseudonym'][$i]
860 ];
861 }
862 }
863 }
864
865 //Compute period
866 $period = new \DatePeriod(
867 //Start from first monday of week
868 new \DateTime('Monday this week'),
869 //Iterate on each day
870 new \DateInterval('P1D'),
871 //End with next sunday and 4 weeks
872 new \DateTime(
873 $this->isGranted('IS_AUTHENTICATED_REMEMBERED')?'Monday this week + 3 week':'Monday this week + 2 week'
874 )
875 );
876
877 //Fetch locations
878 //XXX: we want to display all active locations anyway
879 $locations = $doctrine->getRepository(Location::class)->findTranslatedSortedByPeriod($this->translator, $period, $session['au_id']);
880
881 //Render the view
882 return $this->render('@RapsysAir/session/view.html.twig', ['locations' => $locations]+$this->context, $response);
883 }
884 }