<?php
/**
* Created by PhpStorm.
* User: anthony
* Date: 25/05/18
* Time: 11:56
*/
namespace App\Ovh;
use App\Entity\Auth\AuthUser;
use App\Entity\DemandeDeConge;
use App\Entity\Email\AdresseMailVerif;
use App\Entity\Email\EmailRetour;
use App\Entity\Mailling;
use App\Entity\PieceJointeMailling;
use App\Entity\Pressroom\PressroomCommunique;
use App\Entity\User;
use App\Service\MaillingEnCour\MaillingEnCour;
use App\Service\Utilitaire\AnomalieGestion;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Swift_Mailer;
use Swift_Message;
use Swift_Plugins_LoggerPlugin;
use Swift_Plugins_Loggers_ArrayLogger;
use Swift_SmtpTransport;
use Symfony\Component\HttpKernel\KernelInterface;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use Twig\Loader\FilesystemLoader;
class OvhSend
{
private $ovhHelper;
private $kernel;
private $mailer;
private $anomalieGestion;
private $authUser;
private $em;
/**
* @var Environment $twig
*/
private $twig;
/**
* OvhSend constructor.
*/
public function __construct(OvhHelper $ovhHelper, KernelInterface $kernel, AnomalieGestion $anomalieGestion, EntityManagerInterface $em)
{
$this->authUser = null;
$this->nbMailEnvoye = 0;
$this->anomalieGestion = $anomalieGestion;
$this->ovhHelper = $ovhHelper;
$this->kernel = $kernel;
$this->em = $em;
$loader = new FilesystemLoader(__DIR__.'/views/');
$this->twig = new Environment($loader, array());
}
public function sendMailConfirmationDemandeConge(DemandeDeConge $demandeDeConge){
$template = $this->twig->load('demandeCongeValidation.html.twig');
$message = (new Swift_Message('validation demande de congé'))
->setFrom('louis@escalconsulting.com')
->setTo($demandeDeConge->getAuthUser()->getUser()->getEmail())
->setSubject('validation demande de congé')
->setBody(
$template->render(array('demandeDeConge' => $demandeDeConge)),
'text/html'
)
->setReplyTo('louis@escalconsulting.com');
$message->attach(\Swift_Attachment::fromPath($this->kernel->getRootDir() . '/../public/Interne/demandeConge/'.$demandeDeConge->getDebutConge()->format('Y-m-d').'demandeConge'.
$demandeDeConge->getAuthUser()->getUser()->getNom().'.pdf'));
$authUser = $this->em->getRepository('App:Auth\AuthUser')
->findOneBy(['username' => 'louis']);
/** @var AuthUser $authUser */
$mail = $authUser->getUser()->getEmail();
$password = $authUser->getPasswordMail();
$transport = new Swift_SmtpTransport('exchange.escalconsulting.com', 587, 'tls');
$transport
->setUsername($mail)
->setPassword($password);
$mailer = new Swift_Mailer($transport);
$logger = new Swift_Plugins_Loggers_ArrayLogger;
$mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
$mailer->send($message, $failRecipient);
}
public function getContactSend(Mailling $mailling){
$post = [
'login' => 'Systeme',
'password' => 'i5iJ;5@J7',
];
$ch = curl_init('extranet.escalconsulting.com/identification.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
$response = curl_exec($ch);
curl_close($ch);
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $response, $matches);
foreach($matches[1] as $item) {
parse_str($item, $cookie);
$cookiesRetour = $cookie['PHPSESSID'];
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'extranet.escalconsulting.com/mail_cms.php?action=lstuniq_frame&ID_mail=' . $mailling->getAncienId());
curl_setopt($curl, CURLOPT_COOKIE,"PHPSESSID=".$cookiesRetour);
curl_setopt($curl, CURLOPT_COOKIESESSION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$return = curl_exec($curl);
curl_close($curl);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => 'extranet.escalconsulting.com/information/getInfoListMailling.php?id=' . $mailling->getAncienId(),
));
$retourUserList = curl_exec($curl);
$retourUserList = substr($retourUserList, 0, -1);
curl_close($curl);
$usersSend = explode('~', $retourUserList);
return $usersSend;
}
public function verifMail($contactEmail) {
$blackList = $this->em->getRepository('App:BlackList')->findOneBy(['email' => $contactEmail['email']]);
if($blackList){
return false;
}
$emailVerif = $this->em->getRepository('App:Email\AdresseMailVerif')->findOneBy(['email' => $contactEmail['email']]);
if($emailVerif){
/** @var $emailVerif AdresseMailVerif */
if($emailVerif->getSafeToSend() == 0){
if($emailVerif->getReason() != 'Unreachable'){
return false;
}
}
}
return true;
}
public function getNextMail($idcontact, $contactEmail) {
$url="localhost:81/information/getNextMailByListId.php?id=".$idcontact;
$postFields= $contactEmail;
$options=array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FAILONERROR => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => array("idContact"=>json_encode($postFields))
);
$curl=curl_init();
curl_setopt_array($curl,$options);
$content=curl_exec($curl);
dump($content);
die();
return $content;
}
public function getContactSend2(Mailling $mailling) {
$curl = curl_init();
$url = 'extranet.escalconsulting.com/information/genererMailContactMailling.php?id=' . $mailling->getAncienId();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_COOKIESESSION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$return = curl_exec($curl);
curl_close($curl);
$contactsEmail = json_decode($return, true);
$idsContactWithoutMail = [];
$idContactAEnvoyer = [];
$mailFalse = [];
foreach ($contactsEmail as $idContact => $contactEmail) {
$emailOK = false;
$idContactTraite = $idContact;
$contactEmailTraite = $contactEmail;
while ($emailOK == false) {
$emailOK = $this->verifMail($contactEmailTraite);
if ($emailOK == false) {
$mailFalse[]=$contactEmailTraite;
$contsEmail = $this->getNextMail($idContactTraite,$contactEmailTraite);
dump($contsEmail);
if (count($contsEmail) == 0) {
$idsContactWithoutMail[] = $idContactTraite;
$emailOK = true;
} else if (count($contsEmail) != 1) {
dump("Impossible");
die();
}
foreach ($contsEmail as $idCont => $contEmail) {
$idContactTraite = $idCont;
$contactEmailTraite = $contEmail;
}
} else {
$a=1;
//die();
//idContactAEnvoyer[$idContactTraite] = $contactEmailTraite;
}
}
}
$idsCanBeBetter = [];
foreach ($contactsEmail as $idContact => $contactEmail){
$emailVerif = $this->em->getRepository('App:Email\AdresseMailVerif')->findOneBy(['email' => $contactEmail['email']]);
if($emailVerif){
/** @var $emailVerif AdresseMailVerif */
if($emailVerif->getRole() == 1){
$idsCanBeBetter[$idContact] = $contactEmail;
}
}
}
dump(count($contactsEmail));
die();
}
public function miseAjourPressroom(Mailling $mailling, $update = 0){
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'extranet.escalconsulting.com/information/getPressroomId.php?id=' . $mailling->getClient()->getAncienId(),
));
$idPressroom = curl_exec($curl);
curl_close($curl);
$file = $this->kernel->getRootDir() . '/../public/maillings/'.$mailling->getId().'.pdf';
if($mailling->getClient()->getPressroom()){
$pressroom = $mailling->getClient()->getPressroom();
$pressroomComunique = new PressroomCommunique();
$pressroomComunique->setAncienId($mailling->getAncienId());
$pressroomComunique->setDate(new \DateTime('now'));
if($mailling->getObjetCour()){
$pressroomComunique->setNom($mailling->getObjetCour());
} else {
$pressroomComunique->setNom($mailling->getObjet());
}
$pressroomComunique->setPdf(true);
// recuperation et création des paths
$pathPressroomFile = $this->kernel->getRootDir() . '/../public/pressroomClient/' . $pressroom->getId();
if(!file_exists($pathPressroomFile)){
mkdir($pathPressroomFile,0777);
}
$pathPressroomCommunique = $pathPressroomFile . '/communique/';
if(!file_exists($pathPressroomCommunique)){
mkdir($pathPressroomCommunique,0777);
}
// recupération du pdf
$communiqueFile = $this->kernel->getRootDir() . '/../public/maillings/'. $mailling->getId() . '.pdf';
if(file_exists($communiqueFile)){
copy($communiqueFile, $pathPressroomCommunique. $mailling->getAncienId() . '.pdf');
$pressroomComunique->setPdf(true);
}
// recuperation photo
if($mailling->getPhoto()){
$explodeUrl = explode('.', $mailling->getPhoto()->getUrl());
$extension = end($explodeUrl);
$url = 'extranet.escalconsulting.com/photocp/'. $mailling->getPhoto()->getUrl();
$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);
file_put_contents($pathPressroomFile. '/communique/'. $mailling->getAncienId() . '.' .
$extension , $output);
$pressroomComunique->setPhoto($extension);
$pressroomComunique->setDate($mailling->getDateEnvoi());
}
$pressroom->addPressroomCommunique($pressroomComunique);
$this->em->persist($pressroomComunique);
$this->em->persist($pressroom);
$this->em->flush();
}
}
public function setMaillingSend(Mailling $mailling){
if($mailling->getTypeMail() == "Coupure"){
foreach ($mailling->getPiecesJointes() as $piecesJointe){
/** @var PieceJointeMailling $piecesJointe */
$idCoupure = $piecesJointe->getCoupure()->getAncienId();
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'extranet.escalconsulting.com/information/setCoupureSend.php?id=' . $idCoupure,
));
$coupureSend = curl_exec($curl);
curl_close($curl);
$piecesJointe->getCoupure()->setEnvoyer(true);
$this->em->persist($piecesJointe->getCoupure());
$this->em->flush();
}
} else {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'extranet.escalconsulting.com/information/setMaillingSend.php?id=' . $mailling->getAncienId(),
));
$maillingSend = curl_exec($curl);
curl_close($curl);
}
}
public function sendMailEnvoie(\App\Entity\MaillingEnCour $maillingEnCour){
$endMailling = false;
$maillingEnCour->setDestinataire(trim($maillingEnCour->getDestinataire()));
if($maillingEnCour->getTypeMail() == "mailling"){
$message = $this->getMessageMaillingType($maillingEnCour);
} elseif ($maillingEnCour->getTypeMail() == "veille"){
$message = $this->getMessageVeilleType($maillingEnCour);
} elseif ($maillingEnCour->getTypeMail() == "test"){
$message = $this->getMessageMaillingTestType($maillingEnCour);
} elseif ($maillingEnCour->getTypeMail() == "confirmationBegin"){
$message = $this->getMessageConfirmation($maillingEnCour,'begin');
} elseif ($maillingEnCour->getTypeMail() == "confirmationEnd"){
$message = $this->getMessageConfirmation($maillingEnCour,'end');
if($maillingEnCour->getDestinataire() == 'informatique@escalconsulting.com')
$endMailling = true;
}
if($message != false){
if(is_array($message)){
foreach ($message as $mess){
$this->sendMail($mess, $maillingEnCour);
}
return false;
} else {
$this->sendMail($message, $maillingEnCour);
}
}
if($endMailling){
return $maillingEnCour;
}
return false;
}
public function finMailling(\App\Entity\MaillingEnCour $maillingEnCour){
$maillingEnCourMailling = $this->em->getRepository('App:MaillingEnCour')
->findBy(['mailling' => $maillingEnCour->getMailling(), 'typeMail' => 'mailling', 'envoyer' => true]);
$maillingEnCour->getMailling()->setNbMailEnvoye(count($maillingEnCourMailling));
$maillingEnCour->getMailling()->setEnvoyer(true);
$maillingEnCour->getMailling()->setDateEnvoi(new \DateTime('now'));
$this->em->persist($maillingEnCour->getMailling());
$this->em->flush();
$this->setMaillingSend($maillingEnCour->getMailling());
if($maillingEnCour->getMailling()->getTypeMail() != "Coupure") {
$this->miseAjourPressroom($maillingEnCour->getMailling());
}
}
public function getMessageConfirmation(\App\Entity\MaillingEnCour $maillingEnCour, $status){
$from = $this->getFrom($maillingEnCour);
if($status == 'begin'){
$from = $this->getFrom($maillingEnCour);
$mailling = $maillingEnCour->getMailling();
$pathRSA = $this->kernel->getRootDir() . '/../public/Interne/RSA';
$privateKeyRSA = file_get_contents($pathRSA);
$domainName = 'escalconsulting.com';
$selector = '1515841257';
$signer = new \Swift_Signers_DKIMSigner($privateKeyRSA, $domainName, $selector);
if($mailling->getTypeMail() != 'CP'){
$size = 0;
$pathCoupure = $this->kernel->getRootDir() . '/../public/coupures/';
$iterator = $mailling->getPiecesJointes()->getIterator();
$iterator->uasort(function ($a, $b) {
return ($a->getCoupure()->getDateParution() < $b->getCoupure()->getDateParution()) ? -1 : 1;
});
$mailling->setPiecesJointes(new ArrayCollection(iterator_to_array($iterator)));
foreach ($mailling->getPiecesJointes() as $pieceJointe){
$size = $size + filesize ( $pathCoupure . $pieceJointe->getUrl());
}
$coupuresMessage = [];
if($size < 10000000){
$coupuresMessage[] = $mailling->getPiecesJointes();
} else {
$ratio = $size / 10000000;
$ratio = floor($ratio) + 1;
$sizeMid = $size / $ratio;
$sizeCoupure = 0;
$pieceJointeMail = [];
foreach ($mailling->getPiecesJointes() as $pieceJointe){
if($sizeCoupure > $sizeMid){
$coupuresMessage[] = $pieceJointeMail;
$pieceJointeMail = [];
$sizeCoupure = 0;
}
$pieceJointeMail[] = $pieceJointe;
$sizeCoupure = $sizeCoupure + filesize ( $pathCoupure . $pieceJointe->getUrl());
}
$coupuresMessage[] = $pieceJointeMail;
}
$messages = [];
$i = 1;
foreach ($coupuresMessage as $coupureMessage) {
$template = $this->twig->load('mailCoupure.html.twig');
if (count($coupuresMessage) == 1) {
$objetMail = $mailling->getNom();
} else {
$objetMail = $mailling->getNom() .' '. $i . '/' . count($coupuresMessage);
}
$debut = '';
$fin = '';
if($i == 1){
$debut = $mailling->getDebutMailCoupure();
}
if($i == count($coupuresMessage)){
$fin = $mailling->getFinMailCoupure();
}
$message = (new \Swift_Message($objetMail))
->setFrom($from)
->setTo($maillingEnCour->getDestinataire())
->setSubject($objetMail)
->setBody($template->render(
array('mailling' => $mailling, 'coupureMessage' => $coupureMessage,
'user' => $mailling->getReplyTo(), 'debut' => $debut, 'fin' => $fin,
'logo' => $mailling->getClient()->getLogo()->getUrl(),)),
'text/html')
->setReplyTo($mailling->getReplyTo()->getUser()->getEmail());
$message->attachSigner($signer);
/** @var PieceJointeMailling $pieceJointe */
foreach ($coupureMessage as $pieceJointe) {
$message->attach(\Swift_Attachment::fromPath($pathCoupure. $pieceJointe->getUrl()));
}
$i = $i + 1;
$messages[] = $message;
}
return $messages;
} else {
$rand = '&'.rand(0,1000000).'='.rand(0,1000000);
if (strlen($mailling->getColor())==7){
$color = $mailling->getColor();
} else {
$color = "#F57E60";
}
$template = $this->twig->load('mailConfirmation.html.twig');
$message = (new \Swift_Message($mailling->getObjetCour()))
->setFrom($from)
->setTo($maillingEnCour->getDestinataire())
->setSubject($mailling->getObjetCour())
->setBody(
$template->render(array('mailling' => $mailling, 'user' => $mailling->getReplyTo(),
'logo' => $mailling->getClient()->getLogo()->getUrl(),
'rand' => $rand, 'color' => $color)),
'text/html'
)
->setReplyTo($mailling->getReplyTo()->getUser()->getEmail());
if($mailling->getId() == 6824){
$pathfile = $this->kernel->getRootDir() . '/../public/Interne/';
$message->attach(\Swift_Attachment::fromPath($pathfile. 'infographie.jpg'));
}
$message->attachSigner($signer);
/** @var PieceJointeMailling $piecesJointe */
foreach ($mailling->getPiecesJointes() as $piecesJointe){
$message->attach(\Swift_Attachment::fromPath($this->kernel->getRootDir() . '/../public/maillings/'. $mailling->getAncienId() . '/' . $piecesJointe->getUrl()));
}
}
return $message;
}
$template = $this->twig->load('mailConfirmationFin.html.twig');
if($maillingEnCour->getMailling()->getTypeMail() == 'Coupure'){
$objet = $maillingEnCour->getMailling()->getObjet();
} else {
$objet = $maillingEnCour->getMailling()->getObjetCour();
}
$finObjet = ' a été envoyé';
$message = (new \Swift_Message($objet . $finObjet))
->setFrom($from)
->setTo($maillingEnCour->getDestinataire())
->setSubject($objet . $finObjet)
->setBody(
$template->render(array('mailling' => $maillingEnCour->getMailling())),
'text/html'
);
return $message;
}
public function getMessageVeilleType(\App\Entity\MaillingEnCour $maillingEnCour){
$from = $this->getFrom($maillingEnCour);
$template = $this->twig->load('veille.html.twig');
$message = (new \Swift_Message('Veille du '. $maillingEnCour->getVeille()->getDate()->format('d/m/Y')))
->setFrom($from)
->setTo($maillingEnCour->getDestinataire())
->setSubject('Veille du '. $maillingEnCour->getVeille()->getDate()->format('d/m/Y'))
->setBody(
$template->render(array('veille' => $maillingEnCour->getVeille())),
'text/html'
);
return $message;
}
public function getMessageMaillingTestType(\App\Entity\MaillingEnCour $maillingEnCour){
$from = $this->getFrom($maillingEnCour);
$mailling = $maillingEnCour->getMailling();
$pathRSA = $this->kernel->getRootDir() . '/../public/Interne/RSA';
$privateKeyRSA = file_get_contents($pathRSA);
$domainName = 'escalconsulting.com';
$selector = '1515841257';
$signer = new \Swift_Signers_DKIMSigner($privateKeyRSA, $domainName, $selector);
$rand = '&'.rand(0,1000000).'='.rand(0,1000000);
if($mailling->getTypeMail() != 'CP'){
$size = 0;
$pathCoupure = $this->kernel->getRootDir() . '/../public/coupures/';
$iterator = $mailling->getPiecesJointes()->getIterator();
$iterator->uasort(function ($a, $b) {
return ($a->getCoupure()->getDateParution() < $b->getCoupure()->getDateParution()) ? -1 : 1;
});
$mailling->setPiecesJointes(new ArrayCollection(iterator_to_array($iterator)));
foreach ($mailling->getPiecesJointes() as $pieceJointe){
$size = $size + filesize ( $pathCoupure . $pieceJointe->getUrl());
}
$coupuresMessage = [];
if($size < 10000000){
$coupuresMessage[] = $mailling->getPiecesJointes();
} else {
$ratio = $size / 10000000;
$ratio = floor($ratio) + 1;
$sizeMid = $size / $ratio;
$sizeCoupure = 0;
$pieceJointeMail = [];
foreach ($mailling->getPiecesJointes() as $pieceJointe){
if($sizeCoupure > $sizeMid){
$coupuresMessage[] = $pieceJointeMail;
$pieceJointeMail = [];
$sizeCoupure = 0;
}
$pieceJointeMail[] = $pieceJointe;
$sizeCoupure = $sizeCoupure + filesize ( $pathCoupure . $pieceJointe->getUrl());
}
$coupuresMessage[] = $pieceJointeMail;
}
$messages = [];
$i = 1;
foreach ($coupuresMessage as $coupureMessage) {
$template = $this->twig->load('mailTestCoupure.html.twig');
if (count($coupuresMessage) == 1) {
$objetMail = $mailling->getNom();
} else {
$objetMail = $mailling->getNom() .' '. $i . '/' . count($coupuresMessage);
}
$debut = '';
$fin = '';
if($i == 1){
$debut = $mailling->getDebutMailCoupure();
}
if($i == count($coupuresMessage)){
$fin = $mailling->getFinMailCoupure();
}
$message = (new \Swift_Message($objetMail))
->setFrom($from)
->setTo($maillingEnCour->getDestinataire())
->setSubject($objetMail)
->setBody($template->render(
array('mailling' => $mailling, 'coupureMessage' => $coupureMessage,
'user' => $mailling->getReplyTo(), 'debut' => $debut, 'fin' => $fin, 'rand' => $rand,
'logo' => $mailling->getClient()->getLogo()->getUrl(),)),
'text/html')
->setReplyTo($mailling->getReplyTo()->getUser()->getEmail());
$message->attachSigner($signer);
/** @var PieceJointeMailling $pieceJointe */
foreach ($coupureMessage as $pieceJointe) {
$message->attach(\Swift_Attachment::fromPath($pathCoupure. $pieceJointe->getUrl()));
}
$i = $i + 1;
$messages[] = $message;
}
return $messages;
} else {
if (strlen($mailling->getColor())==7){
$color = $mailling->getColor();
} else {
$color = "#F57E60";
}
if($mailling->getId()== 5517 or $mailling->getId() == 5899){
$template = $this->twig->load('mailClient/logoFCAtest.html.twig');
} else {
$template = $this->twig->load('mailTestNew.html.twig');
}
$message = (new \Swift_Message($mailling->getObjetCour()))
->setFrom($from)
->setTo($maillingEnCour->getDestinataire())
->setSubject($mailling->getObjetCour())
->setBody(
$template->render(array('mailling' => $mailling, 'user' => $mailling->getReplyTo(),
'logo' => $mailling->getClient()->getLogo()->getUrl(),
'rand' => $rand, 'color' => $color)),
'text/html'
)
->setReplyTo($mailling->getReplyTo()->getUser()->getEmail());
if($mailling->getId() == 6824){
$pathfile = $this->kernel->getRootDir() . '/../public/Interne/';
$message->attach(\Swift_Attachment::fromPath($pathfile. 'infographie.jpg'));
}
$message->attachSigner($signer);
/** @var PieceJointeMailling $piecesJointe */
foreach ($mailling->getPiecesJointes() as $piecesJointe){
$message->attach(\Swift_Attachment::fromPath($this->kernel->getRootDir() . '/../public/maillings/'. $mailling->getAncienId() . '/' . $piecesJointe->getUrl()));
}
}
return $message;
}
public function getMessageMaillingType(\App\Entity\MaillingEnCour $maillingEnCour){
if(filter_var(trim($maillingEnCour->getDestinataire()), FILTER_VALIDATE_EMAIL)){
$from = $this->getFrom($maillingEnCour);
$mailling = $maillingEnCour->getMailling();
// dkim sigbnature electronique des mails lors de l'envoie
$pathRSA = $this->kernel->getRootDir() . '/../public/Interne/RSA';
$privateKeyRSA = file_get_contents($pathRSA);
$domainName = 'escalconsulting.com';
$selector = '1515841257';
$signer = new \Swift_Signers_DKIMSigner($privateKeyRSA, $domainName, $selector);
if($mailling->getTypeMail() != 'CP'){
$size = 0;
$pathCoupure = $this->kernel->getRootDir() . '/../public/coupures/';
$iterator = $mailling->getPiecesJointes()->getIterator();
$iterator->uasort(function ($a, $b) {
return ($a->getCoupure()->getDateParution() < $b->getCoupure()->getDateParution()) ? -1 : 1;
});
$mailling->setPiecesJointes(new ArrayCollection(iterator_to_array($iterator)));
foreach ($mailling->getPiecesJointes() as $pieceJointe){
$size = $size + filesize ( $pathCoupure . $pieceJointe->getUrl());
}
$coupuresMessage = [];
if($size < 10000000){
$coupuresMessage[] = $mailling->getPiecesJointes();
} else {
$ratio = $size / 10000000;
$ratio = floor($ratio) + 1;
$sizeMid = $size / $ratio;
$sizeCoupure = 0;
$pieceJointeMail = [];
foreach ($mailling->getPiecesJointes() as $pieceJointe){
if($sizeCoupure > $sizeMid){
$coupuresMessage[] = $pieceJointeMail;
$pieceJointeMail = [];
$sizeCoupure = 0;
}
$pieceJointeMail[] = $pieceJointe;
$sizeCoupure = $sizeCoupure + filesize ( $pathCoupure . $pieceJointe->getUrl());
}
$coupuresMessage[] = $pieceJointeMail;
}
$messages = [];
$i = 1;
foreach ($coupuresMessage as $coupureMessage) {
$template = $this->twig->load('mailCoupure.html.twig');
if (count($coupuresMessage) == 1) {
$objetMail = $mailling->getNom();
} else {
$objetMail = $mailling->getNom() .' '. $i . '/' . count($coupuresMessage);
}
$debut = '';
$fin = '';
if($i == 1){
$debut = $mailling->getDebutMailCoupure();
}
if($i == count($coupuresMessage)){
$fin = $mailling->getFinMailCoupure();
}
$message = (new \Swift_Message($objetMail))
->setFrom($from)
->setTo($maillingEnCour->getDestinataire())
->setSubject($objetMail)
->setBody($template->render(
array('mailling' => $mailling, 'coupureMessage' => $coupureMessage,
'user' => $mailling->getReplyTo(), 'debut' => $debut, 'fin' => $fin,
'logo' => $mailling->getClient()->getLogo()->getUrl(), 'idUser' => $maillingEnCour->getUserId(),
'userSend' => $maillingEnCour->getDestinataire())),
'text/html')
->setReplyTo($mailling->getReplyTo()->getUser()->getEmail());
$message->attachSigner($signer);
/** @var PieceJointeMailling $pieceJointe */
foreach ($coupureMessage as $pieceJointe) {
$message->attach(\Swift_Attachment::fromPath($pathCoupure. $pieceJointe->getUrl()));
}
$i = $i + 1;
$messages[] = $message;
}
return $messages;
} else {
if (strlen($mailling->getColor())==7){
$color = $mailling->getColor();
} else {
$color = "#F57E60";
}
if($mailling->getId()== 5517 or $mailling->getId() == 5899 ){ // template mailling specifique sur demande
$template = $this->twig->load('mailClient/logoFCA.html.twig');
} else {
$template = $this->twig->load('maillingNew.html.twig');
}
$message = (new \Swift_Message($mailling->getObjetCour()))
->setFrom($from)
->setTo($maillingEnCour->getDestinataire())
->setSubject($mailling->getObjetCour())
->setBody(
$template->render(array('mailling' => $mailling, 'user' => $mailling->getReplyTo(),
'logo' => $mailling->getClient()->getLogo()->getUrl(), 'idUser' => $maillingEnCour->getUserId(),
'userSend' => $maillingEnCour->getDestinataire(), 'color' => $color)),
'text/html'
)
->setReplyTo($mailling->getReplyTo()->getUser()->getEmail());
// attache une piece jointe a un mailling spécifique
if($mailling->getId() == 6824){
$pathfile = $this->kernel->getRootDir() . '/../public/Interne/';
$message->attach(\Swift_Attachment::fromPath($pathfile. 'infographie.jpg'));
}
$message->attachSigner($signer);
}
}
else{
$message = false;
$maillingEnCour->setErreur('le mail est incorect');
$this->em->persist($maillingEnCour);
$this->em->flush();
}
return $message;
}
public function sendMail(\Swift_Message $message ,\App\Entity\MaillingEnCour $maillingEnCour){
// Envoi de CP
if($maillingEnCour->getAdressEnvoie()) {
$password = 'skl001';
//recuperer derniere adresse de la table
$derniereAdresseEnvoie = $this->em->getRepository('App:DerniereAdresseEnvoie')->findOneBy(['id' => 1]);
$nomDerniereAdresseEnvoie = $derniereAdresseEnvoie->getAdresseEnvoie();
//recuperer l'id de la derniere adresse envoyee
$adresseEnvoye = $this->em->getRepository('App:CompteurAdressesEnvoi')->findOneBy(['adresse_envoi' => $nomDerniereAdresseEnvoie]);
$IDadresseEnvoyee = $adresseEnvoye->getId();
//on recup le nb total d'adresses d'envoies
$totalAdressesEnvoies = $this->em->getRepository('App:CompteurAdressesEnvoi')->findAll();
$nbAdressesEnvoies = count($totalAdressesEnvoies);
//si ID supp au nb total d'adresses on retourne à 1
if ($IDadresseEnvoyee < $nbAdressesEnvoies) {
$IDnouvelleAdresse = $IDadresseEnvoyee + 1;
} else {
$IDnouvelleAdresse = 1;
}
$nouvelleAdresseEnvoie = $this->em->getRepository('App:CompteurAdressesEnvoi')->findOneBy(['id' => $IDnouvelleAdresse]);
$compteurMail = $this->em->getRepository('App:CompteurAdressesEnvoi')
->findOneBy(['adresse_envoi' => $nouvelleAdresseEnvoie->getAdresseEnvoi(), 'date_envoi_mail' => new \DateTime('now')]);
if (is_null($compteurMail)) {
//on ecrase la date
$nouvelleAdresseEnvoie->setDateEnvoiMail(new \DateTime('now'));
//mettre à jour le compteur d'envoie pour l'adresse
$nouvelleAdresseEnvoie->setCompteurMail(1);
} else {
//mettre à jour le compteur d'envoie pour l'adresse
$nouvelleAdresseEnvoie->setCompteurMail($nouvelleAdresseEnvoie->getCompteurMail() + 1);
}
$derniereAdresseEnvoie->setAdresseEnvoie($nouvelleAdresseEnvoie->getAdresseEnvoi());
$mail = $nouvelleAdresseEnvoie->getAdresseEnvoi();
$this->em->persist($derniereAdresseEnvoie);
$this->em->persist($nouvelleAdresseEnvoie);
$this->em->flush();
//si c'est un gmail
if (substr_compare($maillingEnCour->getDestinataire(), "@gmail.com", -10, 10) === 0) {
//recuperer nombre total d'envoi pour l'adresse mail fictive pour date du jour
$compteur = $this->em->getRepository('App:CompteurAdressesEnvoi')
->findOneBy(['adresse_envoi' => $mail, 'date_envoi_gmail' => new \DateTime('now')]);
if (!is_null($compteur)) {
$compteurGmail = $compteur->getCompteurGmail();
} else {
//si aucun compteur pour cette adresse fictive pour la date du jour, écraser l'ancien compteur et changer la date
$compteurGmail = 0;
$compteur = $this->em->getRepository('App:CompteurAdressesEnvoi')->findOneBy(['adresse_envoi' => $mail]);
$compteur->setCompteurGmail($compteurGmail);
$compteur->setDateEnvoiGmail(new \DateTime('now'));
$this->em->persist($compteur);
$this->em->flush();
}
//si moins de 500 envois gmail, on garde l'adresse fictive de base
if ($compteurGmail < 500) {
//on ajoute un envoi au compteur
$compteur->setCompteurGmail($compteurGmail + 1);
$this->em->persist($compteur);
$this->em->flush();
} else {
$adressesFictives = $this->em->getRepository('App:CompteurAdressesEnvoi')
->findAll();
$trouve = false;
//on parcourt toutes les adresses fictives
foreach ($adressesFictives as $adresse) {
if ($adresse->getDateEnvoiGmail() < new \DateTime('midnight')) {
$adresse->setDateEnvoiGmail(new \DateTime('now'));
$adresse->setCompteurGmail(0);
}
if ($adresse->getCompteurGmail() < 500) {
$trouve = true;
//recuperer l'adresse mail fictive de moins de 500 envois
$mail = $adresse->getAdresseEnvoi();
//On soustrait le compteur $nouvelleAdresseEnvoie si elle est différente de l'adresse envoie courante
if ($mail != $nouvelleAdresseEnvoie->getAdresseEnvoi()) {
$nouvelleAdresseEnvoie->setCompteurMail($nouvelleAdresseEnvoie->getCompteurMail() - 1);
}
$compteurGmail = $adresse->getCompteurGmail();
$adresse->setCompteurGmail($compteurGmail + 1);
$this->em->persist($adresse);
$this->em->flush();
break;
}
}
//dans le cas où il ne reste plus d'adresses fictives à moins de 500 envois gmail
if ($trouve === false) {
$mail = $maillingEnCour->getEnvoyerPar()->getAdresseEnvoi();
$cmpt = $this->em->getRepository('App:CompteurAdressesEnvoi')->findOneBy(['adresse_envoi' => $mail]);
$cmpt->setCompteurGmail($compteurGmail + 1);
$this->em->persist($cmpt);
$this->em->flush();
}
$this->em->persist($nouvelleAdresseEnvoie);
$this->em->flush();
}
}
// dans le cas d'envoi des retombées
} else {
$mail = $maillingEnCour->getEnvoyerPar()->getUser()->getEmail();
$password = $maillingEnCour->getEnvoyerPar()->getPasswordMail();
}
$transport = new \Swift_SmtpTransport('exchange.escalconsulting.com', 587, 'tls');
$transport
->setUsername($mail)
->setPassword($password);
$mailer = new \Swift_Mailer($transport);
$logger = new \Swift_Plugins_Loggers_ArrayLogger;
$mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));
// Correspondre l'adresse mail qui se connecte et l'expediteur
$message->setFrom($mail);
$mailer->send($message, $failRecipient);
if($failRecipient != []){
$maillingEnCour->setErreur('erreur lors de l\'envoie du mail');
} else {
$maillingEnCour->setEnvoyer(true);
}
$this->em->persist($maillingEnCour);
$this->em->flush();
}
public function attachSigner(\Swift_Message $message){
$pathRSA = $this->kernel->getRootDir() . '/../public/Interne/RSA';
$privateKeyRSA = file_get_contents($pathRSA);
$domainName = 'escalconsulting.com';
$selector = '1515841257';
$signer = new \Swift_Signers_DKIMSigner($privateKeyRSA, $domainName, $selector);
$message->attachSigner($signer);
return $message;
}
public function getFrom(\App\Entity\MaillingEnCour $maillingEnCour){
if($maillingEnCour->getAdressEnvoie()){
return $maillingEnCour->getEnvoyerPar()->getAdresseEnvoi();
}
return $maillingEnCour->getEnvoyerPar()->getUser()->getEmail();
}
public function sendMailMerge($rand, AuthUser $authUser){
$template = $this->twig->load('mergePdf.html.twig');
$message = (new Swift_Message('pdf'))
->setFrom('notification@escalconsulting.com')
->setTo($authUser->getUser()->getEmail())
->setSubject('pdf')
->setBody(
$template->render(array('rand'=> $rand)),
'text/html'
)
->setReplyTo('notification@escalconsulting.com');
$mail = 'notification@escalconsulting.com';
$password = 'H76-7Gj%a';
$transport = new Swift_SmtpTransport('exchange.escalconsulting.com', 587, 'tls');
$transport
->setUsername($mail)
->setPassword($password);
$mailer = new Swift_Mailer($transport);
$logger = new Swift_Plugins_Loggers_ArrayLogger;
$mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
$mailer->send($message, $failRecipient);
}
public function sendRappel($rappel){
$rappel['commentaire'] = str_replace(''', '\'', $rappel['commentaire']);
$rappel['titre'] = str_replace(''', '\'', $rappel['titre']);
$template = $this->twig->load('rappel.html.twig');
$destinataire = $rappel['destinataire'];
$message = (new \Swift_Message('rappel intranet'))
->setFrom('rappel@escalconsulting.com')
->setTo($destinataire)
->setSubject('rappel intranet')
->setBody(
$template->render(array('rappel' => $rappel)),
'text/html'
);
$mail = 'rappel@escalconsulting.com';
$password = 'C?uR*5j59';
$transport = new Swift_SmtpTransport('exchange.escalconsulting.com', 587, 'tls');
$transport
->setUsername($mail)
->setPassword($password);
$mailer = new Swift_Mailer($transport);
$logger = new Swift_Plugins_Loggers_ArrayLogger;
$mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
$mailer->send($message, $failRecipient);
dump($failRecipient);
}
public function sendDemandeContact($message, $object, $email, $identite, $telephone){
$template = $this->twig->load('contact.html.twig');
$message = (new \Swift_Message('Notification site web'))
->setFrom('notification@escalconsulting.com')
->setTo('contact@escalconsulting.com')
->setSubject(' Demande Site Web /' .$object)
->setBody(
$template->render(array('identite' => $identite, 'message' => $message, 'email' => $email, 'telephone' => $telephone)),
'text/html'
);
$mail = 'notification@escalconsulting.com';
$password = 'H76-7Gj%a';
$transport = new Swift_SmtpTransport('exchange.escalconsulting.com', 587, 'tls');
$transport
->setUsername($mail)
->setPassword($password);
$mailer = new Swift_Mailer($transport);
$logger = new Swift_Plugins_Loggers_ArrayLogger;
$mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
$mailer->send($message, $failRecipient);
}
/**
* @param DemandeDeConge $demandeDeConge
*/
public function sendMailDemandeCongeResponsable(DemandeDeConge $demandeDeConge, $rand, $user = null){
$userToSend = $this->em->getRepository('App\Entity\User')->findOneBy(['email'=> $demandeDeConge->getPersonneAEnvoyer()]);
/** @var User $userToSend */
if($userToSend->getEmail() == 'louis@escalconsulting.com'){
$template = $this->twig->load('demandeConge.html.twig');
} else {
$template = $this->twig->load('demandeCongeResponsable.html.twig');
}
$message = (new Swift_Message('demande de congé '. $demandeDeConge->getAuthUser()->getUser()->getPrenom()
. ' ' .$demandeDeConge->getAuthUser()->getUser()->getNom()))
->setFrom($demandeDeConge->getAuthUser()->getUser()->getEmail())
->setTo($userToSend->getEmail())
->setSubject('demande de congé '. $demandeDeConge->getAuthUser()->getUser()->getNom() . ' '.
$demandeDeConge->getAuthUser()->getUser()->getPrenom())
->setBody(
$template->render(array('demandeDeConge' => $demandeDeConge, 'rand'=> $rand, 'user' => $userToSend, 'uservalide' => $user)),
'text/html'
)
->setReplyTo($demandeDeConge->getAuthUser()->getUser()->getEmail());
$message->attach(\Swift_Attachment::fromPath($this->kernel->getRootDir() . '/../public/Interne/demandeConge/'.$demandeDeConge->getDebutConge()->format('Y-m-d').'demandeConge'.
$demandeDeConge->getAuthUser()->getUser()->getNom().'.pdf'));
$mail = $demandeDeConge->getAuthUser()->getUser()->getEmail();
$password = $demandeDeConge->getAuthUser()->getPasswordMail();
$transport = new Swift_SmtpTransport('exchange.escalconsulting.com', 587, 'tls');
$transport
->setUsername($mail)
->setPassword($password);
$mailer = new Swift_Mailer($transport);
$logger = new Swift_Plugins_Loggers_ArrayLogger;
$mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
$mailer->send($message, $failRecipient);
}
public function sendReseauxSociaux($coupure){
// gestion des accents
$coupure['titre'] = str_replace(''', '\'', $coupure['titre']);
$coupure['nom_support'] = str_replace(''', '\'', $coupure['nom_support']);
$coupure['doc_lier'] = str_replace(''', '\'', $coupure['doc_lier']);
$template = $this->twig->load('mailReseauxSociaux.html.twig');
$destinataire = "reseauxsociaux@escalconsulting.com";
$message = (new \Swift_Message('Information de la coupure'))
->setFrom('notification@escalconsulting.com')
->setTo($destinataire)
->setSubject('Informations coupures')
->setBody(
$template->render(array('coupure' => $coupure)),
'text/html'
);
$mail = 'notification@escalconsulting.com';
$password = 'H76-7Gj%a';
$transport = new Swift_SmtpTransport('exchange.escalconsulting.com', 587, 'tls');
$transport
->setUsername($mail)
->setPassword($password);
$mailer = new Swift_Mailer($transport);
$logger = new Swift_Plugins_Loggers_ArrayLogger;
$mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
$mailer->send($message, $failRecipient);
}
public function sendDesabonnement($email){
$template = $this->twig->load('notificationDesabonnement.html.twig');
$destinataire = $email;
$message = (new \Swift_Message('Confirmation de désabonnement'))
->setFrom('notification@escalconsulting.com')
->setTo($destinataire)
->setSubject('Confirmation de désabonnement')
->setBody(
$template->render(array('email' => $email)),
'text/html'
);
$mail = 'notification@escalconsulting.com';
$password = 'H76-7Gj%a';
$transport = new Swift_SmtpTransport('exchange.escalconsulting.com', 587, 'tls');
$transport
->setUsername($mail)
->setPassword($password);
$mailer = new Swift_Mailer($transport);
$logger = new Swift_Plugins_Loggers_ArrayLogger;
$mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
$mailer->send($message, $failRecipient);
}
}