]> Raphaël G. Git Repositories - airbundle/blob - Controller/SessionController.php
Cleanup locale
[airbundle] / Controller / SessionController.php
1 <?php
2
3 namespace Rapsys\AirBundle\Controller;
4
5 use Symfony\Component\Asset\Packages;
6 use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
7 use Symfony\Component\Filesystem\Filesystem;
8 use Symfony\Component\HttpFoundation\BinaryFileResponse;
9 use Symfony\Component\HttpFoundation\Request;
10 use Symfony\Component\HttpFoundation\Response;
11 use Symfony\Component\Routing\Exception\MethodNotAllowedException;
12 use Symfony\Component\Routing\Exception\ResourceNotFoundException;
13 use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
14 use Symfony\Component\Routing\RequestContext;
15
16 use Rapsys\AirBundle\Entity\Application;
17 use Rapsys\AirBundle\Entity\User;
18 use Rapsys\AirBundle\Entity\Slot;
19 use Rapsys\AirBundle\Entity\Session;
20 use Rapsys\AirBundle\Entity\Location;
21
22 class SessionController extends DefaultController {
23 /**
24 * Edit session
25 *
26 * @desc Persist session and all required dependencies in database
27 *
28 * @param Request $request The request instance
29 *
30 * @return Response The rendered view or redirection
31 *
32 * @throws \RuntimeException When user has not at least guest role
33 */
34 public function edit(Request $request, $id): Response {
35 //Prevent non-guest to access here
36 $this->denyAccessUnlessGranted('ROLE_GUEST', null, $this->translator->trans('Unable to access this page without role %role%!', ['%role%' => $this->translator->trans('Guest')]));
37
38 //Reject non post requests
39 if (!$request->isMethod('POST')) {
40 throw new \RuntimeException('Request method MUST be POST');
41 }
42
43 //Get doctrine
44 $doctrine = $this->getDoctrine();
45
46 //Set locale
47 $locale = $request->getLocale();
48
49 //Fetch session
50 $session = $doctrine->getRepository(Session::class)->fetchOneById($id, $locale);
51
52 //Check if
53 if (
54 //we are admin
55 !$this->isGranted('ROLE_ADMIN') &&
56 //or attributed user
57 $this->getUser()->getId() != $session['au_id'] &&
58 //or application without attributed user
59 $session['au_id'] !== null && !in_array($this->getUser()->getId(), explode("\n", $session['sau_id']))
60 ) {
61 //Prevent non admin and non attributed user access
62 throw $this->createAccessDeniedException();
63 }
64
65 //Set now
66 $now = new \DateTime('now');
67
68 //Create SessionType form
69 $form = $this->createForm('Rapsys\AirBundle\Form\SessionType', null, [
70 //Set the action
71 'action' => $this->generateUrl('rapsys_air_session_edit', [ 'id' => $id ]),
72 //Set the form attribute
73 'attr' => [],
74 //Set admin
75 'admin' => $this->isGranted('ROLE_ADMIN'),
76 //Set default user to current
77 'user' => $this->getUser()->getId(),
78 //Set begin
79 'begin' => $session['begin'],
80 //Set length
81 'length' => $session['length'],
82 //Set raincancel
83 'raincancel' => ($this->isGranted('ROLE_ADMIN') || $this->getUser()->getId() == $session['au_id']) && $session['rainfall'] >= 2,
84 //Set cancel
85 'cancel' => $this->isGranted('ROLE_ADMIN') || in_array($this->getUser()->getId(), explode("\n", $session['sau_id'])),
86 //Set modify
87 'modify' => $this->isGranted('ROLE_ADMIN') || $this->getUser()->getId() == $session['au_id'] && $session['stop'] >= $now && $this->isGranted('ROLE_REGULAR'),
88 //Set move
89 'move' => $this->isGranted('ROLE_ADMIN') || $this->getUser()->getId() == $session['au_id'] && $session['stop'] >= $now && $this->isGranted('ROLE_SENIOR'),
90 //Set attribute
91 'attribute' => $this->isGranted('ROLE_ADMIN') && $session['locked'] === null,
92 //Set session
93 'session' => $session['id']
94 ]);
95
96 //Refill the fields in case of invalid form
97 $form->handleRequest($request);
98
99 //Handle invalid data
100 #if (true) { $form->isValid();
101 //TODO: mettre une contrainte sur un des boutons submit, je sais pas encore comment
102 if (!$form->isValid()) {
103 //Set page
104 $this->context['page']['title'] = $this->translator->trans(!empty($session['au_id'])?'Session %id% by %pseudonym%':'Session %id%', ['%id%' => $id, '%pseudonym%' => $session['au_pseudonym']]);
105
106 //Set facebook title
107 $this->context['ogps']['title'] = $this->context['page']['title'].' '.$this->translator->trans('at '.$session['l_title']);
108
109 //Set section
110 $this->context['page']['section'] = $this->translator->trans($session['l_title']);
111
112 //Set localization date formater
113 $intlDate = new \IntlDateFormatter($locale, \IntlDateFormatter::TRADITIONAL, \IntlDateFormatter::NONE);
114
115 //Set localization time formater
116 $intlTime = new \IntlDateFormatter($locale, \IntlDateFormatter::NONE, \IntlDateFormatter::SHORT);
117
118 //Set facebook image
119 $this->context['facebook'] += [
120 'texts' => [
121 $session['au_pseudonym'] => [
122 'font' => 'irishgrover',
123 'size' => 110
124 ],
125 ucfirst($intlDate->format($session['start']))."\n".$this->translator->trans('From %start% to %stop%', ['%start%' => $intlTime->format($session['start']), '%stop%' => $intlTime->format($session['stop'])]) => [
126 'align' => 'left'
127 ],
128 $this->translator->trans('at '.$session['l_title']) => [
129 'align' => 'right',
130 'font' => 'labelleaurore',
131 'size' => 75
132 ]
133 ],
134 'updated' => $session['updated']->format('U')
135 ];
136
137 //Add session in context
138 $this->context['session'] = [
139 'id' => $id,
140 'title' => $this->translator->trans('Session %id%', ['%id%' => $id]),
141 'location' => [
142 'id' => $session['l_id'],
143 'at' => $this->translator->trans('at '.$session['l_title'])
144 ]
145 ];
146
147 //Render the view
148 return $this->render('@RapsysAir/session/edit.html.twig', ['form' => $form->createView()]+$this->context);
149 }
150
151 //Get manager
152 $manager = $doctrine->getManager();
153
154 //Get data
155 $data = $form->getData();
156
157 //Fetch session
158 $session = $doctrine->getRepository(Session::class)->findOneById($id);
159
160 //Set user
161 $user = $this->getUser();
162
163 //Replace with requested user for admin
164 if ($this->isGranted('ROLE_ADMIN') && !empty($data['user'])) {
165 $user = $doctrine->getRepository(User::class)->findOneById($data['user']);
166 }
167
168 //Set datetime
169 $datetime = new \DateTime('now');
170
171 //Set canceled time at start minus one day
172 $canceled = (clone $session->getStart())->sub(new \DateInterval('P1D'));
173
174 //Set action
175 $action = [
176 'raincancel' => $form->has('raincancel') && $form->get('raincancel')->isClicked(),
177 'modify' => $form->has('modify') && $form->get('modify')->isClicked(),
178 'move' => $form->has('move') && $form->get('move')->isClicked(),
179 'cancel' => $form->has('cancel') && $form->get('cancel')->isClicked(),
180 'forcecancel' => $form->has('forcecancel') && $form->get('forcecancel')->isClicked(),
181 'attribute' => $form->has('attribute') && $form->get('attribute')->isClicked(),
182 'autoattribute' => $form->has('autoattribute') && $form->get('autoattribute')->isClicked(),
183 'lock' => $form->has('lock') && $form->get('lock')->isClicked(),
184 ];
185
186 //With raincancel and application and (rainfall or admin)
187 if ($action['raincancel'] && ($application = $session->getApplication()) && ($session->getRainfall() >= 2 || $this->isGranted('ROLE_ADMIN'))) {
188 //Cancel application at start minus one day
189 $application->setCanceled($canceled);
190
191 //Update time
192 $application->setUpdated($datetime);
193
194 //Insufficient rainfall
195 //XXX: is admin
196 if ($session->getRainfall() < 2) {
197 //Set score
198 //XXX: magic cheat score 42
199 $application->setScore(42);
200 }
201
202 //Queue application save
203 $manager->persist($application);
204
205 //Add notice in flash message
206 $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()]));
207
208 //Update time
209 $session->setUpdated($datetime);
210
211 //Queue session save
212 $manager->persist($session);
213
214 //Add notice in flash message
215 $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id]));
216 //With modify
217 } elseif ($action['modify']) {
218 //Set begin
219 $session->setBegin($data['begin']);
220
221 //Set length
222 $session->setLength($data['length']);
223
224 //Update time
225 $session->setUpdated($datetime);
226
227 //Queue session save
228 $manager->persist($session);
229
230 //Add notice in flash message
231 $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id]));
232 //With move
233 } elseif ($action['move']) {
234 //Set location
235 $session->setLocation($doctrine->getRepository(Location::class)->findOneById($data['location']));
236
237 //Update time
238 $session->setUpdated($datetime);
239
240 //Queue session save
241 $manager->persist($session);
242
243 //Add notice in flash message
244 $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id]));
245 //With cancel or forcecancel
246 } elseif ($action['cancel'] || $action['forcecancel']) {
247 //Get application
248 $application = $doctrine->getRepository(Application::class)->findOneBySessionUser($session, $user);
249
250 //Not already canceled
251 if ($application->getCanceled() === null) {
252 //Cancel application
253 $application->setCanceled($datetime);
254
255 //Check if application is session application and (canceled 24h before start or forcecancel (as admin))
256 #if ($session->getApplication() == $application && ($datetime < $canceled || $action['forcecancel'])) {
257 if ($session->getApplication() == $application && $action['forcecancel']) {
258 //Set score
259 //XXX: magic cheat score 42
260 $application->setScore(42);
261
262 //Unattribute session
263 $session->setApplication(null);
264
265 //Update time
266 $session->setUpdated($datetime);
267
268 //Queue session save
269 $manager->persist($session);
270
271 //Add notice in flash message
272 $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id]));
273 }
274 //Already canceled
275 } else {
276 //Uncancel application
277 $application->setCanceled(null);
278 }
279
280 //Update time
281 $application->setUpdated($datetime);
282
283 //Queue application save
284 $manager->persist($application);
285
286 //Add notice in flash message
287 $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()]));
288 //With attribute
289 } elseif ($action['attribute']) {
290 //Get application
291 $application = $doctrine->getRepository(Application::class)->findOneBySessionUser($session, $user);
292
293 //Already canceled
294 if ($application->getCanceled() !== null) {
295 //Uncancel application
296 $application->setCanceled(null);
297 }
298
299 //Set score
300 //XXX: magic cheat score 42
301 $application->setScore(42);
302
303 //Update time
304 $application->setUpdated($datetime);
305
306 //Queue application save
307 $manager->persist($application);
308
309 //Add notice in flash message
310 $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()]));
311
312 //Unattribute session
313 $session->setApplication($application);
314
315 //Update time
316 $session->setUpdated($datetime);
317
318 //Queue session save
319 $manager->persist($session);
320
321 //Add notice in flash message
322 $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id]));
323 //With autoattribute
324 } elseif ($action['autoattribute']) {
325 //Get best application
326 //XXX: best application may not issue result while grace time or bad behaviour
327 if (!empty($application = $doctrine->getRepository(Session::class)->findBestApplicationById($id))) {
328 //Attribute session
329 $session->setApplication($application);
330
331 //Update time
332 $session->setUpdated($datetime);
333
334 //Queue session save
335 $manager->persist($session);
336
337 //Add notice in flash message
338 $this->addFlash('notice', $this->translator->trans('Session %id% auto attributed', ['%id%' => $id]));
339 //No application
340 } else {
341 //Add warning in flash message
342 $this->addFlash('warning', $this->translator->trans('Session %id% not auto attributed', ['%id%' => $id]));
343 }
344 //With lock
345 } elseif ($action['lock']) {
346 //Already locked
347 if ($session->getLocked() !== null) {
348 //Set uncanceled
349 $canceled = null;
350
351 //Unlock session
352 $session->setLocked(null);
353 //Not locked
354 } else {
355 //Get application
356 if ($application = $session->getApplication()) {
357 //Set score
358 //XXX: magic cheat score 42
359 $application->setScore(42);
360
361 //Update time
362 $application->setUpdated($datetime);
363
364 //Queue application save
365 $manager->persist($application);
366
367 //Add notice in flash message
368 $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()]));
369 }
370
371 //Unattribute session
372 $session->setApplication(null);
373
374 //Lock session
375 $session->setLocked($datetime);
376 }
377
378 # //Get applications
379 # $applications = $doctrine->getRepository(Application::class)->findBySession($session);
380 #
381 # //Not empty
382 # if (!empty($applications)) {
383 # //Iterate on each applications
384 # foreach($applications as $application) {
385 # //Cancel application
386 # $application->setCanceled($canceled);
387 #
388 # //Update time
389 # $application->setUpdated($datetime);
390 #
391 # //Queue application save
392 # $manager->persist($application);
393 #
394 # //Add notice in flash message
395 # $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()]));
396 # }
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'));
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_short']);
556 //Use Transliterator if available
557 if (class_exists('Transliterator')) {
558 $trans = \Transliterator::create('Any-Latin; Latin-ASCII; Upper()');
559 $title = $trans->transliterate($title);
560 } else {
561 $title = strtoupper($title);
562 }
563 //Store session data
564 $ret[$sessionId] = [
565 'start' => $session['start']->format(\DateTime::ISO8601),
566 'stop' => $session['start']->format(\DateTime::ISO8601),
567 'title' => $title,
568 'short' => $session['p_short'],
569 'rate' => is_null($session['p_rate'])?'Au chapeau':$session['p_rate'].' euro'.($session['p_rate']>1?'s':''),
570 'location' => implode(' ', [$session['l_address'], $session['l_zipcode'], $session['l_city']]),
571 'status' => (empty($session['a_canceled']) && empty($session['locked']))?'confirmed':'cancelled',
572 'updated' => $session['updated']->format(\DateTime::ISO8601),
573 'organizer' => $session['au_forename'],
574 'website' => $this->router->generate('rapsys_air_session_view', ['id' => $sessionId], UrlGeneratorInterface::ABSOLUTE_URL)
575 ];
576 }
577
578 //Set response
579 $response = new Response(json_encode($ret));
580
581 //Set header
582 $response->headers->set('Content-Type', 'application/json');
583
584 //Send response
585 return $response;
586 }
587
588 /**
589 * Display session
590 *
591 * @todo XXX: TODO: add <link rel="prev|next" for sessions or classes ? />
592 * @todo XXX: TODO: like described in: https://www.alsacreations.com/article/lire/1400-attribut-rel-relations.html#xnf-rel-attribute
593 * @todo XXX: TODO: or here: http://microformats.org/wiki/existing-rel-values#HTML5_link_type_extensions
594 *
595 * @desc Display session by id with an application or login form
596 *
597 * @param Request $request The request instance
598 * @param int $id The session id
599 *
600 * @return Response The rendered view
601 */
602 public function view(Request $request, $id): Response {
603 //Fetch doctrine
604 $doctrine = $this->getDoctrine();
605
606 //Set locale
607 $locale = $request->getLocale();
608
609 //Fetch session
610 if (empty($session = $doctrine->getRepository(Session::class)->fetchOneById($id, $locale))) {
611 throw $this->createNotFoundException($this->translator->trans('Unable to find session: %id%', ['%id%' => $id]));
612 }
613
614 //Create response
615 $response = new Response();
616
617 //Set etag
618 $response->setEtag(md5(serialize($session)));
619
620 //With logged user
621 if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
622 //Set last modified
623 $response->setLastModified(new \DateTime('-1 year'));
624
625 //Set as private
626 $response->setPrivate();
627 //Without logged user
628 } else {
629 //Extract applications updated
630 $session['sa_updated'] = array_map(function($v){return new \DateTime($v);}, explode("\n", $session['sa_updated']));
631
632 //Get last modified
633 $lastModified = max(array_merge([$session['updated'], $session['l_updated'], $session['t_updated'], $session['p_updated']], $session['sa_updated']));
634
635 //Set last modified
636 $response->setLastModified($lastModified);
637
638 //Set as public
639 $response->setPublic();
640
641 //Without role and modification
642 if ($response->isNotModified($request)) {
643 //Return 304 response
644 return $response;
645 }
646 }
647
648 //Set localization date formater
649 $intl = new \IntlDateFormatter($locale, \IntlDateFormatter::GREGORIAN, \IntlDateFormatter::SHORT);
650
651 //Set section
652 $this->context['page']['section'] = $this->translator->trans($session['l_title']);
653
654 //Set description
655 $this->context['page']['description'] = $this->translator->trans('Outdoor Argentine Tango session the %date%', [ '%date%' => $intl->format($session['start']) ]);
656
657 //Set keywords
658 $this->context['keywords'] = [
659 $this->translator->trans('outdoor'),
660 $this->translator->trans('Argentine Tango'),
661 ];
662
663 //Set localization date formater
664 $intlDate = new \IntlDateFormatter($locale, \IntlDateFormatter::TRADITIONAL, \IntlDateFormatter::NONE);
665
666 //Set localization time formater
667 $intlTime = new \IntlDateFormatter($locale, \IntlDateFormatter::NONE, \IntlDateFormatter::SHORT);
668
669 //Set facebook image
670 $this->context['facebook'] = [
671 'texts' => [
672 $session['au_pseudonym'] => [
673 'font' => 'irishgrover',
674 'size' => 110
675 ],
676 ucfirst($intlDate->format($session['start']))."\n".$this->translator->trans('From %start% to %stop%', ['%start%' => $intlTime->format($session['start']), '%stop%' => $intlTime->format($session['stop'])]) => [
677 'align' => 'left'
678 ],
679 $this->translator->trans('at '.$session['l_title']) => [
680 'align' => 'right',
681 'font' => 'labelleaurore',
682 'size' => 75
683 ]
684 ],
685 'updated' => $session['updated']->format('U')
686 ]+$this->context['facebook'];
687
688 //With granted session
689 if (!empty($session['au_id'])) {
690 $this->context['keywords'][0] = $session['au_pseudonym'];
691 }
692
693 //Set page
694 $this->context['page']['title'] = $this->translator->trans(!empty($session['au_id'])?'Session %id% by %pseudonym%':'Session %id%', ['%id%' => $id, '%pseudonym%' => $session['au_pseudonym']]);
695
696 //Set facebook title
697 $this->context['ogps']['title'] = $this->context['page']['title'].' '.$this->translator->trans('at '.$session['l_title']);
698
699 //Create application form for role_guest
700 if ($this->isGranted('ROLE_GUEST')) {
701 //Create ApplicationType form
702 $applicationForm = $this->createForm('Rapsys\AirBundle\Form\ApplicationType', null, [
703 //Set the action
704 'action' => $this->generateUrl('rapsys_air_application_add'),
705 //Set the form attribute
706 'attr' => [ 'class' => 'col' ],
707 //Set admin
708 'admin' => $this->isGranted('ROLE_ADMIN'),
709 //Set default user to current
710 'user' => $this->getUser()->getId(),
711 //Set default slot to current
712 'slot' => $this->getDoctrine()->getRepository(Slot::class)->findOneById($session['t_id']),
713 //Set default location to current
714 'location' => $this->getDoctrine()->getRepository(Location::class)->findOneById($session['l_id']),
715 ]);
716
717 //Add form to context
718 $this->context['forms']['application'] = $applicationForm->createView();
719
720 //Set now
721 $now = new \DateTime('now');
722
723 //Create SessionType form
724 $sessionForm = $this->createForm('Rapsys\AirBundle\Form\SessionType', null, [
725 //Set the action
726 'action' => $this->generateUrl('rapsys_air_session_edit', [ 'id' => $id ]),
727 //Set the form attribute
728 'attr' => [ 'class' => 'col' ],
729 //Set admin
730 'admin' => $this->isGranted('ROLE_ADMIN'),
731 //Set default user to current
732 'user' => $this->getUser()->getId(),
733 //Set begin
734 'begin' => $session['begin'],
735 //Set length
736 'length' => $session['length'],
737 //Set raincancel
738 'raincancel' => ($this->isGranted('ROLE_ADMIN') || $this->getUser()->getId() == $session['au_id']) && $session['rainfall'] >= 2,
739 //Set cancel
740 'cancel' => $this->isGranted('ROLE_ADMIN') || in_array($this->getUser()->getId(), explode("\n", $session['sau_id'])),
741 //Set modify
742 'modify' => $this->isGranted('ROLE_ADMIN') || $this->getUser()->getId() == $session['au_id'] && $session['stop'] >= $now && $this->isGranted('ROLE_REGULAR'),
743 //Set move
744 'move' => $this->isGranted('ROLE_ADMIN') || $this->getUser()->getId() == $session['au_id'] && $session['stop'] >= $now && $this->isGranted('ROLE_SENIOR'),
745 //Set attribute
746 'attribute' => $this->isGranted('ROLE_ADMIN') && $session['locked'] === null,
747 //Set session
748 'session' => $session['id']
749 ]);
750
751 //Add form to context
752 $this->context['forms']['session'] = $sessionForm->createView();
753 }
754
755 //Add session in context
756 $this->context['session'] = [
757 'id' => $id,
758 'date' => $session['date'],
759 'begin' => $session['begin'],
760 'start' => $session['start'],
761 'length' => $session['length'],
762 'stop' => $session['stop'],
763 'rainfall' => $session['rainfall'] !== null ? $session['rainfall'].' mm' : $session['rainfall'],
764 'rainrisk' => $session['rainrisk'] !== null ? ($session['rainrisk']*100).' %' : $session['rainrisk'],
765 'realfeel' => $session['realfeel'] !== null ? $session['realfeel'].' °C' : $session['realfeel'],
766 'realfeelmin' => $session['realfeelmin'] !== null ? $session['realfeelmin'].' °C' : $session['realfeelmin'],
767 'realfeelmax' => $session['realfeelmax'] !== null ? $session['realfeelmax'].' °C' : $session['realfeelmax'],
768 'temperature' => $session['temperature'] !== null ? $session['temperature'].' °C' : $session['temperature'],
769 'temperaturemin' => $session['temperaturemin'] !== null ? $session['temperaturemin'].' °C' : $session['temperaturemin'],
770 'temperaturemax' => $session['temperaturemax'] !== null ? $session['temperaturemax'].' °C' : $session['temperaturemax'],
771 'locked' => $session['locked'],
772 'created' => $session['created'],
773 'updated' => $session['updated'],
774 'title' => $this->translator->trans('Session %id%', ['%id%' => $id]),
775 'application' => null,
776 'location' => [
777 'id' => $session['l_id'],
778 'at' => $this->translator->trans('at '.$session['l_title']),
779 'short' => $this->translator->trans($session['l_short']),
780 'title' => $this->translator->trans($session['l_title']),
781 'address' => $session['l_address'],
782 'zipcode' => $session['l_zipcode'],
783 'city' => $session['l_city'],
784 'latitude' => $session['l_latitude'],
785 'longitude' => $session['l_longitude']
786 ],
787 'slot' => [
788 'id' => $session['t_id'],
789 'title' => $this->translator->trans($session['t_title'])
790 ],
791 'snippet' => [
792 'id' => $session['p_id'],
793 'description' => $session['p_description'],
794 'class' => $session['p_class'],
795 'contact' => $session['p_contact'],
796 'donate' => $session['p_donate'],
797 'link' => $session['p_link'],
798 'profile' => $session['p_profile']
799 ],
800 'applications' => null
801 ];
802
803 //With application
804 if (!empty($session['a_id'])) {
805 $this->context['session']['application'] = [
806 'user' => [
807 'id' => $session['au_id'],
808 'by' => $this->translator->trans('by %pseudonym%', [ '%pseudonym%' => $session['au_pseudonym'] ]),
809 'title' => $session['au_pseudonym']
810 ],
811 'id' => $session['a_id'],
812 'canceled' => $session['a_canceled'],
813 'title' => $this->translator->trans('Application %id%', [ '%id%' => $session['a_id'] ]),
814 ];
815 }
816
817 //With applications
818 if (!empty($session['sa_id'])) {
819 //Extract applications id
820 $session['sa_id'] = explode("\n", $session['sa_id']);
821 //Extract applications score
822 //XXX: score may be null before grant or for bad behaviour, replace NULL with 'NULL' to avoid silent drop in mysql
823 $session['sa_score'] = array_map(function($v){return $v==='NULL'?null:$v;}, explode("\n", $session['sa_score']));
824 //Extract applications created
825 $session['sa_created'] = array_map(function($v){return new \DateTime($v);}, explode("\n", $session['sa_created']));
826 //Extract applications updated
827 //XXX: done earlied when computing last modified
828 #$session['sa_updated'] = array_map(function($v){return new \DateTime($v);}, explode("\n", $session['sa_updated']));
829 //Extract applications canceled
830 //XXX: canceled is null before cancelation, replace NULL with 'NULL' to avoid silent drop in mysql
831 $session['sa_canceled'] = array_map(function($v){return $v==='NULL'?null:new \DateTime($v);}, explode("\n", $session['sa_canceled']));
832
833 //Extract applications user id
834 $session['sau_id'] = explode("\n", $session['sau_id']);
835 //Extract applications user pseudonym
836 $session['sau_pseudonym'] = explode("\n", $session['sau_pseudonym']);
837
838 //Init applications
839 $this->context['session']['applications'] = [];
840 foreach($session['sa_id'] as $i => $sa_id) {
841 $this->context['session']['applications'][$sa_id] = [
842 'user' => null,
843 'score' => $session['sa_score'][$i],
844 'created' => $session['sa_created'][$i],
845 'updated' => $session['sa_updated'][$i],
846 'canceled' => $session['sa_canceled'][$i]
847 ];
848 if (!empty($session['sau_id'][$i])) {
849 $this->context['session']['applications'][$sa_id]['user'] = [
850 'id' => $session['sau_id'][$i],
851 'title' => $session['sau_pseudonym'][$i]
852 ];
853 }
854 }
855 }
856
857 //Compute period
858 $period = new \DatePeriod(
859 //Start from first monday of week
860 new \DateTime('Monday this week'),
861 //Iterate on each day
862 new \DateInterval('P1D'),
863 //End with next sunday and 4 weeks
864 new \DateTime(
865 $this->isGranted('IS_AUTHENTICATED_REMEMBERED')?'Monday this week + 3 week':'Monday this week + 2 week'
866 )
867 );
868
869 //Fetch locations
870 //XXX: we want to display all active locations anyway
871 $locations = $doctrine->getRepository(Location::class)->findTranslatedSortedByPeriod($this->translator, $period, $session['au_id']);
872
873 //Render the view
874 return $this->render('@RapsysAir/session/view.html.twig', ['locations' => $locations]+$this->context, $response);
875 }
876 }