vendor/uvdesk/core-framework/Services/TicketService.php line 756

Open in your IDE?
  1. <?php
  2. namespace Webkul\UVDesk\CoreFrameworkBundle\Services;
  3. use Doctrine\ORM\Query;
  4. use Symfony\Component\Yaml\Yaml;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpFoundation\RequestStack;
  9. use Webkul\UVDesk\CoreFrameworkBundle\Entity\User;
  10. use Webkul\UVDesk\CoreFrameworkBundle\Entity\AgentActivity;
  11. use Webkul\UVDesk\MailboxBundle\Utils\Mailbox\Mailbox;
  12. use Symfony\Component\EventDispatcher\GenericEvent;
  13. use Webkul\UVDesk\CoreFrameworkBundle\Entity\Ticket;
  14. use Webkul\UVDesk\CoreFrameworkBundle\Entity\Thread;
  15. use Webkul\UVDesk\CoreFrameworkBundle\Entity\Tag;
  16. use Webkul\UVDesk\CoreFrameworkBundle\Entity\TicketType;
  17. use Webkul\UVDesk\CoreFrameworkBundle\Entity\TicketStatus;
  18. use Webkul\UVDesk\CoreFrameworkBundle\Entity\TicketPriority;
  19. use Webkul\UVDesk\CoreFrameworkBundle\Entity\SupportRole;
  20. use Webkul\UVDesk\CoreFrameworkBundle\Entity\Website;
  21. use Webkul\UVDesk\CoreFrameworkBundle\Entity\SupportGroup;
  22. use Webkul\UVDesk\CoreFrameworkBundle\Entity\SupportTeam;
  23. use Webkul\UVDesk\CoreFrameworkBundle\Entity\SupportLabel;
  24. use Webkul\UVDesk\CoreFrameworkBundle\Entity\SavedReplies;
  25. use Webkul\UVDesk\CoreFrameworkBundle\Entity\Attachment;
  26. use Webkul\UVDesk\MailboxBundle\Utils\MailboxConfiguration;
  27. use Webkul\UVDesk\CoreFrameworkBundle\Utils\TokenGenerator;
  28. use Symfony\Component\DependencyInjection\ContainerInterface;
  29. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  30. use Webkul\UVDesk\CoreFrameworkBundle\Workflow\Events as CoreWorkflowEvents;
  31. use Webkul\UVDesk\CoreFrameworkBundle\Services\FileUploadService;
  32. use Webkul\UVDesk\CoreFrameworkBundle\Services\UserService;
  33. use UVDesk\CommunityPackages\UVDesk\FormComponent\Entity;
  34. use Webkul\UVDesk\MailboxBundle\Utils\Imap\Configuration as ImapConfiguration;
  35. use Symfony\Component\Filesystem\Filesystem;
  36. use Webkul\UVDesk\SupportCenterBundle\Entity\Article;
  37. use Webkul\UVDesk\SupportCenterBundle\Entity\KnowledgebaseWebsite;
  38. use Webkul\UVDesk\AutomationBundle\Entity\PreparedResponses;
  39. use UVDesk\CommunityPackages\UVDesk as UVDeskCommunityPackages;
  40. class TicketService
  41. {
  42.     const PATH_TO_CONFIG '/config/packages/uvdesk_mailbox.yaml';
  43.     protected $container;
  44.     protected $requestStack;
  45.     protected $entityManager;
  46.     protected $fileUploadService;
  47.     protected $userService;
  48.     
  49.     public function __construct(
  50.         ContainerInterface $container
  51.         RequestStack $requestStack
  52.         EntityManagerInterface $entityManager
  53.         FileUploadService $fileUploadService,
  54.         UserService $userService)
  55.     {
  56.         $this->container $container;
  57.         $this->requestStack $requestStack;
  58.         $this->entityManager $entityManager;
  59.         $this->fileUploadService $fileUploadService;
  60.         $this->userService $userService;
  61.     }
  62.     public function getAllMailboxes()
  63.     {
  64.         $collection array_map(function ($mailbox) {
  65.             return [
  66.                 'id' => $mailbox->getId(),
  67.                 'name' => $mailbox->getName(),
  68.                 'isEnabled' => $mailbox->getIsEnabled(),
  69.                 'email'     => $mailbox->getImapConfiguration()->getUsername(),
  70.             ];
  71.         }, $this->parseMailboxConfigurations()->getMailboxes());
  72.         return $collection;
  73.     }
  74.     public function parseMailboxConfigurations(bool $ignoreInvalidAttributes false
  75.     {
  76.         $path $this->getPathToConfigurationFile();
  77.         if (!file_exists($path)) {
  78.             throw new \Exception("File '$path' not found.");
  79.         }
  80.         // Read configurations from package config.
  81.         $mailboxConfiguration = new MailboxConfiguration();
  82.         $swiftmailerService $this->container->get('swiftmailer.service');
  83.         $swiftmailerConfigurations $swiftmailerService->parseSwiftMailerConfigurations();
  84.         foreach (Yaml::parse(file_get_contents($path))['uvdesk_mailbox']['mailboxes'] ?? [] as $id => $params) {
  85.             // Swiftmailer Configuration
  86.             $swiftmailerConfiguration null;
  87.             foreach ($swiftmailerConfigurations as $configuration) {
  88.                 if ($configuration->getId() == $params['smtp_server']['mailer_id']) {
  89.                     $swiftmailerConfiguration $configuration;
  90.                     break;
  91.                 }
  92.             }
  93.             // IMAP Configuration
  94.             ($imapConfiguration ImapConfiguration::guessTransportDefinition($params['imap_server']['host']))
  95.                 ->setUsername($params['imap_server']['username'])
  96.                 ->setPassword($params['imap_server']['password']);
  97.             // Mailbox Configuration
  98.             ($mailbox = new Mailbox($id))
  99.                 ->setName($params['name'])
  100.                 ->setIsEnabled($params['enabled'])
  101.                 ->setImapConfiguration($imapConfiguration);
  102.             
  103.             if (!empty($swiftmailerConfiguration)) {
  104.                 $mailbox->setSwiftMailerConfiguration($swiftmailerConfiguration);
  105.             } else if (!empty($params['smtp_server']['mailer_id']) && true === $ignoreInvalidAttributes) {
  106.                 $mailbox->setSwiftMailerConfiguration($swiftmailerService->createConfiguration('smtp'$params['smtp_server']['mailer_id']));
  107.             }
  108.             $mailboxConfiguration->addMailbox($mailbox);
  109.         }
  110.         return $mailboxConfiguration;
  111.     }
  112.     public function getPathToConfigurationFile()
  113.     {
  114.         return $this->container->get('kernel')->getProjectDir() . self::PATH_TO_CONFIG;
  115.     }
  116.     public function getRandomRefrenceId($email null)
  117.     {
  118.         $email = !empty($email) ? $email $this->container->getParameter('uvdesk.support_email.id');
  119.         $emailDomain substr($emailstrpos($email'@'));
  120.         return sprintf("<%s%s>"TokenGenerator::generateToken(20'0123456789abcdefghijklmnopqrstuvwxyz'), $emailDomain);
  121.     }
  122.     // @TODO: Refactor this out of this service. Use UserService::getSessionUser() instead.
  123.     public function getUser()
  124.     {
  125.         return $this->container->get('user.service')->getCurrentUser();
  126.     }
  127.     public function getDefaultType()
  128.     {
  129.         $typeCode $this->container->getParameter('uvdesk.default.ticket.type');
  130.         $ticketType $this->entityManager->getRepository(TicketType::class)->findOneByCode($typeCode);
  131.         return !empty($ticketType) ? $ticketType null;
  132.     }
  133.     public function getDefaultStatus()
  134.     {
  135.         $statusCode $this->container->getParameter('uvdesk.default.ticket.status');
  136.         $ticketStatus $this->entityManager->getRepository(TicketStatus::class)->findOneByCode($statusCode);
  137.         return !empty($ticketStatus) ? $ticketStatus null;
  138.     }
  139.     public function getDefaultPriority()
  140.     {
  141.         $priorityCode $this->container->getParameter('uvdesk.default.ticket.priority');
  142.         $ticketPriority $this->entityManager->getRepository(TicketPriority::class)->findOneByCode($priorityCode);
  143.         return !empty($ticketPriority) ? $ticketPriority null;
  144.     }
  145.     public function appendTwigSnippet($snippet '')
  146.     {
  147.         switch ($snippet) {
  148.             case 'createMemberTicket':
  149.                 return $this->getMemberCreateTicketSnippet();
  150.                 break;
  151.             default:
  152.                 break;
  153.         }
  154.         return '';
  155.     }
  156.     public function getMemberCreateTicketSnippet()
  157.     {   
  158.         $twigTemplatingEngine $this->container->get('twig');
  159.         $ticketTypeCollection $this->entityManager->getRepository(TicketType::class)->findByIsActive(true);
  160.         
  161.         try {
  162.             if ($this->userService->isfileExists('apps/uvdesk/custom-fields')) {
  163.                 $headerCustomFields $this->container->get('uvdesk_package_custom_fields.service')->getCustomFieldsArray('user');
  164.             } else if ($this->userService->isfileExists('apps/uvdesk/form-component')) {
  165.                 $headerCustomFields $this->container->get('uvdesk_package_form_component.service')->getCustomFieldsArray('user');
  166.             }
  167.         } catch (\Exception $e) {
  168.             // @TODO: Log execption message
  169.         }
  170.         return $twigTemplatingEngine->render('@UVDeskCoreFramework/Snippets/createMemberTicket.html.twig', [
  171.             'ticketTypeCollection' => $ticketTypeCollection,
  172.             'headerCustomFields' => $headerCustomFields ?? null,
  173.         ]);
  174.     }
  175.     public function getCustomerCreateTicketCustomFieldSnippet()
  176.     {
  177.         try {
  178.             if ($this->userService->isfileExists('apps/uvdesk/custom-fields')) {
  179.                 $customFields $this->container->get('uvdesk_package_custom_fields.service')->getCustomFieldsArray('customer');
  180.             } else if ($this->userService->isfileExists('apps/uvdesk/form-component')) {
  181.                 $customFields $this->container->get('uvdesk_package_form_component.service')->getCustomFieldsArray('customer');
  182.             }
  183.         } catch (\Exception $e) {
  184.             // @TODO: Log execption message
  185.         }
  186.         return $customFields ?? null;
  187.     }
  188.     public function createTicket(array $params = [])
  189.     {
  190.         $thread $this->entityManager->getRepository(Thread::class)->findOneByMessageId($params['messageId']);
  191.         if (empty($thread)) {
  192.             $user $this->entityManager->getRepository(User::class)->findOneByEmail($params['from']);
  193.             if (empty($user) || null == $user->getCustomerInstance()) {
  194.                 $role $this->entityManager->getRepository(SupportRole::class)->findOneByCode($params['role']);
  195.                 if (empty($role)) {
  196.                     throw new \Exception("The requested role '" $params['role'] . "' does not exist.");
  197.                 }
  198.                 
  199.                 // Create User Instance
  200.                 $user $this->container->get('user.service')->createUserInstance($params['from'], $params['name'], $role, [
  201.                     'source' => strtolower($params['source']),
  202.                     'active' => true,
  203.                 ]);
  204.             }
  205.             $params['role'] = 4;
  206.             $params['customer'] = $params['user'] = $user;
  207.             return $this->createTicketBase($params);
  208.         }
  209.         return;
  210.     }
  211.     public function createTicketBase(array $ticketData = [])
  212.     {
  213.         if ('email' == $ticketData['source']) {
  214.             try {
  215.                 if (array_key_exists('UVDeskMailboxBundle'$this->container->getParameter('kernel.bundles'))) {
  216.                     $mailbox $this->container->get('uvdesk.mailbox')->getMailboxByEmail($ticketData['mailboxEmail']);
  217.                     $ticketData['mailboxEmail'] = $mailbox['email'];
  218.                 }
  219.             } catch (\Exception $e) {
  220.                 // No mailbox found for this email. Skip ticket creation.
  221.                 return;
  222.             }
  223.         }
  224.         // Set Defaults
  225.         $ticketType = !empty($ticketData['type']) ? $ticketData['type'] : $this->getDefaultType();
  226.         $ticketStatus = !empty($ticketData['status']) ? $ticketData['status'] : $this->getDefaultStatus();
  227.         $ticketPriority = !empty($ticketData['priority']) ? $ticketData['priority'] : $this->getDefaultPriority();
  228.         $ticketMessageId 'email' == $ticketData['source'] ? (!empty($ticketData['messageId']) ? $ticketData['messageId'] : null) : $this->getRandomRefrenceId();
  229.         $ticketData['type'] = $ticketType;
  230.         $ticketData['status'] = $ticketStatus;
  231.         $ticketData['priority'] = $ticketPriority;
  232.         $ticketData['messageId'] = $ticketMessageId;
  233.         $ticketData['isTrashed'] = false;
  234.         $ticket = new Ticket();
  235.         foreach ($ticketData as $property => $value) {
  236.             $callable 'set' ucwords($property);
  237.             if (method_exists($ticket$callable)) {
  238.                 $ticket->$callable($value);
  239.             }
  240.         }
  241.         $this->entityManager->persist($ticket);
  242.         $this->entityManager->flush();
  243.         return $this->createThread($ticket$ticketData);
  244.     }
  245.     
  246.     public function createThread(Ticket $ticket, array $threadData)
  247.     {
  248.         $threadData['isLocked'] = 0;
  249.       
  250.         if ('forward' === $threadData['threadType']) {
  251.             $threadData['replyTo'] = $threadData['to'];
  252.         }
  253.         $collaboratorEmails array_merge(!empty($threadData['cccol']) ? $threadData['cccol'] : [], !empty($threadData['cc']) ? $threadData['cc'] : []);
  254.         if (!empty($collaboratorEmails)) {
  255.             $threadData['cc'] = $collaboratorEmails;
  256.         }
  257.    
  258.         $thread = new Thread();
  259.         $thread->setTicket($ticket);
  260.         $thread->setCreatedAt(new \DateTime());
  261.         $thread->setUpdatedAt(new \DateTime());
  262.         if ($threadData['threadType'] != "note") {
  263.             foreach ($threadData as $property => $value) {
  264.                 if (!empty($value)) {
  265.                     $callable 'set' ucwords($property);
  266.                     if (method_exists($thread$callable)) {
  267.                         $thread->$callable($value);
  268.                     }
  269.                 }
  270.             }
  271.         } else {
  272.             $this->setTicketNotePlaceholderValue($thread$threadData$ticket);
  273.         }
  274.         // Update ticket reference ids is thread message id is defined
  275.         if (null != $thread->getMessageId() && false === strpos($ticket->getReferenceIds(), $thread->getMessageId())) {
  276.             $updatedReferenceIds $ticket->getReferenceIds() . ' ' $thread->getMessageId();            
  277.             $ticket->setReferenceIds($updatedReferenceIds);
  278.             $this->entityManager->persist($ticket);
  279.         }
  280.         if ('reply' === $threadData['threadType']) {
  281.             if ('agent' === $threadData['createdBy']) {
  282.                 // Ticket has been updated by support agents, mark as agent replied | customer view pending
  283.                 $ticket->setIsCustomerViewed(false);
  284.                 $ticket->setIsReplied(true);
  285.                 $customerName $ticket->getCustomer()->getFirstName().' '.$ticket->getCustomer()->getLastName();
  286.                 $agentActivity = new AgentActivity();
  287.                 $agentActivity->setThreadType('reply');
  288.                 $agentActivity->setTicket($ticket);
  289.                 $agentActivity->setAgent($thread->getUser());
  290.                 $agentActivity->setCustomerName($customerName);
  291.                 $agentActivity->setAgentName('agent');
  292.                 $agentActivity->setCreatedAt(new \DateTime());
  293.                 $this->entityManager->persist($agentActivity);
  294.             } else {
  295.                 // Ticket has been updated by customer, mark as agent view | reply pending
  296.                 $ticket->setIsAgentViewed(false);
  297.                 $ticket->setIsReplied(false);
  298.             }
  299.             $this->entityManager->persist($ticket);
  300.         } else if ('create' === $threadData['threadType']) {
  301.             $ticket->setIsReplied(false);
  302.             $this->entityManager->persist($ticket);
  303.             $customerName $ticket->getCustomer()->getFirstName().' '.$ticket->getCustomer()->getLastName();
  304.             $agentActivity = new AgentActivity();
  305.             $agentActivity->setThreadType('create');
  306.             $agentActivity->setTicket($ticket);
  307.             $agentActivity->setAgent($thread->getUser());
  308.             $agentActivity->setCustomerName($customerName );
  309.             $agentActivity->setAgentName('agent');
  310.             $agentActivity->setCreatedAt(new \DateTime());
  311.             $this->entityManager->persist($agentActivity);
  312.         }
  313.         
  314.         $ticket->currentThread $this->entityManager->getRepository(Thread::class)->getTicketCurrentThread($ticket);
  315.         
  316.         $this->entityManager->persist($thread);
  317.         $this->entityManager->flush();
  318.         
  319.         $ticket->createdThread $thread;
  320.         // Uploading Attachments
  321.         if (!empty($threadData['attachments'])) {
  322.             if ('email' == $threadData['source']) {
  323.                 $this->saveThreadEmailAttachments($thread$threadData['attachments']);
  324.             } else if (!empty($threadData['attachments'])) {
  325.                 $this->saveThreadAttachment($thread$threadData['attachments']);
  326.             }
  327.         }
  328.         return $thread;
  329.     }
  330.     public function setTicketNotePlaceholderValue($thread$threadData$ticket)
  331.     {
  332.         if (!empty($threadData)) {
  333.             foreach ($threadData as $property => $value) {
  334.                 if (!empty($value)) {
  335.                     $callable 'set' ucwords($property);
  336.                     if (method_exists($thread$callable)) {
  337.                         if($callable != "setMessage") {
  338.                             $thread->$callable($value);
  339.                         } else {
  340.                             $notesPlaceholders $this->getNotePlaceholderValues($ticket'customer');
  341.                             $content $value;
  342.                             foreach ($notesPlaceholders as $key => $val) {
  343.                                 if(strpos($value"{%$key%}") !== false){
  344.                                     $content strtr($value, ["{%$key%}" => $val"{% $key %}" => $val]);
  345.                                 }
  346.                             }
  347.                             
  348.                             $content stripslashes($content);
  349.                             $thread->$callable($content);
  350.                         }
  351.                     }
  352.                 }
  353.             }
  354.         }
  355.     }
  356.     public function saveThreadAttachment($thread, array $attachments)
  357.     {
  358.         $prefix 'threads/' $thread->getId();
  359.         $uploadManager $this->container->get('uvdesk.core.file_system.service')->getUploadManager();
  360.         foreach ($attachments as $attachment) {
  361.             $uploadedFileAttributes $uploadManager->uploadFile($attachment$prefix);
  362.             if (!empty($uploadedFileAttributes['path'])) {
  363.                 ($threadAttachment = new Attachment())
  364.                     ->setThread($thread)
  365.                     ->setName($uploadedFileAttributes['name'])
  366.                     ->setPath($uploadedFileAttributes['path'])
  367.                     ->setSize($uploadedFileAttributes['size'])
  368.                     ->setContentType($uploadedFileAttributes['content-type']);
  369.                 
  370.                 $this->entityManager->persist($threadAttachment);
  371.             }
  372.         }
  373.         $this->entityManager->flush();
  374.     }
  375.     public function saveThreadEmailAttachments($thread, array $attachments)
  376.     {
  377.         $prefix 'threads/' $thread->getId();
  378.         $uploadManager $this->container->get('uvdesk.core.file_system.service')->getUploadManager();
  379.         
  380.         // Upload thread attachments
  381.         foreach ($attachments as $attachment) {
  382.             $uploadedFileAttributes $uploadManager->uploadEmailAttachment($attachment$prefix);
  383.             
  384.             if (!empty($uploadedFileAttributes['path'])) {
  385.                 ($threadAttachment = new Attachment())
  386.                     ->setThread($thread)
  387.                     ->setName($uploadedFileAttributes['name'])
  388.                     ->setPath($uploadedFileAttributes['path'])
  389.                     ->setSize($uploadedFileAttributes['size'])
  390.                     ->setContentType($uploadedFileAttributes['content-type']);
  391.                 
  392.                 $this->entityManager->persist($threadAttachment);
  393.             }
  394.         }
  395.         $this->entityManager->flush();
  396.     }
  397.     public function getTypes()
  398.     {
  399.         static $types;
  400.         if (null !== $types)
  401.             return $types;
  402.         $qb $this->entityManager->createQueryBuilder();
  403.         $qb->select('tp.id','tp.code As name')->from(TicketType::class, 'tp')
  404.                 ->andwhere('tp.isActive = 1')
  405.                 ->orderBy('tp.code''ASC');
  406.         return $types $qb->getQuery()->getArrayResult();
  407.     }
  408.     public function getStatus()
  409.     {
  410.         static $statuses;
  411.         if (null !== $statuses)
  412.             return $statuses;
  413.         $qb $this->entityManager->createQueryBuilder();
  414.         $qb->select('ts')->from(TicketStatus::class, 'ts');
  415.         // $qb->orderBy('ts.sortOrder', Criteria::ASC);
  416.         return $statuses $qb->getQuery()->getArrayResult();
  417.     }
  418.     public function getTicketTotalThreads($ticketId)
  419.     {
  420.         $qb $this->entityManager->createQueryBuilder();
  421.         $qb->select('COUNT(th.id) as threadCount')->from(Ticket::class, 't')
  422.             ->leftJoin('t.threads''th')
  423.             ->andWhere('t.id = :ticketId')
  424.             ->andWhere('th.threadType = :threadType')
  425.             ->setParameter('threadType','reply')
  426.             ->setParameter('ticketId'$ticketId);
  427.         $qb $this->entityManager->createQueryBuilder();
  428.         $qb->select('COUNT(t.id) as threadCount')->from(Thread::class, 't')
  429.             ->andWhere('t.ticket = :ticketId')
  430.             ->andWhere('t.threadType = :threadType')
  431.             ->setParameter('threadType','reply')
  432.             ->setParameter('ticketId'$ticketId);
  433.         return $qb->getQuery()->getSingleScalarResult();
  434.     }
  435.     public function getTicketTags($request null)
  436.     {
  437.         $qb $this->entityManager->createQueryBuilder();
  438.         $qb->select('tg')->from(Tag::class, 'tg');
  439.         if($request) {
  440.             $qb->andwhere("tg.name LIKE :tagName");
  441.             $qb->setParameter('tagName''%'.urldecode($request->query->get('query')).'%');
  442.             $qb->andwhere("tg.id NOT IN (:ids)");
  443.             $qb->setParameter('ids'explode(',',urldecode($request->query->get('not'))));
  444.         }
  445.         return $qb->getQuery()->getArrayResult();
  446.     }
  447.     
  448.     public function paginateMembersTicketCollection(Request $request)
  449.     {
  450.         $params $request->query->all();
  451.         $activeUser $this->container->get('user.service')->getSessionUser();
  452.         $activeUserTimeZone $this->entityManager->getRepository(Website::class)->findOneBy(['code' => 'Knowledgebase']);
  453.         $agentTimeZone = !empty($activeUser->getTimezone()) ? $activeUser->getTimezone() : $activeUserTimeZone->getTimezone();
  454.         $agentTimeFormat = !empty($activeUser->getTimeformat()) ? $activeUser->getTimeformat() : $activeUserTimeZone->getTimeformat();
  455.         $ticketRepository $this->entityManager->getRepository(Ticket::class);
  456.         $website $this->entityManager->getRepository(Website::class)->findOneBy(['code' => 'helpdesk']);
  457.         $timeZone $website->getTimezone();
  458.         $timeFormat $website->getTimeformat();
  459.         $supportGroupReference $this->entityManager->getRepository(User::class)->getUserSupportGroupReferences($activeUser);
  460.         $supportTeamReference  $this->entityManager->getRepository(User::class)->getUserSupportTeamReferences($activeUser);
  461.         // Get base query
  462.         $baseQuery $ticketRepository->prepareBaseTicketQuery($activeUser$supportGroupReference$supportTeamReference$params);
  463.         $ticketTabs $ticketRepository->getTicketTabDetails($activeUser$supportGroupReference$supportTeamReference$params);
  464.         // Apply Pagination
  465.         $pageNumber = !empty($params['page']) ? (int) $params['page'] : 1;
  466.         $itemsLimit = !empty($params['limit']) ? (int) $params['limit'] : $ticketRepository::DEFAULT_PAGINATION_LIMIT;
  467.         if (isset($params['repliesLess']) || isset($params['repliesMore'])) {
  468.             $paginationOptions = ['wrap-queries' => true];
  469.             $paginationQuery $baseQuery->getQuery()
  470.                 ->setHydrationMode(Query::HYDRATE_ARRAY);
  471.         } else {
  472.             $paginationOptions = ['distinct' => true];
  473.             $paginationQuery $baseQuery->getQuery()
  474.                 ->setHydrationMode(Query::HYDRATE_ARRAY)
  475.                 ->setHint('knp_paginator.count', isset($params['status']) ? $ticketTabs[$params['status']] : $ticketTabs[1]);
  476.         }
  477.         $pagination $this->container->get('knp_paginator')->paginate($paginationQuery$pageNumber$itemsLimit$paginationOptions);
  478.         // Process Pagination Response
  479.         $ticketCollection = [];
  480.         $paginationParams $pagination->getParams();
  481.         $paginationData $pagination->getPaginationData();
  482.         $paginationParams['page'] = 'replacePage';
  483.         $paginationData['url'] = '#' $this->container->get('uvdesk.service')->buildPaginationQuery($paginationParams);
  484.         // $container->get('default.service')->buildSessionUrl('ticket',$queryParameters);
  485.         $ticketThreadCountQueryTemplate $this->entityManager->createQueryBuilder()
  486.             ->select('COUNT(thread.id) as threadCount')
  487.             ->from(Ticket::class, 'ticket')
  488.             ->leftJoin('ticket.threads''thread')
  489.             ->where('ticket.id = :ticketId')
  490.             ->andWhere('thread.threadType = :threadType')->setParameter('threadType''reply');
  491.         
  492.         foreach ($pagination->getItems() as $ticketDetails) {
  493.             $ticket array_shift($ticketDetails);
  494.             $ticketThreadCountQuery = clone $ticketThreadCountQueryTemplate;
  495.             $ticketThreadCountQuery->setParameter('ticketId'$ticket['id']);
  496.             $totalTicketReplies = (int) $ticketThreadCountQuery->getQuery()->getSingleScalarResult();
  497.             $ticketHasAttachments false;
  498.             $dbTime $ticket['createdAt'];
  499.             
  500.             $formattedTime$this->fomatTimeByPreference($dbTime,$timeZone,$timeFormat,$agentTimeZone,$agentTimeFormat);
  501.             $currentDateTime  = new \DateTime('now');
  502.             if($this->getLastReply($ticket['id'])) {
  503.                 $lastRepliedTime 
  504.                 $this->time2string($currentDateTime->getTimeStamp() - $this->getLastReply($ticket['id'])['createdAt']->getTimeStamp());
  505.             } else {
  506.                 $lastRepliedTime 
  507.                 $this->time2string($currentDateTime->getTimeStamp() - $ticket['createdAt']->getTimeStamp());
  508.             }
  509.             $ticketResponse = [
  510.                 'id' => $ticket['id'],
  511.                 'subject' => $ticket['subject'],
  512.                 'isStarred' => $ticket['isStarred'],
  513.                 'isAgentView' => $ticket['isAgentViewed'],
  514.                 'isTrashed' => $ticket['isTrashed'],
  515.                 'source' => $ticket['source'],
  516.                 'group' => $ticketDetails['groupName'],
  517.                 'team' => $ticketDetails['teamName'],
  518.                 'priority' => $ticket['priority'],
  519.                 'type' => $ticketDetails['typeName'],
  520.                 'timestamp' => $formattedTime['dateTimeZone'],
  521.                 'formatedCreatedAt' => $formattedTime['dateTimeZone']->format($formattedTime['timeFormatString']),
  522.                 'totalThreads' => $totalTicketReplies,
  523.                 'agent' => null,
  524.                 'customer' => null,
  525.                 'hasAttachments' => $ticketHasAttachments,
  526.                 'lastReplyTime' => $lastRepliedTime
  527.             ];
  528.            
  529.             if (!empty($ticketDetails['agentId'])) {
  530.                 $ticketResponse['agent'] = [
  531.                     'id' => $ticketDetails['agentId'],
  532.                     'name' => $ticketDetails['agentName'],
  533.                     'smallThumbnail' => $ticketDetails['smallThumbnail'],
  534.                 ];
  535.             }
  536.             if (!empty($ticketDetails['customerId'])) {
  537.                 $ticketResponse['customer'] = [
  538.                     'id' => $ticketDetails['customerId'],
  539.                     'name' => $ticketDetails['customerName'],
  540.                     'email' => $ticketDetails['customerEmail'],
  541.                     'smallThumbnail' => $ticketDetails['customersmallThumbnail'],
  542.                 ];
  543.             }
  544.             array_push($ticketCollection$ticketResponse);
  545.         }
  546.          
  547.         return [
  548.             'tickets' => $ticketCollection,
  549.             'pagination' => $paginationData,
  550.             'tabs' => $ticketTabs,
  551.             'labels' => [
  552.                 'predefind' => $this->getPredefindLabelDetails($activeUser$supportGroupReference$supportTeamReference$params),
  553.                 'custom' => $this->getCustomLabelDetails($this->container),
  554.             ],
  555.           
  556.         ];
  557.     }
  558.     // Convert Timestamp to day/hour/min
  559.     Public function time2string($time) {
  560.         $d floor($time/86400);
  561.         $_d = ($d 10 '0' '').$d;
  562.         $h floor(($time-$d*86400)/3600);
  563.         $_h = ($h 10 '0' '').$h;
  564.         $m floor(($time-($d*86400+$h*3600))/60);
  565.         $_m = ($m 10 '0' '').$m;
  566.         $s $time-($d*86400+$h*3600+$m*60);
  567.         $_s = ($s 10 '0' '').$s;
  568.         $time_str "0 minutes";
  569.         if($_d != 00)
  570.             $time_str $_d." ".'days';
  571.         elseif($_h != 00)
  572.             $time_str $_h." ".'hours';
  573.         elseif($_m != 00)
  574.             $time_str $_m." ".'minutes';
  575.         return $time_str." "."ago";
  576.     }
  577.     public function getPredefindLabelDetails(User $currentUser, array $supportGroupIds = [], array $supportTeamIds = [], array $params = [])
  578.     {
  579.         $data = array();
  580.         $queryBuilder $this->entityManager->createQueryBuilder();
  581.         $ticketRepository $this->entityManager->getRepository(Ticket::class);
  582.         $queryBuilder->select('COUNT(DISTINCT ticket.id) as ticketCount')->from(Ticket::class, 'ticket');
  583.             
  584.         // // applyFilter according to permission
  585.         $queryBuilder->where('ticket.isTrashed != 1');
  586.         $userInstance $currentUser->getAgentInstance();
  587.         if (!empty($userInstance) &&  'ROLE_AGENT' == $userInstance->getSupportRole()->getCode() 
  588.         && $userInstance->getTicketAccesslevel() != 1) {
  589.             $supportGroupIds implode(','$supportGroupIds);
  590.             $supportTeamIds implode(','$supportTeamIds);
  591.             if ($userInstance->getTicketAccesslevel() == 4) {
  592.                 $queryBuilder->andwhere('ticket.agent = ' $currentUser->getId());
  593.             } elseif ($userInstance->getTicketAccesslevel() == 2) {
  594.                 $query '';
  595.                 if ($supportGroupIds){
  596.                     $query .= ' OR supportGroup.id IN('.$supportGroupIds.') ';
  597.                 }
  598.                 if ($supportTeamIds) {
  599.                     $query .= ' OR supportTeam.id IN('.$supportTeamIds.') ';
  600.                 }
  601.                 $queryBuilder->leftJoin('ticket.supportGroup''supportGroup')
  602.                             ->leftJoin('ticket.supportTeam''supportTeam')
  603.                             ->andwhere('( ticket.agent = ' $currentUser->getId().$query.')');
  604.                     
  605.             } elseif ($userInstance->getTicketAccesslevel() == 3) {
  606.                 $query '';
  607.                 if ($supportTeamIds) {
  608.                     $query .= ' OR supportTeam.id IN('.$supportTeamIds.') ';
  609.                 }
  610.                 $queryBuilder->leftJoin('ticket.supportGroup''supportGroup')
  611.                             ->leftJoin('ticket.supportTeam''supportTeam')
  612.                             ->andwhere('( ticket.agent = ' $currentUser->getId().$query')');
  613.             }
  614.         }
  615.         // for all tickets count
  616.         $data['all'] = $queryBuilder->getQuery()->getSingleScalarResult();
  617.         // for new tickets count
  618.         $newQb = clone $queryBuilder;
  619.         $newQb->andwhere('ticket.isNew = 1');
  620.         $data['new'] = $newQb->getQuery()->getSingleScalarResult();
  621.         // for unassigned tickets count
  622.         $unassignedQb = clone $queryBuilder;
  623.         $unassignedQb->andwhere("ticket.agent is NULL");
  624.         $data['unassigned'] = $unassignedQb->getQuery()->getSingleScalarResult();
  625.         // for unanswered ticket count
  626.         $unansweredQb = clone $queryBuilder;
  627.         $unansweredQb->andwhere('ticket.isReplied = 0');
  628.         $data['notreplied'] = $unansweredQb->getQuery()->getSingleScalarResult();
  629.         // for my tickets count
  630.         $mineQb = clone $queryBuilder;
  631.         $mineQb->andWhere("ticket.agent = :agentId")
  632.                 ->setParameter('agentId'$currentUser->getId());
  633.         $data['mine'] = $mineQb->getQuery()->getSingleScalarResult();
  634.         // for starred tickets count
  635.         $starredQb = clone $queryBuilder;
  636.         $starredQb->andwhere('ticket.isStarred = 1');
  637.         $data['starred'] = $starredQb->getQuery()->getSingleScalarResult();
  638.         // for trashed tickets count
  639.         $trashedQb = clone $queryBuilder;
  640.         $trashedQb->where('ticket.isTrashed = 1');
  641.         if ($currentUser->getRoles()[0] != 'ROLE_SUPER_ADMIN' && $userInstance->getTicketAccesslevel() != 1) {
  642.             $trashedQb->andwhere('ticket.agent = ' $currentUser->getId());
  643.         }
  644.         $data['trashed'] = $trashedQb->getQuery()->getSingleScalarResult();
  645.         return $data;
  646.     }
  647.     
  648.     public function paginateMembersTicketThreadCollection(Ticket $ticketRequest $request)
  649.     {
  650.         $params $request->query->all();
  651.         $entityManager $this->entityManager;
  652.         $activeUser $this->container->get('user.service')->getSessionUser();
  653.         $activeUserTimeZone $this->entityManager->getRepository(Website::class)->findOneBy(['code' => 'Knowledgebase']);
  654.         $agentTimeZone = !empty($activeUser->getTimezone()) ? $activeUser->getTimezone() : $activeUserTimeZone->getTimezone();
  655.         $agentTimeFormat = !empty($activeUser->getTimeformat()) ? $activeUser->getTimeformat() : $activeUserTimeZone->getTimeformat();
  656.         
  657.         $threadRepository $entityManager->getRepository(Thread::class);
  658.         $uvdeskFileSystemService $this->container->get('uvdesk.core.file_system.service');
  659.         // Get base query
  660.         $enableLockedThreads $this->container->get('user.service')->isAccessAuthorized('ROLE_AGENT_MANAGE_LOCK_AND_UNLOCK_THREAD');
  661.         $baseQuery $threadRepository->prepareBasePaginationRecentThreadsQuery($ticket$params$enableLockedThreads);
  662.         
  663.         // Apply Pagination
  664.         $paginationItemsQuery = clone $baseQuery;
  665.         $totalPaginationItems $paginationItemsQuery->select('COUNT(DISTINCT thread.id)')->getQuery()->getSingleScalarResult();
  666.         
  667.         $pageNumber = !empty($params['page']) ? (int) $params['page'] : 1;
  668.         $itemsLimit = !empty($params['limit']) ? (int) $params['limit'] : $threadRepository::DEFAULT_PAGINATION_LIMIT;
  669.         
  670.         $paginationOptions = ['distinct' => true];
  671.         $paginationQuery $baseQuery->getQuery()->setHydrationMode(Query::HYDRATE_ARRAY)->setHint('knp_paginator.count', (int) $totalPaginationItems);
  672.         $pagination $this->container->get('knp_paginator')->paginate($paginationQuery$pageNumber$itemsLimit$paginationOptions);
  673.         // Process Pagination Response
  674.         $threadCollection = [];
  675.         $paginationParams $pagination->getParams();
  676.         $paginationData $pagination->getPaginationData();
  677.         $website $this->entityManager->getRepository(Website::class)->findOneBy(['code' => 'helpdesk']);
  678.         $timeZone $website->getTimezone();
  679.         $timeFormat $website->getTimeformat();
  680.         if (!empty($params['threadRequestedId'])) {
  681.             $requestedThreadCollection $baseQuery
  682.                 ->andWhere('thread.id >= :threadRequestedId')->setParameter('threadRequestedId', (int) $params['threadRequestedId'])
  683.                 ->getQuery()->getArrayResult();
  684.             
  685.             $totalRequestedThreads count($requestedThreadCollection);
  686.             $paginationData['current'] = ceil($totalRequestedThreads $threadRepository::DEFAULT_PAGINATION_LIMIT);
  687.             if ($paginationData['current'] > 1) {
  688.                 $paginationData['firstItemNumber'] = 1;
  689.                 $paginationData['lastItemNumber'] = $totalRequestedThreads;
  690.                 $paginationData['next'] = ceil(($totalRequestedThreads 1) / $threadRepository::DEFAULT_PAGINATION_LIMIT);
  691.             }
  692.         }
  693.         $paginationParams['page'] = 'replacePage';
  694.         $paginationData['url'] = '#' $this->container->get('uvdesk.service')->buildPaginationQuery($paginationParams);
  695.         foreach ($pagination->getItems() as $threadDetails) {
  696.             $dbTime $threadDetails['createdAt'];
  697.             $formattedTime $this->fomatTimeByPreference($dbTime,$timeZone,$timeFormat,$agentTimeZone,$agentTimeFormat);
  698.             $threadResponse = [
  699.                 'id' => $threadDetails['id'],
  700.                 'user' => null,
  701.                 'fullname' => null,
  702.                 'reply' => html_entity_decode($threadDetails['message']),
  703.                 'source' => $threadDetails['source'],
  704.                 'threadType' => $threadDetails['threadType'],
  705.                 'userType' => $threadDetails['createdBy'],
  706.                 'timestamp' => $formattedTime['dateTimeZone'],
  707.                 'formatedCreatedAt' => $formattedTime['dateTimeZone']->format($formattedTime['timeFormatString']),
  708.                 'bookmark' => $threadDetails['isBookmarked'],
  709.                 'isLocked' => $threadDetails['isLocked'],
  710.                 'replyTo' => $threadDetails['replyTo'],
  711.                 'cc' => $threadDetails['cc'],
  712.                 'bcc' => $threadDetails['bcc'],
  713.                 'attachments' => $threadDetails['attachments'],
  714.             ];
  715.   
  716.             if (!empty($threadDetails['user'])) {
  717.                 $threadResponse['fullname'] = trim($threadDetails['user']['firstName'] . ' ' $threadDetails['user']['lastName']);
  718.                 $threadResponse['user'] = [
  719.                     'id' => $threadDetails['user']['id'],
  720.                     'smallThumbnail' => $threadDetails['user']['userInstance'][0]['profileImagePath'],
  721.                     'name' => $threadResponse['fullname'],
  722.                 ];
  723.             }
  724.             if (!empty($threadResponse['attachments'])) {
  725.                 $threadResponse['attachments'] = array_map(function ($attachment) use ($entityManager$uvdeskFileSystemService) {
  726.                     $attachmentReferenceObject $entityManager->getReference(Attachment::class, $attachment['id']);
  727.                     return $uvdeskFileSystemService->getFileTypeAssociations($attachmentReferenceObject);
  728.                 }, $threadResponse['attachments']);
  729.             }
  730.             array_push($threadCollection$threadResponse);
  731.         }
  732.         return [
  733.             'threads' => $threadCollection,
  734.             'pagination' => $paginationData,
  735.         ];
  736.     }
  737.     public function massXhrUpdate(Request $request)
  738.     {
  739.         $params $request->request->get('data');
  740.         foreach ($params['ids'] as $ticketId) {
  741.             $ticket $this->entityManager->getRepository(Ticket::class)->find($ticketId);
  742.             if (false == $this->isTicketAccessGranted($ticket)) {
  743.                 throw new \Exception('Access Denied'403);
  744.             }
  745.             
  746.             if (empty($ticket)) {
  747.                 continue;
  748.             }
  749.             switch ($params['actionType']) {
  750.                 case 'trashed':
  751.                     if (false == $ticket->getIsTrashed()) {
  752.                         $ticket->setIsTrashed(true);
  753.                         
  754.                         $this->entityManager->persist($ticket);
  755.                     }
  756.                     // Trigger ticket delete event
  757.                     $event = new CoreWorkflowEvents\Ticket\Delete();
  758.                     $event
  759.                         ->setTicket($ticket)
  760.                     ;
  761.                     $this->container->get('event_dispatcher')->dispatch($event'uvdesk.automation.workflow.execute');
  762.                     break;
  763.                 case 'delete':
  764.                     $threads $ticket->getThreads();
  765.                     $fileService = new Filesystem();
  766.                     if (count($threads) > 0) {
  767.                         foreach($threads as $thread) {
  768.                             if (!empty($thread)) {
  769.                                 $fileService->remove($this->container->getParameter('kernel.project_dir').'/public/assets/threads/'.$thread->getId());
  770.                             }
  771.                         }
  772.                     }
  773.                     $this->entityManager->remove($ticket);
  774.                     
  775.                     break;
  776.                 case 'restored':
  777.                     if (true == $ticket->getIsTrashed()) {
  778.                         $ticket->setIsTrashed(false);
  779.                         $this->entityManager->persist($ticket);
  780.                     }
  781.                     break;
  782.                 case 'agent':
  783.                     if ($ticket->getAgent() == null || $ticket->getAgent() && $ticket->getAgent()->getId() != $params['targetId']) {
  784.                         $agent $this->entityManager->getRepository(User::class)->find($params['targetId']);
  785.                         $ticket->setAgent($agent);
  786.     
  787.                         $this->entityManager->persist($ticket);
  788.     
  789.                         // Trigger Agent Assign event
  790.                         $event = new CoreWorkflowEvents\Ticket\Agent();
  791.                         $event
  792.                             ->setTicket($ticket)
  793.                         ;
  794.     
  795.                         $this->container->get('event_dispatcher')->dispatch($event'uvdesk.automation.workflow.execute');
  796.                     }
  797.                     break;
  798.                 case 'status':
  799.                     if ($ticket->getStatus() == null || $ticket->getStatus() && $ticket->getStatus()->getId() != $params['targetId']) {
  800.                         $status $this->entityManager->getRepository(TicketStatus::class)->findOneById($params['targetId']);
  801.                         $ticket->setStatus($status);
  802.                         $this->entityManager->persist($ticket);
  803.                         // Trigger ticket status event
  804.                         $event = new CoreWorkflowEvents\Ticket\Status();
  805.                         $event
  806.                             ->setTicket($ticket)
  807.                         ;
  808.                         
  809.                         $this->container->get('event_dispatcher')->dispatch($event'uvdesk.automation.workflow.execute');
  810.                     }
  811.                     
  812.                     break;
  813.                 case 'type':
  814.                     if ($ticket->getType() == null || $ticket->getType() && $ticket->getType()->getId() != $params['targetId']) {
  815.                         $type $this->entityManager->getRepository(TicketType::class)->findOneById($params['targetId']);
  816.                         $ticket->setType($type);
  817.     
  818.                         $this->entityManager->persist($ticket);
  819.     
  820.                         // Trigger ticket type event
  821.                         $event = new CoreWorkflowEvents\Ticket\Type();
  822.                         $event
  823.                             ->setTicket($ticket)
  824.                         ;
  825.     
  826.                         $this->container->get('event_dispatcher')->dispatch($event'uvdesk.automation.workflow.execute');
  827.                     }
  828.                     break;
  829.                 case 'group':
  830.                     if ($ticket->getSupportGroup() == null || $ticket->getSupportGroup() && $ticket->getSupportGroup()->getId() != $params['targetId']) {
  831.                         $group $this->entityManager->getRepository(SupportGroup::class)->find($params['targetId']);
  832.                         $ticket->setSupportGroup($group);
  833.     
  834.                         $this->entityManager->persist($ticket);
  835.     
  836.                         // Trigger Support group event
  837.                         $event = new CoreWorkflowEvents\Ticket\Group();
  838.                         $event
  839.                             ->setTicket($ticket)
  840.                         ;
  841.     
  842.                         $this->container->get('event_dispatcher')->dispatch($event'uvdesk.automation.workflow.execute');
  843.                     }
  844.                     break;
  845.                 case 'team':
  846.                     if ($ticket->getSupportTeam() == null || $ticket->getSupportTeam() && $ticket->getSupportTeam()->getId() != $params['targetId']){
  847.                         $team $this->entityManager->getRepository(SupportTeam::class)->find($params['targetId']);
  848.                         $ticket->setSupportTeam($team);
  849.                         
  850.                         $this->entityManager->persist($ticket);
  851.         
  852.                         // Trigger team event
  853.                         $event = new CoreWorkflowEvents\Ticket\Team();
  854.                         $event
  855.                             ->setTicket($ticket)
  856.                         ;
  857.         
  858.                         $this->container->get('event_dispatcher')->dispatch($event'uvdesk.automation.workflow.execute');
  859.                     }
  860.                     break;
  861.                 case 'priority':
  862.                     if ($ticket->getPriority() == null || $ticket->getPriority() && $ticket->getPriority()->getId() != $params['targetId']) {
  863.                         
  864.                         $priority $this->entityManager->getRepository(TicketPriority::class)->find($params['targetId']);
  865.                         $ticket->setPriority($priority);
  866.     
  867.                         $this->entityManager->persist($ticket);
  868.     
  869.                         // Trigger ticket Priority event
  870.                         $event = new CoreWorkflowEvents\Ticket\Priority();
  871.                         $event
  872.                             ->setTicket($ticket)
  873.                         ;
  874.     
  875.                         $this->container->get('event_dispatcher')->dispatch($event'uvdesk.automation.workflow.execute');
  876.                     }
  877.                     break;
  878.                 case 'label':
  879.                     $label $this->entityManager->getRepository(SupportLabel::class)->find($params['targetId']);
  880.                     
  881.                     if ($label && !$this->entityManager->getRepository(Ticket::class)->isLabelAlreadyAdded($ticket$label)) {
  882.                         $ticket->addSupportLabel($label);
  883.                     }
  884.                     
  885.                     $this->entityManager->persist($ticket);
  886.                     break;
  887.                 default:
  888.                     break;
  889.             }
  890.         } 
  891.         $this->entityManager->flush();
  892.         return [
  893.             'alertClass' => 'success',
  894.             'alertMessage' => $this->trans('Tickets have been updated successfully'),
  895.         ];
  896.     }
  897.     
  898.     public function getNotePlaceholderValues($ticket$type "customer")
  899.     {
  900.         $variables = array();
  901.         $variables['ticket.id'] = $ticket->getId();
  902.         $variables['ticket.subject'] = $ticket->getSubject();
  903.         $variables['ticket.status'] = $ticket->getStatus()->getCode();
  904.         $variables['ticket.priority'] = $ticket->getPriority()->getCode();
  905.         if($ticket->getSupportGroup())
  906.             $variables['ticket.group'] = $ticket->getSupportGroup()->getName();
  907.         else
  908.             $variables['ticket.group'] = '';
  909.         $variables['ticket.team'] = ($ticket->getSupportTeam() ? $ticket->getSupportTeam()->getName() : '');
  910.         $customer $this->container->get('user.service')->getCustomerPartialDetailById($ticket->getCustomer()->getId());
  911.         $variables['ticket.customerName'] = $customer['name'];
  912.         $userService $this->container->get('user.service');
  913.       
  914.         $variables['ticket.agentName'] = '';
  915.         $variables['ticket.agentEmail'] = '';
  916.         if ($ticket->getAgent()) {
  917.             $agent $this->container->get('user.service')->getAgentDetailById($ticket->getAgent()->getId());
  918.             if($agent) {
  919.                 $variables['ticket.agentName'] = $agent['name'];
  920.                 $variables['ticket.agentEmail'] = $agent['email'];
  921.             }
  922.         }
  923.         $router $this->container->get('router');
  924.         if ($type == 'customer') {
  925.             $ticketListURL $router->generate('helpdesk_member_ticket_collection', [
  926.                 'id' => $ticket->getId(),
  927.             ], UrlGeneratorInterface::ABSOLUTE_URL);
  928.         } else {
  929.             $ticketListURL $router->generate('helpdesk_customer_ticket_collection', [
  930.                 'id' => $ticket->getId(),
  931.             ], UrlGeneratorInterface::ABSOLUTE_URL);
  932.         }
  933.         $variables['ticket.link'] = sprintf("<a href='%s'>#%s</a>"$ticketListURL$ticket->getId());
  934.         return $variables;
  935.     }
  936.     public function paginateMembersTicketTypeCollection(Request $request)
  937.     {
  938.         // Get base query
  939.         $params $request->query->all();
  940.         $ticketRepository $this->entityManager->getRepository(Ticket::class);
  941.         $paginationQuery $ticketRepository->prepareBasePaginationTicketTypesQuery($params);
  942.         // Apply Pagination
  943.         $paginationOptions = ['distinct' => true];
  944.         $pageNumber = !empty($params['page']) ? (int) $params['page'] : 1;
  945.         $itemsLimit = !empty($params['limit']) ? (int) $params['limit'] : $ticketRepository::DEFAULT_PAGINATION_LIMIT;
  946.         $pagination $this->container->get('knp_paginator')->paginate($paginationQuery$pageNumber$itemsLimit$paginationOptions);
  947.         // Process Pagination Response
  948.         $paginationParams $pagination->getParams();
  949.         $paginationData $pagination->getPaginationData();
  950.         $paginationParams['page'] = 'replacePage';
  951.         $paginationData['url'] = '#' $this->container->get('uvdesk.service')->buildPaginationQuery($paginationParams);
  952.         return [
  953.             'types' => array_map(function ($ticketType) {
  954.                 return [
  955.                     'id' => $ticketType->getId(),
  956.                     'code' => strtoupper($ticketType->getCode()),
  957.                     'description' => $ticketType->getDescription(),
  958.                     'isActive' => $ticketType->getIsActive(),
  959.                 ];
  960.             }, $pagination->getItems()),
  961.             'pagination_data' => $paginationData,
  962.         ];
  963.     }
  964.     public function paginateMembersTagCollection(Request $request)
  965.     {
  966.         // Get base query
  967.         $params $request->query->all();
  968.         $ticketRepository $this->entityManager->getRepository(Ticket::class);
  969.         $baseQuery $ticketRepository->prepareBasePaginationTagsQuery($params);
  970.         // Apply Pagination
  971.         $paginationResultsQuery = clone $baseQuery;
  972.         $paginationResultsQuery->select('COUNT(supportTag.id)');
  973.         $paginationQuery $baseQuery->getQuery()->setHydrationMode(Query::HYDRATE_ARRAY)->setHint('knp_paginator.count'count($paginationResultsQuery->getQuery()->getResult()));
  974.         $paginationOptions = ['distinct' => true];
  975.         $pageNumber = !empty($params['page']) ? (int) $params['page'] : 1;
  976.         $itemsLimit = !empty($params['limit']) ? (int) $params['limit'] : $ticketRepository::DEFAULT_PAGINATION_LIMIT;
  977.         $pagination $this->container->get('knp_paginator')->paginate($paginationQuery$pageNumber$itemsLimit$paginationOptions);
  978.         // Process Pagination Response
  979.         $paginationParams $pagination->getParams();
  980.         $paginationData $pagination->getPaginationData();
  981.         $paginationParams['page'] = 'replacePage';
  982.         $paginationData['url'] = '#' $this->container->get('uvdesk.service')->buildPaginationQuery($paginationParams);
  983.         if (in_array('UVDeskSupportCenterBundle'array_keys($this->container->getParameter('kernel.bundles')))) {
  984.             $articleRepository $this->entityManager->getRepository(Article::class);
  985.             return [
  986.                 'tags' => array_map(function ($supportTag) use ($articleRepository) {
  987.                     return [
  988.                         'id' => $supportTag['id'],
  989.                         'name' => $supportTag['name'],
  990.                         'ticketCount' => $supportTag['totalTickets'],
  991.                         'articleCount' => $articleRepository->getTotalArticlesBySupportTag($supportTag['id']),
  992.                     ];
  993.                 }, $pagination->getItems()),
  994.                 'pagination_data' => $paginationData,
  995.             ];
  996.         } else {
  997.             return [
  998.                 'tags' => array_map(function ($supportTag) {
  999.                     return [
  1000.                         'id' => $supportTag['id'],
  1001.                         'name' => $supportTag['name'],
  1002.                         'ticketCount' => $supportTag['totalTickets'],
  1003.                     ];
  1004.                 }, $pagination->getItems()),
  1005.                 'pagination_data' => $paginationData,
  1006.             ];
  1007.         }
  1008.     }
  1009.     public function getTicketInitialThreadDetails(Ticket $ticket)
  1010.     {
  1011.         $initialThread $this->entityManager->getRepository(Thread::class)->findOneBy([
  1012.             'ticket' => $ticket,
  1013.             'threadType' => 'create',
  1014.         ]);
  1015.         if (!empty($initialThread)) {
  1016.             $author $initialThread->getUser();
  1017.             $authorInstance 'agent' == $initialThread->getCreatedBy() ? $author->getAgentInstance() : $author->getCustomerInstance();
  1018.         
  1019.             $threadDetails = [
  1020.                 'id' => $initialThread->getId(),
  1021.                 'source' => $initialThread->getSource(),
  1022.                 'messageId' => $initialThread->getMessageId(),
  1023.                 'threadType' => $initialThread->getThreadType(),
  1024.                 'createdBy' => $initialThread->getCreatedBy(),
  1025.                 'message' => html_entity_decode($initialThread->getMessage()),
  1026.                 'attachments' => $initialThread->getAttachments(),
  1027.                 'timestamp' => $initialThread->getCreatedAt()->getTimestamp(),
  1028.                 'createdAt' => $initialThread->getCreatedAt()->format('d-m-Y h:ia'),
  1029.                 'user' => $authorInstance->getPartialDetails(),
  1030.                 'cc' => is_array($initialThread->getCc()) ? implode(', '$initialThread->getCc()) : '',
  1031.             ];
  1032.             $attachments $threadDetails['attachments']->getValues();
  1033.             if (!empty($attachments)) {
  1034.                 $uvdeskFileSystemService $this->container->get('uvdesk.core.file_system.service');
  1035.                 $threadDetails['attachments'] = array_map(function ($attachment) use ($uvdeskFileSystemService) {
  1036.                     return $uvdeskFileSystemService->getFileTypeAssociations($attachment);
  1037.                 }, $attachments);
  1038.             }
  1039.         }
  1040.         return $threadDetails ?? null;
  1041.     }
  1042.     public function getCreateReply($ticketId$firewall 'member')
  1043.     {
  1044.         $qb $this->entityManager->createQueryBuilder();
  1045.         $qb->select("th,a,u.id as userId")->from(Thread::class, 'th')
  1046.                 ->leftJoin('th.ticket','t')
  1047.                 ->leftJoin('th.attachments''a')
  1048.                 ->leftJoin('th.user','u')
  1049.                 ->andWhere('t.id = :ticketId')
  1050.                 ->andWhere('th.threadType = :threadType')
  1051.                 ->setParameter('threadType','create')
  1052.                 ->setParameter('ticketId',$ticketId)
  1053.                 ->orderBy('th.id''DESC')
  1054.                 ->getMaxResults(1);
  1055.         $threadResponse $qb->getQuery()->getArrayResult();
  1056.         if((!empty($threadResponse[0][0]))) {
  1057.             $threadDetails $threadResponse[0][0];
  1058.             $userService $this->container->get('user.service');
  1059.             
  1060.             if ($threadDetails['createdBy'] == 'agent') {
  1061.                 $threadDetails['user'] = $userService->getAgentDetailById($threadResponse[0]['userId']);
  1062.             } else {
  1063.                 $threadDetails['user'] = $userService->getCustomerPartialDetailById($threadResponse[0]['userId']);
  1064.             }
  1065.             
  1066.             $threadDetails['reply'] = html_entity_decode($threadDetails['message']);
  1067.             $threadDetails['formatedCreatedAt'] = $this->timeZoneConverter($threadDetails['createdAt']);    
  1068.             $threadDetails['timestamp'] = $userService->convertToDatetimeTimezoneTimestamp($threadDetails['createdAt']);
  1069.         
  1070.             if (!empty($threadDetails['attachments'])) {
  1071.                 $entityManager $this->entityManager;
  1072.                 $uvdeskFileSystemService $this->container->get('uvdesk.core.file_system.service');
  1073.                 $threadDetails['attachments'] = array_map(function ($attachment) use ($entityManager$uvdeskFileSystemService$firewall) {
  1074.                     $attachmentReferenceObject $entityManager->getReference(Attachment::class, $attachment['id']);
  1075.                     return $uvdeskFileSystemService->getFileTypeAssociations($attachmentReferenceObject$firewall);
  1076.                 }, $threadDetails['attachments']);
  1077.             }
  1078.         }
  1079.         
  1080.         return $threadDetails ?? null;
  1081.     }
  1082.     public function hasAttachments($ticketId) {
  1083.         $qb $this->entityManager->createQueryBuilder();
  1084.         $qb->select("DISTINCT COUNT(a.id) as attachmentCount")->from(Thread::class, 'th')
  1085.                 ->leftJoin('th.ticket','t')
  1086.                 ->leftJoin('th.attachments','a')
  1087.                 ->andWhere('t.id = :ticketId')
  1088.                 ->setParameter('ticketId',$ticketId);
  1089.         return intval($qb->getQuery()->getSingleScalarResult());
  1090.     }
  1091.     public function getAgentDraftReply()
  1092.     {
  1093.         $signature $this->getUser()->getAgentInstance()->getSignature();
  1094.         
  1095.         return str_replace"\n"'<br/>'$signature);
  1096.     }
  1097.     public function trans($text)
  1098.     {
  1099.         return $this->container->get('translator')->trans($text);
  1100.     }
  1101.     public function getAllSources()
  1102.     {
  1103.         $sources = ['email' => 'Email''website' => 'Website'];
  1104.         return $sources;
  1105.     }
  1106.     public function getCustomLabelDetails($container)
  1107.     {
  1108.         $currentUser $container->get('user.service')->getCurrentUser();
  1109.         $qb $this->entityManager->createQueryBuilder();
  1110.         $qb->select('COUNT(DISTINCT t) as ticketCount,sl.id')->from(Ticket::class, 't')
  1111.                 ->leftJoin('t.supportLabels','sl')
  1112.                 ->andwhere('sl.user = :userId')
  1113.                 ->setParameter('userId'$currentUser->getId())
  1114.                 ->groupBy('sl.id');
  1115.         $ticketCountResult $qb->getQuery()->getResult();
  1116.         $data = array();
  1117.         $qb $this->entityManager->createQueryBuilder();
  1118.         $qb->select('sl.id,sl.name,sl.colorCode')->from(SupportLabel::class, 'sl')
  1119.                 ->andwhere('sl.user = :userId')
  1120.                 ->setParameter('userId'$currentUser->getId());
  1121.         $labels $qb->getQuery()->getResult();
  1122.         foreach ($labels as $key => $label) {
  1123.             $labels[$key]['count'] = 0;
  1124.             foreach ($ticketCountResult as $ticketCount) {
  1125.                 if(($label['id'] == $ticketCount['id']))
  1126.                     $labels[$key]['count'] = $ticketCount['ticketCount'] ?: 0;
  1127.             }
  1128.         }
  1129.         return $labels;
  1130.     }
  1131.     public function getLabels($request null)
  1132.     {
  1133.         static $labels;
  1134.         if (null !== $labels)
  1135.             return $labels;
  1136.         $qb $this->entityManager->createQueryBuilder();
  1137.         $qb->select('sl')->from(SupportLabel::class, 'sl')
  1138.             ->andwhere('sl.user = :userId')
  1139.             ->setParameter('userId'$this->getUser()->getId());
  1140.         if($request) {
  1141.             $qb->andwhere("sl.name LIKE :labelName");
  1142.             $qb->setParameter('labelName''%'.urldecode($request->query->get('query')).'%');
  1143.         }
  1144.         return $labels $qb->getQuery()->getArrayResult();
  1145.     }
  1146.     public function getTicketCollaborators($ticketId)
  1147.     {
  1148.         $qb $this->entityManager->createQueryBuilder();
  1149.         $qb->select("DISTINCT c.id, c.email, CONCAT(c.firstName,' ', c.lastName) AS name, userInstance.profileImagePath, userInstance.profileImagePath as smallThumbnail")->from(Ticket::class, 't')
  1150.                 ->leftJoin('t.collaborators''c')
  1151.                 ->leftJoin('c.userInstance''userInstance')
  1152.                 ->andwhere('t.id = :ticketId')
  1153.                 ->andwhere('userInstance.supportRole = :roles')
  1154.                 ->setParameter('ticketId'$ticketId)
  1155.                 ->setParameter('roles'4)
  1156.                 ->orderBy('name','ASC');
  1157.         return $qb->getQuery()->getArrayResult();
  1158.     }
  1159.     public function getTicketTagsById($ticketId)
  1160.     {
  1161.         $qb $this->entityManager->createQueryBuilder();
  1162.         $qb->select('tg')->from(Tag::class, 'tg')
  1163.                 ->leftJoin('tg.tickets' ,'t')
  1164.                 ->andwhere('t.id = :ticketId')
  1165.                 ->setParameter('ticketId'$ticketId);
  1166.         return $qb->getQuery()->getArrayResult();
  1167.     }
  1168.     public function getTicketLabels($ticketId)
  1169.     {
  1170.         $qb $this->entityManager->createQueryBuilder();
  1171.         $qb->select('DISTINCT sl.id,sl.name,sl.colorCode')->from(Ticket::class, 't')
  1172.                 ->leftJoin('t.supportLabels','sl')
  1173.                 ->leftJoin('sl.user','slu')
  1174.                 ->andWhere('slu.id = :userId')
  1175.                 ->andWhere('t.id = :ticketId')
  1176.                 ->setParameter('userId'$this->getUser()->getId())
  1177.                 ->setParameter('ticketId'$ticketId);
  1178.         $result $qb->getQuery()->getResult();
  1179.         
  1180.         return $result $result : [];
  1181.     }
  1182.     public function getUserLabels()
  1183.     {
  1184.         $qb $this->entityManager->createQueryBuilder();
  1185.         $qb->select('sl')->from(SupportLabel::class, 'sl')
  1186.                 ->leftJoin('sl.user','slu')
  1187.                 ->andWhere('slu.id = :userId')
  1188.                 ->setParameter('userId'$this->getUser()->getId());
  1189.         $result $qb->getQuery()->getResult();
  1190.         
  1191.         return $result $result : [];
  1192.     }
  1193.     public function getTicketLabelsAll($ticketId)
  1194.     {
  1195.         $qb $this->entityManager->createQueryBuilder();
  1196.         $qb->select('DISTINCT sl.id,sl.name,sl.colorCode')->from(Ticket::class, 't')
  1197.                 ->leftJoin('t.supportLabels','sl')
  1198.                 ->andWhere('t.id = :ticketId')
  1199.                 ->setParameter('ticketId'$ticketId);
  1200.         $result $qb->getQuery()->getResult();
  1201.         
  1202.         return $result $result : [];
  1203.     }
  1204.     public function getManualWorkflow()
  1205.     {
  1206.         $preparedResponseIds = [];
  1207.         $groupIds = [];
  1208.         $teamIds = []; 
  1209.         $userId $this->container->get('user.service')->getCurrentUser()->getAgentInstance()->getId();
  1210.         $preparedResponseRepo $this->entityManager->getRepository(PreparedResponses::class)->findAll();
  1211.         foreach ($preparedResponseRepo as $pr) {
  1212.             if ($userId == $pr->getUser()->getId()) {
  1213.                 //Save the ids of the saved reply.
  1214.                 array_push($preparedResponseIds, (int)$pr->getId());
  1215.             }
  1216.         }
  1217.         // Get the ids of the Group(s) the current user is associated with.
  1218.         $query "select * from uv_user_support_groups where userInstanceId =".$userId;
  1219.         $connection $this->entityManager->getConnection();
  1220.         $stmt $connection->prepare($query);
  1221.         $stmt->execute();
  1222.         $result $stmt->fetchAll();
  1223.         foreach ($result as $row) {
  1224.             array_push($groupIds$row['supportGroupId']);
  1225.         }
  1226.         // Get all the saved reply's ids that is associated with the user's group(s).
  1227.         $query "select * from uv_prepared_response_support_groups";
  1228.         $stmt $connection->prepare($query);
  1229.         $stmt->execute();
  1230.         $result $stmt->fetchAll();
  1231.         foreach ($result as $row) {
  1232.             if (in_array($row['group_id'], $groupIds)) {
  1233.                 array_push($preparedResponseIds, (int) $row['savedReply_id']);
  1234.             }
  1235.         }
  1236.         // Get the ids of the Team(s) the current user is associated with.
  1237.         $query "select * from uv_user_support_teams";
  1238.         $connection $this->entityManager->getConnection();
  1239.         $stmt $connection->prepare($query);
  1240.         $stmt->execute();
  1241.         $result $stmt->fetchAll();
  1242.         foreach($result as $row) {
  1243.             if ($row['userInstanceId'] == $userId) {
  1244.                 array_push($teamIds$row['supportTeamId']);
  1245.             }
  1246.         }
  1247.         $query "select * from uv_prepared_response_support_teams";
  1248.         $stmt $connection->prepare($query);
  1249.         $stmt->execute();
  1250.         $result $stmt->fetchAll();
  1251.         foreach ($result as $row) {
  1252.             if (in_array($row['subgroup_id'], $teamIds)) {
  1253.                 array_push($preparedResponseIds, (int)$row['savedReply_id']);
  1254.             }
  1255.         }
  1256.         $qb $this->entityManager->createQueryBuilder();
  1257.         $qb->select('DISTINCT mw')
  1258.             ->from(PreparedResponses::class, 'mw')
  1259.             ->where('mw.status = 1')
  1260.             ->andWhere('mw.id IN (:ids)')
  1261.             ->setParameter('ids'$preparedResponseIds);
  1262.         
  1263.         return $qb->getQuery()->getResult();
  1264.     }
  1265.     public function getSavedReplies()
  1266.     {   
  1267.         $savedReplyIds = [];
  1268.         $groupIds = [];
  1269.         $teamIds = []; 
  1270.         $userId $this->container->get('user.service')->getCurrentUser()->getAgentInstance()->getId();
  1271.         $savedReplyRepo $this->entityManager->getRepository(SavedReplies::class)->findAll();
  1272.         foreach ($savedReplyRepo as $sr) {
  1273.             if ($userId == $sr->getUser()->getId()) {
  1274.                 //Save the ids of the saved reply.
  1275.                 array_push($savedReplyIds, (int)$sr->getId());
  1276.             }
  1277.         }
  1278.         // Get the ids of the Group(s) the current user is associated with.
  1279.         $query "select * from uv_user_support_groups where userInstanceId =".$userId;
  1280.         $connection $this->entityManager->getConnection();
  1281.         $stmt $connection->prepare($query);
  1282.         $stmt->execute();
  1283.         $result $stmt->fetchAll();
  1284.         foreach ($result as $row) {
  1285.             array_push($groupIds$row['supportGroupId']);
  1286.         }
  1287.         // Get all the saved reply's ids that is associated with the user's group(s).
  1288.         $query "select * from uv_saved_replies_groups";
  1289.         $stmt $connection->prepare($query);
  1290.         $stmt->execute();
  1291.         $result $stmt->fetchAll();
  1292.         foreach ($result as $row) {
  1293.             if (in_array($row['group_id'], $groupIds)) {
  1294.                 array_push($savedReplyIds, (int) $row['savedReply_id']);
  1295.             }
  1296.         }
  1297.         // Get the ids of the Team(s) the current user is associated with.
  1298.         $query "select * from uv_user_support_teams";
  1299.         $connection $this->entityManager->getConnection();
  1300.         $stmt $connection->prepare($query);
  1301.         $stmt->execute();
  1302.         $result $stmt->fetchAll();
  1303.         foreach($result as $row) {
  1304.             if ($row['userInstanceId'] == $userId) {
  1305.                 array_push($teamIds$row['supportTeamId']);
  1306.             }
  1307.         }
  1308.         $query "select * from uv_saved_replies_teams";
  1309.         $stmt $connection->prepare($query);
  1310.         $stmt->execute();
  1311.         $result $stmt->fetchAll();
  1312.         foreach ($result as $row) {
  1313.             if (in_array($row['subgroup_id'], $teamIds)) {
  1314.                 array_push($savedReplyIds, (int)$row['savedReply_id']);
  1315.             }
  1316.         }
  1317.         $qb $this->entityManager->createQueryBuilder();
  1318.         $qb->select('DISTINCT sr')
  1319.         ->from(SavedReplies::class, 'sr')
  1320.         ->Where('sr.id IN (:ids)')
  1321.         ->setParameter('ids'$savedReplyIds);
  1322.         
  1323.         return $qb->getQuery()->getResult();
  1324.     }
  1325.     public function getPriorities()
  1326.     {
  1327.         static $priorities;
  1328.         if (null !== $priorities)
  1329.             return $priorities;
  1330.         $qb $this->entityManager->createQueryBuilder();
  1331.         $qb->select('tp')->from(TicketPriority::class, 'tp');
  1332.         return $priorities $qb->getQuery()->getArrayResult();
  1333.     }
  1334.     public function getTicketLastThread($ticketId)
  1335.     {
  1336.         $qb $this->entityManager->createQueryBuilder();
  1337.         $qb->select("th")->from(Thread::class, 'th')
  1338.                 ->leftJoin('th.ticket','t')
  1339.                 ->andWhere('t.id = :ticketId')
  1340.                 ->setParameter('ticketId',$ticketId)
  1341.                 ->orderBy('th.id''DESC');
  1342.         return $qb->getQuery()->setMaxResults(1)->getSingleResult();
  1343.     }
  1344.     public function getlastReplyAgentName($ticketId)
  1345.     {
  1346.         $qb $this->entityManager->createQueryBuilder();
  1347.         $qb->select("u.id,CONCAT(u.firstName,' ', u.lastName) AS name,u.firstName")->from(Thread::class, 'th')
  1348.                 ->leftJoin('th.ticket','t')
  1349.                 ->leftJoin('th.user''u')
  1350.                 ->leftJoin('u.userInstance''userInstance')
  1351.                 ->andwhere('userInstance.supportRole != :roles')
  1352.                 ->andWhere('t.id = :ticketId')
  1353.                 ->andWhere('th.threadType = :threadType')
  1354.                 ->setParameter('threadType','reply')
  1355.                 ->andWhere('th.createdBy = :createdBy')
  1356.                 ->setParameter('createdBy','agent')
  1357.                 ->setParameter('ticketId',$ticketId)
  1358.                 ->setParameter('roles'4)
  1359.                 ->orderBy('th.id''DESC');
  1360.         $result $qb->getQuery()->setMaxResults(1)->getResult();
  1361.         return $result $result[0] : null;
  1362.     }
  1363.     public function getLastReply($ticketId$userType null
  1364.     {
  1365.         $queryBuilder $this->entityManager->createQueryBuilder();
  1366.         $queryBuilder->select("th, a, u.id as userId")
  1367.             ->from(Thread::class, 'th')
  1368.             ->leftJoin('th.ticket','t')
  1369.             ->leftJoin('th.attachments''a')
  1370.             ->leftJoin('th.user','u')
  1371.             ->andWhere('t.id = :ticketId')
  1372.             ->andWhere('th.threadType = :threadType')
  1373.             ->setParameter('threadType','reply')
  1374.             ->setParameter('ticketId',$ticketId)
  1375.             ->orderBy('th.id''DESC')
  1376.             ->getMaxResults(1);
  1377.         if (!empty($userType)) {
  1378.             $queryBuilder->andWhere('th.createdBy = :createdBy')->setParameter('createdBy'$userType);
  1379.         }
  1380.         
  1381.         $threadResponse $queryBuilder->getQuery()->getArrayResult();
  1382.         
  1383.         if (!empty($threadResponse[0][0])) {
  1384.             $threadDetails $threadResponse[0][0];
  1385.             $userService $this->container->get('user.service');
  1386.             
  1387.             if ($threadDetails['createdBy'] == 'agent') {
  1388.                 $threadDetails['user'] = $userService->getAgentDetailById($threadResponse[0]['userId']);
  1389.             } else {
  1390.                 $threadDetails['user'] = $userService->getCustomerPartialDetailById($threadResponse[0]['userId']);
  1391.             }
  1392.             
  1393.             $threadDetails['reply'] = html_entity_decode($threadDetails['message']);
  1394.             $threadDetails['formatedCreatedAt'] = $this->timeZoneConverter($threadDetails['createdAt']);
  1395.             $threadDetails['timestamp'] = $userService->convertToDatetimeTimezoneTimestamp($threadDetails['createdAt']);
  1396.             if (!empty($threadDetails['attachments'])) {
  1397.                 $entityManager $this->entityManager;
  1398.                 $uvdeskFileSystemService $this->container->get('uvdesk.core.file_system.service');
  1399.                 $threadDetails['attachments'] = array_map(function ($attachment) use ($entityManager$uvdeskFileSystemService) {
  1400.                     $attachmentReferenceObject $this->entityManager->getReference(Attachment::class, $attachment['id']);
  1401.                     return $uvdeskFileSystemService->getFileTypeAssociations($attachmentReferenceObject);
  1402.                 }, $threadDetails['attachments']);
  1403.             }
  1404.         }
  1405.         return $threadDetails ?? null;
  1406.     }
  1407.     public function getSavedReplyContent($savedReplyId$ticketId)
  1408.     {
  1409.         $ticket $this->entityManager->getRepository(Ticket::class)->find($ticketId);
  1410.         $savedReply $this->entityManager->getRepository(SavedReplies::class)->findOneById($savedReplyId);
  1411.         $emailPlaceholders $this->getSavedReplyPlaceholderValues($ticket'customer');
  1412.         return $this->container->get('email.service')->processEmailContent($savedReply->getMessage(), $emailPlaceholderstrue);
  1413.     }
  1414.     public function getSavedReplyPlaceholderValues($ticket$type "customer")
  1415.     {
  1416.         $variables = array();
  1417.         $variables['ticket.id'] = $ticket->getId();
  1418.         $variables['ticket.subject'] = $ticket->getSubject();
  1419.         $variables['ticket.status'] = $ticket->getStatus()->getCode();
  1420.         $variables['ticket.priority'] = $ticket->getPriority()->getCode();
  1421.         if($ticket->getSupportGroup())
  1422.             $variables['ticket.group'] = $ticket->getSupportGroup()->getName();
  1423.         else
  1424.             $variables['ticket.group'] = '';
  1425.         $variables['ticket.team'] = ($ticket->getSupportTeam() ? $ticket->getSupportTeam()->getName() : '');
  1426.         $customer $this->container->get('user.service')->getCustomerPartialDetailById($ticket->getCustomer()->getId());
  1427.         $variables['ticket.customerName'] = $customer['name'];
  1428.         $variables['ticket.customerEmail'] = $customer['email'];
  1429.         $userService $this->container->get('user.service');
  1430.       
  1431.         $variables['ticket.agentName'] = '';
  1432.         $variables['ticket.agentEmail'] = '';
  1433.         if ($ticket->getAgent()) {
  1434.             $agent $this->container->get('user.service')->getAgentDetailById($ticket->getAgent()->getId());
  1435.             if($agent) {
  1436.                 $variables['ticket.agentName'] = $agent['name'];
  1437.                 $variables['ticket.agentEmail'] = $agent['email'];
  1438.             }
  1439.         }
  1440.         
  1441.         $router $this->container->get('router');
  1442.         if ($type == 'customer') {
  1443.             $ticketListURL $router->generate('helpdesk_customer_ticket_collection', [
  1444.                 'id' => $ticket->getId(),
  1445.             ], UrlGeneratorInterface::ABSOLUTE_URL);
  1446.         } else {
  1447.             $ticketListURL $router->generate('helpdesk_member_ticket_collection', [
  1448.                 'id' => $ticket->getId(),
  1449.             ], UrlGeneratorInterface::ABSOLUTE_URL);
  1450.         }
  1451.         $variables['ticket.link'] = sprintf("<a href='%s'>#%s</a>"$ticketListURL$ticket->getId());
  1452.         return $variables;
  1453.     }
  1454.     public function isEmailBlocked($email$website
  1455.     {
  1456.         $flag false;
  1457.         $email strtolower($email);
  1458.         $knowlegeBaseWebsite $this->entityManager->getRepository(KnowledgebaseWebsite::class)->findOneBy(['website' => $website->getId(), 'isActive' => 1]);
  1459.         $list $this->container->get('user.service')->getWebsiteSpamDetails($knowlegeBaseWebsite);
  1460.         // Blacklist
  1461.         if (!empty($list['blackList']['email']) && in_array($email$list['blackList']['email'])) {
  1462.             // Emails
  1463.             $flag true;
  1464.         } elseif (!empty($list['blackList']['domain'])) {
  1465.             // Domains
  1466.             foreach ($list['blackList']['domain'] as $domain) {
  1467.                 if (strpos($email$domain)) {
  1468.                     $flag true;
  1469.                     break;
  1470.                 }
  1471.             }
  1472.         }
  1473.         // Whitelist
  1474.         if ($flag) {
  1475.             if (isset($email$list['whiteList']['email']) && in_array($email$list['whiteList']['email'])) {
  1476.                 // Emails
  1477.                 return false;
  1478.             } elseif (isset($list['whiteList']['domain'])) {
  1479.                 // Domains
  1480.                 foreach ($list['whiteList']['domain'] as $domain) {
  1481.                     if (strpos($email$domain)) {
  1482.                         $flag false;
  1483.                     }
  1484.                 }
  1485.             }
  1486.         }
  1487.         return $flag;
  1488.     }
  1489.     public function timeZoneConverter($dateFlag)
  1490.     {
  1491.         $website $this->entityManager->getRepository(Website::class)->findOneBy(['code' => 'Knowledgebase']);
  1492.         $timeZone $website->getTimezone();
  1493.         $timeFormat $website->getTimeformat();
  1494.         $activeUser $this->container->get('user.service')->getSessionUser();
  1495.         $agentTimeZone = !empty($activeUser) ? $activeUser->getTimezone() : null;
  1496.         $agentTimeFormat = !empty($activeUser) ? $activeUser->getTimeformat() : null;
  1497.         $parameterType gettype($dateFlag);
  1498.         if($parameterType == 'string'){
  1499.             if(is_null($agentTimeZone) && is_null($agentTimeFormat)){
  1500.                 if(is_null($timeZone) && is_null($timeFormat)){
  1501.                     $datePattern date_create($dateFlag);
  1502.                     return date_format($datePattern,'d-m-Y h:ia');
  1503.                 } else {
  1504.                     $dateFlag = new \DateTime($dateFlag);
  1505.                     $datePattern $dateFlag->setTimezone(new \DateTimeZone($timeZone));
  1506.                     return date_format($datePattern$timeFormat);
  1507.                 }
  1508.             } else {
  1509.                 $dateFlag = new \DateTime($dateFlag);
  1510.                 $datePattern $dateFlag->setTimezone(new \DateTimeZone($agentTimeZone));
  1511.                 return date_format($datePattern$agentTimeFormat);
  1512.             }          
  1513.         } else {
  1514.             if(is_null($agentTimeZone) && is_null($agentTimeFormat)){
  1515.                 if(is_null($timeZone) && is_null($timeFormat)){
  1516.                     return date_format($dateFlag,'d-m-Y h:ia');
  1517.                 } else {
  1518.                     $datePattern $dateFlag->setTimezone(new \DateTimeZone($timeZone));
  1519.                     return date_format($datePattern$timeFormat);
  1520.                 }
  1521.             } else {
  1522.                 $datePattern $dateFlag->setTimezone(new \DateTimeZone($agentTimeZone));
  1523.                 return date_format($datePattern$agentTimeFormat);
  1524.             }    
  1525.         }         
  1526.     }
  1527.     public function fomatTimeByPreference($dbTime,$timeZone,$timeFormat,$agentTimeZone,$agentTimeFormat)
  1528.     {
  1529.         if(is_null($agentTimeZone) && is_null($agentTimeFormat)) {
  1530.             if(is_null($timeZone) && is_null($timeFormat)){
  1531.                 $dateTimeZone $dbTime;
  1532.                 $timeFormatString 'd-m-Y h:ia';
  1533.             } else {
  1534.                 $dateTimeZone $dbTime->setTimezone(new \DateTimeZone($timeZone));
  1535.                 $timeFormatString $timeFormat;
  1536.             }
  1537.         } else {
  1538.             $dateTimeZone $dbTime->setTimezone(new \DateTimeZone($agentTimeZone));
  1539.             $timeFormatString $agentTimeFormat;
  1540.         }
  1541.         $time['dateTimeZone'] = $dateTimeZone;
  1542.         $time['timeFormatString'] = $timeFormatString;
  1543.         return $time;
  1544.     }
  1545.     
  1546.     public function isTicketAccessGranted(Ticket $ticketUser $user null$firewall 'members')
  1547.     {
  1548.         // @TODO: Take current firewall into consideration (access check on behalf of agent/customer)
  1549.         if (empty($user)) {
  1550.             $user $this->container->get('user.service')->getSessionUser();
  1551.         }
  1552.         if (empty($user)) {
  1553.             return false;
  1554.         } else {
  1555.             $agentInstance $user->getAgentInstance();
  1556.     
  1557.             if (empty($agentInstance)) {
  1558.                 return false;
  1559.             }
  1560.         }
  1561.         if ($agentInstance->getSupportRole()->getId() == && in_array($agentInstance->getTicketAccessLevel(), [234])) {
  1562.             $accessLevel $agentInstance->getTicketAccessLevel();
  1563.             // Check if user has been given inidividual access
  1564.             if ($ticket->getAgent() != null && $ticket->getAgent()->getId() == $user->getId()) {
  1565.                 return true;
  1566.             }
  1567.             
  1568.             if ($accessLevel == || $accessLevel == 3) {
  1569.                 // Check if user belongs to a support team assigned to ticket
  1570.                 $teamReferenceIds array_map(function ($team) { return $team->getId(); }, $agentInstance->getSupportTeams()->toArray());
  1571.                 
  1572.                 if ($ticket->getSupportTeam() != null && in_array($ticket->getSupportTeam()->getId(), $teamReferenceIds)) {
  1573.                     return true;
  1574.                 } else if ($accessLevel == 2) {
  1575.                     // Check if user belongs to a support group assigned to ticket
  1576.                     $groupReferenceIds array_map(function ($group) { return $group->getId(); }, $agentInstance->getSupportGroups()->toArray());
  1577.                     if ($ticket->getSupportGroup() != null && in_array($ticket->getSupportGroup()->getId(), $groupReferenceIds)) {
  1578.                         return true;
  1579.                     }
  1580.                 }
  1581.             }
  1582.             return false;
  1583.         }
  1584.         return true;
  1585.     }
  1586.     public function addTicketCustomFields($thread$submittedCustomFields = [], $uploadedFilesCollection = [])
  1587.     {
  1588.         $customFieldsService null;
  1589.         $customFieldsEntityReference null;
  1590.         
  1591.         if ($this->userService->isfileExists('apps/uvdesk/custom-fields')) {
  1592.             $customFieldsService $this->container->get('uvdesk_package_custom_fields.service');
  1593.             $customFieldsEntityReference UVDeskCommunityPackages\CustomFields\Entity\CustomFields::class;
  1594.             $customFieldValuesEntityReference UVDeskCommunityPackages\CustomFields\Entity\CustomFieldsValues::class;
  1595.             $ticketCustomFieldValuesEntityReference UVDeskCommunityPackages\CustomFields\Entity\TicketCustomFieldsValues::class;
  1596.         } else if ($this->userService->isfileExists('apps/uvdesk/form-component')) {
  1597.             $customFieldsService $this->container->get('uvdesk_package_form_component.service');
  1598.             $customFieldsEntityReference UVDeskCommunityPackages\FormComponent\Entity\CustomFields::class;
  1599.             $customFieldValuesEntityReference UVDeskCommunityPackages\FormComponent\Entity\CustomFieldsValues::class;
  1600.             $ticketCustomFieldValuesEntityReference UVDeskCommunityPackages\FormComponent\Entity\TicketCustomFieldsValues::class;
  1601.         } else {
  1602.             return;
  1603.         }
  1604.         $ticket $thread->getTicket();
  1605.         $customFieldsCollection $this->entityManager->getRepository($customFieldsEntityReference)->findAll();
  1606.         $customFieldValuesEntityRepository $this->entityManager->getRepository($customFieldValuesEntityReference);
  1607.         foreach ($customFieldsCollection as $customFields) {
  1608.             if (in_array($customFields->getFieldType(), ['select''checkbox''radio']) && !count($customFields->getCustomFieldValues())) {
  1609.                 continue;
  1610.             }
  1611.             
  1612.             if (
  1613.                 !empty($submittedCustomFields
  1614.                 && $customFields->getFieldType() != 'file' 
  1615.                 && isset($submittedCustomFields[$customFields->getId()])
  1616.             ) {
  1617.                 // Check if custom field dependency criterias are fullfilled
  1618.                 if (
  1619.                     count($customFields->getCustomFieldsDependency()) 
  1620.                     && !in_array($ticket->getType(), $customFields->getCustomFieldsDependency()->toArray())
  1621.                 ) {
  1622.                     continue;
  1623.                 }
  1624.                 // Save ticket custom fields
  1625.                 $ticketCustomField = new $ticketCustomFieldValuesEntityReference();
  1626.                 $ticketCustomField
  1627.                     ->setTicket($ticket)
  1628.                     ->setTicketCustomFieldsValues($customFields)
  1629.                     ->setValue(json_encode($submittedCustomFields[$customFields->getId()]))
  1630.                 ;
  1631.                 if (in_array($customFields->getFieldType(), ['select''checkbox''radio'])) {
  1632.                     // Add custom field values mapping too
  1633.                     if (is_array($submittedCustomFields[$customFields->getId()])) {
  1634.                         foreach ($submittedCustomFields[$customFields->getId()] as $value) {
  1635.                             $ticketCustomFieldValues $customFieldValuesEntityRepository->findOneBy([
  1636.                                 'id' => $value
  1637.                                 'customFields' => $customFields
  1638.                             ]);
  1639.                             if (!empty($ticketCustomFieldValues)) {
  1640.                                 $ticketCustomField
  1641.                                     ->setTicketCustomFieldValueValues($ticketCustomFieldValues)
  1642.                                 ;
  1643.                             }
  1644.                         }
  1645.                     } else {
  1646.                         $ticketCustomFieldValues $customFieldValuesEntityRepository->findOneBy([
  1647.                             'id' => $submittedCustomFields[$customFields->getId()], 
  1648.                             'customFields' => $customFields
  1649.                         ]);
  1650.                         if (!empty($ticketCustomFieldValues)) {
  1651.                             $ticketCustomField
  1652.                                 ->setTicketCustomFieldValueValues($ticketCustomFieldValues)
  1653.                             ;
  1654.                         }
  1655.                     }
  1656.                 }
  1657.                 $this->entityManager->persist($ticketCustomField);
  1658.                 $this->entityManager->flush();
  1659.             } else if (
  1660.                 !empty($uploadedFilesCollection
  1661.                 && isset($uploadedFilesCollection[$customFields->getId()]) 
  1662.             ) {
  1663.                 // Upload files
  1664.                 $path '/custom-fields/ticket/' $ticket->getId() . '/';
  1665.                 $fileNames $this->fileUploadService->uploadFile($uploadedFilesCollection[$customFields->getid()], $pathtrue);
  1666.                 if (!empty($fileNames)) {
  1667.                     // Save files entry to attachment table
  1668.                     try {
  1669.                         $newFilesNames $customFieldsService->addFilesEntryToAttachmentTable([$fileNames], $thread);
  1670.                         foreach ($newFilesNames as $value) {
  1671.                             // Save ticket custom fields
  1672.                             $ticketCustomField = new $ticketCustomFieldValuesEntityReference();
  1673.                             $ticketCustomField
  1674.                                 ->setTicket($ticket)
  1675.                                 ->setTicketCustomFieldsValues($customFields)
  1676.                                 ->setValue(json_encode([
  1677.                                     'name' => $value['name'], 
  1678.                                     'path' => $value['path'], 
  1679.                                     'id' => $value['id'], 
  1680.                                 ]))
  1681.                             ;
  1682.                             $this->entityManager->persist($ticketCustomField);
  1683.                             $this->entityManager->flush();
  1684.                         }
  1685.                     } catch (\Exception $e) {
  1686.                         // @TODO: Log execption message
  1687.                     }
  1688.                 }
  1689.             }
  1690.         }
  1691.     }
  1692.     // return attachemnt for initial thread
  1693.     public function getInitialThread($ticketId)
  1694.     {
  1695.         $firstThread null;
  1696.         $intialThread $this->entityManager->getRepository(Thread::class)->findBy(['ticket'=>$ticketId]);
  1697.         
  1698.         foreach ($intialThread as $key => $value) {
  1699.             if ($value->getThreadType() == "create"){
  1700.                 $firstThread $value;
  1701.             }
  1702.         }
  1703.         return $firstThread;
  1704.     }
  1705. }