diff --git a/CHANGELOG-1.1.md b/CHANGELOG-1.1.md index a61c875..d1f30c6 100644 --- a/CHANGELOG-1.1.md +++ b/CHANGELOG-1.1.md @@ -3,6 +3,11 @@ CHANGELOG for 1.1.x This changelog references any relevant changes introduced in 1.1 minor versions. +* 1.1.4 (2024-12-19) + * Microsoft Modern App related updates. + * License and support email address updates. + * Code refactoring. + * 1.1.3 (2023-06-12) * Update: Dropped dependency on uvdesk/composer-plugin in support of symfony/flex diff --git a/Console/RefreshMailboxCommand.php b/Console/RefreshMailboxCommand.php index 14df11c..a927370 100644 --- a/Console/RefreshMailboxCommand.php +++ b/Console/RefreshMailboxCommand.php @@ -10,37 +10,50 @@ use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; +use Webkul\UVDesk\CoreFrameworkBundle\Entity\Microsoft\MicrosoftApp; +use Webkul\UVDesk\CoreFrameworkBundle\Entity\Microsoft\MicrosoftAccount; +use Webkul\UVDesk\CoreFrameworkBundle\Utils\Microsoft\Graph as MicrosoftGraph; +use Webkul\UVDesk\CoreFrameworkBundle\Services\MicrosoftIntegration; +use Webkul\UVDesk\MailboxBundle\Services\MailboxService; +use Webkul\UVDesk\MailboxBundle\Utils\IMAP; class RefreshMailboxCommand extends Command { private $endpoint; + private $outlookEndpoint; + private $router; - public function __construct(ContainerInterface $container, EntityManagerInterface $entityManager) + public function __construct(ContainerInterface $container, EntityManagerInterface $entityManager, MicrosoftIntegration $microsoftIntegration, MailboxService $mailboxService) { - $this->container = $container; - $this->entityManager = $entityManager; + $this->container = $container; + $this->entityManager = $entityManager; + $this->microsoftIntegration = $microsoftIntegration; + $this->mailboxService = $mailboxService; parent::__construct(); } protected function configure() { - $this->setName('uvdesk:refresh-mailbox'); - $this->setDescription('Check if any new emails have been received and process them into tickets'); - - $this->addArgument('emails', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, "Email address of the mailboxes you wish to update"); - $this->addOption('timestamp', 't', InputOption::VALUE_REQUIRED, "Fetch messages no older than the given timestamp"); + $this + ->setName('uvdesk:refresh-mailbox') + ->setDescription('Check if any new emails have been received and process them into tickets') + ->addArgument('emails', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, "Email address of the mailboxes you wish to update") + ->addOption('timestamp', 't', InputOption::VALUE_REQUIRED, "Fetch messages no older than the given timestamp") + ->addOption('secure', null, InputOption::VALUE_NONE, "Use HTTTPS for communicating with required api endpoints") + ; } protected function initialize(InputInterface $input, OutputInterface $output) { - $router = $this->container->get('router'); + $this->router = $this->container->get('router'); $useSecureConnection = $this->isSecureConnectionAvailable(); - $router->getContext()->setHost($this->container->getParameter('uvdesk.site_url')); - $router->getContext()->setScheme(false === $useSecureConnection ? 'http' : 'https'); + $this->router->getContext()->setHost($this->container->getParameter('uvdesk.site_url')); + $this->router->getContext()->setScheme(false === $useSecureConnection ? 'http' : 'https'); - $this->endpoint = $router->generate('helpdesk_member_mailbox_notification', [], UrlGeneratorInterface::ABSOLUTE_URL); + $this->endpoint = $this->router->generate('helpdesk_member_mailbox_notification', [], UrlGeneratorInterface::ABSOLUTE_URL); + $this->outlookEndpoint = $this->router->generate('helpdesk_member_outlook_mailbox_notification', [], UrlGeneratorInterface::ABSOLUTE_URL); } protected function execute(InputInterface $input, OutputInterface $output): int @@ -49,7 +62,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $mailboxEmailCollection = array_map(function ($email) { return filter_var($email, FILTER_SANITIZE_EMAIL); }, $input->getArgument('emails')); - + // Stop execution if no valid emails have been specified if (empty($mailboxEmailCollection)) { if (false === $input->getOption('no-interaction')) { @@ -61,56 +74,74 @@ protected function execute(InputInterface $input, OutputInterface $output): int // Process mailboxes $timestamp = new \DateTime(sprintf("-%u minutes", (int) ($input->getOption('timestamp') ?: 1440))); - + foreach ($mailboxEmailCollection as $mailboxEmail) { $output->writeln("\n# Retrieving mailbox configuration details for $mailboxEmail:\n"); - try { - $mailbox = $this->container->get('uvdesk.mailbox')->getMailboxByEmail($mailboxEmail); + $mailboxConfigurations = $this->mailboxService->parseMailboxConfigurations(); + $mailbox = $mailboxConfigurations->getIncomingMailboxByEmailAddress($mailboxEmail); - if (false == $mailbox['enabled']) { - if (false === $input->getOption('no-interaction')) { - $output->writeln(" Error: Mailbox for email $mailboxEmail is not enabled."); - } - - continue; - } else if (empty($mailbox['imap_server'])) { - if (false === $input->getOption('no-interaction')) { - $output->writeln(" Error: No imap configurations defined for email $mailboxEmail."); - } - - continue; - } - } catch (\Exception $e) { - if (false == $input->getOption('no-interaction')) { + if (empty($mailbox)) { + if (false === $input->getOption('no-interaction')) { $output->writeln(" Error: Mailbox for email $mailboxEmail not found."); + } - // return Command::INVALID; + continue; + } else if (false == $mailbox->getIsEnabled()) { + if (false === $input->getOption('no-interaction')) { + $output->writeln(" Error: Mailbox for email $mailboxEmail is not enabled."); } continue; + } else { + $imapConfiguration = $mailbox->getImapConfiguration(); + + if (empty($imapConfiguration)) { + if (false === $input->getOption('no-interaction')) { + $output->writeln(" Error: No imap configurations defined for email $mailboxEmail."); + } + + continue; + } } try { - $this->refreshMailbox( - $mailbox['imap_server']['host'], - $mailbox['imap_server']['username'], - base64_decode($mailbox['imap_server']['password']), - $timestamp, - $output, - $mailbox - ); + if ($imapConfiguration instanceof IMAP\Transport\SimpleTransportConfigurationInterface) { + $output->writeln(" Cannot fetch emails from mailboxes with simple transport configurations."); + } else if ($imapConfiguration instanceof IMAP\Transport\AppTransportConfigurationInterface) { + $microsoftApp = $this->entityManager->getRepository(MicrosoftApp::class)->findOneByClientId($imapConfiguration->getClient()); + + if (empty($microsoftApp)) { + $output->writeln(" No microsoft app was found for configured client id '" . $imapConfiguration->getClient() . "'."); + + continue; + } else { + $microsoftAccount = $this->entityManager->getRepository(MicrosoftAccount::class)->findOneBy([ + 'email' => $imapConfiguration->getUsername(), + 'microsoftApp' => $microsoftApp, + ]); + + if (empty($microsoftAccount)) { + $output->writeln(" No microsoft account was found with email '" . $imapConfiguration->getUsername() . "' for configured client id '" . $imapConfiguration->getClient() . "'."); + + continue; + } + } + + $this->refreshOutlookMailbox($microsoftApp, $microsoftAccount, $timestamp, $output); + } else { + $this->refreshMailbox($imapConfiguration->getHost(), $imapConfiguration->getUsername(), urldecode($imapConfiguration->getPassword()), $timestamp, $output); + } } catch (\Exception $e) { $output->writeln(" An unexpected error occurred: " . $e->getMessage() . ""); } } - $output->writeln(""); return Command::SUCCESS; } - public function refreshMailbox($server_host, $server_username, $server_password, \DateTime $timestamp, OutputInterface $output, $mailbox) + public function refreshMailbox($server_host, $server_username, $server_password, \DateTime $timestamp, OutputInterface $output) { $output->writeln(" - Establishing connection with mailbox"); @@ -143,65 +174,232 @@ public function refreshMailbox($server_host, $server_username, $server_password, $output->writeln("\n API " . $this->endpoint . "\n"); $counter = 1; + try { + foreach ($emailCollection as $id => $messageNumber) { + $output->writeln(" - Processing email $counter of $emailCount:"); - foreach ($emailCollection as $id => $messageNumber) { - $output->writeln(" - Processing email $counter of $emailCount:"); - - $message = imap_fetchbody($imap, $messageNumber, ""); - list($response, $responseCode, $responseErrorMessage) = $this->parseInboundEmail($message, $output); + $message = imap_fetchbody($imap, $messageNumber, ""); - if ($responseCode == 200) { - $output->writeln("\n 200 " . $response['message'] . "\n"); - } else { - if (!empty($responseErrorMessage)) { - $output->writeln("\n ERROR $responseErrorMessage\n"); - } else { - $output->writeln("\n ERROR " . $response['message'] . "\n"); + list($response, $responseCode) = $this->parseInboundEmail($message, $output); + + if ($response['message'] && !isset($response['error'])) { + $output->writeln("\n 200 " . $response['message'] . "\n"); } + + if (isset($response['error'])) { + $output->writeln("\n ERROR ". $response['message'] ."\n"); + } + + $counter++; } - - if (true == $mailbox['deleted']) { - imap_delete($imap, $messageNumber); + + $output->writeln(" - Mailbox refreshed successfully!"); + } catch (\Exception $e) { + $msg = $e->getMessage(); + $output->writeln(" - $msg"); + } + } + } + + return; + } + + public function refreshOutlookMailbox($microsoftApp, $microsoftAccount, \DateTime $timestamp, OutputInterface $output) + { + $timeSpan = $timestamp->format('Y-m-d'); + $credentials = json_decode($microsoftAccount->getCredentials(), true); + $redirectEndpoint = str_replace('http', 'https', $this->router->generate('uvdesk_member_core_framework_integrations_microsoft_apps_oauth_login', [], UrlGeneratorInterface::ABSOLUTE_URL)); + + $filters = [ + 'ReceivedDateTime' => [ + 'operation' => '>', + 'value' => $timeSpan, + ], + ]; + + $mailboxFolderId = null; + $mailboxFolderCollection = $this->getOutlookMailboxFolders($credentials['access_token'], $credentials['refresh_token'], $microsoftApp, $microsoftAccount, $output); + + foreach ($mailboxFolderCollection as $mailboxFolder) { + if ($mailboxFolder['displayName'] == 'Inbox') { + $mailboxFolderId = $mailboxFolder['id']; + break; + } + } + + $nextLink = null; + $counter = 1; + + do { + $response = $nextLink ? MicrosoftGraph\Me::getMessagesWithNextLink($nextLink, $credentials['access_token']) : MicrosoftGraph\Me::messages($credentials['access_token'], $mailboxFolderId, $filters); + + if (! empty($response['error'])) { + if ( + ! empty($response['error']['code']) + && $response['error']['code'] == 'InvalidAuthenticationToken' + ) { + $tokenResponse = $this->microsoftIntegration->refreshAccessToken($microsoftApp, $credentials['refresh_token']); + + if (! empty($tokenResponse['access_token'])) { + $microsoftAccount->setCredentials(json_encode($tokenResponse)); + $this->entityManager->persist($microsoftAccount); + $this->entityManager->flush(); + + $credentials['access_token'] = $tokenResponse['access_token']; + $response = $nextLink ? MicrosoftGraph\Me::getMessagesWithNextLink($nextLink, $credentials['access_token']) : MicrosoftGraph\Me::messages($credentials['access_token'], $mailboxFolderId, $filters); + } else { + $output->writeln("\n ERROR Failed to retrieve a valid access token.\n"); + + return; } + } else { + $errorCode = $response['error']['code'] ?? 'Unknown'; + $output->writeln("\n ERROR An unexpected api error occurred of type '" . $errorCode . "'.\n"); - $counter ++; + return; } + } + + if ($counter === 1) { + $emailCount = $response['@odata.count'] ?? 'NA'; + $output->writeln(" - Found a total of $emailCount emails in mailbox since $timeSpan"); + } + + if (! empty($response['value'])) { + $output->writeln("\n # Processing all found emails iteratively:"); + $output->writeln("\n API " . $this->outlookEndpoint . "\n"); + + foreach ($response['value'] as $message) { + $output->writeln(" - Processing email $counter of $emailCount:"); + + $detailedMessage = MicrosoftGraph\Me::message($message['id'], $credentials['access_token']); + + $attachments = $detailedMessage['attachments']; + $outlookAttachments = ['outlookAttachments' => []]; + + foreach ($attachments as $attachment) { + if (isset($attachment['contentBytes'])) { + $tempFilePath = sys_get_temp_dir(); + + if (! is_dir($tempFilePath)) { + mkdir($tempFilePath, 0755, true); + } + + $filePath = $tempFilePath . '/' . $attachment['name']; + + if (file_exists($filePath)) { + $mimeType = mime_content_type($filePath); + } else { + $mimeType = 'application/octet-stream'; + } + + $outlookAttachments['outlookAttachments'][] = [ + 'content' => $attachment['contentBytes'], + 'mimeType' => $mimeType, + 'name' => $attachment['name'], + ]; + } + } + + $detailedMessage = array_merge($detailedMessage, $outlookAttachments); + + if (isset($detailedMessage['body']['content'])) { + $detailedMessage['body']['content'] = preg_replace('/]+>/', '', $detailedMessage['body']['content']); + $detailedMessage['body']['content'] = preg_replace('/<\/?head[^>]*>/', '', $detailedMessage['body']['content']); + $detailedMessage['body']['content'] = preg_replace('/<\/?body[^>]*>/', '', $detailedMessage['body']['content']); + } + + unset($detailedMessage['attachments']); + + list($response, $responseCode) = $this->parseOutlookInboundEmail($detailedMessage, $output); + + if ( + $response['message'] + && !isset($response['error']) + ) { + $output->writeln("\n 200 " . $response['message'] . "\n"); + } - $output->writeln(" - Mailbox refreshed successfully!"); + if (isset($response['error'])) { + $output->writeln("\n ERROR ". $response['message'] ."\n"); + } - if (true == $mailbox['deleted']) { - imap_expunge($imap); - imap_close($imap,CL_EXPUNGE); + $counter++; } } - } - return; + $nextLink = $response['@odata.nextLink'] ?? null; + + } while ($nextLink); + + $output->writeln(" - Mailbox refreshed successfully!"); } - public function parseInboundEmail($message, $output) + private function getOutlookMailboxFolders($accessToken, $refreshToken, $microsoftApp, $microsoftAccount, OutputInterface $output) { - $curlHandler = curl_init(); + $response = MicrosoftGraph\Me::mailFolders($accessToken); - curl_setopt($curlHandler, CURLOPT_HEADER, 0); - curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($curlHandler, CURLOPT_POST, 1); - curl_setopt($curlHandler, CURLOPT_URL, $this->endpoint); - curl_setopt($curlHandler, CURLOPT_POSTFIELDS, http_build_query(['email' => $message])); + if (! empty($response['error'])) { + if ( + ! empty($response['error']['code']) + && $response['error']['code'] == 'InvalidAuthenticationToken' + ) { + $tokenResponse = $this->microsoftIntegration->refreshAccessToken($microsoftApp, $refreshToken); + + if (! empty($tokenResponse['access_token'])) { + $microsoftAccount->setCredentials(json_encode($tokenResponse)); + + $this->entityManager->persist($microsoftAccount); + $this->entityManager->flush(); - $curlResponse = curl_exec($curlHandler); - - $response = json_decode($curlResponse, true); - $responseCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE); - $responseErrorMessage = null; + $response = MicrosoftGraph\Me::mailFolders($tokenResponse['access_token']); + + } else { + $output->writeln("\n ERROR Failed to retrieve a valid access token.\n"); - if (curl_errno($curlHandler) || $responseCode != 200) { - $responseErrorMessage = curl_error($curlHandler); + return []; + } + } else { + if (! empty($response['error']['code'])) { + $output->writeln("\n ERROR An unexpected api error occurred of type '" . $response['error']['code'] . "'.\n"); + } else { + $output->writeln("\n ERROR An unexpected api error occurred.\n"); + } + + return []; + } } - curl_close($curlHandler); + return !empty($response['value']) ? $response['value'] : []; + } + + public function parseInboundEmail($message, $output) + { + $processedThread = $this->mailboxService->processMail($message); + $responseMessage = $processedThread['message']; + + if ( + isset($processedThread['content']['from']) + && !empty($processedThread['content']['from']) + ) { + $responseMessage = "Received email from " . $processedThread['content']['from']. ". " . $responseMessage; + } + + if ( + (isset($processedThread['content']['ticket']) + && !empty($processedThread['content']['ticket'])) + && (isset($processedThread['content']['thread']) + && !empty($processedThread['content']['thread'])) + ) { + $responseMessage .= " [tickets/" . $processedThread['content']['ticket'] . "/#" . $processedThread['content']['ticket'] . "]"; + } else if ( + isset($processedThread['content']['ticket']) + && !empty($processedThread['content']['ticket']) + ) { + $responseMessage .= " [tickets/" . $processedThread['content']['ticket'] . "]"; + } - return [$response, $responseCode, $responseErrorMessage]; + return [$processedThread, $responseMessage]; } protected function isSecureConnectionAvailable() @@ -217,4 +415,33 @@ protected function isSecureConnectionAvailable() return $isSecureRequestAvailable; } -} + + public function parseOutlookInboundEmail($detailedMessage, $output) + { + $processedThread = $this->mailboxService->processOutlookMail($detailedMessage); + $responseMessage = $processedThread['message']; + + if ( + isset($processedThread['content']['from']) + && !empty($processedThread['content']['from']) + ) { + $responseMessage = "Received email from " . $processedThread['content']['from']. ". " . $responseMessage; + } + + if ( + (isset($processedThread['content']['ticket']) + && !empty($processedThread['content']['ticket'])) + && (isset($processedThread['content']['thread']) + && !empty($processedThread['content']['thread'])) + ) { + $responseMessage .= " [tickets/" . $processedThread['content']['ticket'] . "/#" . $processedThread['content']['ticket'] . "]"; + } else if ( + isset($processedThread['content']['ticket']) + && !empty($processedThread['content']['ticket']) + ) { + $responseMessage .= " [tickets/" . $processedThread['content']['ticket'] . "]"; + } + + return [$processedThread, $responseMessage]; + } +} \ No newline at end of file diff --git a/Controller/MailboxChannel.php b/Controller/MailboxChannel.php index 755d991..3a9419b 100644 --- a/Controller/MailboxChannel.php +++ b/Controller/MailboxChannel.php @@ -2,173 +2,429 @@ namespace Webkul\UVDesk\MailboxBundle\Controller; +use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\RedirectResponse; use Webkul\UVDesk\MailboxBundle\Utils\Mailbox\Mailbox; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Webkul\UVDesk\MailboxBundle\Utils\MailboxConfiguration; -use Webkul\UVDesk\MailboxBundle\Utils\Imap\Configuration as ImapConfiguration; use Webkul\UVDesk\MailboxBundle\Services\MailboxService; use Symfony\Contracts\Translation\TranslatorInterface; -use Webkul\UVDesk\CoreFrameworkBundle\SwiftMailer\SwiftMailer as SwiftMailerService; use Webkul\UVDesk\CoreFrameworkBundle\Services\UserService; +use Webkul\UVDesk\MailboxBundle\Utils\IMAP; +use Webkul\UVDesk\MailboxBundle\Utils\SMTP; +use Webkul\UVDesk\CoreFrameworkBundle\Entity\Microsoft\MicrosoftApp; +use Webkul\UVDesk\CoreFrameworkBundle\Entity\Microsoft\MicrosoftAccount; +use Webkul\UVDesk\CoreFrameworkBundle\SwiftMailer\SwiftMailer as SwiftMailerService; class MailboxChannel extends AbstractController { - private $mailboxService; - private $translator; - private $swiftMailer; - private $userService; - - public function __construct(UserService $userService, MailboxService $mailboxService, TranslatorInterface $translator, SwiftMailerService $swiftMailer) - { - $this->userService = $userService; - $this->mailboxService = $mailboxService; - $this->translator = $translator; - $this->swiftMailer = $swiftMailer; - } - - public function loadMailboxes() + public function loadMailboxes(UserService $userService) { - if (!$this->userService->isAccessAuthorized('ROLE_ADMIN')) { + if (! $userService->isAccessAuthorized('ROLE_ADMIN')) { return $this->redirect($this->generateUrl('helpdesk_member_dashboard')); } return $this->render('@UVDeskMailbox//listConfigurations.html.twig'); } - - public function createMailboxConfiguration(Request $request) + + public function createMailboxConfiguration(Request $request, EntityManagerInterface $entityManager, UserService $userService, MailboxService $mailboxService, TranslatorInterface $translator, SwiftMailerService $swiftMailer) { - if (!$this->userService->isAccessAuthorized('ROLE_ADMIN')) { + if (! $userService->isAccessAuthorized('ROLE_ADMIN')) { return $this->redirect($this->generateUrl('helpdesk_member_dashboard')); } - $swiftmailerConfigurationCollection = $this->swiftMailer->parseSwiftMailerConfigurations(); + $microsoftAppCollection = $entityManager->getRepository(MicrosoftApp::class)->findBy(['isEnabled' => true, 'isVerified' => true]); + $microsoftAccountCollection = $entityManager->getRepository(MicrosoftAccount::class)->findAll(); + + $microsoftAppCollection = array_map(function ($microsoftApp) { + return [ + 'id' => $microsoftApp->getId(), + 'name' => $microsoftApp->getName(), + ]; + }, $microsoftAppCollection); + + $microsoftAccountCollection = array_map(function ($microsoftAccount) { + return [ + 'id' => $microsoftAccount->getId(), + 'name' => $microsoftAccount->getName(), + 'email' => $microsoftAccount->getEmail(), + ]; + }, $microsoftAccountCollection); + + # load swift mailer configuration + $swiftMailerConfigurationCollection = $swiftMailer->parseSwiftMailerConfigurations(); if ($request->getMethod() == 'POST') { $params = $request->request->all(); + $smtpConfiguration = null; + $imapConfiguration = null; + // IMAP Configuration - if (!empty($params['imap']['transport'])) { - ($imapConfiguration = ImapConfiguration::createTransportDefinition($params['imap']['transport'], !empty($params['imap']['host']) ? trim($params['imap']['host'], '"') : null)) - ->setUsername($params['imap']['username']) - ->setPassword(base64_encode($params['imap']['password'])); + if (! empty($params['imap']['transport'])) { + $imapConfiguration = IMAP\Configuration::createTransportDefinition($params['imap']['transport'], !empty($params['imap']['host']) ? trim($params['imap']['host'], '"') : null); + + if ($imapConfiguration instanceof IMAP\Transport\AppTransportConfigurationInterface) { + if ($params['imap']['transport'] == 'outlook_oauth') { + $microsoftAccount = $entityManager->getRepository(MicrosoftAccount::class)->findOneById($params['imap']['username']); + + if (empty($microsoftAccount)) { + $this->addFlash('warning', 'No configuration details were found for the provided microsoft account.'); + + return $this->render('@UVDeskMailbox//manageConfigurations.html.twig', [ + 'microsoftAppCollection' => $microsoftAppCollection, + 'microsoftAccountCollection' => $microsoftAccountCollection, + ]); + } + + $params['imap']['username'] = $microsoftAccount->getEmail(); + $params['imap']['client'] = $microsoftAccount->getMicrosoftApp()->getClientId(); + + $imapConfiguration + ->setClient($params['imap']['client']) + ->setUsername($params['imap']['username']) + ; + } else { + $this->addFlash('warning', 'The resolved IMAP configuration is not configured for any valid available app.'); + + return $this->render('@UVDeskMailbox//manageConfigurations.html.twig', [ + 'microsoftAppCollection' => $microsoftAppCollection, + 'microsoftAccountCollection' => $microsoftAccountCollection, + ]); + } + } else if ($imapConfiguration instanceof IMAP\Transport\SimpleTransportConfigurationInterface) { + $imapConfiguration + ->setUsername($params['imap']['username']) + ; + } else { + $imapConfiguration + ->setUsername($params['imap']['username']) + ->setPassword(urlencode($params['imap']['password'])) + ; + } } - // Swiftmailer Configuration - if (!empty($params['swiftmailer_id'])) { - foreach ($swiftmailerConfigurationCollection as $configuration) { - if ($configuration->getId() == $params['swiftmailer_id']) { - $swiftmailerConfiguration = $configuration; - break; + // SMTP Configuration + if ( + ! empty($params['smtp']['transport']) + && 'swiftmailer_id' !== $params['smtp']['transport'] + ) { + $smtpConfiguration = SMTP\Configuration::createTransportDefinition($params['smtp']['transport'], !empty($params['smtp']['host']) ? trim($params['smtp']['host'], '"') : null); + + if ($smtpConfiguration instanceof SMTP\Transport\AppTransportConfigurationInterface) { + if ($params['smtp']['transport'] == 'outlook_oauth') { + $microsoftAccount = $entityManager->getRepository(MicrosoftAccount::class)->findOneById($params['smtp']['username']); + + if (empty($microsoftAccount)) { + $this->addFlash('warning', 'No configuration details were found for the provided microsoft account.'); + + return $this->render('@UVDeskMailbox//manageConfigurations.html.twig', [ + 'microsoftAppCollection' => $microsoftAppCollection, + 'microsoftAccountCollection' => $microsoftAccountCollection, + 'swiftmailerConfigurations' => $swiftMailerConfigurationCollection, + ]); + } + + $params['smtp']['username'] = $microsoftAccount->getEmail(); + $params['smtp']['client'] = $microsoftAccount->getMicrosoftApp()->getClientId(); + + $smtpConfiguration + ->setClient($params['smtp']['client']) + ->setUsername($params['smtp']['username']) + ; + } else { + $this->addFlash('warning', 'The resolved SMTP configuration is not configured for any valid available app.'); + + return $this->render('@UVDeskMailbox//manageConfigurations.html.twig', [ + 'microsoftAppCollection' => $microsoftAppCollection, + 'microsoftAccountCollection' => $microsoftAccountCollection, + 'swiftmailerConfigurations' => $swiftMailerConfigurationCollection, + ]); } + } else if ($smtpConfiguration instanceof SMTP\Transport\ResolvedTransportConfigurationInterface) { + $smtpConfiguration + ->setUsername($params['smtp']['username']) + ->setPassword(urlencode($params['smtp']['password'])) + ; + } else { + $smtpConfiguration + ->setHost($params['smtp']['host']) + ->setPort((int) $params['smtp']['port']) + ->setUsername($params['smtp']['username']) + ->setPassword(urlencode($params['smtp']['password'])) + ->setSenderAddress(!empty($params['smtp']['senderAddress']) ? $params['smtp']['senderAddress'] : null) + ; } } - if (!empty($imapConfiguration) && !empty($swiftmailerConfiguration)) { - $mailboxService = $this->mailboxService; + if ( + empty($imapConfiguration) + && empty($smtpConfiguration) + ) { + $this->addFlash('warning', 'Invalid mailbox details provided. Mailbox needs to have at least IMAP or SMTP settings defined.'); + } else { $mailboxConfiguration = $mailboxService->parseMailboxConfigurations(); - ($mailbox = new Mailbox(!empty($params['id']) ? $params['id'] : null)) + // SwiftMailer Configuration + if (! empty($params['swiftmailer_id'])) { + foreach ($swiftMailerConfigurationCollection as $configuration) { + if ($configuration->getId() == $params['swiftmailer_id']) { + $swiftmailerConfiguration = $configuration; + break; + } + } + } + + $mailbox = new Mailbox(!empty($params['id']) ? $params['id'] : null); + $mailbox ->setName($params['name']) ->setIsEnabled(!empty($params['isEnabled']) && 'on' == $params['isEnabled'] ? true : false) - ->setIsDeleted(!empty($params['isDeleted']) && 'on' == $params['isDeleted'] ? true : false) - ->setImapConfiguration($imapConfiguration) - ->setSwiftMailerConfiguration($swiftmailerConfiguration); + ->setIsEmailDeliveryDisabled(!empty($params['isEmailDeliveryDisabled']) && 'on' == $params['isEmailDeliveryDisabled'] ? true : false) + ; + + if (! empty($imapConfiguration)) { + $mailbox + ->setImapConfiguration($imapConfiguration) + ; + } + + if (! empty($smtpConfiguration)) { + $mailbox + ->setSmtpConfiguration($smtpConfiguration) + ; + } + + if (! empty($swiftmailerConfiguration)) { + $mailbox + ->setSwiftMailerConfiguration($swiftmailerConfiguration); + ; + } $mailboxConfiguration->addMailbox($mailbox); + if (! empty($params['isDefault']) && 'on' == $params['isDefault']) { + $mailboxConfiguration + ->setDefaultMailbox($mailbox) + ; + } + file_put_contents($mailboxService->getPathToConfigurationFile(), (string) $mailboxConfiguration); - $this->addFlash('success', $this->translator->trans('Mailbox successfully created.')); + $this->addFlash('success', $translator->trans('Mailbox successfully created.')); + return new RedirectResponse($this->generateUrl('helpdesk_member_mailbox_settings')); } } return $this->render('@UVDeskMailbox//manageConfigurations.html.twig', [ - 'swiftmailerConfigurations' => $swiftmailerConfigurationCollection, + 'microsoftAppCollection' => $microsoftAppCollection, + 'microsoftAccountCollection' => $microsoftAccountCollection, + 'swiftmailerConfigurations' => $swiftMailerConfigurationCollection, ]); } - public function updateMailboxConfiguration($id, Request $request) + public function updateMailboxConfiguration($id, Request $request, EntityManagerInterface $entityManager, UserService $userService, MailboxService $mailboxService, TranslatorInterface $translator, SwiftMailerService $swiftMailer) { - if (!$this->userService->isAccessAuthorized('ROLE_ADMIN')) { + if (! $userService->isAccessAuthorized('ROLE_ADMIN')) { return $this->redirect($this->generateUrl('helpdesk_member_dashboard')); } - - $mailboxService = $this->mailboxService; - $existingMailboxConfiguration = $mailboxService->parseMailboxConfigurations(); - $swiftmailerConfigurationCollection = $this->swiftMailer->parseSwiftMailerConfigurations(); - - foreach ($existingMailboxConfiguration->getMailboxes() as $configuration) { - if ($configuration->getId() == $id) { - $mailbox = $configuration; - break; - } - } + + $mailboxConfiguration = $mailboxService->parseMailboxConfigurations(); + + $mailbox = $mailboxConfiguration->getMailboxById($id); if (empty($mailbox)) { return new Response('', 404); } + $microsoftAppCollection = $entityManager->getRepository(MicrosoftApp::class)->findBy(['isEnabled' => true, 'isVerified' => true]); + $microsoftAccountCollection = $entityManager->getRepository(MicrosoftAccount::class)->findAll(); + + $microsoftAppCollection = array_map(function ($microsoftApp) { + return [ + 'id' => $microsoftApp->getId(), + 'name' => $microsoftApp->getName(), + ]; + }, $microsoftAppCollection); + + $microsoftAccountCollection = array_map(function ($microsoftAccount) { + return [ + 'id' => $microsoftAccount->getId(), + 'name' => $microsoftAccount->getName(), + 'email' => $microsoftAccount->getEmail(), + ]; + }, $microsoftAccountCollection); + + # load swift mailer configuration + $swiftMailerConfigurationCollection = $swiftMailer->parseSwiftMailerConfigurations(); + if ($request->getMethod() == 'POST') { $params = $request->request->all(); + + $smtpConfiguration = null; + $imapConfiguration = null; + // IMAP Configuration if (!empty($params['imap']['transport'])) { - ($imapConfiguration = ImapConfiguration::createTransportDefinition($params['imap']['transport'], !empty($params['imap']['host']) ? trim($params['imap']['host'], '"') : null)) - ->setUsername($params['imap']['username']) - ->setPassword(base64_encode($params['imap']['password'])); - } + $imapConfiguration = IMAP\Configuration::createTransportDefinition($params['imap']['transport'], !empty($params['imap']['host']) ? trim($params['imap']['host'], '"') : null); + + if ($imapConfiguration instanceof IMAP\Transport\AppTransportConfigurationInterface) { + if ($params['imap']['transport'] == 'outlook_oauth') { + $microsoftAccount = $entityManager->getRepository(MicrosoftAccount::class)->findOneById($params['imap']['username']); + + if (empty($microsoftAccount)) { + $this->addFlash('warning', 'No configuration details were found for the provided microsoft account.'); - // Swiftmailer Configuration - if (!empty($params['swiftmailer_id'])) { - foreach ($swiftmailerConfigurationCollection as $configuration) { - if ($configuration->getId() == $params['swiftmailer_id']) { - $swiftmailerConfiguration = $configuration; + return $this->render('@UVDeskMailbox//manageConfigurations.html.twig', [ + 'microsoftAppCollection' => $microsoftAppCollection, + 'microsoftAccountCollection' => $microsoftAccountCollection, + 'swiftmailerConfigurations' => $swiftMailerConfigurationCollection, + ]); + } + + $params['imap']['username'] = $microsoftAccount->getEmail(); + $params['imap']['client'] = $microsoftAccount->getMicrosoftApp()->getClientId(); + + $imapConfiguration + ->setClient($params['imap']['client']) + ->setUsername($params['imap']['username']) + ; + } else { + $this->addFlash('warning', 'The resolved IMAP configuration is not configured for any valid available app.'); - break; + return $this->render('@UVDeskMailbox//manageConfigurations.html.twig', [ + 'microsoftAppCollection' => $microsoftAppCollection, + 'microsoftAccountCollection' => $microsoftAccountCollection, + 'swiftmailerConfigurations' => $swiftMailerConfigurationCollection, + ]); } + } else if ($imapConfiguration instanceof IMAP\Transport\SimpleTransportConfigurationInterface) { + $imapConfiguration + ->setUsername($params['imap']['username']) + ; + } else { + $imapConfiguration + ->setUsername($params['imap']['username']) + ->setPassword(urlencode($params['imap']['password'])) + ; } } - if (!empty($imapConfiguration) && !empty($swiftmailerConfiguration)) { - $mailboxConfiguration = new MailboxConfiguration(); - - foreach ($existingMailboxConfiguration->getMailboxes() as $configuration) { - if ($mailbox->getId() == $configuration->getId()) { - if (empty($params['id'])) { - $mailbox = new Mailbox(); - } else if ($mailbox->getId() != $params['id']) { - $mailbox = new Mailbox($params['id']); + // SMTP Configuration + if ( + ! empty($params['smtp']['transport']) + && 'swiftmailer_id' !== $params['smtp']['transport'] + ) { + $smtpConfiguration = SMTP\Configuration::createTransportDefinition($params['smtp']['transport'], !empty($params['smtp']['host']) ? trim($params['smtp']['host'], '"') : null); + + if ($smtpConfiguration instanceof SMTP\Transport\AppTransportConfigurationInterface) { + if ($params['smtp']['transport'] == 'outlook_oauth') { + $microsoftAccount = $entityManager->getRepository(MicrosoftAccount::class)->findOneById($params['smtp']['username']); + + if (empty($microsoftAccount)) { + $this->addFlash('warning', 'No configuration details were found for the provided microsoft account.'); + + return $this->render('@UVDeskMailbox//manageConfigurations.html.twig', [ + 'microsoftAppCollection' => $microsoftAppCollection, + 'microsoftAccountCollection' => $microsoftAccountCollection, + 'swiftmailerConfigurations' => $swiftMailerConfigurationCollection, + ]); } - $mailbox - ->setName($params['name']) - ->setIsEnabled(!empty($params['isEnabled']) && 'on' == $params['isEnabled'] ? true : false) - ->setIsDeleted(!empty($params['isDeleted']) && 'on' == $params['isDeleted'] ? true : false) - ->setImapConfiguration($imapConfiguration) - ->setSwiftMailerConfiguration($swiftmailerConfiguration); + $params['smtp']['username'] = $microsoftAccount->getEmail(); + $params['smtp']['client'] = $microsoftAccount->getMicrosoftApp()->getClientId(); + + $smtpConfiguration + ->setClient($params['smtp']['client']) + ->setUsername($params['smtp']['username']) + ; + } else { + $this->addFlash('warning', 'The resolved SMTP configuration is not configured for any valid available app.'); + + return $this->render('@UVDeskMailbox//manageConfigurations.html.twig', [ + 'microsoftAppCollection' => $microsoftAppCollection, + 'microsoftAccountCollection' => $microsoftAccountCollection, + 'swiftmailerConfigurations' => $swiftMailerConfigurationCollection, + ]); + } + } else if ($smtpConfiguration instanceof SMTP\Transport\ResolvedTransportConfigurationInterface) { + $smtpConfiguration + ->setUsername($params['smtp']['username']) + ->setPassword(urlencode($params['smtp']['password'])) + ; + } else { + $smtpConfiguration + ->setHost($params['smtp']['host']) + ->setPort((int) $params['smtp']['port']) + ->setUsername($params['smtp']['username']) + ->setPassword(urlencode($params['smtp']['password'])) + ->setSenderAddress(!empty($params['smtp']['senderAddress']) ? $params['smtp']['senderAddress'] : null) + ; + } + } - $mailboxConfiguration->addMailbox($mailbox); + if (empty($imapConfiguration) && empty($smtpConfiguration)) { + $this->addFlash('warning', 'Invalid mailbox details provided. Mailbox needs to have at least IMAP or SMTP settings defined.'); + } else { + $mailboxConfiguration->removeMailbox($mailbox); + + $mailbox = new Mailbox($params['id']); - continue; + // SwiftMailer Configuration + if (! empty($params['swiftmailer_id'])) { + foreach ($swiftMailerConfigurationCollection as $configuration) { + if ($configuration->getId() == $params['swiftmailer_id']) { + $swiftmailerConfiguration = $configuration; + break; + } } + } + + $mailbox + ->setName($params['name']) + ->setIsEnabled(!empty($params['isEnabled']) && 'on' == $params['isEnabled'] ? true : false); - $mailboxConfiguration->addMailbox($configuration); + if (! empty($imapConfiguration)) { + $mailbox + ->setImapConfiguration($imapConfiguration) + ; + } + + if (! empty($smtpConfiguration)) { + $mailbox + ->setSmtpConfiguration($smtpConfiguration) + ; + } + + if (! empty($swiftmailerConfiguration) && empty($smtpConfiguration)) { + $mailbox + ->setSwiftMailerConfiguration($swiftmailerConfiguration); + ; + } + + $mailboxConfiguration->addMailbox($mailbox); + + if (! empty($params['isDefault']) && 'on' == $params['isDefault']) { + $mailboxConfiguration + ->setDefaultMailbox($mailbox) + ; } file_put_contents($mailboxService->getPathToConfigurationFile(), (string) $mailboxConfiguration); - $this->addFlash('success', $this->translator->trans('Mailbox successfully updated.')); - + $this->addFlash('success', $translator->trans('Mailbox successfully updated.')); + return new RedirectResponse($this->generateUrl('helpdesk_member_mailbox_settings')); } } return $this->render('@UVDeskMailbox//manageConfigurations.html.twig', [ - 'mailbox' => $mailbox ?? null, - 'swiftmailerConfigurations' => $swiftmailerConfigurationCollection, + 'mailbox' => $mailbox, + 'microsoftAppCollection' => $microsoftAppCollection, + 'microsoftAccountCollection' => $microsoftAccountCollection, + 'swiftmailerConfigurations' => $swiftMailerConfigurationCollection, ]); } -} +} \ No newline at end of file diff --git a/Controller/MailboxChannelXHR.php b/Controller/MailboxChannelXHR.php index 48ef9f1..91b13b5 100644 --- a/Controller/MailboxChannelXHR.php +++ b/Controller/MailboxChannelXHR.php @@ -30,13 +30,69 @@ public function processRawContentMail(Request $request) if ($rawEmail != false && !empty($rawEmail)) { $this->mailboxService->processMail($rawEmail); - }else{ + } else { dump("Empty Text file not allow"); - } + } + exit(0); } + + public function loadMailboxesXHR(Request $request) + { + $mailboxConfiguration = $this->mailboxService->parseMailboxConfigurations(); + + $defaultMailbox = $mailboxConfiguration->getDefaultMailbox(); + + $collection = array_map(function ($mailbox) use ($defaultMailbox) { + return [ + 'id' => $mailbox->getId(), + 'name' => $mailbox->getName(), + 'isEnabled' => $mailbox->getIsEnabled(), + ]; + }, array_values($mailboxConfiguration->getMailboxes())); + + return new JsonResponse($collection ?? []); + } + + public function removeMailboxConfiguration($id, Request $request) + { + $mailboxService = $this->mailboxService; + $existingMailboxConfiguration = $mailboxService->parseMailboxConfigurations(); + + foreach ($existingMailboxConfiguration->getMailboxes() as $configuration) { + if ($configuration->getId() == $id) { + $mailbox = $configuration; + + break; + } + } + + if (empty($mailbox)) { + return new JsonResponse([ + 'alertClass' => 'danger', + 'alertMessage' => "No mailbox found with id '$id'.", + ], 404); + } + + $mailboxConfiguration = new MailboxConfiguration(); + + foreach ($existingMailboxConfiguration->getMailboxes() as $configuration) { + if ($configuration->getId() == $id) { + continue; + } + + $mailboxConfiguration->addMailbox($configuration); + } + + file_put_contents($mailboxService->getPathToConfigurationFile(), (string) $mailboxConfiguration); + + return new JsonResponse([ + 'alertClass' => 'success', + 'alertMessage' => $this->translator->trans('Mailbox configuration removed successfully.'), + ]); + } - public function processMailXHR(Request $request) + public function processMailXHR(Request $request, MailboxService $mailboxService) { if ("POST" != $request->getMethod()) { return new JsonResponse([ @@ -51,7 +107,7 @@ public function processMailXHR(Request $request) } try { - $processedThread = $this->mailboxService->processMail($request->get('email')); + $processedThread = $mailboxService->processMail($request->get('email')); } catch (\Exception $e) { return new JsonResponse([ 'success' => false, @@ -66,7 +122,7 @@ public function processMailXHR(Request $request) } if (!empty($processedThread['content']['ticket']) && !empty($processedThread['content']['thread'])) { - $responseMessage .= " [tickets/" . $processedThread['content']['ticket'] . "/#" . $processedThread['content']['thread'] . "]"; + $responseMessage .= " [tickets/" . $processedThread['content']['ticket'] . "/#" . $processedThread['content']['ticket'] . "]"; } else if (!empty($processedThread['content']['ticket'])) { $responseMessage .= " [tickets/" . $processedThread['content']['ticket'] . "]"; } @@ -76,56 +132,49 @@ public function processMailXHR(Request $request) 'message' => $responseMessage, ]); } - - public function loadMailboxesXHR(Request $request) - { - $collection = array_map(function ($mailbox) { - return [ - 'id' => $mailbox->getId(), - 'name' => $mailbox->getName(), - 'isEnabled' => $mailbox->getIsEnabled(), - 'isDeleted' => $mailbox->getIsDeleted() ? $mailbox->getIsDeleted() : false, - ]; - }, $this->mailboxService->parseMailboxConfigurations()->getMailboxes()); - - return new JsonResponse($collection ?? []); - } - public function removeMailboxConfiguration($id, Request $request) + public function processOutlookMailXHR(Request $request, MailboxService $mailboxService) { - $mailboxService = $this->mailboxService; - $existingMailboxConfiguration = $mailboxService->parseMailboxConfigurations(); - - foreach ($existingMailboxConfiguration->getMailboxes() as $configuration) { - if ($configuration->getId() == $id) { - $mailbox = $configuration; - - break; - } + if ("POST" != $request->getMethod()) { + return new JsonResponse([ + 'success' => false, + 'message' => 'Request not supported.' + ], 500); + } else if (null == $request->get('email')) { + return new JsonResponse([ + 'success' => false, + 'message' => 'Missing required email data in request content.' + ], 500); } - if (empty($mailbox)) { + try { + $processedThread = $mailboxService->processOutlookMail($request->get('email')); + } catch (\Exception $e) { return new JsonResponse([ - 'alertClass' => 'danger', - 'alertMessage' => "No mailbox found with id '$id'.", - ], 404); + 'success' => false, + 'message' => $e->getMessage(), + 'params' => $request->get('email') + ], 500); } - $mailboxConfiguration = new MailboxConfiguration(); - - foreach ($existingMailboxConfiguration->getMailboxes() as $configuration) { - if ($configuration->getId() == $id) { - continue; - } + $responseMessage = $processedThread['message']; - $mailboxConfiguration->addMailbox($configuration); + if (! empty($processedThread['content']['from'])) { + $responseMessage = "Received email from " . $processedThread['content']['from']. ". " . $responseMessage; } - file_put_contents($mailboxService->getPathToConfigurationFile(), (string) $mailboxConfiguration); + if ( + ! empty($processedThread['content']['ticket']) + && !empty($processedThread['content']['thread']) + ) { + $responseMessage .= " [tickets/" . $processedThread['content']['ticket'] . "/#" . $processedThread['content']['ticket'] . "]"; + } else if (! empty($processedThread['content']['ticket'])) { + $responseMessage .= " [tickets/" . $processedThread['content']['ticket'] . "]"; + } return new JsonResponse([ - 'alertClass' => 'success', - 'alertMessage' => $this->translator->trans('Mailbox configuration removed successfully.'), + 'success' => true, + 'message' => $responseMessage, ]); } } diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index fc4b31e..5a73624 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -18,24 +18,41 @@ public function getConfigTreeBuilder() ->node('enable_delimiter', 'boolean')->defaultValue(false)->end() ->end() ->end() + ->node('default_mailbox', 'scalar')->defaultValue(null)->end() ->node('mailboxes', 'array') ->arrayPrototype() ->children() ->node('name', 'scalar')->cannotBeEmpty()->end() - ->node('enabled', 'boolean')->defaultFalse()->end() - ->node('deleted', 'boolean')->defaultFalse()->end() - ->node('smtp_server', 'array') - ->children() - ->node('mailer_id', 'scalar')->defaultValue('default')->end() - ->end() - ->end() + ->node('enabled', 'boolean')->defaultTrue()->end() + ->node('disable_outbound_emails', 'boolean')->defaultFalse()->end() + ->node('use_strict_mode', 'boolean')->defaultFalse()->end() ->node('imap_server', 'array') ->children() ->node('host', 'scalar')->cannotBeEmpty()->end() ->node('username', 'scalar')->cannotBeEmpty()->end() + ->node('client', 'scalar')->end() ->node('password', 'scalar')->end() + ->node('type', 'scalar')->end() + ->end() + ->end() + ->node('smtp_swift_mailer_server', 'array') + ->children() + ->node('mailer_id', 'scalar')->defaultValue(null) + ->end() ->end() ->end() + ->node('smtp_server', 'array') + ->children() + ->node('host', 'scalar')->cannotBeEmpty()->end() + ->node('port', 'scalar')->end() + ->node('username', 'scalar')->cannotBeEmpty()->end() + ->node('client', 'scalar')->end() + ->node('password', 'scalar')->end() + ->node('type', 'scalar')->end() + ->node('sender_address', 'scalar')->defaultValue(null) + ->end() + ->end() + ->end() ->end() ->end() ->end() diff --git a/EventListener/Mailer.php b/EventListener/Mailer.php new file mode 100644 index 0000000..67beaa9 --- /dev/null +++ b/EventListener/Mailer.php @@ -0,0 +1,82 @@ +mailboxService = $mailboxService; + } + + public function onMailerConfigurationUpdated(ConfigurationUpdatedEvent $event) + { + $isUpdateRequiredFlag = false; + $updatedConfiguration = $event->getUpdatedMailerConfiguration(); + $existingConfiguration = $event->getExistingMailerConfiguration(); + + if ($updatedConfiguration->getId() == $existingConfiguration->getId()) { + // We only need to update if the mailer configuration's id has changed + // or if it has been disabled. + + return; + } + + $mailboxConfiguration = $this->mailboxService->parseMailboxConfigurations(true); + + foreach ($mailboxConfiguration->getMailboxes() as $existingMailbox) { + if ($existingMailbox->getMailerConfiguration()->getId() == $existingConfiguration->getId()) { + // Disable mailbox and update configuration + $mailbox = new Mailbox($existingMailbox->getId()); + $mailbox->setName($existingMailbox->getName()) + ->setIsEnabled($existingMailbox->getIsEnabled()) + ->setImapConfiguration($existingMailbox->getImapConfiguration()) + ->setMailerConfiguration($updatedConfiguration); + + $isUpdateRequiredFlag = true; + $mailboxConfiguration->removeMailbox($existingMailbox); + $mailboxConfiguration->addMailbox($mailbox); + } + } + + if (true === $isUpdateRequiredFlag) { + file_put_contents($this->mailboxService->getPathToConfigurationFile(), (string) $mailboxConfiguration); + } + + return; + } + + public function onMailerConfigurationRemoved(ConfigurationRemovedEvent $event) + { + $isUpdateRequiredFlag = false; + $configuration = $event->getMailerConfiguration(); + $mailboxConfiguration = $this->mailboxService->parseMailboxConfigurations(); + + foreach ($mailboxConfiguration->getMailboxes() as $existingMailbox) { + if (null != $existingMailbox->getMailerConfiguration() && $existingMailbox->getMailerConfiguration()->getId() == $configuration->getId()) { + // Disable mailbox and update configuration + $mailbox = new Mailbox($existingMailbox->getId()); + $mailbox->setName($existingMailbox->getName()) + ->setIsEnabled(false) + ->setImapConfiguration($existingMailbox->getImapConfiguration()); + + $isUpdateRequiredFlag = true; + $mailboxConfiguration->removeMailbox($existingMailbox); + $mailboxConfiguration->addMailbox($mailbox); + } + } + + if (true === $isUpdateRequiredFlag) { + file_put_contents($this->mailboxService->getPathToConfigurationFile(), (string) $mailboxConfiguration); + } + + return; + } +} \ No newline at end of file diff --git a/LICENSE b/LICENSE deleted file mode 100644 index b0c7630..0000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 UVdesk - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..2b9241e --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,47 @@ +Open Software License ("OSL") v. 3.0 + +This Open Software License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Open Software License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, with the proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be licensed under this Open Software License; + + 4. to perform the Original Work publicly; + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including 'fair use' or 'fair dealing'). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright (C) 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Open Software License" or "OSL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. \ No newline at end of file diff --git a/README.md b/README.md index 590c8a3..816b790 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,8 @@ $ composer require uvdesk/mailbox-component License -------------- -The **Mailbox** component and libraries included within the bundle are released under the MIT or BSD license. +The **Mailbox** component and libraries included within the bundle are released under the [OSL-3.0 license][3] [1]: https://www.uvdesk.com/ -[2]: https://getcomposer.org/ \ No newline at end of file +[2]: https://getcomposer.org/ +[3]: https://github.com/uvdesk/mailbox-component/blob/master/LICENSE.txt \ No newline at end of file diff --git a/Resources/config/routes/private.yaml b/Resources/config/routes/private.yaml index d0fb536..c974ceb 100644 --- a/Resources/config/routes/private.yaml +++ b/Resources/config/routes/private.yaml @@ -23,3 +23,11 @@ helpdesk_member_mailbox_remove_configuration_xhr: helpdesk_member_mailbox_direct_convert_mail: path: /processRawEmail controller: Webkul\UVDesk\MailboxBundle\Controller\MailboxChannelXHR::processRawContentMail + +helpdesk_member_outlook_mailbox_notification: + path: /mailbox/outlook/listener + controller: Webkul\UVDesk\MailboxBundle\Controller\MailboxChannelXHR::processOutlookMailXHR + +helpdesk_member_mailbox_notification: + path: /mailbox/listener + controller: Webkul\UVDesk\MailboxBundle\Controller\MailboxChannelXHR::processMailXHR diff --git a/Resources/views/listConfigurations.html.twig b/Resources/views/listConfigurations.html.twig index 9ed54cb..276468e 100644 --- a/Resources/views/listConfigurations.html.twig +++ b/Resources/views/listConfigurations.html.twig @@ -221,7 +221,7 @@ globalMessageResponse = null; }, error: function (model, xhr, options) { - if(url = xhr.getResponseHeader('Location')) + if (url = xhr.getResponseHeader('Location')) window.location = url; } }); @@ -237,6 +237,7 @@ }, render: function() { this.$el.html(this.template(this.model)); + return this; }, confirmRemove: function(e) { diff --git a/Resources/views/manageConfigurations.html.twig b/Resources/views/manageConfigurations.html.twig index f4a759c..a24d076 100644 --- a/Resources/views/manageConfigurations.html.twig +++ b/Resources/views/manageConfigurations.html.twig @@ -85,6 +85,7 @@ + {# Default Mailbox #}