<?php
namespace App\Controller;
use App\Entity\Competitor;
use App\Entity\Pharmacovigilance;
use App\Entity\Privacy;
use App\Entity\Profile;
use App\Entity\User;
use App\Form\ContactUs;
use App\Form\PasswordCreationType;
use App\Form\PharmacovigilanceType;
use App\Form\RegistrationType;
use App\Form\Model\Contact;
use App\Service\UserService;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class DefaultController extends AbstractController
{
protected $mr;
public function __construct(ManagerRegistry $managerRegistry)
{
$this->mr = $managerRegistry;
}
/**
* @Route("/", name="homepage")
*/
public function index(Request $request, AuthenticationUtils $authenticationUtils, MailerInterface $mailer): Response
{
if($this->getUser() != null){
if($this->getUser()->getRole() == "ROLE_ADMIN")
return $this->redirectToRoute("admin_index");
elseif($this->getUser()->getRole() == "ROLE_USER")
return $this->redirectToRoute("user_index");
}
$em = $this->mr->getManager();
$registerTab = false;
// LOGIN
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
// REGISTER
$user = new User();
$form = $this->createForm(RegistrationType::class, $user);
$form->handleRequest($request);
if($form->isSubmitted()){
$valid = true;
// TERMINI E CONDIZIONI
if($form->get('terms')->getData() == false){
$valid = false;
$form->get('terms')->addError(new FormError("Per registrarti devi accettare i termini e condizioni di utilizzo."));
$registerTab = true;
}
// PASSWORD RESISTENTE
if($valid){
$psw = $form->get('password')->getData();
$count = 0;
if(preg_match('/[0-9]/', $psw)) $count++;
if(preg_match('/[a-z]/', $psw)) $count++;
if(preg_match('/[A-Z]/', $psw)) $count++;
if(preg_match('/[\!\#\$\&\(\)\.\+\-_]/', $psw)) $count++;
if($count < 3)
{
$valid = false;
$this->addFlash('notice_warning', 'Inserisci una password resistente. Per maggiori informazioni clicca sulla parola RESISTENTE');
$registerTab = true;
}
}
// RECAPTCHA
$path = 'https://www.google.com/recaptcha/api/siteverify?secret=6LfCPG4UAAAAAMY34gnUymU_hzD6Ekpeune_Rnim&response='.$request->request->get("g-recaptcha-response");
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Accept: application/json'));
curl_setopt($ch, CURLOPT_URL,$path);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
$result = curl_exec($ch);
curl_close($ch);
$res = json_decode($result, true);
if($valid && !$res["success"]){
$valid = false;
$this->addFlash('notice_warning', 'Per registrarti devi provare di non essere un robot.');
$registerTab = true;
}
if($valid && $form->isValid()){
// PASSWORD
$encoder = $this->get('security.encoder_factory')->getEncoder($user);
$password = $encoder->encodePassword($form->get('password')->getData(), null);
$user->setPassword($password);
// ONETIMECODE
$user->setOneTimeCode(md5(uniqid()));
// TIPO ACCOUNT FARMACISTA
$accountType = $em->getRepository("App\Entity\AccountType")->findOneBySlug('external');
$user->setAccountType($accountType);
// CREAZIONE CARTELLE
$directoryPath = uniqid();
mkdir($this->getParameter('kernel.project_dir').'/'.$this->getParameter('web_path').'/users/'.$directoryPath);
mkdir($this->getParameter('kernel.project_dir').'/'.$this->getParameter('web_path').'/users/'.$directoryPath.'/personal_documents/');
$user->setDirectoryPath($directoryPath);
// PERSISTO
$em->persist($user);
$em->flush();
// PROFILO
$profile = new Profile();
$profile->setUser($user);
$em->persist($profile);
// PRIVACY
$date = new \DateTime();
$privacy = new Privacy();
$privacy->setUser($user);
$privacy->setIsTermsAccepted(true);
$privacy->setIsNewsAccepted($form->get('news')->getData());
$privacy->setLastUpdateDateTime($date);
$em->persist($privacy);
$em->flush();
$message = (new TemplatedEmail())
->from($this->getParameter('sender_email'))
->to($user->getEmail())
->subject($this->getParameter('object_registration'))
->htmlTemplate('email/account_activation.html.twig')
->context([
'user' => $user
]);
$mailer->send($message);
$this->addFlash('notice_success', "Registrazione completata. Riceverai una e-mail per l'attivazione all'indirizzo email inserito.");
$registerTab = false;
}
}
return $this->render('default/index.html.twig', array(
'last_username' => $lastUsername,
'error' => $error,
'form' => $form->createView(),
'registerTab' => $registerTab
));
}
/**
* @Route("/recupera-password", name="password_recovery")
*/
public function passwordRecovery(Request $request, MailerInterface $mailer)
{
$em = $this->mr->getManager();
$user = $em->getRepository('App\Entity\User')->findOneByEmail($request->request->get('recovery'));
if(!$user){
$this->addFlash('notice_warning', "L'e-mail inserita non รจ associata a nessun account");
}
else{
$user->setOneTimeCode(md5(uniqid()));
$user->setExpirationOneTimeCode(new \Datetime());
$em->persist($user);
$em->flush();
$message = (new TemplatedEmail())
->from($this->getParameter('sender_email'))
->to($user->getEmail())
->subject($this->getParameter('object_recovery'))
->htmlTemplate('email/password_recovery.html.twig')
->context([
'user' => $user
]);
$mailer->send($message);
$this->addFlash('notice_success', "Ti รจ stata inviata una email per creare la tua nuova password");
}
return $this->redirect($request->server->get('HTTP_REFERER'));
}
/**
* @Route("/attiva/{oneTimeCode}", name="registration_activation", requirements={"oneTimeCode" = "[\w\d]{32}"})
*/
public function registrationActivation(Request $request, $oneTimeCode)
{
$this->get('security.token_storage')->setToken(null);
$em = $this->mr->getManager();
$user = $em->getRepository('App\Entity\User')->findOneBy(array('oneTimeCode' => $oneTimeCode));
if(!$user)
$this->addFlash('notice_danger', "Nessun account corrisponde al codice inserito");
else if($user->isIsActive() == 1)
$this->addFlash('notice_warning', "L'account รจ giร stato attivato con successo");
else{
$user->setIsActive(1);
$em->flush();
$this->addFlash('notice_success', "L'Account รจ stato attivato con successo");
}
return $this->redirectToRoute('homepage');
}
/**
* @Route("/crea-password/{oneTimeCode}", name="password_creation", requirements={"oneTimeCode" = "[\w\d]{32}"})
*/
public function passwordCreation(Request $request, UserPasswordHasherInterface $passwordHasher, $oneTimeCode)
{
$em = $this->mr->getManager();
$user = $em->getRepository('App\Entity\User')->findOneBy(array('oneTimeCode' => $oneTimeCode));
$now = new \DateTime('now');
$expiration = date($now->format("YmdHis"), strtotime('+3 hours'));
if($user->getExpirationOneTimeCode() != null){
if($expiration > $user->getExpirationOneTimeCode()->format("YmdHis")){
$form = $this->createForm(PasswordCreationType::class, $user);
$form->handleRequest($request);
if($form->isSubmitted()){
$valid = true;
if($form->get('password')->getData() != null){
$psw = $form->get('password')->getData();
$count = 0;
if(preg_match('/[0-9]/', $psw)) $count++;
if(preg_match('/[a-z]/', $psw)) $count++;
if(preg_match('/[A-Z]/', $psw)) $count++;
if(preg_match('/[\!\#\$\&\(\)\.\+\-_]/', $psw)) $count++;
if($count < 3)
{
$form->get('password')->addError(new FormError("Inserisci una password resistente."));
$valid = false;
}
}
if($valid && $form->isValid()){
$password = $passwordHasher->hashPassword($user, $form->get("password")->getData());
$user->setPassword($password);
$user->setIsActive(1);
$em->flush();
$this->addFlash('notice_success', "La nuova password รจ stata creata correttamente");
return $this->redirectToRoute("homepage");
}
}
return $this->render('default/create_password.html.twig', array(
'oneTimeCode' => $oneTimeCode,
'form' => $form->createView()
));
}
else{
$this->addFlash('notice_warning', "Il cambio password deve avvenire entro 3 ore dalla richiesta.<br> Per modificare la password, effettuare una nuova richiesta.");
return $this->redirectToRoute("homepage");
}
}
else{
$form = $this->createForm(PasswordCreationType::class, $user);
$form->handleRequest($request);
if($form->isSubmitted()){
$valid = true;
if($form->get('password')->getData() != null){
$psw = $form->get('password')->getData();
$count = 0;
if(preg_match('/[0-9]/', $psw)) $count++;
if(preg_match('/[a-z]/', $psw)) $count++;
if(preg_match('/[A-Z]/', $psw)) $count++;
if(preg_match('/[\!\#\$\&\(\)\.\+\-_]/', $psw)) $count++;
if($count < 3)
{
$form->get('password')->addError(new FormError("Inserisci una password resistente. Per maggiori informazioni clicca sulla parola verde RESISTENTE"));
$valid = false;
}
}
if($valid && $form->isValid()){
$password = $passwordHasher->hashPassword($user, $form->get("password")->getData());
$user->setPassword($password);
$user->setIsActive(1);
$em->flush();
$this->addFlash('notice_success', "La nuova password รจ stata creata correttamente");
return $this->redirectToRoute("homepage");
}
}
return $this->render('default/create_password.html.twig', array(
'oneTimeCode' => $oneTimeCode,
'form' => $form->createView()
));
}
}
/**
* @Route("/cookie", name="cookies")
*/
public function cookies(Request $request)
{
return $this->render('default/cookies.html.twig');
}
/**
* @Route("/aggiorna-comuni", name="update_cities")
*/
public function updateCities(Request $request)
{
$em = $this->mr->getManager();
$name = $request->request->get('name');
$cities = $em->getRepository("App\Entity\City")->findByName($name);
$serializer = $this->container->get('serializer');
$jsonCities = $serializer->serialize($cities, 'json');
$response = array("code" => 100, "success" => true, "cities" => $jsonCities);
return new Response(json_encode($response));
}
/**
* @Route("/aggiungi-concorrente", name="add_competitor")
*/
public function addCompetitor(Request $request)
{
$em = $this->mr->getManager();
$value = $request->request->get('value');
$competitor = new Competitor();
$competitor->setValue($value);
$em->persist($competitor);
$em->flush();
$response = array("code" => 100, "success" => true, "id" => $competitor->getId());
return new Response(json_encode($response));
}
/**
* @Route("/aggiorna-concorrenti", name="update_competitors")
*/
public function updateCompetitors(Request $request)
{
$em = $this->mr->getManager();
$value = $request->request->get('value');
$competitors = $em->getRepository("App\Entity\Competitor")->findAllByValue($value);
$first = true;
$json = '[';
foreach($competitors as $c){
if($first)
$first = false;
else
$json .= ',';
$json .= '{ "id":'.$c->getId().', "value":'.json_encode($c->getValue()).'}';
}
$json .= ']';
$response = array("code" => 100, "success" => true, "competitors" => $json);
return new Response(json_encode($response));
}
/**
* @Route("/aggiorna-referenti", name="update_referents")
*/
public function updateReferents(Request $request)
{
$em = $this->mr->getManager();
$filterSurname = $request->request->get('filterSurname');
$filterName = $request->request->get('filterName');
$filterEmail = $request->request->get('filterEmail');
$referents = $em->getRepository("App\Entity\User")->findByAccountTypeAndSurnameAndNameAndEmail($filterSurname, $filterName, $filterEmail);
$refs = array();
if($filterEmail == "")
$refs = $em->getRepository("App\Entity\Referent")->findBySurnameAndName($filterSurname, $filterName);
$first = true;
$jsonReferents = '[';
foreach($referents as $referent){
if($first)
$first = false;
else
$jsonReferents.= ',';
$jsonReferents.= '{"id":"'.$referent->getId().'", "surname":'.json_encode($referent->getSurname()).', "name":'.json_encode($referent->getName()).', "email":'.json_encode($referent->getEmail()).', "phone":'.json_encode($referent->getProfile()->getPhone()).'}';
}
$jsonReferents .= ']';
$first = true;
$jsonRefs = '[';
foreach($refs as $ref){
if($first)
$first = false;
else
$jsonRefs.= ',';
$jsonRefs.= '{"id":"'.$ref->getId().'", "surname":'.json_encode($ref->getSurname()).', "name":'.json_encode($ref->getName()).', "phone":'.json_encode($ref->getPhone()).'}';
}
$jsonRefs .= ']';
$response = array("code" => 100, "success" => true, "referents" => $jsonReferents, "refs" => $jsonRefs);
return new Response(json_encode($response));
}
/**
* @Route("/aggiorna-enti-fatturanti", name="update_hospitals")
*/
public function updateHospitals(Request $request)
{
$em = $this->mr->getManager();
$name = $request->request->get('name');
$city = $request->request->get('city');
$hospitals = $em->getRepository("App\Entity\Hospital")->findHospitalByNameAndCity($name, $city);
$first = true;
$json = '[';
foreach($hospitals as $hospital){
if($first)
$first = false;
else
$json .= ',';
$json .= '{ "id":'.$hospital->getId().', "name":'.json_encode($hospital->getName()).', "city":'.json_encode($hospital->getCity()->getName()).', "address": '.json_encode($hospital->getAddress()).' }';
}
$json .= ']';
$response = array("code" => 100, "success" => true, "hospitals" => $json);
return new Response(json_encode($response));
}
/**
* @Route("/aggiorna-strutture-sanitarie", name="update_facilities")
*/
public function updateFacilities(Request $request)
{
$em = $this->mr->getManager();
$name = $request->request->get('name');
$city = $request->request->get('city');
$facilities = $em->getRepository("App\Entity\Facility")->findFacilityByNameAndCity($name, $city);
$first = true;
$json = '[';
foreach($facilities as $f){
if($first)
$first = false;
else
$json .= ',';
$json .= '{ "id":'.$f->getId().', "name":'.json_encode($f->getName()).', "city":'.json_encode($f->getCity()->getName()).', "address": '.json_encode($f->getAddress()).' }';
}
$json .= ']';
$response = array("code" => 100, "success" => true, "facilities" => $json);
return new Response(json_encode($response));
}
/**
* @Route("/aggiorna-dipartimenti", name="update_departments")
*/
public function updateDepartments(Request $request)
{
$em = $this->mr->getManager();
$facilityId = $request->request->get('facilityId');
$filterValue = $request->request->get('value');
$departments = $em->getRepository("App\Entity\Department")->findByFacilityAndDepartmentType($facilityId, $filterValue);
$first = true;
$jsonDepartments = '[';
foreach($departments as $department){
if($first)
$first = false;
else
$jsonDepartments.= ',';
$jsonDepartments.= '{"id":"'.$department->getId().'", "department":'.json_encode($department->getDepartmentType()->getValue()).', "notes":'.json_encode($department->getNotes()).'}';
}
$jsonDepartments .= ']';
$response = array("code" => 100, "success" => true, "departments" => $jsonDepartments);
return new Response(json_encode($response));
}
/**
* @Route("/aggiorna-tipi-dipartimento", name="update_department_types")
*/
public function updateDepartmentTypes(Request $request)
{
$em = $this->mr->getManager();
$facilityId = $request->request->get('facilityId');
$value = $request->request->get('value');
$notPairedDepartmentTypes = $em->getRepository("App\Entity\DepartmentType")->findNotPairedWithFacilityFiltered($facilityId, $value);
$first = true;
$jsonNotPairedDepartmentTypes = '[';
foreach($notPairedDepartmentTypes as $notPairedDepartmentType){
if($first)
$first = false;
else
$jsonNotPairedDepartmentTypes.= ',';
$jsonNotPairedDepartmentTypes.= '{"id":"'.$notPairedDepartmentType->getId().'", "value":'.json_encode($notPairedDepartmentType->getValue()).'}';
}
$jsonNotPairedDepartmentTypes .= ']';
$response = array("code" => 100, "success" => true, "departmentTypes" => $jsonNotPairedDepartmentTypes);
return new Response(json_encode($response));
}
/**
* @Route("/aggiorna-gruppi-ospedalieri", name="update_hospital_groups")
*/
public function updateHospitalGroups(Request $request)
{
$session = $request->getSession();
$name = $request->request->get('name');
$em = $this->mr->getManager();
$hospitalGroups = $em->getRepository("App\Entity\HospitalGroup")->findByName($name);
$first = true;
$json = '[';
foreach($hospitalGroups as $hg){
if($first)
$first = false;
else
$json.= ',';
$json.= '{"id":"'.$hg->getId().'", "name":'.json_encode($hg->getName()).'}';
}
$json .= ']';
$response = array("code" => 100, "success" => true, "hospitalGroups" => $json);
return new Response(json_encode($response));
}
/**
* @Route("/aggiorna-esterni", name="update_users")
*/
public function updateUsers(Request $request)
{
$em = $this->mr->getManager();
$value = $request->request->get('value');
$users = $em->getRepository("App\Entity\User")->findExternalsBySurnameAndNameAndEmailAndPhone($value);
$first = true;
$jsonUsers = '[';
foreach($users as $u){
if($first)
$first = false;
else
$jsonUsers.= ',';
$jsonUsers.= '{"id":"'.$u->getId().'", "surname":'.json_encode($u->getSurname()).', "name":'.json_encode($u->getName()).', "email":'.json_encode($u->getEmail()).', "phone":'.json_encode($u->getProfile()->getPhone()).'}';
}
$jsonUsers .= ']';
$response = array("code" => 100, "success" => true, "users" => $jsonUsers);
return new Response(json_encode($response));
}
/**
* @Route("/aiuto", name="help")
*/
public function help(Request $request)
{
$em = $this->mr->getManager();
$slug = $request->request->get('slug');
$help = $em->getRepository("App\Entity\Help")->findOneBySlug($slug);
$response = array("code" => 100, "success" => true, "title" => $help->getTitle(), "text" => $help->getText());
return new Response(json_encode($response));
}
/**
* @Route("/logout", name="logout")
*/
public function logout()
{
}
}