<?php
namespace App\Controller\Nordinfo;
use App\Entity\Cantons;
use App\Entity\Commune;
use App\Entity\Contact;
use App\Entity\ContactRequest;
use App\Entity\CustomForm;
use App\Entity\EventType;
use App\Entity\FileImport;
use App\Entity\Footer;
use App\Entity\FooterSites;
use App\Entity\FormulaireThematique;
use App\Entity\Glossaire;
use App\Entity\Service;
use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use App\Entity\Pages;
use App\Entity\Post;
use SendGrid\Mail\TypeException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\Organization;
use Symfony\Component\HttpFoundation\Response;
use App\Entity\PostCommentaires;
use App\Entity\Ics;
use App\Entity\InscritNewsletter;
use App\Entity\Lieu;
use App\Entity\LogEs;
use App\Entity\MailElu;
use App\Entity\MenuLibelle;
use App\Entity\PagesLegales;
use App\Entity\PostReponses;
use App\Entity\PostType;
use App\Entity\RssArticle;
use App\Entity\RssEvent;
use App\Entity\Statut;
use App\Entity\Tags;
use App\Entity\TargetPublic;
use App\Entity\Territory;
use App\Entity\Topic;
use App\Entity\TypeOrganisation;
use App\Entity\TypeSupport;
use App\Utilities\Feed;
use Dompdf\Dompdf;
use Dompdf\Options;
use App\Entity\User;
use App\Service\AgendaService;
use App\Service\ElasticsearchService;
use App\Service\EpingleService;
use App\Service\MailService;
use App\Service\SchemaService;
use App\Service\RssService;
use App\Service\SendgridMailService;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\RouterInterface;
use App\Utilities\NewFeed;
/**
* @method User getUser()
*/
#[Route(host: "nordinfo.spontaneit.fr")]
//#[Route(host: "info.lenord.fr")]
//#[Route(host:"localhost")]
class MainController extends AbstractController
{
protected mixed $params = [];
protected mixed $arr_intranet = ['admin', 'superadmin', 'redacteur', 'agent'];
public function __construct(
protected EntityManagerInterface $em,
private UserPasswordHasherInterface $hasher,
private Feed $feedUtilities,
private MailService $mail_service,
private SchemaService $schema_service,
private RssService $rss_service,
private EpingleService $epingle_service,
private SendgridMailService $sendgrid_service,
private AgendaService $agenda_service,
private ElasticsearchService $es_service,
private RouterInterface $router,
private NewFeed $new_feed_utilities,
) {
$this->params['admin'] = false;
$this->params['actus'] = false;
$this->params['breadcrumb'] = [];
$this->params['is_pdf'] = 0;
$this->params['is_preview'] = 0;
$this->params['meta_desc'] = "Retrouvez toute l'actualité du Département du Nord sur Nord info - Reportages, initiatives locales, agenda culturel, dossiers thématiques, vidéos, réseaux sociaux,... Nord info, le Département est là !";
$this->params['items_offset'] = 50;
$this->params['initial_limit'] = 50;
$this->params['count_limit'] = 300;
$this->getMenusTop();
$this->getMenusProfile();
$this->params['epingles'] = [];
$this->params['footer'] = $this->em->getRepository(Footer::class)->find(1);
}
#[Route(path: '/', name: 'index')]
public function index(): RedirectResponse
{
return $this->redirect('info');
}
#[Route(path: '/glossaire', name: 'nordinfo_glossaire')]
public function glossaire(Request $request): response
{
$this->params['title'] = "Glossaire";
$this->params['meta_description'] = "Le glossaire du site du Département du Nord : acronymes et définitions utiles";
$glossaire = $this->em->getRepository(Glossaire::class)->findBy([], ['terme' => 'ASC']);
$this->params['glossaires'] = $glossaire;
$this->params['letters'] = $this->em->getRepository(Glossaire::class)->getFirstLetters();
$this->params['breadcrumb'] = [['alias' => '/', 'titre' => 'Accueil'], ['alias' => '', 'titre' => 'Glossaire']];
//$this->params['seo_breadcrumb'] = json_encode($this->seo_service->getSeoBreadcrumb($this->params['breadcrumb'], $request), JSON_UNESCAPED_SLASHES|JSON_HEX_APOS);
$this->params['referer'] = $request->headers->get('referer');
return $this->render('Nordinfo/Main/glossaire.html.twig', $this->params);
}
#[Route(path: '/le-departement', name: 'departement')]
public function departement(Request $request): Response
{
$this->params['env'] = getenv('APP_ENV');
$this->params['referer'] = $request->headers->get('referer');
$this->params['title'] = "Comprendre le département";
$this->params['posts'] = $this->em->getRepository(Pages::class)->getPages(1);
$this->params['type_organisations'] = $this->em->getRepository(TypeOrganisation::class)->findAll();
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
$epingles_ = $this->epingle_service->getEpinglesSection('ledepartement');
foreach ($epingles_ as $epingle) {
array_push($this->params['epingles'], $epingle);
}
return $this->render('Nordinfo/Main/comprendredepartement.html.twig', $this->params);
}
#[Route(path: '/api/post_get_content/{id}', name: 'api_get_content')]
public function post_get_content(Request $request, int $id): Response
{
$post = $this->em->getRepository(Post::class)->find($id);
$content = null;
if ($post->getContent() != null) {
$content = $this->feedUtilities->jsonToHtml($post->getContent(), $request);
}
return new JsonResponse(['content' => $content]);
}
#[Route(path: '/wemap_test', name: 'wemap_test')]
public function wemap_test(): Response
{
//$this->params['pois'] = $this->wemap_service->getAllPois()->results;
return $this->render('Nordinfo/Main/demo-post.html.twig', $this->params);
}
#[Route(path: '/xml/events2evasion.xml', name: 'get_events_nordevasion')]
public function get_events_nordevasion(Request $request): Response
{
$response = new Response($this->rss_service->getXmlNordevasion($this->router, $request->getHost()));
$response->headers->set('Content-Type', 'text/xml');
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
}
#[Route(path: '/rss/{alias}', name: 'rss_article')]
public function rssarticle(string $alias): Response
{
$rssarticle = $this->em->getRepository(RssArticle::class)->findOneBy(['alias' => $alias]);
$response = new Response($this->rss_service->getXmlArticle($rssarticle));
$response->headers->set('Content-Type', 'text/xml');
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
}
#[Route(path: '/rss-event/{alias}', name: 'rss_event')]
public function rssevent(string $alias): Response
{
$rssarticle = $this->em->getRepository(RssEvent::class)->findOneBy(['alias' => $alias]);
$response = new Response($this->rss_service->getXmlEvent($rssarticle));
$response->headers->set('Content-Type', 'text/xml');
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
}
public function import_event(): void
{
ini_set('memory_limit', '-1');
ini_set('max_execution_time', '3000');
$path = $this->get('kernel')->getRootDir() . '/../';
$file = $path . 'RDV-nature-pour-Nord-info.xlsx_5e5e5bb5b9ca6.xlsx';
$fileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($file);
$l = 0;
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($fileType);
$spreadsheet = $reader->load($file);
$datas = $spreadsheet->getSheet(0)->toArray(null, true, true, true);
$type = $this->em->getRepository(EventType::class)->find(8);
$topic = $this->em->getRepository(Topic::class)->find(9);
$status = $this->em->getRepository(Statut::class)->find(1);
$post_type = $this->em->getRepository(PostType::class)->find(8);
$date = new DateTime();
foreach ($datas as $d) {
$l++;
if ($l > 1) {
$territory = $this->em->getRepository(Territory::class)->findOneBy(['display_name' => $d['K']]);
$post = new Post;
$post
->setType($post_type)
->setTitle($d['A'])
->setSubtitle($d['B'])
->setDateDebut($d['C'])
->setDateFin($d['D'])
->setHoraires($d['E'])
->setTarifs($d['F'])
->setLieu($d['H'])
->addEventType($type)
->setVille($d['I'])
->addTopic($topic)
->setOrganizedBy($d['L'])
->setContent($d['M'])
->setStatus($status)
->setCreatedAt($date->format('d/m/Y'))
->setOrganisation4($d['N']);
if ($territory != null) {
$post->addTerritory($territory);
}
$this->em->persist($post);
}
}
$this->em->flush();
}
/*private function xmlToArray(\SimpleXMLElement $xml): mixed
{
$parser = function (\SimpleXMLElement $xml, array $collection = []) use (&$parser) {
$nodes = $xml->children();
$attributes = $xml->attributes();
if (0 !== ($attributes === null ? 0 : count($attributes))) {
foreach ($attributes as $attrName => $attrValue) {
$collection['attributes'][$attrName] = strval($attrValue);
}
}
if (0 === $nodes->count()) {
$collection['value'] = strval($xml);
return $collection;
}
foreach ($nodes as $nodeName => $nodeValue) {
if (($nodeValue->xpath('../' . $nodeName) === null ? 0 : count($nodeValue->xpath('../' . $nodeName))) < 2) {
$collection[$nodeName] = $parser($nodeValue);
continue;
}
$collection[$nodeName][] = $parser($nodeValue);
}
return $collection;
};
return [
$xml->getName() => $parser($xml)
];
}*/
#[Route(path: '/console2020/traitement', name: 'traitement')]
public function traitement(Request $request): RedirectResponse
{
$get = $request->query;
$myFile = $this->em->getRepository(FileImport::class)
->find($get->get('id'));
$path = $this->get('kernel')->getRootDir() . "/../public/upload/imports/";
$inputFileName = $path . $myFile->getFilename();
$string = file_get_contents($inputFileName);
if ($string === false) {
dd('error');
}
$json = json_decode($string, null, 512, JSON_THROW_ON_ERROR);
foreach ($json->posts as $actu) {
$post = new Post;
$user_cr = $this->em->getRepository(User::class)->find(38);
$public = $this->em->getRepository(TargetPublic::class)->find(4);
$type = $this->em->getRepository(PostType::class)->find(8);
$status = $this->em->getRepository(Statut::class)->find(5);
$contenu = null;
$description = null;
$content = null;
(property_exists($actu, 'titre') == true) ? $post->setTitle($actu->titre) : $post->setTitle(null);
(property_exists($actu, 'description') == true) ? $description = $actu->description : $description = null;
(property_exists($actu, 'contenu') == true) ? $content = $actu->contenu : $content = null;
(property_exists($actu, 'illustration') == true) ? $post->setIllustrationdetailName($actu->illustration) : $post->setIllustrationdetailName(null);
(property_exists($actu, 'illustration') == true) ? $post->setIllustrationfilName($actu->illustration) : $post->setIllustrationfilName(null);
$description = str_replace('</h2><BR/>', '</h2>', (string)$description);
$description = str_replace('<br></br>', '<br>', $description);
$description = str_replace('<br /> <br />', '<br>', $description);
$description = str_replace('<br></br>', '<br>', $description);
$description = str_replace('<BR></BR>', '<br>', $description);
$description = str_replace('<b><b>', '<b>', $description);
$description = str_replace('</b> </b>', '</b>', $description);
$description = str_replace('<strong>', '<b>', $description);
$description = str_replace('</strong>', '</b>', $description);
$description = str_replace('<div class="wysiwyg wysiwyg">', ' ', $description);
$description = str_replace('<div class="wysiwyg classic">', ' ', $description);
$description = str_replace('<div>', ' ', $description);
$description = str_replace('</div>', ' ', $description);
$description = str_replace('style="text-align: center "', ' ', $description);
$description = str_replace('style="text-decoration: underline "', ' ', $description);
$description = str_replace('style="border: 1px solid black "', ' ', $description);
$description = str_replace('id="paragraphe0" class="titreContenu"', ' ', $description);
$description = str_replace('style="color: #000000 "', ' ', $description);
$description = str_replace('<p> </p>', ' ', $description);
$description = str_replace('id="document" class="document"', ' ', $description);
$description = str_replace('color: #xxxxxx', ' ', $description);
$description = str_replace('<strong> </strong>', ' ', $description);
$description = str_replace('class="font-weight-bold"', ' ', $description);
$description = str_replace('<p style="text-align: center "> </p>', ' ', $description);
$description = str_replace('<h2></h2>', ' ', $description);
$description = str_replace('<em></em>', ' ', $description);
$description = str_replace('<img></img>', ' ', $description);
$description = str_replace('<span></span>', ' ', $description);
$content = str_replace('</h2><BR/>', '</h2>', (string)$content);
$content = str_replace('<br></br>', '<br>', $content);
$content = str_replace('<br /> <br />', '<br>', $content);
$content = str_replace('<br></br>', '<br>', $content);
$content = str_replace('<BR></BR>', '<br>', $content);
$content = str_replace('<b><b>', '<b>', $content);
$content = str_replace('</b> </b>', '</b>', $content);
$content = str_replace('<strong>', '<b>', $content);
$content = str_replace('</strong>', '</b>', $content);
$content = str_replace('<div class="wysiwyg wysiwyg">', ' ', $content);
$content = str_replace('<div class="wysiwyg classic">', ' ', $content);
$content = str_replace('<div>', ' ', $content);
$content = str_replace('</div>', ' ', $content);
$content = str_replace('style="text-align: center "', ' ', $content);
$content = str_replace('style="text-decoration: underline "', ' ', $content);
$content = str_replace('style="border: 1px solid black "', ' ', $content);
$content = str_replace('id="paragraphe0" class="titreContenu"', ' ', $content);
$content = str_replace('style="color: #000000 "', ' ', $content);
$content = str_replace('<p> </p>', ' ', $content);
$content = str_replace('id="document" class="document"', ' ', $content);
$content = str_replace('color: #xxxxxx', ' ', $content);
$content = str_replace('<strong> </strong>', ' ', $content);
$content = str_replace('class="font-weight-bold"', ' ', $content);
$content = str_replace('<p style="text-align: center "> </p>', ' ', $content);
$content = str_replace('<h2></h2>', ' ', $content);
$content = str_replace('<em></em>', ' ', $content);
$content = str_replace('<img></img>', ' ', $content);
$content = str_replace('<span></span>', ' ', $content);
$post->setShortDescription($description);
$post->setContent($content);
$topic = $this->em->getRepository(Topic::class)->find(12);
$post
->setLink1("Retrouvez le détail de cet article en cliquant sur ce lien")
->setUrl1("https://contact.lenord.fr/contact/" . $actu->_id)
->addTopic($topic)
->setEpingle1(false)
->setEpingle2(false)
->setCreatedBy($user_cr)
->addTargetpublic($public)
->setType($type)
->setCreatedAt($actu->datePublication)
->setDateDebut($actu->datePublication)
->setUpdatedAt($actu->datePublication)
->setStatus($status)
->setSlug($this->get('url_service')->formatAlias($actu->titre));
$this->em->persist($post);
$myFile->setTraite(true)
->setDate(new DateTime);
$this->em->persist($myFile);
}
$this->em->flush();
return $this->redirectToRoute('easyadmin', [
'action' => 'list',
'entity' => $request->query->get('entity')
]);
}
#[Route(path: '/favoris', name: 'favoris')]
public function favoris(Request $request): mixed
{
$this->params['title'] = "Favoris";
$this->params['tagbar'] = false;
$this->params['posts'] = $this->getFavoris($request);
$this->params['items_total'] = sizeof($this->params['posts']);
$this->params['show_date_bar'] = 0;
$this->params['is_favorites_page'] = 1;
$this->params['referer'] = $request->headers->get('referer');
$this->params['breadcrumb'] = $this->setBreadCrumb(null, 'Mes Favoris');
if ($this->params['initial_limit'] != 0) {
array_splice($this->params['posts'], $this->params['initial_limit'], (is_countable($this->params['posts']) ? count($this->params['posts']) : 0) - 1);
}
//Epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
return $this->render('Nordinfo/Main/gabarit_list.html.twig', $this->params);
}
private function getFavoris(Request $request): mixed
{
$post_ids = [];
$user = $this->getUser();
if ($user !== null) {
foreach ($user->getFavoris() as $favori) {
array_push($post_ids, (int)$favori->getId());
}
} else {
$posts = explode(',', $request->cookies->get('favorite'));
foreach ($posts as $index => $value) {
array_push($post_ids, (int)$value);
}
}
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
return $this->em->getRepository(Post::class)->myFavorite(array_values($post_ids));
}
#[Route(path: '/commenter/{token}', name: 'commenter')]
public function commenter(Request $request, string $token): Response
{
$tab = [];
$content = $request->request->get('content');
$params = $request->request;
$commentaire = $this->em->getRepository(PostCommentaires::class)->findOneBy(['token' => $token]);
$post = $commentaire->getPost();
$post->setCommentCount($post->getCommentCount() + 1);
$this->em->persist($post);
$valide = $params->get('validationCheck');
$commentaire
->setValide(($valide != null) ? true : false)
->setDateComment(new DateTime)
->setContent($content);
$this->em->persist($commentaire);
$this->em->flush();
$this->params['post'] = $post;
$content_post = null;
if ($post->getContent() != null) {
$content_post = $this->feedUtilities->jsonToHtml($post->getContent(), $request);
}
$this->params['content_post'] = $content_post;
//Mail
$expediteur = [];
$tab['address'] = ['email' => $commentaire->getAuteur(), 'name' => $commentaire->getAuteur()];
array_push($expediteur, $tab);
$date = new DateTime;
$content_mail = $this->renderView(
'Nordinfo/Mails/commentaire.html.twig',
['titre_article' => $post->getTitle(), 'date_jour' => $date->format('d/m/Y'), 'heure_jour' => $date->format('H:i'), 'url_article' => 'https://info.lenord.fr/' . $post->getSlug(), 'message' => $content]
);
$this->sendgrid_service->send([$commentaire->getAuteur()], $content_mail, "Merci pour votre commentaire");
//$this->mail_service->sendTransacEmail('nordinfo@info-lenord.fr', 'Nord info contact', $commentaire->getAuteur(), $content_mail, "Merci pour votre commentaire");
//mail auteur du post
$dest = [];
$tab['address'] = ['email' => $post->getCreatedBy()->getEmail(), 'name' => $post->getCreatedBy()->getEmail()];
array_push($dest, $tab);
$content_mail_post = $this->renderView(
'Nordinfo/Mails/commentaire_dest.html.twig',
['titre_article' => $post->getTitle(), 'date_jour' => $date->format('d/m/Y'), 'heure_jour' => $date->format('H:i'), 'url_article' => 'https://info.lenord.fr/' . $post->getSlug(), 'message' => $content]
);
$this->mail_service->sendTransacEmail('nordinfo@info-lenord.fr', 'Nord info contact', $post->getCreatedBy()->getEmail(), $content_mail_post, "Merci pour votre commentaire");
$this->params['com'] = $commentaire;
$this->params['message'] = "Merci, votre commentaire a bien été transmis à l'auteur de l'article.";
return $this->render('Nordinfo/Main/endcommentaire.html.twig', $this->params);
}
#[Route(path: '/error', name: 'error')]
public function error(Request $request): Response
{
return $this->render('bundles/TwigBundle/Exception/error404.html.twig', $this->params);
}
#[Route(path: '/comment/{token}', name: 'comment_post')]
public function commentPost(Request $request, string $token): Response
{
$comm = $this->em->getRepository(PostCommentaires::class)->findOneBy(['token' => $token]);
if ($comm == null) {
return $this->redirectToRoute('error', ['_format' => 'html', 'code' => '404']);
}
$date = new DateTime;
if ($date > $comm->getDate()) {
return $this->redirectToRoute('error', ['_format' => 'html', 'code' => '404']);
}
$this->params['post'] = $post = $comm->getPost();
$content_post = null;
if ($post->getContent() != null) {
$content_post = $this->feedUtilities->jsonToHtml($post->getContent(), $request);
}
$this->params['content_post'] = $content_post;
$this->params['com'] = $comm;
return $this->render('Nordinfo/Main/feedback.html.twig', $this->params);
}
#[Route(path: '/save', name: 'save_only')]
public function saveonly(Request $request): Response
{
$form_parameters = null;
if ($request->query->get('article') != null) {
$form_parameters = $request->query->get('article');
} else if ($request->query->get('postevent') != null) {
$form_parameters = $request->query->get('postevent');
}
$post = $this->em->getRepository(Post::class)->find($request->query->get('id'));
$querybuilder = $this->em->createQueryBuilder()
->update()
->from(Post::class, 'post')
->where('post.id = :id')
->setParameter('id', $request->query->get('id'));
foreach ((array)$form_parameters as $index => $value) {
if ($index == 'topics') {
$post->getTopics()->clear();
foreach ($value as $id) {
$topic = $this->em->getRepository(Topic::class)->find($id);
$post->addTopic($topic);
}
} else if ($index == 'territories') {
$post->getTerritories()->clear();
foreach ($value as $id) {
$topic = $this->em->getRepository(Territory::class)->find($id);
$post->addTerritory($topic);
}
} else if ($index == 'targetpublics') {
$post->getTargetpublics()->clear();
foreach ($value as $id) {
$topic = $this->em->getRepository(TargetPublic::class)->find($id);
$post->addTargetpublic($topic);
}
} else if ($index != '_token') {
$querybuilder = $this->setValue($querybuilder, $index, $value);
}
}
$querybuilder->getQuery()
->getSingleScalarResult();
$this->em->persist($post);
$this->em->flush();
return new Response('ok');
}
private function setValue(mixed $querybuilder, mixed $index, mixed $value): mixed
{
//Many to many relations
$querybuilder->set('post.' . $index, ':' . $index)
->setParameter(':' . $index, ($value == "") ? null : $value);
return $querybuilder;
}
/**
* @throws TypeException
*/
#[Route(path: '/form-event', name: 'send_form_event')]
public function sendformEvent(Request $request): Response
{
$post = $request->request;
$result_ = $post->get('nb1') + $post->get('nb2');
if ($result_ == $post->get('captcha') && $post->get('raison') == null) {
$event_type = $this->em->getRepository(EventType::class)->find($post->get('type'));
$date_debut = date_create_from_format('d/m/Y', $post->get('date_debut'));
$date_fin = date_create_from_format('d/m/Y', $post->get('date_fin'));
$auth_extension = ['png', 'jpg', 'jpeg', 'gif', 'pdf'];
$mime_authorized = ['application/pdf', 'image/jpg', 'image/jpeg', 'image/gif', 'image/png'];
$file = null;
$fileName = null;
if ($request->files->get('image') != null) {
$file = $request->files->get('image');
$fileType = $file->getClientMimeType();
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
$fileName = $safeFilename . '-' . uniqid('', true) . '.' . $file->guessExtension();
$uploadDir = $this->getParameter('kernel.project_dir') . '/public/upload/images/';
if (in_array($fileType, $mime_authorized, true) && in_array($file->guessExtension(), $auth_extension, true)) {
try {
$file->move($uploadDir, $fileName);
} catch (FileException) {
$file = null;
$this->params['message'] = 'File could not be uploaded';
return $this->render('Nordinfo/Main/endformerror.html.twig', $this->params);
}
} else {
$file = null;
$this->params['message'] = "Mauvais format d'image";
return $this->render('Nordinfo/Main/endformerror.html.twig', $this->params);
}
}
$destinataires_sendgrid = [];
$dests = "olivier.carpentier@spontaneit.fr;nordinfo@lenord.fr;agenda.nordinfo@lenord.fr";
if ($post->get('dest') != null) {
$dests .= ";" . $post->get('dest');
}
$param_d = explode(';', $dests);
foreach ($param_d as $value) {
$destinataires_sendgrid[] = $value;
}
$m_horaires = ($post->get('horaires') != null) ? '<br><b>Horaires :</b> ' . $post->get('horaires') : '';
$m_tarifs = ($post->get('tarifs') != null) ? '<br><b>Tarifs :</b> ' . $post->get('tarifs') : '';
$m_email = ($post->get('email') != null) ? '<br><b>Adresse courriel pour informations complémentaires et/ou réservation :</b> ' . $post->get('email') : '';
$m_adresse = ($post->get('adresse') != null) ? '<br><b>Adresse :</b> ' . $post->get('adresse') : '';
$m_telephone = ($post->get('telephone') != null) ? '<br><b>Contact téléphonique pour informations complémentaires et/ou réservation :</b> ' . $post->get('telephone') : '';
$m_lien1 = ($post->get('lien1') != null) ? '<br><b>Lien utile 1 :</b> ' . $post->get('lien1') : '';
$m_lien2 = ($post->get('lien2') != null) ? '<br><b>Lien utile 2 :</b> ' . $post->get('lien2') : '';
$message =
'<b>Organisateur :</b> ' . $post->get('organisateur')
. "<br><b>Email de l'organisateur :</b> " . $post->get('email_organisateur')
. "<br><b>Titre de l'évènement :</b> " . $post->get('titre')
. '<br><b>Type de manifestation :</b> ' . $event_type?->getDisplayName()
. '<br><b>Lieu (Salle, lieu dit, Bâtiment) :</b> ' . $post->get('lieu')
. $m_adresse
. '<br><b>Code postal :</b> ' . $post->get('code_postal')
. '<br><b>Ville :</b> ' . $post->get('ville')
. '<br><b>Date de début :</b> ' . $date_debut->format('d/m/Y')
. '<br><b>Date de fin :</b> ' . $date_fin->format('d/m/Y')
. $m_horaires
. $m_tarifs
. '<br><b>Présentation :</b> ' . $post->get('presentation')
. $m_email
. $m_telephone
. $m_lien1
. $m_lien2;
$content_mail = $this->renderView(
'Nordinfo/Mails/proposerevent_exp2.html.twig',
['titre' => $post->get('titre'), 'message' => $message, 'nom_fichier' => $fileName]
);
$this->sendgrid_service->send([$post->get('email_organisateur')], $content_mail, "Merci pour votre évènement", null, $file);
$content_mail = $this->renderView(
'Nordinfo/Mails/proposerevent_dest2.html.twig',
['titre' => $post->get('titre'), 'message' => $message, 'nom_fichier' => $fileName]
);
$this->sendgrid_service->send($destinataires_sendgrid, $content_mail, "Nouvelle proposition d'évènement", null, $file);
//event en base
$post_type = $this->em->getRepository(PostType::class)->find(3);
$status = $this->em->getRepository(Statut::class)->find(1);
$auteur = $this->em->getRepository(User::class)->find(30);
$public = $this->em->getRepository(TargetPublic::class)->find(1);
$event = new Post;
$now = time();
$description = $post->get('presentation');
$description = str_replace('"', '\\"', $description);
$description = nl2br($description);
$description = str_replace(["\r", "\n"], '', $description);
$contentJson = '{"time":' . $now . ',"blocks":[{"type":"paragraph","data":{"text":"' . $description . '"}}';
if ($post->get('email') != null) {
$contentJson .= ', {"type":"paragraph","data":{"text":"Adresse courriel pour informations complémentaires et/ou réservation : <a href=\"mailto:' . $post->get('email') . '\">' . $post->get('email') . '</a>"}}],"version":"2.15.0"}';
} else {
$contentJson .= '],"version":"2.15.0"}';
}
$lieu = ($post->get('adresse') != null) ? $post->get('adresse') : null;
$lieu .= ($lieu != null) ? ', ' : null;
$lieu .= $post->get('lieu');
$json = '{"modeDates":"range","datesRange":{"dateStart":"' . $post->get('date_debut') . '","dateFinish":"' . $post->get('date_fin') . '","dates":[],"modeHours":"simple","hoursDetails":[],"hoursSimple":[{"hour1":"' . $post->get('heure_debut') . '","hour2":"' . $post->get('heure_fin') . '","hour3":"","hour4":""}]},"dateSingle":{"dates":[""],"hoursSimple":[{"hour1":"","hour2":"","hour3":"","hour4":""}]},"datesMultiple":{"dates":[""],"modeHours":"details","hoursDetails":[],"hoursSimple":[{"hour1":"","hour2":"","hour3":"","hour4":""}]}}';
$commune = $this->em->getRepository(Commune::class)->findOneBy(['commune' => $post->get('ville')]);
if ($commune !== null) {
$event->addTerritory($commune->getTerritoire());
}
//LIEU
$str_adresse = $post->get('adresse') . ', ' . $post->get('code_postal') . ', ' . $post->get('ville');
$lieu_new = $this->em->getRepository(Lieu::class)->findOneBy(['adresse' => $str_adresse]);
if ($lieu_new == null) {
$lieu_new = new Lieu;
$lieu_new->setName($post->get('lieu'))
->setAdresse($str_adresse)
->setCodepostal($post->get('code_postal'));
$this->em->persist($lieu_new);
$this->em->flush();
}
$event->setTitle($post->get('titre'))
->setIllustrationfilName($fileName)
->setLieuNew($lieu_new)
->setType($post_type)
->addEventType($event_type)
->addTargetPublic($public)
->setOrganisation4($post->get('adresse') . ' ' . $post->get('code_postal') . ' ' . $post->get('lieu'))
->setHoraires($post->get('horaires'))
->setTarifs($post->get('tarifs'))
->setOrganizedBy($post->get('organisateur'))
->setCommentaires("Organisateur de l'évènement = " . $post->get('email_organisateur') . ($post->get('email') !== null) ? ', Contact et réservation= ' . $post->get('email') . '\n' . ' COPIE DE LA DESCRIPTION:' . $description : null)
->setUrl1($post->get('lien1'))
->setLink1($post->get('lien1'))
->setUrl2($post->get('lien2'))
->setLink2($post->get('lien2'))
->setStatus($status)
->setCreatedBy($auteur)
->setContent($contentJson)
->setLieu($lieu)
->setVille($post->get('ville'))
->setDateDebut($date_debut->format('d/m/Y'))
->setDateFin($date_fin->format('d/m/Y'))
->setJson($json)
->setEpingle1(false)
->setEpingle2(false)
->setDefautFil(false);
$this->em->persist($event);
$this->em->flush();
} else {
$this->params['message'] = 'Captcha erreur';
return $this->render('Nordinfo/Main/endformerror.html.twig', $this->params);
}
return $this->render('Nordinfo/Main/endform.html.twig', $this->params);
}
#[Route(path: '/confirmation', name: 'send_form')]
public function sendform(Request $request): Response
{
$destinataires_sendgrid = [];
$post = $request->request;
$formThematique = $this->em->getRepository(FormulaireThematique::class)->find($post->get('objet'));
$message = $post->get('message');
///AJOUT
if ($formThematique !== null) {
$formThematique = $this->em->getRepository(FormulaireThematique::class)->find($post->get('thematique'));
$objet = $formThematique->getName();
$emails = explode(";", (string) $formThematique->getDestinataires());
for ($i = 0; $i < count($emails); $i++) {
array_push($destinataires_sendgrid, $emails[$i]);
}
} else {
$objet = 'Message à un(e) élu(e) : ' . $request->request->get('dest_nom');
if (str_contains($request->request->get('dest'), ";") == true) {
$ex = explode(";", $request->request->get('dest'));
for($i=0;$i<count($ex);$i++){
array_push($destinataires_sendgrid, $ex[$i]);
}
} else {
array_push($destinataires_sendgrid, $request->request->get('dest'));
}
$mail_elu = new MailElu;
$userIp = $request->getClientIp();
$mail_elu->setDate(new DateTime())
->setElu($request->request->get('dest_nom'))
->setContenu($message)
->setIp($userIp)
->setEmail($post->get('email'));
$this->em->persist($mail_elu);
$this->em->flush();
}
///AJOUT
//exp
//destinataire_
//objet_
//message_
//piece_jointe_
$fileName = null;
$auth_extension = ['png', 'jpg', 'jpeg', 'gif', 'pdf'];
$mime_authorized = ['application/pdf', 'image/jpg', 'image/jpeg', 'image/gif', 'image/png'];
$file = null;
$newname = uniqid();
if ($request->files != null && $request->files->get('file') != null) {
$file = $request->files->get('file');
$fileName = $file->getClientOriginalName();
$fileType = $file->getClientMimeType();
if (in_array($file->guessExtension(), $auth_extension) && in_array($fileType, $mime_authorized)) {
/*try {
$file->move($uploadDir, $newname.'.'.$file->guessExtension());
array_push($files, array(
'name' => $newname.'.'.$file->guessExtension(),
'type' => $fileType,
'data' => $fileData,
));
} catch (FileException) {
$file = null;
return new JsonResponse(['error' => 'File could not be uploaded']);
}*/
} else {
$file = null;
return new JsonResponse(['error' => "Mauvais format d'image"]);
}
}
$date = new DateTime;
$content = $this->renderView(
'Nordinfo/Mails/dest_signalement2.html.twig',
['expediteur_email_' => $post->get('email'), 'destinataire_' => "agent en charge du support aux usagers", 'objet_' => $objet, 'message_' => $message, 'piece_jointe_' => ($fileName != null) ? $fileName : "Aucune pièce jointe", 'date' => "NI" . $date->format('dmYHis')]
);
$nom_dest = 'rédaction du Nord info';
$content_exp = $this->renderView(
'Nordinfo/Mails/exp_signalement2.html.twig',
['destinataire_' => $nom_dest, 'objet_' => $objet, 'message_' => $message, 'piece_jointe_' => ($fileName != null) ? $fileName : "Aucune pièce jointe", 'date' => "NI" . $date->format('dmYHis')]
);
//Newsletter
if ($post->get('newsletter') != null) {
$ins = $this->em->getRepository(InscritNewsletter::class)->findOneBy(['email' => $post->get('email')]);
if ($ins == null) {
$ins = new InscritNewsletter;
$ins->setEmail($post->get('email'))
->setPrenom($post->get('prenom'))
->setNom($post->get('nom'))
->setDate(new DateTime());
$this->em->persist($ins);
$this->em->flush();
}
}
//envoi mail
$result_ = $post->get('nb1') + $post->get('nb2');
if ($result_ == $post->get('captcha') && $post->get('raison') == null) {
try {
//$this->sendMail($content, 'Demande de contact depuis nordinfo : ' . $objet, $destinataires, $files);
//FILES!
$this->sendgrid_service->send($destinataires_sendgrid, $content, 'Demande de contact depuis Nord Info : ' . $objet . ' / ' . 'NI' . $date->format('dmYHis'), ['automate.nordinfo@lenord.fr'], $file);
$this->sendgrid_service->send([$post->get('email')], $content_exp, "Votre message sur Nord info " . $objet . " / " . "NI" . $date->format('dmYHis'), ['automate.nordinfo@lenord.fr'], $file);
} catch (\Exception) {
$this->params['message'] = 'Email erreur';
return $this->render('Nordinfo/Main/endformerror.html.twig', $this->params);
}
}
return $this->render('Nordinfo/Main/endform.html.twig', $this->params);
}
private function getMenusTop(): void
{
$this->params['menusTop'] = $this->em->getRepository(MenuLibelle::class)->findBy(['ordre' => 0]);
}
private function getMenusProfile(): void
{
$this->params['menusprofile'] = $this->em->getRepository(MenuLibelle::class)
->getMenuProfile();
}
#[Route(path: '/ajax/sondage', name: 'ajax_count_sondage')]
public function countResponseSondage(Request $request): Response
{
$response = $this->em->getRepository(PostReponses::class)->find($request->request->get('response_id'));
$response->setCount($response->getCount() + 1);
$this->em->persist($response);
$this->em->flush();
$total_vote = $this->em->getRepository(PostReponses::class)->getTotalVote($request->request->get('sondage_id'))['total'];
$responses = $this->em->getRepository(PostReponses::class)->getSondageResponses($request->request->get('sondage_id'));
$votes = [];
foreach ($responses as $resp) {
array_push($votes, ['texte' => $resp->getTexte(), 'pourcent' => ($resp->getCount() == 0) ? 0 : number_format(($resp->getCount() / $total_vote) * 100, 2)]);
}
return new JsonResponse(['sondage' => $request->request->get('sondage_id'), 'total' => $total_vote, 'votes' => $votes, 'valide' => $response->getValide()]);
}
public function getPublic(): mixed
{
$public = false;
if ($this->getUser() != null) {
if ($this->getUser()->getRole() == 'vip') {
$public = 'vip';
} else if ($this->getUser()->getRole() == 'presse') {
$public = 'presse';
} else if ($this->getUser()->getRole() == 'agent') {
$public = 'agent';
} else if ($this->getUser()->getRole() == 'admin' || $this->getUser()->getRole() == 'superadmin' || $this->getUser()->getRole() == 'redacteur') {
$public = 'tous';
}
}
return $public;
}
#[Route(path: '/tag/{tag}', name: 'search_tag')]
public function search_tag(Request $request, string $tag): Response
{
$this->params['referer'] = $request->headers->get('referer');
$this->params['tag'] = $tag;
$tagName = $tag; // original string from route
$tagEntity = $this->em->getRepository(Tags::class)->findOneBy(['motcle' => $tagName]);
$exp = [];
$this->params['posts'] = [];
if ($tagEntity && $tagEntity->getExpressions()) {
$exp = explode(';', (string)$tagEntity->getExpressions());
$postsFromTag = $this->em->getRepository(Post::class)->getPostsFromTag($tagEntity->getId());
$this->params['posts'] = $postsFromTag;
}
$public = $this->getPublic();
if (count($exp) > 0) {
foreach ($exp as $hashtag) {
$posts = $this->em->getRepository(Post::class)
->getCustomSearchPost($hashtag, false, $public, true);
$this->params['posts'] = array_merge($this->params['posts'], $posts);
}
}
$uniquePosts = [];
$seenIds = [];
foreach ($this->params['posts'] as $post) {
$postId = $post->getId();
if (!in_array($postId, $seenIds, true)) {
$seenIds[] = $postId;
$uniquePosts[] = $post;
}
}
usort($uniquePosts, static function ($a, $b) {
return $b->getCreatedAt() <=> $a->getCreatedAt();
});
$this->params['posts'] = $uniquePosts;
$this->params['posts'] = $this->feedUtilities->social_posts_padding($this->params['posts'], $request);
$this->params['posts'] = $this->feedUtilities->social_posts_detect_links($this->params['posts']);
$this->params['posts'] = $this->feedUtilities->focus_pub_img_dimensions($this->params['posts'], $request);
$this->params['posts_count'] = count($this->params['posts']);
$this->params['text_plus_button'] = 'PLUS DE RÉSULTATS';
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
return $this->render('Nordinfo/Main/search_tags.html.twig', $this->params);
}
#[Route(path: '/recherche_elastic', name: 'recherche_elastic')]
public function recherche_elastic(Request $request): Response
{
$this->params['referer'] = $request->headers->get('referer');
$this->params['search'] = $request->query->get('search');
$intranet = false;
if ($this->getUser() != null) {
$intranet = true;
}
if ($request->query->get('search') != null) {
//Save log
$logEs = new LogEs;
$logEs->setRecherche($request->query->get('search'))
->setDate(new DateTime())
->setSite("info");
$this->em->persist($logEs);
$this->em->flush();
}
$public = $this->getPublic();
$search_conditions = ['intranet' => $intranet, 'public' => $public];
$search_fields = ['combined'];
$results = $this->es_service->searchDocuments('nordinfo', $search_fields, $request->query->get('search'), null, [], [], 200, false, $search_conditions);
$this->params['results'] = $results;
return $this->render('Nordinfo/Main/search_elastic.html.twig', $this->params);
}
#[Route(path: '/recherche', name: 'search_words', priority: 10)]
public function search_words(Request $request): Response
{
$this->params['referer'] = $request->headers->get('referer');
$this->params['search'] = $request->query->get('search');
$intranet = false;
if ($this->getUser() != null) {
$intranet = true;
}
if ($request->query->get('search') != null) {
//Save log
$logEs = new LogEs;
$logEs->setRecherche($request->query->get('search'))
->setDate(new DateTime())
->setSite("info");
$this->em->persist($logEs);
$this->em->flush();
}
$public = $this->getPublic();
$posts = $this->em->getRepository(Post::class)->getCustomSearchPost($request->query->get('search'), $intranet, $public);
$posts = iterator_to_array($posts);
$posts = array_slice($posts, 0, 400);
foreach ($posts as &$post) {
$post['couleurTexte'] = $post['couleur_texte'];
if ($post['couleur_texte']) {
$post['couleurTexte']['codeHexa'] = $post['couleur_texte']['code_hexa'];
$post['couleurTexte']['codeHexaDark'] = $post['couleur_texte']['code_hexa_dark'];
}
if ($post['couleur']) {
$post['couleur']['codeHexa'] = $post['couleur']['code_hexa'];
$post['couleur']['codeHexaDark'] = $post['couleur']['code_hexa_dark'];
}
}
unset($post);
$posts = $this->new_feed_utilities->checkboxes_get_description($posts, $request);
$posts = $this->new_feed_utilities->social_posts_padding($posts, $request);
$posts = $this->new_feed_utilities->focus_pub_img_dimensions($posts, $request);
$posts = $this->new_feed_utilities->social_posts_detect_links($posts);
$this->params['posts'] = $this->agenda_service->parseAgendaEvents($posts);
$this->params['posts_count'] = count($this->params['posts']);
$this->params['text_plus_button'] = 'PLUS DE RÉSULTATS';
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
return $this->render('Nordinfo/Main/search_words.html.twig', $this->params);
}
#[Route(path: '/liste-des-articles', name: 'liste_articles')]
public function listearticles(Request $request): Response
{
$this->params['referer'] = $request->headers->get('referer');
$this->params['list_type'] = 'info';
$this->params['title'] = "L'info";
$this->params['tagbar'] = false;
$this->params['posts'] = $this->em->getRepository(Post::class)->getCustomPosts([1], null, null);
$this->params['posts'] = $this->feedUtilities->social_posts_padding($this->params['posts'], $request);
$this->params['items_total'] = sizeof($this->params['posts']);
$this->params['show_date_bar'] = 0;
$this->params['show_nav'] = 'false';
if ($this->params['initial_limit'] != 0) {
array_splice($this->params['posts'], $this->params['initial_limit'], (is_countable($this->params['posts']) ? count($this->params['posts']) : 0) - 1);
}
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
return $this->render('Nordinfo/Main/gabarit_list.html.twig', $this->params);
}
#[Route(path: '/liste-des-videos', name: 'liste_videos')]
public function listevideos(Request $request): Response
{
$this->params['referer'] = $request->headers->get('referer');
$this->params['list_type'] = 'info';
$this->params['title'] = "L'info";
$this->params['tagbar'] = false;
$this->params['posts'] = $this->em->getRepository(Post::class)->getCustomPosts([4], null, null);
$this->params['posts'] = $this->feedUtilities->social_posts_padding($this->params['posts'], $request);
$this->params['items_total'] = sizeof($this->params['posts']);
$this->params['show_date_bar'] = 0;
$this->params['show_nav'] = 'false';
if ($this->params['initial_limit'] != 0) {
array_splice($this->params['posts'], $this->params['initial_limit'], (is_countable($this->params['posts']) ? count($this->params['posts']) : 0) - 1);
}
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
return $this->render('Nordinfo/Main/gabarit_list.html.twig', $this->params);
}
#[Route(path: '/info', name: 'info')]
public function info(Request $request): Response
{
//$this->get('open_agenda_service')->getAgenda();
//dd('test');
$this->params['referer'] = $request->headers->get('referer');
$this->params['list_type'] = 'info';
$this->params['title'] = "L'info";
$this->params['tagbar'] = true;
$this->params['tags'] = $this->em->getRepository(Tags::class)->getActiveTags();
$type_posts = [1, 2, 6, 7, 9];
if ($this->getUser() != null) {
if (in_array($this->getUser()->getRole(), $this->arr_intranet)) {
array_push($type_posts, 8);
}
}
$public = $this->getPublic();
$this->params['posts'] = $this->em->getRepository(Post::class)->getCustomPosts(
$type_posts,
true,
'info',
null,
null,
true,
'DESC',
$this->params['initial_limit'],
0,
false,
null,
null,
false,
$public
);
$this->params['posts'] = $this->feedUtilities->checkboxes_get_description($this->params['posts'], $request);
$this->params['posts'] = $this->feedUtilities->social_posts_padding($this->params['posts'], $request);
$this->params['posts'] = $this->feedUtilities->focus_pub_img_dimensions($this->params['posts'], $request);
$this->params['posts'] = $this->feedUtilities->social_posts_detect_links($this->params['posts']);
$this->params['items_total'] = (int)$this->em->getRepository(Post::class)->getCustomPosts(
$type_posts,
true,
'info',
null,
null,
true,
null,
null,
0,
true,
null,
null,
false,
$public
);
$this->params['show_date_bar'] = 1;
$this->params['show_nav'] = 'true';
$this->params['text_plus_button'] = 'PLUS D\'INFO';
if ($this->params['initial_limit'] != 0) {
array_splice($this->params['posts'], $this->params['initial_limit'], (is_countable($this->params['posts']) ? count($this->params['posts']) : 0) - 1);
}
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
$epingles_ = $this->epingle_service->getEpinglesSection('a_la_une');
foreach ($epingles_ as $epingle) {
array_push($this->params['epingles'], $epingle);
}
$this->params['sites'] = $this->em->getRepository(FooterSites::class)->getForFooter(false, false, true);
return $this->render('Nordinfo/Main/gabarit_list.html.twig', $this->params);
}
#[Route(path: '/creation-de-compte', name: 'registration')]
public function registration(): Response
{
$this->params['breadcrumb'] = $this->setBreadCrumb(null, 'créer un compte');
$this->params['caps'] = $this->getCaptcha();
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
return $this->render('Nordinfo/Main/registration.html.twig', $this->params);
}
#[Route(path: '/compte-supprime', name: 'remove_account')]
public function removeAccount(Request $request): Response
{
$post = $request->request;
$user = $this->getUser();
$passwordValid = $this->hasher->hashPassword($user, $post->get('password'));
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
if ($passwordValid && $post->get('checkboxConfirmDelete') != null) {
// if ($passwordValid && $post->get('check') == 'SUPPRIMER') {
$destinataire = [];
array_push($destinataire, ['email' => $user->getEmail(), 'name' => $user->getEmail()]);
$content_mail = $this->renderView(
'Nordinfo/Mails/removeAccount.html.twig',
['email' => $user->getEmail(), 'nom' => $user->getPrenom() . ' ' . $user->getNom()]
);
$this->em->remove($user);
$this->em->flush();
$this->sendgrid_service->send([$user->getEmail()], $content_mail, "Confirmation de suppression");
//$this->mail_service->sendTransacEmail('nordinfo@info-lenord.fr', 'Nord info contact', $destinataire, $content_mail, 'Confirmation de suppression');
return $this->render('Nordinfo/Main/endremove.html.twig', $this->params);
} else {
$this->params['message'] = "Une erreur s'est produite";
return $this->render('Nordinfo/Main/endformerror.html.twig', $this->params);
}
}
#[Route(path: '/lien-activation/{token}', name: 'send_activation_again')]
public function sendActivation(Request $request, string $token): Response
{
$user = $this->em->getRepository(User::class)->findOneBy(['token_activation' => $token]);
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
if ($user == null) {
$this->params['message'] = 'Compte déjà activé ou inexistant';
return $this->render('Nordinfo/Main/endformerror.html.twig', $this->params);
}
//Mail
$destinataire = [];
array_push($destinataire, ['email' => $user->getEmail(), 'name' => $user->getEmail()]);
$date = new DateTime;
$url = $url = $this->generateUrl('user_activate', ['token' => $token]);
$content_mail = $this->renderView(
'Nordinfo/Mails/registration.html.twig',
['url_activation' => 'https://' . $request->getHost() . $url]
);
$this->sendgrid_service->send([$user->getEmail()], $content_mail, "Accusé de création de compte");
//$this->mail_service->sendTransacEmail('nordinfo@info-lenord.fr', 'Nord info contact', $destinataire, $content_mail, 'Accusé de création de compte');
return $this->render('Nordinfo/Main/endform.html.twig', $this->params);
}
#[Route(path: '/send_registration', name: 'send_registration')]
public function send_registration(Request $request): Response
{
$post = $request->request;
$caps = $this->getCaptcha();
//$array_search($post->get('nb1'))
$result_ = $post->get('nb1') + $post->get('nb2');
if ($result_ == $post->get('captcha')) {
if ($this->em->getRepository(User::class)->findOneBy(['email' => $post->get('email')]) == null) {
//rechercher si adresse @lenord.fa-r-project//droit => agent sinon droit => public
$role = 'public';
$ex_email = explode("@", $post->get('email'));
if ($ex_email[1] == 'lenord.fr') {
$role = 'agent';
}
$token = hash('md5', $post->get('email') . uniqid());
$this->params['token'] = $token;
$user = new User;
$hpass = $this->hasher->hashPassword($user, $post->get('pass'));
$user->setEmail($post->get('email'))
->setFirstName($post->get('first_name'))
->setLastName($post->get('last_name'))
->setPassword($hpass)
->setRole($role)
->setActive(false)
->setTokenActivation($token);
$this->em->persist($user);
$this->em->flush();
//email
//Mail
$destinataire = [];
array_push($destinataire, ['email' => $post->get('email'), 'name' => $post->get('email')]);
$date = new DateTime;
$url = $url = $this->generateUrl('user_activate', ['token' => $token]);
$content_mail = $this->renderView(
'Nordinfo/Mails/registration.html.twig',
['url_activation' => 'https://' . $request->getHost() . $url]
);
$this->sendgrid_service->send([$post->get('email')], $content_mail, "Accusé de création de compte");
//$this->mail_service->sendTransacEmail('nordinfo@info-lenord.fr', 'Nord info contact', $destinataire, $content_mail, 'Accusé de création de compte');
} else {
$this->params['noenveloppe'] = true;
$this->params['message'] = 'Un compte existe déja avec cette adresse, merci de revérifier votre saisie. Si vous avez oublié votre mot de passe, vous pouvez solliciter sa réinitialisation via <a href="/oubli-mot-de-passe">cette page</a>';
return $this->render('Nordinfo/Main/endformerror.html.twig', $this->params);
}
} else {
$this->params['message'] = 'Captcha erreur';
return $this->render('Nordinfo/Main/endformerror.html.twig', $this->params);
}
return $this->render('Nordinfo/Main/endregister1.html.twig', $this->params);
}
#[Route(path: '/mesactus', name: 'actus')]
public function actus(Request $request): Response
{
$private = false;
$this->params['private'] = false;
if ($this->getUser() != null) {
$function = $request->query->get('function');
if ($function === 'private_only') {
$private = true;
$this->params['private'] = true;
}
}
$this->params['referer'] = $request->headers->get('referer');
$this->params['show_date_bar'] = 1;
$this->params['actus'] = true;
$this->params['list_type'] = 'actus';
$this->params['title'] = 'Actualités';
$dateday = new DateTime;
$dateday->modify('+7 day');
$this->params['date_day'] = $dateday;
$this->params['tags'] = $this->em->getRepository(Tags::class)->getActiveTags();
$this->params['items_total'] = 0;
$type_posts = [1, 2, 4, 5, 6, 7, 9];
if ($this->getUser() != null && in_array($this->getUser()->getRole(), $this->arr_intranet, true)) {
$type_posts[] = 8;
}
$territory_ids = $this->getTerritoryIds($request);
$topic_ids = $this->getTopicIds($request);
$this->params['cookie_territories'] = $this->getTerritories($request);
$this->params['cookie_topics'] = $this->getTopics($request);
if ($topic_ids == null && $territory_ids == null && $this->getUser() != null && in_array($this->getUser()->getRole(), $this->arr_intranet, true)) {
$type_posts = [8];
}
$no_posts = false;
$public = $this->getPublic();
// if ($territory_ids == null && $topic_ids == null) {
// if ($this->getUser() == null || $this->getUser()->getRole() === 'public') {
// $no_posts = true;
// }
// }
if ($private == true && $public === 'tous') {
$territory_ids = null;
$topic_ids = null;
}
$posts = $this->em->getRepository(Post::class)
->getCustomPosts(
$type_posts,
null,
null,
$territory_ids,
$topic_ids,
true,
'DESC',
$this->params['initial_limit'],
0,
false,
null,
null,
false,
$public,
$no_posts,
$private
);
$this->params['items_total'] = (int)$this->em->getRepository(Post::class)
->getCustomPosts(
$type_posts,
null,
null,
$territory_ids,
$topic_ids,
true,
'DESC',
null,
0,
true,
null,
null,
false,
$public,
$no_posts,
$private
);
$this->params['posts'] = $posts;
if (!$no_posts) {
$this->params['posts'] = $this->feedUtilities->social_posts_padding($this->params['posts'], $request);
$this->params['posts'] = $this->feedUtilities->focus_pub_img_dimensions($this->params['posts'], $request);
$this->params['posts'] = $this->feedUtilities->social_posts_detect_links($this->params['posts']);
}
$this->params['show_nav'] = 'true';
$this->params['text_plus_button'] = 'PLUS D\'ACTU';
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
$epingles_ = $this->epingle_service->getEpinglesSection('mesinfos');
foreach ($epingles_ as $epingle) {
$this->params['epingles'][] = $epingle;
}
$this->params['sites'] = $this->em->getRepository(FooterSites::class)->getForFooter(false, false, true);
return $this->render('Nordinfo/Main/actus.html.twig', $this->params);
}
public function direct(Request $request): Response
{
$this->params['referer'] = $request->headers->get('referer');
$this->params['list_type'] = 'direct';
$this->params['title'] = 'En direct';
$this->params['tagbar'] = false;
$this->params['items_offset'] = 20;
$this->params['initial_limit'] = 20;
$post_types = [5, 7, 9];
$public = $this->getPublic();
$this->params['posts'] = $this->em->getRepository(Post::class)->getCustomPosts(
$post_types,
null,
'direct',
null,
null,
false,
'DESC',
$this->params['initial_limit'],
0,
null,
null,
false,
$public
);
$this->params['items_total'] = (int)$this->em->getRepository(Post::class)->getCustomPosts(
$post_types,
null,
'direct',
null,
null,
false,
'DESC',
null,
0,
true,
null,
null,
false,
$public
);
$this->params['posts'] = $this->feedUtilities->checkboxes_get_description($this->params['posts'], $request);
$this->params['posts'] = $this->feedUtilities->social_posts_padding($this->params['posts'], $request);
$this->params['posts'] = $this->feedUtilities->focus_pub_img_dimensions($this->params['posts'], $request);
$this->params['posts'] = $this->feedUtilities->social_posts_detect_links($this->params['posts']);
$this->params['show_nav'] = 'true';
$this->params['show_date_bar'] = true;
$this->params['text_plus_button'] = 'PLUS DE POSTS';
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
return $this->render('Nordinfo/Main/gabarit_list.html.twig', $this->params);
}
#[Route(path: '/nos-reseaux', name: 'reseaux')]
public function reseaux(): Response
{
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
return $this->render('Nordinfo/Main/reseaux.html.twig', $this->params);
}
#[Route(path: '/agenda', name: 'agenda')]
public function agenda(Request $request): Response
{
/**
* BE CAREFUL!
* THE CODE THAT HAS TO DO WITH RETRIEVING ITEMS, HAS TO BE ALSO CLONED INSIDE THE AjaxController.php
*/
$this->params['referer'] = $request->headers->get('referer');
$date_param = $request->query->get('date');
$query_date = null;
$query_date2 = null;
$query_date_from = false;
if (!isset($date_param) || trim($date_param) === '') {
$query_date = new DateTime();
$query_date_from = true;
} else if ($date_param == 'today') {
$query_date = new DateTime();
} else if ($date_param == 'weekend') {
$query_date = new DateTime('Saturday');
$query_date2 = new DateTime('Sunday');
} else {
$query_date_from = true;
$query_date = date_create_from_format('d/m/Y', $date_param);
if ($query_date == false) {
$query_date = date_create_from_format('Y-m-d', $date_param);
}
$outputDate = $query_date->format('d F Y');
$outputDate = str_replace(
array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'),
array('Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'),
$outputDate
);
$this->params['show_date_bar_agenda'] = $outputDate;
}
$this->params['list_type'] = 'agenda';
$this->params['title'] = 'Agenda';
$this->params['tagbar'] = false;
$this->params['cookie_search'] = true;
$territory_ids = $this->getTerritoryIds($request);
$this->params['cookie_territories'] = $this->getTerritories($request);
$this->params['cookie_topics'] = $this->getTopics($request);
$public = $this->getPublic();
$posts = $this->em->getRepository(Post::class)->getCustomArrayPosts(
[3, 6, 7, 9],
true,
'agenda',
$territory_ids,
null,
false,
'ASC',
$this->params['initial_limit'],
0,
false,
$query_date,
$query_date2,
$query_date_from,
$public
);
$posts = iterator_to_array($posts);
$posts = $this->new_feed_utilities->checkboxes_get_description($posts, $request);
$posts = $this->new_feed_utilities->social_posts_padding($posts, $request);
$posts = $this->new_feed_utilities->focus_pub_img_dimensions($posts, $request);
$posts = $this->new_feed_utilities->social_posts_detect_links($posts);
$this->params['posts'] = $this->agenda_service->parseAgendaEvents($posts, $query_date, $query_date2, true);
foreach ($this->params['posts'] as &$post) {
$post['couleurTexte'] = $post['couleur_texte'];
if ($post['couleur_texte']) {
$post['couleurTexte']['codeHexa'] = $post['couleur_texte']['code_hexa'];
$post['couleurTexte']['codeHexaDark'] = $post['couleur_texte']['code_hexa_dark'];
}
if ($post['couleur']) {
$post['couleur']['codeHexa'] = $post['couleur']['code_hexa'];
$post['couleur']['codeHexaDark'] = $post['couleur']['code_hexa_dark'];
}
}
unset($post);
$this->params['items_total'] = (int)$this->em->getRepository(Post::class)
->getCustomPosts(
[3, 6, 7, 9],
true,
'agenda',
$territory_ids,
null,
false,
'ASC',
$this->params['count_limit'],
0,
true,
$query_date,
$query_date2,
$query_date_from,
$public
);
$this->params['show_agenda_filters'] = 1;
$this->params['show_nav'] = 'true';
$this->params['text_plus_button'] = 'PLUS D\'ÉVÈNEMENTS';
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
$epingles_ = $this->epingle_service->getEpinglesSection('agenda');
foreach ($epingles_ as $epingle) {
array_push($this->params['epingles'], $epingle);
}
$this->params['sites'] = $this->em->getRepository(FooterSites::class)->getForFooter(false, false, true);
return $this->render('Nordinfo/Main/agenda.html.twig', $this->params);
}
#[Route(path: '/infolettre', name: 'infolettre')]
public function infolettre(Request $request): Response
{
$this->params['referer'] = $request->headers->get('referer');
$this->params['breadcrumb'] = $this->setBreadCrumb(null, "Infolettre");
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
return $this->render('Nordinfo/Main/infolettre.html.twig', $this->params);
}
#[Route(path: '/videos', name: 'videos')]
public function videos(Request $request): Response
{
$this->params['referer'] = $request->headers->get('referer');
$this->params['list_type'] = 'videos';
$this->params['title'] = 'Vidéos';
$this->params['tagbar'] = false;
$this->params['show_date_bar'] = 1;
$posts_types = [4, 6, 7, 9];
$public = $this->getPublic();
$this->params['posts'] = $this->em->getRepository(Post::class)->getCustomPosts(
$posts_types,
null,
'videos',
null,
null,
false,
'DESC',
$this->params['initial_limit'],
0,
false,
null,
null,
false,
$public
);
$this->params['posts'] = $this->feedUtilities->checkboxes_get_description($this->params['posts'], $request);
$this->params['posts'] = $this->feedUtilities->focus_pub_img_dimensions($this->params['posts'], $request);
$this->params['posts'] = $this->feedUtilities->social_posts_padding($this->params['posts'], $request);
$this->params['posts'] = $this->feedUtilities->social_posts_detect_links($this->params['posts']);
$this->params['items_total'] = (int)$this->em->getRepository(Post::class)->getCustomPosts(
$posts_types,
null,
'videos',
null,
null,
false,
'DESC',
null,
0,
true,
null,
null,
false,
$public
);
$this->params['show_nav'] = 'true';
$this->params['text_plus_button'] = 'PLUS DE VIDEOS';
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
$epingles_ = $this->epingle_service->getEpinglesSection('videos');
foreach ($epingles_ as $epingle) {
array_push($this->params['epingles'], $epingle);
}
$this->params['sites'] = $this->em->getRepository(FooterSites::class)->getForFooter(false, false, true);
return $this->render('Nordinfo/Main/gabarit_list.html.twig', $this->params);
}
#[Route(path: '/video-{slug}', name: 'video_detail')]
public function video_detail_post(Request $request, string $slug): Response
{
return $this->detail_post($request, $slug);
}
private function cmp($a, $b)
{
return strcmp((string)$a->getOrderFolder(), (string)$b->getOrderFolder());
}
protected function isFavoritev2($post_id, $user, $request): bool
{
$favorite = false;
$user = $this->getUser();
if ($user !== null) {
foreach ($user->getFavoris() as $favori) {
if ($post_id == $favori->getId()) {
$favorite = true;
break;
}
}
} else {
if ($request->cookies->get('favorite') != null) {
if (in_array($post_id, explode(',', (string)$request->cookies->get('favorite'))) == true) {
$favorite = true;
}
}
}
return $favorite;
}
protected function isFavorite(mixed $post, mixed $user, Request $request): bool
{
$favorite = false;
$user = $this->getUser();
if ($user !== null) {
foreach ($user->getFavoris() as $favori) {
if ($post->getId() == $favori->getId()) {
$favorite = true;
break;
}
}
} else {
if ($request->cookies->get('favorite') != null) {
if (in_array($post->getId(), explode(',', (string)$request->cookies->get('favorite'))) == true) {
$favorite = true;
}
}
}
return $favorite;
}
protected function getRelatedPosts(mixed $post): array
{
$number = 0;
$relateds = [];
$relatedPost1 = $post->getRelatedPost1();
if ($relatedPost1 === null) {
$number = 1;
} else if ($relatedPost1->getStatus()->getId() === 5) {
$relateds[] = $post->getRelatedPost1();
}
$relatedPost2 = $post->getRelatedPost2();
if ($relatedPost2 === null) {
$number = 2;
} else if ($relatedPost2->getStatus()->getId() === 5) {
$relateds[] = $post->getRelatedPost2();
}
$relatedPost3 = $post->getRelatedPost3();
if ($relatedPost3 === null) {
$number = 3;
} else if ($relatedPost3->getStatus()->getId() === 5) {
$relateds[] = $post->getRelatedPost3();
}
$type_id = $post->getType()->getId();
$topics_id = [];
foreach ($post->getTopics() as $topic) {
$topics_id[] = $topic->getId();
}
$territories_id = [];
foreach ($post->getTerritories() as $territory) {
$territories_id[] = $territory->getId();
}
$posts = $this->em->getRepository(Post::class)->getRelatedPost($number, $type_id, $topics_id, $territories_id, $post->getId());
foreach ($posts as $p) {
if (count($relateds) === 4) {
break;
}
if ($p->getSlug() !== null) {
$relateds[] = $p;
}
}
return $relateds;
}
protected function setBreadCrumb(mixed $post = null, mixed $page_title = null, mixed $departement = false, mixed $liste = null): mixed
{
$breadcrumb = [];
array_push($breadcrumb, ['alias' => $this->generateUrl('index'), 'titre' => 'Accueil']);
if ($post != null) {
switch ($post->getType()->getType()) {
case 'article':
case 'sondage':
case 'folder':
case 'pub':
array_push($breadcrumb, ['alias' => $this->generateUrl('info'), 'titre' => "L'info"]);
break;
case 'event':
array_push($breadcrumb, ['alias' => $this->generateUrl('agenda'), 'titre' => "Agenda"]);
break;
case 'video':
array_push($breadcrumb, ['alias' => $this->generateUrl('videos'), 'titre' => "Vidéos"]);
break;
case 'socialpost':
array_push($breadcrumb, ['alias' => $this->generateUrl('direct'), 'titre' => 'En direct']);
break;
}
array_push($breadcrumb, ['alias' => '', 'titre' => $post->getTitle()]);
}
if ($page_title != null && $departement == false) {
array_push($breadcrumb, ['alias' => '', 'titre' => $page_title]);
} else if ($page_title != null && $departement == true && $liste == null) {
array_push($breadcrumb, ['alias' => $this->generateUrl('departement'), 'titre' => 'le Département']);
array_push($breadcrumb, ['alias' => '', 'titre' => $page_title]);
} else if ($page_title != null && $departement == true && $liste != null) {
array_push($breadcrumb, ['alias' => $this->generateUrl('departement'), 'titre' => 'le Département']);
if ($liste == 'elus') {
array_push($breadcrumb, ['alias' => $this->generateUrl('contacts'), 'titre' => 'contacts et élus']);
} else {
array_push($breadcrumb, ['alias' => $this->generateUrl(
'organisations',
['type' => $liste]
), 'titre' => $liste]);
}
array_push($breadcrumb, ['alias' => '', 'titre' => $page_title]);
}
return $breadcrumb;
}
protected function getTerritories(Request $request): mixed
{
$cookie_territories = [];
$territories = [];
$user = $this->getUser();
if ($user !== null) {
foreach ($user->getTerritoires() as $territoire) {
array_push($territories, (int)$territoire->getId());
}
} else {
if ($request->cookies->get('territories') != null) {
$territories = explode(',', $request->cookies->get('territories'));
}
}
foreach ($territories as $territory_id) {
$terr = $this->em->getRepository(Territory::class)->find($territory_id);
$cookie_territories[] = $terr->getDisplayName();
}
return $cookie_territories;
}
protected function getTerritoryIds(Request $request): mixed
{
$territories = [];
$user = $this->getUser();
if ($user !== null) {
foreach ($user->getTerritoires() as $territoire) {
array_push($territories, (int)$territoire->getId());
}
} else {
if ($request->cookies->get('territories') != null) {
$territories = explode(',', $request->cookies->get('territories'));
}
}
return $territories;
}
protected function getTopics(Request $request): mixed
{
$cookie_topics = [];
$topics = [];
$user = $this->getUser();
if ($user !== null) {
foreach ($user->getThematiques() as $topic) {
$topics[] = (int)$topic->getId();
}
} else {
if ($request->cookies->get('topics') != null) {
$topics = explode(',', $request->cookies->get('topics'));
}
}
foreach ($topics as $topic_id) {
$terr = $this->em->getRepository(Topic::class)->find($topic_id);
$cookie_topics[] = ($terr != null) ? $terr->getDisplayName() : 'error';
}
return $cookie_topics;
}
protected function getTopicIds(Request $request): mixed
{
$topics = [];
$user = $this->getUser();
if ($user !== null) {
foreach ($user->getThematiques() as $topic) {
$topics[] = (int)$topic->getId();
}
} else {
if ($request->cookies->get('topics') != null) {
$topics = explode(',', $request->cookies->get('topics'));
}
}
return $topics;
}
#[Route(path: '/contact/{slug}', name: 'contact_detail')]
public function detail_contact(Request $request, string $slug): Response
{
$contact = $this->em->getRepository(Contact::class)->getContact_($slug);
$this->params['contact'] = $contact;
$posts = [];
$count_post = 0;
foreach ($contact->getPosts1() as $pp) {
if ($count_post >= 3) {
break;
}
$posts[] = $pp;
$count_post++;
}
if ($count_post < 3) {
foreach ($contact->getPosts2() as $pp) {
if ($count_post >= 3) {
break;
}
$posts[] = $pp;
$count_post++;
}
}
if ($count_post < 3) {
foreach ($contact->getPosts3() as $pp) {
if ($count_post >= 3) {
break;
}
$posts[] = $pp;
$count_post++;
}
}
$this->params['breadcrumb'] = $this->setBreadCrumb(null, $contact->getFirstName() . ' ' . $contact->getLastName(), true, 'elus');
$this->params['contact_posts'] = $posts;
$this->params['referer'] = $request->headers->get('referer');
$this->params['caps'] = $this->getCaptcha();
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
if ($request->get('function') == 'download_pdf') {
$this->params['is_pdf'] = 1;
$pdfOptions = new Options();
$pdfOptions->set('defaultFont', 'Arial');
$pdfOptions->setIsRemoteEnabled(true);
$dompdf = new Dompdf($pdfOptions);
$html = $this->renderView('Nordinfo/Main/detail_contact.html.twig', $this->params);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$output = $dompdf->output();
$filename = sprintf('nord-info-%s.pdf', $contact->getFirstName());
return new Response(
$output,
200,
[
'Content-Type' => 'application/pdf',
'Content-Disposition' => sprintf('attachment; filename="%s"', "$filename"),
]
);
} else {
return $this->render('Nordinfo/Main/detail_contact.html.twig', $this->params);
}
}
#[Route(path: '/organisation/{id}', name: 'organisation_detail')]
public function detail_organisation(Request $request, mixed $id): mixed
{
$organisation = $this->em->getRepository(Organization::class)->getOrganisation($id);
$this->params['organisation'] = $organisation;
$this->params['referer'] = $request->headers->get('referer');
$type = null;
$type_id = $organisation->getTypeOrganisation()->getId();
/*switch ($type_id) {
case 1:
$type = 'colleges';
break;
case 2:
$type = 'secteur-social';
break;
case 3:
case 4:
$type = 'espaces-naturels-sensibles';
break;
}*/
$type = $organisation->getTypeOrganisation()->getName();
$this->params['breadcrumb'] = $this->setBreadCrumb(null, $organisation->getTitle(), true, $type);
$related_posts = [];
$ids_done = [];
foreach ($organisation->getPosts1() as $post) {
if (($post->getStatus()->getId() === 5) && !in_array($post->getId(), $ids_done, true)) {
$related_posts[] = $post;
$ids_done[] = $post->getId();
}
}
foreach ($organisation->getPosts2() as $post) {
if (($post->getStatus()->getId() === 5) && !in_array($post->getId(), $ids_done, true)) {
$related_posts[] = $post;
$ids_done[] = $post->getId();
}
}
foreach ($organisation->getPosts3() as $post) {
if (($post->getStatus()->getId() === 5) && !in_array($post->getId(), $ids_done, true)) {
$related_posts[] = $post;
$ids_done[] = $post->getId();
}
}
$this->params['related_posts'] = $related_posts;
$this->params['caps'] = $this->getCaptcha();
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
return $this->render('Nordinfo/Main/detail_organisation.html.twig', $this->params);
}
#[Route(path: '/le-departement/{slug}', name: 'page')]
public function page(Request $request, string $slug): Response
{
$this->params['referer'] = $request->headers->get('referer');
$post = $this->em->getRepository(Pages::class)->findOneBy(['alias_url' => $slug, 'actif' => 1, 'nordinfo' => 1]);
if (!$post) {
throw $this->createNotFoundException('La page demandée n\'existe pas.');
}
$this->params['post'] = $post;
$content_post = null;
if ($this->params['post']->getContent() != null) {
$content_post = $this->feedUtilities->jsonToHtml($this->params['post']->getContent(), $request, $this->params['post']->getTitre());
}
$this->params['content_post'] = $content_post;
$this->params['breadcrumb'] = $this->setBreadCrumb(null, $this->params['post']->getTitre(), true);
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
return $this->render('Nordinfo/Main/detail_page.html.twig', $this->params);
}
#[Route(path: '/post-testing/{id}', name: 'post_testing')]
public function postTesting(Request $request, mixed $id): Response
{
$post = $this->em
->getRepository(Post::class)
->find($id);
$contentJson = $post->getContent();
$html = $this->feedUtilities->jsonToHtml($contentJson, $request);
return $this->render('Nordinfo/Main/demo-post.html.twig', ['page_content' => $html]);
}
#[Route(path: '/elements', name: 'elements')]
public function elements(): Response
{
return $this->render('Nordinfo/Main/elements.html.twig', $this->params);
}
#[Route(path: '/thematiques', name: 'topics')]
public function topics(Request $request): Response
{
$this->params['referer'] = $request->headers->get('referer');
$this->params['topics'] = $this->em->getRepository(Topic::class)->getAll();
$checkTopics = [];
if ($this->getUser() != null) {
foreach ($this->getUser()->getThematiques() as $topic) {
array_push($checkTopics, $topic->getId());
}
} else if ($request->cookies->get('topics') != null) {
$checkTopics = explode(',', $request->cookies->get('topics'));
}
$this->params['checkTopics'] = $checkTopics;
$this->params['show_nav'] = 'false';
$this->params['breadcrumb'] = $this->setBreadCrumb(null, 'vos thématiques');
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
return $this->render('Nordinfo/Main/topics.html.twig', $this->params);
}
#[Route(path: '/vos-lieux', name: 'vos_lieux')]
public function vos_lieux(Request $request): Response
{
$this->params['referer'] = $request->headers->get('referer');
$checkTerritories = [];
if ($this->getUser() != null) {
foreach ($this->getUser()->getTerritoires() as $territoire) {
array_push($checkTerritories, $territoire->getId());
}
} else if ($request->cookies->get('territories') != null) {
$checkTerritories = explode(',', $request->cookies->get('territories'));
}
$territories = $this->em->getRepository(Territory::class)->getListeTerritories();
$this->params['territories'] = $territories;
$this->params['checkTerritories'] = $checkTerritories;
$this->params['show_nav'] = 'false';
$this->params['breadcrumb'] = $this->setBreadCrumb(null, 'Vos lieux de vie');
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
return $this->render('Nordinfo/Main/vos_lieux.html.twig', $this->params);
}
#[Route(path: '/mon-compte', name: 'mon_compte')]
public function monCompte(Request $request)
{
if ($this->getUser() == null) {
return $this->redirect('login');
}
$this->params['referer'] = $request->headers->get('referer');
$this->params['show_nav'] = 'false';
$this->params['breadcrumb'] = $this->setBreadCrumb(null, 'Mon Compte');
$this->params['cookie_territories'] = $this->getTerritories($request);
$this->params['cookie_topics'] = $this->getTopics($request);
$this->params['posts_favoris'] = $this->getFavoris($request);
$this->params['items_total_favoris'] = sizeof($this->params['posts_favoris']);
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
return $this->render('Nordinfo/Main/profile.html.twig', $this->params);
}
private function getCaptcha(): mixed
{
$captchaCh = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$captchaLe = ["zéro", "un", "deux", "trois", "quatre", "cinq", "six", "sept", "huit", "neuf", "dix"];
$testcap = array_merge($captchaCh, $captchaLe);
$rnd = array_rand($testcap, 2);
$i1 = $rnd[0];
if ($rnd[0] >= 11) {
$i1 = $rnd[0] - 11;
}
$i2 = $rnd[1];
if ($rnd[1] >= 11) {
$i2 = $rnd[1] - 11;
}
$capp = ["valeur1" => ["libelle" => $testcap[$rnd[0]], "valeur" => $captchaCh[$i1]], "valeur2" => ["libelle" => $testcap[$rnd[1]], "valeur" => $captchaCh[$i2]]];
return $capp;
}
#[Route(path: '/proposer-un-evenement', name: 'proposer_event')]
public function proposerEvent(Request $request): Response
{
$this->params['referer'] = $request->headers->get('referer');
$this->params['types'] = $this->em->getRepository(EventType::class)->findAll();
$communes = $this->em->getRepository(Cantons::class)->getCommunes();
$villes = [];
foreach ($communes as $cc) {
$villes = array_merge(array_map('trim', explode(',', (string)$cc['communes'])), $villes);
}
asort($villes);
$this->params['villes'] = $villes;
$this->params['caps'] = $this->getCaptcha();
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
return $this->render('Nordinfo/Main/proposerevent.html.twig', $this->params);
}
#[Route(path: '/support', name: 'signaler')]
public function signaler(Request $request): Response
{
$this->params['referer'] = $request->headers->get('referer');
$this->params['types_support'] = $this->em->getRepository(TypeSupport::class)->findAll();
$this->params['breadcrumb'] = $this->setBreadCrumb(null, 'contact');
$this->params['objet'] = null;
if ($request->query->get('objet') != null) {
$this->params['objet'] = 4;
}
$this->params['caps'] = $this->getCaptcha();
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
$this->params['thematiques'] = $this->em->getRepository(FormulaireThematique::class)->findBy(['bool_info' => 1], ['name' => 'ASC']);
return $this->render('Nordinfo/Main/signaler.html.twig', $this->params);
}
#[Route(path: '/organisations/{type}', name: 'search_organisation')]
public function searchorganisations(Request $request, $type): Response
{
return $this->organisations($request, $type);
}
#[Route(path: '/search-organisations/{type}', name: 'organisations')]
public function organisations(Request $request, $type): Response
{
$this->params['type_'] = $type;
$to = $this->em->getRepository(TypeOrganisation::class)->findOneByName($type);
$this->params['title'] = $to->getTitreListe();
$id_type = $to->getId();
$this->params['breadcrumb'] = $this->setBreadCrumb(null, 'liste des organisations', true);
$this->params['referer'] = $request->headers->get('referer');
$filter_title = null;
$search = $request->query->get('search');
$search_id = null;
$this->params['is_search'] = 0;
$uri_path = parse_url($request->getUri(), PHP_URL_PATH);
$uri_segments = explode('/', $uri_path);
$uri_segment_filter = urldecode($uri_segments[2]);
if ($request->query->get('territoire_id') != "") {
$search = null;
$search_id = $request->query->get('territoire_id');
$territory = $this->em->getRepository(Territory::class)->find($request->query->get('territoire_id'));
$filter_title = 'Résultats pour ' . $territory->getDisplayName();
$this->params['is_search'] = 1;
} else if ($uri_segment_filter != '') {
$search_id = null;
$filter_title = ' résultats pour "' . $uri_segment_filter . '"';
$this->params['is_search'] = 1;
}
$this->params['contacts'] = $this->em->getRepository(Organization::class)->getOrganisations_($id_type, $search, $search_id);
$this->params['territoires'] = $this->em->getRepository(Territory::class)->findAll();
$this->params['filter_title'] = ($filter_title != null) ? (is_countable($this->params['contacts']) ? count($this->params['contacts']) : 0) . $filter_title : null;
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
return $this->render('Nordinfo/Main/organisations.html.twig', $this->params);
}
#[Route(path: '/search-contacts', name: 'search_contact')]
public function search_contacts(Request $request): Response
{
return $this->contacts($request);
}
#[Route(path: '/contacts', name: 'contacts')]
public function contacts(Request $request): Response
{
$this->params['referer'] = $request->headers->get('referer');
$this->params['cantons'] = $this->em->getRepository(Cantons::class)->findAll();
$search = null;
$search_id = null;
$filter_title = null;
$this->params['is_search'] = 0;
if ($request->query->get('canton_id') != "") {
$search = null;
$search_id = $request->query->get('canton_id');
$this->params['is_search'] = 1;
$canton = $this->em->getRepository(Cantons::class)->find($request->query->get('canton_id'));
$filter_title = ' résultats pour "' . $canton->getCanton() . '"';
} else if ($request->query->get('search') != "") {
$search = $request->query->get("search");
$search_id = null;
$this->params['is_search'] = 1;
$filter_title = ' résultats pour "' . $search . '"';
}
$this->params['breadcrumb'] = $this->setBreadCrumb(null, 'contacts et élus', true);
$this->params['contacts'] = $this->em->getRepository(Contact::class)->getContacts_(1, $search, $search_id);
$this->params['filter_title'] = ($filter_title != null) ? (is_countable($this->params['contacts']) ? count($this->params['contacts']) : 0) . $filter_title : null;
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
return $this->render('Nordinfo/Main/contacts.html.twig', $this->params);
}
#[Route(path: '/apercu-feedback', name: 'feedback')]
public function feedback(Request $request): Response
{
$this->params['referer'] = $request->headers->get('referer');
return $this->render('Nordinfo/Main/feedback.html.twig', $this->params);
}
#[Route(path: '/inviter-a-commenter/{id}', name: 'invite_comment_post')]
public function inviteToComment(mixed $id): Response
{
$this->params['post'] = $this->em->getRepository(Post::class)->find($id);
$this->params['id'] = $id;
$this->params['users_agent'] = $this->em->getRepository(User::class)->getUsersComment();
return $this->render('Admin/comment_invite.html.twig', $this->params);
}
#[Route(path: '/send-invite-comment/{id}', name: 'send_invitation_comment')]
public function sendInviteToComment(Request $request, $id): RedirectResponse
{
$user = $this->getUser();
$post = $request->request;
//Mail
$date = date_create_from_format('d/m/Y', $post->get('date'));
//Interne
if ($post->get('emails_interne') != null && !empty($post->get('emails_interne'))) {
foreach ((array)$post->get('emails_interne') as $user_id) {
$user = $this->em->getRepository(User::class)->find($user_id);
$destinataire = [];
array_push($destinataire, ['email' => $user->getEmail(), 'name' => $user->getEmail()]);
//Envoi email
$article = $this->em->getRepository(Post::class)->find($id);
$token = base64_encode(random_bytes(60));
$token = str_replace(["+", "/"], '_', $token);
$doit_valider = $post->get('doit_valider');
$com = new PostCommentaires;
$com
->setPost($article)
->setDate($date)
->setAuteur($user->getEmail())
->setToken($token)
->setDoitValider(($doit_valider != null) ? $doit_valider : false)
->setValide(false);
$this->em->persist($com);
//date url titre
$url = $this->generateUrl('comment_post', ['token' => $token]);
$content_mail = $this->renderView(
'Nordinfo/Mails/commentaire_invite.html.twig',
['texte_email' => $post->get('texte_email'), 'image' => $article->getIllustrationfilName(), 'titre' => $article->getTitle(), 'date' => $date, 'url' => 'https://' . $request->getHost() . $url]
);
$this->sendgrid_service->send([$user->getEmail()], $content_mail, "Nordinfo : Invitation à commenter");
//$this->mail_service->sendTransacEmail('nordinfo@info-lenord.fr', 'Nord info contact', $destinataire, $content_mail, 'Nordinfo : Invitation à commenter');
}
}
//Externe
if ($post->get('emails') != null) {
$dests = explode(';', $post->get('emails'));
foreach ($dests as $str) {
$destinataire = [];
array_push($destinataire, ['email' => $str, 'name' => $str]);
//Envoi email
$article = $this->em->getRepository(Post::class)->find($id);
$token = base64_encode(random_bytes(60));
$token = str_replace(["+", "/"], '_', $token);
$doit_valider = $post->get('doit_valider');
$com = new PostCommentaires;
$com
->setPost($article)
->setDate($date)
->setAuteur($str)
->setToken($token)
->setDoitValider(($doit_valider != null) ? $doit_valider : false)
->setValide(false);
$this->em->persist($com);
//date url titre
$url = $this->generateUrl('comment_post', ['token' => $token]);
$content_mail = $this->renderView(
'Nordinfo/Mails/commentaire_invite.html.twig',
['texte_email' => $post->get('texte_email'), 'image' => $article->getIllustrationfilName(), 'titre' => $article->getTitle(), 'date' => $date, 'url' => 'https://' . $request->getHost() . $url]
);
$this->sendgrid_service->send([$str], $content_mail, "Nordinfo : Invitation à commenter");
//$this->mail_service->sendTransacEmail('nordinfo@info-lenord.fr', 'Nord info contact', $destinataire, $content_mail, 'Nordinfo : Invitation à commenter');
}
}
$this->em->flush();
$url = '/console2020/?entity=Article&action=list';
return $this->redirect($url);
}
public function importXls(): void
{
$path = $this->get('kernel')->getRootDir() . '/../';
$file = $path . 'mdie.xls';
$fileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($file);
$l = 0;
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($fileType);
$spreadsheet = $reader->load($file);
$datas = $spreadsheet->getSheet(0)->toArray(null, true, true, true);
foreach ($datas as $d) {
$l++;
if ($l > 1) {
if ($d['C'] == "") {
break;
}
$type = $this->em->getRepository(TypeOrganisation::class)->find(6);
$territory = $this->em->getRepository(Territory::class)->find($d['K']);
$organisation = new Organization;
$organisation->setTitle($d['C'])
->setSubtitle($d['D'])
->setEmail($d['M'])
->setPhone($d['N'])
->setAcceo($d['O'])
->setCodePostal($d['J'])
->setRue($d['H'])
->setVille($d['I'])
->setTypeOrganisation($type)
->setTerritory($territory);
$this->em->persist($organisation);
}
echo $l . '\r\n';
}
$this->em->flush();
}
/*
#[Route(path: '/console2020/ckfinder', name: 'ckfinder')]
public function ckfinder(): Response
{
return $this->render('/Main/ckfinder.html.twig');
}
*/
#[Route(path: '/ics', name: 'ics_download')]
public function downloadics(Request $request): Response
{
$post = $request->request;
$date_start = date_create_from_format('d/m/Y', $post->get('date_start'))->setTime(10, 0, 0);
$date_end = date_create_from_format('d/m/Y', $post->get('date_end'))->setTime(18, 0, 0);
$ics = new ICS(['location' => $post->get('location'), 'description' => $post->get('description'), 'dtstart' => $date_start, 'dtend' => $date_end, 'summary' => $post->get('summary'), 'url' => $post->get('url')]);
$filename = $post->get('summary') . '.ics';
$response = new Response($ics->to_string());
$response->headers->set('charset', 'utf-8');
$response->headers->set('Content-Type', 'text/calendar');
$response->headers->set('Content-Disposition', 'attachment');
$response->headers->set('filename', $filename);
return $response;
}
#[Route(path: '/sitemap', name: 'sitemap')]
public function sitemap(Request $request): Response
{
$urls = [];
$this->params['page_title'] = "Plan du site";
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
$this->params['referer'] = $request->headers->get('referer');
$urls['index']['parent']['url'] = $this->generateUrl('index');
$urls['index']['parent']['name'] = "Accueil";
$j = 0;
$urls['fil']['parent']['url'] = "";
$urls['fil']['parent']['name'] = "Actus";
$urls['fil']['children'][$j]['url'] = $this->generateUrl('actus');
$urls['fil']['children'][$j]['name'] = "Mes actus";
$j++;
$urls['fil']['children'][$j]['url'] = $this->generateUrl('info');
$urls['fil']['children'][$j]['name'] = "L'info";
$j++;
$urls['fil']['children'][$j]['url'] = $this->generateUrl('agenda');
$urls['fil']['children'][$j]['name'] = "Agenda";
$j++;
$urls['fil']['children'][$j]['url'] = $this->generateUrl('videos');
$urls['fil']['children'][$j]['name'] = "Vidéos";
$urls['custom']['parent']['url'] = "";
$urls['custom']['parent']['name'] = "Personnalisation";
$j = 0;
$urls['custom']['children'][$j]['url'] = $this->generateUrl('favoris');;
$urls['custom']['children'][$j]['name'] = "Favoris";
$j++;
$urls['custom']['children'][$j]['url'] = $this->generateUrl('vos_lieux');;
$urls['custom']['children'][$j]['name'] = "Mes lieux de vie";
$j++;
$urls['custom']['children'][$j]['url'] = $this->generateUrl('topics');;
$urls['custom']['children'][$j]['name'] = "Mes centres d'intérêt";
$urls['departement']['parent']['url'] = $this->generateUrl('departement');
$urls['departement']['parent']['name'] = "Le département";
$j = 0;
$urls['departement']['children'][$j]['url'] = $this->generateUrl('page', ['slug' => "le-territoire"]);
$urls['departement']['children'][$j]['name'] = "Le territoire";
$j++;
$urls['departement']['children'][$j]['url'] = $this->generateUrl('page', ['slug' => "les-competences"]);
$urls['departement']['children'][$j]['name'] = "Les compétences";
$j++;
$urls['departement']['children'][$j]['url'] = $this->generateUrl('page', ['slug' => "le-conseil-departemental"]);
$urls['departement']['children'][$j]['name'] = "L'institution";
$j++;
$urls['departement']['children'][$j]['url'] = $this->generateUrl('contacts');
$urls['departement']['children'][$j]['name'] = "Les cantons et leurs élus";
$j++;
$types = $this->em->getRepository(TypeOrganisation::class)->findAll();
foreach ($types as $type) {
$urls['departement']['children'][$j]['url'] = $this->generateUrl('organisations', ['type' => $type->getName()]);
$urls['departement']['children'][$j]['name'] = $type->getTitreListe();
$j++;
}
$urls['legal']['parent']['url'] = "";
$urls['legal']['parent']['name'] = "Pages légales";
$j = 0;
$urls['legal']['children'][$j]['url'] = $this->generateUrl('post_detail', ['slug' => 'mentions-legales-nordinfo']);
$urls['legal']['children'][$j]['name'] = "Mentions légales";
$j++;
$urls['legal']['children'][$j]['url'] = $this->generateUrl('post_detail', ['slug' => 'cgu']);
$urls['legal']['children'][$j]['name'] = "Conditions générales";
$j++;
$urls['legal']['children'][$j]['url'] = $this->generateUrl('post_detail', ['slug' => 'accessibilite-nordinfo']);
$urls['legal']['children'][$j]['name'] = "Accessibilité";
$urls['form']['parent']['url'] = "";
$urls['form']['parent']['name'] = "Support";
$j = 0;
$urls['form']['children'][$j]['url'] = $this->generateUrl('signaler');;
$urls['form']['children'][$j]['name'] = "Contact";
$urls['sitemap_page']['parent']['url'] = $this->generateUrl('sitemap');
$urls['sitemap_page']['parent']['name'] = 'Plan du site';
$this->params['urls'] = $urls;
return $this->render('Nordinfo/Main/sitemap.html.twig', $this->params);
}
#[Route(path: '/sitemap.xml', name: 'nordinfo_plandusite_xml')]
public function services_plandusite_xml(): Response
{
$domain = "https://info.lenord.fr";
$dom = new \DOMDocument('1.0', 'UTF-8');
$rss = $dom->createElement('urlset');
$rss->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
$rss_node = $dom->appendChild($rss);
$url = $dom->createElement('url');
$url_node = $rss_node->appendChild($url);
$url_node->appendChild($dom->createElement('loc', $domain . $this->generateUrl('index')));
$url = $dom->createElement('url');
$url_node = $rss_node->appendChild($url);
$url_node->appendChild($dom->createElement('loc', $domain . $this->generateUrl('actus')));
$url = $dom->createElement('url');
$url_node = $rss_node->appendChild($url);
$url_node->appendChild($dom->createElement('loc', $domain . $this->generateUrl('info')));
$url = $dom->createElement('url');
$url_node = $rss_node->appendChild($url);
$url_node->appendChild($dom->createElement('loc', $domain . $this->generateUrl('agenda')));
$url = $dom->createElement('url');
$url_node = $rss_node->appendChild($url);
$url_node->appendChild($dom->createElement('loc', $domain . $this->generateUrl('videos')));
$url = $dom->createElement('url');
$url_node = $rss_node->appendChild($url);
$url_node->appendChild($dom->createElement('loc', $domain . $this->generateUrl('favoris')));
$url = $dom->createElement('url');
$url_node = $rss_node->appendChild($url);
$url_node->appendChild($dom->createElement('loc', $domain . $this->generateUrl('vos_lieux')));
$url = $dom->createElement('url');
$url_node = $rss_node->appendChild($url);
$url_node->appendChild($dom->createElement('loc', $domain . $this->generateUrl('topics')));
$url = $dom->createElement('url');
$url_node = $rss_node->appendChild($url);
$url_node->appendChild($dom->createElement('loc', $domain . $this->generateUrl('departement')));
$url = $dom->createElement('url');
$url_node = $rss_node->appendChild($url);
$url_node->appendChild($dom->createElement('loc', $domain . $this->generateUrl('page', ['slug' => "le-territoire"])));
$url = $dom->createElement('url');
$url_node = $rss_node->appendChild($url);
$url_node->appendChild($dom->createElement('loc', $domain . $this->generateUrl('page', ['slug' => "les-competences"])));
$url = $dom->createElement('url');
$url_node = $rss_node->appendChild($url);
$url_node->appendChild($dom->createElement('loc', $domain . $this->generateUrl('page', ['slug' => "le-conseil-departemental"])));
$url = $dom->createElement('url');
$url_node = $rss_node->appendChild($url);
$url_node->appendChild($dom->createElement('loc', $domain . $this->generateUrl('contacts')));
$types = $this->em->getRepository(TypeOrganisation::class)->findAll();
foreach ($types as $type) {
$url = $dom->createElement('url');
$url_node = $rss_node->appendChild($url);
$url_node->appendChild($dom->createElement('loc', $domain . $this->generateUrl('organisations', ['type' => $type->getName()])));
}
//Posts
$posts = $this->em->getRepository(Post::class)->findBy(['status' => 5]);
$date = new DateTime();
foreach ($posts as $post) {
if ($post->getSlug() != null) {
$date_update = date_create_from_format('Y-m-d H:i:s', $post->getDateDernierStatut());
$date_update = ($date_update != false) ? $date_update->format('Y-m-d') : $date->format('Y-m-d');
$url = $dom->createElement('url');
$url_node = $rss_node->appendChild($url);
$url_node->appendChild($dom->createElement('loc', $domain . $this->generateUrl('post_detail', ['slug' => $post->getSlug(), 'archive' => false])));
//$url_node->appendChild($dom->createElement('lastmod', $post->getDateUpdate()->format('Y-m-d')));
$url_node->appendChild($dom->createElement('changefreq', 'monthly'));
$url_node->appendChild($dom->createElement('lastmod', $date_update));
}
}
$url = $dom->createElement('url');
$url_node = $rss_node->appendChild($url);
$url_node->appendChild($dom->createElement('loc', $domain . $this->generateUrl('post_detail', ['slug' => 'mentions-legales-nordinfo'])));
$url = $dom->createElement('url');
$url_node = $rss_node->appendChild($url);
$url_node->appendChild($dom->createElement('loc', $domain . $this->generateUrl('post_detail', ['slug' => 'cgu'])));
$url = $dom->createElement('url');
$url_node = $rss_node->appendChild($url);
$url_node->appendChild($dom->createElement('loc', $domain . $this->generateUrl('post_detail', ['slug' => 'accessibilite-nordinfo'])));
$url = $dom->createElement('url');
$url_node = $rss_node->appendChild($url);
$url_node->appendChild($dom->createElement('loc', $domain . $this->generateUrl('signaler')));
$url = $dom->createElement('url');
$url_node = $rss_node->appendChild($url);
$url_node->appendChild($dom->createElement('loc', $domain . $this->generateUrl('sitemap')));
$xml = $dom->saveXML();
$response = new Response($xml);
$response->headers->set('Content-Type', 'text/xml');
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
}
#[Route(path: '/console2021/apercu/{id}', name: 'apercu_post')]
public function apercu_post(Request $request, mixed $id): Response
{
$this->params['actus'] = false;
$this->params['admin'] = true;
$this->params['favorite'] = false;
$this->params['referer'] = $request->headers->get('referer');
$post = $this->em->getRepository(Post::class)->findOneBy(['slug' => $id]);
$this->params['short_description'] = $post?->getShortDescription();
$this->params['is_preview'] = true;
$content_post = null;
if ($post?->getContent() !== null) {
$content_post = $this->feedUtilities->jsonToHtml($post?->getContent(), $request);
}
if ($post?->getType()?->getType() === 'folder') {
$this->params['related_posts'] = $post?->getRelatedPosts();
$this->params['related_posts'] = $this->feedUtilities->social_posts_padding($this->params['related_posts'], $request);
} else {
$this->params['related_posts'] = $this->getRelatedPosts($post);
}
$this->params['content_post'] = $content_post;
$this->params['post'] = $post;
if ($post?->getType()?->getType() === 'folder') {
$k = 0;
foreach ($this->params['related_posts'] as $p) {
$this->params['related_posts'][$k]->str_date = $this->formatJsonDate($p->getJson());
$k++;
}
return $this->render('Nordinfo/Main/detail_folder.html.twig', $this->params);
}
$url = $post?->getSubtitle();
if ($post?->getType()?->getType() === "video") {
$this->params['youtube_video_id'] = $url;
}
if ($post?->getType()?->getType() === "event") {
$json_convert_dates = $this->formatDateAgendaJson($post?->getJson());
$this->params['ics_date_debut'] = $json_convert_dates['ics_date_debut'];
$this->params['ics_date_fin'] = $json_convert_dates['ics_date_fin'];
$this->params['event_date'] = $json_convert_dates['date_string'];
$this->params['event_heures'] = $json_convert_dates['heure_string'];
$this->params['event_lieu'] = null;
$this->params['event_ville'] = null;
$this->params['event_adresse'] = null;
}
if ($post?->getType()?->getType() === 'pub' || $post?->getType()?->getType() === 'socialpost') {
return new Response("Pas d'aperçu possible pour ce type de post");
}
return $this->render('Nordinfo/Main/detail_post.html.twig', $this->params);
}
#[Route(path: '/send_form_custom/{alias}', name: 'send_form_custom_info', host: "info.lenord.fr")]
public function send_form_custom(Request $request, string $alias): Response
{
$post = $request->request;
$custom_form = $this->em->getRepository(CustomForm::class)->findOneBy(array('alias' => $alias));
$destinataires_sendgrid = [];
$objet = null;
$objet = "Votre message à " . $custom_form->getDestinataire() . " via le site Nord info";
$emails = explode(";", (string)$custom_form->getEmail());
for ($i = 0; $i < count($emails); $i++) {
array_push($destinataires_sendgrid, $emails[$i]);
}
$message = $post->get('message');
//exp
//destinataire_
//objet_
//message_
//piece_jointe_
$fileName = null;
$auth_extension = ['png', 'jpg', 'jpeg', 'gif', 'pdf'];
$mime_authorized = ['application/pdf', 'image/jpg', 'image/jpeg', 'image/gif', 'image/png'];
$file = null;
$newname = uniqid();
if ($request->files != null && $request->files->get('file') != null) {
$file = $request->files->get('file');
$fileName = $file->getClientOriginalName();
$fileType = $file->getClientMimeType();
if (in_array($file->guessExtension(), $auth_extension) && in_array($fileType, $mime_authorized)) {
try {
/*$file->move($uploadDir, $newname.'.'.$file->guessExtension());
array_push($files, array(
'name' => $newname.'.'.$file->guessExtension(),
'type' => $fileType,
'data' => $fileData,
));*/
} catch (FileException) {
$file = null;
return new JsonResponse(['error' => 'File could not be uploaded']);
}
} else {
$file = null;
return new JsonResponse(['error' => "Mauvais format d'image"]);
}
}
$date = new DateTime;
$content = "Le message suivant vient de vous être envoyé via le site Nord info par " . $post->get('nom_prenom') .
" - Merci de répondre directement à " . $post->get('email') . " : " . "\n" . $post->get('message') . "\n\n" . "Nord, le Département est là - https://info.lenord.fr/";
$nom_dest = $custom_form->getDestinataire();
$content_exp = "Bonjour, votre message a été transmis à " . $nom_dest . "." . "\n\n" .
"Message : " . $post->get('message');
if ($fileName !== null) {
$content_exp .= "\n" . "Pièce jointe : " . $fileName;
}
$content_exp .= "\n\n" . "Nord, le Département est là - https://info.lenord.fr/";
/*$content_exp = $this->renderView(
'Nordinfo/Mails/exp_signalement_custom.html.twig',
['destinataire_' => $nom_dest, 'objet_' => $objet, 'message_' => $message, 'piece_jointe_' => ($fileName != null) ? $fileName : "Aucune pièce jointe", 'date' => "NI".$date->format('dmYHis')]
);*/
//envoi mail
$result_ = $post->get('nb1') + $post->get('nb2');
if ($result_ == $post->get('captcha') && $post->get('raison') == null) {
try {
//$this->sendMail($content, 'Demande de contact depuis nordinfo : ' . $objet, $destinataires, $files);
//FILES!
$this->sendgrid_service->send($destinataires_sendgrid, $content, "Message envoyé par " . $post->get('nom_prenom') . " via le site Nord info", null, $file, false, $post->get('email'));
//$this->mail_service->sendTransacEmail('nordinfo@info-lenord.fr', 'Nord info contact', $destinataires, $content, 'Demande de contact depuis nordinfo : ' . $objet);
$this->sendgrid_service->send([$post->get('email')], $content_exp, $objet, null, $file, false);
//$this->mail_service->sendTransacEmail('nordinfo@info-lenord.fr', 'Nord info contact', $post->get('email'), $content_exp, "Nord info - Envoi d’un message ");
} catch (\Exception) {
$this->params['message'] = 'Email erreur';
return $this->render('Nordinfo/Main/endformerror.html.twig', $this->params);
}
} else {
$this->params['message'] = 'Catcha erreur';
return $this->render('Nordinfo/Main/endformerror.html.twig', $this->params);
}
return $this->render('Nordinfo/Main/endform.html.twig', $this->params);
}
#[Route(path: '/{slug}', name: 'post_detail')]
public function detail_post(Request $request, string $slug): Response
{
if ($request->get('function') === 'download_pdf') {
$this->params['is_pdf'] = 1;
}
$post = $this->em->getRepository(Post::class)->findOneBy(['slug' => $slug]);
if ($post === null) {
return $this->pagelegales($request, $slug);
}
if ($post->getArchive() === true) {
return $this->error($request);
}
$presse = false;
$vip = false;
$agent = false;
$topics_list = null;
foreach ($post->getTargetpublics() as $topic) {
if ($topic->getId() == 3) {
$presse = true;
}
if ($topic->getId() == 2) {
$vip = true;
}
if ($topic->getId() == 4) {
$agent = true;
}
$topics_list .= ($topics_list != null) ? ', ' : '';
$topics_list .= $topic->getName();
}
if ($post->getStatus()?->getId() !== 5) {
return $this->redirectToRoute('error', ['_format' => 'html', 'code' => '404']);
}
if ($post->getType()?->getId() === 8 && $this->getUser() == null) {
return $this->redirect('info');
}
if ($presse && ($this->getUser() == null || $this->getUser()->getRole() != 'presse')) {
return $this->redirectToRoute('error', ['_format' => 'html', 'code' => '404']);
}
if ($vip && ($this->getUser() == null || $this->getUser()->getRole() != 'vip')) {
return $this->redirectToRoute('error', ['_format' => 'html', 'code' => '404']);
}
if ($agent && ($this->getUser() == null || $this->getUser()->getRole() != 'agent')) {
return $this->redirectToRoute('error', ['_format' => 'html', 'code' => '404']);
}
$this->params['referer'] = $request->headers->get('referer');
$this->params['post'] = $post;
$content_post = null;
if ($post->getContent() != null) {
$content_post = $this->feedUtilities->jsonToHtml($post->getContent(), $request, $post->getTitle());
}
$this->params['short_description'] = $post->getSubtitle();
$url = $post->getSubtitle();
if ($post->getType()->getType() === "video") {
$this->params['youtube_video_id'] = $url;
}
$this->params['breadcrumb'] = $this->setBreadCrumb($post);
$this->params['content_post'] = $content_post;
$this->params['favorite'] = $this->isFavorite($post, $this->getUser(), $request);
if ($post->getType()?->getType() === 'folder') {
$iterator = $post->getRelatedPosts()->getIterator();
$iterator->uasort(fn ($a, $b) => ($a->getOrderFolder() > $b->getOrderFolder()) ? -1 : 1);
$rarray = [];
$array = new ArrayCollection(iterator_to_array($iterator));
foreach ($array as $po) {
$rarray[] = $po;
}
$this->params['related_posts'] = $rarray;
} else {
$this->params['related_posts'] = $this->getRelatedPosts($post);
}
$this->params['related_posts'] = $this->feedUtilities->checkboxes_get_description($this->params['related_posts'], $request);
$this->params['related_posts'] = $this->feedUtilities->social_posts_padding($this->params['related_posts'], $request);
$this->params['related_posts'] = $this->feedUtilities->social_posts_detect_links($this->params['related_posts']);
$this->params['related_posts'] = $this->feedUtilities->focus_pub_img_dimensions($this->params['related_posts'], $request);
$this->params['openGraph'] = ["url" => "https://info.lenord.fr/" . $post->getSlug(), "type" => "article", "title" => $post->getTitle(), "image" => "https://info.lenord.fr/upload/images/" . $post->getIllustrationFilName(), "description" => $content_post];
$this->params['twitter_card'] = ["card" => "summary", "site" => "@info.lenord.fr"];
$this->params['articleSchema'] = [];
$this->params['placement_image'] = 'placement2';
if ($post->getType()?->getType() === 'event') {
$json_convert_dates = $this->formatDateAgendaJson($post->getJson());
$this->params['ics_date_debut'] = $json_convert_dates['ics_date_debut'];
$this->params['ics_date_fin'] = $json_convert_dates['ics_date_fin'];
$this->params['event_date'] = $json_convert_dates['date_string'];
$this->params['event_heures'] = $json_convert_dates['heure_string'];
$this->params['event_lieu'] = null;
$this->params['event_ville'] = null;
if ($post->getLieuNew() !== null) {
$this->params['event_lieu'] = $post->getLieuNew()->getName();
$this->params['event_ville'] = $post->getLieuNew()->getVille();
}
$this->params['event_adresse'] = null;
$date_debut = null;
$date_fin = null;
$start_date = null;
$end_date = null;
if ($post->getDateDebut() !== null) {
$date_debut = date_create_from_format('d/m/Y', $post->getDateDebut());
$start_date = $date_debut->format('c');
}
if ($post->getDateFin() !== null) {
$date_fin = date_create_from_format('d/m/Y', $post->getDateFin());
$end_date = $date_fin->format('c');
}
$schema_params = [
'startDate' => $start_date,
'endDate' => $end_date,
'inLanguage' => 'FR',
'isAccessibleForFree' => ($post->getTarifs() != null) ? true : false,
'location' => $post->getLieu() . ' ' . $post->getVille(),
'organizer' => $post->getOrganizedBy(),
'name' => $post->getTitle(),
'description' => $content_post,
'image' => "https:/info.lenord.fr/upload/images/" . $post->getIllustrationFilName(),
//'sameAs'
'url' => "https:/info.lenord.fr/" . $post->getSlug(),
];
$this->params['articleSchema'] = $this->schema_service->generateSchema($schema_params, 'Event');
} else {
$currentRoute = $request->attributes->get('_route');
$currentUrl = $this->generateUrl($currentRoute, ['slug' => $slug], true);
$schema_params = ['mainEntityOfPage' => $currentUrl, 'image' => "https:/info.lenord.fr/upload/images/" . $post->getIllustrationDetailName(), 'articleBody' => $content_post, 'articleSection' => $topics_list, 'headline' => $post->getTitle(), 'description' => $post->getShortDescription(), 'url' => "https:/info.lenord.fr/" . $post->getSlug(), 'thumbnailUrl' => "https:/info.lenord.fr/upload/images/" . $post->getIllustrationFilName(), 'author' => ["@type" => "Person", "name" => $post->getCreatedBy()?->getFirstName() . ' ' . $post->getCreatedBy()?->getLastName()], 'dateCreated' => $post->getCreatedAt(), 'dateModified' => $post->getUpdatedAt(), 'datePublished' => $post->getDateDebut(), 'publisher' => ["@type" => "Organization", "name" => "Département du Nord", 'logo' => ["@type" => "ImageObject", "url" => "https://lenord.fr/upload/docs/image/png/2020-06/logo_nord_vlenord.png"]], 'creativeWorkStatus' => $post->getStatus()->getName()];
$this->params['articleSchema'] = $this->schema_service->generateSchema($schema_params, 'NewsArticle');
}
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
if ($request->get('function') === 'download_pdf') {
$pdfOptions = new Options();
$pdfOptions->set('defaultFont', 'Arial');
$pdfOptions->setIsRemoteEnabled(true);
$dompdf = new Dompdf($pdfOptions);
$html = $this->renderView('Nordinfo/Main/detail_post.html.twig', $this->params);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$output = $dompdf->output();
$filename = sprintf('nord-info-%s.pdf', $post->getTitle());
return new Response(
$output,
200,
[
'Content-Type' => 'application/pdf',
'Content-Disposition' => sprintf('attachment; filename="%s"', "$filename"),
]
);
} else {
if ($post->getPositionImage() !== null && $post->getPositionImage()?->getId() === 1) {
$this->params['placement_image'] = 'placement1';
} else if ($post->getPositionImage()?->getId() === 3) {
$this->params['placement_image'] = 'placement3';
}
if ($post->getType()->getType() == 'folder') {
$k = 0;
foreach ($this->params['related_posts'] as $p) {
$this->params['related_posts'][$k]->str_date = $this->formatJsonDate($p->getJson());
$k++;
}
return $this->render('Nordinfo/Main/detail_folder.html.twig', $this->params);
}
return $this->render('Nordinfo/Main/detail_post.html.twig', $this->params);
}
}
private function formatJsonDate(mixed $json): mixed
{
$str_date = null;
$current_date = new DateTime();
$current_date->setTime(0, 0, 0);
$json_horaires = json_decode($json, true);
if ($json_horaires !== null) {
switch ($json_horaires['modeDates']) {
case "range":
//de date debut a date fin
$date_debut = date_create_from_format('d/m/Y', $json_horaires['datesRange']['dateStart']);
$date_fin = date_create_from_format('d/m/Y', $json_horaires['datesRange']['dateFinish']);
$ics_date_debut = $json_horaires['datesRange']['dateStart'];
$ics_date_fin = $json_horaires['datesRange']['dateStart'];
$evDateDebut = $this->formatStringDate($date_debut);
$evDateFin = $this->formatStringDate($date_fin);
$same_day = false;
if ($evDateDebut['day'] == $evDateFin['day']) {
if ($evDateDebut['month'] == $evDateFin['month']) {
$same_day = true;
}
}
if ($evDateDebut['day'] == 1 || $evDateDebut['day'] == '01' || $evDateDebut['day'] == '1') {
$day_debut = $this->array_date_trad["fr"][1];
} else {
$day_debut = $evDateDebut['day'];
}
if ($evDateDebut['month'] == $evDateFin['month'] && $evDateDebut['year'] == $evDateFin['year']) {
if ($same_day) {
//$this->translator->trans('du') . ' ' .
$str_date = $evDateFin['day'] . ' ' . $evDateFin['month'];
} else {
$str_date = 'Du ' . $day_debut . ' au ' . $evDateFin['day'] . ' ' . $evDateFin['month'];
}
} else {
//check year de la date debut et fin
if ($evDateDebut['year'] !== $evDateFin['year']) {
$str_date = 'Du ' . $day_debut . ' ' . $evDateDebut['month'] . ' ' . $evDateDebut['year'] . ' au ' . $evDateFin['day'] . ' ' . $evDateFin['month'] . ' ' . $evDateFin['year'];
} else {
$str_date = 'Du ' . $day_debut . ' ' . $evDateDebut['month'] . ' au ' . $evDateFin['day'] . ' ' . $evDateFin['month'] . ' ' . $evDateFin['year'];
}
}
break;
case 'multiple':
$nombre_date = 0;
$dates_multiples = [];
$dates = $json_horaires['datesMultiple']['dates'];
foreach ($dates as $d) {
array_push($dates_multiples, $d);
}
$date = null;
$array_dates = $dates_multiples;
$i = 0;
foreach ($array_dates as $d) {
if ($i > 0) {
$str_date .= ", ";
}
$date = date_create_from_format('d/m/Y', $dates_multiples[$i]);
$str_date .= $date->format('d') . ' ' . $this->months["fr"][$date->format('n')] . ' ' . $date->format('Y');
$i++;
}
break;
case 'single':
$start_date = date_create_from_format('d/m/Y', $json_horaires['dateSingle']['dates'][0]);
$day = 'Le ' . $start_date->format('d');
$str_date .= $day;
$str_month = $this->months["fr"][$start_date->format('n')];
$str_date .= ' ' . $str_month;
$str_date .= ' ' . $start_date->format('Y');
break;
}
}
return $str_date;
}
public function pagelegales(Request $request, string $slug): Response
{
$this->params['referer'] = $request->headers->get('referer');
if ($slug == "comprendre-le-departement") {
return $this->redirectToRoute('comprendre_le_departement');
}
$post = $this->em->getRepository(PagesLegales::class)->findOneBy(['slug' => $slug, 'actif' => 1]);
if(!$post){
throw $this->createNotFoundException('La page demandée n\'existe pas.');
}
$this->params['post'] = $post;
$this->params['breadcrumb'] = $this->setBreadCrumb(null, $this->params['post']->getTitre());
//epingle
$this->params['epingles'] = $this->epingle_service->getEpingles('nordinfo');
$epingles_ = $this->epingle_service->getEpinglesSection('legales_nordinfo');
foreach ($epingles_ as $epingle) {
array_push($this->params['epingles'], $epingle);
}
if ($request->get('function') == 'download_pdf') {
$this->params['is_pdf'] = 1;
$pdfOptions = new Options();
$pdfOptions->set('defaultFont', 'Arial');
$pdfOptions->setIsRemoteEnabled(true);
$dompdf = new Dompdf($pdfOptions);
$html = $this->renderView('Nordinfo/Main/detail_page_legale.html.twig', $this->params);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$output = $dompdf->output();
$filename = sprintf('nord-info-%s.pdf', $this->params['post']->getTitre());
return new Response(
$output,
200,
[
'Content-Type' => 'application/pdf',
'Content-Disposition' => sprintf('attachment; filename="%s"', "$filename"),
]
);
} else {
return $this->render('Nordinfo/Main/detail_page_legale.html.twig', $this->params);
}
}
#[Route(path: '/ajax/getServicesAll', name: 'services_ajax_getServicesAllNordInfo')]
public function getServicesAllNordInfo(Request $request): Response
{
$services = $this->em->getRepository(Service::class)->getServicesByGrandprofil($request->request->get('alias'));
return new JsonResponse(['datas' => $services]);
}
private mixed $months = array(
'fr' => array(
1 => 'janvier',
2 => 'février',
3 => 'mars',
4 => 'avril',
5 => 'mai',
6 => 'juin',
7 => 'juillet',
8 => 'août',
9 => 'septembre',
10 => 'octobre',
11 => 'novembre',
12 => 'décembre'
),
'en' => array(
1 => 'January',
2 => 'February',
3 => 'March',
4 => 'April',
5 => 'May',
6 => 'June',
7 => 'July',
8 => 'August',
9 => 'September',
10 => 'October',
11 => 'November',
12 => 'December',
),
'nl' => array(
1 => 'januari',
2 => 'februari',
3 => 'maart',
4 => 'april',
5 => 'mei',
6 => 'juni',
7 => 'juli',
8 => 'augustus',
9 => 'september',
10 => 'oktober',
11 => 'november',
12 => 'december'
)
);
private function formatStringDate(mixed $date): mixed
{
if ($date instanceof DateTime) {
return array(
'day' => $date->format('j'),
'month' => $this->months["fr"][$date->format('n')],
'year' => $date->format('Y')
);
}
return array(
'day' => null,
'month' => null,
'year' => null
);
}
private mixed $array_date_trad = array(
'fr' => array(
1 => '1er'
),
'en' => array(
1 => '1st'
),
'nl' => array(
1 => '1st'
)
);
private function formatDateAgendaJson(string $json): mixed
{
$str_date = null;
$current_date = new DateTime();
$current_date->setTime(0, 0, 0);
$json_horaires = json_decode($json, true);
$ics_date_debut = null;
$ics_date_fin = null;
$str_heure = null;
if ($json_horaires !== null) {
switch ($json_horaires['modeDates']) {
case "range":
//de date debut a date fin
$date_debut = date_create_from_format('d/m/Y', $json_horaires['datesRange']['dateStart']);
$date_fin = date_create_from_format('d/m/Y', $json_horaires['datesRange']['dateFinish']);
$ics_date_debut = $json_horaires['datesRange']['dateStart'];
$ics_date_fin = $json_horaires['datesRange']['dateStart'];
$evDateDebut = $this->formatStringDate($date_debut);
$evDateFin = $this->formatStringDate($date_fin);
$same_day = false;
if ($evDateDebut['day'] == $evDateFin['day']) {
if ($evDateDebut['month'] == $evDateFin['month']) {
$same_day = true;
}
}
if ($evDateDebut['day'] == 1 || $evDateDebut['day'] == '01' || $evDateDebut['day'] == '1') {
$day_debut = $this->array_date_trad["fr"][1];
} else {
$day_debut = $evDateDebut['day'];
}
if ($evDateDebut['month'] == $evDateFin['month'] && $evDateDebut['year'] == $evDateFin['year']) {
if ($same_day) {
//$this->translator->trans('du') . ' ' .
$str_date = $evDateFin['day'] . ' ' . $evDateFin['month'];
} else {
$str_date = 'Du ' . $day_debut . ' au ' . $evDateFin['day'] . ' ' . $evDateFin['month'];
}
} else {
//check year de la date debut et fin
if ($evDateDebut['year'] !== $evDateFin['year']) {
$str_date = 'Du ' . $day_debut . ' ' . $evDateDebut['month'] . ' ' . $evDateDebut['year'] . ' au ' . $evDateFin['day'] . ' ' . $evDateFin['month'] . ' ' . $evDateFin['year'];
} else {
$str_date = 'Du ' . $day_debut . ' ' . $evDateDebut['month'] . ' au ' . $evDateFin['day'] . ' ' . $evDateFin['month'] . ' ' . $evDateFin['year'];
}
}
if ($json_horaires['datesRange']['modeHours'] == 'simple') {
if ($json_horaires['datesRange']['hoursSimple'][0]['hour1'] !== null && $json_horaires['datesRange']['hoursSimple'][0]['hour2'] != null) {
$str_heure .= str_replace(":", "h", $json_horaires['datesRange']['hoursSimple'][0]['hour1']) . " - " . str_replace(":", "h", $json_horaires['datesRange']['hoursSimple'][0]['hour2']);
}
if ($json_horaires['datesRange']['hoursSimple'][0]['hour3'] !== null && $json_horaires['datesRange']['hoursSimple'][0]['hour4'] != null) {
$str_heure .= " et " . str_replace(":", "h", $json_horaires['datesRange']['hoursSimple'][0]['hour3']) . " - " . str_replace(":", "h", $json_horaires['datesRange']['hoursSimple'][0]['hour4']);
}
}
$str_date = '<strong>' . $str_date . '</strong>';
break;
case 'multiple':
$nombre_date = 0;
$dates_multiples = [];
$dates = $json_horaires['datesMultiple']['dates'];
foreach ($dates as $d) {
$date_json = date_create_from_format('d/m/Y', $d);
if ($date_json >= $current_date) {
array_push($dates_multiples, $d);
}
}
$nombre_date = count($dates_multiples);
$ics_date_debut = $dates_multiples[0];
$ics_date_fin = $dates_multiples[0];
if ($json_horaires['datesMultiple']['modeHours'] == 'simple') {
$date = null;
if ($nombre_date == 1) {
$date1 = date_create_from_format('d/m/Y', $dates_multiples[0]);
$str_date .= 'Le ' . $date1->format('d') . ' ' . $this->months["fr"][$date1->format('n')];
} else if ($nombre_date == 2) {
$date1 = date_create_from_format('d/m/Y', $dates_multiples[0]);
$date2 = date_create_from_format('d/m/Y', $dates_multiples[1]);
$str_date .= 'Les ' . $date1->format('d') . ' ' . $this->months["fr"][$date1->format('n')] . ' et ' . $date2->format('d') . ' ';
$str_month = $this->months["fr"][$date2->format('n')];
$str_date .= ' ' . $str_month;
} else if ($nombre_date == 3) {
$date1 = date_create_from_format('d/m/Y', $dates_multiples[0]);
$date2 = date_create_from_format('d/m/Y', $dates_multiples[1]);
$date3 = date_create_from_format('d/m/Y', $dates_multiples[2]);
$str_date .= 'Les ' . $date1->format('d') . ' ' . $this->months["fr"][$date1->format('n')] . ', ' . $date2->format('d') . ' ' . $this->months["fr"][$date2->format('n')] . ' et ' . $date3->format('d') . ' ' . $this->months["fr"][$date3->format('n')];
} else if ($nombre_date > 3) {
$array_dates = $dates_multiples;
$i = 0;
foreach ($array_dates as $d) {
if ($i > 0) {
$str_date .= "<br>";
}
$date = date_create_from_format('d/m/Y', $dates_multiples[$i]);
$str_date .= $date->format('d') . ' ' . $this->months["fr"][$date->format('n')] . ' ' . $date->format('Y');
$i++;
}
}
$str_date = '<strong>' . $str_date . '</strong>';
if ($json_horaires['datesMultiple']['hoursSimple'][0]['hour1'] !== null && $json_horaires['datesMultiple']['hoursSimple'][0]['hour2'] != null) {
$str_heure .= str_replace(":", "h", $json_horaires['datesMultiple']['hoursSimple'][0]['hour1']) . ' - ' . str_replace(":", "h", $json_horaires['datesMultiple']['hoursSimple'][0]['hour2']);
}
if ($json_horaires['datesMultiple']['hoursSimple'][0]['hour3'] !== null && $json_horaires['datesMultiple']['hoursSimple'][0]['hour4'] != null) {
$str_heure .= " et " . str_replace(":", "h", $json_horaires['datesMultiple']['hoursSimple'][0]['hour3']) . " - " . str_replace(":", "h", $json_horaires['datesMultiple']['hoursSimple'][0]['hour4']);
}
} else if ($json_horaires['datesMultiple']['modeHours'] == 'details') {
$hoursDetails = $json_horaires['datesMultiple']['hoursDetails'];
$i = 0;
foreach ($hoursDetails as $hour) {
$start_date = date_create_from_format('d/m/Y', $hour['date']);
if ($start_date <= $current_date) {
continue;
}
if ($i > 0) {
$str_date .= "<br>";
}
if ($hour['hour1'] !== null && $hour['hour2'] != null) {
$str_date .= '<strong>' . $start_date->format('d') . ' ' . $this->months["fr"][$start_date->format('n')] . ' ' . $start_date->format('Y') . '</strong>, ' .
str_replace(":", "h", $hour['hour1']) . ' - ' . str_replace(":", "h", $hour['hour2']);
}
if ($hour['hour3'] !== null && $hour['hour4'] != null) {
$str_date .= ' et ' . str_replace(":", "h", $hour['hour3']) . ' - ' . str_replace(":", "h", $hour['hour4']);
}
$i++;
}
}
break;
case 'single':
$start_date = date_create_from_format('d/m/Y', $json_horaires['dateSingle']['dates'][0]);
$ics_date_debut = $json_horaires['dateSingle']['dates'][0];
$ics_date_fin = $json_horaires['dateSingle']['dates'][0];
$day = $start_date->format('d');
if ($start_date->format('d') == 1 || $start_date->format('d') == '01') {
$day = "1er";
}
$str_date .= 'Le ' . $day;
$str_month = $this->months["fr"][$start_date->format('n')];
$str_date .= ' ' . $str_month;
if ($start_date->format('Y') != $current_date->format('Y')) {
$str_date .= ' ' . $start_date->format('Y');
}
if ($json_horaires['dateSingle']['hoursSimple'][0]['hour1'] !== null && $json_horaires['dateSingle']['hoursSimple'][0]['hour2'] != null) {
$str_heure .= $json_horaires['dateSingle']['hoursSimple'][0]['hour1'] . ' - ' . $json_horaires['dateSingle']['hoursSimple'][0]['hour2'];
}
if ($json_horaires['dateSingle']['hoursSimple'][0]['hour3'] !== null && $json_horaires['dateSingle']['hoursSimple'][0]['hour4'] != null) {
$str_heure .= " et " . $json_horaires['dateSingle']['hoursSimple'][0]['hour3'] . " - " . $json_horaires['dateSingle']['hoursSimple'][0]['hour4'];
}
$str_date = '<strong>' . $str_date . '</strong>';
break;
}
}
return [
"date_string" => $str_date,
"ics_date_debut" => $ics_date_debut,
"ics_date_fin" => $ics_date_fin,
"heure_string" => $str_heure
];
}
}