vendor\uvdesk\mailbox-component\Console\RefreshMailboxCommand.php line 130

Open in your IDE?
  1. <?php
  2. namespace Webkul\UVDesk\MailboxBundle\Console;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Symfony\Component\Console\Command\Command;
  5. use Symfony\Component\Console\Input\InputOption;
  6. use Symfony\Component\Console\Input\InputArgument;
  7. use Symfony\Component\Console\Input\InputInterface;
  8. use Symfony\Component\Console\Output\OutputInterface;
  9. use Symfony\Component\DependencyInjection\ContainerInterface;
  10. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  11. class RefreshMailboxCommand extends Command
  12. {
  13.     private $container;
  14.     private $entityManager;
  15.     public function __construct(ContainerInterface $containerEntityManagerInterface $entityManager)
  16.     {
  17.         $this->container $container;
  18.         $this->entityManager $entityManager;
  19.         parent::__construct();
  20.     }
  21.     protected function configure()
  22.     {
  23.         $this->setName('uvdesk:refresh-mailbox');
  24.         $this->setDescription('Check if any new emails have been received and process them into tickets');
  25.         $this->addArgument('emails'InputArgument::IS_ARRAY InputArgument::OPTIONAL"Email address of the mailboxes you wish to update");
  26.         $this->addOption('timestamp''t'InputOption::VALUE_REQUIRED"Fetch messages no older than the given timestamp");
  27.     }
  28.     protected function execute(InputInterface $inputOutputInterface $output):int
  29.     {
  30.         // Sanitize emails
  31.         $mailboxEmailCollection array_map(function ($email) {
  32.             return filter_var($emailFILTER_SANITIZE_EMAIL);
  33.         }, $input->getArgument('emails'));
  34.        
  35.         // Stop execution if no valid emails have been specified
  36.         if (empty($mailboxEmailCollection)) {
  37.             if (false === $input->getOption('no-interaction')) {
  38.                 $output->writeln("\n <comment>No valid mailbox emails specified.</comment>\n");
  39.             }
  40.             return Command::INVALID;
  41.         }
  42.         // Process mailboxes
  43.         $timestamp = new \DateTime(sprintf("-%u minutes", (int) ($input->getOption('timestamp') ?: 1440)));
  44.         $output->writeln("\n <comment>1. Processing uvdesk mailbox configuration.</comment>");
  45.         foreach ($mailboxEmailCollection as $mailboxEmail) {
  46.             try {
  47.                 $mailbox $this->container->get('uvdesk.mailbox')->getMailboxByEmail($mailboxEmail);
  48.                 if (false == $mailbox['enabled']) {
  49.                     if (false === $input->getOption('no-interaction')) {
  50.                         $output->writeln("\n <comment>Mailbox for email </comment><info>$mailboxEmail</info><comment> is not enabled.</comment>\n");
  51.                     }
  52.     
  53.                     continue;
  54.                 } else if (empty($mailbox['imap_server'])) {
  55.                     if (false === $input->getOption('no-interaction')) {
  56.                         $output->writeln("\n <comment>No imap configurations defined for email </comment><info>$mailboxEmail</info><comment>.</comment>\n");
  57.                     }
  58.     
  59.                     continue;
  60.                 }
  61.             } catch (\Exception $e) {
  62.                 if (false == $input->getOption('no-interaction')) {
  63.                     $output->writeln("\n <comment>Mailbox for email </comment><info>$mailboxEmail</info><comment> not found.</comment>\n");
  64.                     return Command::INVALID;
  65.                 }
  66.                 continue;
  67.             }
  68.             $output->writeln("\n <comment>2. Opening imap stream... </comment>");
  69.             $this->refreshMailbox($mailbox['imap_server']['host'], $mailbox['imap_server']['username'], base64_decode($mailbox['imap_server']['password']), $timestamp$output$mailbox);
  70.         }
  71.         return Command::SUCCESS;
  72.     }
  73.     public function refreshMailbox($server_host$server_username$server_password\DateTime $timestampOutputInterface $output$mailbox)
  74.     {
  75.         $imap imap_open($server_host$server_username$server_password);
  76.         $output->writeln("\n <comment>3. IMAP stream opened.</comment>");
  77.         if ($imap) {
  78.             $timeSpan $timestamp->format('d F Y');
  79.             $output->writeln("\n <comment>4. Fetching Email collection since </comment><info>$timeSpan</info><comment>.</comment>");
  80.             $emailCollection imap_search($imap'SINCE "' $timestamp->format('d F Y') . '"');
  81.             if (is_array($emailCollection)) {
  82.                 $emailCount count($emailCollection);
  83.                 $useSecureConnection $this->isSecureConnectionAvailable();
  84.                 $output->writeln("\n <comment>5. Total fetched email -> </comment><info>$emailCount</info><comment></comment>");
  85.                 $output->writeln("\n <comment>6. Starting to convert Emails into Tickets -> </comment>\n=============================================\n=============================================\n");
  86.                 $counter 1;
  87.                 
  88.                 foreach ($emailCollection as $id => $messageNumber) {
  89.                     $output->writeln("\n <comment> Converting email </comment><info>$counter</info><comment> out of </comment><info>$emailCount</info><comment>.</comment>");
  90.                     $message imap_fetchbody($imap$messageNumber"");
  91.                     $this->pushMessage($message$useSecureConnection$output);
  92.                     if (true == $mailbox['deleted']) {
  93.                         imap_delete($imap$messageNumber);
  94.                     }
  95.                     $counter ++;
  96.                 }
  97.                 $output->writeln("\n <comment>Mailbox refreshed successfully !!!</comment>");
  98.                 if (true == $mailbox['deleted']) {
  99.                     imap_expunge($imap);
  100.                     imap_close($imap,CL_EXPUNGE);
  101.                 }
  102.             }
  103.         }
  104.         return;
  105.     }
  106.     public function pushMessage($messagebool $secure false$output)
  107.     {
  108.         $router $this->container->get('router');
  109.         $router->getContext()->setHost($this->container->getParameter('uvdesk.site_url'));
  110.         $router->getContext()->setScheme(true === $secure 'https' 'http');
  111.         $curlHandler curl_init();
  112.         $requestUrl $router->generate('helpdesk_member_mailbox_notification', [], UrlGeneratorInterface::ABSOLUTE_URL);   
  113.         
  114.         curl_setopt($curlHandlerCURLOPT_HEADER0);
  115.         curl_setopt($curlHandlerCURLOPT_RETURNTRANSFER1);
  116.         curl_setopt($curlHandlerCURLOPT_POST1);
  117.         curl_setopt($curlHandlerCURLOPT_URL$requestUrl);
  118.         curl_setopt($curlHandlerCURLOPT_POSTFIELDShttp_build_query(['email' => $message]));
  119.         $curlResponse curl_exec($curlHandler);
  120.         if ($curlResponse != 200 ) {
  121.             $curlResponse $this->getTagValue($curlResponse'title');
  122.             $output->writeln("\n <comment> Error -> </comment><info>$curlResponse</info><comment></comment>");
  123.             exit();
  124.         }
  125.         curl_close($curlHandler);
  126.     }
  127.     function getTagValue($string$tag)
  128.     {
  129.         $pattern "/<{$tag}>(.*?)<\/{$tag}>/s";
  130.         preg_match($pattern$string$matches);
  131.         return isset($matches[1]) ? $matches[1] : '';
  132.     }
  133.     protected function isSecureConnectionAvailable()
  134.     {
  135.         $headers = [CURLOPT_NOBODY => trueCURLOPT_HEADER => false];
  136.         $curlHandler curl_init('https://' $this->container->getParameter('uvdesk.site_url'));
  137.         curl_setopt_array($curlHandler$headers);
  138.         curl_exec($curlHandler);
  139.         $isSecureRequestAvailable curl_errno($curlHandler) === true false;
  140.         curl_close($curlHandler);
  141.         return $isSecureRequestAvailable;
  142.     }
  143. }