<?php
// src/Controller/RegistrationController.php
namespace App\Controller;
use App\Form\UserType;
use App\Entity\User;
use App\Helper\Helpers;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Psr\Log\LoggerInterface;
use \Datetime;
class RegistrationController extends AbstractController
{
/**
* @Route("/register", name="user_registration")
*/
public function registerAction(Request $request, UserPasswordEncoderInterface $passwordEncoder, LoggerInterface $logger)
{
$securityContext = $this->container->get('security.authorization_checker');
if ($securityContext->isGranted('IS_AUTHENTICATED_FULLY')) {
return $this->redirectToRoute('main');
}
if (isset($_GET['info'])) {
$info=$_GET['info'];
} else {
$info="";
}
// 1) build the form
$user = new User();
$form = $this->createForm(UserType::class, $user);
$error = null;
// 2) handle the submit (will only happen on POST)
$form->handleRequest($request);
if ($form->isSubmitted()) {
if($form->isValid()){
// reCAPTCHA validation
$captcha = $request->request->get('g-recaptcha-response');
$secret = '6LfSVu0dAAAAACvOElC-RsnH9-UwU9nS6287Muar';
$response = json_decode(
file_get_contents(
sprintf(
'https://www.google.com/recaptcha/api/siteverify?secret=%s&response=%s',
$secret,
$captcha
)
),
true
);
if ($response['success'] == false) {
return $this->render(
'registration/register.html.twig',array('form' => $form->createView(),
'error' => 'reCAPTCHA'
)
);
}
$repUser = $this->getDoctrine()->getRepository(User::class);
$existingUser = $repUser->findOneByEmail($user->getEmail());
if ($existingUser) {
$error = 'Este email ya se encuentra registrado';
return $this->render('registration/register.html.twig',array(
'form' => $form->createView(),
'error' => $error,
)
);
}
$password = $passwordEncoder->encodePassword($user, $user->getPlainPassword());
$user->setRoles(["ROLE_USER"]);
//$user->setActive(false);
$user->setActive(true);
$user->setPassword($password);
date_default_timezone_set('Europe/Madrid');
$user->setCreatedDate(new \DateTime());
$to = $user->getEmail();
$hash = Helpers::encrypt($to);
$subject = 'Activa tu cuenta en EntradasyTickets';
$from = 'admin@entradasytickets.com';
$separator = md5(time());
$eol = PHP_EOL;
// main header
$headers = "From: " . $from . $eol;
$headers .= "MIME-Version: 1.0" . $eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"";
$message = file_get_contents('./partials/register1.html');
$message .= "<br/><h3><strong>ATENCION: Tu cuenta aun no esta activa.</strong></h3>";
$message .= "<br/><a href='https://entradasytickets.com/verify_email?hash=".$hash."'>Por favor haz click aqui para activarla:";
$message .= "<br/>https://entradasytickets.com/verify_email?hash=".$hash;
$message .= "<br/>";
$message .= "<br/>";
$message .= "<br/><h3>¡Gracias por crear tu cuenta!</h3>";
$message .= file_get_contents('./partials/register2.html');
$body = "";
// message
$body .= "--" . $separator . $eol;
$body .= "Content-Type: text/html; charset=\"iso-8859-1\"" . $eol;
$body .= "Content-Transfer-Encoding: 8bit" . $eol . $eol;
$body .= $message . $eol;
$body .= "--" . $separator . $eol;
$body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
$body .= "Content-Transfer-Encoding: 8bit" . $eol . $eol;
$body .= "*Este mensaje se envia con HTML si no lo ves bien por favor configure su navegador" . $eol;
//mail($to, $subject, $body, $headers);
// 4) save the User!
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$logger->info('User register successfully');
$entityManager->flush();
// ... do any other work - like sending them an email, etc
// maybe set a "flash" success message for the user
return $this->redirectToRoute(
'login',
//array('info' => "Para poder seguir adelante tienes que activar la cuenta a través del enlace de confirmación que hemos enviado por correo. IMPORTANTE MIRAR BANDEJA DE SPAM")
array('info' => "Puedes iniciar sesión para comprar las entradas")
);
}else{
$error = "Las contraseñas deben coincidir";
}
}
return $this->render('registration/register.html.twig',array(
'form' => $form->createView(),
'error' => $error,
'info' => $info
));
}
/**
* @Route("/recover_password", name="recover_password")
*/
public function remindpw(UserPasswordEncoderInterface $passwordEncoder, LoggerInterface $logger)
{
$securityContext = $this->container->get('security.authorization_checker');
if ($securityContext->isGranted('IS_AUTHENTICATED_FULLY')) {
return $this->redirectToRoute('main');
}
if (isset($_POST['_email'])) {
$repUser = $this->getDoctrine()->getRepository(User::class);
if ($user = $repUser->findOneByEmail($_POST['_email'])) {
//mandar mail con contraseña generada automaticamente
$psswd = substr(md5(microtime()), 1, 8);
$password = $passwordEncoder->encodePassword($user, $psswd);
$user->setPassword($password);
$to = $user->getEmail();
$from = 'admin@entradasytickets.com';
$subject = 'Tu nueva contraseña en EntradasyTickets';
$separator = md5(time());
$eol = PHP_EOL;
// main header
$headers = "From: " . $from . $eol;
$headers .= "MIME-Version: 1.0" . $eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"";
$message = file_get_contents('./partials/register1.html');
$message .= "<br/>Te hemos generado una nueva contraseña automática:";
$message .= "<br/><h3>".$psswd;
$message .= "</h3><br/>";
$message .= "<br/>Entra en tu cuenta y cambia esta contraseña por la que prefieras.";
$message .= "<br/>";
$message .= "<br/>";
//si no ha activado su cuenta
if (!$user->getisActive()) {
$hash = Helpers::encrypt($to);
$message .= "<br/><h4><strong>ATENCIÓN: Tu cuenta aún no está activa.</strong></h4>";
$message .= "<br/><a href='https://entradasytickets.com/verify_email?hash=".$hash."'>Por favor haz click aquí para activarla:";
$message .= "<br/>https://entradasytickets.com/verify_email?hash=".$hash;
$message .= "<br/>";
$message .= "<br/>";
}
$message .= file_get_contents('./partials/register2.html');
$body = "";
// message
$body .= "--" . $separator . $eol;
$body .= "Content-Type: text/html; charset=\"iso-8859-1\"" . $eol;
$body .= "Content-Transfer-Encoding: 8bit" . $eol . $eol;
$body .= $message . $eol;
mail($to, $subject, $body, $headers);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$logger->info('User new password successfully sent');
$entityManager->flush();
return $this->redirectToRoute(
'login',
array('info' => "Tienes una nueva contraseña en tu buzón de correo electrónico. IMPORTANTE MIRAR BANDEJA DE SPAM")
);
} else {
//sino devolver con error al formulario
return $this->render(
'registration/recoverpw.html.twig',
array('error' => 'El email introducido no está asociado a un usuario registrado.'
)
);
}
}
return $this->render(
'registration/recoverpw.html.twig'
);
}
}