src/Controller/EditController.php line 166

Open in your IDE?
  1. <?php
  2. /*
  3.  * To change this license header, choose License Headers in Project Properties.
  4.  * To change this template file, choose Tools | Templates
  5.  * and open the template in the editor.
  6.  */
  7. namespace App\Controller;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  11. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  12. use App\Entity\OriginalDictionary;
  13. use App\Entity\TranslationDictionary;
  14. use App\Entity\DocumentDictionary;
  15. use Twig\Environment;
  16. use App\Service\utiltranslate;
  17. use Doctrine\ORM\EntityManagerInterface;
  18. /**
  19.  * Controlador que renderiza el template para editar y guarda los datos editados
  20.  *
  21.  * @author arodriguez
  22.  */
  23. class EditController extends AbstractController
  24. {
  25.     private $twig;
  26.     private $utiltranslate;
  27.     private $em;
  28.     public function __construct(EntityManagerInterface $em,Environment $twig,utiltranslate $utiltranslate)
  29.     {
  30.         $this->em $em;
  31.         $this->twig $twig;
  32.         $this->utiltranslate$utiltranslate;
  33.     }
  34.     /* Calcula el id del siguiente elemento mostrado en el grid*/         
  35.     private function siguiente($id$length)
  36.     {
  37.         $position array_search($id$_SESSION['ids']);
  38.         if($position === $length-1)   return null;
  39.         else return $_SESSION['ids'][++$position];        
  40.     }
  41.     
  42.     /* Calcula el id del  elemento anterior mostrado en el grid*/   
  43.     private function anterior($id)
  44.     {
  45.         $position array_search($id$_SESSION['ids']);
  46.         if($position == 0)   return null;
  47.         else return $_SESSION['ids'][--$position];
  48.     }
  49.     
  50.     /**
  51.      * Comprueba si el docuemnto está listo en un idioma en concreto para
  52.      * enviar el mail al creador del mismo. Se comprueba también la cantidad de
  53.      * idiomas que han completado la traducción para indicarlo en el correo
  54.      * @param type $documents
  55.      * @param type $langTraduccion
  56.      */
  57.     private function checkDocuments($documents,$langTraduccion)
  58.     {
  59.        
  60.        foreach($documents as $document)
  61.        {
  62.            $id $document->getId();
  63.            $completados=0;
  64.            //Obtenemos los idiomas que hay en cada documento.
  65.            $langsOfDocument $this->em->getRepository(DocumentDictionary::class)->getLangsOfDocument();
  66.            $total count($langsOfDocument);
  67.            $send false;
  68.            foreach ($langsOfDocument as $lang){
  69.                $result $this->utiltranslate->getPending($id,$lang);
  70.                $auxcompletados $completados;
  71.                //Si quedan pendientes, no está listo el documento aún.
  72.                if($result$completados += 0;
  73.                else $completados +=1;
  74.                if(($langTraduccion===$lang)&&($auxcompletados!==$completados)){
  75.                    $send=true;
  76.                }
  77.            }
  78.            if (($send)&&($completados>0)){
  79.                $this->utiltranslate->sendLanguageReady($document$langTraduccion,  $total$completados);
  80.            }
  81.        }
  82.     }
  83.     
  84.     private function sendReview($originalText$previous$documents)
  85.     {
  86.         //Obtenemos los creadores distintos asociados a los documentos que han sido afectados por la modificación.
  87.         $creators= array();
  88.         $documentos "";
  89.         $isWebErrorfalse;
  90.         foreach ($documents as $document)
  91.         { 
  92.             $project $document->getProject();
  93.             if($project->getName()=="Web") {$isWebError true;}
  94.             $temp $document->getCreator();
  95.             if (!in_array($temp$creators)) {$creators[]=$temp;} 
  96.             $documentos.= $document->getName().",  "
  97.         }
  98.         //Manda el correo a cada creador.
  99.         $message = \Swift_Message::newInstance()
  100.                 ->setSubject("Un texto en castellano ha sido modificado")
  101.                 ->setFrom('webmaster@visiotechsecurity.com');
  102.         foreach ($creators as $user)
  103.         {
  104.             $message->setTo($user->getEmail())
  105.                 ->setBody("Se ha cambiado de: \n".$previous."\n"
  106.                         " a: \n".$originalText.
  107.                         ".\n\n Esto afecta a los siguientes documentos: \n".$documentos);            
  108.             $respuesta $this->get('mailer')->send($message);
  109.            // $this->mailer->send($message);            
  110.         }
  111.         
  112.         //Si se ha prpoducido un error en un documento de la web se notifica a producto para que cambie la ficha.
  113.         if($isWebError)
  114.         {
  115.             $message->setTo("producto@visiotechsecurity.com")
  116.                 ->setBody("Se ha cambiado de: \n".$previous."\n"
  117.                         " a: \n".$originalText.
  118.                         ".\n\n Esto afecta a los productos siguientes: \n".$documentos);            
  119.             $respuesta $this->get('mailer')->send($message);
  120.         }
  121.         return new Response("Mensaje enviado");         
  122.     }
  123.     
  124.     private function modifyBaseText($originalText$previous$documents)
  125.     {
  126.         foreach($documents as $document)
  127.         {
  128.             $baseText $document->getBaseText();
  129.             $replace=str_replace($previous,$originalText$baseText);
  130.             $document->setBaseText($replace);  
  131.             //$baseText = $document->getBaseText();
  132.         }        
  133.     }
  134.     
  135.     private function setReview($original$lang)
  136.     {
  137.         $em =$this->getDoctrine()->getManager();
  138.         $translations$original->getTranslations()->toArray();
  139.         $emTranslation=$em->getRepository(TranslationDictionary::class);
  140.         $currentLangs $emTranslation->getLanguagesOfOriginal($original);
  141.         foreach($translations as $translation)
  142.         {
  143.             if ($lang!==$translation->getLang())
  144.             {
  145.                 $translation->setStatus("review");
  146.             }
  147.         }        
  148.     }
  149.     /**
  150.      * @Route("/jtext" , name = "controlJtext")
  151.      * @Template("dictionary/edit.html.twig")
  152.      * Realiza la búsqueda del texto a traducir y muestra su información en la vista para editarlo
  153.      */
  154.     public function controlJtext(){
  155.         return $this->render('dictionary/jtext.html.twig');
  156.     }
  157.     /**
  158.      * @Route("/translations/edit/{id}/{lang}" , name = "showEditData")
  159.      * @Template("dictionary/edit.html.twig")
  160.      * Realiza la búsqueda del texto a traducir y muestra su información en la vista para editarlo
  161.      */
  162.     public function showEditAction($id =0$lang ="en")
  163.     {      
  164.         //obtenemos la traducción de la base de datos
  165.         $em =$this->getDoctrine()->getManager();     
  166.         $row $em->getRepository(TranslationDictionary::class)->find($id);
  167.         if (!$row
  168.         {
  169.             throw $this->createNotFoundException
  170.             (
  171.                 'No translation found for id '.$id
  172.             );
  173.         }
  174.         //cogemos los documentos y los proyectos asociados a la traduccion.
  175.         
  176.         list($project,$document)=$this->utiltranslate->getProjectsyDocumentsOfTranslation($id);
  177.         
  178.         //cogemos el texto original y el texto de la traducción.
  179.         $original $row->getOriginal();
  180.         $originalText $original->getOriginal();
  181.         $translationText $row->getTranslation(); 
  182.         
  183.         //Cogemos todos los documentos y proyectos asociados.
  184.         list($documents,$projects)=$this->utiltranslate->getProjectsyDocuments();
  185.         
  186.         //Si está en review mostramos el texto que había antes.
  187.         if($row->getStatus()==="review"$previous $original->getPrevious();
  188.         else $previous "";
  189.         //Con los ids en sesión calculamos los ids de las traducciones anterior y siguiente. 0 si no hay traducción.
  190.         if(isset($_SESSION['ids']))
  191.         {
  192.             $length count($_SESSION['ids']);
  193.             $siguiente $this->siguiente($id $length);
  194.             $anterior $this->anterior($id);
  195.         }
  196.         else
  197.         {
  198.             $siguiente=0;
  199.             $anterior=0;
  200.         }
  201.         return array
  202.         (
  203.            'id' => $id,
  204.            'lang' => $lang
  205.            'original' => $originalText
  206.            'translation' => $translationText,
  207.            'documents'=> $documents,
  208.            'document'=>$document,
  209.            'projects'=> $projects,
  210.            'project'=>$project,
  211.            'siguiente' => $siguiente,
  212.            'anterior' => $anterior,
  213.            'previous' => $previous,
  214.         );       
  215.     }
  216.     
  217.     /**
  218.      * @Route("/translations/editSucces/{id}/{lang}/" , name = "editData")
  219.      * @param type $id
  220.      * @param type $lang
  221.      * Modifica en la base de datos lo introducido en el template edit.html.twig
  222.      * obteniendo la informacion mediante POST recogido en el formulario de la vista.
  223.      */
  224.     public function editAction($id$lang)
  225.     {
  226.         $id intval($id);
  227.         $em =$this->getDoctrine()->getManager();
  228.         //Recogemos el texto introducido como traducción.
  229.         if (isset($_POST["translation"]))
  230.         {
  231.             $nTranslation trim($_POST["translation"]);
  232.             $isHTMLfilter_var($_POST["ishtml"], FILTER_VALIDATE_BOOLEAN);
  233.             if(!$isHTML)
  234.             {
  235.                 $nTranslation strip_tags($nTranslation);
  236.                 $evilStrings=array("[% VAR%]","[% VAR %]","[%VAR %]","[%var%]","[%DAR%]");
  237.                 $nTranslation str_replace($evilStrings"[%VAR%]"$nTranslation);
  238.             }
  239.             $nTranslation str_replace("&nbsp;"," "$nTranslation);
  240.         }
  241.         
  242.         //Recuperamos el objeto traducción a partir del id.
  243.         $translation $em->getRepository(TranslationDictionary::class)->find($id);
  244.         
  245.         
  246.         if (!$translation
  247.         {
  248.             throw $this->createNotFoundException(
  249.                 'No translation found for id '.$id
  250.             );
  251.         }
  252.         //Obtenemos el objeto original
  253.         $original $translation->getOriginal();  
  254.         $check false;
  255.         //si guardamos algo que está en review pasa a ready.
  256.         if($translation->getStatus()==="review"
  257.         {
  258.             $translation->setStatus("ready");   
  259.             $check true;
  260.         }
  261.         
  262.         
  263.         $hashNueva hash('md5',$nTranslation);
  264.         if (isset($_POST["copyCheck"]))
  265.         {
  266.             //Si se ha marcado copyCheck guardamos la misma traduccion en todos los idiomas y marcamos fixed
  267.             $original->setFixed(true);
  268.             $this->copyTranslations($original,$nTranslation,$hashNueva,$em); 
  269.             $check true;
  270.         }
  271.         else
  272.         {
  273.             //Mediante hash comprobamos que se haya modificado la traduccion y la guardamos
  274.             $hashTranslation $translation->getHash();            
  275.             if($hashTranslation!== $hashNueva)
  276.             {
  277.                 $translation->setTranslation($nTranslation);
  278.                 $translation->setHash($hashNueva);
  279.                 $check true;
  280.             }
  281.         }
  282.         $translation->setModified(new \DateTime());
  283.         $documents$translation->getDocuments();
  284.         //Si se ha editado el texto original...        
  285.         if (isset($_POST["original"])) 
  286.         {
  287.             $nOriginaltrim(htmlspecialchars($_POST["original"]));
  288.             //Comprobamos si realmente se ha modificado, en ese caso, lo guardamos
  289.             $hashOriginal $original->getHash();
  290.             $hashNuevoOriginal hash('md5'$nOriginal);
  291.             if($hashNuevoOriginal !== $hashOriginal)
  292.             {
  293.                 $original -> setOriginal($nOriginal);
  294.                 $original -> setHash($hashNuevoOriginal);
  295.                 
  296.                 //ponemos en review las traducciones en el resto de idiomas.
  297.                 $this->setReview($original,$lang);
  298.                 $this->setReview($original,$lang);
  299.                 $this->modifyBaseText($original->getOriginal(),$original->getPrevious(),$documents);
  300.                 //Mandamos un correo a los creadores de los documentos indicando que se ha modificado el original.
  301.                 $this->sendReview($original->getOriginal(), $original->getPrevious(),$documents);
  302.             }
  303.         }
  304.         
  305.         $em->flush();
  306.         //deshabilitamos las notificaciones a documentos porque el cruce de documentos lo tiene a la tabla vieja de usuarios. Hay que actualizarlos a la tabla nueva de 
  307.        // if ($check){
  308.         //    $this->checkDocuments($documents,$lang);
  309.        // }
  310.         if (isset($_POST["move"])){             
  311.             $move$_POST["move"];
  312.             //cogemos el id de la traducción siguiente.
  313.             if ($move==="siguiente"$id $this->siguiente ($idcount($_SESSION['ids'])); 
  314.             //cogemos el anterior si se ha puldado la flecha hacia atras.
  315.             else if($move==="anterior"$id $this->anterior($id);
  316.             // Si damos a guardar, volvemos al grid habiendo guardado los cambios.
  317.             else return $this->redirect($this->generateUrl('showTranslationsGrid', array('lang' => $lang)),301 ); 
  318.            
  319.             
  320.             return $this->redirect ($this->generateUrl ('showEditData', array('id' =>$id'lang' =>$lang)), 301);
  321.         }
  322.         return $this->redirect($this->generateUrl('showTranslationsGrid', array('lang' => $lang)),301 ); 
  323.         
  324.     }
  325.     
  326.      /**
  327.      * 
  328.      * @param type $original DictionaryOriginal sobre el que sacar las traduccioness
  329.      * @param type $nTranslation texto a guardar
  330.      * @param type $hashNueva hash del texto a almacenar
  331.      * @param type $em manager de doctrine
  332.      * Funcion utilizada para copiar el texto de la traducción a todos los idiomas
  333.      * cuando el texto sea fijo
  334.      */
  335.     private function copyTranslations($original,$nTranslation,$hashNueva)
  336.     {
  337.         $translations $original->getTranslations();
  338.         
  339.         if($translations)
  340.         { //Copiamos el texto a las traducciones existentes.    
  341.             foreach($translations as $translation)
  342.             {
  343.                 $translation->setTranslation($nTranslation);
  344.                 $translation->setHash($hashNueva);                
  345.             }
  346.         }           
  347.     }
  348.     
  349.     
  350.     
  351. }