vendor\uvdesk\support-center-bundle\Controller\Ticket.php line 78

Open in your IDE?
  1. <?php
  2. namespace Webkul\UVDesk\SupportCenterBundle\Controller;
  3. use Symfony\Component\HttpFoundation\Request;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\EventDispatcher\GenericEvent;
  6. use Symfony\Component\Validator\Constraints\DateTime;
  7. use Symfony\Component\Security\Core\User\UserInterface;
  8. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  9. use Webkul\UVDesk\SupportCenterBundle\Form\Ticket as TicketForm;
  10. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  11. use Webkul\UVDesk\CoreFrameworkBundle\Workflow\Events as CoreWorkflowEvents;
  12. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  13. use Webkul\UVDesk\CoreFrameworkBundle\Services\UserService;
  14. use Webkul\UVDesk\CoreFrameworkBundle\Services\UVDeskService;
  15. use Webkul\UVDesk\CoreFrameworkBundle\Services\TicketService;
  16. use Webkul\UVDesk\CoreFrameworkBundle\Services\CustomFieldsService;
  17. use Webkul\UVDesk\CoreFrameworkBundle\FileSystem\FileSystem;
  18. use Symfony\Contracts\Translation\TranslatorInterface;
  19. use Webkul\UVDesk\CoreFrameworkBundle\Services\ReCaptchaService;
  20. use Symfony\Component\DependencyInjection\ContainerInterface;
  21. use Symfony\Component\HttpKernel\KernelInterface;
  22. use Webkul\UVDesk\SupportCenterBundle\Entity as SupportEntites;
  23. use Webkul\UVDesk\CoreFrameworkBundle\Entity as CoreEntites;
  24. class Ticket extends AbstractController
  25. {
  26.     private $userService;
  27.     private $eventDispatcher;
  28.     private $translator;
  29.     private $uvdeskService;
  30.     private $ticketService;
  31.     private $CustomFieldsService;
  32.     private $recaptchaService;
  33.     private $kernel;
  34.     public function __construct(UserService $userServiceUVDeskService $uvdeskService,EventDispatcherInterface $eventDispatcherTranslatorInterface $translatorTicketService $ticketServiceCustomFieldsService $CustomFieldsServiceReCaptchaService $recaptchaServiceKernelInterface $kernel)
  35.     {
  36.         $this->userService $userService;
  37.         $this->eventDispatcher $eventDispatcher;
  38.         $this->translator $translator;
  39.         $this->uvdeskService $uvdeskService;
  40.         $this->ticketService $ticketService;
  41.         $this->CustomFieldsService $CustomFieldsService;
  42.         $this->recaptchaService $recaptchaService;
  43.         $this->kernel $kernel;
  44.     }
  45.     protected function isWebsiteActive()
  46.     {
  47.         $entityManager $this->getDoctrine()->getManager();
  48.         $website $entityManager->getRepository(CoreEntites\Website::class)->findOneByCode('knowledgebase');
  49.         if (!empty($website)) {
  50.             $knowledgebaseWebsite $entityManager->getRepository(SupportEntites\KnowledgebaseWebsite::class)->findOneBy(['website' => $website->getId(), 'status' => 1]);
  51.             
  52.             if (!empty($knowledgebaseWebsite) && true == $knowledgebaseWebsite->getIsActive()) {
  53.                 return true;
  54.             }
  55.         }
  56.         $this->noResultFound();
  57.     }
  58.     /**
  59.      * If customer is playing with url and no result is found then what will happen
  60.      * @return
  61.      */
  62.     protected function noResultFound()
  63.     {
  64.         throw new NotFoundHttpException('Not found !');
  65.     }
  66.     public function ticketadd(Request $requestContainerInterface $container)
  67.     {
  68.         $this->isWebsiteActive();
  69.         
  70.         $formErrors $errors = array();
  71.         $em $this->getDoctrine()->getManager();
  72.         $website $em->getRepository(CoreEntites\Website::class)->findOneByCode('knowledgebase');
  73.         $websiteConfiguration $this->uvdeskService->getActiveConfiguration($website->getId());
  74.         if (!$websiteConfiguration || !$websiteConfiguration->getTicketCreateOption() || ($websiteConfiguration->getLoginRequiredToCreate() && !$this->getUser())) {
  75.             return $this->redirect($this->generateUrl('helpdesk_knowledgebase'));
  76.         }
  77.         $post $request->request->all();
  78.         $recaptchaDetails $this->recaptchaService->getRecaptchaDetails();
  79.         if($request->getMethod() == "POST") {
  80.             if ($recaptchaDetails && $recaptchaDetails->getIsActive() == true && $this->recaptchaService->getReCaptchaResponse($request->request->get('g-recaptcha-response'))
  81.             ) {
  82.                 $this->addFlash('warning'$this->translator->trans("Warning ! Please select correct CAPTCHA !"));
  83.             } else {
  84.                 if($_POST) {
  85.                     $error false;
  86.                     $message '';
  87.                     $ticketType $em->getRepository(CoreEntites\TicketType::class)->find($request->request->get('type'));
  88.                     
  89.                     if($request->files->get('customFields') && !$this->CustomFieldsService->validateAttachmentsSize($request->files->get('customFields'))) {
  90.                         $error true;
  91.                         $this->addFlash(
  92.                                 'warning',
  93.                                 $this->translator->trans("Warning ! Files size can not exceed %size% MB", [
  94.                                     '%size%' => $this->getParameter('max_upload_size')
  95.                                 ])
  96.                             );
  97.                     }
  98.     
  99.                     $ticket = new CoreEntites\Ticket();
  100.                     $loggedUser $this->get('security.token_storage')->getToken()->getUser();
  101.                     
  102.                     if(!empty($loggedUser) && $loggedUser != 'anon.') {
  103.                         
  104.                         $form $this->createForm(TicketForm::class, $ticket, [
  105.                             'container' => $container,
  106.                             'entity_manager' => $em,
  107.                         ]);
  108.                         $email $loggedUser->getEmail();
  109.                         try {
  110.                             $name $loggedUser->getFirstName() . ' ' $loggedUser->getLastName();
  111.                         } catch(\Exception $e) {
  112.                             $name explode(' 'strstr($email'@'true));
  113.                         }
  114.                     } else {
  115.                         $form $this->createForm(TicketForm::class, $ticket, [
  116.                             'container' => $container,
  117.                             'entity_manager' => $em,
  118.                         ]);
  119.                         $email $request->request->get('from');
  120.                         $name explode(' '$request->request->get('name'));
  121.                     }
  122.     
  123.                     $website $em->getRepository(CoreEntites\Website::class)->findOneByCode('knowledgebase');
  124.                     if(!empty($email) && $this->ticketService->isEmailBlocked($email$website)) {
  125.                         $request->getSession()->getFlashBag()->set('warning'$this->translator->trans('Warning ! Cannot create ticket, given email is blocked by admin.'));
  126.                         return $this->redirect($this->generateUrl('helpdesk_customer_create_ticket'));
  127.                     }
  128.     
  129.                     if($request->request->all())
  130.                         $form->submit($request->request->all());
  131.     
  132.                     if ($form->isValid() && !count($formErrors) && !$error) {
  133.                         $data = array(
  134.                             'from' => $email//email$request->getSession()->getFlashBag()->set('success', $this->translator->trans('Success ! Ticket has been created successfully.'));
  135.                             'subject' => $request->request->get('subject'),
  136.                             // @TODO: We need to filter js (XSS) instead of html
  137.                             'reply' => str_replace(['&lt;script&gt;''&lt;/script&gt;'], ''htmlspecialchars($request->request->get('reply'))),
  138.                             'firstName' => $name[0],
  139.                             'lastName' => isset($name[1]) ? $name[1] : '',
  140.                             'role' => 4,
  141.                             'active' => true
  142.                         );
  143.     
  144.                         $em $this->getDoctrine()->getManager();
  145.                         $data['type'] = $em->getRepository(CoreEntites\TicketType::class)->find($request->request->get('type'));
  146.     
  147.                         if(!is_object($data['customer'] = $this->container->get('security.token_storage')->getToken()->getUser()) == "anon.") {
  148.                             $supportRole $em->getRepository(CoreEntites\SupportRole::class)->findOneByCode("ROLE_CUSTOMER");
  149.     
  150.                             $customerEmail $params['email'] = $request->request->get('from');
  151.                             $customer $em->getRepository(CoreEntites\User::class)->findOneBy(array('email' => $customerEmail));
  152.                             $params['flag'] = (!$customer) ? 0;
  153.     
  154.                             $data['firstName'] = current($nameDetails explode(' '$request->request->get('name')));
  155.                             $data['fullname'] = $request->request->get('name');
  156.                             $data['lastName'] = ($data['firstName'] != end($nameDetails)) ? end($nameDetails) : " ";
  157.                             $data['from'] = $customerEmail;
  158.                             $data['role'] = 4;
  159.                             $data['customer'] = $this->userService->createUserInstance($customerEmail$data['fullname'], $supportRole$extras = ["active" => true]);
  160.                         } else {
  161.                             $userDetail $em->getRepository(CoreEntites\User::class)->find($data['customer']->getId());
  162.                             $data['email'] = $customerEmail $data['customer']->getEmail();
  163.                             $nameCollection = [$userDetail->getFirstName(), $userDetail->getLastName()];
  164.                             $name implode(' '$nameCollection);
  165.                             $data['fullname'] = $name;
  166.                         }
  167.                         $data['user'] = $data['customer'];
  168.                         $data['subject'] = $request->request->get('subject');
  169.                         $data['source'] = 'website';
  170.                         $data['threadType'] = 'create';
  171.                         $data['message'] = $data['reply'];
  172.                         $data['createdBy'] = 'customer';
  173.                         $data['attachments'] = $request->files->get('attachments');
  174.     
  175.                         if(!empty($request->server->get("HTTP_CF_CONNECTING_IP") )) {
  176.                             $data['ipAddress'] = $request->server->get("HTTP_CF_CONNECTING_IP");
  177.                             if(!empty($request->server->get("HTTP_CF_IPCOUNTRY"))) {
  178.                                 $data['ipAddress'] .= '(' $request->server->get("HTTP_CF_IPCOUNTRY") . ')';
  179.                             }
  180.                         }
  181.     
  182.                         $thread $this->ticketService->createTicketBase($data);
  183.                         
  184.                         if (!empty($thread)) {
  185.                             $ticket $thread->getTicket();
  186.                             if($request->request->get('customFields') || $request->files->get('customFields')) {
  187.                                 $this->ticketService->addTicketCustomFields($thread$request->request->get('customFields'), $request->files->get('customFields'));                        
  188.                             }
  189.                             $this->addFlash('success'$this->translator->trans('Success ! Ticket has been created successfully.'));
  190.                         } else {
  191.                             $this->addFlash('warning'$this->translator->trans('Warning ! Can not create ticket, invalid details.'));
  192.                         }
  193.                         // Trigger ticket created event
  194.                         $event = new GenericEvent(CoreWorkflowEvents\Ticket\Create::getId(), [
  195.                             'entity' => $thread->getTicket(),
  196.                         ]);
  197.     
  198.                         $this->eventDispatcher->dispatch($event'uvdesk.automation.workflow.execute');
  199.     
  200.                         if(null != $this->getUser()) {
  201.                             return $this->redirect($this->generateUrl('helpdesk_customer_ticket_collection'));
  202.                         } else {
  203.                             return $this->redirect($this->generateUrl('helpdesk_knowledgebase'));
  204.                         }
  205.                         
  206.                     } else {
  207.                         $errors $this->getFormErrors($form);
  208.                         $errors array_merge($errors$formErrors);
  209.                     }
  210.                 } else {
  211.                     $this->addFlash(
  212.                         'warning',
  213.                         $this->translator->trans("Warning ! Post size can not exceed 25MB")
  214.                     );
  215.                 }
  216.     
  217.                 if(isset($errors) && count($errors)) {
  218.                     $this->addFlash('warning'key($errors) . ': ' reset($errors));
  219.                 }
  220.             }
  221.         }
  222.         $breadcrumbs = [
  223.             [
  224.                 'label' => $this->translator->trans('Support Center'),
  225.                 'url' => $this->generateUrl('helpdesk_knowledgebase')
  226.             ],
  227.             [
  228.                 'label' => $this->translator->trans("Create Ticket Request"),
  229.                 'url' => '#'
  230.             ],
  231.         ];
  232.         return $this->render('@UVDeskSupportCenter/Knowledgebase/ticket.html.twig',
  233.             array(
  234.                 'formErrors' => $formErrors,
  235.                 'errors' => json_encode($errors),
  236.                 'customFieldsValues' => $request->request->get('customFields'),
  237.                 'breadcrumbs' => $breadcrumbs,
  238.                 'post' => $post
  239.             )
  240.         );
  241.     }
  242.     public function ticketList(Request $request)
  243.     {
  244.         $em $this->getDoctrine()->getManager();
  245.         $ticketRepo $em->getRepository(CoreEntites\Ticket::class);
  246.         $currentUser $this->get('security.token_storage')->getToken()->getUser();
  247.         if(!$currentUser || $currentUser == "anon.") {
  248.             //throw error
  249.         }
  250.         
  251.         $tickets $ticketRepo->getAllCustomerTickets($currentUser);
  252.         
  253.         return $this->render('@UVDeskSupportCenter/Knowledgebase/ticketList.html.twig', array(
  254.             'ticketList' => $tickets,
  255.         ));
  256.     }
  257.     public function saveReply(int $idRequest $request)
  258.     {
  259.         $this->isWebsiteActive();
  260.         $data $request->request->all();
  261.         $ticket $this->getDoctrine()->getRepository(CoreEntites\Ticket::class)->find($id);
  262.         $user $this->userService->getSessionUser();
  263.         // process only if access for the resource.
  264.         if (empty($ticket) || ( (!empty($user)) && $user->getId() != $ticket->getCustomer()->getId()) ) {
  265.             if(!$this->isCollaborator($ticket$user)) {
  266.                 throw new \Exception('Access Denied'403);
  267.             }
  268.         }
  269.         if($_POST) {
  270.             if(str_replace(' ','',str_replace('&nbsp;','',trim(strip_tags($data['message'], '<img>')))) != "") {
  271.                 if(!$ticket)
  272.                     $this->noResultFound();
  273.                 $data['ticket'] = $ticket;
  274.                 $data['user'] = $this->userService->getCurrentUser();
  275.                 // Checking if reply is from collaborator end
  276.                 $isTicketCollaborator $ticket->getCollaborators() ? $ticket->getCollaborators()->toArray() : [];
  277.                 $isCollaborator false;
  278.                 foreach ($isTicketCollaborator as $value) {
  279.                     if($value->getId() == $data['user']->getId()){
  280.                         $isCollaborator true;
  281.                     }
  282.                 }
  283.                 // @TODO: Refactor -> Why are we filtering only these two characters?
  284.                 $data['message'] = str_replace(['&lt;script&gt;''&lt;/script&gt;'], ''htmlspecialchars($data['message']));
  285.                 $userDetail $this->userService->getCustomerPartialDetailById($data['user']->getId());
  286.                 $data['fullname'] = $userDetail['name'];
  287.                 $data['source'] = 'website';
  288.                 $data['createdBy'] = $isCollaborator 'collaborator' 'customer';
  289.                 $data['attachments'] = $request->files->get('attachments');
  290.                 $thread $this->ticketService->createThread($ticket$data);
  291.                 $em $this->getDoctrine()->getManager();
  292.                 $status $em->getRepository(CoreEntites\TicketStatus::class)->findOneByCode($data['status']);
  293.                 if($status) {
  294.                     $flag 0;
  295.                     if($ticket->getStatus() != $status) {
  296.                         $flag 1;
  297.                     }
  298.                     $ticket->setStatus($status);
  299.                     $em->persist($ticket);
  300.                     $em->flush();
  301.                 }
  302.                 if ($thread->getcreatedBy() == 'customer') {
  303.                     $event = new GenericEvent(CoreWorkflowEvents\Ticket\CustomerReply::getId(), [
  304.                         'entity' =>  $ticket,
  305.                         'thread' =>  $thread
  306.                     ]);
  307.                 } else {
  308.                     $event = new GenericEvent(CoreWorkflowEvents\Ticket\CollaboratorReply::getId(), [
  309.                         'entity' =>  $ticket,
  310.                         'thread' =>  $thread
  311.                     ]);
  312.                 }
  313.                 $this->eventDispatcher->dispatch($event'uvdesk.automation.workflow.execute');
  314.                 $this->addFlash('success'$this->translator->trans('Success ! Reply added successfully.'));
  315.             } else {
  316.                 $this->addFlash('warning'$this->translator->trans('Warning ! Reply field can not be blank.'));
  317.             }
  318.         } else {
  319.             $this->addFlash('warning'$this->translator->trans('Warning ! Post size can not exceed 25MB'));
  320.         }
  321.         return $this->redirect($this->generateUrl('helpdesk_customer_ticket',array(
  322.             'id' => $ticket->getId()
  323.         )));
  324.     }
  325.     public function tickets(Request $request)
  326.     {
  327.         $this->isWebsiteActive();
  328.         // List Announcement if any
  329.         $announcements =  $this->getDoctrine()->getRepository(SupportEntites\Announcement::class)->findBy(['isActive' => 1]);
  330.         $groupAnnouncement = [];
  331.         foreach($announcements as $announcement) {
  332.             $announcementGroupId $announcement->getGroup();
  333.             $isTicketExist =  $this->getDoctrine()->getRepository(CoreEntites\Ticket::class)->findBy(['supportGroup' => $announcementGroupId'customer' => $this->userService->getCurrentUser()]);
  334.             if (!empty($isTicketExist)) {
  335.                 $groupAnnouncement[] = $announcement;
  336.             }
  337.         }
  338.         return $this->render('@UVDeskSupportCenter/Knowledgebase/ticketList.html.twig',
  339.             array(
  340.                 'searchDisable' => true,
  341.                 'groupAnnouncement' => $groupAnnouncement
  342.             )
  343.         );
  344.     }
  345.     /**
  346.      * ticketListXhrAction "Filter and sort ticket collection on ajax request"
  347.      * @param Object $request "HTTP Request object"
  348.      * @return JSON "JSON response"
  349.      */
  350.     public function ticketListXhr(Request $requestContainerInterface $container)
  351.     {
  352.         $this->isWebsiteActive();
  353.         $json = array();
  354.         if($request->isXmlHttpRequest()) {
  355.             $repository $this->getDoctrine()->getRepository(CoreEntites\Ticket::class);
  356.     
  357.             $json $repository->getAllCustomerTickets($request->query$container);
  358.         }
  359.         $response = new Response(json_encode($json));
  360.         $response->headers->set('Content-Type''application/json');
  361.         return $response;
  362.     }
  363.     /**
  364.      * threadListXhrAction "Filter and sort user collection on ajx request"
  365.      * @param Object $request "HTTP Request object"
  366.      * @return JSON "JSON response"
  367.      */
  368.     public function threadListXhr(Request $requestContainerInterface $container)
  369.     {
  370.         $this->isWebsiteActive();
  371.         $json = array();
  372.         if($request->isXmlHttpRequest()) {
  373.             $ticket $this->getDoctrine()->getRepository(CoreEntites\Ticket::class)->find($request->attributes->get('id'));
  374.             // $this->denyAccessUnlessGranted('FRONT_VIEW', $ticket);
  375.             $repository $this->getDoctrine()->getRepository(CoreEntites\Thread::class);
  376.             $json $repository->getAllCustomerThreads($request->attributes->get('id'),$request->query$container);
  377.         }
  378.         $response = new Response(json_encode($json));
  379.         $response->headers->set('Content-Type''application/json');
  380.         return $response;
  381.     }
  382.     public function ticketView($idRequest $request)
  383.     {
  384.         $this->isWebsiteActive();
  385.         $entityManager $this->getDoctrine()->getManager();
  386.         $user $this->userService->getSessionUser();
  387.         $ticket $entityManager->getRepository(CoreEntites\Ticket::class)->findOneBy(['id' => $id]);
  388.         $isConfirmColl false;
  389.         if ($ticket == null && empty($ticket)) {
  390.             throw new NotFoundHttpException('Page Not Found!');
  391.         }
  392.         if (!empty($ticket) && ( (!empty($user)) && $user->getId() != $ticket->getCustomer()->getId()) ) {
  393.             if($this->isCollaborator($ticket$user)) {
  394.                 $isConfirmColl true;
  395.             }
  396.             if ($isConfirmColl != true) {
  397.                 throw new \Exception('Access Denied'403);
  398.             } 
  399.         }
  400.         if (!empty($user) && $user->getId() == $ticket->getCustomer()->getId()) {
  401.             $ticket->setIsCustomerViewed(1);
  402.             $entityManager->persist($ticket);
  403.             $entityManager->flush();
  404.         }
  405.         $checkTicket $entityManager->getRepository(CoreEntites\Ticket::class)->isTicketCollaborator($ticket$user->getEmail());
  406.         
  407.         $twigResponse = [
  408.             'ticket' => $ticket,
  409.             'searchDisable' => true,
  410.             'initialThread' => $this->ticketService->getTicketInitialThreadDetails($ticket),
  411.             'localizedCreateAtTime' => $this->userService->getLocalizedFormattedTime($ticket->getCreatedAt(), $user),
  412.             'isCollaborator' => $checkTicket,
  413.         ];
  414.         return $this->render('@UVDeskSupportCenter/Knowledgebase/ticketView.html.twig'$twigResponse);
  415.     }
  416.     // Check if user is collaborator for the ticket
  417.     public function isCollaborator($ticket$user) {
  418.         $isCollaborator false;
  419.         if(!empty($ticket->getCollaborators()->toArray())) {
  420.             foreach($ticket->getCollaborators()->toArray() as $collaborator) {
  421.                 if($collaborator->getId() == $user->getId()) {
  422.                     $isCollaborator true;
  423.                 }
  424.             }
  425.         }
  426.         return $isCollaborator;
  427.     }
  428.     // Ticket rating
  429.     public function rateTicket(Request $request) {
  430.         $this->isWebsiteActive();
  431.         $json = array();
  432.         $em $this->getDoctrine()->getManager();
  433.         $data json_decode($request->getContent(), true);
  434.         $id $data['id'];
  435.         $count intval($data['rating']);
  436.         
  437.         if($count || $count 6) {
  438.             $ticket $em->getRepository(CoreEntites\Ticket::class)->find($id);
  439.             $customer $this->userService->getCurrentUser();
  440.             $rating $em->getRepository(CoreEntites\TicketRating::class)->findOneBy(array('ticket' => $id,'customer'=>$customer->getId()));
  441.             if($rating) {
  442.                 $rating->setcreatedAt(new \DateTime);
  443.                 $rating->setStars($count);
  444.                 $em->persist($rating);
  445.                 $em->flush();
  446.             } else {
  447.                 $rating = new CoreEntites\TicketRating();
  448.                 $rating->setStars($count);
  449.                 $rating->setCustomer($customer);
  450.                 $rating->setTicket($ticket);
  451.                 $em->persist($rating);
  452.                 $em->flush();
  453.             }
  454.             $json['alertClass'] = 'success';
  455.             $json['alertMessage'] = $this->translator->trans('Success ! Rating has been successfully added.');
  456.         } else {
  457.             $json['alertClass'] = 'danger';
  458.             $json['alertMessage'] = $this->translator->trans('Warning ! Invalid rating.');
  459.         }
  460.         $response = new Response(json_encode($json));
  461.         $response->headers->set('Content-Type''application/json');
  462.         return $response;
  463.     }
  464.     public function downloadAttachmentZip(Request $request)
  465.     {
  466.         $threadId $request->attributes->get('threadId');
  467.         $attachmentRepository $this->getDoctrine()->getManager()->getRepository(CoreEntites\Attachment::class);
  468.         $threadRepository $this->getDoctrine()->getManager()->getRepository(CoreEntites\Thread::class);
  469.         $thread $threadRepository->findOneById($threadId);
  470.         $attachment $attachmentRepository->findByThread($threadId);
  471.         if (!$attachment) {
  472.             $this->noResultFound();
  473.         }
  474.         $ticket $thread->getTicket();
  475.         $user $this->userService->getSessionUser();
  476.         
  477.         // process only if access for the resource.
  478.         if (empty($ticket) || ( (!empty($user)) && $user->getId() != $ticket->getCustomer()->getId()) ) {
  479.             if(!$this->isCollaborator($ticket$user)) {
  480.                 throw new \Exception('Access Denied'403);
  481.             }
  482.         }
  483.         $zipname 'attachments/' .$threadId.'.zip';
  484.         $zip = new \ZipArchive;
  485.         $zip->open($zipname\ZipArchive::CREATE);
  486.         if(count($attachment)){
  487.             foreach ($attachment as $attach) {
  488.                 $zip->addFile(substr($attach->getPath(), 1)); 
  489.             }
  490.         }
  491.         $zip->close();
  492.         $response = new Response();
  493.         $response->setStatusCode(200);
  494.         $response->headers->set('Content-type''application/zip');
  495.         $response->headers->set('Content-Disposition''attachment; filename=' $threadId '.zip');
  496.         $response->sendHeaders();
  497.         $response->setContent(readfile($zipname));
  498.         return $response;
  499.     }
  500.     public function downloadAttachment(Request $request)
  501.     {
  502.         $attachmendId $request->attributes->get('attachmendId');
  503.         $attachmentRepository $this->getDoctrine()->getManager()->getRepository(CoreEntites\Attachment::class);
  504.         $attachment $attachmentRepository->findOneById($attachmendId);
  505.         $baseurl $request->getScheme() . '://' $request->getHttpHost() . $request->getBasePath();
  506.         if (!$attachment) {
  507.             $this->noResultFound();
  508.         }
  509.         $ticket $attachment->getThread()->getTicket();
  510.         $user $this->userService->getSessionUser();
  511.         
  512.         // process only if access for the resource.
  513.         if (empty($ticket) || ( (!empty($user)) && $user->getId() != $ticket->getCustomer()->getId()) ) {
  514.             if(!$this->isCollaborator($ticket$user)) {
  515.                 throw new \Exception('Access Denied'403);
  516.             }
  517.         }
  518.         $path $this->kernel->getProjectDir() . "/public/"$attachment->getPath();
  519.         $response = new Response();
  520.         $response->setStatusCode(200);
  521.         
  522.         $response->headers->set('Content-type'$attachment->getContentType());
  523.         $response->headers->set('Content-Disposition''attachment; filename='$attachment->getName());
  524.         $response->headers->set('Content-Length'$attachment->getSize());
  525.         $response->sendHeaders();
  526.         $response->setContent(readfile($path));
  527.         
  528.         return $response;
  529.     }
  530.     
  531.     public function ticketCollaboratorXhr(Request $request)
  532.     {
  533.         $json = array();
  534.         $content json_decode($request->getContent(), true);
  535.         $em $this->getDoctrine()->getManager();
  536.         $ticket $em->getRepository(CoreEntites\Ticket::class)->find($content['ticketId']);
  537.         $user $this->userService->getSessionUser();
  538.         
  539.         // process only if access for the resource.
  540.         if (empty($ticket) || ( (!empty($user)) && $user->getId() != $ticket->getCustomer()->getId()) ) {
  541.             if(!$this->isCollaborator($ticket$user)) {
  542.                 throw new \Exception('Access Denied'403);
  543.             }
  544.         }
  545.         
  546.         if ($request->getMethod() == "POST") {
  547.             if ($content['email'] == $ticket->getCustomer()->getEmail()) {
  548.                 $json['alertClass'] = 'danger';
  549.                 $json['alertMessage'] = $this->translator->trans('Error ! Can not add customer as a collaborator.');
  550.             } else {
  551.                 $data = array(
  552.                     'from' => $content['email'],
  553.                     'firstName' => ($firstName ucfirst(current(explode('@'$content['email'])))),
  554.                     'lastName' => ' ',
  555.                     'role' => 4,
  556.                 );
  557.                 $supportRole $em->getRepository(CoreEntites\SupportRole::class)->findOneByCode('ROLE_CUSTOMER');
  558.                 $collaborator $this->userService->createUserInstance($data['from'], $data['firstName'], $supportRole$extras = ["active" => true]);
  559.                 
  560.                 $checkTicket $em->getRepository(CoreEntites\Ticket::class)->isTicketCollaborator($ticket,$content['email']);
  561.                 
  562.                 if (!$checkTicket) {
  563.                     $ticket->addCollaborator($collaborator);
  564.                     $em->persist($ticket);
  565.                     $em->flush();
  566.                     $ticket->lastCollaborator $collaborator;
  567.                     $collaborator $em->getRepository(CoreEntites\User::class)->find($collaborator->getId());
  568.                     
  569.                     $event = new GenericEvent(CoreWorkflowEvents\Ticket\Collaborator::getId(), [
  570.                         'entity' => $ticket,
  571.                     ]);
  572.                     $this->eventDispatcher->dispatch($event'uvdesk.automation.workflow.execute');
  573.                    
  574.                     $json['collaborator'] =  $this->userService->getCustomerPartialDetailById($collaborator->getId());
  575.                     $json['alertClass'] = 'success';
  576.                     $json['alertMessage'] = $this->translator->trans('Success ! Collaborator added successfully.');
  577.                 } else {
  578.                     $json['alertClass'] = 'danger';
  579.                     $json['alertMessage'] = $this->translator->trans('Error ! Collaborator is already added.');
  580.                 }
  581.             }
  582.         } elseif ($request->getMethod() == "DELETE") {
  583.             $collaborator $em->getRepository(CoreEntites\User::class)->findOneBy(array('id' => $request->attributes->get('id')));
  584.             
  585.             if ($collaborator) {
  586.                 $ticket->removeCollaborator($collaborator);
  587.                 $em->persist($ticket);
  588.                 $em->flush();
  589.                 $json['alertClass'] = 'success';
  590.                 $json['alertMessage'] = $this->translator->trans('Success ! Collaborator removed successfully.');
  591.             } else {
  592.                 $json['alertClass'] = 'danger';
  593.                 $json['alertMessage'] = $this->translator->trans('Error ! Invalid Collaborator.');
  594.             }
  595.         }
  596.         $response = new Response(json_encode($json));
  597.         $response->headers->set('Content-Type''application/json');
  598.         return $response;
  599.     }
  600. }