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

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