<?php
namespace App\Controller;
use App\Entity\User;
use App\Entity\Customer;
use App\Entity\CustomerProfil;
use App\Repository\CustomerProfilRepository;
use App\Form\RegistrationFormType;
use App\Form\CustomerFormType;
use App\Message\MailNotification;
use App\Security\EmailVerifier;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mime\Address;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use App\Repository\UserRepository;
use SymfonyCasts\Bundle\VerifyEmail\VerifyEmailHelperInterface;
use App\Services\UserManager;
use App\Services\CustomerManager;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
use Symfony\Component\Mime\Email;
use App\Config\Config;
use DateTime;
class RegistrationController extends AbstractController
{
private EmailVerifier $emailVerifier;
private $verifyEmail;
public function __construct(
CustomerManager $customerManager,
EmailVerifier $emailVerifier,
Security $security,
SessionInterface $session,
EntityManagerInterface $entityManager,
VerifyEmailHelperInterface $verifyEmail,
UserManager $um,
MailerInterface $mailer,
Config $config
) {
$this->emailVerifier = $emailVerifier;
$this->entityManager = $entityManager;
$this->session = $session;
$this->security = $security;
$this->verifyEmail = $verifyEmail;
$this->um = $um;
$this->mailer = $mailer;
$this->customerManager = $customerManager;
$this->config = $config;
}
#[Route("/register", name: "app_register")]
public function register(
Request $request,
UserPasswordHasherInterface $userPasswordHasher,
EntityManagerInterface $entityManager
): Response {
$user = new User();
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($this->session->get("to_be_redirected")) {
$this->um->updateUser(
$_POST["registration_form"]["email"],
password_hash(
$_POST["registration_form"]["plainPassword"],
PASSWORD_DEFAULT
),
null,
null,
null,
$_POST["registration_form"]["username"]
);
$user = $this->um->getUserByEmail(
$_POST["registration_form"]["email"]
)[0];
$this->addFlash(
"success_register",
"Un email de confirmation a été envoyé."
);
$this->emailVerifier->sendEmailConfirmation($user);
// return $this->redirectToRoute("register_information");
return $this->redirectToRoute("catalog_participant", [
"origin" => "?=0",
"new" => 1,
"f" => $this->session->get("to_be_redirected")["formation"],
"sd" => $this->session->get("to_be_redirected")["startDate"],
]);
}
if ($form->get("captcha")->getData()) {
if ( $form->isValid() ||
in_array(
strtolower($form->get("captcha")->getData()),
$this->capcha_keys()
)
) {
///***********************************
if($q=$this->um->getUserByEmail($_POST["registration_form"]["email"]))
{
if ( $_POST["registration_form"]["plainPassword"] != $_POST["registration_form"]["plainPasswordConfirm"]) {
$this->addFlash(
"invalid_confirm_password",
"Vos mots de passe doivent être identiques."
);
return $this->redirectToRoute("login");
}
if($q[0]->getIdUserProfil()==2)
{
$q[0]->setIdUserProfil(1);
$q[0]->setRoles(["ROLE_CUSTOMER"]);
$q[0]->setIsProfessional(1);
$q[0]->setPassword(
$userPasswordHasher->hashPassword(
$q[0],
$_POST["registration_form"]["plainPassword"]
)
);
$entityManager->flush();
if(!$q[0]->isVerified())
{
$this->emailVerifier->sendEmailConfirmation($q[0]);
$this->addFlash(
"success_register",
"Un email de confirmation a été envoyé."
);
return $this->redirectToRoute("register_information");
}
$this->addFlash(
"success_register",
"Le compte a bien été mise à jour."
);
return $this->redirectToRoute("register_information");
}
else{
$this->addFlash(
"verify_email_error",
"Adresse email déjà enregistrée ou Captcha incorrect"
);
return $this->redirectToRoute("login");
}
}
///***********************************
// encode the plain password
if (
$form->get("plainPassword")->getData() ===
$form->get("plainPasswordConfirm")->getData()
) {
$user->setPassword(
$userPasswordHasher->hashPassword(
$user,
$form->get("plainPassword")->getData()
)
);
$user->setRoles(["ROLE_CUSTOMER"]);
$user->setIsActive(1);
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash(
"success_register",
"Un email de confirmation a été envoyé."
);
$this->emailVerifier->sendEmailConfirmation($user);
return $this->redirectToRoute("register_information");
} else {
$this->addFlash(
"invalid_confirm_password",
"Vos mots de passe doivent être identiques."
);
return $this->redirectToRoute("login");
}
} else {
$this->addFlash(
"verify_email_error",
"Adresse email déjà enregistrée ou Captcha incorrect"
);
return $this->redirectToRoute("login");
}
} else {
$this->addFlash(
"verify_recapcha_error",
"Veuillez valider le Captcha"
);
return $this->redirectToRoute("login");
}
}
if (isset($_GET["em"])) {
$_email = base64_decode($_GET["em"]);
}
if (isset($_GET["exist"])) {
$exist = $_GET["exist"];
}
if (isset($_GET["f"]) && isset($_GET["sd"])) {
$this->session->set("to_be_redirected", [
"formation" => $_GET["f"],
"startDate" => $_GET["sd"],
]);
}
return $this->render("acoa/registration/_register.html.twig", [
"registrationForm" => $form->createView(),
"_email" => isset($_email) ? $_email : null,
"exist" => isset($exist) ? $exist : 1,
]);
}
#[Route("/verify/email/register", name: "app_verify_email")]
public function verifyUserEmail(
Request $request,
UserRepository $userRepository
): Response {
$id = $request->get("id"); // retrieve the user id from the url
// Verify the user id exists and is not null
if (null === $id) {
return $this->redirectToRoute("login");
}
$user = $userRepository->find($id);
// Ensure the user exists in persistence
if (null === $user) {
return $this->redirectToRoute("login");
}
// Do not get the User's Id or Email Address from the Request object
try {
$this->verifyEmail->validateEmailConfirmation(
$request->getUri(),
$user->getId(),
$user->getEmail()
);
} catch (VerifyEmailExceptionInterface $e) {
$this->addFlash("verify_email_error", $e->getReason());
return $this->redirectToRoute("app_register");
}
// Mark your user as verified. e.g. switch a User::verified property to true
$user->setIsVerified(1);
$this->entityManager->persist($user);
$this->entityManager->flush();
$this->addFlash(
"success",
"Votre adresse est vérifiée, merci de vous connecter pour finaliser la réservation."
);
//return $this->redirectToRoute("register_information");
return $this->redirectToRoute("backend_my_account");
}
#[Route("/register/information", name: "register_information")]
public function registerInformation(
Request $request,
CustomerProfilRepository $customerProfilRepository,
SessionInterface $session
): Response {
$this->denyAccessUnlessGranted("IS_AUTHENTICATED_FULLY");
$currentUser = $this->security->getUser();
$new = $this->session->get("new");
$f = $this->session->get("f");
$sd = $this->session->get("sd");
$ics = $this->session->get("ics");
if (
(int) $new == 1 &&
$currentUser->getEmail() &&
$this->customerManager->hasCompanyNameByEmail(
$currentUser->getEmail()
)
) {
$this->session->set("new", "0");
return $this->redirectToRoute("catalog_participant", [
"origin" => "?=0",
"f" => $f,
"sd" => $sd,
"ics" => $ics,
]);
}
$customer = new Customer();
$customer->setFirstName($currentUser->getFirstName());
$customer->setLastName($currentUser->getLastName());
$customer->setEmail($currentUser->getEmail());
$customer->setPassword($currentUser->getPassword());
if (
$session->get("nbUser") == 1 &&
$session->get("user0")->getFirstName() ==
$customer->getFirstName() &&
$session->get("user0")->getLastName() == $customer->getLastName()
) {
$customer->setIdCustomerProfil(
$customerProfilRepository->find(2)->getIdCustomerProfil()
);
} else {
$customer->setIdCustomerProfil(
$customerProfilRepository->find(1)->getIdCustomerProfil()
);
}
$form = $this->createForm(CustomerFormType::class, $customer);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->entityManager->persist($customer);
$this->entityManager->flush();
// PL$ - updateUser with customer info
$this->um->updateUserByCustomer(
$customer->getEmail(),
$this->customerManager->getLastIdCustomer(),
$customer->getFirstName(),
$customer->getLastName()
);
// $this->um->updateUserIdCustomer($customer->getEmail(), $this->customerManager->getLastIdCustomer());
$this->session->set("idCustomer", $customer->getId());
$currentUser->setIdCustomer($customer->getId());
$currentUser->setFirstName($customer->getFirstName());
$currentUser->setLastName($customer->getLastName());
$currentUser->setEmail($customer->getEmail());
if (
$this->session->get("idCourseSession") &&
$this->session->get("redirect_to_cart") == 1
) {
return $this->redirectToRoute("catalog_panier", [
"idCourseSession" => $this->session->get("idCourseSession"),
]);
}
if ($this->session->get("idCourseSession") !== null) {
return $this->redirectToRoute("catalog_panier", [
"idCourseSession" => $this->session->get("idCourseSession"),
]);
} else {
return $this->redirectToRoute("backend_my_account");
}
}
return $this->render("acoa/registration/information.html.twig", [
"form" => $form->createView(),
]);
}
#[Route("/register/learners", name: "register_learners")]
public function registerLearners(Request $request)
{
$status = false;
$value = false;
$email = "";
if (isset($_GET["ko"]) && $_GET["ko"] == "email") {
$status = true;
}
if (isset($_GET["value"]) && $_GET["value"]) {
$value = true;
$email = $_GET["value"];
}
return $this->render("acoa/registration/register_learners.html.twig", [
"ko_email" => $status,
"email" => $value,
"value" => $email,
]);
}
#[Route("/register/learners/confirm", name: "register_learners_confirm")]
public function registerConfirmation()
{
foreach (array_chunk($_POST["participants"], 4) as $record) {
$email = $record[2];
$formation = $record[3];
if ($this->um->emailExist($email)) {
return $this->redirectToRoute("register_learners", [
"ko" => "email",
"value" => $email,
]);
}
$user = new User();
$user->setFirstName($record[1]);
$user->setLastName($record[0]);
$user->setPassword(
password_hash("iokljhko!$#pkY@787NK---LN47", PASSWORD_DEFAULT)
);
$user->setEmail($email);
$user->setRoles(["ROLE_STUDENT"]);
$user->setIsVerified(1);
$user->setIsActive(1);
$this->entityManager->persist($user);
$this->entityManager->flush();
$url =
$_SERVER["SERVER_NAME"] .
"/confirm/registration/" .
base64_encode("iokljhko!$#pkY@787NK---LN47") .
"?sun=" .
base64_encode($email) .
"&f=" .
base64_encode($formation);
$em = (new Email())
->from($this->config->getMailSender())
->priority(Email::PRIORITY_HIGH)
->to($email)
->cc("kalidougattaba@gmail.com", "pascal.liatard@abware.fr")
->subject("Registration")
->html($url);
$this->mailer->send($em);
// $this->dispatchMessage(new MailNotification($email, "Registration", "<p>Click on the link bellow to sign: </p><br><a href='" . $url . "'>" . "Click here" . "</a>"));
}
return $this->redirectToRoute("home");
}
#[Route("/confirm/registration/{params}", name: "confirm_registration")]
public function confirmRegistration(Request $request)
{
return $this->render(
"acoa/registration/confirm_registration_student.html.twig",
[
"email" => base64_decode($_GET["sun"]),
"formation" => base64_decode($_GET["f"]),
]
);
}
#[Route("/register/finalize", name: "register_finalize")]
public function finalizeRegistration()
{
if (
!isset($_POST["firstName"]) ||
!isset($_POST["lastName"]) ||
!isset($_POST["userName"]) ||
!isset($_POST["password"]) ||
!isset($_POST["confirmPassword"])
) {
return $this->redirectToRoute("confirm_registration");
}
$password = strip_tags($_POST["password"]);
$confirmPassword = strip_tags($_POST["confirmPassword"]);
$email = strip_tags($_POST["email"]);
$firstName = strip_tags($_POST["firstName"]);
$lastName = strip_tags($_POST["lastName"]);
$userName = strip_tags($_POST["userName"]);
$occupation = strip_tags($_POST["occupation"]);
$formation = strip_tags($_POST["formation"]);
if ($password != $confirmPassword) {
return $this->redirectToRoute("home");
}
$this->um->updateUser(
$email,
password_hash($password, PASSWORD_DEFAULT),
$occupation,
$firstName,
$lastName,
$userName
);
$em = (new TemplatedEmail())
->from($this->config->getMailSender())
->priority(Email::PRIORITY_HIGH)
->to($email)
->cc("kalidougattaba@gmail.com", "pascal.liatard@abware.fr")
->subject(
$firstName .
" " .
$lastName .
", confirmation de votre inscription"
)
->htmlTemplate(
"acoa/email/mailto_student_confirm_registration.html.twig"
)
->context([
"link" => $this->config->getDomain(),
"firstName" => $firstName,
"lastName" => $lastName,
]);
$this->mailer->send($em);
/*$content =
"Votre inscription sur la plateforme Acoa pour la formation " .
$formation .
" a bien été prise en compte !";*/
// $this->dispatchMessage(new MailNotification($email, "Registration | Confirmation", "<p>Click on the link bellow to sign: </p><br><a href='" . $content . "'>" . "Click here" . "</a>"));
return $this->redirectToRoute("home");
// return $this->render('registration/register_finalize.html.twig', ['email'=>base64_decode( $_GET['sun'])]);
}
public function capcha_keys()
{
return ["dsp6da", "jkhj6J", "juihk7", "iuiu28", "ukr1zb", "h1rzeh", "ky4tbg", "kzr4te", "beg0vj", "yit3rb", "ag1str", "tt0yke", "2vgjut", "po7bid", "tr6krg", "az78ea", "thd3fe", "fv5fed", "io8gre", "kyj2yt", "kz78ez", "kth4rt", "fr3ovd", "hkd1u5", "jlefk6", "btdt7s", "hty8bg", "kgb7rg", "gero7e", "ng8hfh", "hrt6tz", "grj3ef", "tukd0h", "tr4mzt", "try2cr", "rg6jtr", "reht1e", "ndrer7", "trzj2w", "af45ye", "grea2h", "rth98h", "pou4rt", "hj0tbf", "ndh6hg", "rui296", "kloeiog", "ouieng", "urtjrz", "trjy6l", "jdh8sh", "por2ei", "fezgr2", "jdtr2h", "jr32tr", "fez1kl", "ub23hf"];
}
}