<?php
/**
* Created by PhpStorm.
* User: anthony
* Date: 25/05/18
* Time: 10:45
*/
namespace App\Controller;
use App\Entity\Actualite;
use App\Entity\Auth\AuthUser;
use App\Entity\Client;
use App\Entity\ClientRoleUser;
use App\Entity\Coupure;
use App\Entity\Email\AdresseMailVerif;
use App\Entity\Email\EmailRetour;
use App\Entity\Mailling;
use App\Entity\PieceJointeMailling;
use App\Entity\ThemeDescriptif;
use App\Entity\Veille;
use App\Ovh\OvhSend;
use App\Service\Coupure\GenerateCoupureInterface;
use App\Service\Ftp\FtpGetPieceJointe;
use App\Service\MaillingEnCour\MaillingEnCour;
use Doctrine\ORM\EntityManagerInterface;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Spipu\Html2Pdf\Html2Pdf;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\Normalizer\PropertyNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Doctrine\Common\Annotations\AnnotationReader;
use PDO;
class MaillingController extends Controller
{
/**
* @Route("api/maillings/maillings/getErreur/{idMailling}", methods={"GET"}, name="get.erreur.mailling.en.cours")
*/
public function getErreurMaillingEnCourAction($idMailling, EntityManagerInterface $em, MaillingEnCour $maillingEnCour){
$maillingEnCoursErreur = $maillingEnCour->getMaillingErreur($idMailling);
$encoders = array(new XmlEncoder(), new JsonEncoder());
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$normalizer = new PropertyNormalizer($classMetadataFactory);
$dateTimeNormalizer = new DateTimeNormalizer('d-m-y H:i');
$serializer = new Serializer([$normalizer,$dateTimeNormalizer], $encoders);
$jsonContent = $serializer->normalize($maillingEnCoursErreur, null, array('groups' => array('email_retour')));
$response = new JsonResponse($jsonContent);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* @Route("/maillings/content/{id}",methods={"GET"},name="get.mailling.content")
*/
public function getMaillingContentAction($id, Request $request, KernelInterface $kernel)
{
$em = $this->get('doctrine.orm.entity_manager');
$mailling = $em->getRepository('App\Entity\Mailling')
->find($request->get('id'));
$path = $kernel->getRootDir() . '/../public/maillings/' . $mailling->getAncienId() . '.html';
$read = file_get_contents($path);
return new JsonResponse(utf8_encode($read));
}
/**
* @Route("/maillings/getNbEnvoyer/{id}",methods={"GET"},name="get.mailling.nb.envoyer")
*/
public function getMaillingNbEnvoyer($id)
{
$em = $this->get('doctrine.orm.entity_manager');
$mailling = $em->getRepository('App\Entity\Mailling')
->findOneBy(['ancienId' => $id]);
return new JsonResponse($mailling->getNbMailEnvoye());
}
/**
* @Route("/maillings/checkDelete",methods={"GET"},name="mail.check")
*/
public function getCheckMailAction()
{
$em = $this->get('doctrine.orm.entity_manager');
$maillings = $em->getRepository("App\Entity\Mailling")
->findBy(['envoyer' => 0 , 'enCour' => 0 ]);
$checkIfMaillingExist = $this->get('check.mailling.exist');
$anomalieGestion = $this->get('gestion.anomalie');
foreach ($maillings as $mailling){
if($checkIfMaillingExist->checKMailling($mailling) < 1){
$suivitOuvertures = $em->getRepository('App:SuivitOuvertureMailling')
->findBy(['mailling' => $mailling]);
if(count($suivitOuvertures) < 1){
$em->remove($mailling);
}
else{
$anomalieGestion->addAnomalieDeleteWithSuivit($mailling);
}
}
}
$em->flush();
return new Response('ok');
}
/**
* @Route("/maillings/send/test/{idMailling}/{idAuthUser}",methods={"GET"},name="send.mailling.test")
*/
public function getSendMailTestAction($idMailling, $idAuthUser, MaillingEnCour $maillingEnCour, KernelInterface $kernel)
{
$em = $this->get('doctrine.orm.entity_manager');
$mailling = $em->getRepository("App\Entity\Mailling")
->find($idMailling);
$authUser = $em->getRepository("App\Entity\Auth\AuthUser")
->find($idAuthUser);
if($authUser){
if($mailling){
/** @var Mailling $mailling
* @var AuthUser $authUser
*/
if (strpos($mailling->getEnvoyePar()->getAdresseEnvoi(), '@escalconsulting.com') !== false) {
$maillingEnCour->addTestSend($mailling,$authUser);
return new JsonResponse('mail test lancé en envoi');
} else {
return new JsonResponse('l\'utilisateur ne possède pas d\'addresse d\'envoi');
}
} else {
return new JsonResponse('le mailling n\'existe pas');
}
} else {
return new JsonResponse('l\'utilisateur n\'existe pas');
}
}
/**
* @Route("/maillings/send/veille/{id}", methods={"GET"}, name="mailling.veille.send")
*/
public function sendVeilleAction(MaillingEnCour $maillingEnCour, EntityManagerInterface $em, $id, KernelInterface $kernel){
$veille = $em->getRepository('App:Veille')->find($id);
if($veille){
$match_date = $veille->getDate();
$date = new \DateTime();
$interval = $date->diff($match_date);
if($interval->days == 0) {
if(!$veille->getValider()){
$veille->setValider(true);
$em->persist($veille);
$em->flush();
$maillingEnCour->addVeilleSend($veille);
$this->importerVeilleNetwork($id, $em, $kernel);
return new JsonResponse('veille lancer en envoi');
}
}
}
return new JsonResponse('veille déja envoyé');
}
/**
* @Route("/maillings/importer/veille/network/{id}", methods={"GET"}, name="mailling_importer_veille_network")
*/
public function importerVeilleNetwork($id, EntityManagerInterface $em, KernelInterface $kernel){
$veille = $em->getRepository('App:Veille')->find($id);
if ($veille){
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$date = new \DateTime('today');
$dateF = new \DateTime('tomorrow');
$sheet->setCellValue("A1", "Articles veille du " . $date->format('Y-m-d'));
$ligne = 2;
$veilles = $em->getRepository('App:Veille')->findAll();
foreach ($veilles as $veille) {
if($veille->getDate()>= $date && $veille->getDate()<= $dateF){
foreach ($veille->getVeilleThematiques() as $veilleThematique) {
foreach ($veilleThematique->getElementsVeille() as $element) {
$sheet->setCellValue("A" . $ligne, '=Hyperlink("'.$element->getLiens().'")');
$ligne = $ligne + 1;
}
}
}
}
foreach (range('A', 'B') as $columnID) {
$spreadsheet->getActiveSheet()->getColumnDimension($columnID)
->setAutoSize(true);
}
$writer = new Xlsx($spreadsheet);
$fileName = './excelStat/Veille Quotidienne du '. $date->format('Y-m-d').'.xlsx';
$writer->save($fileName);
$file = $kernel->getRootDir() . '/../public/excelStat/Veille Quotidienne du '. $date->format('Y-m-d').'.xlsx';
// Enregistrement sur le Network
$ftp_server = "docs.escalconsulting.com";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
ftp_login($ftp_conn, 'informatique', 'E9;b5+AAx%k6')or die("Cannot login");
ftp_pasv($ftp_conn, true) or die("Cannot switch to passive mode");
ftp_put($ftp_conn, "/../ESCAL Consulting/Network/Conseil/Veille Quotidienne/Veille Quotidienne du ". $date->format('Y-m-d').".xlsx", $file);
ftp_close($ftp_conn);
// retirer du fichier public
if (file_exists($file)) {
unlink($file);
}
}
return new JsonResponse('veille importee');
}
/**
* @Route("/maillings/supprimer/veille/network/{id}", methods={"GET"}, name="mailling_supprimer_veille_network")
*/
public function supprimerVeilleNetwork($id, EntityManagerInterface $em, KernelInterface $kernel){
$veille = $em->getRepository('App:Veille')->find($id);
if ($veille){
$date = new \DateTime('today');
// supprimer du network
$ftp_server = "docs.escalconsulting.com";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
ftp_login($ftp_conn, 'informatique', 'E9;b5+AAx%k6') or die("Cannot login");
ftp_pasv($ftp_conn, true) or die("Cannot switch to passive mode");
ftp_delete($ftp_conn, "/../ESCAL Consulting/Network/Conseil/Veille Quotidienne/Veille Quotidienne du ". $date->format('Y-m-d').".xlsx");
ftp_close($ftp_conn);
}
return new JsonResponse('veille supprimée');
}
/**
* @Route("/maillings/send/date/{idMailling}",methods={"GET"},name="send.mail.date")
*/
public function getSendMaillingDateAction($idMailling , MaillingEnCour $maillingEnCour, Request $request)
{
ini_set('memory_limit',-1);
set_time_limit(0);
$dateEnvoie = $request->query->get('date');
$dateEnvoie = new \DateTime($dateEnvoie);
$em = $this->get('doctrine.orm.entity_manager');
$mailling = $em->getRepository("App\Entity\Mailling")
->find($idMailling);
if($mailling){
if($mailling->getValiderEnvoi()){
if(!$mailling->getEnCour()){
if(!$mailling->getEnvoyer()){
if (strpos($mailling->getEnvoyePar()->getAdresseEnvoi(), '@escalconsulting.com') !== false) {
$mailling->setEnCour(true);
$em->persist($mailling);
$em->flush();
if($maillingEnCour->addMaillingSend($mailling, $dateEnvoie, true) == false){
return new JsonResponse('le mailling est déja en cours d\'envoi');
}
return new JsonResponse('le mailling a été lancé en envoi');
} else {
return new JsonResponse('l\'utilisateur ne possède pas d\'addresse d\'envoi');
}
} else {
return new JsonResponse('le mailling est déjà en envoyé');
}
} else {
return new JsonResponse('le mailling est déjà en cours d\'envoi');
}
} else {
return new JsonResponse('le mailling doit être validé');
}
} else {
return new JsonResponse('le mailling n\'existe pas');
}
}
/**
* @Route("/maillings/send/{idMailling}",methods={"GET"},name="send.mail.reel")
*/
public function getSendMaillingAction($idMailling , MaillingEnCour $maillingEnCour, OvhSend $ovhSend, ActualiteController $actualiteController)
{
ini_set('memory_limit',-1);
set_time_limit(0);
$em = $this->get('doctrine.orm.entity_manager');
$mailling = $em->getRepository("App\Entity\Mailling")
->find($idMailling);
/** @var Mailling $mailling */
if($mailling){
if($mailling->getValiderEnvoi()){
if(!$mailling->getEnCour()){
if(!$mailling->getEnvoyer()){
if (strpos($mailling->getEnvoyePar()->getAdresseEnvoi(), '@escalconsulting.com') !== false) {
$mailling->setEnCour(true);
$em->persist($mailling);
$em->flush();
if ($mailling->getTypeMail() == 'CP') {
// on créé une actualité
$this->creerActualiteMailing($idMailling, $em, $ovhSend, $actualiteController);
// on envoie le contenu final du cp à intranet
try
{
$bdd = new PDO('mysql:host=185.126.230.125;dbname=escal_web;charset=utf8', 'escalprod', 'skl001');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$contenu = $mailling->getContent();
$query = 'UPDATE `ecw_mails` SET `contenu_cp`="'.$contenu.'" WHERE `ID_mail`='.$mailling->getAncienId();
$retour = $bdd->exec($query);
}
if($maillingEnCour->addMaillingSend($mailling, new \DateTime('now')) == false){
return new JsonResponse('le mailling est déja en cours d\'envoi');
}
return new JsonResponse('le mailling a été lancé en envoi');
} else {
return new JsonResponse('l\'utilisateur ne possède pas d\'addresse d\'envoi');
}
} else {
return new JsonResponse('le mailling est déjà en envoyé');
}
} else {
return new JsonResponse('le mailling est déjà en cours d\'envoi');
}
} else {
return new JsonResponse('le mailling doit être validé');
}
} else {
return new JsonResponse('le mailling n\'existe pas');
}
}
/**
* @Route("/maillings/creer/actualite/suite/envoie/{idMailling}", methods={"GET"}, name="creer_actu_mailing")
*/
public function creerActualiteMailing($idMailling, EntityManagerInterface $em, OvhSend $ovhSend, ActualiteController $actualiteController){
$mailling = $em->getRepository('App:Mailling')->find($idMailling);
$actualite = new Actualite();
$nomMailling = str_replace(''', '\'', $mailling->getNom());
$actualite->setNom($nomMailling);
$actualite->setClient($mailling->getClient());
$actualite->setPitch($mailling->getResumer());
$actualite->setCreation(new \DateTime('now'));
$actualite->setAuteur($mailling->getEnvoyePar());
$em->persist($actualite);
$em->flush();
$actualite = $em->getRepository('App:Actualite')->findDerniereActu();
$theme = new ThemeDescriptif();
$theme->setLibelle($mailling->getResumerCour());
$theme->setActualite($actualite);
$em->persist($theme);
$em->flush();
$actualiteController->parutionImporterCopie($actualite->getId(), 0, $em);
try
{
$bdd = new PDO('mysql:host=185.126.230.125;dbname=escal_web;charset=utf8', 'escalprod', 'skl001');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$query = 'SELECT MAX(`ID_actualite`) as actuId FROM `ecw_actualites`';
$reponse = $bdd->query($query);
while ($row = $reponse->fetch()) {
$actuAncienId = $row['actuId'];
}
$reponse->closeCursor();
$actualite->setAncienId($actuAncienId);
$em->flush();
$ovhSend->sendMailNouvelleActualite($actualite);
return new JsonResponse('ok');
}
/**
* @Route("/mailling/enCour/{idMailling}", methods={"GET"}, name="mailling.en.cour.status")
*/
public function getMaillingInfoEnCourAction($idMailling, EntityManagerInterface $em, MaillingEnCour $maillingEnCour){
$mailling = $em->getRepository('App:Mailling')->find($idMailling);
$retour = [];
if($mailling){
$debutMailling = $maillingEnCour->getIfMaillingBegin($mailling);
if($debutMailling !== false){
$nbMailling = $maillingEnCour->getNbMailMailling($mailling);
$nbMaillingAttente = $maillingEnCour->getNbMailRestantAvantFin($mailling);
if($nbMaillingAttente != false){
$dateFurtureEnvoie = $maillingEnCour->getHeureEnvoieFuture($mailling);
if( $dateFurtureEnvoie == false){
$retour['nbMaillAttente'] = $nbMaillingAttente;
$retour['nbMailToSend'] = $nbMailling[0];
$retour['nbMailSend'] = $nbMailling[1];
} else {
$retour['message_erreur'] = 'le mailling commencera a être envoyé le ' . $dateFurtureEnvoie;
}
} else {
if($mailling->getEnvoyer() == true){
$retour['message_erreur'] = 'le mailling a fini d\'être envoyé';
}
$retour['message_erreur'] = 'Le mailling est en cours d\'envoi, l\'affichage du diagramme peut prendre plusieurs minutes. Merci de patienter.';
}
} else {
$retour['message_erreur'] = 'le mailling n\'est pas en envoi';
}
} else {
$retour['message_erreur'] = 'le mailling n\'existe pas';
}
return new JsonResponse($retour);
}
/**
* @Route("/maillings/deleteMailling/{idMailling}", methods={"DELETE"}, name="delete.mailling")
*/
public function deleteMailling($idMailling, EntityManagerInterface $em){
$mailling = $em->getRepository('App:Mailling')->find($idMailling);
if($mailling->getEnCour() === false){
$maillingsEnCour = $em->getRepository('App:MaillingEnCour')->findBy(['mailling' => $mailling]);
foreach ($maillingsEnCour as $maillingEnCour){
$em->remove($maillingEnCour);
}
$em->remove($mailling);
$em->flush();
$retour['message'] = 'le mailling a été supprimé';
} else {
$retour['message'] = 'le mailling a déjà été lancé en envoi';
}
return new JsonResponse($retour);
}
/**
* @Route("/maillings/prepareCoupure/{idClient}", methods={"GET"}, name="mailling.cree.coupure")
*/
public function creeMaillingCoupure($idClient, EntityManagerInterface $em, GenerateCoupureInterface $generateCoupure){
$client = $em->getRepository('App:Client')->find($idClient);
if($client){
/** @var Client $client */
$mailling = $em->getRepository('App:Mailling')->findOneBy(['client' => $client, 'typeMail' => 'Coupure', 'envoyer' => false]);
/** @var Mailling $mailling */
if($mailling){
foreach ($mailling->getPiecesJointes() as $piecesJointe){
$mailling->removePiecesJointe($piecesJointe);
$em->remove($piecesJointe);
}
$em->flush();
} else{
$mailling = new Mailling();
$mailling->setClient($client);
$date = new \DateTime('now');
$mailling->setNom('Retombées presse '. $client->getNom(). ' du '.date_format($date, 'd/m/Y'));
$mailling->setObjet('Retombées presse '. $client->getNom(). ' du '.date_format($date, 'd/m/Y'));
foreach ($client->getRolesUserClient() as $roleUserClient){
/** @var ClientRoleUser $roleUserClient */
if($roleUserClient->getRole() == 'Bo'){
$mailling->setEnvoyePar($roleUserClient->getAuthUser());
$mailling->setReplyTo($roleUserClient->getAuthUser());
}
}
$mailling->setTypeMail('Coupure');
}
$coupuresClient = $em->getRepository('App:Coupure')->findBy(['client' => $client, 'envoyer' => false]);
foreach ($coupuresClient as $coupure){
/** @var Coupure $coupure */
$pieceJointeMailling = new PieceJointeMailling();
$pieceJointeMailling->setUrl($coupure->getPiecesJointe());
$pieceJointeMailling->setCoupure($coupure);
$pieceJointeMailling->setMailling($mailling);
$mailling->addPiecesJointe($pieceJointeMailling);
}
$mailling->setValiderEnvoi(0);
$mailling->setEnCour(0);
$mailling->setEnvoyer(0);
$mailling->setNbMail(0);
$mailling->setNbMailEnvoye(0);
$mailling->setDebutMailCoupure($generateCoupure->generateDebutMail($mailling));
$mailling->setFinMailCoupure($generateCoupure->generateFinMail($mailling));
$mailling->sethyperlien(1);
$em->persist($mailling);
$em->flush();
} else {
$retour['message_erreur'] = 'le client n\'existe pas';
}
return new JsonResponse(['idMailling' => $mailling->getId()]);
}
/**
* @Route("/maillings/information/{idMailling}", methods={"GET"}, name="nb.mail.envoyer")
*/
public function getNombreMailEnvoyer($idMailling, EntityManagerInterface $em){
$mailling = $em->getRepository('App:Mailling')->findBy(['ancienId' => $idMailling]);
if(!isset($mailling[0])){
return new JsonResponse(0);
}
$mailling = $mailling[0];
return new JsonResponse($mailling->getNbMailEnvoye());
}
/**
* @Route("/maillings/refreshNbMail/{idMailling}", methods={"GET"}, name="nb.mail.envoyer.refresh")
*/
public function getRefreshNombreMail(OvhSend $ovhSend, $idMailling, EntityManagerInterface $em){
$mailling = $em->getRepository('App:Mailling')->find($idMailling);
/** @var Mailling $mailling */
$contactsSend = $ovhSend->getContactSend($mailling);
$nbMail = 0;
foreach ($contactsSend as $contactSend) {
$userInfo = explode('#', $contactSend);
$userMail = trim($userInfo[0]);
$blackList = $em->getRepository('App:BlackList')
->findOneBy(['email'=> $userMail]);
if(!$blackList) {
$nbMail = $nbMail + 1;
}
}
if($mailling->getNbMail() != $nbMail){
$mailling->setNbMail($nbMail);
}
$em->persist($mailling);
$em->flush();
return new JsonResponse($mailling->getNbMail());
}
/**
* @Route("/mailing/contactsenvoireel/{idMailling}", methods={"GET"}, name="mailing.contact.Envoi.reel")
*/
public function getContactsEnvoiReel($idMailling, EntityManagerInterface $em) {
$mailing = $em->getRepository('App:Mailling')->findOneBy(["ancienId" => $idMailling]);
$mailingsEnCours = $em->getRepository('App:MaillingEnCour')->findBy(["mailling" => $mailing->getId()]);
$contactsIDIntranet = [];
foreach ($mailingsEnCours as $mailingEncours) {
if(!is_null($mailingEncours->getUserId()))
$contactsIDIntranet[] = $mailingEncours->getUserId();
}
return new JsonResponse($contactsIDIntranet);
}
/**
* @Route("/mailing/get/contacts/safe/{idMailling}", methods={"GET"}, name="mailing_contact_safe_envoi")
*/
public function getContactsSafeEnvoi($idMailling, EntityManagerInterface $em, OvhSend $ovhSend) {
$contactsSafe = '';
// liste contacts hors blacklist et email retour
$mailing = $em->getRepository('App:Mailling')->findOneBy(["ancienId" => $idMailling]);
$contactsSend = $ovhSend->getContactSend($mailing);
foreach ($contactsSend as $contactSend) {
$contactInfo = explode('#', $contactSend);
$contactMail = trim($contactInfo[0]);
$contactID = trim($contactInfo[1]);
$adresseEmailVerif = $em->getRepository('App:Email\AdresseMailVerif')->findOneBy(['email' => $contactMail]);
// Rapidité de traitement
$qb = $em->createQueryBuilder();
$emailRetour = $qb->select('1')
->from(EmailRetour::class, 'er')
->where('er.email = :email')
->setParameter('email', $contactMail)
->orderBy('er.id', 'DESC')
->setMaxResults(1)
->getQuery()
->getResult();
$safeToSend = 0;
//Si l'adresse mail a deja ete verifie : recuperer le statut de l'adresse mail verifiee
if ($adresseEmailVerif){
// Gestion de cas des adresses mails de type "Accept All"
if(!$emailRetour && $adresseEmailVerif->getSafeToSend()==1){
$safeToSend = 1;
}
}
$blackList = $em->getRepository('App:BlackList')->findOneBy(['email' => $contactMail]);
if (!$blackList || $blackList->getAutorise() == 1) {
$dateDuJour = new \DateTime('now');
//La dateAbsence correspond à la date de retour
if($emailRetour && $emailRetour->getDateAbsence()>$dateDuJour) {
$safeToSend = 0;
}
// Ne pas bloquer l'envoi à l'adresse mail classée 'autre' par les BO
if($emailRetour && $emailRetour->getRaison() == 'autre') {
$safeToSend = 1;
}
if($safeToSend == 1) {
$contactsSafe = $contactsSafe . '"'.$contactMail.'", ';
}
}
// vérifier si contact dans les listes coeur de cible et itw articles du client, envoyer obligatoirement
$contact = $em->getRepository('App\Entity\Contact')->findOneBy(['ancienId' => $contactID]);
$safeInListe = false;
if ($contact != null) {
$listes = $em->getRepository('App:ListeContact')->findListeCoeurCibleEtItwArticlesClient($mailing->getClient()->getNom());
foreach ($listes as $liste){
$asso = $this->getDoctrine()->getRepository('App:ListeContactContact')->findBy(['contact' => $contact, 'listeContact' => $liste]);
if ($asso != null) {
$safeInListe = true;
}
}
if ($safeInListe === true) {
$safeToSend = 1;
}
}
if($safeToSend == 1) {
$contactsSafe = $contactsSafe . '"'.$contactMail.'", ';
}
}
return new JsonResponse($contactsSafe);
}
/**
* @Route("/api/maillings/auteur/intranet/{maillingId}", methods={"GET"}, name="rechercher_auteur_intranet_mailling")
*/
public function rechercherAncienIdAuteur ($maillingId)
{
$mailling = $this->getDoctrine()->getRepository('App:Mailling')->find($maillingId);
$authUserId = 0;
// récupérer ancien id authuser
if($mailling->getAuteur() != null) {
if($mailling->getAuteur()->getUser() != null) {
$nomPrenom = $mailling->getAuteur()->getUser()->getPrenom() . "." . $mailling->getAuteur()->getUser()->getNom();
if (strpos($nomPrenom, ' ') !== false) {
$nomPrenom = str_replace(' ', '.', $nomPrenom);
}
$url = 'extranet.escalconsulting.com/information/getMembreByNom.php?name=' . $nomPrenom;
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_HEADER, false);
$output = curl_exec($c);
curl_close($c);
$output = json_decode($output);
$output = (array)$output;
$authUserId = $output['id'];
}
}
return new JsonResponse($authUserId);
}
/**
* @Route("/api/maillings/liste/associee/associer/{maillingId}/{listeAId}", methods={"GET"}, name="mailling_liste_associee_associer")
*/
public function addMailingListeAssociee($maillingId, $listeAId, EntityManagerInterface $em): JsonResponse
{
$mailling = $this->getDoctrine()->getRepository('App:Mailling')->find($maillingId);
$listeA = $this->getDoctrine()->getRepository('App:ListeContact')->find($listeAId);
$mailling->addListesAssociee($listeA);
$em->flush();
return new JsonResponse("ok");
}
/**
* @Route("/api/maillings/liste/desassociee/associer/{maillingId}/{listeDId}", methods={"GET"}, name="mailling_liste_desassociee_associer")
*/
public function addMailingListeDesassociee($maillingId, $listeDId, EntityManagerInterface $em): JsonResponse
{
$mailling = $this->getDoctrine()->getRepository('App:Mailling')->find($maillingId);
$listeD = $this->getDoctrine()->getRepository('App:ListeContact')->find($listeDId);
$mailling->addListesDesassociee($listeD);
$em->flush();
return new JsonResponse("ok");
}
/**
* @Route("/api/maillings/liste/associee/desassocier/{maillingId}", methods={"GET"}, name="mailling_liste_associee_desassocier")
*/
public function deleteMailingListeAssociee($maillingId, EntityManagerInterface $em): JsonResponse
{
$mailling = $this->getDoctrine()->getRepository('App:Mailling')->find($maillingId);
$associations = $mailling->getListesAssociees();
foreach ($associations as $association) {
$mailling->removeListesAssociee($association);
}
$em->flush();
return new JsonResponse("ok");
}
/**
* @Route("/api/maillings/liste/desassociee/desassocier/{maillingId}", methods={"GET"}, name="mailling_liste_desassociee_desassocier")
*/
public function deleteMailingListeDesassociee($maillingId, EntityManagerInterface $em): JsonResponse
{
$mailling = $this->getDoctrine()->getRepository('App:Mailling')->find($maillingId);
$associations = $mailling->getListesDesassociees();
foreach ($associations as $association) {
$mailling->removeListesDesassociee($association);
}
$em->flush();
return new JsonResponse("ok");
}
/**
* @Route("/api/maillings/importation/copie/mailling/{maillingId}/{ancienId}", methods={"GET"}, name="mailing_importer_copie_intranet")
*/
public function mailingImporterCopie ($maillingId, $ancienId, EntityManagerInterface $em)
{
try
{
$bdd = new PDO('mysql:host=185.126.230.125;dbname=escal_web;charset=utf8', 'escalprod', 'skl001');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
// récupérer données mailing
$mailling = $this->getDoctrine()->getRepository('App:Mailling')->find($maillingId);
// récupérer ancien id auteur
$authUserId = 0;
if($mailling->getAuteur() != null) {
$nomPrenom = $mailling->getAuteur()->getUser()->getPrenom().".".$mailling->getAuteur()->getUser()->getNom();
if (strpos($nomPrenom,' ') !== false) {
$nomPrenom = str_replace(' ','.', $nomPrenom);
}
$url = 'extranet.escalconsulting.com/information/getMembreByNom.php?name='.$nomPrenom;
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_HEADER, false);
$output = curl_exec($c);
curl_close($c);
$output = json_decode($output);
$output = (array)$output;
$authUserId = $output['id'];
}
// récupérer nom
$nom = $mailling->getNom();
// récupérer from
$from = $mailling->getEnvoyePar()->getUser()->getEmail();
// récupérer nomfrom
$nomfrom = $mailling->getAuteur()->getUser()->getPrenom()." ".$mailling->getAuteur()->getUser()->getNom();
// récupérer replyto
$replyto = $mailling->getReplyTo()->getUser()->getEmail();
// récupérer objet
$objet = $mailling->getObjet();
// récupérer id client
if($mailling->getClient() != null){
$clientId = $mailling->getClient()->getAncienId();
} else {
$clientId = 0;
}
// récupérer priorite
if($mailling->getPriorite() == 1){
$priorite = "1 (Highest)";
} else if($mailling->getPriorite() == 2){
$priorite = "2 (High)";
} else if($mailling->getPriorite() == 3){
$priorite = "3 (Normal)";
} else if($mailling->getPriorite() == 4){
$priorite = "4 (Low)";
} else if($mailling->getPriorite() == 5){
$priorite = "5 (Lowest)";
}
$cc = '';
$bcc = '';
$format = 'Html';
$typeId = 3;
// récupérer ancien id signataire
$signataireId = 0;
if($mailling->getEnvoyePar() != null) {
$nomPrenomBis = $mailling->getEnvoyePar()->getUser()->getPrenom().".".$mailling->getEnvoyePar()->getUser()->getNom();
if (strpos($nomPrenomBis,' ') !== false) {
$nomPrenomBis = str_replace(' ','.', $nomPrenomBis);
}
$url = 'extranet.escalconsulting.com/information/getMembreByNom.php?name='.$nomPrenomBis;
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_HEADER, false);
$output = curl_exec($c);
curl_close($c);
$output = json_decode($output);
$output = (array)$output;
$signataireId = $output['id'];
}
$track = 'N';
$dejaEnvoye = 0;
$dateEnvoi = null;
// récupérer création
if ($mailling->getCreation() != null) {
$creation = $mailling->getCreation()->format('Y-m-d H:i');
} else {
$creation = '';
}
// récupérer modification
if ($mailling->getModification() != null) {
$modification = $mailling->getModification()->format('Y-m-d H:i');
} else {
$modification = '';
}
$encours = 0;
$postfb = 0;
$posttw = 0;
$postfbes = 0;
$posttwes = 0;
$heureenvoi = '00:00:00';
// récupérer id outil
if($mailling->getOutil() != null){
$outilId = $mailling->getOutil()->getId();
} else {
$outilId = 0;
}
// récupérer id niveau
if($mailling->getNiveau() != null){
$niveauId = $mailling->getNiveau()->getId();
} else {
$niveauId = 0;
}
// récupérer id sous niveau
if($mailling->getSousNiveau() != null){
$sousniveauId = $mailling->getSousNiveau()->getId();
} else {
$sousniveauId = 0;
}
// récupérer contenu
$contenu = $mailling->getContent();
// si ce n'est pas une mise à jour
if ($ancienId == 0) {
// on insère le mailling
if (strpos($nom,'"') !== false) {
$nom = str_replace('"','\"', $nom);
}
if (strpos($objet,'"') !== false) {
$objet = str_replace('"','\"', $objet);
}
if (strpos($contenu,'"') !== false) {
$contenu = str_replace('"','\"', $contenu);
}
$query = 'INSERT INTO `ecw_mails`(`nom_mail`, `cc_mail`, `bcc_mail`, `from_mail`, `nomfrom_mail`, `replyto_mail`, `objet_mail`, `client_mail`, `format_mail`, `priorite_mail`, `IDtype_mail`, `IDmembresignature_mail`, `track_mail`, `DejaEnvoye`, `dateenvoi_mail`, `ID_auteur_mail`, `creation_mail`, `modif_mail`, `encours`, `post_facebook`, `post_twitter`, `post_facebook_escal`, `post_twitter_escal`, `heureenvoi_mail`, `ID_outil`, `ID_niveau`, `ID_sous_niveau`, `contenu_cp`) '
.' VALUES ("'.$nom.'","'.$cc.'","'.$bcc.'","'.$from.'","'.$nomfrom.'","'.$replyto.'","'.$objet.'",'.$clientId.',"'.$format.'","'.$priorite.'",'.$typeId.','.$signataireId.',"'.$track.'",'.$dejaEnvoye.',NULL,'.$authUserId.',"'.$creation.'", NULL,'.$encours.','.$postfb.','.$posttw.','.$postfbes.','.$posttwes.',"'.$heureenvoi.'",'.$outilId.','.$niveauId.','.$sousniveauId.',"'.$contenu.'")';
$retour = $bdd->exec($query);
if (!$retour) {
echo 'Problème lors de l\'insertion du mailing';
}
// on récupère le mailing nouvellement créé
$query = 'SELECT MAX(`ID_mail`) as mailId FROM `ecw_mails`';
$reponse = $bdd->query($query);
while ($row = $reponse->fetch()) {
$maillingAncienId = $row['mailId'];
}
$reponse->closeCursor();
// on insère les associations du mailing
// liste associee
$listeAsso = $mailling->getListesAssociees();
if(count($listeAsso) > 0) {
$query10 = 'DELETE FROM `ecw_mail_liste_asso` WHERE `ID_mail`='.$maillingAncienId;
$retour10 = $bdd->exec($query10);
foreach ($listeAsso as $liste) {
$query11 = 'INSERT INTO `ecw_mail_liste_asso`(`ID_mail`, `ID_liste_contact`) '
.' VALUES ('.$maillingAncienId.','.$liste->getAncienId().')';
$retour11 = $bdd->exec($query11);
if (!$retour11) {
echo 'Problème lors de l\'insertion de l\'asso mailing liste associee';
}
}
}
// liste desassociee
$listeDesa = $mailling->getListesDesassociees();
if(count($listeDesa) > 0) {
$query12 = 'DELETE FROM `ecw_mail_listetoremove_asso` WHERE `ID_mail`=' . $maillingAncienId;
$retour12 = $bdd->exec($query12);
foreach ($listeDesa as $liste) {
$query13 = 'INSERT INTO `ecw_mail_listetoremove_asso`(`ID_mail`, `ID_liste_contact`) '
. ' VALUES (' . $maillingAncienId . ',' . $liste->getAncienId() . ')';
$retour13 = $bdd->exec($query13);
if (!$retour13) {
echo 'Problème lors de l\'insertion de l\'asso mailing liste desassociee';
}
}
}
return new JsonResponse($maillingAncienId);
}
// si c'est une mise à jour
else if ($ancienId != 0) {
// on met à jour le mailing
if (strpos($nom,'"') !== false) {
$nom = str_replace('"','\"', $nom);
}
if (strpos($objet,'"') !== false) {
$objet = str_replace('"','\"', $objet);
}
if (strpos($contenu,'"') !== false) {
$contenu = str_replace('"','\"', $contenu);
}
$query = 'UPDATE `ecw_mails` SET `nom_mail`="'.$nom.'",`cc_mail`="'.$cc.'",`bcc_mail`="'.$bcc.'",`from_mail`="'.$from.'",`nomfrom_mail`="'.$nomfrom.'",`replyto_mail`="'.$replyto.'",`objet_mail`="'.$objet.'",`client_mail`='.$clientId.', `format_mail`="'.$format.'", `priorite_mail`="'.$priorite.'", `IDtype_mail`='.$typeId.', `IDmembresignature_mail`='.$signataireId.', `track_mail`="'.$track.'", `DejaEnvoye`='.$dejaEnvoye.', `dateenvoi_mail`= NULL, `ID_auteur_mail`='.$authUserId.', `modif_mail`="'.$modification.'", `encours`='.$encours.', `post_facebook`='.$postfb.', `post_twitter`='.$posttw.', `post_facebook_escal`='.$postfbes.', `post_twitter_escal`='.$posttwes.', `heureenvoi_mail`="'.$heureenvoi.'", `ID_outil`='.$outilId.', `ID_niveau`='.$niveauId.', `ID_sous_niveau`='.$sousniveauId.', `contenu_cp`="'.$contenu.'" WHERE `ID_mail`='.$ancienId;
$retour = $bdd->exec($query);
// on update les associations du mailing
// liste associee
$listeAsso = $mailling->getListesAssociees();
$query10 = 'DELETE FROM `ecw_mail_liste_asso` WHERE `ID_mail`='.$ancienId;
$retour10 = $bdd->exec($query10);
if(count($listeAsso) > 0) {
foreach ($listeAsso as $liste) {
$query11 = 'INSERT INTO `ecw_mail_liste_asso`(`ID_mail`, `ID_liste_contact`) '
.' VALUES ('.$ancienId.','.$liste->getAncienId().')';
$retour11 = $bdd->exec($query11);
if (!$retour11) {
echo 'Problème lors de l\'insertion de l\'asso mailing liste associee';
}
}
}
// liste desassociee
$listeDesa = $mailling->getListesDesassociees();
$query12 = 'DELETE FROM `ecw_mail_listetoremove_asso` WHERE `ID_mail`=' . $ancienId;
$retour12 = $bdd->exec($query12);
if(count($listeDesa) > 0) {
foreach ($listeDesa as $liste) {
$query13 = 'INSERT INTO `ecw_mail_listetoremove_asso`(`ID_mail`, `ID_liste_contact`) '
. ' VALUES (' . $ancienId . ',' . $liste->getAncienId() . ')';
$retour13 = $bdd->exec($query13);
if (!$retour13) {
echo 'Problème lors de l\'insertion de l\'asso mailing liste desassociee';
}
}
}
return new JsonResponse($ancienId);
}
}
/**
* @Route("/api/maillings/considerer/envoye/{ancienIdMailing}", methods={"GET"}, name="mailing_considerer_envoyer")
*/
public function considererEnvoyeMailing($ancienIdMailing, EntityManagerInterface $em): JsonResponse
{
try
{
$bdd = new PDO('mysql:host=185.126.230.125;dbname=escal_web;charset=utf8', 'escalprod', 'skl001');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
if ($ancienIdMailing != 0 && $ancienIdMailing != '') {
$query = 'UPDATE `ecw_mails` SET `DejaEnvoye`= 1 WHERE `ID_mail`='.$ancienIdMailing;
$retour = $bdd->exec($query);
}
return new JsonResponse("ok");
}
/**
* @Route("/api/maillings/total/contact/liste/{mailingId}/{type}", methods={"GET"}, name="mailing_total_contact_liste")
*/
public function detailsListeContactInfo ($mailingId, $type, EntityManagerInterface $em)
{
$ids = array();
$mailing = $em->getRepository('App:Mailling')->find($mailingId);
if ($type == 'associe') {
$listesMailling = $mailing->getListesAssociees();
} else {
$listesMailling = $mailing->getListesDesassociees();
}
foreach ($listesMailling as $liste){
$ids[] = $liste->getId();
}
$contacts = $this->getDoctrine()->getRepository('App:Contact')->findDistinctTotalContactMailing($ids);
$encoders = array(new XmlEncoder(), new JsonEncoder());
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$normalizer = new PropertyNormalizer($classMetadataFactory);
$normalizerDate = new DateTimeNormalizer();
$serializer = new Serializer([$normalizer, $normalizerDate], $encoders);
$jsonContent = $serializer->normalize($contacts, null, array('groups' => array('contact')));
$response = new JsonResponse($jsonContent);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* @Route("/api/maillings/importation/supprimer/copie/mailing/{ancienIdMailing}", methods={"GET"}, name="mailing_supprimer_copie_intranet")
*/
public function mailingSupprimerCopie ($ancienIdMailing)
{
try
{
$bdd = new PDO('mysql:host=185.126.230.125;dbname=escal_web;charset=utf8', 'escalprod', 'skl001');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
// supprimer asso liste associee
$query = 'DELETE FROM `ecw_mail_liste_asso` WHERE `ID_mail`='.$ancienIdMailing;
$retour = $bdd->exec($query);
// supprimer asso liste desassociee
$query1 = 'DELETE FROM `ecw_mail_listetoremove_asso` WHERE `ID_mail`='.$ancienIdMailing;
$retour1 = $bdd->exec($query1);
// supprimer mailing
$query5 = 'DELETE FROM `ecw_mails` WHERE `ID_mail`='.$ancienIdMailing;
$retour5 = $bdd->exec($query5);
return new JsonResponse('ok');
}
/**
* @Route("/api/maillings/add/ftp/html/{maillingId}", methods={"GET"}, name="mailing_add_ftp_copie_intranet")
*/
public function addMailHtml ($maillingId, FtpGetPieceJointe $ftp)
{
$result = $ftp->addMailHTML($maillingId);
if(isset($result['type'])){
return new Response(json_encode($result));
}
return new Response('{ "status": "ok" }');
}
}