<?php
namespace App\Controller\Advertiser\Generic;
use App\Controller\AbstractClass\AbstractDefaultController;
use App\Controller\Endpoint\DefaultController;
use App\Entity\Advertiser;
use App\Entity\Export;
use App\Entity\News;
use App\Entity\OperationFamily;
use App\Entity\User;
use App\Form\LoginFom;
use App\Form\LostPasswordForm;
use App\Repository\UserRepository;
use App\Service\Access;
use App\Service\AdvertisingManagement;
use App\Service\ContentService;
use App\Service\DataLogger;
use App\Service\EmailService;
use App\Service\Language;
use App\Service\User as UserService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
/**
* Class DefaultController
*/
class GenericDefaultController extends AbstractDefaultController
{
private DataLogger $logger;
private Request $request;
// private RequestStack $requestStack;
public function __construct(RequestStack $requestStack, DataLogger $dataLogger)
{
// $this->requestStack = $requestStack;
$this->logger = $dataLogger;
$this->request = $requestStack->getMainRequest();
}
/**
* @throws \Exception
*/
public function index(Access $access, AdvertisingManagement $advertiserService, ContentService $contentService, EntityManagerInterface $em): Response
{
$access->check('view', null);
$user = $this->getUser();
$advertiser = $advertiserService->getCurrentAdvertiser();
$homepage = $contentService->getHomepage($advertiser);
$operationFamilies = $em->getRepository(OperationFamily::class)->findBy([
'advertiser' => $advertiser,
'status' => true,
]);
$newsList = [];
if (!empty($operationFamilies)) {
foreach ($operationFamilies as $key => $operationFamily) {
$familyNews = $em->getRepository(News::class)->findBy(
[
'operationFamily' => $operationFamily,
'status' => true,
],
['createdAt' => 'DESC'],
2
);
if (!empty($familyNews)) {
$newsList = array_merge($newsList, $familyNews);
}
}
}
return $this->render('homepage/show.html.twig', [
'homepage' => $homepage,
'newsList' => $newsList,
]);
}
/**
* @throws \Exception
*/
public function login(AuthenticationUtils $authenticationUtils, AdvertisingManagement $advertiserService, UserService $userService, UserPasswordHasherInterface $userPasswordHasherInterface, RouterInterface $routerService, TokenStorageInterface $tokenStorage): Response
{
if ($this->isGranted('ROLE_USER')) {
return $this->redirectToRoute('index');
}
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
$this->logger->add('Visualisation de la page login/', null, null, 'info');
$advertiserData = [];
$currentAdvertiser = $advertiserService->getCurrentAdvertiser();
if ($currentAdvertiser instanceof Advertiser) {
$advertiserData = [
'logo' => '/uploads/logos/' . $currentAdvertiser->getLogo(),
'name' => $currentAdvertiser->getTitle(),
'firstColor' => $currentAdvertiser->getFirstColor(),
'secondColor' => $currentAdvertiser->getSecondColor(),
];
}
$goTo = '/';
$gotoSessionValue = $this->request->getSession()->get('rgoto');
if (!empty($gotoSessionValue) && !filter_var($gotoSessionValue, FILTER_VALIDATE_URL)) {
$goTo = $gotoSessionValue;
}
$form = $this->createForm(LoginFom::class);
$form->handleRequest($this->request);
if ($form->isSubmitted() && $form->isValid()) {
$error = 'Aucun compte ne correspond à ces identifiants.';
$datas = $form->getData();
$login = $datas['username'];
$password = $datas['password'];
$user = $userService->getUserByLogin($currentAdvertiser, $login);
if ($user instanceof User) {
if ($userPasswordHasherInterface->isPasswordValid($user, $password)) {
// Manually authenticate user in controller
// $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$token = new UsernamePasswordToken($user, 'main', $user->getRoles());
$tokenStorage->setToken($token);
$this->request->getSession()->set('_security_main', serialize($token));
return $this->redirect($goTo);
}
}
}
return $this->render('default/login.html.twig', [
'form' => $form->createView(),
'last_username' => $lastUsername,
'error' => $error,
'advertiserData' => $advertiserData,
]);
}
/**
* @throws \Exception
*/
public function logout(): Response
{
$user = $this->getUser();
$this->logger->add('Déconnexion', $user instanceof User ? $user->getId() : 0, null, 'info');
$this->request->getSession()->clear();
return $this->redirectToRoute('login');
}
/**
* @throws \Exception
*/
public function lostpassword(UserRepository $repository, EmailService $emailService, EntityManagerInterface $em): Response
{
$form = $this->createForm(LostPasswordForm::class);
$form->handleRequest($this->request);
$msg = '';
$this->logger->add('Visualisation de la page lostpassword/', null, null, 'info');
if ($form->isSubmitted() && $form->isValid()) {
$datas = $form->getData();
$user = $repository->findByEmail($datas['email']);
if (null !== $user) {
$token = uniqid();
$user->setlastToken($token);
$em->flush();
$this->logger->add('Demande de mot de passe par un utilisateur', $user->getId(), null, 'info');
$url = $this->request->getScheme() . '://' . $this->request->getHost() . $this->generateUrl('user_resetpassword', ['token' => $user->getToken()]);
$to = $user->getEmail();
$mailBody = $this->render('emails/lostpassword.html.twig', [
'firstname' => $user->getFirstname(),
'lastname' => $user->getLastname(),
'url' => $url,
]);
$mailPart = $this->render('emails/lostpassword.txt.twig', [
'firstname' => $user->getFirstname(),
'lastname' => $user->getLastname(),
'url' => $url,
]);
$params = [
'part' => $mailPart,
'type' => 'lostpassword',
];
$emailService->send('Lost Password', 'no-reply@staci-animations.com', $to, $mailBody, $params);
}
$msg = 'SENT';
}
return $this->render('default/lostpassword.html.twig', [
'form' => $form->createView(),
'msg' => $msg,
]);
}
/**
* @throws \Exception
*/
public function download(Access $access, EntityManagerInterface $em, AdvertisingManagement $advertiserService): Response
{
$access->check('view', null);
$exportType = [
'Commandes',
'Report',
'Quota',
'Commandes',
'Report',
'Quota',
'Commandes',
'Report',
'Quota',
];
$exportStatus = [
'en attente',
'en cours',
'fini',
'erreur',
];
$currentAdvertiser = $advertiserService->getCurrentAdvertiser();
$downloads = $em->getRepository(Export::class)->findBy([
'user' => $this->getUser(),
'advertiser' => $currentAdvertiser,
]);
$downloadArray = [];
foreach ($downloads as $download) {
$downloadArray[] = [
'uuid' => $download->getUuid(),
'type' => $exportType[$download->getType()],
'date' => !empty($download->getDate()) ? date('d-m-Y H:i', $download->getDate()) : '',
'start' => !empty($download->getStartedAt()) ? date('d-m-Y H:i', $download->getStartedAt()) : '',
'end' => !empty($download->getEndedAt()) ? date('d-m-Y H:i', $download->getEndedAt()) : '',
'status' => $exportStatus[$download->getStatus()],
'file' => $download->getFile(),
];
}
return $this->render('default/download.html.twig', [
'downloadArray' => $downloadArray,
]);
}
/**
* @throws \Exception
*/
public function downloadFile(EntityManagerInterface $em, Access $access, string $uuid): Response
{
$access->check('view', null);
$file = $em->getRepository(Export::class)->findOneBy([
'uuid' => $uuid,
]);
if ($file instanceof Export && $file->getUser() === $this->getUser()) {
return $this->file(__DIR__ . '/../../../../var/exports/' . $file->getFile(), $file->getFile(), ResponseHeaderBag::DISPOSITION_INLINE);
}
return new Response('<html><body></body></html>');
}
public function admin(): Response
{
return new Response('<html><body>Admin page!</body></html>');
}
public function switchLanguage(Language $language, UrlMatcherInterface $urlMatcher): Response
{
$currentLanguage = $language->getLanguage();
$newlanguage = $this->request->query->get('switch-language', $currentLanguage);
if ($currentLanguage !== $newlanguage) {
$language->setLanguage($newlanguage);
}
return $this->redirectToRoute($this->getRefererRoute($urlMatcher));
}
private function getRefererRoute(UrlMatcherInterface $urlMatcher): string
{
$referer = $this->request->headers->get('referer');
$lastPath = substr($referer, \strlen($this->request->getScheme() . '://'));
$lastPath = substr($lastPath, (int) strpos($lastPath, '/'));
try {
$parameters = $urlMatcher->match($lastPath);
return $parameters['_route'];
} catch (ResourceNotFoundException|MethodNotAllowedException) {
return 'index';
}
}
}