]> Raphaƫl G. Git Repositories - airbundle/blob - Controller/DefaultController.php
Add security denied template
[airbundle] / Controller / DefaultController.php
1 <?php
2
3 namespace Rapsys\AirBundle\Controller;
4
5 use Rapsys\AirBundle\Entity\Application;
6 use Rapsys\AirBundle\Entity\Session;
7 use Symfony\Bridge\Twig\Mime\TemplatedEmail;
8 use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
9 use Symfony\Component\DependencyInjection\ContainerInterface;
10 use Symfony\Component\Form\FormError;
11 use Symfony\Component\HttpFoundation\Request;
12 use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
13 use Symfony\Component\Mailer\MailerInterface;
14 use Symfony\Component\Mime\NamedAddress;
15 use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
16 use Symfony\Component\Translation\TranslatorInterface;
17
18 class DefaultController extends AbstractController {
19 //Config array
20 protected $config;
21
22 //Translator instance
23 protected $translator;
24
25 public function __construct(ContainerInterface $container, TranslatorInterface $translator) {
26 //Retrieve config
27 $this->config = $container->getParameter($this->getAlias());
28
29 //Set the translator
30 $this->translator = $translator;
31 }
32
33 public function contact(Request $request, MailerInterface $mailer) {
34 //Set section
35 $section = $this->translator->trans('Contact');
36
37 //Set title
38 $title = $section.' - '.$this->translator->trans($this->config['site']['title']);
39
40 //Create the form according to the FormType created previously.
41 //And give the proper parameters
42 $form = $this->createForm('Rapsys\AirBundle\Form\ContactType', null, [
43 // To set the action use $this->generateUrl('route_identifier')
44 'action' => $this->generateUrl('rapsys_air_contact'),
45 'method' => 'POST'
46 ]);
47
48 if ($request->isMethod('POST')) {
49 // Refill the fields in case the form is not valid.
50 $form->handleRequest($request);
51
52 if ($form->isValid()) {
53 //Get data
54 $data = $form->getData();
55
56 //Create message
57 $message = (new TemplatedEmail())
58 //Set sender
59 ->from(new NamedAddress($data['mail'], $data['name']))
60 //Set recipient
61 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
62 ->to(new NamedAddress($this->config['contact']['mail'], $this->config['contact']['name']))
63 //Set subject
64 ->subject($data['subject'])
65
66 //Set path to twig templates
67 ->htmlTemplate('@RapsysAir/mail/contact.html.twig')
68 ->textTemplate('@RapsysAir/mail/contact.text.twig')
69
70 //Set context
71 ->context(
72 [
73 'site_logo' => $this->config['site']['logo'],
74 'site_title' => $this->config['site']['title'],
75 'site_url' => $this->get('router')->generate('rapsys_air_homepage', [], UrlGeneratorInterface::ABSOLUTE_URL),
76 'copy_long' => $this->config['copy']['long'],
77 'copy_short' => $this->config['copy']['short'],
78 'subject' => $data['subject'],
79 'message' => strip_tags($data['message']),
80 ]
81 );
82
83 //Try sending message
84 //XXX: mail delivery may silently fail
85 try {
86 //Send message
87 $mailer->send($message);
88
89 //Redirect on the same route with sent=1 to cleanup form
90 return $this->redirectToRoute($request->get('_route'), ['sent' => 1]+$request->get('_route_params'));
91 //Catch obvious transport exception
92 } catch(TransportExceptionInterface $e) {
93 if ($message = $e->getMessage()) {
94 //Add error message mail unreachable
95 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to contact: %mail%: %message%', ['%mail%' => $this->config['contact']['mail'], '%message%' => $this->translator->trans($message)])));
96 } else {
97 //Add error message mail unreachable
98 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to contact: %mail%', ['%mail%' => $this->config['contact']['mail']])));
99 }
100 }
101 }
102 }
103
104 //Render template
105 return $this->render('@RapsysAir/form/contact.html.twig', ['title' => $title, 'section' => $section, 'form' => $form->createView(), 'sent' => $request->query->get('sent', 0)]);
106 }
107
108 public function index() {
109 //Set section
110 $section = $this->translator->trans('Index');
111
112 //Set title
113 $title = $section.' - '.$this->translator->trans($this->config['site']['title']);
114
115 //Render template
116 return $this->render('@RapsysAir/page/index.html.twig', ['title' => $title, 'section' => $section]);
117 }
118
119 public function admin(Request $request) {
120 //Prevent non-admin to access here
121 $this->denyAccessUnlessGranted('ROLE_GUEST', null, 'Unable to access this page without ROLE_GUEST!');
122
123 //Set section
124 $section = $this->translator->trans('Admin');
125
126 //Set title
127 $title = $section.' - '.$this->translator->trans($this->config['site']['title']);
128
129 header('Content-Type: text/plain');
130 var_dump('TODO');
131 exit;
132 //Create the form according to the FormType created previously.
133 //And give the proper parameters
134 $form = $this->createForm('Rapsys\AirBundle\Form\ApplicationType', null, [
135 // To set the action use $this->generateUrl('route_identifier')
136 'action' => $this->generateUrl('rapsys_air_admin'),
137 'method' => 'POST',
138 'attr' => [ 'class' => 'form_col' ]
139 ]);
140
141 //Get doctrine
142 $doctrine = $this->getDoctrine();
143
144 //Handle request
145 if ($request->isMethod('POST')) {
146 // Refill the fields in case the form is not valid.
147 $form->handleRequest($request);
148
149 if ($form->isValid()) {
150 //Get data
151 $data = $form->getData();
152
153 //Get manager
154 $manager = $doctrine->getManager();
155
156 //Protect session fetching
157 try {
158 $session = $doctrine->getRepository(Session::class)->findOneByLocationSlotDate($data['location'], $data['slot'], $data['date']);
159 //Catch no session case
160 } catch (\Doctrine\ORM\NoResultException $e) {
161 //Create the session
162 $session = new Session();
163 $session->setLocation($data['location']);
164 $session->setSlot($data['slot']);
165 $session->setDate($data['date']);
166 $session->setCreated(new \DateTime('now'));
167 $session->setUpdated(new \DateTime('now'));
168 $manager->persist($session);
169 //Flush to get the ids
170 #$manager->flush();
171 }
172
173 //Init application
174 $application = false;
175
176 //Protect application fetching
177 try {
178 //TODO: handle admin case where we provide a user in extra
179 $application = $doctrine->getRepository(Application::class)->findOneBySessionUser($session, $this->getUser());
180
181 //Add error message to mail field
182 $form->get('slot')->addError(new FormError($this->translator->trans('Application already exists')));
183 //Catch no application cases
184 //XXX: combine these catch when php 7.1 is available
185 } catch (\Doctrine\ORM\NoResultException $e) {
186 //Catch invalid argument because session is not already persisted
187 } catch(\Doctrine\ORM\ORMInvalidArgumentException $e) {
188 }
189
190 //Create new application if none found
191 if (!$application) {
192 //Create the application
193 $application = new Application();
194 $application->setSession($session);
195 //TODO: handle admin case where we provide a user in extra
196 $application->setUser($this->getUser());
197 $application->setCreated(new \DateTime('now'));
198 $application->setUpdated(new \DateTime('now'));
199 $manager->persist($application);
200
201 //Flush to get the ids
202 $manager->flush();
203
204 //Add notice in flash message
205 $this->addFlash('notice', $this->translator->trans('Application request the %date% for %location% on the slot %slot% saved', ['%location%' => $data['location']->getTitle(), '%slot%' => $data['slot']->getTitle(), '%date%' => $data['date']->format('Y-m-d')]));
206
207 //Redirect to cleanup the form
208 return $this->redirectToRoute('rapsys_air_admin');
209 }
210 }
211 }
212
213 //Compute period
214 $period = new \DatePeriod(
215 //Start from first monday of week
216 new \DateTime('Monday this week'),
217 //Iterate on each day
218 new \DateInterval('P1D'),
219 //End with next sunday and 4 weeks
220 new \DateTime('Monday this week + 5 week')
221 );
222
223 //Fetch sessions
224 $sessions = $doctrine->getRepository(Session::class)->findByDatePeriod($period);
225
226 //Init calendar
227 $calendar = [];
228
229 //Init month
230 $month = null;
231
232 //Iterate on each day
233 foreach($period as $date) {
234 //Init day in calendar
235 $calendar[$Ymd = $date->format('Ymd')] = [
236 'title' => $date->format('d'),
237 'class' => [],
238 'sessions' => []
239 ];
240 //Append month for first day of month
241 if ($month != $date->format('m')) {
242 $month = $date->format('m');
243 $calendar[$Ymd]['title'] .= '/'.$month;
244 }
245 //Deal with today
246 if ($date->format('U') == ($today = strtotime('today'))) {
247 $calendar[$Ymd]['title'] .= '/'.$month;
248 $calendar[$Ymd]['current'] = true;
249 $calendar[$Ymd]['class'][] = 'current';
250 }
251 //Disable passed days
252 if ($date->format('U') < $today) {
253 $calendar[$Ymd]['disabled'] = true;
254 $calendar[$Ymd]['class'][] = 'disabled';
255 }
256 //Set next month days
257 if ($date->format('m') > date('m')) {
258 $calendar[$Ymd]['next'] = true;
259 $calendar[$Ymd]['class'][] = 'next';
260 }
261 //Iterate on each session to find the one of the day
262 foreach($sessions as $session) {
263 if (($sessionYmd = $session->getDate()->format('Ymd')) == $Ymd) {
264 //Count number of application
265 $count = count($session->getApplications());
266
267 //Compute classes
268 $class = [];
269 if ($session->getApplication()) {
270 $class[] = 'granted';
271 } elseif ($count == 0) {
272 $class[] = 'orphaned';
273 } elseif ($count > 1) {
274 $class[] = 'disputed';
275 } else {
276 $class[] = 'pending';
277 }
278
279 //Add the session
280 $calendar[$Ymd]['sessions'][$session->getSlot()->getId().$session->getLocation()->getId()] = [
281 'id' => $session->getId(),
282 'title' => ($count > 1?'['.$count.'] ':'').$session->getSlot()->getTitle().' '.$session->getLocation()->getTitle(),
283 'class' => $class
284 ];
285 }
286 }
287
288 //Sort sessions
289 ksort($calendar[$Ymd]['sessions']);
290 }
291
292 return $this->render('@RapsysAir/admin/index.html.twig', ['title' => $title, 'section' => $section, 'form' => $form->createView(), 'calendar' => $calendar]);
293 }
294
295 public function session(Request $request, $id) {
296 /*header('Content-Type: text/plain');
297 var_dump($calendar);
298 exit;*/
299
300 //Set section
301 $section = $this->translator->trans('Session %id%', ['%id%' => $id]);
302
303 //Set title
304 $title = $section.' - '.$this->translator->trans($this->config['site']['title']);
305
306 //Create the form according to the FormType created previously.
307 //And give the proper parameters
308 /*$form = $this->createForm('Rapsys\AirBundle\Form\ApplicationType', null, [
309 // To set the action use $this->generateUrl('route_identifier')
310 'action' => $this->generateUrl('rapsys_air_admin'),
311 'method' => 'POST',
312 'attr' => [ 'class' => 'form_col' ]
313 ]);*/
314
315 //Get doctrine
316 $doctrine = $this->getDoctrine();
317
318 //Fetch session
319 $session = $doctrine->getRepository(Session::class)->findOneById($id);
320
321 return $this->render('@RapsysAir/admin/session.html.twig', ['title' => $title, 'section' => $section, /*'form' => $form->createView(),*/ 'session' => $session]);
322 }
323
324 /**
325 * {@inheritdoc}
326 */
327 public function getAlias() {
328 return 'rapsys_air';
329 }
330 }