<?php
namespace App\Controller;
use App\Entity\General;
use App\Entity\Service;
use App\Repository\ActualiteRepository;
use App\Repository\ArticleRepository;
use App\Repository\BlogRepository;
use App\Repository\CategorieRealisationRepository;
use App\Repository\ClientRepository;
use App\Repository\CookiesRepository;
use App\Repository\EmplacementRepository;
use App\Repository\GeneralRepository;
use App\Repository\ImagesAccueilRepository;
use App\Repository\MentionsLegalesRepository;
use App\Repository\NosGarantiesRepository;
use App\Repository\PolitiqueDeConfidentialiteRepository;
use App\Repository\RealisationRepository;
use App\Repository\ServiceRepository;
use App\Repository\TarifRepository;
use App\Repository\TemoignageRepository;
use Exception;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\String\Slugger\AsciiSlugger;
use Symfony\Component\Yaml\Yaml;
class WebsiteController extends AbstractController
{
public const RELATIVE_PATH_TO_PROJECT_FOLDER = '../';
/**
* @Route("/", name="home")
*/
public function home(NosGarantiesRepository $nosGarantiesRepository, GeneralRepository $generalRepository,RealisationRepository $realisationRepository, ArticleRepository $articleRepository, ActualiteRepository $actualiteRepository,ClientRepository $clientRepository,TemoignageRepository $temoignageRepository,ImagesAccueilRepository $imageAccueilRepository,ServiceRepository $serviceRepository): Response
{
$generalItem = $generalRepository->find(1);
$realisations = $realisationRepository->findAll();
$allActualites = $actualiteRepository->findAll();
$allArticles = $articleRepository->findAll();
$allClient = $clientRepository->findAll();
$allTemoignages = $temoignageRepository->findAll();
$allEngagements = $nosGarantiesRepository->findAll();
$imagesAccueil = $imageAccueilRepository->find(1);
$services = $serviceRepository->findBy([],['id' => 'DESC'],3);
return $this->render('pages/home.html.twig', [
"general" => $generalItem,
'realisations' => array_reverse($realisations),
'actualites' => array_reverse($allActualites),
'clients' => array_reverse($allClient),
'temoignages' => array_reverse($allTemoignages),
'articles' => array_reverse($allArticles),
'engagements' => $allEngagements,
"imageAccueil" => $imagesAccueil,
'services' => $services
]);
}
/**
* @Route("/realisations", name="realisations")
*/
public function realisation(RealisationRepository $realisationRepository,ClientRepository $clientRepository,CategorieRealisationRepository $categorieRealisationRepository): Response
{
$realisations = $realisationRepository->findAll();
$allClient = $clientRepository->findAll();
$categoriesRealisations = $categorieRealisationRepository->findAll();
return $this->render('pages/realisations.html.twig', [
'realisations' => $realisations,
'clients' => $allClient,
'categories' => $categoriesRealisations
]);
}
/**
* @Route("/blogs", name="blogs")
*/
public function blogs(BlogRepository $blogRepository, GeneralRepository $generalRepository): Response
{
$allBlogs = $blogRepository->findAll();
$general = $generalRepository->find(1);
$allBlogs = array_reverse($allBlogs);
return $this->render('pages/blogs.html.twig', [
'blogs' => $allBlogs,
'general' => $general
]);
}
/**
* @Route("/actualites", name="actualites")
*/
public function articles(ArticleRepository $articleRepository, GeneralRepository $generalRepository): Response
{
$allArticles = $articleRepository->findAll();
$general = $generalRepository->find(1);
$allArticles = array_reverse($allArticles);
return $this->render('pages/articles.html.twig', [
'articles' => $allArticles,
'general' => $general
]);
}
/**
* @Route("/social", name="social")
*/
public function actualites(ActualiteRepository $actualiteRepository): Response
{
$allActualites = $actualiteRepository->findAll();
return $this->render('pages/social.html.twig', [
'actualites' => array_reverse($allActualites),
]);
}
/**
* @Route("/cookies", name="cookies")
*/
public function cookies(CookiesRepository $cookieRepo): Response
{
$cookie = $cookieRepo->find(1);
return $this->render('pages/cookies.html.twig', [
'cookies' => $cookie,
]);
}
/**
* @Route("/mentions-legales", name="mentionsLegales")
*/
public function mentionsLegales(MentionsLegalesRepository $mentionsLegalesRepository): Response
{
$mentionsLegales = $mentionsLegalesRepository->find(1);
return $this->render('pages/mentionsLegales.html.twig', [
'mentionsLegales' => $mentionsLegales,
]);
}
/**
* @Route("/politique-de-confidentialite", name="politiqueDeConfidentialite")
*/
public function politiqueDeConfidentialite(PolitiqueDeConfidentialiteRepository $PolitiqueDeConfidentialiteRepository): Response
{
$pdc = $PolitiqueDeConfidentialiteRepository->find(1);
return $this->render('pages/pdc.html.twig', [
'pdc' => $pdc,
]);
}
/**
* @Route("/blog/{id}", name="blog", methods={"GET"})
*/
public function blog(BlogRepository $blogRepository, GeneralRepository $generalRepository,int $id): Response
{
$blog = $blogRepository->find($id);
$general = $generalRepository->find(1);
$nextBlog = $blogRepository->find($blog->getId() +1);
$previousBlog = $blogRepository->find($blog->getId() -1);
$otherBlogs = $blogRepository->findBy([],[],3);
return $this->render('pages/blog.html.twig', [
'blog' => $blog,
'general' => $general,
'nextBlog' => $nextBlog,
'previousBlog' => $previousBlog,
'otherBlogs' => $otherBlogs
]);
}
/**
* @Route("/actualite/{id}", name="actualite", methods={"GET"})
*/
public function actualite(ArticleRepository $articleRepository, GeneralRepository $generalRepository,int $id): Response
{
$article = $articleRepository->find($id);
$general = $generalRepository->find(1);
$nextArticle = $articleRepository->find($article->getId() +1);
$previousArticle = $articleRepository->find($article->getId() -1);
$otherArticles = $articleRepository->findBy([],[],3);
return $this->render('pages/article.html.twig', [
'article' => $article,
'general' => $general,
'nextArticle' => $nextArticle,
'previousArticle' => $previousArticle,
'otherArticles' => $otherArticles
]);
}
/**
* @Route("/contact", name="contact")
*/
public function contact(EmplacementRepository $emplacementRepository,Request $request,MailerInterface $mailer,GeneralRepository $repository): Response
{
if($request->isMethod('POST')){
if($request->files->get('widget-contact-form-file')){
/** @var UploadedFile $file */
$file = $request->files->get('widget-contact-form-file');
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$slugger = new AsciiSlugger();
// this is needed to safely include the file name as part of the URL
$safeFilename = $slugger->slug($originalFilename);
$newFilename = $safeFilename.'-'.uniqid().'.'.$file->guessExtension();
try {
$file->move(
'images/upload',
$newFilename
);
} catch (FileException $e) {
return new JsonResponse(['response' => 'danger','message' => 'Oups, une erreur est survenu pendant l\'envoi de votre fichier, tentez de nous contacter directement par mail.']);
}
};
$name = $request->get('widget-contact-form-name');
$mail = $request->get('widget-contact-form-email');
$phone = $request->get('widget-contact-form-phone');
$message = $request->get('widget-contact-form-message');
$entrepriseName = $repository->find(1)->getNomEntreprise();
$email = (new Email())
->from('do-not-reply@spidertec.fr')
->subject("[$entrepriseName] Nouveau message Client")
->html($this->renderView('email/contact.html.twig',[
'name' => $name,
'email' => $mail,
'message' => $message,
'phone' => $phone,
'entrepriseName' => $entrepriseName
]))
->to($repository->find(1)->getAdresseEmail());
if(isset($file)){
$email->attachFromPath("images/upload/$newFilename");
}
$email->ensureValidity();
$mailer->send($email);
return new JsonResponse(['response' => 'success',"message" => 'Message envoyé']);
}
else{
$text = $request->get('text');
$allEmplacements = $emplacementRepository->findAll();
return $this->render('pages/contact.html.twig', [
'emplacements' => array_reverse($allEmplacements),
'text' => $text
]);
}
}
/**
* @Route("/tarifs" , name="tarifs")
*/
public function tarifs(TarifRepository $tarifRepository){
$allTarifs = $tarifRepository->findBy([],['id' => 'DESC']);
return $this->render('pages/tarifs.html.twig',[
'tarifs' => $allTarifs
]);
}
/**
* @Route("/services", name="services")
*/
public function services(ServiceRepository $serviceRepository): Response
{
$allServices = $serviceRepository->findBy([],['id' => 'DESC']);
return $this->render('pages/services.html.twig', [
'services' => $allServices,
]);
}
/**
* @Route("/service/{id}", name="service", methods={"GET"})
*/
public function service(ServiceRepository $serviceRepository, GeneralRepository $generalRepository,int $id): Response
{
$service = $serviceRepository->find($id);
$general = $generalRepository->find(1);
$nextService = $serviceRepository->find($service->getId() +1);
$previousService = $serviceRepository->find($service->getId() -1);
$otherServices = $serviceRepository->findBy([],[],3);
return $this->render('pages/service.html.twig', [
'service' => $service,
'general' => $general,
'nextService' => $nextService,
'previousService' => $previousService,
'otherServices' => $otherServices
]);
}
/**
* @Route("preview/service/{id}", name="preview-service")
*/
public function previewService(Service $service,ServiceRepository $serviceRepository, GeneralRepository $generalRepository): Response
{
$general = $generalRepository->find(1);
$nextService = $serviceRepository->find($service->getId() +1);
$previousService = $serviceRepository->find($service->getId() -1);
$otherServices = $serviceRepository->findBy([],[],3);
return $this->render('composantsPages/homeComponents/preview/service.html.twig',[
'service' => $service,
'general' => $general,
'nextService' => $nextService,
'previousService' => $previousService,
'otherServices' => $otherServices]);
}
/**
* @Route("qui-sommes-nous", name="page-qui-sommes-nous")
*/
public function pageQuiSommesNous(){
return $this->render('pages/quiSommesNous.html.twig');
}
/**
* @Route("/admin/text-edit",name="text-edit")
* @Route("/admin/text-edit/{slug}",name="text-edit-single")
* @return Response
*/
public function editText(string $slug = null, Request $request)
{
$data = Yaml::parseFile('../translations/messages.fr.yaml');
if ($request->isMethod('POST')) {
$trueData = [];
$datas = $request->request->all();
foreach ($datas as $singleLineKey => $value) {
$accessors = explode('&', $singleLineKey);
$this->setValueByArrayKeys($accessors, $trueData, $value);
}
$yaml = Yaml::dump($trueData);
file_put_contents('../translations/messages.fr.yaml', $yaml);
$data = Yaml::parseFile('../translations/messages.fr.yaml');
if (!is_null($slug)) {
return $this->redirect($request->headers->get('referer'));
}
}
return $this->render('pages/text-edit_ajax.html.twig', [
'data' => $data,
'search' => $slug
]);
}
private function setValueByArrayKeys($array_keys, &$multi, $value)
{
$m = &$multi;
foreach ($array_keys as $k) {
if (!isset($m[$k])) {
$m[$k] = null;
}
$m = &$m[$k];
}
$m = $value;
}
/**
* @Route("/cc",name="cc")
*
*/
public function cc(Request $request,KernelInterface $kernel)
{
General::refreshColor();
if($this->getUser()){
if(in_array('ROLE_ADMIN',$this->getUser()->getRoles())){
$application = new Application($kernel);
$application->setAutoExit(false);
$input = new ArrayInput(['command' => 'cache:clear']);
$output = new NullOutput();
$application->run($input, $output);
return $this->redirect($request->headers->get('referer'));
}
}
throw $this->createAccessDeniedException();
}
/**
* @Route("/status.json",name="website_status")
*/
public function getStatus(Request $request)
{
return new JsonResponse([
'server_name' => $_SERVER['SERVER_NAME'] ?? 'empty',
'server_ip' => $_SERVER['SERVER_ADDR'] ?? 'empty',
'dns_records' => dns_get_record($_SERVER['SERVER_NAME'])
],200,[
'Access-Control-Allow-Origin' => '*'
]);
}
/**
* @Route("/mail-test", name="mail_test")
* @param Request $request
* @param GeneralRepository $repository
* @param MailerInterface $mailer
* @return Response
*/
public function testEmail(Request $request,GeneralRepository $repository,MailerInterface $mailer) : Response
{
$email = (new Email())
->from($repository->find(1)->getAdresseEmail())
->subject("[".$_SERVER['SERVER_NAME']."] Message test de mail")
->html("Mail de test")
->to('test-spidertec@yopmail.com','cadarsir@gmail.com');
try{
$mailer->send($email);
$this->addFlash('success','Envoi d\'email réussi');
} catch (TransportExceptionInterface $e) {
$this->addFlash('danger','Envoi d\'email échoué');
}
return $this->redirect($request->headers->get('referer'));
}
/**
* @Route("/admin/urlset", name="url_api_add")
*/
public function addSet(Request $request)
{
$this->checkClient($request->getClientIp());
$sites = $this->getUrlSetContentFile();
$filePath = self::RELATIVE_PATH_TO_PROJECT_FOLDER.$this->getParameter('sites_file');
$preprod = $request->request->get('preprod');
$preprod_mdp = $request->request->get('preprod_mdp');
$prod = $request->request->get('prod');
$prod_mdp = $request->request->get('prod_mdp');
$name = ucfirst(str_replace('-',' ',$request->request->get('name','')));
if($request->getMethod() == 'POST'){
$toCreate = [];
if(!empty($name))
{
$foundSite = $this->findSite($sites,$name);
if(!is_null($foundSite)){
return new Response("Site déjà existant.",401);
}
$toCreate['name'] = $name;
if(!is_null($preprod)){
$toCreate['preprod'] = $preprod;
if(!is_null($preprod_mdp)){
$toCreate['preprod_mdp'] = $preprod_mdp;
}
}
if(!is_null($prod) && !is_null($prod_mdp)){
$toCreate['prod'] = $prod;
$toCreate['prod_mdp'] = $prod_mdp;
}
$sites[] = $toCreate;
file_put_contents($filePath,json_encode($sites));
return new JsonResponse($this->getUrlSetContentFile());
}
else{
return new Response("Paramètres incorrects.",400);
}
}
else{
return new Response("//todo.",401);
}
}
/**
* @Route("/admin/urlset/get",name="url_api_get")
* @param Request $request
* @return JsonResponse
*/
public function getUrlsSetContent(Request $request)
{
try{
$this->denyAccessUnlessGranted('ROLE_ADMIN');
$content = $this->getUrlSetContentFile();
return new JsonResponse($content);
}catch(Exception $e){
return new JsonResponse([]);
}
}
private function getUrlSetContentFile()
{
$sitesJsonEmplacement = $this->getParameter('sites_file');
$filePath = self::RELATIVE_PATH_TO_PROJECT_FOLDER.$sitesJsonEmplacement;
return json_decode(file_get_contents($filePath),true);
}
private function checkClient($ip){
$authorizedIps = $this->getParameter('api_urlset_authorized_ips');
if(!in_array($ip,$authorizedIps)){
throw new Exception("Client non autorisé");
}
}
private function findSite($sites,$name) : ?array
{
return array_values(array_filter($sites,function(array $site) use ($name){return $site['name'] == $name;}))[0] ?? null;
}
}