vendor/uvdesk/mailbox-component/Console/RefreshMailboxCommand.php line 134

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.     ini_set('memory_limit','-1');
  76.         $imap imap_open($server_host$server_username$server_password);
  77.         $output->writeln("\n <comment>3. IMAP stream opened.</comment>");
  78.         if ($imap) {
  79.             $timeSpan $timestamp->format('d F Y');
  80.             $output->writeln("\n <comment>4. Fetching Email collection since </comment><info>$timeSpan</info><comment>.</comment>");
  81.             $emailCollection imap_search($imap'SINCE "' $timestamp->format('d F Y') . '"');
  82.             if (is_array($emailCollection)) {
  83.                 $emailCount count($emailCollection);
  84.                 $useSecureConnection $this->isSecureConnectionAvailable();
  85.                 $output->writeln("\n <comment>5. Total fetched email -> </comment><info>$emailCount</info><comment></comment>");
  86.                 $output->writeln("\n <comment>6. Starting to convert Emails into Tickets -> </comment>\n=============================================\n=============================================\n");
  87.                 $counter 1;
  88.                 
  89.                 foreach ($emailCollection as $id => $messageNumber) {
  90.             if ($counter 1) {
  91.                     $output->writeln("\n <comment> Converting email </comment><info>$counter</info><comment> out of </comment><info>$emailCount</info><comment>.</comment>");
  92.                     $message imap_fetchbody($imap$messageNumber"");
  93.             $this->pushMessage($message$useSecureConnection$output);
  94.                     if (true == $mailbox['deleted']) {
  95.                         imap_delete($imap$messageNumber);
  96.                     }
  97.             }    
  98.                     $counter ++;
  99.                 }
  100.                 $output->writeln("\n <comment>Mailbox refreshed successfully !!!</comment>");
  101.                 if (true == $mailbox['deleted']) {
  102.                     imap_expunge($imap);
  103.                     imap_close($imap,CL_EXPUNGE);
  104.                 }
  105.             }
  106.         }
  107.         return;
  108.     }
  109.     public function pushMessage($messagebool $secure false$output)
  110.     {
  111.     ini_set('memory_limit','-1');
  112.         $router $this->container->get('router');
  113.         $router->getContext()->setHost($this->container->getParameter('uvdesk.site_url'));
  114.         $router->getContext()->setScheme(true === $secure 'https' 'http');
  115.         $curlHandler curl_init();
  116.         $requestUrl $router->generate('helpdesk_member_mailbox_notification', [], UrlGeneratorInterface::ABSOLUTE_URL);   
  117.         
  118.         curl_setopt($curlHandlerCURLOPT_HEADER0);
  119.         curl_setopt($curlHandlerCURLOPT_RETURNTRANSFER1);
  120.         curl_setopt($curlHandlerCURLOPT_POST1);
  121.         curl_setopt($curlHandlerCURLOPT_URL$requestUrl);
  122.         curl_setopt($curlHandlerCURLOPT_POSTFIELDShttp_build_query(['email' => $message]));
  123.         $curlResponse curl_exec($curlHandler);
  124.         if ($curlResponse != 200 ) {
  125.             $curlResponse $this->getTagValue($curlResponse'title');
  126.             $output->writeln("\n <comment> Error -> </comment><info>$curlResponse</info><comment></comment>");
  127.             exit();
  128.         }
  129.         curl_close($curlHandler);
  130.     }
  131.     function getTagValue($string$tag)
  132.     {
  133.         $pattern "/<{$tag}>(.*?)<\/{$tag}>/s";
  134.         preg_match($pattern$string$matches);
  135.         return isset($matches[1]) ? $matches[1] : '';
  136.     }
  137.     protected function isSecureConnectionAvailable()
  138.     {
  139.         $headers = [CURLOPT_NOBODY => trueCURLOPT_HEADER => false];
  140.         $curlHandler curl_init('https://' $this->container->getParameter('uvdesk.site_url'));
  141.         curl_setopt_array($curlHandler$headers);
  142.         curl_exec($curlHandler);
  143.         $isSecureRequestAvailable curl_errno($curlHandler) === true false;
  144.         curl_close($curlHandler);
  145.         return $isSecureRequestAvailable;
  146.     }
  147. }