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