<?php
namespace App\Controller;
use App\Entity\Agent;
use App\Entity\Customer;
use App\Entity\CustomerComment;
use App\Entity\Mail;
use App\Entity\MailAttachment;
use App\Entity\Parameter;
use DateInterval;
use DateTime;
use Doctrine\Persistence\ObjectManager;
use Error;
use SSilence\ImapClient\ImapClientException;
use SSilence\ImapClient\ImapClient;
use SSilence\ImapClient\IncomingMessage;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class CrmController extends AbstractCrmController
{
/**
* @Route("/mailSingle", name="mailSingle")
* @return Response
* @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
*/
public function mailSingle(Request $request): Response
{
/** @var $agent Agent */
$agent = $this->get('session')->get('User');
$em = $this->getDoctrine()->getManager();
$repoMail = $em->getRepository(Mail::class);
/** @var $mail Mail */
$mail = $repoMail->findOneById($request->get('id'));
$repoMailAttachment = $em->getRepository(MailAttachment::class);
$mailAttachments = $repoMailAttachment->findByMail($mail->getId());
if ($mailAttachments == null) {
$mailAttachments = array();
}
//if($mail->getAgent()->getId() == $agent->getId())
return $this->render('crm/mailSingle.html.twig', [
'email' => $mail,
'mailAttachments' => $mailAttachments
]);
}
/**
* @Route("/myEmails", name="myEmails")
* @return Response
* @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
*/
public function myEmails(): Response
{
/** @var $agent Agent */
$agent = $this->get('session')->get('User');
$em = $this->getDoctrine()->getManager();
$repoMail = $em->getRepository(Mail::class);
$existing = $repoMail->findBy(array('agent' => $agent), array('message_uid' => 'DESC'));
return $this->render('crm/myEmails.html.twig', [
'emails' => $existing,
'detailsView' => false
]);
}
/**
* @Route("/getEmail", name="getEmail")
* @return Response
* @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
*/
public function getEmail(Request $request): Response
{
$forceMode = $request->get('force') == null || $request->get('force') == '' ? 0 : ($request->get('force') == '1' ? 1 : 0);
// throw new \Exception("forceMode " . $forceMode);
/** @var $agent Agent */
$agent = $this->get('session')->get('User');
if ($agent == null) {
return $this->render('crm/getEmail.html.twig', [
'emaill' => "noAgent"
]);
}
if ($agent->getPasswordToEmail() == null) {
return $this->render('crm/getEmail.html.twig', [
'emaill' => "no password to email"
]);
}
$now = new DateTime('now');
$emailAllowedDate = $agent->getEmailAllowDate();
if ($emailAllowedDate == null) {
$emailAllowedDate = $now;
}
if (!$forceMode && $emailAllowedDate->getTimestamp() > $now->getTimestamp()) {
return $this->render('crm/getEmail.html.twig', [
'emaill' => "getEmail is allowed only each 5 minutes"
]);
}
$em = $this->getDoctrine()->getManager();
$repoAgent = $em->getRepository(Agent::class);
/** @var $agent Agent */
$agent = $repoAgent->findOneById($agent->getId());
$newEmailAllowedDate = new DateTime('now');
$newEmailAllowedDate->add(new DateInterval('PT5M'));
$agent->setEmailAllowDate($newEmailAllowedDate);
$em->persist($agent);
$em->flush();
$mailbox = 'ssl0.ovh.net:993';
$username = $agent->getEmail();//'test@unimetasoft.com';
$password = $agent->getPasswordToEmail(); //'LEn3EpMRW7v3YNs';
$encryption = ImapClient::ENCRYPT_SSL; // TLS OR NULL accepted
// Open connection
try {
$imap = new ImapClient($mailbox, $username, $password, $encryption);
// You can also check out example-connect.php for more connection options
} catch (ImapClientException $error) {
echo $error->getMessage() . PHP_EOL; // You know the rule, no errors in production ...
die(); // Oh no :( we failed
}
$mailInfo = '';
$folders = $imap->getFolders();
foreach ($folders as $folder) {
foreach (array_keys($folder) as $x)
//echo array_keys($x);
$mailInfo .= ' folder [ ' . $x . ' ]';
}
// Select the folder INBOX
$imap->selectFolder('INBOX');
// Count the messages in current folder
$overallMessages = $imap->countMessages();
$mailInfo .= ' -> ' . $overallMessages;
if (!$forceMode && $agent->getHowManyMessages() === $overallMessages) {
return $this->render('crm/getEmail.html.twig', [
'emaill' => "norhing to do -> number of messages " . $agent->getHowManyMessages()
]);
}
$unreadMessages = $imap->countUnreadMessages();
// Fetch all the messages in the current folder
$customerRepo = $em->getRepository(Customer::class);
$customers = $customerRepo->findAll();
$numberOfIterations = $overallMessages / 10;
$repoMail = $em->getRepository(Mail::class);
for ($i = 0; $i < $numberOfIterations; $i++) {
$messages = $imap->getMessages(10, $i);
$existing = $repoMail->findByAgent($agent);
$agent->setHowManyMessages(count($existing));
$em->persist($agent);
$em->flush();
$howMany = 0;
/** @var IncomingMessage $singleMail */
foreach ($messages as $singleMessage) {
$howMany += $this->saveSingleEmail($existing, $singleMessage, $agent, $customers, $em);
}
$mailInfo .= ' howMany=' . $howMany;
if ($howMany == 0 && !$forceMode) {
break;
}
}
$existing = $repoMail->findByAgent($agent);
$agent->setHowManyMessages(count($existing));
$em->persist($agent);
$em->flush();
return $this->render('crm/getEmail.html.twig', [
'emaill' => $mailInfo
]);
}
private function isExistingContaining($existing, $message_id, $messageUid)
{
/** @var Mail $singleMail */
foreach ($existing as $singleMail) {
if (strval($singleMail->getMessageUid()) === strval($messageUid) && $singleMail->getMessageId() === $message_id) {// &&
return true;
}
}
return false;
}
/**
* @Route("/testEmail", name="testEmail")
* @param \Swift_Mailer $mailer
* @return Response
* @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
*/
public function testEmail(\Swift_Mailer $mailer): Response
{
$message = (new \Swift_Message('Hello Email'))
->setFrom('crm@wronieruchomosci.pl')
->setTo('tzygadl@gmail.com')
->setBody('ggg'
// $this->renderView(
// // templates/hello/email.txt.twig
// 'hello/email.txt.twig',
// ['name' => 'xxx']
// )
);
$mailer->send($message);
return $this->redirectToRoute('app_crm');
}
/**
* @Route("/", name="app_crm")
* @param Request $request
* @return Response
*/
public function index(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository(Customer::class);
/** @var $agent Agent */
$agent = $this->get('session')->get('User');
if ($agent == null) {
return $this->render('crm/login.html.twig', [
'controller_name' => 'CrmController',
]);
}
if ($request->get('page')) {
$page = $request->get('page');
} else {
$page = 1;
}
if ($request->get('pageToCall')) {
$pageToCall = $request->get('pageToCall');
} else {
$pageToCall = 1;
}
if ($agent->getAgentRole() === 'admin') {
$all = $repo->findAllDesc("/", $page - 1);
$xpages = $repo->findAllXpages("/", $page);
} else {
$all = $repo->findAllDesc("/", $page - 1, $agent);
$xpages = $repo->findAllXpages("/", $page, $agent);
}
$tocall = $repo->toCall("/", $pageToCall - 1, $agent);
$tocallpages = $repo->findToCallXpages("/", $page, $agent);
return $this->render('crm/index.html.twig', [
'controller_name' => 'CrmController',
'myCustomers' => $all,
'xpages' => $xpages,
'tocall' => $tocall,
'image_picture' => $this->getImagePicture($agent),
'tocallpages' => $tocallpages,
'logged' => $agent
]);
}
/**
* @Route("/logout", name="logout")
*/
public function logout(): Response
{
$this->get('session')->set('User', null);
return $this->redirectToRoute('app_crm');
}
/**
* @Route("/login", name="login")
* @param Request $request
* @return Response
*/
public function login(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository(Agent::class);
if (empty($repo->findAll())) {
$a = new Agent();
$a->setEmail('admin@admin.pl');
$a->setPassword('admin');
$a->setPasswordToEmail('n/a');
$a->setFirstname('admin');
$a->setLastname('admin');
$a->setAgentRole('admin');
$em->persist($a);
$em->flush();
}
if ($repo->findBy(
array('email' => $request->get('email'), 'password' => $request->get('password'))) == null) {
return $this->render('crm/login.html.twig', [
'controller_name' => 'CrmController',
'logged' => $this->get('session')->get('User')
]);
} else {
$this->get('session')->set('User', $repo->findOneBy(
array('email' => $request->get('email'), 'password' => $request->get('password'))));
return $this->redirectToRoute('app_crm');
}
}
/**
* @Route("/allContacts", name="allContacts")
* @param Request $request
* @return Response
*/
public function allContacts(Request $request): Response
{
if (!$this->get('session')->get('User')) {
return $this->redirectToRoute('app_crm');
}
if (!$this->isAdminOrManager()) {
return $this->redirectToRoute('app_crm');
}
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository(Customer::class);
if ($request->get('page')) {
$page = $request->get('page');
} else {
$page = 1;
}
$all = $repo->findAllDesc("/allContacts", $page - 1);
$xpages = $repo->findAllXpages("/allContacts", $page);
/** @var $contact Customer */
$this->repairContactPhones($all, $em);
/** @var $contact Customer */
return $this->render('crm/contacts.html.twig', [
'controller_name' => 'CrmController',
'myCustomers' => $all,
'image_picture' => $this->getImagePicture($this->get('session')->get('User')),
'xpages' => $xpages,
'logged' => $this->get('session')->get('User')
]);
}
/**
* @Route("/myContacts", name="myContacts")
*/
public function myContacts(Request $request): Response
{
if (!$this->get('session')->get('User')) {
return $this->redirectToRoute('app_crm');
}
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository(Customer::class);
if ($request->get('page')) {
$page = $request->get('page');
} else {
$page = 1;
}
$myContacts = $repo->findAllDesc("/myContacts", $page - 1, $this->get('session')->get('User'));
$xpages = $repo->findAllXpages("/myContacts", $page, $this->get('session')->get('User'));
$this->repairContactPhones($myContacts, $em);
return $this->render('crm/contacts.html.twig', [
'controller_name' => 'CrmController',
'myCustomers' => $myContacts,
'image_picture' => $this->getImagePicture($this->get('session')->get('User')),
'xpages' => $xpages,
'logged' => $this->get('session')->get('User')
]);
}
/**
* @Route("/searchContacts", name="searchContacts")
*/
public function searchContacts(Request $request): Response
{
if (!$this->get('session')->get('User')) {
return $this->redirectToRoute('app_crm');
}
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository(Customer::class);
$myContacts = $repo->search($request->get('text'), "/searchContacts",
$this->isAdminOrManager() ? null : $this->get('session')->get('User'));
$xpages = array();
$this->repairContactPhones($myContacts, $em);
return $this->render('crm/contacts.html.twig', [
'controller_name' => 'CrmController',
'myCustomers' => $myContacts,
'image_picture' => $this->getImagePicture($this->get('session')->get('User')),
'xpages' => $xpages,
'logged' => $this->get('session')->get('User')
]);
}
/**
* @Route("/newContact", name="newContact")
*/
public function newContact(): Response
{
if (!$this->get('session')->get('User')) {
return $this->redirectToRoute('app_crm');
}
$em = $this->getDoctrine()->getManager();
// $repo = $em->getRepository(Customer::class);
return $this->render('crm/newContact.html.twig', [
'controller_name' => 'CrmController',
'logged' => $this->get('session')->get('User'),
'image_picture' => $this->getImagePicture($this->get('session')->get('User')),
]);
}
/**
* @Route("/reserve", name="reserve")
*/
public function reserve(Request $request, \Swift_Mailer $mailer): Response
{
return $this->reserveCustomer($request->get('id'), $request->get('action'), $mailer);
}
public function reserveCustomer($id, $action, \Swift_Mailer $mailer, $message = null): Response
{
if (!$this->get('session')->get('User')) {
return $this->redirectToRoute('app_crm');
}
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository(Customer::class);
$repo2 = $em->getRepository(Agent::class);
/** @var $customer Customer */
$customer = $repo->findOneById($id);
$now = new DateTime('now');
$user = $this->get('session')->get('User');
if ($customer->getReservedTo() != null && $now < $customer->getReservedTo()) {
if ($customer->getAgent()->getId() != $this->get('session')->get('User')->getId()) {
if ($customer->getReservedTo()->getTimestamp() <= $now->getTimestamp()) {
$message = "przejmujesz_klienta_od_"
. $customer->getAgent()->getFirstname() . '_' . $customer->getAgent()->getLastname();
$emailToSend = (new \Swift_Message('Przejęty klient '))
->setFrom('crm@wronieruchomosci.pl')
->setTo($customer->getAgent()->getEmail())
->setBody('Użytkownik ' . $user->getFirstname() . ' ' . $user->getLastname() . ' ' . $user->getEmail() . " przejął Twojego klienta "
. $customer->getFirstname() . ' ' . $customer->getLastname() . ' ' . $customer->getEmail() . ' ' . $customer->getPhone());
$mailer->send($emailToSend);
$customer->setAddDate($now);
$customer->setAgent($this->get('session')->get('User'));
} else {
return $this->redirect($action . "?reserved_by=" . $customer->getAgent()->getFirstname() . '_' . $customer->getAgent()->getLastname());
}
}
}
$customer->setAddDate($now);
$customer->setAgent($repo2->findOneById($this->get('session')->get('User')->getId()));
$date = new DateTime('now');
$em = $this->getDoctrine()->getManager();
$repoParameter = $em->getRepository(Parameter::class);
/** @var Parameter $reservationHours */
$reservationHours = $repoParameter->findOneByParam('reservationHours');
if (!$reservationHours) {
$reservationHours = new Parameter();
$reservationHours->setParam("reservationHours");
$reservationHours->setVal("80");
$em->persist($reservationHours);
$em->flush();
}
$date->add(new DateInterval('PT' . $reservationHours->getVal() . 'H'));
$customer->setReservedTo($date);
$em->persist($customer);
$em->flush();
if ($message) {
$redirection = "/details?id=" . $customer->getId() . "&message=$message";
} else {
$redirection = $action . "?reserved_now=" . $customer->getReservedToFormatted();
}
return $this->redirect($redirection);
}
/**
* @Route("/call", name="call")
*/
public function call(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository(Customer::class);
/** @var $customer Customer */
$customer = $repo->findOneById($request->get('id'));
$customer->setStatus('do obdzwonki');
$em->persist($customer);
$em->flush();
return $this->redirect($request->get('action'));
}
/**
* @Route("/callMade", name="callMade")
*/
public function callMade(Request $request): Response
{
if (!$this->get('session')->get('User')) {
return $this->redirectToRoute('app_crm');
}
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository(Customer::class);
/** @var $customer Customer */
$customer = $repo->findOneById($request->get('id'));
$customer->setStatus('obdzwoniono');
$em->persist($customer);
$em->flush();
return $this->redirectToRoute('app_crm');
}
/**
* @Route("/details", name="details")
*/
public function details(Request $request): Response
{
if (!$this->get('session')->get('User')) {
return $this->redirectToRoute('app_crm');
}
/** @var $agent Agent */
$agent = $this->get('session')->get('User');
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository(Customer::class);
$repoComments = $em->getRepository(CustomerComment::class);
/** @var $customer Customer */
$customer = $repo->findOneById($request->get('id'));
$repoMail = $em->getRepository(Mail::class);
if (!$this->isAdminOrManager()) {
if ($customer->getAgent() && $agent->getId() != $customer->getAgent()->getId()) {
$customerAgentMails = $repoMail->findBy(array('customer' => $customer->getId(), 'agent' => $agent->getId()));
if (empty($customerAgentMails)) {
return $this->redirectToRoute('app_crm');
}
}
}
$customerMails = $repoMail->findByCustomer($request->get('id'));
$customerComments = $repoComments->findByCustomer($request->get('id'));
return $this->render('crm/customerDetails.html.twig', [
'controller_name' => 'CrmController',
'logged' => $this->get('session')->get('User'),
'customerComments' => $customerComments,
'image_picture' => $this->getImagePicture($this->get('session')->get('User')),
'isAdminOrManager' => $this->isAdminOrManager(),
'currentDate' => (new DateTime('now'))->format('Y-m-d'),
'customer' => $customer,
'emails' => $customerMails,
'detailsView' => true
]);
}
/**
* @Route("/updateDetails", name="updateDetails")
*/
public function updateDetails(Request $request): Response
{
if (!$this->get('session')->get('User')) {
return $this->redirectToRoute('app_crm');
}
if ($request->get('customertype') == null || $request->get('customertype') === '') {
return $this->redirectToRoute('details', array(
'id' => $request->get('id'),
));
}
if ($request->get('phone') == null || $request->get('phone') === '') {
if ($request->get('email') == null || $request->get('email') === '') {
return $this->redirectToRoute('details', array(
'id' => $request->get('id'),
));
}
}
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository(Customer::class);
$checkCustomer = $this->checkCustomer($request);
if ($checkCustomer != null) {
if ("klient_jest_juz_w_bazie" === $checkCustomer) {
/** @var $duplicate Customer */
$duplicate = $repo->findDuplicate($request->get('email'), $request->get('phone'), $request->get('link'));
if (intval($duplicate->getId()) != intval($request->get('id'))) {
return $this->redirect("/details?id=" . $request->get('id') . "&message=" . $checkCustomer);
}
}
//
// return $this->redirectToRoute('details', array(
// 'id' => $request->get('id'),
// ));
}
/** @var $customer Customer */
$customer = $repo->findOneById($request->get('id'));
$customer->setPhone($request->get('phone'));
if (empty($request->get('contractdate'))) {
$customer->setContractDate(null);
} else {
$customer->setContractDate(DateTime::createFromFormat('Y-m-d', $request->get('contractdate')));
}
if (empty($request->get('reservedto'))) {
$customer->setReservedTo(null);
} else {
$customer->setReservedTo(DateTime::createFromFormat('Y-m-d', $request->get('reservedto')));
}
$customer->setEmail($request->get('email'));
$customer->setLink($request->get('link'));
$customer->setFirstname($request->get('firstname'));
$customer->setLastname($request->get('lastname'));
$customer->setCustomerType($request->get('customertype'));
$customer->setStatus($request->get('status'));
$em->persist($customer);
$em->flush();
return $this->redirectToRoute('details', array(
'id' => $customer->getId(),
));
}
/**
* @Route("/addComment", name="addComment")
*/
public function addComment(Request $request): Response
{
if (!$this->get('session')->get('User')) {
return $this->redirectToRoute('app_crm');
}
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository(Customer::class);
$customer = $repo->findOneById($request->get('id'));
$comment = new CustomerComment();
$comment->setCustomer($customer);
$comment->setDate(DateTime::createFromFormat('Y-m-d', $request->get('actiondate')));
$comment->setCommentAddDate(new \DateTime());
$comment->setComment($request->get('customerComment'));
$em->persist($comment);
$em->flush();
return $this->redirectToRoute('details', array(
'id' => $customer->getId(),
));
}
private function checkCustomer(Request $request)
{
if ($request->get('customertype') == null || $request->get('customertype') === '') {
return "bledny_typ_klienta";
}
if ($request->get('phone') == null || $request->get('phone') === '') {
if ($request->get('email') == null || $request->get('email') === '') {
return "nie_podano_telefonu_ani_maila";
}
}
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository(Customer::class);
$duplicate = $repo->findDuplicate($request->get('email'), $request->get('phone'), $request->get('link'));
if ($duplicate) {
return "klient_jest_juz_w_bazie";
}
return null;
}
/**
* @Route("/newCustomer", name="newCustomer")
* @param Request $request
* @param \Swift_Mailer $mailer
* @return Response
*/
public function newCustomer(Request $request, \Swift_Mailer $mailer): Response
{
if (!$this->get('session')->get('User')) {
return $this->redirectToRoute('app_crm');
}
$em = $this->getDoctrine()->getManager();
$checkCustomer = $this->checkCustomer($request);
$customer = new Customer();
$message = null;
/** @var $user Agent */
$user = $this->get('session')->get('User');
if ($checkCustomer != null) {
if ("klient_jest_juz_w_bazie" === $checkCustomer) {
$repo = $em->getRepository(Customer::class);
/** @var $duplicate Customer */
$duplicate = $repo->findDuplicate($request->get('email'), $request->get('phone'), $request->get('link'));
$now = new DateTime('now');
if ($duplicate->getReservedTo() && $duplicate->getAgent()) {
if ($duplicate->getReservedTo()->getTimestamp() > $now->getTimestamp()
&& $duplicate->getAgent()->getId() !== $user->getId()) {
return $this->redirect("/newContact?message=" . $checkCustomer . "_zarezerwowany_przez_"
. $duplicate->getAgent()->getFirstname() . '_' . $duplicate->getAgent()->getLastname());
} else {
$customer = $duplicate;
$message = $checkCustomer . "_i_go_przejmujesz_od_"
. $duplicate->getAgent()->getFirstname() . '_' . $duplicate->getAgent()->getLastname();
$message2 = (new \Swift_Message('Przejęty klient '))
->setFrom('crm@wronieruchomosci.pl')
->setTo($duplicate->getAgent()->getEmail())
->setBody('Użytkownik ' . $user->getFirstname() . ' ' . $user->getLastname() . ' ' . $user->getEmail() . " przejął Twojego klienta " . $duplicate->getFirstname() . ' ' . $duplicate->getLastname() . ' ' . $duplicate->getEmail() . ' ' . $duplicate->getPhone());
$mailer->send($message2);
}
} else {
$customer = $duplicate;
$message = $checkCustomer . "_choc_nie_byl_do_nikogo_przypisany";
}
} else {
return $this->redirect("/newContact?message=" . $checkCustomer);
}
}
if ($request->get('phone')) {
$customer->setPhone($request->get('phone'));
}
if (!$customer->getAddDate()) {
$customer->setAddDate(new DateTime('now'));
}
if ($request->get('email')) {
$customer->setEmail($request->get('email'));
}
if ($request->get('link')) {
$customer->setLink($request->get('link'));
}
if ($request->get('firstname')) {
$customer->setFirstname($request->get('firstname'));
}
if ($request->get('lastname')) {
$customer->setLastname($request->get('lastname'));
}
$customer->setCustomerType($request->get('customertype'));
$customer->setStatus('nowy');
$em->persist($customer);
$em->flush();
if ($request->get('customerComment') != null && !empty($request->get('customerComment'))) {
$comment = new CustomerComment();
$comment->setCustomer($customer);
$comment->setDate(new \DateTime());
$comment->setCommentAddDate(new \DateTime());
$comment->setComment("" . $user->getFirstname() . ' ' . $user->getLastname() . " Dodano klienta: " . $request->get('customerComment'));
$em->persist($comment);
$em->flush();
} else {
$comment = new CustomerComment();
$comment->setCustomer($customer);
$comment->setDate(new \DateTime());
$comment->setCommentAddDate(new \DateTime());
$comment->setComment("" . $user->getFirstname() . ' ' . $user->getLastname() . " Dodano klienta");
$em->persist($comment);
$em->flush();
}
// $redirection = "/details?id=" . $customer->getId();
return $this->reserveCustomer($customer->getId(), "/", $mailer, $message);
// return $this->redirectToRoute('app_crm');
}
/**
* @param Agent $agent
* @return string
*/
private function getImagePicture(?Agent $agent): string
{
$imagePicture = $agent && $agent->getImageUrl() ? $agent->getImageUrl() : '';
return $imagePicture;
}
/**
* @param $existing
* @param $singleMessage
* @param Agent $agent
* @param $customers
* @param ObjectManager $em
* @param string $mailInfo
* @return integer
*/
private function saveSingleEmail($existing, $singleMessage, Agent $agent, $customers, ObjectManager $em): string
{
if (!$this->isExistingContaining($existing, $singleMessage->header->message_id, $singleMessage->header->uid)) {
$mailEntity = new Mail();
$mailEntity->setSubject($singleMessage->header->subject);//
$mailEntity->setSender($singleMessage->header->from);//
if (property_exists($singleMessage->header, 'to')) {
$mailEntity->setReceiver($singleMessage->header->to);//
} else {
$mailEntity->setReceiver($agent->getEmail());
}
$mailEntity->setReceiveDate($singleMessage->header->date);//
$mailEntity->setMessageId($singleMessage->header->message_id);//
$mailEntity->setMessageUid($singleMessage->header->uid);//.)
$mailEntity->setMessageText($singleMessage->message->text);
if ($mailEntity->getMessageText() == null) {
$mailEntity->setMessageText("");
}
//$mailEntity->setFullMail(serialize($singleMessage));
//$mailEntity->setMessageText($singleMail->attachments);
$mailEntity->setAgent($agent);
/** @var $singleCustomer Customer */
foreach ($customers as $singleCustomer) {
if ($singleCustomer->getEmail() && $singleCustomer->getEmail() !== ''
&& str_contains($mailEntity->getSender(), $singleCustomer->getEmail())) {
$mailEntity->setCustomer($singleCustomer);
break;
}
}
if ($mailEntity->getCustomer() == null) {
$senderTLC = strtolower($mailEntity->getSender());
/** @var $singleCustomer Customer */
foreach ($customers as $singleCustomer) {
$firstnameTLC = strtolower($singleCustomer->getFirstname());
$lastnameTLC = strtolower($singleCustomer->getLastname());
if ($firstnameTLC != null
&& $firstnameTLC !== ''
&& str_contains($senderTLC, $firstnameTLC)
&& $lastnameTLC != null
&& $lastnameTLC !== ''
&& str_contains($senderTLC, $lastnameTLC)) {
$mailEntity->setCustomer($singleCustomer);
break;
}
}
}
$em->persist($mailEntity);
if ($singleMessage->attachments) {
foreach ($singleMessage->attachments as $attachment) {
$name = $attachment->name;
$contents = base64_decode($attachment->body);
$mailAttachment = new MailAttachment();
$mailAttachment->setName($attachment->name);
$mailAttachment->setBody('');
$mailAttachment->setMail($mailEntity);
$em->persist($mailAttachment);
$em->flush();
if (!file_exists('attachment')) {
mkdir("attachment", 0777, true);
}
if (!file_exists("attachment/" . $mailAttachment->getId())) {
mkdir("attachment/" . $mailAttachment->getId(), 0777, true);
}
if ($name == null || str_starts_with($name, "=?")) {
$name = "" . $mailAttachment->getId();
}
file_put_contents("attachment/" . $mailAttachment->getId() . "/" . $name, $contents);
$mailAttachment->setBody("/attachment/" . $mailAttachment->getId() . "/" . $name);
$em->persist($mailAttachment);
$em->flush();
}
}
return 1;
}
return 0;
}
/**
* @param $myContacts
* @param ObjectManager $em
* @return void
*/
public function repairContactPhones($myContacts, ObjectManager $em): void
{
/** @var $contact Customer */
foreach ($myContacts as $contact) {
if (strpos($contact->getPhone(), ' ') !== false) {
$contact->setPhone(str_replace(' ', '', $contact->getPhone()));
$em->persist($contact);
$em->flush();
}
}
}
}