]> Raphaël G. Git Repositories - airbundle/blob - Controller/DefaultController.php
Fix translation string
[airbundle] / Controller / DefaultController.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\Bridge\Twig\Mime\TemplatedEmail;
15 use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
16 use Symfony\Component\Filesystem\Filesystem;
17 use Symfony\Component\Form\FormError;
18 use Symfony\Component\HttpFoundation\Request;
19 use Symfony\Component\HttpFoundation\Response;
20 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
21 use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
22 use Symfony\Component\Mime\Address;
23 use Symfony\Component\Security\Core\Exception\AccessDeniedException;
24
25 use Rapsys\AirBundle\Entity\Dance;
26 use Rapsys\AirBundle\Entity\Location;
27 use Rapsys\AirBundle\Entity\Session;
28 use Rapsys\AirBundle\Entity\Snippet;
29 use Rapsys\AirBundle\Entity\User;
30 use Rapsys\AirBundle\Token\AnonymousToken;
31
32 /**
33 * {@inheritdoc}
34 */
35 class DefaultController extends AbstractController {
36 /**
37 * The about page
38 *
39 * Display the about informations
40 *
41 * @param Request $request The request instance
42 * @return Response The rendered view
43 */
44 public function about(Request $request): Response {
45 //Set page
46 $this->context['title']['page'] = $this->translator->trans('About');
47
48 //Set description
49 $this->context['description'] = $this->translator->trans('Libre Air about');
50
51 //Set keywords
52 $this->context['keywords'] = [
53 $this->translator->trans('about'),
54 $this->translator->trans('Libre Air')
55 ];
56
57 //Render template
58 $response = $this->render('@RapsysAir/default/about.html.twig', $this->context);
59 $response->setEtag(md5($response->getContent()));
60 $response->setPublic();
61 $response->isNotModified($request);
62
63 //Return response
64 return $response;
65 }
66
67 /**
68 * The contact page
69 *
70 * Send a contact mail to configured contact
71 *
72 * @param Request $request The request instance
73 *
74 * @return Response The rendered view or redirection
75 */
76 public function contact(Request $request): Response {
77 //Set page
78 $this->context['title']['page'] = $this->translator->trans('Contact');
79
80 //Set description
81 $this->context['description'] = $this->translator->trans('Contact Libre Air');
82
83 //Set keywords
84 $this->context['keywords'] = [
85 $this->translator->trans('contact'),
86 $this->translator->trans('Libre Air'),
87 $this->translator->trans('outdoor'),
88 $this->translator->trans('Argentine Tango'),
89 $this->translator->trans('calendar')
90 ];
91
92 //Set data
93 $data = [];
94
95 //With user
96 if ($user = $this->security->getUser()) {
97 //Set data
98 $data = [
99 'name' => $user->getRecipientName(),
100 'mail' => $user->getMail()
101 ];
102 }
103
104 //Create the form according to the FormType created previously.
105 //And give the proper parameters
106 $form = $this->factory->create('Rapsys\AirBundle\Form\ContactType', $data, [
107 'action' => $this->generateUrl('rapsysair_contact'),
108 'captcha' => true,
109 'method' => 'POST'
110 ]);
111
112 if ($request->isMethod('POST')) {
113 // Refill the fields in case the form is not valid.
114 $form->handleRequest($request);
115
116 if ($form->isSubmitted() && $form->isValid()) {
117 //Get data
118 $data = $form->getData();
119
120 //Create message
121 $message = (new TemplatedEmail())
122 //Set sender
123 ->from(new Address($data['mail'], $data['name']))
124 //Set recipient
125 ->to(new Address($this->context['contact']['address'], $this->context['contact']['name']))
126 //Set subject
127 ->subject($data['subject'])
128
129 //Set path to twig templates
130 ->htmlTemplate('@RapsysAir/mail/contact.html.twig')
131 ->textTemplate('@RapsysAir/mail/contact.text.twig')
132
133 //Set context
134 ->context(
135 [
136 'subject' => $data['subject'],
137 'message' => strip_tags($data['message']),
138 ]+$this->context
139 );
140
141 //Try sending message
142 //XXX: mail delivery may silently fail
143 try {
144 //Send message
145 $this->mailer->send($message);
146
147 //Redirect on the same route with sent=1 to cleanup form
148 return $this->redirectToRoute($request->attributes->get('_route'), ['sent' => 1]+$request->attributes->get('_route_params'));
149 //Catch obvious transport exception
150 } catch(TransportExceptionInterface $e) {
151 if ($message = $e->getMessage()) {
152 //Add error message mail unreachable
153 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to contact: %mail%: %message%', ['%mail%' => $this->context['contact']['address'], '%message%' => $this->translator->trans($message)])));
154 } else {
155 //Add error message mail unreachable
156 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to contact: %mail%', ['%mail%' => $this->context['contact']['address']])));
157 }
158 }
159 }
160 }
161
162 //Render template
163 return $this->render('@RapsysAir/form/contact.html.twig', ['form' => $form->createView(), 'sent' => $request->query->get('sent', 0)]+$this->context);
164 }
165
166 /**
167 * The index page
168 *
169 * Display session calendar
170 *
171 * @param Request $request The request instance
172 * @return Response The rendered view
173 */
174 public function index(Request $request): Response {
175 //Add cities
176 $this->context['cities'] = $this->doctrine->getRepository(Location::class)->findCitiesAsArray($this->period);
177
178 //Add calendar
179 $this->context['calendar'] = $this->doctrine->getRepository(Session::class)->findAllByPeriodAsCalendarArray($this->period, !$this->checker->isGranted('IS_AUTHENTICATED_REMEMBERED'));
180
181 //Add dances
182 $this->context['dances'] = $this->doctrine->getRepository(Dance::class)->findNamesAsArray();
183
184 //Set modified
185 $this->modified = max(array_map(function ($v) { return $v['modified']; }, array_merge($this->context['calendar'], $this->context['cities'], $this->context['dances'])));
186
187 //Create response
188 $response = new Response();
189
190 //With logged user
191 if ($this->checker->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
192 //Set last modified
193 $response->setLastModified(new \DateTime('-1 year'));
194
195 //Set as private
196 $response->setPrivate();
197 //Without logged user
198 } else {
199 //Set etag
200 //XXX: only for public to force revalidation by last modified
201 $response->setEtag(md5(serialize(array_merge($this->context['calendar'], $this->context['cities'], $this->context['dances']))));
202
203 //Set last modified
204 $response->setLastModified($this->modified);
205
206 //Set as public
207 $response->setPublic();
208
209 //Without role and modification
210 if ($response->isNotModified($request)) {
211 //Return 304 response
212 return $response;
213 }
214 }
215
216 //With cities
217 if (!empty($this->context['cities'])) {
218 //Set locations
219 $locations = [];
220
221 //Set coordinates
222 $coordinates = [];
223
224 //Iterate on each cities
225 foreach($this->context['cities'] as $city) {
226 //Iterate on each locations
227 foreach($city['locations'] as $location) {
228 //Add location
229 $locations[$location['id']] = $location;
230 //Add coordinates
231 $coordinates[] = [ $location['latitude'], $location['longitude'] ];
232 }
233 }
234
235 //Add multi
236 #TODO: add multimap.link here ???
237 //$this->context['multimap'] = $this->map->getMultiMap($this->translator->trans('Libre Air cities sector map'), $this->modified->getTimestamp(), $coordinates);
238 $this->context['multimap'] = $this->image->getMulti($coordinates) + ['caption' => $this->translator->trans('Libre Air cities sector map')];
239
240 //Set cities
241 $cities = array_map(function ($v) { return $v['in']; }, $this->context['cities']);
242
243 //Set dances
244 $dances = array_map(function ($v) { return $v['name']; }, $this->context['dances']);
245 } else {
246 //Set cities
247 $cities = [];
248
249 //Set dances
250 $dances = [];
251 }
252
253 //Set keywords
254 //TODO: use splice instead of that shit !!!
255 //TODO: handle smartly indoor and outdoor !!!
256 $this->context['keywords'] = array_values(
257 array_merge(
258 $dances,
259 $cities,
260 [
261 $this->translator->trans('indoor'),
262 $this->translator->trans('outdoor'),
263 $this->translator->trans('calendar'),
264 $this->translator->trans('Libre Air')
265 ]
266 )
267 );
268
269 //Get textual cities
270 $cities = implode($this->translator->trans(' and '), array_filter(array_merge([implode(', ', array_slice($cities, 0, -1))], array_slice($cities, -1)), 'strlen'));
271
272 //Get textual dances
273 $dances = implode($this->translator->trans(' and '), array_filter(array_merge([implode(', ', array_slice($dances, 0, -1))], array_slice($dances, -1)), 'strlen'));
274
275 //Set title
276 $this->context['title']['page'] = $this->translator->trans('%dances% %cities%', ['%dances%' => $dances, '%cities%' => $cities]);
277
278 //Set description
279 //TODO: handle french translation when city start with a A, change à in en !
280 $this->context['description'] = $this->translator->trans('%dances% indoor and outdoor calendar %cities%', ['%dances%' => $dances, '%cities%' => $cities]);
281
282 //Set facebook type
283 //XXX: only valid for home page
284 $this->context['facebook']['metas']['og:type'] = 'website';
285
286 //Render the view
287 return $this->render('@RapsysAir/default/index.html.twig', $this->context, $response);
288 }
289
290 /**
291 * The organizer regulation page
292 *
293 * Display the organizer regulation policy
294 *
295 * @param Request $request The request instance
296 * @return Response The rendered view
297 */
298 public function organizerRegulation(Request $request): Response {
299 //Set page
300 $this->context['title']['page'] = $this->translator->trans('Organizer regulation');
301
302 //Set description
303 $this->context['description'] = $this->translator->trans('Libre Air organizer regulation');
304
305 //Set keywords
306 $this->context['keywords'] = [
307 $this->translator->trans('organizer regulation'),
308 $this->translator->trans('Libre Air')
309 ];
310
311 //Render template
312 $response = $this->render('@RapsysAir/default/organizer_regulation.html.twig', $this->context);
313
314 //Set as cachable
315 $response->setEtag(md5($response->getContent()));
316 $response->setPublic();
317 $response->isNotModified($request);
318
319 //Return response
320 return $response;
321 }
322
323 /**
324 * The terms of service page
325 *
326 * Display the terms of service policy
327 *
328 * @param Request $request The request instance
329 * @return Response The rendered view
330 */
331 public function termsOfService(Request $request): Response {
332 //Set page
333 $this->context['title']['page'] = $this->translator->trans('Terms of service');
334
335 //Set description
336 $this->context['description'] = $this->translator->trans('Libre Air terms of service');
337
338 //Set keywords
339 $this->context['keywords'] = [
340 $this->translator->trans('terms of service'),
341 $this->translator->trans('Libre Air')
342 ];
343
344 //Render template
345 $response = $this->render('@RapsysAir/default/terms_of_service.html.twig', $this->context);
346
347 //Set as cachable
348 $response->setEtag(md5($response->getContent()));
349 $response->setPublic();
350 $response->isNotModified($request);
351
352 //Return response
353 return $response;
354 }
355
356 /**
357 * The frequently asked questions page
358 *
359 * Display the frequently asked questions
360 *
361 * @param Request $request The request instance
362 * @return Response The rendered view
363 */
364 public function frequentlyAskedQuestions(Request $request): Response {
365 //Set page
366 $this->context['title']['page'] = $this->translator->trans('Frequently asked questions');
367
368 //Set description
369 $this->context['description'] = $this->translator->trans('Libre Air frequently asked questions');
370
371 //Set keywords
372 $this->context['keywords'] = [
373 $this->translator->trans('frequently asked questions'),
374 $this->translator->trans('faq'),
375 $this->translator->trans('Libre Air')
376 ];
377
378 //Render template
379 $response = $this->render('@RapsysAir/default/frequently_asked_questions.html.twig', $this->context);
380
381 //Set as cachable
382 $response->setEtag(md5($response->getContent()));
383 $response->setPublic();
384 $response->isNotModified($request);
385
386 //Return response
387 return $response;
388 }
389
390 /**
391 * List all users
392 *
393 * Display all user with a group listed as users
394 *
395 * @param Request $request The request instance
396 *
397 * @return Response The rendered view
398 */
399 public function userIndex(Request $request): Response {
400 //With admin role
401 if ($this->checker->isGranted('ROLE_ADMIN')) {
402 //Set title
403 $this->context['title']['page'] = $this->translator->trans('Libre Air user list');
404
405 //Set section
406 $this->context['title']['section'] = $this->translator->trans('User');
407
408 //Set description
409 $this->context['description'] = $this->translator->trans('Lists Libre air users');
410 //Without admin role
411 } else {
412 //Set title
413 $this->context['title']['page'] = $this->translator->trans('Libre Air organizer list');
414
415 //Set section
416 $this->context['title']['section'] = $this->translator->trans('Organizer');
417
418 //Set description
419 $this->context['description'] = $this->translator->trans('Lists Libre air organizers');
420 }
421
422 //Set keywords
423 $this->context['keywords'] = [
424 $this->translator->trans('users'),
425 $this->translator->trans('user list'),
426 $this->translator->trans('listing'),
427 $this->translator->trans('Libre Air')
428 ];
429
430 //Fetch users
431 $users = $this->doctrine->getRepository(User::class)->findIndexByGroupId();
432
433 //With admin role
434 if ($this->checker->isGranted('ROLE_ADMIN')) {
435 //Display all users
436 $this->context['groups'] = $users;
437 //Without admin role
438 } else {
439 //Only display senior organizers
440 $this->context['users'] = $users[$this->translator->trans('Senior')];
441 }
442
443 //Render the view
444 return $this->render('@RapsysAir/user/index.html.twig', $this->context);
445 }
446
447 /**
448 * List all sessions for the user
449 *
450 * Display all sessions for the user with an application or login form
451 *
452 * @param Request $request The request instance
453 * @param int $id The user id
454 *
455 * @return Response The rendered view
456 */
457 public function userView(Request $request, int $id, ?string $user): Response {
458 //Get user
459 if (empty($this->context['user'] = $this->doctrine->getRepository(User::class)->findOneByIdAsArray($id, $this->locale))) {
460 //Throw not found
461 throw new NotFoundHttpException($this->translator->trans('Unable to find user: %id%', ['%id%' => $id]));
462 }
463
464 //Create token
465 $token = new AnonymousToken($this->context['user']['roles']);
466
467 //Prevent access when not admin, user is not guest and not currently logged user
468 if (!($isAdmin = $this->checker->isGranted('ROLE_ADMIN')) && !($isGuest = $this->decision->decide($token, ['ROLE_GUEST']))) {
469 //Throw access denied
470 throw new AccessDeniedException($this->translator->trans('Unable to access user: %id%', ['%id%' => $id]));
471 }
472
473 //With invalid user slug
474 if ($this->context['user']['slug'] !== $user) {
475 //Redirect to cleaned url
476 return $this->redirectToRoute('rapsysair_user_view', ['id' => $id, 'user' => $this->context['user']['slug']]);
477 }
478
479 //Fetch calendar
480 $this->context['calendar'] = $this->doctrine->getRepository(Session::class)->findAllByPeriodAsCalendarArray($this->period, !$this->checker->isGranted('IS_AUTHENTICATED_REMEMBERED'), null, null, $id);
481
482 //Get locations at less than 2 km
483 $this->context['locations'] = $this->doctrine->getRepository(Location::class)->findAllByUserIdAsArray($id, $this->period, 2);
484
485 //Set ats
486 $ats = [];
487
488 //Set dances
489 $dances = [];
490
491 //Set indoors
492 $indoors = [];
493
494 //Set ins
495 $ins = [];
496
497 //Set insides
498 $insides = [];
499
500 //Set locations
501 $locations = [];
502
503 //Set types
504 $types = [];
505
506 //Iterate on each calendar
507 foreach($this->context['calendar'] as $date => $calendar) {
508 //Iterate on each session
509 foreach($calendar['sessions'] as $sessionId => $session) {
510 //Add dance
511 $dances[$session['application']['dance']['name']] = $session['application']['dance']['name'];
512
513 //Add types
514 $types[$session['application']['dance']['type']] = lcfirst($session['application']['dance']['type']);
515
516 //Add indoors
517 $indoors[$session['location']['indoor']?'indoor':'outdoor'] = $this->translator->trans($session['location']['indoor']?'indoor':'outdoor');
518
519 //Add insides
520 $insides[$session['location']['indoor']?'inside':'outside'] = $this->translator->trans($session['location']['indoor']?'inside':'outside');
521
522 //Add ats
523 $ats[$session['location']['id']] = $session['location']['at'];
524
525 //Add ins
526 $ins[$session['location']['id']] = $session['location']['in'];
527
528 //Session with application user id
529 if (!empty($session['application']['user']['id']) && $session['application']['user']['id'] == $id) {
530 //Add location
531 $locations[$session['location']['id']] = $session['location'];
532 }
533 }
534 }
535
536 //Set modified
537 //XXX: dance modified is already computed inside calendar modified
538 $this->modified = max(array_merge([$this->context['user']['modified']], array_map(function ($v) { return $v['modified']; }, array_merge($this->context['calendar'], $this->context['locations']))));
539
540 //Create response
541 $response = new Response();
542
543 //With logged user
544 if ($this->checker->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
545 //Set last modified
546 $response->setLastModified(new \DateTime('-1 year'));
547
548 //Set as private
549 $response->setPrivate();
550 //Without logged user
551 } else {
552 //Set etag
553 //XXX: only for public to force revalidation by last modified
554 $response->setEtag(md5(serialize(array_merge($this->context['user'], $this->context['calendar'], $this->context['locations']))));
555
556 //Set last modified
557 $response->setLastModified($this->modified);
558
559 //Set as public
560 $response->setPublic();
561
562 //Without role and modification
563 if ($response->isNotModified($request)) {
564 //Return 304 response
565 return $response;
566 }
567 }
568
569 //With locations
570 if (!empty($this->context['locations'])) {
571 //Set coordinates
572 $coordinates = [];
573
574 //Iterate on each locations
575 foreach($this->context['locations'] as $location) {
576 //Add coordinates
577 $coordinates[] = [ $location['latitude'], $location['longitude'] ];
578 }
579
580 //Add multi map
581 #TODO: add multimap.link here ???
582 //$this->context['multimap'] = $this->map->getMultiMap($this->context['user']['multimap'], $this->modified->getTimestamp(), $this->context['locations']);
583 $this->context['multimap'] = $this->image->getMulti($coordinates) + ['caption' => $this->context['user']['multimap']];
584 }
585
586 //Set keywords
587 $this->context['keywords'] = [
588 $this->context['user']['pseudonym'],
589 $this->translator->trans('calendar'),
590 $this->translator->trans('Libre Air')
591 ];
592
593 //Set cities
594 $cities = array_unique(array_map(function ($v) { return $v['city']; }, $locations));
595
596 //Set titles
597 $titles = array_map(function ($v) { return $v['title']; }, $locations);
598
599 //Insert dances in keywords
600 array_splice($this->context['keywords'], 1, 0, array_merge($types, $dances, $indoors, $insides, $titles, $cities));
601
602 //Deduplicate ins
603 $ins = array_unique($ins);
604
605 //Get textual dances
606 $dances = implode($this->translator->trans(' and '), array_filter(array_merge([implode(', ', array_slice($dances, 0, -1))], array_slice($dances, -1)), 'strlen'));
607
608 //Get textual types
609 $types = implode($this->translator->trans(' and '), array_filter(array_merge([implode(', ', array_slice($types, 0, -1))], array_slice($types, -1)), 'strlen'));
610
611 //Get textual indoors
612 $indoors = implode($this->translator->trans(' and '), array_filter(array_merge([implode(', ', array_slice($indoors, 0, -1))], array_slice($indoors, -1)), 'strlen'));
613
614 //Get textual ats
615 $ats = implode($this->translator->trans(' and '), array_filter(array_merge([implode(', ', array_slice($ats, 0, -1))], array_slice($ats, -1)), 'strlen'));
616
617 //Get textual ins
618 $ins = implode($this->translator->trans(' and '), array_filter(array_merge([implode(', ', array_slice($ins, 0, -1))], array_slice($ins, -1)), 'strlen'));
619
620 //Set title
621 $this->context['title']['page'] = $this->translator->trans('%pseudonym% organizer', ['%pseudonym%' => $this->context['user']['pseudonym']]);
622
623 //Set section
624 $this->context['title']['section'] = $this->translator->trans('User');
625
626 //With locations
627 if (!empty($locations)) {
628 //Set description
629 $this->context['description'] = ucfirst($this->translator->trans('%dances% %types% %indoors% calendar %ats% %ins% %pseudonym%', ['%dances%' => $dances, '%types%' => $types, '%indoors%' => $indoors, '%ats%' => $ats, '%ins%' => $ins, '%pseudonym%' => $this->translator->trans('by %pseudonym%', ['%pseudonym%' => $this->context['user']['pseudonym']])]));
630 //Without locations
631 } else {
632 //Set description
633 $this->context['description'] = $this->translator->trans('%pseudonym% calendar', ['%pseudonym%' => $this->context['user']['pseudonym']]);
634 }
635
636 //Set user description
637 $this->context['locations_description'] = $this->translator->trans('Libre Air %pseudonym% location list', ['%pseudonym%' => $this->translator->trans('by %pseudonym%', ['%pseudonym%' => $this->context['user']['pseudonym']])]);
638
639 //Set alternates
640 $this->context['alternates'] += $this->context['user']['alternates'];
641
642 //Create snippet forms for role_guest
643 //TODO: optimize this call
644 if ($isAdmin || $isGuest && $this->security->getUser() && $this->context['user']['id'] == $this->security->getUser()->getId()) {
645 //Fetch all user snippet
646 $snippets = $this->doctrine->getRepository(Snippet::class)->findByUserIdLocaleIndexByLocationId($id, $this->locale);
647
648 //Get user
649 $user = $this->doctrine->getRepository(User::class)->findOneById($id);
650
651 //Iterate on locations
652 foreach($this->context['locations'] as $locationId => $location) {
653 //With existing snippet
654 if (isset($snippets[$location['id']])) {
655 //Set existing in current
656 $current = $snippets[$location['id']];
657 //Without existing snippet
658 } else {
659 //Init snippet
660 $current = new Snippet($this->locale, $this->doctrine->getRepository(Location::class)->findOneById($location['id']), $user);
661 }
662
663 //Create SnippetType form
664 $form = $this->factory->createNamed(
665 //Set form id
666 'snippet_'.$locationId.'_'.$id.'_'.$this->locale,
667 //Set form type
668 'Rapsys\AirBundle\Form\SnippetType',
669 //Set form data
670 $current
671 );
672
673 //Refill the fields in case of invalid form
674 $form->handleRequest($request);
675
676 //Handle submitted and valid form
677 //TODO: add a delete snippet ?
678 if ($form->isSubmitted() && $form->isValid()) {
679 //Get snippet
680 $snippet = $form->getData();
681
682 //Queue snippet save
683 $this->manager->persist($snippet);
684
685 //Flush to get the ids
686 $this->manager->flush();
687
688 //Add notice
689 $this->addFlash('notice', $this->translator->trans('Snippet for %user% %location% updated', ['%location%' => $location['at'], '%user%' => $this->context['user']['pseudonym']]));
690
691 //Redirect to cleaned url
692 return $this->redirectToRoute('rapsysair_user_view', ['id' => $id, 'user' => $this->context['user']['slug']]);
693 }
694
695 //Add form to context
696 $this->context['forms']['snippets'][$locationId] = $form->createView();
697
698 //With location user source image
699 if (($isFile = is_file($source = $this->config['path'].'/location/'.$location['id'].'/'.$id.'.png')) && ($mtime = stat($source)['mtime'])) {
700 //Set location image
701 $this->context['locations'][$locationId]['image'] = $this->image->getThumb($location['miniature'], $mtime, $source);
702 }
703
704 //Create ImageType form
705 $form = $this->factory->createNamed(
706 //Set form id
707 'image_'.$locationId.'_'.$id,
708 //Set form type
709 'Rapsys\AirBundle\Form\ImageType',
710 //Set form data
711 [
712 //Set location
713 'location' => $location['id'],
714 //Set user
715 'user' => $id
716 ],
717 //Set form attributes
718 [
719 //Enable delete with image
720 'delete' => isset($this->context['locations'][$locationId]['image'])
721 ]
722 );
723
724 //Refill the fields in case of invalid form
725 $form->handleRequest($request);
726
727 //Handle submitted and valid form
728 if ($form->isSubmitted() && $form->isValid()) {
729 //With delete
730 if ($form->has('delete') && $form->get('delete')->isClicked()) {
731 //With source and mtime
732 if ($isFile && !empty($source) && !empty($mtime)) {
733 //Clear thumb
734 $this->image->remove($mtime, $source);
735
736 //Unlink file
737 unlink($this->config['path'].'/location/'.$location['id'].'/'.$id.'.png');
738
739 //Add notice
740 $this->addFlash('notice', $this->translator->trans('Image for %user% %location% deleted', ['%location%' => $location['at'], '%user%' => $this->context['user']['pseudonym']]));
741
742 //Redirect to cleaned url
743 return $this->redirectToRoute('rapsysair_user_view', ['id' => $id, 'user' => $this->context['user']['slug']]);
744 }
745 }
746
747 //With image
748 if ($image = $form->get('image')->getData()) {
749 //Check source path
750 if (!is_dir($dir = dirname($source))) {
751 //Create filesystem object
752 $filesystem = new Filesystem();
753
754 try {
755 //Create dir
756 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
757 $filesystem->mkdir($dir, 0775);
758 } catch (IOExceptionInterface $e) {
759 //Throw error
760 throw new \Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
761 }
762 }
763
764 //Set source
765 $source = realpath($dir).'/'.basename($source);
766
767 //Create imagick object
768 $imagick = new \Imagick();
769
770 //Read image
771 $imagick->readImage($image->getRealPath());
772
773 //Save image
774 if (!$imagick->writeImage($source)) {
775 //Throw error
776 throw new \Exception(sprintf('Unable to write image "%s"', $source));
777 }
778
779 //Add notice
780 $this->addFlash('notice', $this->translator->trans('Image for %user% %location% updated', ['%location%' => $location['at'], '%user%' => $this->context['user']['pseudonym']]));
781
782 //Redirect to cleaned url
783 return $this->redirectToRoute('rapsysair_user_view', ['id' => $id, 'user' => $this->context['user']['slug']]);
784 }
785 }
786
787 //Add form to context
788 $this->context['forms']['images'][$locationId] = $form->createView();
789 }
790 }
791
792 //Render the view
793 return $this->render('@RapsysAir/user/view.html.twig', ['id' => $id]+$this->context);
794 }
795 }