vendor/uvdesk/core-framework/Services/EmailService.php line 32

Open in your IDE?
  1. <?php
  2. namespace Webkul\UVDesk\CoreFrameworkBundle\Services;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Symfony\Component\DependencyInjection\ContainerInterface;
  5. use Symfony\Component\HttpFoundation\RequestStack;
  6. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  7. use Symfony\Component\Mailer\Transport;
  8. use Symfony\Component\Mime\Email;
  9. use Symfony\Component\Mime\Address;
  10. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  11. use Webkul\UVDesk\CoreFrameworkBundle\Entity\EmailTemplates;
  12. use Webkul\UVDesk\CoreFrameworkBundle\Entity\MicrosoftApp;
  13. use Webkul\UVDesk\CoreFrameworkBundle\Entity\MicrosoftAccount;
  14. use Webkul\UVDesk\CoreFrameworkBundle\Entity\Ticket;
  15. use Webkul\UVDesk\CoreFrameworkBundle\Entity\User;
  16. use Webkul\UVDesk\CoreFrameworkBundle\Entity\Website;
  17. use Webkul\UVDesk\CoreFrameworkBundle\Utils\Microsoft\Graph as MicrosoftGraph;
  18. use Webkul\UVDesk\CoreFrameworkBundle\Utils\TokenGenerator;
  19. use Webkul\UVDesk\MailboxBundle\Services\MailboxService;
  20. use Webkul\UVDesk\MailboxBundle\Utils\SMTP\Transport\AppTransportConfigurationInterface;
  21. use Webkul\UVDesk\CoreFrameworkBundle\Services\MicrosoftIntegration;
  22. class EmailService
  23. {
  24.     private $request;
  25.     private $container;
  26.     private $entityManager;
  27.     private $session;
  28.     private $mailer;
  29.     public function __construct(ContainerInterface $containerRequestStack $requestEntityManagerInterface $entityManagerSessionInterface $sessionMailboxService $mailboxServiceMicrosoftIntegration $microsoftIntegration)
  30.     {
  31.         $this->request $request;
  32.         $this->container $container;
  33.         $this->entityManager $entityManager;
  34.         $this->session $session;
  35.         $this->mailboxService $mailboxService;
  36.         $this->microsoftIntegration $microsoftIntegration;
  37.     }
  38.     public function trans($text)
  39.     {
  40.         return $this->container->get('translator')->trans($text);
  41.     }
  42.     public function getEmailPlaceHolders($params)
  43.     {
  44.         $placeHolders = [];
  45.         $allEmailPlaceholders = [];
  46.         $template is_array($params) ? ($params['match'] . 'Note') : (!empty($params) ? $params 'template');
  47.         if ($template == 'template') {
  48.             $placeHolders = [
  49.                 'ticket' => [
  50.                     'id' => [
  51.                         'title' => $this->trans('Ticket Id'),
  52.                         'info' => $this->trans('ticket.id.placeHolders.info'),
  53.                     ],
  54.                     'subject' => [
  55.                         'title' => $this->trans('Ticket Subject'),
  56.                         'info' => $this->trans('ticket.subject.placeHolders.info'),
  57.                     ],
  58.                     'message' => [
  59.                         'title' => $this->trans('Ticket Message'),
  60.                         'info' => $this->trans('ticket.message.placeHolders.info'),
  61.                     ],
  62.                     'attachments' => [
  63.                         'title' => $this->trans('Ticket Attachments'),
  64.                         'info' => $this->trans('ticket.attachments.placeHolders.info'),
  65.                     ],
  66.                     'threadMessage' => [
  67.                         'title' => $this->trans('Ticket Thread Message'),
  68.                         'info' => $this->trans('ticket.threadMessage.placeHolders.info'),
  69.                     ],
  70.                     'tags' => [
  71.                         'title' => $this->trans('Ticket Tags'),
  72.                         'info' => $this->trans('ticket.tags.placeHolders.info'),
  73.                     ],
  74.                     'source' => [
  75.                         'title' => $this->trans('Ticket Source'),
  76.                         'info' => $this->trans('ticket.source.placeHolders.info'),
  77.                     ],
  78.                     'status' => [
  79.                         'title' => $this->trans('Ticket Status'),
  80.                         'info' => $this->trans('ticket.status.placeHolders.info'),
  81.                     ],
  82.                     'priority' => [
  83.                         'title' => $this->trans('Ticket Priority'),
  84.                         'info' => $this->trans('ticket.priority.placeHolders.info'),
  85.                     ],
  86.                     'group' => [
  87.                         'title' => $this->trans('Ticket Group'),
  88.                         'info' => $this->trans('ticket.group.placeHolders.info'),
  89.                     ],
  90.                     'team' => [
  91.                         'title' => $this->trans('Ticket Team'),
  92.                         'info' => $this->trans('ticket.team.placeHolders.info'),
  93.                     ],
  94.                     'customerName' => [
  95.                         'title' => $this->trans('Ticket Customer Name'),
  96.                         'info' => $this->trans('ticket.customerName.placeHolders.info'),
  97.                     ],
  98.                     'customerEmail' => [
  99.                         'title' => $this->trans('Ticket Customer Email'),
  100.                         'info' => $this->trans('ticket.customerEmail.placeHolders.info'),
  101.                     ],
  102.                     'agentName' => [
  103.                         'title' => $this->trans('Ticket Agent Name'),
  104.                         'info' => $this->trans('ticket.agentName.placeHolders.info'),
  105.                     ],
  106.                     'agentEmail' => [
  107.                         'title' => $this->trans('Ticket Agent Email'),
  108.                         'info' => $this->trans('ticket.agentEmail.placeHolders.info'),
  109.                     ],
  110.                     'agentLink' => [
  111.                         'title' => $this->trans('Ticket Agent Link'),
  112.                         'info' => $this->trans('ticket.link.placeHolders.info'),
  113.                     ],
  114.                     'customerLink' => [
  115.                         'title' => $this->trans('Ticket Customer Link'),
  116.                         'info' => $this->trans('ticket.link.placeHolders.info'),
  117.                     ],
  118.                     'collaboratorName' => [
  119.                         'title' => $this->trans('Last Collaborator Name'),
  120.                         'info' => $this->trans('ticket.collaborator.name.placeHolders.info'),
  121.                     ],
  122.                     'collaboratorEmail' => [
  123.                         'title' => $this->trans('Last Collaborator Email'),
  124.                         'info' => $this->trans('ticket.collaborator.email.placeHolders.info'),
  125.                     ],
  126.                 ],
  127.                 'user'  => [
  128.                     'userName' => [
  129.                         'title' => $this->trans('Agent/ Customer Name'),
  130.                         'info' => $this->trans('user.name.info'),
  131.                     ],
  132.                     'userEmail' => [
  133.                         'title' => $this->trans('Email'),
  134.                         'info' => $this->trans('user.email.info'),
  135.                     ],
  136.                     'accountValidationLink' => [
  137.                         'title' => $this->trans('Account Validation Link'),
  138.                         'info' => $this->trans('user.account.validate.link.info'),
  139.                     ],
  140.                     'forgotPasswordLink' => [
  141.                         'title' => $this->trans('Password Forgot Link'),
  142.                         'info' => $this->trans('user.password.forgot.link.info'),
  143.                     ],
  144.                 ],
  145.                 'global' => [
  146.                     'companyName' => [
  147.                         'title' => $this->trans('Company Name'),
  148.                         'info' => $this->trans('global.companyName'),
  149.                     ],
  150.                     'companyLogo' => [
  151.                         'title' => $this->trans('Company Logo'),
  152.                         'info' => $this->trans('global.companyLogo'),
  153.                     ],
  154.                     'companyUrl' => [
  155.                         'title' => $this->trans('Company URL'),
  156.                         'info' => $this->trans('global.companyUrl'),
  157.                     ],
  158.                 ],
  159.             ];
  160.         } elseif ($template == 'savedReply') {
  161.             $placeHolders = [
  162.                 'ticket' => [
  163.                     'id' => [
  164.                         'title' => $this->trans('Ticket Id'),
  165.                         'info' => $this->trans('ticket.id.placeHolders.info'),
  166.                     ],
  167.                     'subject' => [
  168.                         'title' => $this->trans('Ticket Subject'),
  169.                         'info' => $this->trans('ticket.subject.placeHolders.info'),
  170.                     ],
  171.                     'status' => [
  172.                         'title' => $this->trans('Ticket Status'),
  173.                         'info' => $this->trans('ticket.status.placeHolders.info'),
  174.                     ],
  175.                     'priority' => [
  176.                         'title' => $this->trans('Ticket Priority'),
  177.                         'info' => $this->trans('ticket.priority.placeHolders.info'),
  178.                     ],
  179.                     'group' => [
  180.                         'title' => $this->trans('Ticket Group'),
  181.                         'info' => $this->trans('ticket.group.placeHolders.info'),
  182.                     ],
  183.                     'team' => [
  184.                         'title' => $this->trans('Ticket Team'),
  185.                         'info' => $this->trans('ticket.team.placeHolders.info'),
  186.                     ],
  187.                     'customerName' => [
  188.                         'title' => $this->trans('Ticket Customer Name'),
  189.                         'info' => $this->trans('ticket.customerName.placeHolders.info'),
  190.                     ],
  191.                     'customerEmail' => [
  192.                         'title' => $this->trans('Ticket Customer Email'),
  193.                         'info' => $this->trans('ticket.customerEmail.placeHolders.info'),
  194.                     ],
  195.                     'agentName' => [
  196.                         'title' => $this->trans('Ticket Agent Name'),
  197.                         'info' => $this->trans('ticket.agentName.placeHolders.info'),
  198.                     ],
  199.                     'agentEmail' => [
  200.                         'title' => $this->trans('Ticket Agent Email'),
  201.                         'info' => $this->trans('ticket.agentEmail.placeHolders.info'),
  202.                     ],
  203.                     'link' => [
  204.                         'title' => $this->trans('Ticket Link'),
  205.                         'info' => $this->trans('ticket.link.placeHolders.info'),
  206.                     ],
  207.                 ],
  208.             ];
  209.         } elseif ($template == 'ticketNote') {
  210.             $placeHolders = [
  211.                 'type' => [
  212.                     'previousType' => [
  213.                         'title' => $this->trans('Previous Type'),
  214.                         'info' => $this->trans('type.previous.placeHolders.info'),
  215.                     ],
  216.                     'updatedType' => [
  217.                         'title' => $this->trans('Updated Type'),
  218.                         'info' => $this->trans('type.updated.placeHolders.info'),
  219.                     ],
  220.                 ],
  221.                 'status' => [
  222.                     'previousStatus' => [
  223.                         'title' => $this->trans('Previous Status'),
  224.                         'info' => $this->trans('status.previous.placeHolders.info'),
  225.                     ],
  226.                     'updatedStatus' => [
  227.                         'title' => $this->trans('Updated Status'),
  228.                         'info' => $this->trans('status.updated.placeHolders.info'),
  229.                     ],
  230.                 ],
  231.                 'group' => [
  232.                     'previousGroup' => [
  233.                         'title' => $this->trans('Previous Group'),
  234.                         'info' => $this->trans('group.previous.placeHolders.info'),
  235.                     ],
  236.                     'updatedGroup' => [
  237.                         'title' => $this->trans('Updated Group'),
  238.                         'info' => $this->trans('group.updated.placeHolders.info'),
  239.                     ],
  240.                 ],
  241.                 'team' => [
  242.                     'previousTeam' => [
  243.                         'title' => $this->trans('Previous Team'),
  244.                         'info' => $this->trans('team.previous.placeHolders.info'),
  245.                     ],
  246.                     'updatedTeam' => [
  247.                         'title' => $this->trans('Updated Team'),
  248.                         'info' => $this->trans('team.updated.placeHolders.info'),
  249.                     ],
  250.                 ],
  251.                 'priority' => [
  252.                     'previousPriority' => [
  253.                         'title' => $this->trans('Previous Priority'),
  254.                         'info' => $this->trans('priority.previous.placeHolders.info'),
  255.                     ],
  256.                     'updatedPriority' => [
  257.                         'title' => $this->trans('Updated Priority'),
  258.                         'info' => $this->trans('priority.updated.placeHolders.info'),
  259.                     ],
  260.                 ],
  261.                 'agent' => [
  262.                     'previousAgent' => [
  263.                         'title' => $this->trans('Previous Agent'),
  264.                         'info' => $this->trans('agent.previous.placeHolders.info'),
  265.                     ],
  266.                     'updatedAgent' => [
  267.                         'title' => $this->trans('Updated Agent'),
  268.                         'info' => $this->trans('agent.updated.placeHolders.info'),
  269.                     ],
  270.                     'responsePerformingAgent' => [
  271.                         'title' => $this->trans('Response Performing Agent'),
  272.                         'info' => $this->trans('agent.response.placeHolders.info'),
  273.                     ],
  274.                 ],
  275.             ];
  276.         } elseif($template == 'manualNote') {
  277.             $placeHolders = [
  278.                 'ticket' => [
  279.                     'id' => [
  280.                         'title' => $this->trans('Ticket Id'),
  281.                         'info' => $this->trans('ticket.id.placeHolders.info'),
  282.                     ],
  283.                     'subject' => [
  284.                         'title' => $this->trans('Ticket Subject'),
  285.                         'info' => $this->trans('ticket.subject.placeHolders.info'),
  286.                     ],
  287.                     'status' => [
  288.                         'title' => $this->trans('Ticket Status'),
  289.                         'info' => $this->trans('ticket.status.placeHolders.info'),
  290.                     ],
  291.                     'priority' => [
  292.                         'title' => $this->trans('Ticket Priority'),
  293.                         'info' => $this->trans('ticket.priority.placeHolders.info'),
  294.                     ],
  295.                     'group' => [
  296.                         'title' => $this->trans('Ticket Group'),
  297.                         'info' => $this->trans('ticket.group.placeHolders.info'),
  298.                     ],
  299.                     'team' => [
  300.                         'title' => $this->trans('Ticket Team'),
  301.                         'info' => $this->trans('ticket.team.placeHolders.info'),
  302.                     ],
  303.                     'customerName' => [
  304.                         'title' => $this->trans('Ticket Customer Name'),
  305.                         'info' => $this->trans('ticket.customerName.placeHolders.info'),
  306.                     ],
  307.                     'customerEmail' => [
  308.                         'title' => $this->trans('Ticket Customer Email'),
  309.                         'info' => $this->trans('ticket.customerEmail.placeHolders.info'),
  310.                     ],
  311.                     'agentName' => [
  312.                         'title' => $this->trans('Ticket Agent Name'),
  313.                         'info' => $this->trans('ticket.agentName.placeHolders.info'),
  314.                     ],
  315.                     'agentEmail' => [
  316.                         'title' => $this->trans('Ticket Agent Email'),
  317.                         'info' => $this->trans('ticket.agentEmail.placeHolders.info'),
  318.                     ],
  319.                 ],
  320.             ];
  321.         }
  322.         return $placeHolders;
  323.     }
  324.     public function getEmailPlaceholderValues(User $user$userType 'member')
  325.     {
  326.         if (null == $user->getVerificationCode()) {
  327.             // Set user verification code
  328.             $user->setVerificationCode(TokenGenerator::generateToken());
  329.             $this->entityManager->persist($user);
  330.             $this->entityManager->flush();
  331.         }
  332.         $router $this->container->get('router');
  333.         $helpdeskWebsite $this->entityManager->getRepository(Website::class)->findOneByCode('helpdesk');
  334.         // Link to company knowledgebase
  335.         if (false == array_key_exists('UVDeskSupportCenterBundle'$this->container->getParameter('kernel.bundles'))) {
  336.             $companyURL $this->container->getParameter('uvdesk.site_url');
  337.         } else {
  338.             $companyURL $router->generate('helpdesk_knowledgebase', [], UrlGeneratorInterface::ABSOLUTE_URL);
  339.         }
  340.         // Resolve path to helpdesk brand image
  341.         $companyLogoURL sprintf('http://%s%s'$this->container->getParameter('uvdesk.site_url'), '/bundles/uvdeskcoreframework/images/uv-avatar-uvdesk.png');
  342.         $helpdeskKnowledgebaseWebsite $this->entityManager->getRepository(Website::class)->findOneByCode('knowledgebase');
  343.         if (!empty($helpdeskKnowledgebaseWebsite) && null != $helpdeskKnowledgebaseWebsite->getLogo()) {
  344.             $companyLogoURL sprintf('http://%s%s'$this->container->getParameter('uvdesk.site_url'), $helpdeskKnowledgebaseWebsite->getLogo());
  345.         }
  346.         
  347.         // Link to update account login credentials
  348.         $updateCredentialsURL $router->generate'helpdesk_update_account_credentials', [
  349.             'email' => $user->getEmail(),
  350.             'verificationCode' => $user->getVerificationCode(),
  351.         ], UrlGeneratorInterface::ABSOLUTE_URL);
  352.         $placeholderParams = [
  353.             'user.userName' => $user->getFullName(),
  354.             'user.userEmail' => $user->getEmail(),
  355.             'user.assignUserEmail' => $user->getEmail(),
  356.             'user.forgotPasswordLink' => "<a href='$updateCredentialsURL'>$updateCredentialsURL</a>",
  357.             'user.accountValidationLink' => "<a href='$updateCredentialsURL'>$updateCredentialsURL</a>",
  358.             'global.companyName' => $helpdeskWebsite->getName(),
  359.             'global.companyLogo' => "<img style='max-height:60px' src='$companyLogoURL'/>",
  360.             'global.companyUrl' => "<a href='$companyURL'>$companyURL</a>",
  361.         ];
  362.         
  363.         return $placeholderParams;
  364.     }
  365.     public function getTicketPlaceholderValues(Ticket $ticket$type "")
  366.     {
  367.         $supportTeam $ticket->getSupportTeam();
  368.         $supportGroup $ticket->getSupportGroup();
  369.         $supportTags array_map(function ($supportTag) { return $supportTag->getName(); }, $ticket->getSupportTags()->toArray());
  370.         
  371.         $router $this->container->get('router');
  372.         $helpdeskWebsite $this->entityManager->getRepository(Website::class)->findOneByCode('helpdesk');
  373.         
  374.         // Resolve path to helpdesk brand image
  375.         $companyLogoURL sprintf('http://%s%s'$this->container->getParameter('uvdesk.site_url'), '/bundles/uvdeskcoreframework/images/uv-avatar-uvdesk.png');
  376.         $helpdeskKnowledgebaseWebsite $this->entityManager->getRepository(Website::class)->findOneByCode('knowledgebase');
  377.         if (!empty($helpdeskKnowledgebaseWebsite) && null != $helpdeskKnowledgebaseWebsite->getLogo()) {
  378.             $companyLogoURL sprintf('http://%s%s'$this->container->getParameter('uvdesk.site_url'), $helpdeskKnowledgebaseWebsite->getLogo());
  379.         }
  380.         
  381.         // Link to company knowledgebase
  382.         if (false == array_key_exists('UVDeskSupportCenterBundle'$this->container->getParameter('kernel.bundles'))) {
  383.             $companyURL $this->container->getParameter('uvdesk.site_url');
  384.         } else {
  385.             $companyURL $router->generate('helpdesk_knowledgebase', [], UrlGeneratorInterface::ABSOLUTE_URL);
  386.         }
  387.         $customerPartialDetails $ticket->getCustomer()->getCustomerInstance()->getPartialDetails();
  388.         $agentPartialDetails $ticket->getAgent() ? $ticket->getAgent()->getAgentInstance()->getPartialDetails() : null;
  389.         //Ticket Url and create ticket url for agent
  390.         $viewTicketURLAgent $router->generate('helpdesk_member_ticket', [
  391.             'ticketId' => $ticket->getId(),
  392.         ], UrlGeneratorInterface::ABSOLUTE_URL);
  393.         $generateTicketURLAgent $router->generate('helpdesk_member_create_ticket', [], UrlGeneratorInterface::ABSOLUTE_URL);
  394.         if (false != array_key_exists('UVDeskSupportCenterBundle'$this->container->getParameter('kernel.bundles'))) {
  395.                 $viewTicketURL $router->generate('helpdesk_customer_ticket', [
  396.                     'id' => $ticket->getId(),
  397.                 ], UrlGeneratorInterface::ABSOLUTE_URL);
  398.     
  399.                 $generateTicketURLCustomer $router->generate('helpdesk_customer_create_ticket', [], UrlGeneratorInterface::ABSOLUTE_URL);
  400.         } else {
  401.             $viewTicketURL '';
  402.             $generateTicketURLCustomer '';
  403.         }
  404.         $placeholderParams = [
  405.             'ticket.id' => $ticket->getId(),
  406.             'ticket.subject' => $ticket->getSubject(),
  407.             'ticket.message' => count($ticket->getThreads()) > preg_replace("/<img[^>]+\>/i"""$ticket->getThreads()->get(0)->getMessage()) : preg_replace("/<img[^>]+\>/i"""$this->container->get('ticket.service')->getInitialThread($ticket->getId())->getMessage()),
  408.             'ticket.threadMessage' => $this->threadMessage($ticket),
  409.             'ticket.tags' => implode(','$supportTags),
  410.             'ticket.source' => ucfirst($ticket->getSource()),
  411.             'ticket.status' => $ticket->getStatus()->getDescription(),
  412.             'ticket.priority' => $ticket->getPriority()->getDescription(),
  413.             'ticket.team' => $supportTeam $supportTeam->getName() : '',
  414.             'ticket.group' => $supportGroup $supportGroup->getName() : '',
  415.             'ticket.customerName' => $customerPartialDetails['name'],
  416.             'ticket.customerEmail' => $customerPartialDetails['email'],
  417.             'ticket.agentName' => !empty($agentPartialDetails) ? $agentPartialDetails['name'] : '',
  418.             'ticket.agentEmail' => !empty($agentPartialDetails) ? $agentPartialDetails['email'] : '',
  419.             'ticket.attachments' => '',
  420.             'ticket.collaboratorName' => $this->getCollaboratorName($ticket),
  421.             'ticket.collaboratorEmail' => $this->getCollaboratorEmail($ticket),
  422.             'ticket.agentLink' => sprintf("<a href='%s'>#%s</a>"$viewTicketURLAgent$ticket->getId()),
  423.             'ticket.ticketGenerateUrlAgent' => sprintf("<a href='%s'>click here</a>"$generateTicketURLAgent),
  424.             'ticket.customerLink' => sprintf("<a href='%s'>#%s</a>"$viewTicketURL$ticket->getId()),
  425.             'ticket.ticketGenerateUrlCustomer' => sprintf("<a href='%s'>click here</a>"$generateTicketURLCustomer),
  426.             'global.companyName' => $helpdeskWebsite->getName(),
  427.             'global.companyLogo' => "<img style='max-height:60px' src='$companyLogoURL'/>",
  428.             'global.companyUrl' => "<a href='$companyURL'>$companyURL</a>",
  429.         ];
  430.         return $placeholderParams;
  431.     }
  432.     public function threadMessage($ticket)
  433.     {
  434.         $message null;
  435.         if (isset($ticket->createdThread) && $ticket->createdThread->getThreadType() != "note") {
  436.             return preg_replace("/<img[^>]+\>/i"""$ticket->createdThread->getMessage());
  437.         } elseif (isset($ticket->currentThread) && $ticket->currentThread->getThreadType() != "note") {
  438.             return  preg_replace("/<img[^>]+\>/i"""$ticket->currentThread->getMessage());
  439.         } else {
  440.             $messages $ticket->getThreads();
  441.             for ($i count($messages) - $i >= 0  $i--) { 
  442.                 if (isset($messages[$i]) && $messages[$i]->getThreadType() != "note") {
  443.                     return preg_replace("/<img[^>]+\>/i"""$messages[$i]->getMessage());
  444.                 }
  445.             }
  446.         }
  447.         return "";
  448.     }
  449.     public function processEmailSubject($subject, array $emailPlaceholders = [])
  450.     {
  451.         foreach ($emailPlaceholders as $var => $value) {
  452.             $subject strtr($subject, ["{%$var%}" => $value"{% $var %}" => $value]);
  453.         }
  454.         
  455.         return $subject;
  456.     }
  457.     public function processEmailContent($content, array $emailPlaceholders = [], $isSavedReply false)
  458.     {
  459.         $twigTemplatingEngine $this->container->get('twig');
  460.         $baseEmailTemplate $this->container->getParameter('uvdesk.default.templates.email');
  461.         foreach ($emailPlaceholders as $var => $value) {
  462.             $content strtr($content, ["{%$var%}" => $value"{% $var %}" => $value]);
  463.         }
  464.         $content $isSavedReply stripslashes($content) : htmlspecialchars_decode(preg_replace(['#&lt;script&gt;#''#&lt;/script&gt;#'], ['&amp;lt;script&amp;gt;''&amp;lt;/script&amp;gt;'], $content));
  465.         return $twigTemplatingEngine->render($baseEmailTemplate, ['message' => $content]);
  466.     }
  467.     public function sendMail($subject$content$recipient, array $headers = [], $mailboxEmail null, array $attachments = [], $cc = [], $bcc = [])
  468.     {
  469.         // Send emails only if any mailer configuration is available
  470.         $mailer null;
  471.         $mailboxConfigurations $this->mailboxService->parseMailboxConfigurations();
  472.         if (empty($mailboxEmail)) {
  473.             $mailbox $mailboxConfigurations->getDefaultMailbox();
  474.             if (empty($mailbox)) {
  475.                 return;
  476.             } else if (false == $mailbox->getIsEnabled()) {
  477.                 return;
  478.             }
  479.             $mailboxSmtpConfiguration $mailbox->getSmtpConfiguration();
  480.             // Send email on behalf of support helpdesk
  481.             $supportEmailName $mailbox->getName();
  482.             $supportEmail $mailboxSmtpConfiguration->getUsername();
  483.         } else {
  484.             // Register automations conditionally if AutomationBundle has been added as an dependency.
  485.             if (!array_key_exists('UVDeskMailboxBundle'$this->container->getParameter('kernel.bundles'))) {
  486.                 return;
  487.             }
  488.             $mailbox $mailboxConfigurations->getOutgoingMailboxByEmailAddress($mailboxEmail);
  489.             // Send email on behalf of configured mailbox
  490.             if (empty($mailbox)) {
  491.                 // @TODO: Log exception - Mailbox not found
  492.                 $this->session->getFlashBag()->add('warning'$this->container->get('translator')->trans("No mailbox was found for email address '$mailboxEmail'. Please review your settings and try again later."));
  493.                 
  494.                 return;
  495.             } else if (false == $mailbox->getIsEnabled()) {
  496.                 // @TODO: Log mailbox disabled notice
  497.                 $this->session->getFlashBag()->add('warning'$this->container->get('translator')->trans("The selected mailbox for email address '$mailboxEmail' is currently disabled. Please review your settings and try again later."));
  498.     
  499.                 return;
  500.             }
  501.             
  502.             $mailboxSmtpConfiguration $mailbox->getSmtpConfiguration();
  503.             $supportEmailName $mailbox->getName();
  504.             $supportEmail $mailboxSmtpConfiguration->getUsername();
  505.         }
  506.         // Prepare email
  507.         $email = new Email();
  508.         $email
  509.             ->from(new Address($supportEmail$supportEmailName))
  510.             ->subject($subject)
  511.             ->text(strip_tags($content))
  512.             ->html($content)
  513.         ;
  514.         // Manage email recipients
  515.         if (!empty($recipient)) {
  516.             $email->to($recipient);
  517.         }
  518.         foreach ($cc as $emailAddress) {
  519.             $email->addCc($emailAddress);
  520.         }
  521.         foreach ($bcc as $emailAddress) {
  522.             $email->addBcc($emailAddress);
  523.         }
  524.         // Manage email attachments
  525.         foreach ($attachments as $attachment) {
  526.             if (!empty($attachment['path']) && !empty($attachment['name'])) {
  527.                 $email->attachFromPath($attachment['path'], $attachment['name']);
  528.                 
  529.                 continue;
  530.             } 
  531.             $email->attachFromPath($attachment);
  532.         }
  533.         // Configure email headers
  534.         $emailHeaders $email->getHeaders();
  535.         foreach ($headers as $name => $value) {
  536.             if (is_array($value) && !empty($value['messageId'])) {
  537.                 $value $value['messageId'];
  538.             }
  539.             $emailHeaders->addTextHeader($name$value);
  540.         }
  541.         // Send email
  542.         $messageId null;
  543.         try {
  544.             if ($mailboxSmtpConfiguration instanceof AppTransportConfigurationInterface) {
  545.                 $microsoftApp $this->entityManager->getRepository(MicrosoftApp::class)->findOneByClientId($mailboxSmtpConfiguration->getClient());
  546.                 if (empty($microsoftApp)) {
  547.                     $this->session->getFlashBag()->add('warning'$this->container->get('translator')->trans('An unexpected error occurred while trying to send email. Please try again later.'));
  548.                     $this->session->getFlashBag()->add('warning'$this->container->get('translator')->trans('No associated microsoft apps were found for configured mailbox.'));
  549.                     return null;
  550.                 }
  551.                 $microsoftAccount $this->entityManager->getRepository(MicrosoftAccount::class)->findOneBy([
  552.                     'email' => $mailboxSmtpConfiguration->getUsername(), 
  553.                     'microsoftApp' => $microsoftApp
  554.                 ]);
  555.                 if (empty($microsoftAccount)) {
  556.                     $this->session->getFlashBag()->add('warning'$this->container->get('translator')->trans('An unexpected error occurred while trying to send email. Please try again later.'));
  557.                     $this->session->getFlashBag()->add('warning'$this->container->get('translator')->trans('No associated microsoft account was found for configured mailbox.'));
  558.                     return null;
  559.                 }
  560.                 $credentials json_decode($microsoftAccount->getCredentials(), true);
  561.                 $emailParams = [
  562.                     'subject' => $subject
  563.                     'body' => [
  564.                         'contentType' => 'HTML'
  565.                         'content' => $content
  566.                     ], 
  567.                     'toRecipients' => [
  568.                         [
  569.                             'emailAddress' => [
  570.                                 'address' => $recipient
  571.                             ], 
  572.                         ], 
  573.                     ], 
  574.                 ];
  575.                 foreach ($headers as $name => $value) {
  576.                     if ($name == 'X-Transport') {
  577.                         continue;
  578.                     }
  579.                     if (is_array($value)) {
  580.                         $value $value['messageId'];
  581.                     }
  582.                     $emailParams['internetMessageHeaders'][] = [
  583.                         'name' => "x-$name"
  584.                         'value' => $value
  585.                     ];
  586.                 }
  587.                 $graphResponse MicrosoftGraph\Me::sendMail($credentials['access_token'], $emailParams);
  588.                 // Refresh access token if expired
  589.                 if (!empty($graphResponse['error'])) {
  590.                     if (!empty($graphResponse['error']['code']) && $graphResponse['error']['code'] == 'InvalidAuthenticationToken') {
  591.                         $tokenResponse $this->microsoftIntegration->refreshAccessToken($microsoftApp$credentials['refresh_token']);
  592.                         if (!empty($tokenResponse['access_token'])) {
  593.                             $microsoftAccount
  594.                                 ->setCredentials(json_encode($tokenResponse))
  595.                             ;
  596.                             
  597.                             $this->entityManager->persist($microsoftAccount);
  598.                             $this->entityManager->flush();
  599.                             
  600.                             $credentials json_decode($microsoftAccount->getCredentials(), true);
  601.                             $graphResponse MicrosoftGraph\Me::sendMail($credentials['access_token'], $emailParams);
  602.                         }
  603.                     }
  604.                 }
  605.             } else {
  606.                 $dsn strtr("smtp://{email}:{password}@{host}:{port}", [
  607.                     "{email}" => $mailboxSmtpConfiguration->getUsername(), 
  608.                     "{password}" => $mailboxSmtpConfiguration->getPassword(), 
  609.                     "{host}" => $mailboxSmtpConfiguration->getHost(), 
  610.                     "{port}" => $mailboxSmtpConfiguration->getPort(), 
  611.                 ]);
  612.                 if (false == $mailbox->getIsStrictModeEnabled()) {
  613.                     $dsn .= "?verify_peer=0";
  614.                 }
  615.                 $transport Transport::fromDsn($dsn);
  616.                 $sentMessage $transport->send($email);
  617.                 if (!empty($sentMessage)) {
  618.                     $messageId $sentMessage->getMessageId();
  619.                 }
  620.             }
  621.         } catch (\Exception $e) {
  622.             // @TODO: Log exception
  623.             $this->session->getFlashBag()->add('warning'$this->container->get('translator')->trans('An unexpected error occurred while trying to send email. Please try again later.'));
  624.             $this->session->getFlashBag()->add('warning'$this->container->get('translator')->trans($e->getMessage()));
  625.         }
  626.         return !empty($messageId) ? "<$messageId>" null;
  627.     }
  628.     public function getCollaboratorName($ticket)
  629.     {
  630.         $name null;
  631.         $ticket->lastCollaborator null;
  632.         if ($ticket->getCollaborators() != null && count($ticket->getCollaborators()) > 0) {
  633.             try {
  634.                 $ticket->lastCollaborator $ticket->getCollaborators()[ -count($ticket->getCollaborators()) ];
  635.             } catch(\Exception $e) {
  636.             }
  637.         }
  638.         if ($ticket->lastCollaborator != null) {
  639.             $name =  $ticket->lastCollaborator->getFirstName()." ".$ticket->lastCollaborator->getLastName();
  640.         }
  641.         
  642.         return $name != null $name '';
  643.     }
  644.     public function getCollaboratorEmail($ticket)
  645.     {
  646.         $email null;
  647.         $ticket->lastCollaborator null;
  648.         if ($ticket->getCollaborators() != null && count($ticket->getCollaborators()) > 0) {
  649.             try {
  650.                 $ticket->lastCollaborator $ticket->getCollaborators()[ -count($ticket->getCollaborators()) ];
  651.             } catch(\Exception $e) {
  652.             }
  653.         }
  654.         if ($ticket->lastCollaborator != null) {
  655.             $email $ticket->lastCollaborator->getEmail();
  656.         }
  657.         
  658.         return $email != null $email '';;
  659.     }
  660. }