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

Open in your IDE?
  1. <?php
  2. //SI
  3. namespace Webkul\UVDesk\SupportCenterBundle\Controller;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\EventDispatcher\GenericEvent;
  7. use Webkul\UVDesk\CoreFrameworkBundle\Entity\Thread;
  8. use Webkul\UVDesk\CoreFrameworkBundle\Entity\Website;
  9. use Symfony\Component\Validator\Constraints\DateTime;
  10. use Symfony\Component\Security\Core\User\UserInterface;
  11. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  12. use Webkul\UVDesk\CoreFrameworkBundle\Entity\TicketRating;
  13. use Webkul\UVDesk\SupportCenterBundle\Form\Ticket as TicketForm;
  14. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  15. use Webkul\UVDesk\SupportCenterBundle\Entity\KnowledgebaseWebsite;
  16. use Webkul\UVDesk\CoreFrameworkBundle\Entity\Ticket as TicketEntity;
  17. use Webkul\UVDesk\CoreFrameworkBundle\Workflow\Events as CoreWorkflowEvents;
  18. use Symfony\Component\Process\PhpProcess;
  19. use Webkul\UVDesk\SupportCenterBundle\Controller\ObjClient;
  20. use Webkul\UVDesk\CoreFrameworkBundle\Entity\Attachment;
  21. use Webkul\UVDesk\CoreFrameworkBundle\Entity\SupportTicketSubtypes;
  22. class Ticket extends Controller
  23. {
  24.     protected function isWebsiteActive()
  25.     {
  26.         $entityManager $this->getDoctrine()->getManager();
  27.         $website $entityManager->getRepository(Website::class)->findOneByCode('knowledgebase');
  28.         if (!empty($website)) {
  29.             $knowledgebaseWebsite $entityManager->getRepository(KnowledgebaseWebsite::class)->findOneBy(['website' => $website->getId(), 'status' => 1]);
  30.             
  31.             if (!empty($knowledgebaseWebsite) && true == $knowledgebaseWebsite->getIsActive()) {
  32.                 return true;
  33.             }
  34.         }
  35.         $this->noResultFound();
  36.     }
  37.     /**
  38.      * If customer is playing with url and no result is found then what will happen
  39.      * @return
  40.      */
  41.     protected function noResultFound()
  42.     {
  43.         throw new NotFoundHttpException('Not found !');
  44.     }
  45.     public function solicitarUrgencia($ticket$entityManager)
  46.     {
  47.         $nova = array(" ");
  48.         //Modificacion para validar si se muestra el boton.
  49.         $currentThread $this->getDoctrine()->getRepository('UVDeskCoreFrameworkBundle:Thread')->getTicketCurrentThread($ticket);
  50.         $attachments $entityManager->getRepository(Attachment::class)->findByThread($currentThread);
  51.         $subject utf8_encode($ticket->getSubject());
  52.         $subject str_replace($nova"<BLANK>"$subject);
  53.         $msj utf8_encode($currentThread->getMessage());
  54.         $msj str_replace($nova"<BLANK>"$msj);
  55.         if(count($attachments)){
  56.             $pathutf8_encode($attachments[0]->getPath());
  57.             $path str_replace($nova"<BLANK>"$path);
  58.             $nameFileAttachment=utf8_encode($attachments[0]->getName());
  59.             $nameFileAttachment str_replace($nova"<BLANK>"$nameFileAttachment);
  60.         }else{
  61.             $nameFileAttachment=$path='';
  62.         }
  63.         $user $this->get('user.service')->getSessionUser();
  64.         $haveSupport file_get_contents($_ENV['EXTERNAL_PATH']."UserController.php?case=1&user=".$user->getEmail());
  65.         if($haveSupport==1//24/7
  66.             $TicketStatus $entityManager->getRepository('UVDeskCoreFrameworkBundle:TicketStatus')->findOneById("8"); //in process of attention
  67.         if($haveSupport==3//Low Cost
  68.             $TicketStatus $entityManager->getRepository('UVDeskCoreFrameworkBundle:TicketStatus')->findOneById("7");//Pending Payment
  69.         $TicketPriority $entityManager->getRepository('UVDeskCoreFrameworkBundle:TicketPriority')->findOneById("4"); // Urgent
  70.         $UserClient file_get_contents($_ENV['EXTERNAL_PATH']."UserController.php?case=3&user=".$user->getEmail());
  71.         $jsonUser=json_decode($UserClienttrue);
  72.         $str$_SERVER['HTTP_REFERER'];
  73.         $param_url=explode("public/",$str);
  74.         $lang=substr($param_url[1],0,2);
  75.         //$lang='es';
  76.         //$haveSupport=1;
  77.         $url=$_ENV['EXTERNAL_PATH']."TicketController.php?case=1&serial='".$jsonUser[0]["Nroserie"]."'&haveSupport='".$haveSupport."'&user='".$user->getEmail()."'&subject='".$subject."'&msj='".$msj."'&path='".$path."'&nameFileAttachment='".$nameFileAttachment."'&lang='".$lang."'&whatsapp='".$ticket->getWhatsapp()."'";
  78.         $idTicketSeries file_get_contents($url);
  79.         $ticket->setCodigoSeries($idTicketSeries);
  80.         $ticket->setPriority($TicketPriority);
  81.         $ticket->setStatus($TicketStatus);
  82.         $entityManager->persist($ticket);
  83.         $entityManager->flush();
  84.     }
  85.     
  86.      public function trans($text)
  87.     {
  88.         return $this->container->get('translator')->trans($text);
  89.     }
  90.     
  91. public function getTicketData(Request $request) {
  92.     $supportTicketSubtypesId $request->query->get('supportTicketSubtypesId');
  93.     // Conectar a la base de datos
  94.     $connection $this->getDoctrine()->getConnection();
  95.     // Consulta para obtener el subtipo de ticket
  96.     $subtypeQuery 'SELECT * FROM uv_ticket_subtype WHERE id = :id';
  97.     $stmt $connection->prepare($subtypeQuery);
  98.     $stmt->execute(['id' => $supportTicketSubtypesId]);
  99.     $supportTicketSubtype $stmt->fetch();
  100.     if (!$supportTicketSubtype) {
  101.         return new Response(json_encode(['error' => 'No se encontró el subtipo de ticket']), Response::HTTP_NOT_FOUND);
  102.     }
  103.     // Consulta para obtener los datos del ticket
  104.     $dataQuery '
  105.         SELECT d.id, d.data, d.tipo, ds.required
  106.         FROM uv_ticket_data d
  107.         JOIN uv_ticket_data_subtype ds ON ds.id_ticket_data = d.id
  108.         WHERE ds.id_ticket_subtype = :id_ticket_subtype
  109.     ';
  110.     $stmt $connection->prepare($dataQuery);
  111.     $stmt->execute(['id_ticket_subtype' => $supportTicketSubtypesId]);
  112.     $ticketDataCollection $stmt->fetchAll();
  113.     $translator $this->container->get('translator');
  114.        //     $emailPlaceholders['ticket.status'] = $translator->trans($emailPlaceholders['ticket.status'],[],'messages',$language);
  115.             
  116.     // Convertir los datos a un arreglo
  117.     $ticketDataArray = [];
  118.     foreach ($ticketDataCollection as $ticketData) {
  119.         $ticketDataArray[] = [
  120.             'data' => $translator->trans($ticketData['data']),
  121.             'required' => $ticketData['required'],
  122.             // Agrega otras propiedades que necesites
  123.         ];
  124.     }
  125.     // Preparar la respuesta
  126.     $responseArray = [
  127.         'id' => $supportTicketSubtype['id'],
  128.         'ticketData' => $ticketDataArray// Agrega la colección de TicketData
  129.     ];
  130.     return new Response(json_encode($responseArray), Response::HTTP_OK, ['Content-Type' => 'application/json']);
  131. }
  132.     public function ticketadd(Request $request)
  133.     {
  134.       
  135.         $this->isWebsiteActive();   
  136.         
  137.         $formErrors $errors = array();
  138.         $em $this->getDoctrine()->getManager();
  139.         $website $em->getRepository(Website::class)->findOneByCode('knowledgebase');
  140.         $websiteConfiguration $this->get('uvdesk.service')->getActiveConfiguration($website->getId());
  141.         if (!$websiteConfiguration || !$websiteConfiguration->getTicketCreateOption() || ($websiteConfiguration->getLoginRequiredToCreate() && !$this->getUser())) {
  142.             return $this->redirect($this->generateUrl('helpdesk_knowledgebase'));
  143.         }
  144.         $post $request->request->all();
  145.         $fueraDeHorario=file_get_contents($_ENV['EXTERNAL_PATH']."UserController.php?case=2");
  146.         //Validación día feriado
  147.         $esFeriado=file_get_contents($_ENV['EXTERNAL_PATH']."UserController.php?case=4");
  148.         $user $this->get('user.service')->getSessionUser();
  149.         //Horario comercial
  150.         $conexionSeries 1;
  151.         if($fueraDeHorario){
  152.             $isSupportActive=file_get_contents($_ENV['EXTERNAL_PATH']."UserController.php?case=1&user=".$user->getEmail());
  153.             //Si esta fuera de horario y no hay conexión , creo el ticket, no envío correo y muestro mensaje
  154.             if($isSupportActive == -1){
  155.                 $isSupportActive 1;
  156.                 $conexionSeries 0;
  157.             }
  158.         }else{
  159.             //Si esta en horario comercial creo el ticket, no consunlto info de plan de usuario a series y no envío correo
  160.             $isSupportActive=1;
  161.         }
  162.         if($request->getMethod() == "POST") {
  163.             //Solicitud de urgencia en session
  164.             $session $request->getSession();
  165.             if($session->get('critical')){
  166.                 $start_date = new \DateTime($session->get('critical'));
  167.                 $since_start $start_date->diff(new \DateTime(date("Y-m-d H:i:s")));
  168.                 if($since_start->10){
  169.                     $session->remove('critical');
  170.                 }else{
  171.                     $request->getSession()->getFlashBag()->set('warning'$this->get('translator')->trans('Warning ! You previously requested an emergency, please wait 10 minutes and try again.'));
  172.                     return $this->redirect($this->generateUrl('helpdesk_customer_create_ticket'));
  173.                 }
  174.             }
  175.             //Validaciones para estado critical/urgent
  176.             if($post['priority'] == 4){
  177.                 if($post['urgent_check']){
  178.                    /*  if($post['business_impact']){
  179.                         if($post['phone']){
  180.                         }else{
  181.                             $request->getSession()->getFlashBag()->set('warning', $this->get('translator')->trans('Warning ! Phone is required.'));
  182.                             return $this->redirect($this->generateUrl('helpdesk_customer_create_ticket'));
  183.                         }
  184.                     }else{
  185.                         $request->getSession()->getFlashBag()->set('warning', $this->get('translator')->trans('Warning ! Business impact is required.'));
  186.                         return $this->redirect($this->generateUrl('helpdesk_customer_create_ticket'));
  187.                     } */
  188.                 }else{
  189.                     $request->getSession()->getFlashBag()->set('warning'$this->get('translator')->trans('Warning ! Urgent check is required.'));
  190.                     return $this->redirect($this->generateUrl('helpdesk_customer_create_ticket'));
  191.                 }
  192.             }else{
  193.             }
  194.             /////////////////////////////
  195.             //INICIO CAMBIO :  Cuando NO tiene usuario activo debo crear el ticket pero se debe poner en estado "pendiente de pago" 
  196.             $user $this->get('user.service')->getSessionUser();
  197.             
  198.         //Horario comercial
  199.             $conexionSeries 1;
  200.             $fueraDeHorario=file_get_contents($_ENV['EXTERNAL_PATH']."UserController.php?case=2");
  201.             if($fueraDeHorario){
  202.                 $isSupportActive=file_get_contents($_ENV['EXTERNAL_PATH']."UserController.php?case=1&user=".$user->getEmail());
  203.                 //Si esta fuera de horario y no hay conexión , creo el ticket, no envío correo y muestro mensaje
  204.                 if($isSupportActive == -1){
  205.                     $isSupportActive 1;
  206.                     $conexionSeries 0;
  207.                 }
  208.             }else{
  209.                 //Si esta en horario comercial creo el ticket, no consunlto info de plan de usuario a series y no envío correo
  210.                 $isSupportActive=1;
  211.             }
  212.             //FIN CAMBIO /////////////////////////
  213.             
  214.             if($_POST) {
  215.                 $error false;
  216.                 $message '';
  217.                 $ticketType $em->getRepository('UVDeskCoreFrameworkBundle:TicketType')->find($request->request->get('type'));
  218.             
  219.                 
  220.                 if($request->files->get('customFields') && !$this->get('file.service')->validateAttachmentsSize($request->files->get('customFields'))) {
  221.                     $error true;
  222.                     $this->addFlash(
  223.                             'warning',
  224.                             $this->get('translator')->trans("Warning ! Files size can not exceed %size% MB", [
  225.                                 '%size%' => $this->container->getParameter('max_upload_size')
  226.                             ])
  227.                         );
  228.                 }
  229.                 $ticket = new TicketEntity();
  230.                 
  231.                 $loggedUser $this->get('security.token_storage')->getToken()->getUser();
  232.                 
  233.                 if(!empty($loggedUser) && $loggedUser != 'anon.') {
  234.                     
  235.                     $form $this->createForm(TicketForm::class, $ticket, [
  236.                         'container' => $this->container,
  237.                         'entity_manager' => $em,
  238.                     ]);
  239.                     $email $loggedUser->getEmail();
  240.                     try {
  241.                         $name $loggedUser->getFirstName() . ' ' $loggedUser->getLastName();
  242.                     } catch(\Exception $e) {
  243.                         $name explode(' 'strstr($email'@'true));
  244.                     }
  245.                 } else {
  246.                     $form $this->createForm(TicketForm::class, $ticket, [
  247.                         'container' => $this->container,
  248.                         'entity_manager' => $em,
  249.                     ]);
  250.                     $email $request->request->get('from');
  251.                     $name explode(' '$request->request->get('name'));
  252.                 }
  253.                 $website $em->getRepository('UVDeskCoreFrameworkBundle:Website')->findOneByCode('knowledgebase');
  254.                 if(!empty($email) && $this->container->get('ticket.service')->isEmailBlocked($email$website)) {
  255.                     $request->getSession()->getFlashBag()->set('warning'$this->get('translator')->trans('Warning ! Cannot create ticket, given email is blocked by admin.'));
  256.                     return $this->redirect($this->generateUrl('helpdesk_customer_create_ticket'));
  257.                 }
  258.                 if($request->request->all())
  259.                     $form->submit($request->request->all());
  260.                 if ($form->isValid() && !count($formErrors) && !$error) {
  261.                     $data = array(
  262.                         'from' => $email//email$request->getSession()->getFlashBag()->set('success', $this->get('translator')->trans('Success ! Ticket has been created successfully.'));
  263.                         'subject' => $request->request->get('subject'),
  264.                         'reference' => $request->request->get('reference'),
  265.                         // @TODO: We need to filter js (XSS) instead of html
  266.                         'reply' => strip_tags($request->request->get('reply')),
  267.                         'firstName' => $name[0],
  268.                         'lastName' => isset($name[1]) ? $name[1] : '',
  269.                         'role' => 4,
  270.                         'active' => true
  271.                     );
  272.                     $em $this->getDoctrine()->getManager();
  273.                     if($request->request->get('subtype')){
  274.                                 die(print_r($request->request->get('subtype')));
  275.                         $data['subtype'] =  $em->getRepository('UVDeskCoreFrameworkBundle:SupportTicketSubtypes')->find($request->request->get('subtype'));
  276.                     }
  277.                     
  278.                     
  279.             
  280.                     $data['type'] = $em->getRepository('UVDeskCoreFrameworkBundle:TicketType')->find($request->request->get('type'));
  281.                     $data['priority'] = $em->getRepository('UVDeskCoreFrameworkBundle:TicketPriority')->find($request->request->get('priority'));
  282.                     if(!is_object($data['customer'] = $this->container->get('security.token_storage')->getToken()->getUser()) == "anon.") {
  283.                         $supportRole $em->getRepository('UVDeskCoreFrameworkBundle:SupportRole')->findOneByCode("ROLE_CUSTOMER");
  284.                         $customerEmail $params['email'] = $request->request->get('from');
  285.                         $customer $em->getRepository('UVDeskCoreFrameworkBundle:User')->findOneBy(array('email' => $customerEmail));
  286.                         $params['flag'] = (!$customer) ? 0;$request->getSession()->getFlashBag()->set('success'$this->get('translator')->trans('Success ! Ticket has been created successfully.'));
  287.                         $data['firstName'] = current($nameDetails explode(' '$request->request->get('name')));
  288.                         $data['fullname'] = $request->request->get('name');
  289.                         $data['lastName'] = ($data['firstName'] != end($nameDetails)) ? end($nameDetails) : " ";
  290.                         $data['from'] = $customerEmail;
  291.                         $data['role'] = 4;
  292.                         $data['customer'] = $this->get('user.service')->createUserInstance($customerEmail$data['fullname'], $supportRole$extras = ["active" => true]);
  293.                     } else {
  294.                         $userDetail $em->getRepository('UVDeskCoreFrameworkBundle:User')->find($data['customer']->getId());
  295.                         $data['email'] = $customerEmail $data['customer']->getEmail();
  296.                         $nameCollection = [$userDetail->getFirstName(), $userDetail->getLastName()];
  297.                         $name implode(' '$nameCollection);
  298.                         $data['fullname'] = $name;
  299.                     }
  300.                     $data['user'] = $data['customer'];
  301.                     $data['subject'] = $request->request->get('subject');
  302.                     $data['reference'] = $request->request->get('reference');
  303.                     $data['source'] = 'website';
  304.                     $data['threadType'] = 'create';
  305.                     $data['message'] = str_replace(['&lt;script&gt;''&lt;/script&gt;'], ''htmlspecialchars($data['reply']));
  306.                     $data['message'] = nl2br($data['message']);
  307.                     $data['createdBy'] = 'customer';
  308.                     $data['attachments'] = $request->files->get('attachments');
  309.                     $data['businessImpact'] = $post['business_impact'] ? $post['business_impact']:'';
  310.                     $data['whatsapp'] = $post['phone'] ? $post['phone']:'';
  311.                     $data['urlPlataforma'] = $post['urlPlataforma'] ? $post['urlPlataforma']:'';
  312.                     
  313.                     //Si es soporte, se selecciona un subtipo y se asigna el ticket al agente de ese grupo de subtipo que menos tickets abiertos asignados tiene
  314.                     if($request->request->get('subtype')){
  315.                         $userService $this->container->get('user.service');
  316.                         $agentUsers $userService->getAgentUsersByTicketSubtype($request->request->get('subtype'));
  317.                         if($agentUsers[0]){
  318.                             $data['agent'] = $em->getRepository('UVDeskCoreFrameworkBundle:User')->findOneBy(array('id' => $agentUsers[0]['id']));
  319.                         }
  320.                     }
  321.                     if(!empty($request->server->get("HTTP_CF_CONNECTING_IP") )) {
  322.                         $data['ipAddress'] = $request->server->get("HTTP_CF_CONNECTING_IP");
  323.                         if(!empty($request->server->get("HTTP_CF_IPCOUNTRY"))) {
  324.                             $data['ipAddress'] .= '(' $request->server->get("HTTP_CF_IPCOUNTRY") . ')';
  325.                         }
  326.                     }
  327.                     ///// INICIO cambio estado tipo de licencias vencidas o resto de licencias que entren en el grupo (24/7, Low cost, Lunes a viernes)
  328.                     if($isSupportActive=='0' ||  $isSupportActive=='2'){
  329.                         
  330.                      if($conexionSeries == 0){
  331.                             $thread $this->get('ticket.service')->createTicketBase($data,1);
  332.                         }else{
  333.                             $thread $this->get('ticket.service')->createTicketBase($data,1); //estado pendiente de pago
  334.                             //envio email
  335.                             $user $this->get('user.service')->getSessionUser();
  336.                             $UserClient file_get_contents($_ENV['EXTERNAL_PATH']."UserController.php?case=3&user=".$user->getEmail());
  337.                             $jsonUser=json_decode($UserClienttrue);
  338.                             $url=$_ENV['EXTERNAL_PATH']."TicketController.php?case=2&serial='".$jsonUser[0]["Nroserie"]."'&haveSupport='".$isSupportActive."'&user='".$user->getEmail()."'&subject=''&msj=''&path=''&nameFileAttachment=''";
  339.                             $aClient=file_get_contents($url);
  340.                         }
  341.                     }
  342.                     else{
  343.                         $thread $this->get('ticket.service')->createTicketBase($data,1);
  344.                     }
  345.                     ///// FIN cambio 
  346.                     
  347.                     if ($thread) {
  348.                         if($conexionSeries == 0){
  349.                             $request->getSession()->getFlashBag()->set('warning'$this->get('translator')->trans('Success ! Ticket has been created successfully. SYSTEM IN RECOVERY, CONTACT SUPPORT AT sop24op@softguard.com'));
  350.                         }else{
  351.                             $request->getSession()->getFlashBag()->set('success'$this->get('translator')->trans('Success ! Ticket has been created successfully.'));
  352.                         }
  353.                     } else {
  354.                         $request->getSession()->getFlashBag()->set('warning'$this->get('translator')->trans('Warning ! Can not create ticket, invalid details.'));
  355.                     }
  356.                     // Trigger ticket created event
  357.                     $event = new GenericEvent(CoreWorkflowEvents\Ticket\Create::getId(), [
  358.                         'entity' => $thread->getTicket(),
  359.                     ]);
  360.                     $this->get('event_dispatcher')->dispatch('uvdesk.automation.workflow.execute'$event);
  361.                     
  362.                 
  363.                     //aca se debe mandar mail de pago, para lo cual se debe insertar en quotes. FALTA DEFINIR.
  364.                     //return $this->render('@UVDeskSupportCenter/Knowledgebase/ticketList.html.twig',
  365.                       //  array(
  366.                         //    'searchDisable' => true
  367.                        // )
  368.                     //);
  369.                     if($post['priority'] == 4) {
  370.                         
  371.                             $curl curl_init();
  372.                             curl_setopt_array($curl, array(
  373.                                 CURLOPT_URL => $_ENV['URL_API'].'token.php',
  374.                                 CURLOPT_RETURNTRANSFER => true,
  375.                                 CURLOPT_ENCODING => "",
  376.                                 CURLOPT_MAXREDIRS => 10,
  377.                                 CURLOPT_TIMEOUT => 240,
  378.                                 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  379.                                 CURLOPT_CUSTOMREQUEST => "GET",
  380.                                 CURLOPT_HTTPHEADER => array(
  381.                                     "cache-control: no-cache"
  382.                                 ),
  383.                             ));
  384.                     
  385.                             $responseToken curl_exec($curl);
  386.                     
  387.                     
  388.                     
  389.                             $jResponseToken=json_decode($responseTokentrue);
  390.                             $token=$jResponseToken['token'];
  391.                     
  392.                             $envioMensaje "https://sistema.softguard.com/sistema/sg/endpoint/ticketera-addlectura.php?t=".$token."&ticket=".$thread->getTicket()->getCodigoSeries()."&evento=6&ticketera=".$thread->getTicket()->getId();
  393.                    
  394.                     
  395.                             $curl curl_init();
  396.                             curl_setopt_array($curl, array(
  397.                                 CURLOPT_URL => $envioMensaje,
  398.                                 CURLOPT_RETURNTRANSFER => true,
  399.                                 CURLOPT_ENCODING => "",
  400.                                 CURLOPT_MAXREDIRS => 10,
  401.                                 CURLOPT_TIMEOUT => 240,
  402.                                 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  403.                                 CURLOPT_CUSTOMREQUEST => "POST",
  404.                                 CURLOPT_HTTPHEADER => array(
  405.                                     "cache-control: no-cache"
  406.                                 ),
  407.                             ));
  408.                     
  409.                             $idioms curl_exec($curl);
  410.                    
  411.                             curl_close($curl);
  412.                         $session->set('critical'date("Y-m-d H:i:s"));
  413.                         $this->solicitarUrgencia($thread->getTicket(), $em);
  414.                     }
  415.                     return $this->redirect($this->generateUrl('helpdesk_customer_ticket_collection'));
  416.                     //return $this->redirect($this->generateUrl('helpdesk_customer_create_ticket'));
  417.                 } else {
  418.                     $errors $this->getFormErrors($form);
  419.                     $errors array_merge($errors$formErrors);
  420.                 }
  421.             } else {
  422.                 $this->addFlash(
  423.                     'warning',
  424.                     $this->get('translator')->trans("Warning ! Post size can not exceed 25MB")
  425.                 );
  426.             }
  427.             if(isset($errors) && count($errors)) {
  428.                 $this->addFlash('warning'key($errors) . ': ' reset($errors));
  429.             }
  430.         }
  431.         $sesion=null;
  432.         if($this->get('user.service')->getSessionUser()!=null)
  433.             $sesion=true;
  434.         $breadcrumbs = [
  435.             [
  436.                 'label' => $this->get('translator')->trans('Support Center'),
  437.                 'url' => $this->generateUrl('helpdesk_knowledgebase'), 'sesion'=> $sesion
  438.             ],
  439.             [
  440.                 'label' => $this->get('translator')->trans("Create Ticket Request"),
  441.                 'url' => '#''sesion'=> $sesion
  442.             ],
  443.         ];
  444.         
  445.         return $this->render('@UVDeskSupportCenter/Knowledgebase/ticket.html.twig',
  446.             array(
  447.                 'formErrors' => $formErrors,
  448.                 'errors' => json_encode($errors),
  449.                 'customFieldsValues' => $request->request->get('customFields'),
  450.                 'breadcrumbs' => $breadcrumbs,
  451.                 'post' => $post,
  452.                 'fueraDeHorario' => $fueraDeHorario,
  453.                 'isSupportActive' => $isSupportActive,
  454.                 'esFeriado' => $esFeriado
  455.             )
  456.         );
  457.     }
  458.     public function ticketList(Request $request)
  459.     {
  460.         
  461.         $em $this->getDoctrine()->getManager();
  462.         $ticketRepo $em->getRepository('UVDeskCoreFrameworkBundle:Ticket');
  463.         $currentUser $this->get('security.token_storage')->getToken()->getUser();
  464.         if(!$currentUser || $currentUser == "anon.") {
  465.             //throw error
  466.         }
  467.         
  468.         $tickets $ticketRepo->getAllCustomerTickets($currentUser);
  469.     
  470.         return $this->render('@UVDeskSupportCenter/Knowledgebase/ticketList.html.twig', array(
  471.             'ticketList' => $tickets,
  472.         ));
  473.     }
  474.     public function changeStatus(int $id,Request $request){
  475.         
  476.         $nova = array(" ");
  477.         $entityManager $this->getDoctrine()->getManager();
  478.         $ticket $this->getDoctrine()->getRepository('UVDeskCoreFrameworkBundle:Ticket')->find($id);
  479.         //Solicitud de urgencia en session
  480.         $session $request->getSession();
  481.         if($session->get('critical')){
  482.             $start_date = new \DateTime($session->get('critical'));
  483.             $since_start $start_date->diff(new \DateTime(date("Y-m-d H:i:s")));
  484.             if($since_start->10){
  485.                 $session->remove('critical');
  486.             }else{
  487.                 $request->getSession()->getFlashBag()->set('warning'$this->get('translator')->trans('Warning ! You previously requested an emergency, please wait 10 minutes and try again.'));
  488.                 return $this->redirect($this->generateUrl('helpdesk_customer_ticket',array(
  489.                     'id' => $ticket->getId()
  490.                 )));
  491.             }
  492.         }
  493.         $session->set('critical'date("Y-m-d H:i:s"));
  494.        
  495.         //Modificacion para validar si se muestra el boton.
  496.         $currentThread =  $this->getDoctrine()->getRepository('UVDeskCoreFrameworkBundle:Thread')->getTicketCurrentThread($ticket);
  497.        
  498.         $attachments $entityManager->getRepository(Attachment::class)->findByThread($currentThread);
  499.         
  500.         $subject utf8_encode($ticket->getSubject());
  501.         $subject str_replace($nova"<BLANK>"$subject);
  502.         $msj utf8_encode($currentThread->getMessage());
  503.         $msj str_replace($nova"<BLANK>"$msj);
  504.         
  505.         if(count($attachments)){
  506.             $pathutf8_encode($attachments[0]->getPath());
  507.             $path str_replace($nova"<BLANK>"$path);
  508.         
  509.             $nameFileAttachment=utf8_encode($attachments[0]->getName());
  510.             $nameFileAttachment str_replace($nova"<BLANK>"$nameFileAttachment);
  511.         }else{
  512.             $nameFileAttachment=$path='';
  513.         }
  514.         $user $this->get('user.service')->getSessionUser();
  515.         $haveSupport file_get_contents($_ENV['EXTERNAL_PATH']."UserController.php?case=1&user=".$user->getEmail());
  516.         if($haveSupport == -1){
  517.             $request->getSession()->getFlashBag()->set('warning'$this->get('translator')->trans('Warning ! Cannot create ticket, connection failed.'));
  518.             return $this->redirect($this->generateUrl('helpdesk_customer_ticket',array(
  519.                 'id' => $ticket->getId()
  520.             )));
  521.         }      
  522.         if($haveSupport==1//24/7
  523.             $TicketStatus $entityManager->getRepository('UVDeskCoreFrameworkBundle:TicketStatus')->findOneById("8"); //in process of attention
  524.         // no debe aparecer el boton por lo tanto aqui no deberia entrar
  525.         // if($haveSupport==2) 
  526.         // $TicketStatus = $entityManager->getRepository('UVDeskCoreFrameworkBundle:TicketStatus')->findOneById("7");
  527.         
  528.         if($haveSupport==3//Low Cost
  529.             $TicketStatus $entityManager->getRepository('UVDeskCoreFrameworkBundle:TicketStatus')->findOneById("7");//Pending Payment
  530.         
  531.         $TicketPriority $entityManager->getRepository('UVDeskCoreFrameworkBundle:TicketPriority')->findOneById("4"); // Urgent
  532.     
  533.         $UserClient file_get_contents($_ENV['EXTERNAL_PATH']."UserController.php?case=3&user=".$user->getEmail());
  534.         $jsonUser=json_decode($UserClienttrue);
  535.         $str$_SERVER['HTTP_REFERER'];
  536.         $param_url=explode("public/",$str);
  537.         $lang=substr($param_url[1],0,2);
  538.         $url=$_ENV['EXTERNAL_PATH']."TicketController.php?case=1&serial='".$jsonUser[0]["Nroserie"]."'&haveSupport='".$haveSupport."'&user='".$user->getEmail()."'&subject='".$subject."'&msj='".$msj."'&path='".$path."'&nameFileAttachment='".$nameFileAttachment."'&lang='".$lang."'";
  539.         //$aClient=file_get_contents($url);
  540.         //$idTicketSeries = file_get_contents($url);
  541.         if (($idTicketSeries = @file_get_contents($url)) === false) {
  542.             $error error_get_last();
  543.             $myfileIdTicket fopen("log_id_ticket_series_err.txt""a") or die ("Unable to open file!");
  544.             fwrite($myfileIdTicket$error['message']);
  545.             fclose($myfileIdTicket);
  546.         }
  547.         $myfileIdTicket fopen("log_id_ticket_series.txt""a") or die ("Unable to open file!");
  548.         fwrite($myfileIdTicket$idTicketSeries);
  549.         fclose($myfileIdTicket);
  550.         if($idTicketSeries == -|| $idTicketSeries == 0){
  551.             $request->getSession()->getFlashBag()->set('warning'$this->get('translator')->trans('Warning ! Cannot create ticket, connection failed.'));
  552.             return $this->redirect($this->generateUrl('helpdesk_customer_ticket',array(
  553.                 'id' => $ticket->getId()
  554.             )));
  555.         }
  556.         $ticket->setCodigoSeries($idTicketSeries);
  557.         $ticket->setPriority($TicketPriority);
  558.         $ticket->setStatus($TicketStatus);
  559.         $entityManager->persist($ticket);
  560.         $entityManager->flush();
  561.           
  562.         
  563.         ///////////////////////////
  564.         $this->addFlash('success',$this->get('translator')->trans("SuccessUrgency ! Urgency requested successfully."));
  565.         
  566.         return $this->redirect($this->generateUrl('helpdesk_customer_ticket',array(
  567.             'id' => $ticket->getId()
  568.         )));
  569.     }
  570.     public function rollback(int $id,Request $request){
  571.         $nova = array(" ");
  572.         $entityManager $this->getDoctrine()->getManager();
  573.         $ticket $this->getDoctrine()->getRepository('UVDeskCoreFrameworkBundle:Ticket')->find($id);
  574.        
  575.         
  576.         $currentThread =  $this->getDoctrine()->getRepository('UVDeskCoreFrameworkBundle:Thread')->getTicketCurrentThread($ticket);
  577.         $attachments $entityManager->getRepository(Attachment::class)->findByThread($currentThread);
  578.         
  579.         
  580.         $TicketStatus $entityManager->getRepository('UVDeskCoreFrameworkBundle:TicketStatus')->findOneById("1");
  581.         
  582.         $TicketPriority $entityManager->getRepository('UVDeskCoreFrameworkBundle:TicketPriority')->findOneById("1");
  583.             
  584.         $ticket->setPriority($TicketPriority);
  585.         $ticket->setStatus($TicketStatus);
  586.         $entityManager->persist($ticket);
  587.         $entityManager->flush();
  588.         $user $this->get('user.service')->getSessionUser();
  589.         $UserClient file_get_contents($_ENV['EXTERNAL_PATH']."UserController.php?case=3&user=".$user->getEmail());
  590.         if($UserClient == -1){
  591.             $request->getSession()->getFlashBag()->set('warning'$this->get('translator')->trans('Warning ! Cannot create ticket, connection failed.'));
  592.             return $this->redirect($this->generateUrl('helpdesk_customer_ticket',array(
  593.                 'id' => $ticket->getId()
  594.             )));
  595.         }
  596.         $jsonUser=json_decode($UserClienttrue);
  597.         $url=$_ENV['EXTERNAL_PATH']."TicketController.php?case=3&codigo_series='".$ticket->getCodigoSeries()."'&user='".$user->getEmail();
  598.        // $url=$_ENV['EXTERNAL_PATH']."TicketController.php?case=3&serial='".$jsonUser[0]["Nroserie"];
  599.         
  600.         $aClient=file_get_contents($url);   
  601.         if($aClient == -1){
  602.             $request->getSession()->getFlashBag()->set('warning'$this->get('translator')->trans('Warning ! Cannot create ticket, connection failed.'));
  603.             return $this->redirect($this->generateUrl('helpdesk_customer_ticket',array(
  604.                 'id' => $ticket->getId()
  605.             )));
  606.         }
  607.         
  608.         $this->addFlash('success',$this->get('translator')->trans("SuccessCanceled ! Urgency Canceled."));
  609.         
  610.         return $this->redirect($this->generateUrl('helpdesk_customer_ticket',array(
  611.             'id' => $ticket->getId()
  612.         )));
  613.     }
  614.     public function saveReply(int $idRequest $request)
  615.     {
  616.         $this->isWebsiteActive();
  617.         $data $request->request->all();
  618.         $ticket $this->getDoctrine()->getRepository('UVDeskCoreFrameworkBundle:Ticket')->find($id);
  619.         if($_POST) {
  620.             if(str_replace(' ','',str_replace('&nbsp;','',trim(strip_tags($data['message'], '<img>')))) != "") {
  621.                 if(!$ticket)
  622.                     $this->noResultFound();
  623.                 $data['ticket'] = $ticket;
  624.                 $data['user'] = $this->get('user.service')->getCurrentUser();
  625.                 // @TODO: Refactor -> Why are we filtering only these two characters?
  626.                 $data['message'] = str_replace(['&lt;script&gt;''&lt;/script&gt;'], ''$data['message']);
  627.                 $userDetail $this->get('user.service')->getCustomerPartialDetailById($data['user']->getId());
  628.                 $data['fullname'] = $userDetail['name'];
  629.                 $data['source'] = 'website';
  630.                 $data['createdBy'] = 'customer';
  631.                 $data['attachments'] = $request->files->get('attachments');
  632.                 
  633.                 $em $this->getDoctrine()->getManager();
  634.                 $status $em->getRepository('UVDeskCoreFrameworkBundle:TicketStatus')->findOneByCode($data['status']);
  635.                // if($ticket->getStatus()->getId() == 5 || $ticket->getStatus()->getId() == 2 || $ticket->getStatus()->getId() == 3 || $ticket->getStatus()->getId() == 9){
  636.                     $ticket->setStatus($em->getRepository('UVDeskCoreFrameworkBundle:TicketStatus')->findOneByCode("open"));
  637.                // }
  638.                 $thread $this->get('ticket.service')->createThread($ticket$data);
  639.                 if($ticket->getPriority()->getId() == 4){
  640.                     $curl curl_init();
  641.                     curl_setopt_array($curl, array(
  642.                         CURLOPT_URL => $_ENV['URL_API'].'token.php',
  643.                         CURLOPT_RETURNTRANSFER => true,
  644.                         CURLOPT_ENCODING => "",
  645.                         CURLOPT_MAXREDIRS => 10,
  646.                         CURLOPT_TIMEOUT => 240,
  647.                         CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  648.                         CURLOPT_CUSTOMREQUEST => "GET",
  649.                         CURLOPT_HTTPHEADER => array(
  650.                             "cache-control: no-cache"
  651.                         ),
  652.                     ));
  653.             
  654.                     $responseToken curl_exec($curl);
  655.             
  656.             
  657.             
  658.                     $jResponseToken=json_decode($responseTokentrue);
  659.                     $token=$jResponseToken['token'];
  660.             
  661.                     $envioMensaje "https://sistema.softguard.com/sistema/sg/endpoint/ticketera-addlectura.php?t=".$token."&ticket=".$ticket->getCodigoSeries()."&evento=6&ticketera=".$ticket->getId();
  662.            
  663.                     
  664.                     $curl curl_init();
  665.                     curl_setopt_array($curl, array(
  666.                         CURLOPT_URL => $envioMensaje,
  667.                         CURLOPT_RETURNTRANSFER => true,
  668.                         CURLOPT_ENCODING => "",
  669.                         CURLOPT_MAXREDIRS => 10,
  670.                         CURLOPT_TIMEOUT => 240,
  671.                         CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  672.                         CURLOPT_CUSTOMREQUEST => "POST",
  673.                         CURLOPT_HTTPHEADER => array(
  674.                             "cache-control: no-cache"
  675.                         ),
  676.                     ));
  677.             
  678.                     $idioms curl_exec($curl);
  679.            
  680.                     curl_close($curl);
  681.                 }
  682.                 if($status) {
  683.                     $flag 0;
  684.                     if($ticket->getStatus() != $status) {
  685.                         $flag 1;
  686.                     }
  687.                     $ticket->setStatus($status);
  688.                     $em->persist($ticket);
  689.                     $em->flush();
  690.                 }
  691.                 // Trigger customer reply event
  692.                 $event = new GenericEvent(CoreWorkflowEvents\Ticket\CustomerReply::getId(), [
  693.                     'entity' =>  $ticket,
  694.                 ]);
  695.                 $this->get('event_dispatcher')->dispatch('uvdesk.automation.workflow.execute'$event);
  696.                 $this->addFlash('success'$this->get('translator')->trans("Success ! Reply added successfully."));
  697.             } else {
  698.                 $this->addFlash(
  699.                     'warning',
  700.                     $this->get('translator')->trans("Warning ! Reply field can not be blank.")
  701.                 );
  702.             }
  703.         } else {
  704.             $this->addFlash(
  705.                 'warning',
  706.                 $this->get('translator')->trans("Warning ! Post size can not exceed 25MB")
  707.             );
  708.         }
  709.         
  710.         
  711.         return $this->redirect($this->generateUrl('helpdesk_customer_ticket',array(
  712.             'id' => $ticket->getId()
  713.         )));
  714.     }
  715.     public function tickets(Request $request)
  716.     {
  717.         $this->isWebsiteActive();
  718.         
  719.        /*
  720.         $str= substr($_SERVER['HTTP_REFERER'], strlen($_SERVER['HTTP_REFERER'])-5,5);
  721.         if($str=='login')
  722.             return $this->redirect($this->generateUrl('helpdesk_knowledgebase'));
  723.     */
  724.         return $this->render('@UVDeskSupportCenter/Knowledgebase/ticketList.html.twig',
  725.             array(
  726.                 'searchDisable' => true
  727.             )
  728.         );
  729.     }
  730.     /**
  731.      * ticketListXhrAction "Filter and sort ticket collection on ajax request"
  732.      * @param Object $request "HTTP Request object"
  733.      * @return JSON "JSON response"
  734.      */
  735.     public function ticketListXhr(Request $request)
  736.     {
  737.         
  738.         
  739.         $this->isWebsiteActive();
  740.         $json = array();
  741.         if($request->isXmlHttpRequest()) {
  742.             $repository $this->getDoctrine()->getRepository('UVDeskCoreFrameworkBundle:Ticket');
  743.     
  744.             $json $repository->getAllCustomerTickets($request->query$this->container);
  745.         }
  746.         //prueba
  747.         //$a=file_get_contents("http://localhost/uvdesk/1.0.6/external/controlador.php");
  748.         $response = new Response(json_encode($json));
  749.         $response->headers->set('Content-Type''application/json');
  750.         return $response;
  751.     }
  752.     /**
  753.      * threadListXhrAction "Filter and sort user collection on ajx request"
  754.      * @param Object $request "HTTP Request object"
  755.      * @return JSON "JSON response"
  756.      */
  757.     public function threadListXhr(Request $request)
  758.     {
  759.         $this->isWebsiteActive();
  760.         $json = array();
  761.         if($request->isXmlHttpRequest()) {
  762.             $ticket $this->getDoctrine()->getRepository('UVDeskCoreFrameworkBundle:Ticket')->find($request->attributes->get('id'));
  763.             // $this->denyAccessUnlessGranted('FRONT_VIEW', $ticket);
  764.             $repository $this->getDoctrine()->getRepository('UVDeskCoreFrameworkBundle:Thread');
  765.             $json $repository->getAllCustomerThreads($request->attributes->get('id'),$request->query$this->container);
  766.         }
  767.         $response = new Response(json_encode($json));
  768.         $response->headers->set('Content-Type''application/json');
  769.         return $response;
  770.     }
  771.     public function ticketView($idRequest $request)
  772.     {
  773.         $this->isWebsiteActive();
  774.         
  775.         $entityManager $this->getDoctrine()->getManager();
  776.         $user $this->get('user.service')->getSessionUser();
  777.         $ticket $entityManager->getRepository(TicketEntity::class)->findOneBy(['id' => $id'customer' => $user]);
  778.         
  779.         ///////////////////////////
  780.         //Modificacion para validar si se muestra el boton. getEmail()
  781.     $conexionSeries 1;
  782.         $isSupportActive=file_get_contents($_ENV['EXTERNAL_PATH']."UserController.php?case=1&user=".$user->getEmail());
  783.     if($isSupportActive == -1){
  784.             $isSupportActive 0;
  785.             $conexionSeries 0;
  786.         }
  787.         if($conexionSeries == 0){
  788.             $isEnabledButton 0;
  789.         }else{
  790.             $isEnabledButton=file_get_contents($_ENV['EXTERNAL_PATH']."UserController.php?case=2");
  791.         }       
  792.        
  793.         ///////////////////////////
  794.         if($conexionSeries == 0) {
  795.             $esFeriado 0;
  796.         }else{
  797.             //Validación día feriado
  798.             $esFeriado=file_get_contents($_ENV['EXTERNAL_PATH']."UserController.php?case=4");
  799.         }
  800.         if (empty($ticket)) {
  801.             throw new NotFoundHttpException('Page Not Found!');
  802.         }
  803.         if (!empty($user) && $user->getId() == $ticket->getCustomer()->getId()) {
  804.            // $ticket->setIsCustomerViewed(1);
  805.             $entityManager->persist($ticket);
  806.             $entityManager->flush();
  807.         }
  808.         
  809.       
  810.         $twigResponse = [
  811.             'ticket' => $ticket,
  812.             'searchDisable' => true,
  813.             'initialThread' => $this->get('ticket.service')->getTicketInitialThreadDetails($ticket),
  814.             'localizedCreateAtTime' => $this->get('user.service')->getLocalizedFormattedTime($user$ticket->getCreatedAt()),
  815.             'isSupportActive'=>$isSupportActive,
  816.             'isEnabledButton'=>$isEnabledButton,
  817.             'esFeriado'=>$esFeriado,
  818.         'conexionSeries'=>$conexionSeries
  819.         ];
  820.         return $this->render('@UVDeskSupportCenter/Knowledgebase/ticketView.html.twig'$twigResponse);
  821.     }
  822.     // Ticket rating
  823.     public function rateTicket(Request $request) {
  824.         $this->isWebsiteActive();
  825.         $json = array();
  826.         $em $this->getDoctrine()->getManager();
  827.         $data json_decode($request->getContent(), true);
  828.         $id $data['id'];
  829.         $count intval($data['rating']);
  830.         
  831.         if($count || $count 6) {
  832.             $ticket $em->getRepository('UVDeskCoreFrameworkBundle:Ticket')->find($id);
  833.             $customer $this->get('user.service')->getCurrentUser();
  834.             $rating $em->getRepository('UVDeskCoreFrameworkBundle:TicketRating')->findOneBy(array('ticket' => $id,'customer'=>$customer->getId()));
  835.             if($rating) {
  836.                 $rating->setcreatedAt(new \DateTime);
  837.                 $rating->setStars($count);
  838.                 $em->persist($rating);
  839.                 $em->flush();
  840.             } else {
  841.                 $rating = new TicketRating();
  842.                 $rating->setStars($count);
  843.                 $rating->setCustomer($customer);
  844.                 $rating->setTicket($ticket);
  845.                 $em->persist($rating);
  846.                 $em->flush();
  847.             }
  848.             $json['alertClass'] = 'success';
  849.             $json['alertMessage'] = $this->get('translator')->trans('Success ! Rating has been successfully added.');
  850.         } else {
  851.             $json['alertClass'] = 'danger';
  852.             $json['alertMessage'] = $this->get('translator')->trans('Warning ! Invalid rating.');
  853.         }
  854.         $response = new Response(json_encode($json));
  855.         $response->headers->set('Content-Type''application/json');
  856.         return $response;
  857.     }
  858.     public function voteTicket(Request $request) {
  859.         $this->isWebsiteActive();
  860.         $json = array();
  861.         $em $this->getDoctrine()->getManager();
  862.         $id $request->attributes->get('id');
  863.         $count intval($request->attributes->get('vote')); 
  864.         $comment $request->attributes->get('comment');
  865. /* 
  866.         if($count > 0 || $count < 4) {
  867.             $ticket = $em->getRepository('UVDeskCoreFrameworkBundle:Ticket')->find($id);
  868.             $customer = $this->get('user.service')->getCurrentUser();
  869.             $ticket->setVote($count);
  870.             $em->persist($ticket);
  871.             $em->flush();
  872.           
  873.            
  874.             $json['alertClass'] = 'success';
  875.             $json['alertMessage'] = $this->get('translator')->trans('Success ! Rating has been successfully added.');
  876.         } else {
  877.             $json['alertClass'] = 'danger';
  878.             $json['alertMessage'] = $this->get('translator')->trans('Warning ! Invalid rating.');
  879.         }
  880.  */
  881.         if($count || $count 6) {
  882.             $ticket $em->getRepository('UVDeskCoreFrameworkBundle:Ticket')->find($id);
  883.             $customer $this->get('user.service')->getCurrentUser();
  884.             $rating $em->getRepository('UVDeskCoreFrameworkBundle:TicketRating')->findOneBy(array('ticket' => $id,'customer'=>$customer->getId()));
  885.             if($rating) {
  886.                 $rating->setcreatedAt(new \DateTime);
  887.                 $rating->setStars($count);
  888.                 $rating->setFeedback($comment);
  889.                 $em->persist($rating);
  890.                 $em->flush();
  891.             } else {
  892.                 $rating = new TicketRating();
  893.                 $rating->setStars($count);
  894.                 $rating->setFeedback($comment);
  895.                 $rating->setCustomer($customer);
  896.                 $rating->setTicket($ticket);
  897.                 $em->persist($rating);
  898.                 $em->flush();
  899.             }
  900.             $json['alertClass'] = 'success';
  901.             $json['alertMessage'] = $this->get('translator')->trans('Success ! Rating has been successfully added.');
  902.         } else {
  903.             $json['alertClass'] = 'danger';
  904.             $json['alertMessage'] = $this->get('translator')->trans('Warning ! Invalid rating.');
  905.         }
  906.         $response = new Response(json_encode($json));
  907.         $response->headers->set('Content-Type''application/json');
  908.         return $response;
  909.     }
  910.     public function downloadAttachmentZip(Request $request)
  911.     {
  912.         $threadId $request->attributes->get('threadId');
  913.         $attachmentRepository $this->getDoctrine()->getManager()->getRepository('UVDeskCoreFrameworkBundle:Attachment');
  914.         $attachment $attachmentRepository->findByThread($threadId);
  915.         if (!$attachment) {
  916.             $this->noResultFound();
  917.         }
  918.         $zipname 'attachments/' .$threadId.'.zip';
  919.         $zip = new \ZipArchive;
  920.         $zip->open($zipname, \ZipArchive::CREATE);
  921.         if(count($attachment)){
  922.             foreach ($attachment as $attach) {
  923.                 $zip->addFile(substr($attach->getPath(), 1)); 
  924.             }
  925.         }
  926.         $zip->close();
  927.         $response = new Response();
  928.         $response->setStatusCode(200);
  929.         $response->headers->set('Content-type''application/zip');
  930.         $response->headers->set('Content-Disposition''attachment; filename=' $threadId '.zip');
  931.         $response->sendHeaders();
  932.         $response->setContent(readfile($zipname));
  933.         return $response;
  934.     }
  935.     public function downloadAttachment(Request $request)
  936.     {
  937.         $attachmendId $request->attributes->get('attachmendId');
  938.         $attachmentRepository $this->getDoctrine()->getManager()->getRepository('UVDeskCoreFrameworkBundle:Attachment');
  939.         $attachment $attachmentRepository->findOneById($attachmendId);
  940.         $baseurl $request->getScheme() . '://' $request->getHttpHost() . $request->getBasePath();
  941.         if (!$attachment) {
  942.             $this->noResultFound();
  943.         }
  944.         $path $this->get('kernel')->getProjectDir() . "/public/"$attachment->getPath();
  945.         $response = new Response();
  946.         $response->setStatusCode(200);
  947.         
  948.         $response->headers->set('Content-type'$attachment->getContentType());
  949.         $response->headers->set('Content-Disposition''attachment; filename='$attachment->getName());
  950.         $response->sendHeaders();
  951.         $response->setContent(readfile($path));
  952.         
  953.         return $response;
  954.     }
  955.     
  956.     public function ticketCollaboratorXhr(Request $request)
  957.     {
  958.         $json = array();
  959.         $content json_decode($request->getContent(), true);
  960.         $em $this->getDoctrine()->getManager();
  961.         $ticket $em->getRepository('UVDeskCoreFrameworkBundle:Ticket')->find($content['ticketId']);
  962.         
  963.         if ($request->getMethod() == "POST") {
  964.             if ($content['email'] == $ticket->getCustomer()->getEmail()) {
  965.                 $json['alertClass'] = 'danger';
  966.                 $json['alertMessage'] = $this->get('translator')->trans('Error ! Can not add customer as a collaborator.');
  967.             } else {
  968.                 $data = array(
  969.                     'from' => $content['email'],
  970.                     'firstName' => ($firstName ucfirst(current(explode('@'$content['email'])))),
  971.                     'lastName' => ' ',
  972.                     'role' => 4,
  973.                 );
  974.                 $supportRole $em->getRepository('UVDeskCoreFrameworkBundle:SupportRole')->findOneByCode('ROLE_CUSTOMER');
  975.                 $collaborator $this->get('user.service')->createUserInstance($data['from'], $data['firstName'], $supportRole$extras = ["active" => true]);
  976.                 
  977.                 $checkTicket $em->getRepository('UVDeskCoreFrameworkBundle:Ticket')->isTicketCollaborator($ticket,$content['email']);
  978.                 
  979.                 if (!$checkTicket) {
  980.                     $ticket->addCollaborator($collaborator);
  981.                     $em->persist($ticket);
  982.                     $em->flush();
  983.                     $ticket->lastCollaborator $collaborator;
  984.                     $collaborator $em->getRepository('UVDeskCoreFrameworkBundle:User')->find($collaborator->getId());
  985.                    
  986.                     $json['collaborator'] =  $this->get('user.service')->getCustomerPartialDetailById($collaborator->getId());
  987.                     $json['alertClass'] = 'success';
  988.                     $json['alertMessage'] = $this->get('translator')->trans('Success ! Collaborator added successfully.');
  989.                 } else {
  990.                     $json['alertClass'] = 'danger';
  991.                     $json['alertMessage'] = $this->get('translator')->trans('Error ! Collaborator is already added.');
  992.                 }
  993.             }
  994.         } elseif ($request->getMethod() == "DELETE") {
  995.             $collaborator $em->getRepository('UVDeskCoreFrameworkBundle:User')->findOneBy(array('id' => $request->attributes->get('id')));
  996.             
  997.             if ($collaborator) {
  998.                 $ticket->removeCollaborator($collaborator);
  999.                 $em->persist($ticket);
  1000.                 $em->flush();
  1001.                 $json['alertClass'] = 'success';
  1002.                 $json['alertMessage'] = $this->get('translator')->trans('Success ! Collaborator removed successfully.');
  1003.             } else {
  1004.                 $json['alertClass'] = 'danger';
  1005.                 $json['alertMessage'] = $this->get('translator')->trans('Error ! Invalid Collaborator.');
  1006.             }
  1007.         }
  1008.         $response = new Response(json_encode($json));
  1009.         $response->headers->set('Content-Type''application/json');
  1010.         return $response;
  1011.     }
  1012.     
  1013.       public function getTicketChatStatusXHR(Request $request)
  1014.     {
  1015.         
  1016.         $entityManager $this->getDoctrine()->getManager();
  1017.         $ticketId $request->get('id');
  1018.         $json = [];
  1019.         $ticket $entityManager->getRepository('UVDeskCoreFrameworkBundle:Ticket')->findOneById($ticketId);
  1020.         if (!empty($ticket)) {
  1021.             $isStarred $ticket->getIsStarred();
  1022.           
  1023.             if ($request->isXmlHttpRequest()) {
  1024.                 $json['isStarred'] = $isStarred;
  1025.             }
  1026.             
  1027.             return new Response(json_encode($json), 200, ['Content-Type' => 'application/json']);
  1028.         } else {
  1029.             return new Response(json_encode(['error' => 'Ticket not found']), 404, ['Content-Type' => 'application/json']);
  1030.         }
  1031.     }
  1032. }