<?php
namespace App\Controller;
use App\Entity\CBRCAGCADocument;
use App\Entity\CBRCArticle;
use App\Entity\CBRCArticleCategory;
use App\Entity\CBRCUser;
use App\Form\Type\CBRCUserDescriptionType;
use App\Form\Type\CBRCUserType;
use App\Form\Type\ContactType;
use App\Form\Type\ModifyEmailType;
use App\Form\Type\ModifyPasswordType;
use App\Utilities\Mail;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\HttpFoundation\Request;
class HomeController extends AbstractController
{
/**
* @Route("", name="home")
*/
public function ShowHome(Request $request, PaginatorInterface $paginator): \Symfony\Component\HttpFoundation\Response
{
$articles = $this->getDoctrine()->getRepository(CBRCArticle::class)->findHome();
$pagination = $paginator->paginate(
$articles, /* query NOT result */
$request->query->getInt('page', 1), /*page number*/
10 /*limit per page*/
);
return $this->render('home.html.twig', [
'articles' => $articles,
'pagination' => $pagination,
]);
}
/**
* @Route("/categorie/{categoryname}", name="home_by_category")
*/
public function ShowHomeByCategory(string $categoryname, Request $request, PaginatorInterface $paginator): \Symfony\Component\HttpFoundation\Response
{
$isnone=false;
$category= $this->getDoctrine()->getRepository(CBRCArticleCategory::class)->findOneBy(['name'=>$categoryname]);
if(!$category && $categoryname!="none")
throw new NotFoundHttpException();
if($categoryname=="none") {
$articles =$this->getDoctrine()->getRepository(CBRCArticle::class)->findHomeNoneCategory();
$isnone=true;
}
else{
$articles = $this->getDoctrine()->getRepository(CBRCArticle::class)->findHomeByCategory($category);
}
$pagination = $paginator->paginate(
$articles, /* query NOT result */
$request->query->getInt('page', 1), /*page number*/
10 /*limit per page*/
);
return $this->render('home.html.twig', [
'articles' => $articles,
'pagination' => $pagination,
'activecategory' => $category,
'isnone' => $isnone,
]);
}
/**
* @Route ("creeruncompte", name="signup")
*/
public function ShowSignUp(Request $request, UserPasswordEncoderInterface $passwordEncoder): \Symfony\Component\HttpFoundation\Response
{
$user = new CBRCUser();
$form = $this->createForm(CBRCUserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$password = $passwordEncoder->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->container->get('security.token_storage')->setToken($token);
$this->container->get('session')->set('_security_main', serialize($token));
return $this->redirectToRoute('account');
//test modif 5
}
return $this->render('homesignup.html.twig', [
'registerform' => $form->createView(),
]);
}
/**
* @Route("/contact", name="contact")
*/
public function ShowContact(Request $request)
{
//form contact
$formcontact = $this->createForm(ContactType::class,null,[
'attr' => [
'onsubmit' => 'return oncontactsubmit(event);'
]
]);
$formcontact->handleRequest($request);
if($formcontact->isSubmitted() && $formcontact->isValid()){
$name = $formcontact->getData()['name'];
$email = $formcontact->getData()['email'];
$message = $formcontact->getData()['message'];
$recaptchatoken = $formcontact['recaptchatoken']->getData();
if(!in_array($_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1')))
{
$recaptcha = new \ReCaptcha\ReCaptcha("6Ldhw70gAAAAAAefuTIeH2S7hu8LH6f2n8Mw_UCN");
$resp = $recaptcha->setExpectedAction('contact')
->verify($recaptchatoken, $_SERVER['REMOTE_ADDR']);
//->setExpectedHostname('dev.cbrc51.fr')
if (!$resp->isSuccess()) {
$this->addFlash('danger', 'Etes vous un robot?');
return $this->redirect($request->getUri());
}
}
$txtmessage = "Demande de ".$name." dont l'adresse mail est ".$email." et le message est: ".$message;
$subject = "Contact";
$htmlmessage = $this->renderView('mail/askinformationmail.html.twig', [
'subject' => $subject,
'name' => $name,
'email' => $email,
'message' => $message,
]);
$return = Mail::SendMailToAdmin($email, $subject, $htmlmessage, $txtmessage);
if($return ==false)
{
$this->addFlash('danger', 'Erreur lors de l\'envoi du mail');
}
else
{
$this->addFlash('success', 'Le message a été envoyé');
}
return $this->redirect($request->getUri());
}
if($formcontact->isSubmitted() && !$formcontact->isValid())
{
foreach($formcontact->getErrors(true) as $error)
$this->addFlash('danger', "(".$error->getOrigin()->getName().") ".$error->getMessage());
return $this->redirect($request->getUri());
}
return $this->render('homecontact.html.twig', [
'formcontact' => $formcontact->createView(),
]);
}
/**
* @Route("/informations", name="about")
*/
public function ShowAbout(Request $request)
{
$documents = $this->getDoctrine()->getRepository(CBRCAGCADocument::class)->findAll();
return $this->render('homeabout.html.twig', [
'documents' => $documents,
]);
}
/**
* @Route("/mentionslegales", name="legal")
*/
public function ShowLegal(Request $request)
{
return $this->render('homelegal.html.twig', [
]);
}
/**
* @Route ("/moncompte", name="account")
*/
public function ShowAccount(Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$user = $this->getUser();
$formuserdescription = $this->createForm(CBRCUserDescriptionType::class, $user->getDescription());
$formuserdescription->handleRequest($request);
if ($formuserdescription->isSubmitted() && $formuserdescription->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$this->addFlash('success', 'Modification effetuée');
return $this->redirect($request->getUri());
}
if ($formuserdescription->isSubmitted() && !$formuserdescription->isValid()) {
foreach ($formuserdescription->getErrors(true) as $error)
$this->addFlash('danger', "(" . $error->getOrigin()->getName() . ") " . $error->getMessage());
$formuserdescription->clearErrors(true);
return $this->redirect($request->getUri());
}
//formmodifypassword
$formuserpassword = $this->createForm(ModifyPasswordType::class);
$formuserpassword->handleRequest($request);
if ($formuserpassword->isSubmitted() && $formuserpassword->isValid()) {
//Check actual password
$password = $formuserpassword->getData()['actualpassword'];
//check password
$validpassword = $passwordEncoder->isPasswordValid($user, $password);
if ($validpassword) {
$password = $passwordEncoder->encodePassword($user, $formuserpassword->getData()['plainPassword']);
$user->setPassword($password);
// 4) save the User!
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash('primary', 'Le mot de passe a été modifié');
return $this->redirect($request->getUri());
} else {
$formuserpassword->get('actualpassword')->addError(new FormError('Mauvais mot de passe'));
}
}
if ($formuserpassword->isSubmitted() && !$formuserpassword->isValid()) {
foreach ($formuserpassword->getErrors(true) as $error)
$this->addFlash('danger', "(" . $error->getOrigin()->getName() . ") " . $error->getMessage());
return $this->redirect($request->getUri());
}
//formmodifyemail
$formuseremail = $this->createForm(ModifyEmailType::class, null, ['email_placeholder' => $user->getEmail()]);
$formuseremail->handleRequest($request);
if ($formuseremail->isSubmitted() && $formuseremail->isValid()) {
//Check actual password
$password = $formuseremail->getData()['password'];
//check password
$validpassword = $passwordEncoder->isPasswordValid($user, $password);
if ($validpassword) {
$usermail = $formuseremail->getData()['email'];
$user->setEmail($usermail);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash('primary', 'L\'adresse email a été modifée');
return $this->redirect($request->getUri());
} else {
$formuseremail->get('password')->addError(new FormError('Mauvais mot de passe'));
}
}
if ($formuseremail->isSubmitted() && !$formuseremail->isValid()) {
foreach ($formuseremail->getErrors(true) as $error)
$this->addFlash('danger', "(" . $error->getOrigin()->getName() . ") " . $error->getMessage());
return $this->redirect($request->getUri());
}
return $this->render('homeaccount.html.twig', [
'userdescriptionform' => $formuserdescription->createView(),
'modifypasswordform' => $formuserpassword->createView(),
'modifyemailform' => $formuseremail->createView(),
'idactive'=>0,
]
);
}
public function RenderAccountMenu(int $idactive=0)
{
return $this->render('menu/accountmenu.html.twig', [
'idactive' => $idactive
]
);
}
}