]> Raphaël G. Git Repositories - airbundle/blob - Controller/DefaultController.php
Fix map coordinates
[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->get('_route'), ['sent' => 1]+$request->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 $this->context['multimap'] = $this->image->getMulti($coordinates);
237 #$this->translator->trans('Libre Air cities sector map'), $this->modified->getTimestamp(), $locations
238
239 //Set cities
240 $cities = array_map(function ($v) { return $v['in']; }, $this->context['cities']);
241
242 //Set dances
243 $dances = array_map(function ($v) { return $v['name']; }, $this->context['dances']);
244 } else {
245 //Set cities
246 $cities = [];
247
248 //Set dances
249 $dances = [];
250 }
251
252 //Set keywords
253 //TODO: use splice instead of that shit !!!
254 //TODO: handle smartly indoor and outdoor !!!
255 $this->context['keywords'] = array_values(
256 array_merge(
257 $dances,
258 $cities,
259 [
260 $this->translator->trans('indoor'),
261 $this->translator->trans('outdoor'),
262 $this->translator->trans('calendar'),
263 $this->translator->trans('Libre Air')
264 ]
265 )
266 );
267
268 //Get textual cities
269 $cities = implode($this->translator->trans(' and '), array_filter(array_merge([implode(', ', array_slice($cities, 0, -1))], array_slice($cities, -1)), 'strlen'));
270
271 //Get textual dances
272 $dances = implode($this->translator->trans(' and '), array_filter(array_merge([implode(', ', array_slice($dances, 0, -1))], array_slice($dances, -1)), 'strlen'));
273
274 //Set title
275 $this->context['title']['page'] = $this->translator->trans('%dances% %cities%', ['%dances%' => $dances, '%cities%' => $cities]);
276
277 //Set description
278 //TODO: handle french translation when city start with a A, change à in en !
279 $this->context['description'] = $this->translator->trans('%dances% indoor and outdoor calendar %cities%', ['%dances%' => $dances, '%cities%' => $cities]);
280
281 //Set facebook type
282 //XXX: only valid for home page
283 $this->context['facebook']['metas']['og:type'] = 'website';
284
285 //Render the view
286 return $this->render('@RapsysAir/default/index.html.twig', $this->context, $response);
287 }
288
289 /**
290 * The organizer regulation page
291 *
292 * Display the organizer regulation policy
293 *
294 * @param Request $request The request instance
295 * @return Response The rendered view
296 */
297 public function organizerRegulation(Request $request): Response {
298 //Set page
299 $this->context['title']['page'] = $this->translator->trans('Organizer regulation');
300
301 //Set description
302 $this->context['description'] = $this->translator->trans('Libre Air organizer regulation');
303
304 //Set keywords
305 $this->context['keywords'] = [
306 $this->translator->trans('organizer regulation'),
307 $this->translator->trans('Libre Air')
308 ];
309
310 //Render template
311 $response = $this->render('@RapsysAir/default/organizer_regulation.html.twig', $this->context);
312
313 //Set as cachable
314 $response->setEtag(md5($response->getContent()));
315 $response->setPublic();
316 $response->isNotModified($request);
317
318 //Return response
319 return $response;
320 }
321
322 /**
323 * The terms of service page
324 *
325 * Display the terms of service policy
326 *
327 * @param Request $request The request instance
328 * @return Response The rendered view
329 */
330 public function termsOfService(Request $request): Response {
331 //Set page
332 $this->context['title']['page'] = $this->translator->trans('Terms of service');
333
334 //Set description
335 $this->context['description'] = $this->translator->trans('Libre Air terms of service');
336
337 //Set keywords
338 $this->context['keywords'] = [
339 $this->translator->trans('terms of service'),
340 $this->translator->trans('Libre Air')
341 ];
342
343 //Render template
344 $response = $this->render('@RapsysAir/default/terms_of_service.html.twig', $this->context);
345
346 //Set as cachable
347 $response->setEtag(md5($response->getContent()));
348 $response->setPublic();
349 $response->isNotModified($request);
350
351 //Return response
352 return $response;
353 }
354
355 /**
356 * The frequently asked questions page
357 *
358 * Display the frequently asked questions
359 *
360 * @param Request $request The request instance
361 * @return Response The rendered view
362 */
363 public function frequentlyAskedQuestions(Request $request): Response {
364 //Set page
365 $this->context['title']['page'] = $this->translator->trans('Frequently asked questions');
366
367 //Set description
368 $this->context['description'] = $this->translator->trans('Libre Air frequently asked questions');
369
370 //Set keywords
371 $this->context['keywords'] = [
372 $this->translator->trans('frequently asked questions'),
373 $this->translator->trans('faq'),
374 $this->translator->trans('Libre Air')
375 ];
376
377 //Render template
378 $response = $this->render('@RapsysAir/default/frequently_asked_questions.html.twig', $this->context);
379
380 //Set as cachable
381 $response->setEtag(md5($response->getContent()));
382 $response->setPublic();
383 $response->isNotModified($request);
384
385 //Return response
386 return $response;
387 }
388
389 /**
390 * List all users
391 *
392 * Display all user with a group listed as users
393 *
394 * @param Request $request The request instance
395 *
396 * @return Response The rendered view
397 */
398 public function userIndex(Request $request): Response {
399 //With admin role
400 if ($this->checker->isGranted('ROLE_ADMIN')) {
401 //Set title
402 $this->context['title']['page'] = $this->translator->trans('Libre Air user list');
403
404 //Set section
405 $this->context['title']['section'] = $this->translator->trans('User');
406
407 //Set description
408 $this->context['description'] = $this->translator->trans('Lists Libre air users');
409 //Without admin role
410 } else {
411 //Set title
412 $this->context['title']['page'] = $this->translator->trans('Libre Air organizer list');
413
414 //Set section
415 $this->context['title']['section'] = $this->translator->trans('Organizer');
416
417 //Set description
418 $this->context['description'] = $this->translator->trans('Lists Libre air organizers');
419 }
420
421 //Set keywords
422 $this->context['keywords'] = [
423 $this->translator->trans('users'),
424 $this->translator->trans('user list'),
425 $this->translator->trans('listing'),
426 $this->translator->trans('Libre Air')
427 ];
428
429 //Fetch users
430 $users = $this->doctrine->getRepository(User::class)->findIndexByGroupId();
431
432 //With admin role
433 if ($this->checker->isGranted('ROLE_ADMIN')) {
434 //Display all users
435 $this->context['groups'] = $users;
436 //Without admin role
437 } else {
438 //Only display senior organizers
439 $this->context['users'] = $users[$this->translator->trans('Senior')];
440 }
441
442 //Render the view
443 return $this->render('@RapsysAir/user/index.html.twig', $this->context);
444 }
445
446 /**
447 * List all sessions for the user
448 *
449 * Display all sessions for the user with an application or login form
450 *
451 * @param Request $request The request instance
452 * @param int $id The user id
453 *
454 * @return Response The rendered view
455 */
456 public function userView(Request $request, int $id, ?string $user): Response {
457 //Get user
458 if (empty($this->context['user'] = $this->doctrine->getRepository(User::class)->findOneByIdAsArray($id, $this->locale))) {
459 //Throw not found
460 throw new NotFoundHttpException($this->translator->trans('Unable to find user: %id%', ['%id%' => $id]));
461 }
462
463 //Create token
464 $token = new AnonymousToken($this->context['user']['roles']);
465
466 //Prevent access when not admin, user is not guest and not currently logged user
467 if (!($isAdmin = $this->checker->isGranted('ROLE_ADMIN')) && !($isGuest = $this->decision->decide($token, ['ROLE_GUEST']))) {
468 //Throw access denied
469 throw new AccessDeniedException($this->translator->trans('Unable to access user: %id%', ['%id%' => $id]));
470 }
471
472 //With invalid user slug
473 if ($this->context['user']['slug'] !== $user) {
474 //Redirect to cleaned url
475 return $this->redirectToRoute('rapsysair_user_view', ['id' => $id, 'user' => $this->context['user']['slug']]);
476 }
477
478 //Fetch calendar
479 $this->context['calendar'] = $this->doctrine->getRepository(Session::class)->findAllByPeriodAsCalendarArray($this->period, !$this->checker->isGranted('IS_AUTHENTICATED_REMEMBERED'), null, null, $id);
480
481 //Get locations at less than 2 km
482 $this->context['locations'] = $this->doctrine->getRepository(Location::class)->findAllByUserIdAsArray($id, $this->period, 2);
483
484 //Set ats
485 $ats = [];
486
487 //Set dances
488 $dances = [];
489
490 //Set indoors
491 $indoors = [];
492
493 //Set ins
494 $ins = [];
495
496 //Set insides
497 $insides = [];
498
499 //Set locations
500 $locations = [];
501
502 //Set types
503 $types = [];
504
505 //Iterate on each calendar
506 foreach($this->context['calendar'] as $date => $calendar) {
507 //Iterate on each session
508 foreach($calendar['sessions'] as $sessionId => $session) {
509 //Add dance
510 $dances[$session['application']['dance']['name']] = $session['application']['dance']['name'];
511
512 //Add types
513 $types[$session['application']['dance']['type']] = lcfirst($session['application']['dance']['type']);
514
515 //Add indoors
516 $indoors[$session['location']['indoor']?'indoor':'outdoor'] = $this->translator->trans($session['location']['indoor']?'indoor':'outdoor');
517
518 //Add insides
519 $insides[$session['location']['indoor']?'inside':'outside'] = $this->translator->trans($session['location']['indoor']?'inside':'outside');
520
521 //Add ats
522 $ats[$session['location']['id']] = $session['location']['at'];
523
524 //Add ins
525 $ins[$session['location']['id']] = $session['location']['in'];
526
527 //Session with application user id
528 if (!empty($session['application']['user']['id']) && $session['application']['user']['id'] == $id) {
529 //Add location
530 $locations[$session['location']['id']] = $session['location'];
531 }
532 }
533 }
534
535 //Set modified
536 //XXX: dance modified is already computed inside calendar modified
537 $this->modified = max(array_merge([$this->context['user']['modified']], array_map(function ($v) { return $v['modified']; }, array_merge($this->context['calendar'], $this->context['locations']))));
538
539 //Create response
540 $response = new Response();
541
542 //With logged user
543 if ($this->checker->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
544 //Set last modified
545 $response->setLastModified(new \DateTime('-1 year'));
546
547 //Set as private
548 $response->setPrivate();
549 //Without logged user
550 } else {
551 //Set etag
552 //XXX: only for public to force revalidation by last modified
553 $response->setEtag(md5(serialize(array_merge($this->context['user'], $this->context['calendar'], $this->context['locations']))));
554
555 //Set last modified
556 $response->setLastModified($this->modified);
557
558 //Set as public
559 $response->setPublic();
560
561 //Without role and modification
562 if ($response->isNotModified($request)) {
563 //Return 304 response
564 return $response;
565 }
566 }
567
568 //Add multi map
569 $this->context['multimap'] = $this->map->getMultiMap($this->context['user']['multimap'], $this->modified->getTimestamp(), $this->context['locations']);
570
571 //Set keywords
572 $this->context['keywords'] = [
573 $this->context['user']['pseudonym'],
574 $this->translator->trans('calendar'),
575 $this->translator->trans('Libre Air')
576 ];
577
578 //Set cities
579 $cities = array_unique(array_map(function ($v) { return $v['city']; }, $locations));
580
581 //Set titles
582 $titles = array_map(function ($v) { return $v['title']; }, $locations);
583
584 //Insert dances in keywords
585 array_splice($this->context['keywords'], 1, 0, array_merge($types, $dances, $indoors, $insides, $titles, $cities));
586
587 //Deduplicate ins
588 $ins = array_unique($ins);
589
590 //Get textual dances
591 $dances = implode($this->translator->trans(' and '), array_filter(array_merge([implode(', ', array_slice($dances, 0, -1))], array_slice($dances, -1)), 'strlen'));
592
593 //Get textual types
594 $types = implode($this->translator->trans(' and '), array_filter(array_merge([implode(', ', array_slice($types, 0, -1))], array_slice($types, -1)), 'strlen'));
595
596 //Get textual indoors
597 $indoors = implode($this->translator->trans(' and '), array_filter(array_merge([implode(', ', array_slice($indoors, 0, -1))], array_slice($indoors, -1)), 'strlen'));
598
599 //Get textual ats
600 $ats = implode($this->translator->trans(' and '), array_filter(array_merge([implode(', ', array_slice($ats, 0, -1))], array_slice($ats, -1)), 'strlen'));
601
602 //Get textual ins
603 $ins = implode($this->translator->trans(' and '), array_filter(array_merge([implode(', ', array_slice($ins, 0, -1))], array_slice($ins, -1)), 'strlen'));
604
605 //Set title
606 $this->context['title']['page'] = $this->translator->trans('%pseudonym% organizer', ['%pseudonym%' => $this->context['user']['pseudonym']]);
607
608 //Set section
609 $this->context['title']['section'] = $this->translator->trans('User');
610
611 //With locations
612 if (!empty($locations)) {
613 //Set description
614 $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']])]));
615 //Without locations
616 } else {
617 //Set description
618 $this->context['description'] = $this->translator->trans('%pseudonym% calendar', ['%pseudonym%' => $this->context['user']['pseudonym']]);
619 }
620
621 //Set user description
622 $this->context['locations_description'] = $this->translator->trans('Libre Air %pseudonym% location list', ['%pseudonym%' => $this->translator->trans('by %pseudonym%', ['%pseudonym%' => $this->context['user']['pseudonym']])]);
623
624 //Set alternates
625 $this->context['alternates'] += $this->context['user']['alternates'];
626
627 //Create snippet forms for role_guest
628 //TODO: optimize this call
629 if ($isAdmin || $isGuest && $this->security->getUser() && $this->context['user']['id'] == $this->security->getUser()->getId()) {
630 //Fetch all user snippet
631 $snippets = $this->doctrine->getRepository(Snippet::class)->findByUserIdLocaleIndexByLocationId($id, $this->locale);
632
633 //Get user
634 $user = $this->doctrine->getRepository(User::class)->findOneById($id);
635
636 //Iterate on locations
637 foreach($this->context['locations'] as $locationId => $location) {
638 //With existing snippet
639 if (isset($snippets[$location['id']])) {
640 //Set existing in current
641 $current = $snippets[$location['id']];
642 //Without existing snippet
643 } else {
644 //Init snippet
645 $current = new Snippet($this->locale, $this->doctrine->getRepository(Location::class)->findOneById($location['id']), $user);
646 }
647
648 //Create SnippetType form
649 $form = $this->factory->createNamed(
650 //Set form id
651 'snippet_'.$locationId.'_'.$id.'_'.$this->locale,
652 //Set form type
653 'Rapsys\AirBundle\Form\SnippetType',
654 //Set form data
655 $current
656 );
657
658 //Refill the fields in case of invalid form
659 $form->handleRequest($request);
660
661 //Handle submitted and valid form
662 //TODO: add a delete snippet ?
663 if ($form->isSubmitted() && $form->isValid()) {
664 //Get snippet
665 $snippet = $form->getData();
666
667 //Queue snippet save
668 $this->manager->persist($snippet);
669
670 //Flush to get the ids
671 $this->manager->flush();
672
673 //Add notice
674 $this->addFlash('notice', $this->translator->trans('Snippet for %user% %location% updated', ['%location%' => $location['at'], '%user%' => $this->context['user']['pseudonym']]));
675
676 //Redirect to cleaned url
677 return $this->redirectToRoute('rapsysair_user_view', ['id' => $id, 'user' => $this->context['user']['slug']]);
678 }
679
680 //Add form to context
681 $this->context['forms']['snippets'][$locationId] = $form->createView();
682
683 //With location user source image
684 if (($isFile = is_file($source = $this->config['path'].'/location/'.$location['id'].'/'.$id.'.png')) && ($mtime = stat($source)['mtime'])) {
685 //Set location image
686 $this->context['locations'][$locationId]['image'] = $this->image->getThumb($location['miniature'], $mtime, $source);
687 }
688
689 //Create ImageType form
690 $form = $this->factory->createNamed(
691 //Set form id
692 'image_'.$locationId.'_'.$id,
693 //Set form type
694 'Rapsys\AirBundle\Form\ImageType',
695 //Set form data
696 [
697 //Set location
698 'location' => $location['id'],
699 //Set user
700 'user' => $id
701 ],
702 //Set form attributes
703 [
704 //Enable delete with image
705 'delete' => isset($this->context['locations'][$locationId]['image'])
706 ]
707 );
708
709 //Refill the fields in case of invalid form
710 $form->handleRequest($request);
711
712 //Handle submitted and valid form
713 if ($form->isSubmitted() && $form->isValid()) {
714 //With delete
715 if ($form->has('delete') && $form->get('delete')->isClicked()) {
716 //With source and mtime
717 if ($isFile && !empty($source) && !empty($mtime)) {
718 //Clear thumb
719 $this->image->remove($mtime, $source);
720
721 //Unlink file
722 unlink($this->config['path'].'/location/'.$location['id'].'/'.$id.'.png');
723
724 //Add notice
725 $this->addFlash('notice', $this->translator->trans('Image for %user% %location% deleted', ['%location%' => $location['at'], '%user%' => $this->context['user']['pseudonym']]));
726
727 //Redirect to cleaned url
728 return $this->redirectToRoute('rapsysair_user_view', ['id' => $id, 'user' => $this->context['user']['slug']]);
729 }
730 }
731
732 //With image
733 if ($image = $form->get('image')->getData()) {
734 //Check source path
735 if (!is_dir($dir = dirname($source))) {
736 //Create filesystem object
737 $filesystem = new Filesystem();
738
739 try {
740 //Create dir
741 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
742 $filesystem->mkdir($dir, 0775);
743 } catch (IOExceptionInterface $e) {
744 //Throw error
745 throw new \Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
746 }
747 }
748
749 //Set source
750 $source = realpath($dir).'/'.basename($source);
751
752 //Create imagick object
753 $imagick = new \Imagick();
754
755 //Read image
756 $imagick->readImage($image->getRealPath());
757
758 //Save image
759 if (!$imagick->writeImage($source)) {
760 //Throw error
761 throw new \Exception(sprintf('Unable to write image "%s"', $source));
762 }
763
764 //Add notice
765 $this->addFlash('notice', $this->translator->trans('Image for %user% %location% updated', ['%location%' => $location['at'], '%user%' => $this->context['user']['pseudonym']]));
766
767 //Redirect to cleaned url
768 return $this->redirectToRoute('rapsysair_user_view', ['id' => $id, 'user' => $this->context['user']['slug']]);
769 }
770 }
771
772 //Add form to context
773 $this->context['forms']['images'][$locationId] = $form->createView();
774 }
775 }
776
777 //Render the view
778 return $this->render('@RapsysAir/user/view.html.twig', ['id' => $id]+$this->context);
779 }
780 }