vendor/uvdesk/support-center-bundle/Controller/Ticket.php line 75

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