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