]> Raphaël G. Git Repositories - userbundle/blob - Controller/UserController.php
Add context user informations logged as emergency
[userbundle] / Controller / UserController.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys UserBundle 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\UserBundle\Controller;
13
14 use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
15
16 use Symfony\Bridge\Twig\Mime\TemplatedEmail;
17 use Symfony\Component\Form\FormError;
18 use Symfony\Component\HttpFoundation\Request;
19 use Symfony\Component\HttpFoundation\Response;
20 use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
21 use Symfony\Component\HttpKernel\Exception\GoneHttpException;
22 use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
23 use Symfony\Component\Mime\Address;
24 use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
25 use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
26
27 /**
28 * {@inheritdoc}
29 */
30 class UserController extends AbstractController {
31 /**
32 * User index
33 *
34 * @param Request $request The request
35 * @return Response The response
36 */
37 public function index(Request $request): Response {
38 //Without admin
39 if (!$this->checker->isGranted('ROLE_'.strtoupper($this->config['default']['admin']))) {
40 //Throw 403
41 throw $this->createAccessDeniedException($this->translator->trans('Unable to list users', [], $this->alias));
42 }
43
44 //Get count
45 $this->context['count'] = $this->doctrine->getRepository($this->config['class']['user'])->findCountAsInt();
46
47 //With not enough users
48 if ($this->context['count'] - $this->page * $this->limit < 0) {
49 //Throw 404
50 throw $this->createNotFoundException($this->translator->trans('Unable to find users', [], $this->alias));
51 }
52
53 //Get users by groups
54 $this->context['groups'] = $this->doctrine->getRepository($this->config['class']['user'])->findIndexByGroupId($this->page, $this->limit);
55
56 //Render view
57 return $this->render(
58 //Template
59 $this->config['index']['view']['name'],
60 //Context
61 $this->context+$this->config['index']['view']['context']
62 );
63 }
64
65 /**
66 * Confirm account from mail link
67 *
68 * @param Request $request The request
69 * @param string $hash The hashed password
70 * @param string $mail The shorted mail address
71 * @return Response The response
72 */
73 public function confirm(Request $request, string $hash, string $mail): Response {
74 //With invalid hash
75 if ($hash != $this->slugger->hash($mail)) {
76 //Throw bad request
77 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash], $this->alias));
78 }
79
80 //Get mail
81 $mail = $this->slugger->unshort($smail = $mail);
82
83 //Without valid mail
84 if (filter_var($mail, FILTER_VALIDATE_EMAIL) === false) {
85 //Throw bad request
86 //XXX: prevent slugger reverse engineering by not displaying decoded mail
87 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail], $this->alias));
88 }
89
90 //Without existing registrant
91 if (!($user = $this->doctrine->getRepository($this->config['class']['user'])->findOneByMail($mail))) {
92 //Add error message mail already exists
93 //XXX: prevent slugger reverse engineering by not displaying decoded mail
94 $this->addFlash('error', $this->translator->trans('The account do not exists', [], $this->alias));
95
96 //Redirect to register view
97 return $this->redirectToRoute($this->config['route']['register']['name'], $this->config['route']['register']['context']);
98 }
99
100 //Set active
101 $user->setActive(true);
102
103 //Persist user
104 $this->manager->persist($user);
105
106 //Send to database
107 $this->manager->flush();
108
109 //Add error message mail already exists
110 $this->addFlash('notice', $this->translator->trans('Your account has been activated', [], $this->alias));
111
112 //Redirect to user view
113 return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $this->slugger->hash($smail)]+$this->config['route']['edit']['context']);
114 }
115
116 /**
117 * Edit account by shorted mail
118 *
119 * @param Request $request The request
120 * @param string $hash The hashed password
121 * @param string $mail The shorted mail address
122 * @return Response The response
123 */
124 public function edit(Request $request, string $hash, string $mail): Response {
125 //With invalid hash
126 if ($hash != $this->slugger->hash($mail)) {
127 //Throw bad request
128 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash], $this->alias));
129 }
130
131 //Get mail
132 $mail = $this->slugger->unshort($smail = $mail);
133
134 //With existing subscriber
135 if (empty($user = $this->doctrine->getRepository($this->config['class']['user'])->findOneByMail($mail))) {
136 //Throw not found
137 //XXX: prevent slugger reverse engineering by not displaying decoded mail
138 throw $this->createNotFoundException($this->translator->trans('Unable to find account', [], $this->alias));
139 }
140
141 //Prevent access when not admin, user is not guest and not currently logged user
142 if (!$this->checker->isGranted('ROLE_'.strtoupper($this->config['default']['admin'])) && $user != $this->security->getUser() || !$this->checker->isGranted('IS_AUTHENTICATED_FULLY')) {
143 //Throw access denied
144 //XXX: prevent slugger reverse engineering by not displaying decoded mail
145 throw $this->createAccessDeniedException($this->translator->trans('Unable to access user', [], $this->alias));
146 }
147
148 //Create the EditType form and give the proper parameters
149 $edit = $this->factory->create($this->config['edit']['view']['edit'], $user, [
150 //Set action to edit route name and context
151 'action' => $this->generateUrl($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $this->slugger->hash($smail)]+$this->config['route']['edit']['context']),
152 //Set civility class
153 'civility_class' => $this->config['class']['civility'],
154 //Set civility default
155 'civility_default' => $this->doctrine->getRepository($this->config['class']['civility'])->findOneByTitle($this->config['default']['civility']),
156 //Disable mail
157 'mail' => $this->checker->isGranted('ROLE_'.strtoupper($this->config['default']['admin'])),
158 //Disable password
159 'password' => false,
160 //Set method
161 'method' => 'POST',
162 //Set domain
163 'translation_domain' => $this->alias
164 ]+($this->checker->isGranted('ROLE_'.strtoupper($this->config['default']['admin']))?$this->config['edit']['admin']:$this->config['edit']['field']));
165
166 //With admin role
167 if ($this->checker->isGranted('ROLE_'.strtoupper($this->config['default']['admin']))) {
168 //Create the EditType form and give the proper parameters
169 $reset = $this->factory->create($this->config['edit']['view']['reset'], $user, [
170 //Set action to edit route name and context
171 'action' => $this->generateUrl($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $this->slugger->hash($smail)]+$this->config['route']['edit']['context']),
172 //Set method
173 'method' => 'POST',
174 //Set domain
175 'translation_domain' => $this->alias
176 ]);
177
178 //With post method
179 if ($request->isMethod('POST')) {
180 //Refill the fields in case the form is not valid.
181 $reset->handleRequest($request);
182
183 //With reset submitted and valid
184 if ($reset->isSubmitted() && $reset->isValid()) {
185 //Set data
186 $data = $reset->getData();
187
188 //Set password
189 $data->setPassword($this->hasher->hashPassword($data, $data->getPassword()));
190
191 //Queue snippet save
192 $this->manager->persist($data);
193
194 //Flush to get the ids
195 $this->manager->flush();
196
197 //Add notice
198 $this->addFlash('notice', $this->translator->trans('Account password updated', [], $this->alias));
199
200 //Redirect to cleanup the form
201 return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail = $this->slugger->short($mail), 'hash' => $this->slugger->hash($smail)]+$this->config['route']['edit']['context']);
202 }
203 }
204
205 //Add reset view
206 $this->config['edit']['view']['context']['reset'] = $reset->createView();
207 }
208
209 //With post method
210 if ($request->isMethod('POST')) {
211 //Refill the fields in case the form is not valid.
212 $edit->handleRequest($request);
213
214 //With edit submitted and valid
215 if ($edit->isSubmitted() && $edit->isValid()) {
216 //Set data
217 $data = $edit->getData();
218
219 //Queue snippet save
220 $this->manager->persist($data);
221
222 //Try saving in database
223 try {
224 //Flush to get the ids
225 $this->manager->flush();
226
227 //Add notice
228 $this->addFlash('notice', $this->translator->trans('Account updated', [], $this->alias));
229
230 //Redirect to cleanup the form
231 return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail = $this->slugger->short($mail), 'hash' => $this->slugger->hash($smail)]+$this->config['route']['edit']['context']);
232 //Catch double slug or mail
233 } catch (UniqueConstraintViolationException $e) {
234 //Add error message mail already exists
235 $this->addFlash('error', $this->translator->trans('The account already exists', [], $this->alias));
236 }
237 }
238 //Without admin role
239 //XXX: prefer a reset on login to force user unspam action
240 } elseif (!$this->checker->isGranted('ROLE_'.strtoupper($this->config['default']['admin']))) {
241 //Add notice
242 $this->addFlash('notice', $this->translator->trans('To change your password login with your mail and any password then follow the procedure', [], $this->alias));
243 }
244
245 //Render view
246 return $this->render(
247 //Template
248 $this->config['edit']['view']['name'],
249 //Context
250 ['register' => $edit->createView()]+$this->config['edit']['view']['context']
251 );
252 }
253
254 /**
255 * Login
256 *
257 * @param Request $request The request
258 * @param AuthenticationUtils $authenticationUtils The authentication utils
259 * @param ?string $hash The hashed password
260 * @param ?string $mail The shorted mail address
261 * @return Response The response
262 */
263 public function login(Request $request, AuthenticationUtils $authenticationUtils, ?string $hash, ?string $mail): Response {
264 //Create the LoginType form and give the proper parameters
265 $login = $this->factory->create($this->config['login']['view']['form'], null, [
266 //Set action to login route name and context
267 'action' => $this->generateUrl($this->config['route']['login']['name'], $this->config['route']['login']['context']),
268 //Set method
269 'method' => 'POST',
270 //Set domain
271 'translation_domain' => $this->alias
272 ]);
273
274 //Init context
275 $context = [];
276
277 //With mail
278 if (!empty($mail) && !empty($hash)) {
279 //With invalid hash
280 if ($hash != $this->slugger->hash($mail)) {
281 //Throw bad request
282 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash], $this->alias));
283 }
284
285 //Get mail
286 $mail = $this->slugger->unshort($smail = $mail);
287
288 //Without valid mail
289 if (filter_var($mail, FILTER_VALIDATE_EMAIL) === false) {
290 //Throw bad request
291 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail], $this->alias));
292 }
293
294 //Prefilled mail
295 $login->get('mail')->setData($mail);
296 //Last username entered by the user
297 } elseif ($lastUsername = $authenticationUtils->getLastUsername()) {
298 $login->get('mail')->setData($lastUsername);
299 }
300
301 //Get the login error if there is one
302 if ($error = $authenticationUtils->getLastAuthenticationError()) {
303 //Get translated error
304 $error = $this->translator->trans($error->getMessageKey(), [], $this->alias);
305
306 //Add error message to mail field
307 $login->get('mail')->addError(new FormError($error));
308
309 //Create the RecoverType form and give the proper parameters
310 $recover = $this->factory->create($this->config['recover']['view']['form'], null, [
311 //Set action to recover route name and context
312 'action' => $this->generateUrl($this->config['route']['recover']['name'], $this->config['route']['recover']['context']),
313 //Without password
314 'password' => false,
315 //Set method
316 'method' => 'POST',
317 //Set domain
318 'translation_domain' => $this->alias
319 ]);
320
321 //Get recover mail entity
322 $recover->get('mail')
323 //Set mail from login form
324 ->setData($login->get('mail')->getData())
325 //Add recover error
326 ->addError(new FormError($this->translator->trans('Use this form to recover your account', [], $this->alias)));
327
328 //Add recover form to context
329 $context['recover'] = $recover->createView();
330 } else {
331 //Add notice
332 $this->addFlash('notice', $this->translator->trans('To change your password login with your mail and any password then follow the procedure', [], $this->alias));
333 }
334
335 //Render view
336 return $this->render(
337 //Template
338 $this->config['login']['view']['name'],
339 //Context
340 ['login' => $login->createView(), 'disabled' => $request->query->get('disabled', 0)]+$context+$this->config['login']['view']['context']
341 );
342 }
343
344 /**
345 * Recover account
346 *
347 * @param Request $request The request
348 * @param ?string $hash The hashed password
349 * @param ?string $pass The shorted password
350 * @param ?string $mail The shorted mail address
351 * @return Response The response
352 */
353 public function recover(Request $request, ?string $hash, ?string $pass, ?string $mail): Response {
354 //Set user
355 $user = null;
356
357 //Set context
358 $context = [];
359
360 //With mail, pass and hash
361 if (!empty($mail) && !empty($pass) && !empty($hash)) {
362 //With invalid hash
363 if ($hash != $this->slugger->hash($mail.$pass)) {
364 //Throw bad request
365 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash], $this->alias));
366 }
367
368 //Get mail
369 $mail = $this->slugger->unshort($smail = $mail);
370
371 //Without valid mail
372 if (filter_var($mail, FILTER_VALIDATE_EMAIL) === false) {
373 //Throw bad request
374 //XXX: prevent slugger reverse engineering by not displaying decoded mail
375 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail], $this->alias));
376 }
377
378 //With existing subscriber
379 if (empty($user = $this->doctrine->getRepository($this->config['class']['user'])->findOneByMail($mail))) {
380 //Throw not found
381 //XXX: prevent slugger reverse engineering by not displaying decoded mail
382 throw $this->createNotFoundException($this->translator->trans('Unable to find account', [], $this->alias));
383 }
384
385 //With unmatched pass
386 if ($pass != $this->slugger->hash($user->getPassword())) {
387 //Throw not found
388 //XXX: prevent use of outdated recover link
389 throw new GoneHttpException($this->translator->trans('Outdated recover link', [], $this->alias));
390 }
391
392 //Set context
393 $context = ['mail' => $smail, 'pass' => $pass, 'hash' => $hash];
394 }
395
396 //Create the LoginType form and give the proper parameters
397 $form = $this->factory->create($this->config['recover']['view']['form'], $user, [
398 //Set action to recover route name and context
399 'action' => $this->generateUrl($this->config['route']['recover']['name'], $context+$this->config['route']['recover']['context']),
400 //With user disable mail
401 'mail' => ($user === null),
402 //With user enable password
403 'password' => ($user !== null),
404 //Set method
405 'method' => 'POST',
406 //Set domain
407 'translation_domain' => $this->alias
408 ]);
409
410 //With post method
411 if ($request->isMethod('POST')) {
412 //Refill the fields in case the form is not valid.
413 $form->handleRequest($request);
414
415 //With form submitted and valid
416 if ($form->isSubmitted() && $form->isValid()) {
417 //Set data
418 $data = $form->getData();
419
420 //With user
421 if ($user !== null) {
422 //Set hashed password
423 $hashed = $this->hasher->hashPassword($user, $user->getPassword());
424
425 //Update pass
426 $pass = $this->slugger->hash($hashed);
427
428 //Set user password
429 $user->setPassword($hashed);
430
431 //Persist user
432 $this->manager->persist($user);
433
434 //Send to database
435 $this->manager->flush();
436
437 //Add notice
438 $this->addFlash('notice', $this->translator->trans('Account password updated', [], $this->alias));
439
440 //Redirect to user login
441 return $this->redirectToRoute($this->config['route']['login']['name'], ['mail' => $smail, 'hash' => $this->slugger->hash($smail)]+$this->config['route']['login']['context']);
442 //Find user by data mail
443 } elseif ($user = $this->doctrine->getRepository($this->config['class']['user'])->findOneByMail($data['mail'])) {
444 //Set context
445 $context = [
446 'recipient_mail' => $user->getMail(),
447 'recipient_name' => $user->getRecipientName()
448 ] + array_replace_recursive(
449 $this->config['context'],
450 $this->config['recover']['view']['context'],
451 $this->config['recover']['mail']['context']
452 );
453
454 //Generate each route route
455 foreach($this->config['recover']['route'] as $route => $tag) {
456 //Only process defined routes
457 if (!empty($this->config['route'][$route])) {
458 //Process for recover mail url
459 if ($route == 'recover') {
460 //Set the url in context
461 $context[$tag] = $this->router->generate(
462 $this->config['route'][$route]['name'],
463 //Prepend recover context with tag
464 [
465 'mail' => $smail = $this->slugger->short($context['recipient_mail']),
466 'pass' => $spass = $this->slugger->hash($pass = $user->getPassword()),
467 'hash' => $this->slugger->hash($smail.$spass)
468 ]+$this->config['route'][$route]['context'],
469 UrlGeneratorInterface::ABSOLUTE_URL
470 );
471 }
472 }
473 }
474
475 //Translate subject
476 $context['subject'] = $subject = ucfirst(
477 $this->translator->trans(
478 $this->config['recover']['mail']['subject'],
479 $this->slugger->flatten($context, null, '.', '%', '%'),
480 $this->alias
481 )
482 );
483
484 //Create message
485 $message = (new TemplatedEmail())
486 //Set sender
487 ->from(new Address($this->config['contact']['address'], $this->translator->trans($this->config['contact']['name'], [], $this->alias)))
488 //Set recipient
489 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
490 ->to(new Address($context['recipient_mail'], $context['recipient_name']))
491 //Set subject
492 ->subject($context['subject'])
493
494 //Set path to twig templates
495 ->htmlTemplate($this->config['recover']['mail']['html'])
496 ->textTemplate($this->config['recover']['mail']['text'])
497
498 //Set context
499 ->context($context);
500
501 //Add created notice
502 $this->addFlash('notice', $this->translator->trans('Account recovered', [], $this->alias));
503
504 //Try sending message
505 //XXX: mail delivery may silently fail
506 try {
507 //Send message
508 $this->mailer->send($message);
509
510 //Add sent notice
511 $this->addFlash('notice', $this->translator->trans('Your recovery mail has been sent, to retrieve your account follow the recuperate link inside', [], $this->alias));
512
513 //Add junk warning
514 $this->addFlash('warning', $this->translator->trans('If you did not receive a recovery mail, check your Spam or Junk mail folder', [], $this->alias));
515
516 //Redirect on home route to cleanup form
517 return $this->redirectToRoute($this->config['route']['home']['name'], $this->config['route']['home']['context']);
518 //Catch obvious transport exception
519 } catch(TransportExceptionInterface $e) {
520 //Add error message mail unreachable
521 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to reach account', [], $this->alias)));
522 }
523 }
524 }
525 }
526
527 //Render view
528 return $this->render(
529 //Template
530 $this->config['recover']['view']['name'],
531 //Context
532 ['recover' => $form->createView()]+$this->config['recover']['view']['context']
533 );
534 }
535
536 /**
537 * Register an account
538 *
539 * @param Request $request The request
540 * @return Response The response
541 */
542 public function register(Request $request): Response {
543 //With mail
544 if (!empty($_POST['register']['mail'])) {
545 //Log new user infos
546 $this->logger->emergency(
547 //Translated register informations
548 $this->translator->trans(
549 'register: mail=%mail% locale=%locale% confirm=%confirm% ip=%ip%',
550 [
551 '%mail%' => $postMail = $_POST['register']['mail'],
552 '%locale%' => $request->getLocale(),
553 '%confirm%' => $this->router->generate(
554 $this->config['route']['confirm']['name'],
555 //Prepend subscribe context with tag
556 [
557 'mail' => $postSmail = $this->slugger->short($postMail),
558 'hash' => $this->slugger->hash($postSmail)
559 ]+$this->config['route']['confirm']['context'],
560 UrlGeneratorInterface::ABSOLUTE_URL
561 ),
562 '%ip%' => $request->getClientIp()
563 ],
564 $this->alias
565 ),
566 //Set context
567 [
568 'file' => __FILE__,
569 'line' => __LINE__
570 ]
571 );
572 }
573
574 //Init reflection
575 $reflection = new \ReflectionClass($this->config['class']['user']);
576
577 //Create new user
578 $user = $reflection->newInstance('', '');
579
580 //Create the RegisterType form and give the proper parameters
581 $form = $this->factory->create($this->config['register']['view']['form'], $user, [
582 //Set action to register route name and context
583 'action' => $this->generateUrl($this->config['route']['register']['name'], $this->config['route']['register']['context']),
584 //Set captcha
585 'captcha' => true,
586 //Set civility class
587 'civility_class' => $this->config['class']['civility'],
588 //Set civility default
589 'civility_default' => $this->doctrine->getRepository($this->config['class']['civility'])->findOneByTitle($this->config['default']['civility']),
590 //Set method
591 'method' => 'POST',
592 //Set domain
593 'translation_domain' => $this->alias
594 ]+($this->checker->isGranted('ROLE_'.strtoupper($this->config['default']['admin']))?$this->config['register']['admin']:$this->config['register']['field']));
595
596 //With post method
597 if ($request->isMethod('POST')) {
598 //Refill the fields in case the form is not valid.
599 $form->handleRequest($request);
600
601 //With form submitted and valid
602 if ($form->isSubmitted() && $form->isValid()) {
603 //Set data
604 $data = $form->getData();
605
606 //Set password
607 $user->setPassword($this->hasher->hashPassword($user, $user->getPassword()));
608
609 //Persist user
610 $this->manager->persist($user);
611
612 //Iterate on default group
613 foreach($this->config['default']['group'] as $i => $groupTitle) {
614 //Fetch group
615 if (($group = $this->doctrine->getRepository($this->config['class']['group'])->findOneByTitle($groupTitle))) {
616 //Set default group
617 //XXX: see vendor/symfony/security-core/Role/Role.php
618 $user->addGroup($group);
619 //Group not found
620 } else {
621 //Throw exception
622 //XXX: consider missing group as fatal
623 throw new \Exception(sprintf('Group %s listed in %s.default.group[%d] not found by title', $groupTitle, $this->alias, $i));
624 }
625 }
626
627 //Set context
628 $context = [
629 'recipient_mail' => $user->getMail(),
630 'recipient_name' => $user->getRecipientName()
631 ] + array_replace_recursive(
632 $this->config['context'],
633 $this->config['register']['view']['context'],
634 $this->config['register']['mail']['context']
635 );
636
637 //Generate each route route
638 foreach($this->config['register']['route'] as $route => $tag) {
639 //Only process defined routes
640 if (!empty($this->config['route'][$route])) {
641 //Process for confirm mail url
642 if ($route == 'confirm') {
643 //Set the url in context
644 $context[$tag] = $this->router->generate(
645 $this->config['route'][$route]['name'],
646 //Prepend register context with tag
647 [
648 'mail' => $smail = $this->slugger->short($context['recipient_mail']),
649 'hash' => $this->slugger->hash($smail)
650 ]+$this->config['route'][$route]['context'],
651 UrlGeneratorInterface::ABSOLUTE_URL
652 );
653 }
654 }
655 }
656
657 //Translate subject
658 $context['subject'] = $subject = ucfirst(
659 $this->translator->trans(
660 $this->config['register']['mail']['subject'],
661 $this->slugger->flatten($context, null, '.', '%', '%'),
662 $this->alias
663 )
664 );
665
666 //Create message
667 $message = (new TemplatedEmail())
668 //Set sender
669 ->from(new Address($this->config['contact']['address'], $this->translator->trans($this->config['contact']['name'], [], $this->alias)))
670 //Set recipient
671 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
672 ->to(new Address($context['recipient_mail'], $context['recipient_name']))
673 //Set subject
674 ->subject($context['subject'])
675
676 //Set path to twig templates
677 ->htmlTemplate($this->config['register']['mail']['html'])
678 ->textTemplate($this->config['register']['mail']['text'])
679
680 //Set context
681 ->context($context);
682
683 //Try saving in database
684 try {
685 //Send to database
686 $this->manager->flush();
687
688 //Add created notice
689 $this->addFlash('notice', $this->translator->trans('Account created', [], $this->alias));
690
691 //Try sending message
692 //XXX: mail delivery may silently fail
693 try {
694 //Send message
695 $this->mailer->send($message);
696
697 //Add verification notice
698 $this->addFlash('notice', $this->translator->trans('Your verification mail has been sent, to activate your account you must follow the confirmation link inside', [], $this->alias));
699
700 //Add junk warning
701 $this->addFlash('warning', $this->translator->trans('If you did not receive a verification mail, check your Spam or Junk mail folders', [], $this->alias));
702
703 //Redirect on home route to cleanup form
704 return $this->redirectToRoute($this->config['route']['home']['name'], $this->config['route']['home']['context']);
705 //Catch obvious transport exception
706 } catch(TransportExceptionInterface $e) {
707 //Add error message mail unreachable
708 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to reach account', [], $this->alias)));
709 }
710 //Catch double subscription
711 } catch (UniqueConstraintViolationException $e) {
712 //Add error message mail already exists
713 $this->addFlash('error', $this->translator->trans('The account already exists', [], $this->alias));
714 }
715 }
716 }
717
718 //Render view
719 return $this->render(
720 //Template
721 $this->config['register']['view']['name'],
722 //Context
723 ['register' => $form->createView()]+$this->config['register']['view']['context']
724 );
725 }
726 }