src/Controller/ChecklistController.php line 2273

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Service\SycoreService;
  4. use Exception;
  5. use Psr\Log\LoggerInterface;
  6. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpFoundation\JsonResponse;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\Serializer\Serializer;
  11. use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
  12. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  13. use Symfony\Component\Serializer\Encoder\XmlEncoder;
  14. use App\Entity\Chklst;
  15. use App\Entity\ChklstTask;
  16. use App\Entity\TaskServer;
  17. use App\Entity\Queue;
  18. use App\Entity\ChklstTemplateWebapp;
  19. use App\Entity\User;
  20. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  21. use Symfony\Component\Form\Extension\Core\Type\IntegerType;
  22. use App\Service\WebExFactorySymfonyService;
  23. use App\Service\TelegramBCFactorySymfonyService;
  24. use App\converger\rest_api_util\ResponseARC;
  25. use Symfony\Component\Serializer\Normalizer\CustomNormalizer;
  26. use phpseclib\Crypt\AES;
  27. use App\Utility\ExcelFactory;
  28. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  29. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  30. use App\Command\libs\Tasks\GraphLinksModel;
  31. use App\Repository\TaskRepository;
  32. use Dompdf\Dompdf;
  33. use Dompdf\Options;
  34. use Symfony\Component\HttpFoundation\HeaderUtils;
  35. use App\Command\libs\Functions;
  36. use Doctrine\DBAL\Types\Types;
  37. use App\Audit\WorkflowAuditLoggerFactory;
  38. use App\Audit\WorkflowAuditLogger;
  39. class ChecklistController  extends AbstractController
  40. {
  41.     // Temporaneo!
  42.     private $USE_NEW_IMPEXP = true;
  43.     private $sycoreService;
  44.     public function __construct(SycoreService $sycoreService) {
  45.         $this->sycoreService = $sycoreService;
  46.     }
  47.     private function getLogger()
  48.     {
  49.         $logger = $this->get('logger');
  50.         return $logger instanceof Logger ? $logger : null;
  51.     }
  52.     public function custom_addslashes($var, $params)
  53.     {
  54.         $db_driver = $params->get('db_driver');
  55.         if ($db_driver == "pdo_mysql") {
  56.             $textDecode = addslashes($var);
  57.         } else {
  58.             $textDecode = pg_escape_string($var);
  59.         }
  60.         return $textDecode;
  61.     }
  62.     /***  AGGIUNTA METODI PER DESIGNER **/
  63.     public function uploadImageFlowAction(Request $request, $cid, LoggerInterface $logger, ParameterBagInterface $params)
  64.     {
  65.         $target_dir = $params->get('kernel.project_dir') . '/public/wf_uploads/' . $cid . '/' . $request->getBasePath();
  66.         //$logger = $this->getLogger();
  67.         if (isset($_FILES['file'])) {
  68.             $logger->debug("_FILES set");
  69.         } else {
  70.             $logger->debug(json_encode($_FILES));
  71.         }
  72.         if (isset($_POST['file'])) {
  73.             $logger->debug("_POST set");
  74.             $logger->debug(json_encode($_POST));
  75.         } else {
  76.             $logger->debug(json_encode($_POST));
  77.         }
  78.         if (0 < $_POST['file']['error']) {
  79.             $logger->debug("Error: " . $_POST['file']['error'] . "<br>");
  80.             //echo 'Error: ' . $_FILES['file']['error'] . '<br>';
  81.         } else {
  82.             move_uploaded_file($_POST['file']['tmp_name'], $target_dir . $_POST['file']['name']);
  83.         }
  84.     }
  85.     public function getSybotWorkflows(Request $request, LoggerInterface $logger, ParameterBagInterface $params){
  86.             $em = $this->getDoctrine()->getManager();
  87.         $user = $this->getUser();
  88.         $userId = $user->getId();
  89.         //-----------------------------------------------------------------
  90.         // Recupera la lista dei workflow visibili per l’utente corrente
  91.         //-----------------------------------------------------------------
  92.         $listWorkflow = "
  93.             SELECT DISTINCT 
  94.                 ct.id, 
  95.                 name, 
  96.                 description, 
  97.                 CASE hidden WHEN 1 THEN 'NO' ELSE 'SI' END AS hidden,   
  98.                 CASE flag_type_checklist 
  99.                     WHEN 'A' THEN 'Azioni'
  100.                     WHEN 'V' THEN 'Verifica'
  101.                     WHEN 'G' THEN 'Generale'
  102.                     WHEN 'TC' THEN 'Tars Collaudo'
  103.                     WHEN 'TP' THEN 'Tars Produzione'
  104.                 END AS flag_type_checklist,
  105.                 
  106.                 TO_CHAR(ct.data_creazione, 'dd-mm-yyyy hh24:mi:ss') AS data_creazione, 
  107.                 TO_CHAR(ct.data_modifica, 'dd-mm-yyyy hh24:mi:ss') AS data_modifica,
  108.                 ct.locked,
  109.                 ct.modificato_da,
  110.                 ct.lock_session_user_id,
  111.                 ctc.nome AS categoria
  112.             FROM chklst_template ct 
  113.                 
  114.                 JOIN chklst_template_role cr ON ct.id = cr.id_template
  115.                 JOIN chklst_template_categories ctc ON ct.id_category = ctc.id
  116.                 JOIN (
  117.                     SELECT ur.id_roles
  118.                     FROM user_acm u
  119.                     JOIN user_profile_roles ur ON u.id = ur.id_user
  120.                     WHERE u.id = :userId 
  121.                     AND ur.id_profile IN (1, 2)
  122.                 ) ur ON cr.id_roles = ur.id_roles
  123.             ORDER BY name, hidden DESC, flag_type_checklist
  124.         ";
  125.         $statement = $em->getConnection()->prepare($listWorkflow);
  126.         $statement->bindValue('userId', $userId);
  127.         $statement->execute();
  128.         $sqlListWorkflow = $statement->fetchAll();
  129.         $ListWorkflow =array();
  130.         foreach($sqlListWorkflow as $r)
  131.         {
  132.             //RECUPERA I PARAMETRI ASSOCIATI AL WORKFLOW
  133.             $sqlParams= "select * from  chklst_template_parameters
  134.                          where chklst_id = :id";
  135.             $statement = $em->getConnection()->prepare($sqlParams);
  136.             $statement->bindValue('id', $r['id']);
  137.             $statement->execute();
  138.             $ResulQueryParams = $statement->fetchAll();             
  139.             
  140.             //
  141.             //-------------------------------------------------
  142.             // Recupera i ruoli associati al template corrente
  143.             //-------------------------------------------------
  144.             $sqlRuoli = "
  145.                 SELECT STRING_AGG(r.description_roles, '; ') AS ruoli
  146.                 FROM chklst_template_role ctr
  147.                 JOIN roles r ON ctr.id_roles = r.id_roles
  148.                 WHERE ctr.id_template = :id
  149.             ";
  150.             $statement = $em->getConnection()->prepare($sqlRuoli);
  151.             $statement->bindValue('id', $r['id']);
  152.             $statement->execute();
  153.             $ResulQueryRuoli = $statement->fetch();
  154.             $Functions = new Functions($this, $logger, $em);
  155.             $checkTemplateByRole = $Functions->chkOpenTemplateByRoleBpmn($r['id'],$userId) ;
  156.         
  157.             $templateRole=null;
  158.             foreach($checkTemplateByRole as $c){
  159.                 $templateRole=$c['result_role'];
  160.             }
  161.             //------------------------------------------------
  162.             // Ultima esecuzione del template
  163.             //------------------------------------------------
  164.             /*$sqlExec = "
  165.                 SELECT TO_CHAR(MAX(run_start), 'dd-mm-yyyy hh24:mi:ss') AS max_exec
  166.                 FROM chklst
  167.                 WHERE from_template_id = :id
  168.             ";
  169.             $statement = $em->getConnection()->prepare($sqlExec);
  170.             $statement->bindValue('id', $r['id']);
  171.             $statement->execute();
  172.             $ResulQueryMaxExec = $statement->fetch();*/
  173.             //------------------------------------------------
  174.             // Username dell'ultimo modificatore
  175.             //------------------------------------------------
  176.             $sqlUsername = "
  177.                 SELECT username 
  178.                 FROM user_acm 
  179.                 WHERE id = :modificato_da
  180.             ";
  181.             $statement = $em->getConnection()->prepare($sqlUsername);
  182.             $statement->bindValue('modificato_da', $r['modificato_da']);
  183.             $statement->execute();
  184.             $modificatoDa_Username = $statement->fetch();
  185.             $ListWorkflow_tmp = array('id' => $r['id'],
  186.                                         'name' => $r['name'],
  187.                                         'description_workflow' => $r['description'],
  188.                                         'visibilita_workflow' => $r['hidden'],
  189.                                         'tipologia_workflow' => $r['flag_type_checklist'],
  190.                                         //'validita_workflow' => $r['task_validate'],
  191.                                         'data_creazione' => $r['data_creazione'],
  192.                                         'data_modifica' => $r['data_modifica'],
  193.                                         'modificato_da' =>$r['modificato_da'],
  194.                                         'lock_session'=>$r['lock_session_user_id'],
  195.                                         'modificatoDa_Username' =>$modificatoDa_Username['username'] ?? '',
  196.                                         'locked' => $r['locked'],
  197.                                         'ruoli' => $ResulQueryRuoli['ruoli'],
  198.                                         //'MaxExec' => $ResulQueryMaxExec['max_exec'],
  199.                                         'categoria' => $r['categoria'],
  200.                                         'templateRole' => $templateRole,
  201.                                         'userId' => $userId    ,
  202.                                         'wfl_params' => $ResulQueryParams
  203.                 );
  204.             array_push($ListWorkflow,$ListWorkflow_tmp);
  205.         }
  206.         
  207.         return new JsonResponse(['data' => $ListWorkflow]);
  208.     }
  209.     public function checklistSelectionFlowChartAction(Request $request, LoggerInterface $logger, ParameterBagInterface $params)
  210.     {
  211.         $em = $this->getDoctrine()->getManager();
  212.         //$logger->debug('[checklistSelectionFlowChart] PHP INI SIZE: ' . ini_get('upload_max_filesize'));
  213.         //$logger->debug('[checklistSelectionFlowChart] PHP FILE UPLOAD: ' . ini_get('max_file_uploads'));
  214.         $upload_max_filesize = ini_get('upload_max_filesize');
  215.         $upload_max_filesize_n = preg_replace('/[^0-9]/', '', $upload_max_filesize);
  216.         $upload_max_filesize_t = preg_replace('/[0-9]/', '', $upload_max_filesize);
  217.         //CONVERSIONE A BYTE
  218.         $upload_max_filesize = $this->toByteSize($upload_max_filesize_n, $upload_max_filesize_t);
  219.         $user = $this->getUser();
  220.         $userId = $user->getId();
  221.         $Functions = new Functions($this, $logger, $em);
  222.         $roles = $Functions->getAllUserRoles($userId) ;
  223.         
  224.         $UserRole = $user->getUserRole();
  225.         $logger->debug("[serviceAssuranceDashboardAction] UserRole " . $UserRole);
  226.         $max_file_uploads = ini_get('max_file_uploads');
  227.         if (isset($_GET["selectionType"])) {
  228.             $selectionType = $_GET["selectionType"];
  229.             $logger->debug("[checklistSelectionFlowChart]  selectionType " . $selectionType);
  230.             $selectedToOpen = 'ND';
  231.             if ($selectionType == "new") {
  232.                 $selectedToOpen = $_GET["selectedToOpen"];
  233.             }
  234.         } else {
  235.             $selectionType = 'ND';
  236.             $selectedToOpen = 'ND';
  237.         }
  238.         /* export config*/
  239.         /*$sql = "select name_config, value from config";
  240.         $stmt = $em->getConnection()->prepare($sql);
  241.         $stmt->execute();
  242.         $config = $stmt->fetchAll();*/
  243.         $sql = "select id, nome, descrizione from chklst_template_categories order by id";
  244.         $stmt = $em->getConnection()->prepare($sql);
  245.         $stmt->execute();
  246.         $categories = $stmt->fetchAll();        
  247.         return $this->render(
  248.             'checklistSelectionFlowchart.html.twig',
  249.             array(
  250.                 'upload_max_filesize' => $upload_max_filesize,
  251.                 'max_file_uploads' => $max_file_uploads,
  252.                 'logged_user' => $user,
  253.                 'roles' => $roles,
  254.                 'user_role' => $UserRole,
  255.                 'selectionType' => $selectionType,
  256.                 'selectedToOpen' => $selectedToOpen,
  257.             //'config' => $config,
  258.                 'categories' => $categories
  259.             )
  260.         );
  261.     }
  262.     
  263.     public function checklistVerifyNameAction(LoggerInterface $logger)
  264.     {
  265.         $csrfToken = $_POST['csrftoken'];
  266.         if (!$this->isCsrfTokenValid('checklist_verify_name', $csrfToken)) {
  267.             throw new \Exception('Csrf token not valid');
  268.         }
  269.         $em = $this->getDoctrine()->getManager();
  270.         $checklistName = $_POST["checklist_name"];
  271.         if ($checklistName) {
  272.             $sql = "select count(1) from chklst_template where name = :name";
  273.             $stmt = $em->getConnection()->prepare($sql);
  274.             $stmt->bindValue('name', $checklistName);
  275.             $stmt->execute();
  276.             $ResulQuery = $stmt->fetch();
  277.             $count = $ResulQuery;
  278.             $ret = ['data' => $count];
  279.             return new JsonResponse($ret);
  280.         }
  281.         return new JsonResponse(['data' => ['count' => 'null']]);
  282.     }
  283.     public function    checklistImportSelectionAction(Request $request, LoggerInterface $logger)
  284.     {
  285.         $csrfToken = $request->request->get('csrftoken');
  286.         if (!$this->isCsrfTokenValid('checklist_import_selection', $csrfToken)) {
  287.             throw new \Exception('Csrf token not valid');
  288.         }
  289.         $em = $this->getDoctrine()->getManager();
  290.         $user = $this->getUser();
  291.         $res_json = new JsonResponse;
  292.         $arrayListChecklist = array();
  293.         $user = $this->getUser();
  294.         $userId = $user->getId();
  295.         $logger->debug("[ChecklistImportSelection] Visualizzazione checklist esistenti " . $userId);
  296.         $q = "select distinct a.tipologia, a.id, a.name, a.description, a.hidden, a.route, a.flag_type_checklist, a.categoria, a.task_validate, 
  297.                     coalesce(to_char(a.data_creazione, 'DD-MM-YYYY'), '-') data_creazione, 
  298.                     coalesce(to_char(a.data_modifica,'DD-MM-YYYY'), '-') data_modifica
  299.                 from 
  300.                 (select 'workflow' tipologia, ct.id, name, description, case hidden when 1 then 'NO' else 'SI' end hidden, '' route,  
  301.                                                                                         case flag_type_checklist when 'A' then 'Azioni'
  302.                                                                                          when 'V' then 'Verifica'
  303.                                                                                          when 'G' then 'Generale'
  304.                                                                                          when 'TC' then 'Tars Collaudo'
  305.                                                                                          when 'TP' then 'Tars Produzione'
  306.                                                                 end flag_type_checklist,
  307.                                                                 ctc.nome categoria,
  308.                                                                 cj.task_validate,
  309.                                                                 ct.data_creazione, ct.data_modifica
  310.                                     from chklst_template ct join chklst_jflow cj on (ct.id = cj.chklst_template)
  311.                                      join chklst_template_role cr on ct.id = cr.id_template
  312.                                      join chklst_template_categories ctc on ct.id_category = ctc.id
  313.                                      join (SELECT ur.id_roles
  314.                                                  FROM user_acm u
  315.                                                             join user_profile_roles ur on u.id = ur.id_user
  316.                                                  WHERE u.id = :userId and ur.id_profile in (1,2)) ur on cr.id_roles = ur.id_roles ) a
  317.                 order by 
  318.                         a.name, a.hidden desc, a.flag_type_checklist";
  319.         $statement = $em->getConnection()->prepare($q);
  320.         $statement->bindValue('userId', $userId);
  321.         $statement->execute();
  322.         $ResulQuery = $statement->fetchAll();
  323.         $Ruoli = "";
  324.         foreach ($ResulQuery as $res) {
  325.             // $logger->debug("[ChecklistImportSelection]  handling: ". $res["name"]);
  326.             //$logger->debug("[ChecklistImportSelection] array ".json_encode($res));
  327.             if ($res['tipologia'] == 'workflow') {
  328.                 $sqlRuoli = "select  string_agg( r.description_roles, '; ') AS ruoli                
  329.                 from chklst_template_role ctr, roles r
  330.                 where ctr.id_roles = r.id_roles 
  331.                 and ctr.id_template = :cid ";
  332.                  $statement = $em->getConnection()->prepare($sqlRuoli);
  333.                 $statement->bindValue('cid', $res['id']);
  334.                 $statement->execute();
  335.                 $ResulQueryRuoli = $statement->fetchAll()[0];
  336.                 $Ruoli = $ResulQueryRuoli['ruoli'];
  337.         
  338.                 $sqlImgPreview = "select flow_image from chklst_jflow where chklst_template = :cid ";
  339.                 $statement = $em->getConnection()->prepare($sqlImgPreview);
  340.                 $statement->bindValue('cid', $res['id']);
  341.                 $statement->execute();
  342.                 $ResulSqlImgPreview = $statement->fetchAll();
  343.                 $imgPreviewPath = "#";
  344.                 if ($ResulSqlImgPreview[0]["flow_image"]) {
  345.                     $imgPreviewPath = $ResulSqlImgPreview[0]['flow_image'];
  346.                 }
  347.             } else {
  348.                 $imgPreviewPath = '';
  349.             }
  350.             $arrayListChecklistTmp = array(
  351.                 'tipologia' => $res['tipologia'],
  352.                 'idTemplate' => $res['id'],
  353.                 'NomeChecklist' => $res['name'],
  354.                 'Descrizione' => $res['description'],
  355.                 'Visibilita' => $res['hidden'],
  356.                 'TipoChecklist' => $res['flag_type_checklist'],
  357.                 'Categoria' => $res['categoria'],
  358.                 'Ruoli' => $Ruoli,
  359.                 'Route' => $res['route'],
  360.                 'ImgPreviewPath' => $imgPreviewPath,
  361.                 'task_validate' => $res['task_validate'],
  362.                 'DataCreazione' => $res['data_creazione'],
  363.                 'DataModifica' => $res['data_modifica']
  364.             );
  365.             array_push($arrayListChecklist, $arrayListChecklistTmp);
  366.         }
  367.         $logger->debug("[ChecklistImportSelection] Ritorno al FrontEnd l'array");
  368.         $res_json->setData(array('arrayListChecklist' => $arrayListChecklist));
  369.         return $res_json;
  370.     }
  371.     public function checklistFlowChartLoadWebexAction(Request $request, LoggerInterface $logger, WebExFactorySymfonyService $webExFactorySymfonyService, ParameterBagInterface $params)
  372.     {
  373.         $csrfToken = $request->request->get('csrftoken');
  374.         if (!$this->isCsrfTokenValid('checklist_flowchart_webex', $csrfToken)) {
  375.             throw new \Exception('Csrf token not valid');
  376.         }
  377.         $em = $this->getDoctrine()->getManager();
  378.         //$logger = $this->getLogger();
  379.         $user = $this->getUser();
  380.         // qui la chiamata per recuperare la factory
  381.         $factoryWE = $webExFactorySymfonyService; 
  382.         // ottengo il client dalla factory
  383.         $clientWE = $factoryWE->getClient();
  384.         // chiamo il servizio che mi da la lista delle rooms
  385.         $retMsg = $clientWE->listMyRooms();
  386.         // risultato ok, possiamo recuperare le info
  387.         if ($retMsg->getResult() == ResponseARC::OK) {
  388.             $rooms = $retMsg->getData();
  389.         } else {
  390.             $rooms = [];
  391.         }
  392.         // se > 0, ci sono updates da registrare, altrimenti no
  393.         if (count($rooms) > 0) {
  394.             // $chatId ÃƒÂ¨ l'id che dobbiamo usare per contattare telegram
  395.             // hai un'occorrenza se
  396.             // bot aggiunto o rimosso da una chat oppure se ÃƒÂ¨ stato cambiato nome alla chat
  397.             foreach ($rooms as $room) {
  398.                 $room_id = $room["id"];
  399.                 $room_title = $room["title"];
  400.                 $sql = "INSERT INTO webex_rooms (id,title) 
  401.                            values ('$room_id', '$room_title')
  402.                         ON CONFLICT (id) DO UPDATE
  403.                           SET title = '$room_title'";
  404.                 $stmt = $em->getConnection()->prepare($sql);
  405.                 $stmt->execute();
  406.             } //hcaerof on $updates
  407.         } // fi count($updates)
  408.         $sql = "select id, title from webex_rooms";
  409.         $stmt = $em->getConnection()->prepare($sql);
  410.         $stmt->execute();
  411.         $ResulQuery = $stmt->fetchAll();
  412.         $rooms = $ResulQuery;
  413.         $ret = ['data' => ['webex_rooms' => $rooms]];
  414.         return new JsonResponse($ret);
  415.     }
  416.     public function checklistFlowChartLoadSelectedWebexAction(Request $request, LoggerInterface $logger)
  417.     {
  418.         $csrfToken = $request->request->get('csrftoken');
  419.         if (!$this->isCsrfTokenValid('checklist_flowchart_webex_selected', $csrfToken)) {
  420.             throw new \Exception('Csrf token not valid');
  421.         }
  422.         $em = $this->getDoctrine()->getManager();
  423.         //$myId = $request->query->get('id');
  424.         $sql = "select id, title from webex_rooms";
  425.         $stmt = $em->getConnection()->prepare($sql);
  426.         //$stmt->bindValue('myId', $myId);
  427.         $stmt->execute();
  428.         $ResulQuery = $stmt->fetchAll();
  429.         //$IdProfile=$ResulQuery['id_profile'];
  430.         $ret = ['data' => ['webex_rooms' => $ResulQuery]];
  431.         return new JsonResponse($ret);
  432.     }
  433.     public function checklistFlowChartLoadTelegramAction(Request $request, LoggerInterface $logger, TelegramBCFactorySymfonyService $telegramBCFactorySymfonyService, ParameterBagInterface $params)
  434.     {
  435.         $csrfToken = $request->request->get('csrftoken');
  436.         if (!$this->isCsrfTokenValid('checklist_flowchart_telegram', $csrfToken)) {
  437.             throw new \Exception('Csrf token not valid');
  438.         }
  439.         $em = $this->getDoctrine()->getManager();
  440.         //$logger = $this->getLogger();
  441.         $user = $this->getUser();
  442.         $sql = "select * from anag_service where active = 'Y' and service_type='telegram' ";
  443.         $stmt = $em->getConnection()->prepare($sql);
  444.         $stmt->execute();
  445.         $telegram_chat = $stmt->fetchAll();
  446.         $ret = ['data' => ['telegram_chat' => $telegram_chat]];
  447.         return new JsonResponse($ret);
  448.         // qui la chiamata al per ottenere la factory
  449.         $factoryTeleg = $telegramBCFactorySymfonyService; 
  450.         // ottengo il client dalla factory
  451.         $botClient = $factoryTeleg->getClient();
  452.         // chiamo il getUpdates sul client
  453.         $ret = $botClient->getUpdates();
  454.         // check se il servizio ÃƒÂ¨ andato bene
  455.         if ($ret->getResult() == ResponseARC::OK) {
  456.             $updates = $ret->getData();
  457.             /*
  458.              * array associativo organizzata come segue :
  459.              [ "$chatId" => ["active" => $val      // flag Y|N che indica se il bot ÃƒÂ¨ assegnato alla chat o no
  460.              ,"title" => $val       // titolo della chat
  461.              ,"dtUpdate" => $val    // DateTime dell'update fornito dal server Telegram
  462.              ,"uxTimestamp" => $val // Timestamp Unix dell'update fornito dal server Telegram
  463.              ,"updateId" => $val    // Id Telegram assegnato all'update
  464.              ]
  465.              ,"$chatId" => [...],
  466.              ... ]
  467.              */
  468.             // se > 0, ci sono updates da registrare, altrimenti no
  469.             if (count($updates) > 0) {
  470.                 // $chatId ÃƒÂ¨ l'id che dobbiamo usare per contattare telegram
  471.                 // hai un'occorrenza se
  472.                 // bot aggiunto o rimosso da una chat oppure se ÃƒÂ¨ stato cambiato nome alla chat
  473.                 foreach ($updates as $chatId => $updInfo) {
  474.                     $chat_id = $chatId;
  475.                     $active = $updInfo["active"];
  476.                     $title = $updInfo["title"];
  477.                     $dt_update = $updInfo["dtUpdate"];
  478.                     $ux_timestamp = $updInfo["uxTimestamp"];
  479.                     $update_id = $updInfo["updateId"];
  480.                     $service_type = "telegram";
  481.                     $sql = "insert into anag_service (chat_id,active,title,dt_update,ux_timestamp,update_id,service_type) 
  482.                                 values ('$chat_id', '$active', '$title', to_timestamp($ux_timestamp)::timestamp , $ux_timestamp, $update_id, '$service_type') 
  483.                                 ON CONFLICT ('$chat_id') DO UPDATE  set
  484.                                 active = '$active', 
  485.                                 title = '$title', 
  486.                                 dt_update = to_timestamp($ux_timestamp)::timestamp , 
  487.                                 ux_timestamp = $ux_timestamp, 
  488.                                 update_id = $update_id, 
  489.                                 service_type = '$service_type'";
  490.                     $stmt = $em->getConnection()->prepare($sql);
  491.                     $stmt->execute();
  492.                 } //hcaerof on $updates
  493.             } // fi count($updates)
  494.         } // fi $ret->getResult();
  495.         $sql = "select * from anag_service where active = 'Y' and service_type='telegram' ";
  496.         $stmt = $em->getConnection()->prepare($sql);
  497.         $stmt->execute();
  498.         $telegram_chat = $stmt->fetchAll();
  499.         $ret = ['data' => ['telegram_chat' => $telegram_chat]];
  500.         return new JsonResponse($ret);
  501.     }
  502.     private function getWorkflowParameters($id_workflow){
  503.         $conn = $this->getDoctrine()->getManager()->getConnection();
  504.         $query_parameters = 'SELECT * FROM chklst_template_parameters WHERE chklst_id = :id_workflow';
  505.         $statement = $conn-> prepare($query_parameters);
  506.         $statement->bindValue("id_workflow", $id_workflow);
  507.         $statement->execute();    
  508.         $chklst_parameters = $statement->fetchAll();
  509.         return $chklst_parameters;
  510.     }
  511.     //----------------------------------------------------------------------------------
  512.     // Aggiorna i dati del Workflow (Nome, Descrizione, Ruoli, parametri, ecc...)
  513.     //----------------------------------------------------------------------------------
  514.     public function updateChktmplFlowAction(Request $request, $cid, LoggerInterface $logger, ParameterBagInterface $params, CsrfTokenManagerInterface $tokenManager)
  515.     {
  516.         $csrfToken = $request->request->get('csrftoken');
  517.         $forbiddenPattern = '/^(?:\$\$|#>)|[\'"]+/';
  518.         
  519.         if (!$this->isCsrfTokenValid('chktmpl_flow_update', $csrfToken)) {
  520.             throw new \Exception('Csrf token not valid');
  521.         }
  522.         
  523.         $user = $this->getUser();
  524.         $userId = $user->getId();
  525.         $em = $this->getDoctrine()->getManager();
  526.         $connection = $em->getConnection();
  527.         //$db_driver = $params->get('db_driver');
  528.         $IdTemplate = $cid;
  529.         $id = $_POST["form_id_c"];
  530.         $name = trim($_POST["form_nome_c"]);
  531.         $description = $_POST["form_descrizione_c"];
  532.         //$hidden = $_POST["form_att_c"];
  533.         // -----------------------------------------------------------
  534.         // Nel caso in cui il nome Ã¨ vuoto non procedo con l'update
  535.         // -----------------------------------------------------------
  536.         if($name == ""){
  537.             return new JsonResponse(['success' => false]);    
  538.         }
  539.         if (isset($_POST["da_inattive" . '_' . $cid])) {
  540.             // $logger->debug("sto dentro isset da_inattive_" . $cid);
  541.             $q = "update chklst_template set name = :name, "
  542.                 . " description = :description , data_modifica = now(), modificato_da = :modificato_da  "
  543.                 . " where id = :id;";
  544.             $statement = $connection->prepare($q);
  545.             $statement->bindValue('description', $description);
  546.             $statement->bindValue('modificato_da', $userId);
  547.             $statement->bindValue('name', $name);
  548.             $statement->bindValue('id', $id);
  549.             $statement->execute();
  550.         } else {
  551.             // $logger->debug("sto dentro ELSE isset da_inattive_" . $cid);
  552.             $flag_send_webex = "N";
  553.             $room_webex      = "";
  554.             $text_send_webex = "Riepilogo esecuzione Checklist";
  555.             $to_send_message = "";
  556.             $cc_send_message = "";
  557.             $flag_send_mail  = "N";
  558.             $sql = "select * from roles";
  559.             $stmt = $connection->prepare($sql);
  560.             $stmt->execute();
  561.             $roles = $stmt->fetchAll();
  562.             
  563.             $lista_ruoli = preg_grep("/^ins_chk_2_*/", array_keys($_POST));
  564.             if (count($lista_ruoli) > 0) {
  565.                 $sql = "delete from chklst_template_role where id_template = :cid ";
  566.                 $statement = $connection->prepare($sql);
  567.                 $statement->bindValue('cid', $cid);
  568.                 $statement->execute();
  569.                 foreach ($roles as $role) {
  570.                     $id_role = $role['id_roles'];
  571.                      foreach ($lista_ruoli as $l) {
  572.                          if ($role['description_roles'] == $_POST[$l]) {
  573.                              $sql = "insert into chklst_template_role (id_template,id_roles) values ($cid, $id_role) 
  574.                                     ON CONFLICT (id_template,id_roles) DO NOTHING";
  575.                              $statement = $connection->prepare($sql);
  576.                              $statement->execute();
  577.                          }
  578.                      }
  579.                 }
  580.             }
  581.             if (isset($_POST["form_category"])) {
  582.                 $wflCategory  = $_POST["form_category"];
  583.             }
  584.             $q = "update chklst_template set name = :name, "
  585.                 . " description = :description , flag_send_webex= :flag_send_webex , room_webex= :room_webex , text_send_webex= :text_send_webex , "
  586.                 . " to_send_message= :to_send_message , cc_send_message= :cc_send_message , flag_send_mail= :flag_send_mail , id_category= :id_category , data_modifica = now(), modificato_da = :modificato_da "
  587.                 . " where id = :id;";
  588.             $statement = $connection->prepare($q);
  589.             $statement->bindValue('name', $name);
  590.             $statement->bindValue('description', $description);
  591.             $statement->bindValue('flag_send_webex', $flag_send_webex);
  592.             $statement->bindValue('room_webex', $room_webex);
  593.             $statement->bindValue('text_send_webex', $text_send_webex);
  594.             $statement->bindValue('to_send_message', $to_send_message);
  595.             $statement->bindValue('cc_send_message', $cc_send_message);
  596.             $statement->bindValue('flag_send_mail', $flag_send_mail);
  597.             $statement->bindValue('id_category', $wflCategory);
  598.             $statement->bindValue('modificato_da', $userId);
  599.             $statement->bindValue('id', $id);
  600.             $statement->execute();
  601.             /**************** INIZIO GESTIONE UPLOAD WORKFLOW FILES *********************/
  602.             $target_dir = $params->get('kernel.project_dir') . '/public/wf_uploads/' . $cid . '/' . $request->getBasePath();
  603.             if (!file_exists($target_dir)) {
  604.                 mkdir($target_dir, 0777, true);
  605.             }
  606.             $delete_parameters = "delete from chklst_template_workflow_files where chklst_id = '$cid'";
  607.             $statement = $connection->prepare($delete_parameters);
  608.             $statement->execute();
  609.             $em->flush();
  610.             $wf_description = "";
  611.             $param_name = "";
  612.             $param_file_name = "";
  613.             $param_file_path = "";
  614.             $param_file_type = "";
  615.                     
  616.             $em->flush();
  617.             /****************  FINE GESTIONE UPLAOD WORKFLOW FILES  *********************/
  618.             /********************** INIZIO GESTIONE PARAMETRI **********************/
  619.             $delete_parameters = "delete from chklst_template_parameters where chklst_id = :cid ";
  620.             $statement = $connection->prepare($delete_parameters);
  621.             $statement->bindValue('cid', $cid);
  622.             $statement->execute();
  623.             $list_param_type = preg_grep("/^form_lista_param_type_.*/", array_keys($_POST));
  624.             $functions = new Functions($this, $logger, $em);
  625.             foreach ($list_param_type as $l) {
  626.                 $exp = explode("_", $l);
  627.                 $i = end($exp);
  628.                 if (isset($_POST["form_lista_param_type_" . $i]) && isset($_POST["form_lista_param_name_" . $i]) && isset($_POST["form_lista_param_value_" . $i])) {
  629.                     $param_type = $_POST["form_lista_param_type_" . $i];
  630.                     $param_name    = $_POST["form_lista_param_name_" . $i];
  631.                     $param_value = $_POST["form_lista_param_value_" . $i];
  632.                     // Gestione parametro di tipo Encrypt
  633.                     if($param_type === "encrypt"){
  634.                         $hidden_encrypt_param = $_POST["hidden_checklist_param_value_" . $i];
  635.                         if($hidden_encrypt_param === "1"){
  636.                             $param_value = $functions->encrypt($param_value);
  637.                         }
  638.                     }
  639.                     
  640.                     // Se il nome parametro corrisponde al pattern proibito, salto l'inserimento
  641.                     if (preg_match($forbiddenPattern, $param_name)) {
  642.                         continue; 
  643.                     }
  644.                     $sql = "insert into chklst_template_parameters (chklst_id, param_name, param_value, param_type)
  645.                         values (:cid, :param_name, :param_value, :param_type)
  646.                         ON CONFLICT(chklst_id, param_name) DO UPDATE SET
  647.                         param_name = :param_name,
  648.                         param_value = :param_value,
  649.                         param_type = :param_type ";
  650.                     $statement = $connection->prepare($sql);
  651.                     $statement->bindValue('cid', $cid);
  652.                     $statement->bindValue('param_name', $param_name);
  653.                     $statement->bindValue('param_value', $param_value);
  654.                     $statement->bindValue('param_type', $param_type);
  655.                     $statement->execute();
  656.                 }
  657.             }
  658.             /******************* FINE GESTIONE PARAMETRI ***********************/
  659.             /**************** INIZIO GESTIONE UPLOAD FILES *********************/
  660.             $target_dir = $params->get('kernel.project_dir') . '/uploads/' . $cid . '/' . $request->getBasePath();
  661.             if (!file_exists($target_dir)) {
  662.                 mkdir($target_dir, 0777, true);
  663.             }
  664.             //$logger->debug("[updateChktmplAction] creta directory ".$target_dir);
  665.             $sql_old_parameters_files = "select param_file_name from chklst_template_parameters_files where chklst_id = '$cid'";
  666.             $statement = $connection->prepare($sql_old_parameters_files);
  667.             $statement->execute();
  668.             $old_parameters_files = $statement->fetchAll();
  669.             //$logger->debug("[updateChktmplAction] Old Parmeters: " . json_encode($old_parameters_files));
  670.             $delete_parameters = "delete from chklst_template_parameters_files where chklst_id = '$cid'";
  671.             $statement = $connection->prepare($delete_parameters);
  672.             $statement->execute();
  673.             $delete_parameters = "delete from chklst_template_parameters where chklst_id = '$cid' and flag_file='Y'";
  674.             $statement = $connection->prepare($delete_parameters);
  675.             $statement->execute();
  676.             $em->flush();
  677.             $list_fileToUpload = preg_grep("/^form_lista_files_param_name_*/", array_keys($_POST));
  678.             foreach ($list_fileToUpload as $l) {
  679.                 $exp = explode("_", $l);
  680.                 $i = end($exp);
  681.                 if (isset($_FILES["fileToUpload_" . $i]) && isset($_POST["form_lista_files_param_name_" . $i])) {
  682.                     //$logger->debug("[updateChktmplAction] STO DENTRO ISSET FILES");
  683.                     $target_file = $target_dir . basename($_FILES["fileToUpload_" . $i]["name"]);
  684.                     if (move_uploaded_file($_FILES["fileToUpload_" . $i]["tmp_name"], $target_file)) {
  685.                         //$logger->debug("[updateChktmplAction] The file " . basename(htmlEntities($_FILES["fileToUpload_" . $i]["name"], ENT_QUOTES)) . " has been uploaded.");
  686.                         $param_name    = $this->custom_addslashes($_POST["form_lista_files_param_name_" . $i], $params);
  687.                         if (isset($_FILES["fileToUpload_" . $i]["name"])) {
  688.                             $param_file_name = basename($_FILES["fileToUpload_" . $i]["name"]);
  689.                             $param_file_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
  690.                         } else {
  691.                             $param_file_name = $_POST["form_lista_files_param_file_name_" . $i];
  692.                             $param_file_type = strtolower(pathinfo($param_file_name, PATHINFO_EXTENSION));
  693.                         }
  694.                         $param_file_path = $target_dir;
  695.                         // Se il nome parametro corrisponde al pattern proibito, salto l'inserimento
  696.                         if (preg_match($forbiddenPattern, $param_name)) {
  697.                             continue; 
  698.                         }
  699.                         $sql = "insert into chklst_template_parameters_files (chklst_id, param_name, param_file_name, param_file_path, param_file_type)
  700.                             values (:cid, :param_name, :param_file_name, :param_file_path, :param_file_type)
  701.                             ON CONFLICT (chklst_id, param_name) DO UPDATE SET
  702.                             param_file_name = :param_file_name,
  703.                             param_file_path = :param_file_path,
  704.                             param_file_type = :param_file_type";
  705.                         $statement = $connection->prepare($sql);
  706.                         $statement->bindValue('cid', $cid);
  707.                         $statement->bindValue('param_name', $param_name);
  708.                         $statement->bindValue('param_file_name', $param_file_name);
  709.                         $statement->bindValue('param_file_path', $param_file_path);
  710.                         $statement->bindValue('param_file_type', $param_file_type);
  711.                         $statement->execute();
  712.                         /***** Gestione file come parametri checklist *****/
  713.                         // Parmetro param_name.filename (di tipo file) per il nome file da sostituire senza apici
  714.                         $param_name_filename = $param_name . '.filename';
  715.                         $sql = "insert into chklst_template_parameters (chklst_id, param_name, param_value, param_type, flag_file)
  716.                                 values (:cid, :param_name_filename, :param_file_name, 'file', 'Y')
  717.                                 ON CONFLICT (chklst_id, param_name) DO UPDATE SET
  718.                                 param_value = :param_file_name,
  719.                                 param_type = 'file',
  720.                                 flag_file = 'Y'";
  721.                         $statement = $connection->prepare($sql);
  722.                         $statement->bindValue('cid', $cid);
  723.                         $statement->bindValue('param_name_filename', $param_name_filename);
  724.                         $statement->bindValue('param_file_name', $param_file_name);
  725.                         $statement->execute();
  726.                         // Parmetro param_name.file (di tipo file) per il file con path da sostituire senza apici
  727.                         $param_name_file = $param_name . '.file';
  728.                         $param_file_value = $param_file_path . $param_file_name;
  729.                         $sql = "insert into chklst_template_parameters (chklst_id, param_name, param_value, param_type, flag_file)
  730.                                 values (:cid, :param_name_file, :param_file_value, 'file', 'Y')
  731.                                 ON CONFLICT (chklst_id, param_name) DO UPDATE SET
  732.                                 param_value = :param_file_value,
  733.                                 param_type = 'file',
  734.                                 flag_file = 'Y'";
  735.                         $statement = $connection->prepare($sql);
  736.                         $statement->bindValue('cid', $cid);
  737.                         $statement->bindValue('param_name_file', $param_name_file);
  738.                         $statement->bindValue('param_file_value', $param_file_value);
  739.                         $statement->execute();
  740.                         // Parmetro param_name.content (di tipo file) per la lettura del contenuto del file
  741.                         $param_name_content = $param_name . '.content';
  742.                         $sql = "insert into chklst_template_parameters (chklst_id, param_name, param_value, param_type, flag_file)
  743.                                 values (:cid, :param_name_content, :param_file_value, 'file', 'Y')
  744.                                 ON CONFLICT (chklst_id, param_name) DO UPDATE SET
  745.                                 param_value = :param_file_value,
  746.                                 param_type = 'file',
  747.                                 flag_file = 'Y'";
  748.                         $statement = $connection->prepare($sql);
  749.                         $statement->bindValue('cid', $cid);
  750.                         $statement->bindValue('param_name_content', $param_name_content);
  751.                         $statement->bindValue('param_file_value', $param_file_value);
  752.                         $statement->execute();
  753.                     } elseif (isset($_POST["form_lista_files_param_file_name_" . $i])) {
  754.                         //$logger->debug("[updateChktmplAction] STO DENTRO ISSET FILE NAME");
  755.                         $param_name    = $this->custom_addslashes(htmlEntities($_POST["form_lista_files_param_name_" . $i], ENT_QUOTES), $params);
  756.                         $param_file_name = $this->custom_addslashes(htmlEntities($_POST["form_lista_files_param_file_name_" . $i], ENT_QUOTES), $params);
  757.                         $param_file_type = strtolower(pathinfo($param_file_name, PATHINFO_EXTENSION));
  758.                         $param_file_path = $target_dir;
  759.                         // Se il nome parametro corrisponde al pattern proibito, salto l'inserimento
  760.                         if (preg_match($forbiddenPattern, $param_name)) {
  761.                             continue; 
  762.                         }
  763.                         $sql = "insert into chklst_template_parameters_files (chklst_id, param_name, param_file_name, param_file_path, param_file_type)
  764.                                         values (:cid, :param_name, :param_file_name, :param_file_path, :param_file_type)
  765.                                         ON CONFLICT (chklst_id, param_name) DO UPDATE SET
  766.                                         param_name = :param_name,
  767.                                         param_file_name = :param_file_name,
  768.                                         param_file_path = :param_file_path,
  769.                                         param_file_type = :param_file_type";
  770.                         $statement = $connection->prepare($sql);
  771.                         $statement->bindValue('cid', $cid);
  772.                         $statement->bindValue('param_name', $param_name);
  773.                         $statement->bindValue('param_file_name', $param_file_name);
  774.                         $statement->bindValue('param_file_path', $param_file_path);
  775.                         $statement->bindValue('param_file_type', $param_file_type);
  776.                         $statement->execute();
  777.                         /***** Gestione file come parametri checklist *****/
  778.                         // Parmetro param_name.filename (di tipo file) per il nome file da sostituire senza apici
  779.                         $param_name_filename = $param_name . '.filename';
  780.                         $sql = "insert into chklst_template_parameters (chklst_id, param_name, param_value, param_type, flag_file)
  781.                                     values (:cid, :param_name_filename, :param_file_name, 'file', 'Y')
  782.                                     ON CONFLICT (chklst_id, param_name) DO UPDATE SET
  783.                                     param_value = :param_file_name,
  784.                                     param_type = 'file',
  785.                                     flag_file = 'Y'";
  786.                         $statement = $connection->prepare($sql);
  787.                         $statement->bindValue('cid', $cid);
  788.                         $statement->bindValue('param_name_filename', $param_name_filename);
  789.                         $statement->bindValue('param_file_name', $param_file_name);
  790.                         $statement->execute();
  791.                         // Parmetro param_name.file (di tipo file) per il file con path da sostituire senza apici
  792.                         $param_name_file = $param_name . '.file';
  793.                         $param_file_value = $param_file_path . $param_file_name;
  794.                         $sql = "insert into chklst_template_parameters (chklst_id, param_name, param_value, param_type, flag_file)
  795.                                     values (:cid, :param_name_file, :param_file_value, 'file', 'Y')
  796.                                     ON CONFLICT (chklst_id, param_name) DO UPDATE SET
  797.                                     param_value = :param_file_value,
  798.                                     param_type = 'file',
  799.                                     flag_file = 'Y'";
  800.                         $statement = $connection->prepare($sql);                        
  801.                         $statement->bindValue('cid', $cid);
  802.                         $statement->bindValue('param_name_file', $param_name_file);
  803.                         $statement->bindValue('param_file_value', $param_file_value);
  804.                         $statement->execute();
  805.                         // Parmetro param_name.content (di tipo file) per la lettura del contenuto del file
  806.                         $param_name_content = $param_name . '.content';
  807.                         $sql = "insert into chklst_template_parameters (chklst_id, param_name, param_value, param_type, flag_file)
  808.                                     values (:cid, :param_name_content, :param_file_value, 'file', 'Y')
  809.                                     ON CONFLICT (chklst_id, param_name) DO UPDATE SET
  810.                                     param_value = :param_file_value,
  811.                                     param_type = 'file',
  812.                                     flag_file = 'Y'";
  813.                         $statement = $connection->prepare($sql);
  814.                         $statement->bindValue('cid', $cid);
  815.                         $statement->bindValue('param_name_content', $param_name_content);
  816.                         $statement->bindValue('param_file_value', $param_file_value);
  817.                         $statement->execute();
  818.                     }
  819.                 }
  820.             }
  821.             $em->flush();
  822.             $sql_new_parameters_files = "select param_file_name from chklst_template_parameters_files where chklst_id = '$cid'";
  823.             $statement = $connection->prepare($sql_new_parameters_files);
  824.             $statement->execute();
  825.             $new_parameters_files = $statement->fetchAll();
  826.             //$logger->debug("[updateChktmplAction] New Parmeters: " . json_encode($new_parameters_files));
  827.             foreach ($old_parameters_files as $old_parameters_file) {
  828.                 $cnt = 0;
  829.                 foreach ($new_parameters_files as $new_parameters_file) {
  830.                     if ($old_parameters_file['param_file_name'] == $new_parameters_file['param_file_name']) {
  831.                         //$logger->debug("[updateChktmplAction] File " . $old_parameters_file['param_file_name'] . " presente nei nuovi parametri.");
  832.                         $cnt += 1;
  833.                     }
  834.                 }
  835.                 if ($cnt == 0) {
  836.                     //$logger->debug("[updateChktmplAction] File " . $old_parameters_file['param_file_name'] . " NON presente nei nuovi parametri.");
  837.                     if (file_exists($target_dir . $old_parameters_file['param_file_name']) && !is_dir($target_dir . $old_parameters_file['param_file_name'])) {
  838.                         if (!unlink($target_dir . $old_parameters_file['param_file_name'])) {
  839.                             //$logger->debug("[updateChktmplAction] Non ÃƒÂ¨ stato possibile eliminare il file " . $old_parameters_file['param_file_name'] . ".");
  840.                         } else {
  841.                             $sql = "delete from chklst_template_parameters_files where chklst_id=:$cid and param_file_name= :param_file_name";
  842.                             $statement = $connection->prepare($sql);
  843.                             $statement->bindValue('cid', $cid);
  844.                             $statement->bindValue('param_file_name', $old_parameters_file['param_file_name']);
  845.                             $statement->execute();
  846.                             //$logger->debug("[updateChktmplAction] File " . $old_parameters_file['param_file_name'] . " eliminato correttamente.");
  847.                         }
  848.                     }
  849.                 }
  850.             }
  851.             /****************  FINE GESTIONE UPLAOD FILES  *********************/
  852.         }
  853.         
  854.         $wflParams = $this->getWorkflowParameters($IdTemplate);
  855.         /*return $this->redirect($this->generateUrl('checklist_flowchart', array(
  856.             'idTemplate' => $IdTemplate, 
  857.             'csrftoken' => $tokenManager->getToken('checklist_flowchart')->getValue()
  858.         )));*/
  859.         return new JsonResponse([
  860.             'success' => true,
  861.             'wflParams' => $wflParams,
  862.         ]);
  863.     }
  864.     #Action che crea la chklst per il designer
  865.     public function insertChktmplFlowAction(Request $request, LoggerInterface $logger, ParameterBagInterface $params, CsrfTokenManagerInterface $tokenManager)
  866.     {
  867.         $csrfToken = $request->request->get('csrftoken');
  868.         if (!$this->isCsrfTokenValid('insert_chklst', $csrfToken)) {
  869.             throw new \Exception('Csrf token not valid');
  870.         }
  871.         $user = $this->getUser();
  872.         $name =trim($_POST["form_nome"]);
  873.         $description = trim($_POST["form_descrizione"]);
  874.         $hidden = htmlEntities($_POST["form_att"], ENT_QUOTES);
  875.         
  876.         // check nome del workflow Ã¨ vuoto, assegna un nome di default
  877.         if($name == ""){
  878.             $name = "workflow_" . date("Ymd_His");
  879.         }
  880.         $category = 1;
  881.         if (isset($_POST["form_category"])) {
  882.             $category  = htmlEntities($_POST["form_category"], ENT_QUOTES);
  883.         }
  884.         $em = $this->getDoctrine()->getManager();
  885.         $connection = $em->getConnection();
  886.         $userId = $user->getId();
  887.         $q = "insert into chklst_template (name, description, hidden, flag_send_webex, room_webex, text_send_webex, to_send_message, cc_send_message, flag_send_mail, id_category, data_creazione, creato_da, modificato_da) "
  888.             . "values (:name, :description, :hidden, 'N', '', 'Riepilogo esecuzione Checklist', '', '','N', :category, now(), :userId, :userId2 ) ON CONFLICT (name) DO NOTHING;";
  889.         $statement = $connection->prepare($q);
  890.         $statement->bindValue('name', $name);
  891.         $statement->bindValue('description', $description);
  892.         $statement->bindValue('hidden', $hidden);
  893.         $statement->bindValue('category', $category);
  894.         $statement->bindValue('userId', $userId);
  895.         $statement->bindValue('userId2', $userId);
  896.         $statement->execute();
  897.         $q = "select id from chklst_template "
  898.             . " where name = :name ";
  899.         $statement = $connection->prepare($q);
  900.         $statement->bindValue('name', $name);
  901.         $statement->execute();
  902.         $res = $statement->fetchAll()[0];
  903.         $cid = $res['id'];
  904.         // INIZIO GESTIONE RUOLI CHECKLIST
  905.         $sql = "select * from roles";
  906.         $stmt = $em->getConnection()->prepare($sql);
  907.         $stmt->execute();
  908.         $roles = $stmt->fetchAll();
  909.         $lista_ruoli = preg_grep("/^ins_chk_2_*/", array_keys($_POST));
  910.         if (count($lista_ruoli) > 0) {
  911.             $sql = "delete from chklst_template_role where id_template = :cid";
  912.             $statement = $connection->prepare($sql);
  913.             $statement->bindValue('cid', $cid);
  914.             $statement->execute();
  915.             foreach ($roles as $role) {
  916.                 $id_role = $role['id_roles'];
  917.                 $logger->debug("ruolo: " . $id_role);
  918.                 foreach ($lista_ruoli as $l) {
  919.                     if ($role['description_roles'] == $_POST[$l]) {
  920.                         $logger->debug("sto dentro isset " . $id_role);
  921.                         $sql = "insert into chklst_template_role (id_template,id_roles) values ($cid, $id_role)";
  922.                         $statement = $connection->prepare($sql);
  923.                         $statement->execute();
  924.                     }
  925.                 }
  926.             }
  927.         }
  928.         // FINE GESTIONE RUOLI CHECKLIST
  929.         /****************  INIZIO INTEGRAZIONE DESIGNER  *********************/
  930.         $sqld = "insert into chklst_jflow (chklst_template, json_flow) values($cid,'')";
  931.         $statement = $connection->prepare($sqld);
  932.         $statement->execute();
  933.         /****************  FINE INTEGRAZIONE DESIGNER  *********************/
  934.         /**************** INIZIO GESTIONE UPLOAD WORKFLOW FILES *********************/
  935.         $target_dir = $params->get('kernel.project_dir') . '/public/wf_uploads/' . $cid . '/' . $request->getBasePath();
  936.         if (!file_exists($target_dir)) {
  937.             mkdir($target_dir, 0777, true);
  938.         }
  939.         $wf_description = "";
  940.         $param_name = "";
  941.         $param_file_name = "";
  942.         $param_file_path = "";
  943.         $param_file_type = "";
  944.         $list_wf_files_param_name = preg_grep("/^form_lista_wf_files_param_name_0_*/", array_keys($_POST));
  945.         foreach ($list_wf_files_param_name as $l) {
  946.             $exp = explode("_", $l);
  947.             $i = end($exp);
  948.             if (isset($_POST["form_wf_text_0"])) {
  949.                 $wf_description = $this->custom_addslashes(htmlEntities($_POST["form_wf_text_0"], ENT_QUOTES), $params);
  950.             }
  951.             if (isset($_FILES["wf_fileToUpload" . '_0_' . $i]) && isset($_POST["form_lista_wf_files_param_name" . '_0_' . $i])) {
  952.                 //$logger->debug("[updateChktmplAction] STO DENTRO ISSET wf_FILES");
  953.                 $target_file = $target_dir . basename(htmlEntities($_FILES["wf_fileToUpload" . '_0_' . $i]["name"], ENT_QUOTES));
  954.                 if (move_uploaded_file(htmlEntities($_FILES["wf_fileToUpload" . '_0_' . $i]["tmp_name"], ENT_QUOTES), $target_file)) {
  955.                     //$logger->debug("[updateChktmplAction] The wf_file " . basename(htmlEntities($_FILES["wf_fileToUpload" . '_0_' . $i]["name"], ENT_QUOTES)) . " has been uploaded.");
  956.                     $param_name    = $this->custom_addslashes(htmlEntities($_POST["form_lista_wf_files_param_name" . '_0_' . $i], ENT_QUOTES), $params);
  957.                     if (isset($_FILES["wf_fileToUpload" . '_0_' . $i]["name"])) {
  958.                         $param_file_name = basename(htmlEntities($_FILES["wf_fileToUpload" . '_0_' . $i]["name"], ENT_QUOTES));
  959.                         $param_file_type = pathinfo($param_file_name, PATHINFO_EXTENSION);
  960.                     } else {
  961.                         $param_file_name = htmlEntities($_POST["form_lista_wf_files_param_file_name" . '_0_' . $i], ENT_QUOTES);
  962.                         $param_file_type = pathinfo($param_file_name, PATHINFO_EXTENSION);
  963.                     }
  964.                     $param_file_path = $target_dir;
  965.                 }
  966.             }
  967.             $sql = "insert into chklst_template_workflow_files (chklst_id, param_name, param_file_name, param_file_path, param_file_type)
  968.                             values (:cid, :param_name, :param_file_name, :param_file_path, :param_file_type)
  969.                             ON CONFLICT (chklst_id, param_name) DO UPDATE SET
  970.                             param_file_name = :param_file_name,
  971.                             param_file_path = :param_file_path,
  972.                             param_file_type = :param_file_type";
  973.             $statement = $connection->prepare($sql);
  974.             $statement->bindValue('cid', $cid);
  975.             $statement->bindValue('param_name', $param_name);
  976.             $statement->bindValue('param_file_name', $param_file_name);
  977.             $statement->bindValue('param_file_path', $param_file_path);
  978.             $statement->bindValue('param_file_type', $param_file_type);
  979.             $statement->execute();
  980.         }
  981.         $em->flush();
  982.         /****************  FINE GESTIONE UPLAOD WORKFLOW FILES  *********************/
  983.         /********************** INIZIO GESTIONE PARAMETRI **********************/
  984.         $list_param_type_0 = preg_grep("/^form_lista_param_type_0_*/", array_keys($_POST));
  985.         foreach ($list_param_type_0 as $l) {
  986.             $exp = explode("_", $l);
  987.             $i = end($exp);
  988.             if (isset($_POST["form_lista_param_type" . '_0_' . $i]) && isset($_POST["form_lista_param_name" . '_0_' . $i]) && isset($_POST["form_lista_param_value" . '_0_' . $i])) {
  989.                 $param_type = $_POST["form_lista_param_type" . '_0_' . $i];
  990.                 $param_name    = $this->custom_addslashes(htmlEntities($_POST["form_lista_param_name" . '_0_' . $i], ENT_QUOTES), $params);
  991.                 $param_value = $this->custom_addslashes(htmlEntities($_POST["form_lista_param_value" . '_0_' . $i], ENT_QUOTES), $params);
  992.                 $sql = "insert into chklst_template_parameters (chklst_id, param_name, param_value, param_type)
  993.                         values (:cid, :param_name, :param_value, :param_type)
  994.                         ON CONFLICT(chklst_id, param_name) DO UPDATE SET
  995.                         param_name = :param_name,
  996.                         param_value = :param_value,
  997.                         param_type = :param_type ";
  998.                 $statement = $connection->prepare($sql);
  999.                 $statement->bindValue('cid', $cid);
  1000.                 $statement->bindValue('param_name', $param_name);
  1001.                 $statement->bindValue('param_value', $param_value);
  1002.                 $statement->bindValue('param_type', $param_type);
  1003.                 $statement->execute();
  1004.             }
  1005.         }
  1006.         /******************* FINE GESTIONE PARAMETRI ***********************/
  1007.         /**************** INIZIO GESTIONE UPLOAD FILES *********************/
  1008.         $target_dir = $params->get('kernel.project_dir') . '/uploads/' . $cid . '/' . $request->getBasePath();
  1009.         if (!file_exists($target_dir)) {
  1010.             mkdir($target_dir, 0777, true);
  1011.         }
  1012.         $list_files_param_name = preg_grep("/^form_lista_files_param_name_0_*/", array_keys($_POST));
  1013.         foreach ($list_files_param_name as $l) {
  1014.             $exp = explode("_", $l);
  1015.             $id = end($exp);
  1016.             if (isset($_FILES["fileToUpload" . '_0_' . $id]) && isset($_POST["form_lista_files_param_name" . '_0_' . $id])) {
  1017.                 //$logger->debug("[updateChktmplAction] STO DENTRO ISSET FILES");
  1018.                 $target_file = $target_dir . basename(htmlEntities($_FILES["fileToUpload" . '_0_' . $id]["name"], ENT_QUOTES));
  1019.                 if (move_uploaded_file(htmlEntities($_FILES["fileToUpload" . '_0_' . $id]["tmp_name"], ENT_QUOTES), $target_file)) {
  1020.                     //$logger->debug("[updateChktmplAction] The file " . basename(htmlEntities($_FILES["fileToUpload" . '_0_' . $id]["name"], ENT_QUOTES)) . " has been uploaded.");
  1021.                     $param_name    = $_POST["form_lista_files_param_name" . '_0_' . $id];
  1022.                     if (isset($_FILES["fileToUpload" . '_0_' . $id]["name"])) {
  1023.                         $param_file_name = basename(htmlEntities($_FILES["fileToUpload" . '_0_' . $id]["name"], ENT_QUOTES));
  1024.                         $param_file_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
  1025.                     } else {
  1026.                         $param_file_name = $this->custom_addslashes(htmlEntities($_POST["form_lista_files_param_file_name" . '_0_' . $id], ENT_QUOTES), $params);
  1027.                         $param_file_type = strtolower(pathinfo($param_file_name, PATHINFO_EXTENSION));
  1028.                     }
  1029.                     $param_file_path = $target_dir;
  1030.                     $sql = "insert into chklst_template_parameters_files (chklst_id, param_name, param_file_name, param_file_path, param_file_type)
  1031.                                 values (:cid, :param_name, :param_file_name, :param_file_path, :param_file_type)
  1032.                                 ON CONFLICT (chklst_id, param_name) DO UPDATE SET
  1033.                                 param_file_name = :param_file_name,
  1034.                                 param_file_path = :param_file_path,
  1035.                                 param_file_type = :param_file_type";
  1036.                     $statement = $connection->prepare($sql);                            
  1037.                     $statement->bindValue('cid', $cid);
  1038.                     $statement->bindValue('param_name', $param_name);
  1039.                     $statement->bindValue('param_file_name', $param_file_name);
  1040.                     $statement->bindValue('param_file_path', $param_file_path);
  1041.                     $statement->bindValue('param_file_type', $param_file_type);
  1042.                     $statement->execute();
  1043.                     /***** Gestione file come parametri checklist *****/
  1044.                     // Parmetro param_name (di tipo stringa) per il nome file da sostituire con gli apici
  1045.                     $sql = "insert into chklst_template_parameters (chklst_id, param_name, param_value, param_type, flag_file)
  1046.                                 values (:cid, :param_name, :param_file_name, 'string', 'Y')
  1047.                                 ON CONFLICT (chklst_id, param_name) DO UPDATE SET
  1048.                                 param_value = :param_file_name,
  1049.                                 param_type = 'string',
  1050.                                 flag_file = 'Y'";
  1051.                     $statement = $connection->prepare($sql);                    
  1052.                     $statement->bindValue('cid', $cid);
  1053.                     $statement->bindValue('param_name', $param_name);
  1054.                     $statement->bindValue('param_file_name', $param_file_name);
  1055.                     $statement->execute();
  1056.                     // Parmetro param_name.filename (di tipo file) per il nome file da sostituire senza apici
  1057.                     $param_name_filename = $param_name . '.filename';
  1058.                     $sql = "insert into chklst_template_parameters (chklst_id, param_name, param_value, param_type, flag_file)
  1059.                                 values (:cid, :param_name_filename, :param_file_name, 'file', 'Y')
  1060.                                 ON CONFLICT (chklst_id, param_name) DO UPDATE SET
  1061.                                 param_value = :param_file_name,
  1062.                                 param_type = 'file',
  1063.                                 flag_file = 'Y'";
  1064.                     $statement = $connection->prepare($sql);                    
  1065.                     $statement->bindValue('cid', $cid);
  1066.                     $statement->bindValue('param_name_filename', $param_name_filename);
  1067.                     $statement->bindValue('param_file_name', $param_file_name);
  1068.                     $statement->execute();
  1069.                     // Parmetro param_name.file (di tipo file) per il file con path da sostituire senza apici
  1070.                     $param_name_file = $param_name . '.file';
  1071.                     $param_file_value = $param_file_path . $param_file_name;
  1072.                     $sql = "insert into chklst_template_parameters (chklst_id, param_name, param_value, param_type, flag_file)
  1073.                                 values (:cid, :param_name_file, :param_file_value, 'file', 'Y')
  1074.                                 ON CONFLICT (chklst_id, param_name) DO UPDATE SET
  1075.                                 param_value = :param_file_value,
  1076.                                 param_type = 'file',
  1077.                                 flag_file = 'Y'";
  1078.                     $statement = $connection->prepare($sql);                    
  1079.                     $statement->bindValue('cid', $cid);
  1080.                     $statement->bindValue('param_name_file', $param_name_file);
  1081.                     $statement->bindValue('param_file_value', $param_file_value);
  1082.                     $statement->execute();
  1083.                     // Parmetro param_name.content (di tipo file) per la lettura del contenuto del file
  1084.                     $param_name_content = $param_name . '.content';
  1085.                     $sql = "insert into chklst_template_parameters (chklst_id, param_name, param_value, param_type, flag_file)
  1086.                                 values (:cid, :param_name_content, :param_file_value, 'file', 'Y')
  1087.                                 ON CONFLICT (chklst_id, param_name) DO UPDATE SET
  1088.                                 param_value = :param_file_value,
  1089.                                 param_type = 'file',
  1090.                                 flag_file = 'Y'";
  1091.                     $statement = $connection->prepare($sql);
  1092.                     $statement->bindValue('cid', $cid);
  1093.                     $statement->bindValue('param_name_content', $param_name_content);
  1094.                     $statement->bindValue('param_file_value', $param_file_value);
  1095.                     $statement->execute();
  1096.                 }
  1097.             }
  1098.         }
  1099.         $em->flush();
  1100.         /****************  FINE GESTIONE UPLAOD FILES  *********************/
  1101.         if ($request->request->get('isApi')) {
  1102.             return $this->json(["wflId" => $cid]);
  1103.         }
  1104.         return $this->redirect($this->generateUrl('checklist_flowchart', array('idTemplate' => $cid, 'csrftoken' => $tokenManager->getToken('checklist_flowchart')->getValue())));
  1105.     }
  1106.     public function saveFlowJsonAction(Request $request, LoggerInterface $logger, ParameterBagInterface $params, TaskRepository $taskRepository)
  1107.     {
  1108.         session_write_close();
  1109.         
  1110.         $csrfToken = $request->request->get('csrftoken');
  1111.         
  1112.         if (!$this->isCsrfTokenValid('saveFlowchartJson', $csrfToken)) {
  1113.             throw new \Exception('Csrf token not valid');
  1114.         }
  1115.         
  1116.         $em = $this->getDoctrine()->getManager();
  1117.         $em->getConnection()->beginTransaction(); // suspend auto-commit
  1118.         $res_json = new JsonResponse;
  1119.         $task_validate = false;
  1120.         $json_flow = $request->request->get('json_flow');
  1121.         $chklst_id = $request->request->get('chklst_id');
  1122.         $flow_image = $request->files->get('flow_image');
  1123.         $relativeFilename = "";
  1124.         if ($flow_image != null) {
  1125.             $relativeFilename = "img/flowchart/preview/preview_workflow_id_$chklst_id.png";
  1126.             $targetFilename = "preview_workflow_id_$chklst_id.png";
  1127.             $targetDirectory = $params->get('projectDir') . "/public/img/flowchart/preview/";
  1128.             $flow_image->move($targetDirectory, $targetFilename);
  1129.         }
  1130.         //$json_flow = json_encode($datijson);
  1131.         try {
  1132.             $user = $this->getUser();
  1133.             $userId = $user->getId();
  1134.             $sql = "update chklst_template set data_modifica = now(), modificato_da = :userId where id = :chklst_id";
  1135.             $stmt = $em->getConnection()->prepare($sql);
  1136.             $stmt->bindValue('chklst_id', $chklst_id);
  1137.             $stmt->bindValue('userId', $userId);
  1138.             $stmt->execute();
  1139.             $datijson = json_decode($json_flow, true);
  1140.             //step 1 validità
  1141.             $graphLinksModel = new GraphLinksModel($datijson, $logger, $em, $params, $taskRepository);
  1142.             //$tasksWithNoLinks = $graphLinksModel->findTasksWithNoLinks();
  1143.             $startPoints = $graphLinksModel->findMultipleStart();
  1144.             $taskOrder = $graphLinksModel->findPaths();
  1145.             $currentModel = $graphLinksModel->getModel();
  1146.             $taskValidate = "Y";
  1147.             $canRunAlone = true;
  1148.             if (count($currentModel) == 3) {
  1149.                 $taskValidate = "N";
  1150.             }
  1151.             if (count($currentModel) == 4) {
  1152.                 $anagId = str_replace("]", "", explode("_", array_keys($currentModel)[3])[2]);
  1153.                 $sql = "select can_run_alone from task_anagrafica where id = :anagId";
  1154.                 $stmt = $em->getConnection()->prepare($sql);
  1155.                 $stmt->bindValue('anagId', $anagId);
  1156.                 $stmt->execute();
  1157.                 $returnCanRunAlone = $stmt->fetchAll()[0]["can_run_alone"];
  1158.                 if ($returnCanRunAlone == 0) {
  1159.                     $canRunAlone = false;
  1160.                 }
  1161.             }
  1162.             if (!$canRunAlone || $startPoints > 1) {
  1163.                 $taskValidate = "N";
  1164.             }
  1165.             $sql = "update chklst_jflow  set json_flow = :json_flow, flow_image = :relativeFilename ,
  1166.                         task_jorder = :task_jorder, task_validate = :task_validate
  1167.                         where chklst_template = :chklst_id";
  1168.             $stmt = $em->getConnection()->prepare($sql);
  1169.             $stmt->bindValue('json_flow', $json_flow);
  1170.             $stmt->bindValue('relativeFilename', $relativeFilename);
  1171.             $stmt->bindValue('task_jorder', $taskOrder);
  1172.             $stmt->bindValue('task_validate', $taskValidate);
  1173.             $stmt->bindValue('chklst_id', $chklst_id);
  1174.             $stmt->execute();
  1175.             //se ci sono piu nodi che non hanno ingressi dal top, allora Ã¨ invalido, perché ci sono più partenze
  1176.             $em->getConnection()->commit();
  1177.             //return 0;
  1178.             $res_json->setData(array('task_validate' => $taskValidate));
  1179.             return $res_json;
  1180.         } catch (\Exception $e) {
  1181.             $em->getConnection()->rollBack();            
  1182.             throw $e;
  1183.         }
  1184.     }
  1185.     public function loadFlowJsonAction(Request $request, LoggerInterface $logger, ParameterBagInterface $params)
  1186.     {
  1187.         session_write_close();
  1188.         $csrfToken = $request->request->get('csrftoken');
  1189.         if (!$this->isCsrfTokenValid('load_designer', $csrfToken)) {
  1190.             throw new \Exception('Csrf token not valid');
  1191.         }
  1192.         //$logger = $this->getLogger();
  1193.         $db_driver = $params->get('db_driver');
  1194.         $res_json = new JsonResponse;
  1195.         $em = $this->getDoctrine()->getManager();
  1196.         $chklst_id = $request->request->get('chklst_id');
  1197.         #dall id della checklist vedo se sulla chklst_jflow c e il flow altrimenti lo calcolo 
  1198.         #recuperando i task, il loro ordine e compongo il json 
  1199.         $sql = "select json_flow,task_validate from chklst_jflow where chklst_template = :cid ";
  1200.         $stmt = $em->getConnection()->prepare($sql);
  1201.         $stmt->bindValue('cid', $chklst_id);
  1202.         $stmt->execute();
  1203.         $jsons = $stmt->fetchAll();
  1204.         foreach ($jsons as $json) {
  1205.             $json_flow[] = $json['json_flow'];
  1206.             $task_validate[] = $json['task_validate'];
  1207.         }
  1208.         //per verificare i nodi terminali
  1209.         $IdsFromArray = array();
  1210.         $hiddenTasks = array();
  1211.         if (strpos(json_encode($task_validate), "Y")) {
  1212.             $logger->debug("task_validate" . json_encode($task_validate));
  1213.             $task_validate_v = true;
  1214.         } else {
  1215.             $logger->debug("task_validate FALSE");
  1216.             $task_validate_v = false;
  1217.         }
  1218.         $res_json->setData(array('json_flow' => $json_flow[0], 'task_validate' => $task_validate_v));
  1219.         return $res_json;
  1220.     }
  1221.     /*** FINE AGGIUNTA METODI DESIGNER **/
  1222.     public function dashboardAction(Request $request, LoggerInterface $logger, ParameterBagInterface $params)
  1223.     {
  1224.         $em = $this->getDoctrine()->getManager();
  1225.         $tipologia = "tutti";
  1226.         if (isset($_POST["periodo"])) {
  1227.             $periodo = $_POST["periodo"];
  1228.         } else {
  1229.             $periodo = '7 day';
  1230.         }
  1231.         $dateSchedule = date_create_from_format('d/m/Y H:i', '31/12/2999 23:59');
  1232.         $logger->debug("[dashboardAction] Data Schedulata " . json_encode($dateSchedule));
  1233.         $logger->debug('[dashboardAction] Periodo: ' . $periodo);
  1234.         $chktmpl2 = $em->getRepository('App\Entity\ChklstTemplate')
  1235.             ->findByHidden(0);
  1236.         $now = new \DateTime();
  1237.         $now->modify("+1 day");
  1238.         $filtroPeriodo = new \DateTime();
  1239.         $filtroPeriodo = $filtroPeriodo->modify('-' . $periodo);
  1240.         //$logger->debug('filtroPeriodo: '. $filtroPeriodo);
  1241.         $logger->debug('[dashboardAction] Filtro Periodo: ' . $periodo);
  1242.         $logger->debug('*************** QUERY IdPerido ********************');
  1243.         $idPeriodo = $em->createQueryBuilder()
  1244.             ->select('IDENTITY(c.fromTemplate) AS fromTemplate')
  1245.             ->from('App:Chklst', 'c')
  1246.             ->where('c.runStart between :filtroPeriodo and :now')
  1247.             ->setParameter('filtroPeriodo', $filtroPeriodo->format('Y-m-d'))
  1248.             ->setParameter('now', $now->format('Y-m-d'))
  1249.             ->distinct()
  1250.             ->getQuery()
  1251.             ->getResult();
  1252.         $logger->debug('*************** FINE QUERY IdPerido ********************');
  1253.         //$logger->debug('idPeriodo: '. $idPeriodo);
  1254.         $user = $this->getUser();
  1255.         $userId = $user->getId();
  1256.         $UserRole = $user->getUserRole();
  1257.         $logger->debug("[dashboardAction] UserRole " . $UserRole);
  1258.         $logger->debug('Tiro Fuori i checklist id filtrati per utente');
  1259.         $sql = "SELECT DISTINCT ct.id
  1260.                                     FROM chklst_template ct";
  1261.         //if ($UserRole <> "ROLE_SUPER_ADMIN") {
  1262.             $sql .= " join chklst_template_role cr on ct.id = cr.id_template
  1263.                                          join (SELECT ur.id_roles
  1264.                                                      FROM user_acm u
  1265.                                                                 join user_profile_roles ur on u.id = ur.id_user
  1266.                                                      WHERE u.id = $userId and ur.id_profile in (1,2)) ur on cr.id_roles = ur.id_roles
  1267.                                                      ";
  1268.         //}
  1269.         $sql .=  " join chklsttmpl2task cw on ct.id = cw.chklsttmpl_id";
  1270.         $logger->debug('Query Cehcklist id ' . $sql);
  1271.         $sql = $em->getConnection()->prepare($sql);
  1272.         $sql->execute();
  1273.         $cklstId = $sql->fetchAll();
  1274.         $logger->debug('*************** QUERY chktmpl ********************');
  1275.         $chktmpl = $em
  1276.             ->getRepository('App:ChklstTemplate')
  1277.             ->createQueryBuilder('t')
  1278.             ->where('t.id in (:idPeriodo)')
  1279.             ->andWhere('t.id in (:cklstId)')
  1280.             ->andWhere('t.hidden = 0')
  1281.             ->setParameter('idPeriodo', $idPeriodo)
  1282.             ->setParameter('cklstId', $cklstId)
  1283.             ->getQuery()
  1284.             ->getResult();
  1285.         $logger->debug("[dashboardAction] Prima Query " . $UserRole);
  1286.         $sql = " select giorno, sum(cnt) cnt, sum(success) success, sum(error) error, sum(running) running, sum(stopped) stopped, sum(not_run) not_run 
  1287.                 from (
  1288.                     select * from (select d.gg giorno, count(ct.name) cnt,
  1289.                             sum(case when lower(run_result)='success' then 1 else 0 end) success,
  1290.                             sum(case when lower(run_result)='failed' then 1 else 0 end) error,
  1291.                             sum(case when c.run_start is not null and lower(run_result) is null then 1 else 0 end) running,
  1292.                             sum(case when lower(run_result)='stopped' then 1 else 0 end) stopped,
  1293.                             sum(case when c.name is null then 1 else 0 end) not_run
  1294.                             FROM (select to_char(i::date, 'yyyy-mm-dd') gg from generate_series(current_date - 90, current_date, '1 day'::interval) i)  d
  1295.                             left join chklst c
  1296.                             on( d.gg = to_char(c.run_start, 'yyyy-mm-dd'))
  1297.                             left join (select max(id) id, name, to_char(run_start, 'yyyy-mm-dd') 
  1298.                                         FROM chklst 
  1299.                                         where run_start < current_date
  1300.                                         group by name, to_char(run_start, 'yyyy-mm-dd')) c_max
  1301.                                         on (c.id=c_max.id)     
  1302.                             right join chklst_template ct on c.from_template_id = ct.id and ct.hidden=0 
  1303.                             join chklst_template_role cr on ct.id = cr.id_template
  1304.                             join (SELECT ur.id_roles
  1305.                                   FROM user_acm u
  1306.                                   join user_profile_roles ur on u.id = ur.id_user
  1307.                                  WHERE u.id = $userId and ur.id_profile in (1,2)) ur on (cr.id_roles = ur.id_roles)
  1308.                              where d.gg between to_char(current_date - '$periodo'::interval , 'yyyy-mm-dd') and to_char(current_date, 'yyyy-mm-dd')
  1309.                             and (c.run_end < to_date('2999-12-31', 'yyyy-mm-dd') or c.run_end is null)
  1310.                             group by d.gg
  1311.                             order by giorno desc) a ) b
  1312.                             group by giorno
  1313.                             order by giorno"; //: "select giorno, sum(cnt) cnt, sum(success) success, sum(error) error, sum(running) running, sum(stopped) stopped, sum(not_run) not_run from( " . $webAppRunPerDay . "" . (($tipologia == "webapp") ? ") b group by giorno order by giorno asc" : "") . ""
  1314.                             
  1315.         $logger->debug("[dashboardAction] Esecuzione Query POSTGRESQL " . $sql);
  1316.         $stmt = $em->getConnection()->prepare($sql);
  1317.         $stmt->execute();
  1318.         $chklst_run = $stmt->fetchAll();
  1319.         $sql = "select sum(cnt) tot, sum(success) ok , sum(error) ko,  sum(stopped) stop
  1320.                             from ( select * from (select to_char(c.run_start, 'yyyy-mm-dd') giorno, count(ct.name) cnt,
  1321.                                     sum(case when lower(run_result)='success' then 1 else 0 end) success,
  1322.                                     sum(case when lower(run_result)='failed' then 1 else 0 end) error,
  1323.                                     sum(case when lower(run_result) is null then 1 else 0 end) running,
  1324.                                     sum(case when lower(run_result)='stopped' then 1 else 0 end) stopped,
  1325.                                     sum(case when c.name is null then 1 else 0 end) not_run
  1326.                                     FROM chklst c left join (select max(id) id, name, to_char(run_start, 'yyyy-mm-dd')
  1327.                                                         FROM chklst
  1328.                                       where run_start < current_date
  1329.                                                         group by name, to_char(run_start, 'yyyy-mm-dd')) c_max
  1330.                                     on c.id=c_max.id 
  1331.                                     right join chklst_template ct on c.from_template_id = ct.id and ct.hidden=0 
  1332.                                     join chklst_template_role cr on ct.id = cr.id_template and ct.hidden=0
  1333.                                     join (SELECT ur.id_roles
  1334.                                                 FROM user_acm u
  1335.                                                 join user_profile_roles ur on u.id = ur.id_user
  1336.                                                 WHERE u.id = $userId and ur.id_profile in (1,2)) ur on cr.id_roles = ur.id_roles
  1337.                                     where to_char(c.run_start, 'yyyy-mm-dd') between to_char(current_date- '$periodo'::interval , 'yyyy-mm-dd') 
  1338.                                                                              and to_char(current_date, 'yyyy-mm-dd')
  1339.                                                 and c.run_end < to_date('2999-12-31', 'yyyy-mm-dd')
  1340.                                     group by to_char(c.run_start, 'yyyy-mm-dd')
  1341.                                     order by giorno desc) a) b"// : "select sum(cnt) tot, sum(success) ok , sum(error) ko,  sum(stopped) stop from ( " . $webAppRunPerDay . "" . (($tipologia == "webapp") ? ") b " : "") . ""
  1342.                                     ;
  1343.         $logger->debug("[dashboardAction] Esecuzione Query POSTGRESQL " . $sql);
  1344.         $stmt = $em->getConnection()->prepare($sql);
  1345.         $stmt->execute();
  1346.         $chklst_run_t = $stmt->fetchAll()[0];
  1347.         //        $chklst_run_tot[] = array('label' =>'Totali', 'value' => $chklst_run_t['tot']);
  1348.         $chklst_run_tot[] = array('label' => 'Completed', 'value' => $chklst_run_t['ok']);
  1349.         $chklst_run_tot[] = array('label' => 'KO', 'value' => $chklst_run_t['ko']);
  1350.         $chklst_run_tot[] = array('label' => 'Stopped', 'value' => $chklst_run_t['stop']);
  1351.         // Query  POSTGRESQL
  1352.         $sql = //in_array($tipologia, ["tutti", "workflow"]) ? "" . ($tipologia == "tutti" ? $classificaWebApp : "") . 
  1353.         "select name, from_template_id, sum(cnt) tot, sum(success) ok , sum(error) ko,  sum(stopped) stop
  1354.             from (select * from 
  1355.                     (select ct.name, c.from_template_id , to_char(c.run_start, 'yyyy-mm-dd') giorno, count(ct.name) cnt,
  1356.                                     sum(case when lower(run_result)='success' then 1 else 0 end) success,
  1357.                                     sum(case when lower(run_result)='failed' then 1 else 0 end) error,
  1358.                                     sum(case when lower(run_result) is null then 1 else 0 end) running,
  1359.                                     sum(case when lower(run_result)='stopped' then 1 else 0 end) stopped,
  1360.                                     sum(case when c.name is null then 1 else 0 end) not_run
  1361.                     FROM chklst c
  1362.                     left join (select max(id) id, name, to_char(run_start, 'yyyy-mm-dd')
  1363.                                                 FROM chklst
  1364.                                   where run_start < current_date
  1365.                                                 group by name, to_char(run_start, 'yyyy-mm-dd')) c_max
  1366.                                     on c.id=c_max.id 
  1367.                                     right join chklst_template ct on c.from_template_id = ct.id  and ct.hidden=0 
  1368.                                     join chklst_template_role cr on ct.id = cr.id_template 
  1369.                                     join (SELECT ur.id_roles
  1370.                                           FROM user_acm u
  1371.                                           join user_profile_roles ur on u.id = ur.id_user
  1372.                                          WHERE u.id = $userId and ur.id_profile in (1,2)) ur on cr.id_roles = ur.id_roles
  1373.                                      where to_char(c.run_start, 'yyyy-mm-dd') between to_char(current_date - '$periodo'::interval , 'yyyy-mm-dd') 
  1374.                                                             and to_char(current_date, 'yyyy-mm-dd')
  1375.                                                 and c.run_end < to_date('2999-12-31', 'yyyy-mm-dd')
  1376.                                     group by ct.name, from_template_id, to_char(c.run_start, 'yyyy-mm-dd')
  1377.                                     order by giorno desc) a) b
  1378.                   group by name, from_template_id
  1379.                                     order by tot desc"// : $classificaWebApp
  1380.                                     ;
  1381.         $logger->debug("[dashboardAction] Esecuzione Query POSTGRESQL " . $sql);
  1382.         $stmt = $em->getConnection()->prepare($sql);
  1383.         $stmt->execute();
  1384.         $chklst_val = $stmt->fetchAll();
  1385.         // Query POSTGRESQL
  1386.         $sql = //in_array($tipologia, ["tutti", "workflow"]) ? "" . ($tipologia == "tutti" ? $classificaWebApp : "") .
  1387.          "select name, from_template_id, sum(cnt) tot, sum(success) ok , sum(error) ko,  sum(stopped) stop
  1388.                     from (select * from (select ct.name, c.from_template_id , to_char(c.run_start, 'yyyy-mm-dd') giorno, count(ct.name) cnt,
  1389.                                     sum(case when lower(run_result)='success' then 1 else 0 end) success,
  1390.                                     sum(case when lower(run_result)='failed' then 1 else 0 end) error,
  1391.                                     sum(case when lower(run_result) is null then 1 else 0 end) running,
  1392.                                     sum(case when lower(run_result)='stopped' then 1 else 0 end) stopped,
  1393.                                     sum(case when c.name is null then 1 else 0 end) not_run
  1394.                                     FROM chklst c
  1395.                                              left join (select max(id) id, name, to_char(run_start, 'yyyy-mm-dd')
  1396.                                                                     FROM chklst
  1397.                                                                     where run_start < sysdate()
  1398.                                                                     group by name, to_char(run_start, 'yyyy-mm-dd')) c_max
  1399.                                     on c.id=c_max.id
  1400.                                     right join chklst_template ct on c.from_template_id = ct.id  and ct.hidden=0 
  1401.                                     join chklst_template_role cr on ct.id = cr.id_template 
  1402.                                        join (SELECT ur.id_roles
  1403.                                           FROM user_acm u
  1404.                                           join user_profile_roles ur on u.id = ur.id_user
  1405.                                          WHERE u.id = $userId and ur.id_profile in (1,2)) ur on cr.id_roles = ur.id_roles
  1406.                                      where to_char(c.run_start, 'yyyy-mm-dd') between to_char(current_date - '$periodo'::interval , 'yyyy-mm-dd') 
  1407.                                                                              and to_char(current_date, 'yyyy-mm-dd')
  1408.                                                 and c.run_end < to_date('2999-12-31', 'yyyy-mm-dd')
  1409.                                     group by ct.name, from_template_id,to_char(c.run_start, 'yyyy-mm-dd')
  1410.                                     order by giorno desc) a) b
  1411.                                     group by name, from_template_id
  1412.                                     order by ok desc" // : $classificaWebApp
  1413.                                     ;
  1414.         $logger->debug("[dashboardAction] Esecuzione Query POSTGRESQL " . $sql);
  1415.         $stmt = $em->getConnection()->prepare($sql);
  1416.         $stmt->execute();
  1417.         $chklst_ok = $stmt->fetchAll();
  1418.         $sql = //in_array($tipologia, ["tutti", "workflow"]) ? "" . ($tipologia == "tutti" ? $classificaWebApp : "") . 
  1419.         "select name, from_template_id, sum(cnt) tot, sum(success) ok , sum(error) ko,  sum(stopped) stop
  1420.                     from (select * from (select ct.name, c.from_template_id , to_char(c.run_start, 'yyyy-mm-dd') giorno, count(ct.name) cnt,
  1421.                                     sum(case when lower(run_result)='success' then 1 else 0 end) success,
  1422.                                     sum(case when lower(run_result)='failed' then 1 else 0 end) error,
  1423.                                     sum(case when lower(run_result) is null then 1 else 0 end) running,
  1424.                                     sum(case when lower(run_result)='stopped' then 1 else 0 end) stopped,
  1425.                                     sum(case when c.name is null then 1 else 0 end) not_run
  1426.                                     FROM chklst c
  1427.                                              left join (select max(id) id, name, to_char(run_start, 'yyyy-mm-dd')
  1428.                                                                     FROM chklst
  1429.                                                                     where run_start < sysdate()
  1430.                                                                     group by name, to_char(run_start, 'yyyy-mm-dd')) c_max
  1431.                                     on c.id=c_max.id
  1432.                                     right join chklst_template ct on c.from_template_id = ct.id  and ct.hidden=0 
  1433.                                     join chklst_template_role cr on ct.id = cr.id_template 
  1434.                                         join (SELECT ur.id_roles
  1435.                                           FROM user_acm u
  1436.                                            join user_profile_roles ur on u.id = ur.id_user
  1437.                                            WHERE u.id = $userId and ur.id_profile in (1,2)) ur on cr.id_roles = ur.id_roles
  1438.                                     where to_char(c.run_start, 'yyyy-mm-dd') between to_char(current_date - '$periodo'::interval , 'yyyy-mm-dd') 
  1439.                                                                              and to_char(current_date, 'yyyy-mm-dd')
  1440.                                                 and c.run_end < to_date('2999-12-31', 'yyyy-mm-dd')
  1441.                                     group by ct.name, from_template_id,to_char(c.run_start, 'yyyy-mm-dd')
  1442.                                     order by giorno desc) a) b
  1443.                                     group by name, from_template_id
  1444.                                     order by ko desc" //: $classificaWebApp
  1445.                                     ;
  1446.         $logger->debug("[dashboardAction] Esecuzione Query POSTGRESQL " . $sql);
  1447.         $stmt = $em->getConnection()->prepare($sql);
  1448.         $stmt->execute();
  1449.         $chklst_ko = $stmt->fetchAll();
  1450.         $sql = //in_array($tipologia, ["tutti", "workflow"]) ? "" . ($tipologia == "tutti" ? $classificaWebApp : "") . 
  1451.         "select name, from_template_id, sum(cnt) tot, sum(success) ok , sum(error) ko,  sum(stopped) stop
  1452.                     from (select * from (select ct.name, c.from_template_id , to_char(c.run_start, 'yyyy-mm-dd') giorno, count(ct.name) cnt,
  1453.                                     sum(case when lower(run_result)='success' then 1 else 0 end) success,
  1454.                                     sum(case when lower(run_result)='failed' then 1 else 0 end) error,
  1455.                                     sum(case when lower(run_result) is null then 1 else 0 end) running,
  1456.                                     sum(case when lower(run_result)='stopped' then 1 else 0 end) stopped,
  1457.                                     sum(case when c.name is null then 1 else 0 end) not_run
  1458.                                     FROM chklst c
  1459.                                              left join (select max(id) id, name, to_char(run_start, 'yyyy-mm-dd')
  1460.                                                                     FROM chklst
  1461.                                                                     where run_start < sysdate()
  1462.                                                                     group by name, to_char(run_start, 'yyyy-mm-dd')) c_max
  1463.                                     on c.id=c_max.id
  1464.                                     right join chklst_template ct on c.from_template_id = ct.id  and ct.hidden=0
  1465.                                     join chklst_template_role cr on ct.id = cr.id_template
  1466.                                     join (SELECT ur.id_roles
  1467.                                           FROM user_acm u
  1468.                                           join user_profile_roles ur on u.id = ur.id_user
  1469.                                          WHERE u.id = $userId and ur.id_profile in (1,2)) ur on cr.id_roles = ur.id_roles                                         
  1470.                                     where to_char(c.run_start, 'yyyy-mm-dd') between to_char(current_date - '$periodo'::interval , 'yyyy-mm-dd') 
  1471.                                                                              and to_char(current_date, 'yyyy-mm-dd')
  1472.                                                 and c.run_end < to_date('2999-12-31', 'yyyy-mm-dd')
  1473.                                     group by ct.name, from_template_id,to_char(c.run_start, 'yyyy-mm-dd')
  1474.                                     order by giorno desc) a) b
  1475.                                     group by name, from_template_id
  1476.                                     order by stop desc" //: $classificaWebApp
  1477.                                     ;
  1478.         $logger->debug("[dashboardAction] Esecuzione Query POSTGRESQL " . $sql);
  1479.         $stmt = $em->getConnection()->prepare($sql);
  1480.         $stmt->execute();
  1481.         $chklst_int = $stmt->fetchAll();
  1482.         $checklist = [];
  1483.         $checklistArr = [];
  1484.         foreach ($chktmpl as $c) {
  1485.             if ($c->getId() < $params->get('webAppFromIndex') and (in_array($tipologia, ["tutti", "workflow"]))) {
  1486.                 $logger->debug('*************** QUERY checkrun ********************');
  1487.                 $checkrun = $em->createQueryBuilder()
  1488.                     ->select('c')
  1489.                     ->from('App:Chklst', 'c')
  1490.                     ->where('c.fromTemplate = :template')
  1491.                     ->andWhere('c.runEnd is null')
  1492.                     ->setParameter('template', $c)
  1493.                     ->getQuery()
  1494.                     ->getResult();
  1495.                 $logger->debug('*************** QUERY history ********************');
  1496.                 $history = $em->createQueryBuilder()
  1497.                     ->select('c')
  1498.                     ->from('App:Chklst', 'c')
  1499.                     ->where('c.fromTemplate = :template')
  1500.                     ->andWhere('c.runStart < :today')
  1501.                     ->andWhere('c.runEnd < :dateSchedule')
  1502.                     ->setParameter('today', new \DateTime())
  1503.                     ->setParameter('template', $c)
  1504.                     ->setParameter('dateSchedule', $dateSchedule)
  1505.                     ->orderBy('c.id', 'DESC')
  1506.                     ->setMaxResults('1')
  1507.                     ->getQuery()
  1508.                     ->getResult();
  1509.                 $logger->debug('*************** QUERY historyArray ********************');
  1510.                 $historyArray = $em->createQueryBuilder()
  1511.                     ->select('c')
  1512.                     ->from('App:Chklst', 'c')
  1513.                     ->where('c.fromTemplate = :template')
  1514.                     ->andWhere('c.runStart < :today')
  1515.                     ->andWhere('c.runEnd < :dateSchedule')
  1516.                     ->setParameter('today', new \DateTime())
  1517.                     ->setParameter('template', $c)
  1518.                     ->setParameter('dateSchedule', $dateSchedule)
  1519.                     ->orderBy('c.id', 'DESC')
  1520.                     ->setMaxResults('1')
  1521.                     ->getQuery()
  1522.                     ->getArrayResult();
  1523.                 $logger->debug('*************** QUERY ctask_history ********************');
  1524.                 $ctask_history = [];
  1525.                 foreach ($history as $h) {
  1526.                     $ctask_history = $em->createQueryBuilder()
  1527.                         ->select('c')
  1528.                         ->from('App:ChklstTask', 'c')
  1529.                         ->where('c.chklst_id = :chklst_id')
  1530.                         ->setParameter('chklst_id', $h->getID())
  1531.                         ->orderBy('c.taskOrder', 'DESC')
  1532.                         // ->setMaxResults('1')
  1533.                         ->getQuery()
  1534.                         ->getResult();
  1535.                 }
  1536.                 $status = 'idle';
  1537.                 if (!empty($checkrun)) {
  1538.                     $logger->debug("[dashboardAction] Valore Checkrun " . json_encode($checkrun));
  1539.                     if ($checkrun[0]->getRunStart() === null) {
  1540.                         $status = 'queued';
  1541.                     } else {
  1542.                         $status = 'running';
  1543.                     }
  1544.                     $logger->debug("[dashboardAction] Status " . $status);
  1545.                     $sql = "select count(*) tot, 
  1546.                                         sum(case when nullif(chk.run_result,'Queued') = 'Success' then 1 else 0 end ) as ok, 
  1547.                                         sum(case when nullif(chk.run_result,'Queued') = 'Failed' then 1 else 0 end ) as ko, 
  1548.                                         sum(case when chk.run_start is not null and chk.run_end is null then 1 else 0 end  ) as  running, 
  1549.                                         sum(case when nullif(chk.run_result,'Queued') = 'Queued' and chk.run_start is null then 1 else 0 end) as queue 
  1550.                                         from chklst_task chkt inner join chklst chk on (chkt.chklst_id = chk.id)";
  1551.                     if ($UserRole <> "ROLE_SUPER_ADMIN") {
  1552.                         $sql .= "inner join    chklst_template ct on (chk.from_template_id = ct.id)
  1553.                                             join chklst_template_role cr on ct.id = cr.id_template
  1554.                                             join (SELECT ur.id_roles
  1555.                                                    FROM user_acm u
  1556.                                                       join user_profile_roles ur on u.id = ur.id_user
  1557.                                                  WHERE u.id = $userId and ur.id_profile in (1,2)) ur on cr.id_roles = ur.id_roles";
  1558.                     }
  1559.                     $sql .= " where chklst_id = " . $checkrun[0]->getId();
  1560.                     $logger->debug("[dashboardAction] Esecuzione Query POSTGRESQL " . $sql);
  1561.                 } else {
  1562.                     $sql = "select count(t.id) tot, 0 ok, 0 ko, 0 running, count(t.id) queue
  1563.                                 from task t left join chklsttmpl2task ct on ct.task_id = t.id
  1564.                                             left join chklst_template c on c.id = ct.chklsttmpl_id
  1565.                                 where t.hidden='0' and c.id = " . $c->getId();
  1566.                     $logger->debug("[dashboardAction] Valore Checkrun (Else)");
  1567.                 }
  1568.                 $stmt = $em->getConnection()->prepare($sql);
  1569.                 $stmt->execute();
  1570.                 $task_status = $stmt->fetchAll();
  1571.                 if ($status == "running") {
  1572.                     $sql_last_task = "select id, name, description, run_start from chklst_task "
  1573.                         . "where chklst_id = " . $checkrun[0]->getId() . " "
  1574.                         . "and   run_start is not null "
  1575.                         . "and   run_end is null ";
  1576.                     $logger->debug("[dashboardAction] status operation : " . $status . ' id checklist ' . $checkrun[0]->getId()); 
  1577.                 } else {
  1578.                     $sql_last_task = "select 0 id, 'n/a' as name, 'nessuna esecuzione in corso' description, null run_start";
  1579.                 }
  1580.                 $stmt = $em->getConnection()->prepare($sql_last_task);
  1581.                 $stmt->execute();
  1582.                 $last_task = $stmt->fetchAll();
  1583.                 $logger->debug("[dashboardAction] Ultimo Task " . json_encode($last_task));
  1584.                 if (count($last_task) == 0) {
  1585.                     $last_task = [""];
  1586.                     $last_server = [];
  1587.                 } else {
  1588.                     $sql_last_server = "select id, hostname, ip_address, run_result from task_server where task_id = " . $last_task[0]['id'];
  1589.                     $stmt = $em->getConnection()->prepare($sql_last_server);
  1590.                     $stmt->execute();
  1591.                     $last_server = $stmt->fetchAll();
  1592.                 }
  1593.                 $parameters = array();
  1594.                 foreach ($history as $h) {
  1595.                     $sql_parameters = "select * from v_chklst_template_parameters where chklst_run_id = " . $h->getId();
  1596.                     $stmt = $em->getConnection()->prepare($sql_parameters);
  1597.                     $stmt->execute();
  1598.                     $chklst_parameters = $stmt->fetchAll();
  1599.                     $parameters[] = array($h->getId() => array("params" => $chklst_parameters));
  1600.                 }
  1601.                 $sql_parameters_all = "select * from chklst_template_parameters where chklst_id = " . $c->getId();
  1602.                 $stmt = $em->getConnection()->prepare($sql_parameters_all);
  1603.                 $stmt->execute();
  1604.                 $parameters_all = $stmt->fetchAll();
  1605.                 if (count($parameters_all) == 0) {
  1606.                     $parameters_all = [];
  1607.                 }
  1608.                 $chklst = array("template" => $c, "status" => $status, "history" => $history, "ctask_history" => $ctask_history, "task_status" => $task_status[0], "last_task" => $last_task[0], "last_server" => $last_server, "parameters" => $parameters, "parameters_all" => $parameters_all);
  1609.                 $logger->debug('checklist chklst:: ' . json_encode($chklst));
  1610.                 $checklist[$c->getName()] = $chklst;
  1611.                 //history array
  1612.                 $chklstArr = array("template" => $c, "status" => $status, "history" => $historyArray, "ctask_history" => $ctask_history, "task_status" => $task_status[0], "last_task" => $last_task[0], "last_server" => $last_server, "parameters" => $parameters, "parameters_all" => $parameters_all);
  1613.                 $logger->debug('checklist json:: ' . json_encode($chklstArr));
  1614.                 if (empty($chklstArr)) {
  1615.                     $logger->debug('Array chklstArr vuoto');
  1616.                     $checklistArr = null;
  1617.                 } else {
  1618.                     $logger->debug('Array chklstArr valorizzato');
  1619.                     $checklistArr[$c->getName()] = $chklstArr;
  1620.                 }
  1621.             }
  1622.         }
  1623.         $sql_webex_rooms = "select id, title from webex_rooms ";
  1624.         $stmt = $em->getConnection()->prepare($sql_webex_rooms);
  1625.         $stmt->execute();
  1626.         $webex_rooms = $stmt->fetchAll();
  1627.         $colors = ['plum', 'cyan', 'aqua', 'red', 'blue', 'purple', 'green', 'pink', 'orange', 'brown'];
  1628.         $logger->debug("dati graph: " . json_encode($chklst_run));
  1629.         //    $user = json_encode($this->getUser());
  1630.         $user = $this->getUser();
  1631.         $chklst_run_json = json_encode($chklst_run, JSON_NUMERIC_CHECK);
  1632.         $logger->debug("dati graph json: " . $chklst_run_json);
  1633.         $chklst_run_tot_json = json_encode($chklst_run_tot, JSON_NUMERIC_CHECK);
  1634.         $logger->debug("dati donut json: " . $chklst_run_tot_json);
  1635.         //$logger->debug('checklist json:: '. json_encode($chklstArr));
  1636.         $chklst_val_json = json_encode($chklst_val, JSON_NUMERIC_CHECK);
  1637.         $logger->debug("dati val checklist: " . $chklst_val_json);
  1638.         $logger->debug("dati val checklist: " . json_encode($checklist));
  1639.         //ordino la checklist in base all'ultimo run start in modo decrescente
  1640.         usort($checklist, function ($a, $b) {
  1641.             $aDateTime = "";
  1642.             if (!empty($a["history"][0]) && !empty($b["history"][0])) {
  1643.                 if (gettype($a["history"][0]->getRunStart()) == "string") {
  1644.                     $aDateTime = $a["history"][0]->getRunStart();
  1645.                 } else {
  1646.                     $aDateTime = $a["history"][0]->getRunStart()->format('Y-m-d H:i:s');
  1647.                 }
  1648.                 $bDateTime = "";
  1649.                 if (gettype($b["history"][0]->getRunStart()) == "string") {
  1650.                     $bDateTime = $b["history"][0]->getRunStart();
  1651.                 } else {
  1652.                     $bDateTime = $b["history"][0]->getRunStart()->format('Y-m-d H:i:s');
  1653.                 }
  1654.                 return strtotime($bDateTime) - strtotime($aDateTime);
  1655.             } else {
  1656.                 $aDateTime = date_create_from_format('d/m/Y H:i', '31/12/2999 23:59');
  1657.                 $bDateTime = date_create_from_format('d/m/Y H:i', '31/12/2999 23:59');
  1658.             }
  1659.         });
  1660.         $categoriesSql = "select id, nome, descrizione from chklst_template_categories order by id";
  1661.         $stmt = $em->getConnection()->prepare($categoriesSql);
  1662.         $stmt->execute();
  1663.         $categories = $stmt->fetchAll();
  1664.         if (isset($_POST["from"])) {
  1665.             //    if ($_POST["from"] == 'dashboard'){
  1666.             $res_json = new JsonResponse();
  1667.             $res_json->setData(
  1668.                 array(
  1669.                     'chklst_run' => $chklst_run,
  1670.                     'chklst_run_json' => $chklst_run_json,
  1671.                     'chklst_run_tot' => $chklst_run_tot,
  1672.                     'chklst_run_tot_json' => $chklst_run_tot_json,
  1673.                     'chklst_val' => $chklst_val,
  1674.                     'chklst_ok' => $chklst_ok,
  1675.                     'chklst_ko' => $chklst_ko,
  1676.                     'chklst_int' => $chklst_int,
  1677.                     'chklst_val_json' => $chklst_val_json,
  1678.                     'chklst' => $checklistArr,
  1679.                     'categories' => $categories,
  1680.                     'dashboardTile' => $this->get('twig')->render('dashboardTile.html.twig', array('logged_user' => $user, 'chklst_run' => $chklst_run, 'chklst' => $checklist))
  1681.                 )
  1682.             );
  1683.             return $res_json;
  1684.         } else {
  1685.             return $this->render(
  1686.                 'dashboard.html.twig',
  1687.                 array(
  1688.                     'chklst' => $checklist,
  1689.                     'chktmpl' => $chktmpl,
  1690.                     'colors' => $colors,
  1691.                     'ws_address' => $_SERVER['SERVER_NAME'],
  1692.                     'logged_user' => $user,
  1693.                     'webex_rooms' => $webex_rooms,
  1694.                     'chklst_run' => $chklst_run,
  1695.                     'chklst_run_json' => $chklst_run_json,
  1696.                     'chklst_run_tot' => $chklst_run_tot,
  1697.                     'chklst_run_tot_json' => $chklst_run_tot_json,
  1698.                     'chklst_val' => $chklst_val,
  1699.                     'chklst_ok' => $chklst_ok,
  1700.                     'chklst_ko' => $chklst_ko,
  1701.                     'chklst_int' => $chklst_int,
  1702.                     'categories' => $categories,
  1703.                 )
  1704.             );
  1705.         }
  1706.     }
  1707.     public function showChecklistAction(Request $request, LoggerInterface $logger, ParameterBagInterface $params)
  1708.     {
  1709.         $csrfToken = $request->request->get('csrftoken');
  1710.         if (!$this->isCsrfTokenValid('checklist_detail', $csrfToken)) {
  1711.             throw new \Exception('Csrf token not valid');
  1712.         }
  1713.         session_write_close();
  1714.         $em = $this->getDoctrine()->getManager();
  1715.         $chklst_id = $request->request->get('chklst_id');
  1716.         $which = $request->request->get('which');
  1717.         $requestType = $request->request->get('requestType');
  1718.         $id_template = $request->request->get('id_template');
  1719.     
  1720.         $task = [];
  1721.         //if ($id_template < $params->get('webAppFromIndex')) {
  1722.             
  1723.             $chklst = $em->find('App:Chklst', $chklst_id);
  1724.             $sql = 'SELECT t.id , t.name "name", tanag.id "key_anag", tanag.path_image_task "path_image_task", tanag.tipologia_task, tanag.descrizione_task, t.description, t.cmd_type "cmdType", 
  1725.                 t.cmd_text "cmdText", t.match_text "matchText",t.run_end as "runEnd",
  1726.                 t.run_start as "runStart", case when t.run_end is null then null else t.run_result end "runResult", t.run_result_action, t.ko_hint "koHint", (coalesce(t.run_end,now()) - t.run_start)::time as difference,
  1727.                 sum(case when coalesce(s.run_result, ' . "'queued'" . ') = ' . "'Failed'" . ' then 1 else 0 end) "failedServer",
  1728.                 ts.continue_task "Continue_Task",                                
  1729.                             t.result_api,
  1730.                             t.filename_spool_query, t.spool_on_file, ts.id task_id, t.chklst_id,                            
  1731.                             t.save_attachments_email, t.slave
  1732.                 FROM chklst_task t left join task_server s on s.task_id = t.id
  1733.                 join task ts on t.task_id=ts.id
  1734.                 join task_anagrafica tanag on ts.cmd_type = tanag.tipo_task 
  1735.                 join pre_chklsttmpl2task t2t on ts.id=t2t.task_id
  1736.                 WHERE t.chklst_id = ' . $chklst_id . ' AND t.run_start is not null ';
  1737.             switch ($which) {
  1738.                 case "OK":
  1739.                     $sql = $sql . "and coalesce(t.run_result, 'Queued') = 'Success' ";
  1740.                     break;
  1741.                 case "KO":
  1742.                     $sql = $sql . "and coalesce(t.run_result, 'Queued') = 'Failed' ";
  1743.                     break;
  1744.                 case "In coda":
  1745.                     $sql = $sql . "and t.run_start is null ";
  1746.                     break;
  1747.                 case "In esecuzione":
  1748.                     $sql = $sql . "and t.run_start is not null and t.run_end is null ";
  1749.                     break;
  1750.                 case "STOPPED":
  1751.                     $sql = $sql . "and t.run_result = 'STOPPED' ";
  1752.                     break;
  1753.                 default:
  1754.                     break;
  1755.             }
  1756.             $sql = $sql . "group by  t.id, t.name, tanag.id,  tanag.path_image_task, tanag.tipologia_task, tanag.descrizione_task, t.description, t.cmd_type, t.cmd_text, t.match_text, t.run_start, t.run_result,         
  1757.                         t.run_result_action, t.ko_hint, t.run_end - t.run_start, ts.continue_task,
  1758.                         t.result_api,
  1759.                         t.filename_spool_query, t.spool_on_file, ts.id, t.chklst_id, t2t.task_order, t.slave "
  1760.                 . " order by t.run_start desc";
  1761.             $stmt = $em->getConnection()->prepare($sql);
  1762.             $stmt->execute();
  1763.             $detail = $stmt->fetchAll();
  1764.             foreach ($detail as $d) {
  1765.                 $task[$d['id']]['detail'] = $d;
  1766.                 $sql = "SELECT s.id, s.hostname, s.ip_address, s.run_result, s.result_text "
  1767.                     . "FROM task_server s "
  1768.                     . "WHERE s.task_id = " . $d['id'] . " "
  1769.                     . "order by s.server_order";
  1770.                 $stmt = $em->getConnection()->prepare($sql);
  1771.                 $stmt->execute();
  1772.                 $server = $stmt->fetchAll();
  1773.                 $task[$d['id']]['server'] = $server;
  1774.                 //
  1775.                 if ($d["cmdType"] == "checkemail")
  1776.                     if ($d["save_attachments_email"] == "Y") {
  1777.                         $sql = "select public_file_path from chklst_email_attachments
  1778.                                 where id_run = :idRun";
  1779.                         $stmt = $em->getConnection()->prepare($sql);
  1780.                         $stmt->bindValue("idRun", $d["id"]);
  1781.                         $stmt->execute();
  1782.                         $zipEmailToDownload = $stmt->fetchAll();
  1783.                         $task[$d["id"]]['detail']["save_attachments_email_zip"] = null;
  1784.                         if (count($zipEmailToDownload) > 0)
  1785.                             $task[$d["id"]]['detail']["save_attachments_email_zip"] = $zipEmailToDownload[0]["public_file_path"];
  1786.                     }
  1787.             }
  1788.         // } else {
  1789.             
  1790.         //     $chklst = new Chklst();
  1791.         //     $sql = "
  1792.         //     select name
  1793.         //     from custom.webapp_anag 
  1794.         //     where 
  1795.         //     id = :id_template                
  1796.         //     ";
  1797.         //     $stmt = $em->getConnection()->prepare($sql);
  1798.         //     $stmt->bindValue('id_template', $id_template);
  1799.         //     $stmt->execute();
  1800.         //     $ResultQuery = $stmt->fetchAll()[0];
  1801.         //     $chklst->setName($ResultQuery["name"]);
  1802.             
  1803.         //     $sql = "
  1804.         //     select wt.id, 
  1805.         //             wt.\"name\" as name, 
  1806.         //             wt.description description, 
  1807.         //             id_chklst_run,
  1808.         //             tanag.path_image_task path_image_task,
  1809.         //              run_update \"runStart\", 
  1810.         //              run_result \"runResult\", 
  1811.         //             '' \"cmdType\", 
  1812.         //             '' \"cmdText\", 
  1813.         //             '' \"matchText\", 
  1814.         //             '' \"failedServer\", 
  1815.         //             '' \"koHint\", 
  1816.         //             'N' \"Continue_Task\", 
  1817.         //             'N' flag_send_sms, 
  1818.         //             '' result_api, 
  1819.         //             '' number_call, 
  1820.         //             wt.id \"Id_Task\",
  1821.         //             'N' flag_send_call_text_to_speech, 
  1822.         //             'N' flag_send_call, 
  1823.         //             'N' flag_send_call_uccx, 
  1824.         //             'N' flag_send_mail, 
  1825.         //             'N' flag_information,
  1826.         //             '' run_result_action, 
  1827.         //             '' difference,
  1828.         //             wt.description information
  1829.         //     from custom.webapp_log wl join custom.webapp_task wt on (wl.id_task = wt.id)
  1830.         //     join task_anagrafica tanag on wt.cmd_type = tanag.tipo_task 
  1831.         //     where wl.id_template = :id_template and id_chklst_run = :id_chklst_run                    
  1832.         //     ";
  1833.         //     $stmt = $em->getConnection()->prepare($sql);
  1834.         //     $stmt->bindValue('id_template', $id_template);
  1835.         //     $stmt->bindValue('id_chklst_run', $chklst_id);
  1836.         //     $stmt->execute();
  1837.         //     $ResultQuery = $stmt->fetchAll();
  1838.         //     foreach ($ResultQuery as $row) {
  1839.         //         $task[$row['id']]['detail'] = $row;
  1840.         //         $task[$row['id']]['server'] = null;
  1841.         //     }
  1842.         // }
  1843.         if ($requestType == "API") {
  1844.             $sql = "select run_result from chklst where id = :id_chklst_run";
  1845.             $stmt = $em->getConnection()->prepare($sql);
  1846.             $stmt->bindValue('id_chklst_run', $chklst_id);
  1847.             $stmt->execute();
  1848.             $resultQuery = $stmt->fetchAll();
  1849.             $continue = 1;
  1850.             if (!empty($resultQuery) && $resultQuery[0]["run_result"] != "") {
  1851.                 $continue = 0;
  1852.             }
  1853.             $listKeyTaskRan = array();
  1854.             if (!empty($task)) {
  1855.                 foreach ($task as $key => $value) {
  1856.                     // $listKeyTaskRan[] = ["key" => "[TASK {$id_template}_{$value['detail']['task_id']}_{$value['detail']['key_anag']}]",
  1857.                     //                     "result" =>  array_map('utf8_encode', [strtolower($value['detail']['runResult'])])[0]];
  1858.                     $listKeyTaskRan[] = [
  1859.                         "key" => "[TASK {$id_template}_{$value['detail']['task_id']}_{$value['detail']['key_anag']}]",
  1860.                         "result" =>  mb_convert_encoding(strtolower($value['detail']['runResult']), 'UTF-8'),
  1861.                         "isSlave" => $value['detail']['slave']
  1862.                     ];
  1863.                 }
  1864.             }
  1865.             $listParametersWorklfowRun = "
  1866.                     SELECT chklst_id,
  1867.                             param_name,
  1868.                             param_value,
  1869.                             param_type,
  1870.                             chklst_run_id
  1871.                     FROM v_chklst_template_parameters 
  1872.                     WHERE chklst_run_id IN ($chklst_id) and param_name not like '%SYBOT_USER%'
  1873.                     ORDER BY chklst_id DESC, chklst_run_id DESC";
  1874.             $statement = $em->getConnection()->prepare($listParametersWorklfowRun);
  1875.             $statement->execute();
  1876.             $ParameterWorkflowRun = $statement->fetchAll();
  1877.             $ParameterWorkflow = array();
  1878.             foreach ($ParameterWorkflowRun as $pr) {
  1879.                 $ParameterWorkflow_tmp = array(
  1880.                     'chklst_id' => $pr['chklst_id'],
  1881.                     'param_name' => $pr['param_name'],
  1882.                     'param_value' => $pr['param_value'],
  1883.                     'param_type' => $pr['param_type'],
  1884.                     'chklst_run_id' => $pr['chklst_run_id']
  1885.                 );
  1886.                 array_push($ParameterWorkflow, $ParameterWorkflow_tmp);
  1887.             }
  1888.         
  1889.             $myrender = $this->render(
  1890.                 'checklist-detail.html.twig',
  1891.                 array(
  1892.                     'title' => $chklst->getName(),
  1893.                     'task' => $task,
  1894.                     'ListaParameterWorkflow' => $ParameterWorkflow
  1895.                 )
  1896.             );
  1897.             return $this->json(["html" => $myrender->getContent(), "continue" => $continue, "listKeyTaskRan" => $listKeyTaskRan]);
  1898.         }
  1899.         $myrender = $this->render('checklist-detail.html.twig', 
  1900.             array('title' => $chklst->getName(), 
  1901.                   'task' => $task, 
  1902.                   'ListaParameterWorkflow' =>[]));
  1903.         return $myrender;
  1904.     }
  1905.     public function runChecklistAction(Request $request, LoggerInterface $logger, ParameterBagInterface $params, WorkflowAuditLoggerFactory $auditLoggerFactory, $method = null)
  1906.     {
  1907.         $csrfToken = isset($_REQUEST['csrftoken']) ? $_REQUEST['csrftoken'] : $request->request->get('csrftoken');
  1908.         $method= isset($_REQUEST['method']) ? $_REQUEST['method'] : $method;
  1909.         
  1910.         if( $method != 'internal'){
  1911.             if (!$this->isCsrfTokenValid('run_save', $csrfToken)) {
  1912.                 throw new \Exception('Csrf token not valid');
  1913.             }
  1914.         }
  1915.         $em = $this->getDoctrine()->getManager();
  1916.         $connection = $em->getConnection();
  1917.         
  1918.         if (isset($_REQUEST['template_id'])) {
  1919.             $template_id = htmlEntities($_REQUEST['template_id'], ENT_QUOTES);
  1920.         } else {
  1921.             $template_id = htmlEntities($request->request->get('template_id'), ENT_QUOTES);
  1922.         }
  1923.         $CallType = $request->request->get('remote_api');
  1924.         if (isset($_GET["remote_api"])) {
  1925.             $CallType = $_GET["remote_api"];
  1926.         }
  1927.                 
  1928.         $template = $em->find('App:ChklstTemplate', $template_id);
  1929.         
  1930.         // --------------------------------------------------------------------
  1931.         // Recuper $run_user_id in base al tipo di chiamata
  1932.         // --------------------------------------------------------------------
  1933.         if ($request->request->get('token')){
  1934.             $token = $request->request->get('token');
  1935.             $sql = "select id_user 
  1936.                     from user_token 
  1937.                     where token = :token";
  1938.             $stmt = $em->getConnection()->prepare($sql);
  1939.             $stmt->bindValue('token', $token);
  1940.             $stmt->execute();
  1941.             $run_user_id = $stmt->fetchOne();                
  1942.         } else if ($CallType == 'BPMN_API') {
  1943.             $run_user_id = $request->request->get('run_user_id');
  1944.         } else if ($CallType == 'SCHEDULER') {
  1945.             $run_user_id = 1;                        
  1946.         } else {                
  1947.             $run_user_id =$this->getUser()->getId();
  1948.         }
  1949.         // --------------------------------------------------------------------
  1950.         //
  1951.         // --------------------------------------------------------------------
  1952.         $ins = "INSERT INTO chklst (name, description, run_start, run_result, run_end, run_user_id, ko_mail_task_id, ok_mail_task_id, from_template_id)
  1953.             VALUES (:name,:description, null, null, null,:run_user_id,null, null, :from_template_id)
  1954.             ON CONFLICT (from_template_id, name, run_start)
  1955.             DO NOTHING";
  1956.         $stmt = $em->getConnection()->prepare($ins);
  1957.         $stmt->bindValue('name', $template->getName() );
  1958.         $stmt->bindValue('description', $template->getDescription() );
  1959.         $stmt->bindValue('run_user_id', $run_user_id );
  1960.         $stmt->bindValue('from_template_id', $template_id);
  1961.         $stmt->execute();
  1962.         
  1963.         $chklst_new_id = $em->getConnection()->lastInsertId();
  1964.         $logger->debug("[runChecklistAction] chklst_new_id: ".json_encode($chklst_new_id));
  1965.         $checklist = $em->find(Chklst::class,$chklst_new_id);
  1966.         $logger->debug("[runChecklistAction] checklis: ".json_encode($checklist));
  1967.         
  1968.         $template_task = $em->getRepository('App:Chklsttmpl2task')->findByChklsttmpl($template);
  1969.         foreach ($template_task as $tt) {
  1970.             $config_json = $tt->getTask()->getConfigJson();
  1971.             // Dal DB $config_json arriva come array vuoto [] invece di un oggetto {}.
  1972.             // Lo trasformiamo in stdClass per avere un oggetto vuoto valido
  1973.             // da usare con jsonb_set e altre operazioni su JSON come oggetto.
  1974.             if (empty($config_json)){
  1975.                 $config_json = new \stdClass(); // {}
  1976.             }
  1977.             $ctask = new ChklstTask();
  1978.             $ctask
  1979.                 ->setChklst($checklist)
  1980.                 ->setName($tt->getTask()->getName())
  1981.                 ->setDescription($tt->getTask()->getDescription())
  1982.                 ->setCmdType($tt->getTask()->getCmdType())
  1983.                 ->setCmdText($tt->getTask()->getCmdText())
  1984.                 ->setReturnType($tt->getTask()->getReturnType())
  1985.                 ->setMatchOperator($tt->getTask()->getMatchOperator())
  1986.                 ->setMatchText($tt->getTask()->getMatchValue())
  1987.                 ->setCmdMaxRetry($tt->getTask()->getCmdMaxRetry())
  1988.                 ->setCmdTimeRetry($tt->getTask()->getCmdTimeRetry())
  1989.                 ->setKoHint($tt->getTask()->getKoHint())
  1990.                 ->setTaskOrder($tt->getTaskOrder())
  1991.                 ->setKoTask($tt->getKoTask())
  1992.                 ->setSlave($tt->getSlave())
  1993.                 ->setFlagBitmask($tt->getFlagBitmask())
  1994.                 ->setRunBitmask($tt->getRunBitmask())
  1995.                 ->setTypeDb($tt->getTask()->getTypeDb())
  1996.                 ->setIpDb($tt->getTask()->getIpDb())
  1997.                 ->setUserDb($tt->getTask()->getUserDb())
  1998.                 ->setPwdDb($tt->getTask()->getPwdDb())
  1999.                 ->setPortDb($tt->getTask()->getPortDb())
  2000.                 ->setNameDb($tt->getTask()->getNameDb())
  2001.                 ->setService($tt->getTask()->getService())
  2002.                 //->setSetTimeout($tt->getAction()->getSetTimeout())
  2003.                 ->setFlagStopChk($tt->getTask()->getFlagStopChk())
  2004.                 ->setFlagJumpTask($tt->getTask()->getFlagJumpTask())
  2005.                 ->setNextTask($tt->getTask()->getNextTask())
  2006.                 //->setFlagJumpTaskAct($tt->getAction()->getFlagJumpTaskAct())
  2007.                 //->setNextTaskAct($tt->getAction()->getNextTaskAct())
  2008.                 //->setFlagJumpKoAct($tt->getAction()->getFlagJumpKoAct())
  2009.                 //->setNextTaskKoAct($tt->getAction()->getNextTaskKoAct())
  2010.                 ->setConnectDirect($tt->getTask()->getConnectDirect())
  2011.                 ->setStatementSelect($tt->getTask()->getStatementSelect())
  2012.                 ->setAuthUsername($tt->getTask()->getAuthUsername())
  2013.                 ->setAuthPassword($tt->getTask()->getAuthPassword())
  2014.                 ->setAuthProtocol($tt->getTask()->getAuthProtocol())
  2015.                 ->setAuthPort($tt->getTask()->getAuthPort())
  2016.                 ->setAuthType($tt->getTask()->getAuthType())
  2017.                 ->setAuthToken($tt->getTask()->getAuthToken())
  2018.                 ->setAuthUrl($tt->getTask()->getAuthUrl())
  2019.                 ->setFlagRunAs($tt->getTask()->getFlagRunAs())
  2020.                 ->setRunAsUser($tt->getTask()->getRunAsUser())
  2021.                 ->setFlagRunAsUserPassword($tt->getTask()->getFlagRunAsUserPassword())
  2022.                 ->setRunAsPassword($tt->getTask()->getRunAsPassword())
  2023.                 ->setFlagCheckExitStatus($tt->getTask()->getFlagCheckExitStatus())
  2024.                 ->setFlagCheckCountQuery($tt->getTask()->getFlagCheckCountQuery())
  2025.                 ->setFlagMailAttachment($tt->getTask()->getFlagMailAttachment())
  2026.                 ->setMailAttachment($tt->getTask()->getMailAttachment())
  2027.                 ->setSendToMail($tt->getTask()->getSendToMail())
  2028.                 ->setSendCcMail($tt->getTask()->getSendCcMail())
  2029.                 ->setSendTextMail($tt->getTask()->getSendTextMail())
  2030.                 ->setSendObjectMail($tt->getTask()->getSendObjectMail())
  2031.                 ->setSpoolOnFile($tt->getTask()->getSpoolOnFile())
  2032.                 ->setFilenameSpoolQuery($tt->getTask()->getFilenameSpoolQuery())
  2033.                 ->setFtpAnonymous($tt->getTask()->getFtpAnonymous())
  2034.                 ->setFtpHostname($tt->getTask()->getFtpHostname())
  2035.                 ->setFtpPort($tt->getTask()->getFtpPort())
  2036.                 ->setFtpUser($tt->getTask()->getFtpUser())
  2037.                 ->setFtpPassword($tt->getTask()->getFtpPassword())
  2038.                 ->setFtpDirectory($tt->getTask()->getFtpDirectory())
  2039.                 ->setFtpFilename($tt->getTask()->getFtpFilename())
  2040.                 ->setConfigureTimeout($tt->getTask()->getConfigureTimeout())
  2041.                 ->setServerCheckEmail($tt->getTask()->getServerCheckEmail())
  2042.                 ->setPortCheckEmail($tt->getTask()->getPortCheckEmail())
  2043.                 ->setUserCheckEmail($tt->getTask()->getUserCheckEmail())
  2044.                 ->setPassCheckEmail($tt->getTask()->getPassCheckEmail())
  2045.                 ->setFromCheckEmail($tt->getTask()->getFromCheckEmail())
  2046.                 ->setSubjectCheckEmail($tt->getTask()->getSubjectCheckEmail())
  2047.                 ->setBodyCheckEmail($tt->getTask()->getBodyCheckEmail())
  2048.                 ->setAttemptCheckEmail($tt->getTask()->getAttemptCheckEmail())
  2049.                 ->setPollingCheckEmail($tt->getTask()->getPollingCheckEmail())
  2050.                 ->setUrlNavWeb($tt->getTask()->getUrlNavWeb())
  2051.                 ->setUserNavWeb($tt->getTask()->getUserNavWeb())
  2052.                 ->setPassNavWeb($tt->getTask()->getPassNavWeb())
  2053.                 ->setObjectNameNavWeb($tt->getTask()->getObjectNameNavWeb())
  2054.                 ->setNavWebAnonymous($tt->getTask()->getNavWebAnonymous())
  2055.                 ->setNavWebSpoolObjectid($tt->getTask()->getNavWebSpoolObjectid())
  2056.                 ->setIdUserNavWeb($tt->getTask()->getIdUserNavWeb())
  2057.                 ->setIdPassNavWeb($tt->getTask()->getIdPassNavWeb())
  2058.                 ->setTypeCheckEmail($tt->getTask()->getTypeCheckEmail())
  2059.                 ->setFtpInAllDirectory($tt->getTask()->getFtpInAllDirectory())
  2060.                 ->setObjectTypeNavWeb($tt->getTask()->getObjectTypeNavWeb())
  2061.                 ->setUseCertificateDb($tt->getTask()->getUseCertificateDb())
  2062.                 ->setTarsRunProjectName($tt->getTask()->getTarsRunProjectName())
  2063.                 ->setTarsRunSuiteName($tt->getTask()->getTarsRunSuiteName())
  2064.                 ->setTarsRunPathScenario($tt->getTask()->getTarsRunPathScenario())
  2065.                 ->setTarsRunNomeScenario($tt->getTask()->getTarsRunNomeScenario())
  2066.                 //->setTarsRunIdentificativo($tt->getTask()->getTarsRunIdentificativo())
  2067.                 ->setTarsRunParametroDefault($tt->getTask()->getTarsRunParametroDefault())
  2068.                 ->setTarsRunUser($tt->getTask()->getTarsRunUser())
  2069.                 ->setTarsRunIpaddress($tt->getTask()->getTarsRunIpaddress())
  2070.                 ->setTarsRunHostname($tt->getTask()->getTarsRunHostname())
  2071.                 ->setTarsRunPassword($tt->getTask()->getTarsRunPassword())
  2072.                 ->setTarsRunUsePassword($tt->getTask()->getTarsRunUsePassword())
  2073.                 ->setSaveAttachmentsEmail($tt->getTask()->getSaveAttachmentsEmail())
  2074.                 ->setInformationText($tt->getTask()->getInformationText())
  2075.                 ->setFlagSendCall($tt->getTask()->getFlagSendCall())
  2076.                 ->setTextToSpeechFlagCall($tt->getTask()->getTextToSpeechFlagCall())
  2077.                 ->setTextToSpeechNumberCall($tt->getTask()->getTextToSpeechNumberCall())
  2078.                 ->setTextToSpeechTextSendCall($tt->getTask()->getTextToSpeechTextSendCall())
  2079.                 ->setUccxFlagCall($tt->getTask()->getUccxFlagCall())
  2080.                 ->setUccxNumberCall($tt->getTask()->getUccxPromptMessage())
  2081.                 ->setUccxConfirmMessage($tt->getTask()->getUccxConfirmMessage())
  2082.                 ->setSmsFlagSend($tt->getTask()->getSmsFlagSend())
  2083.                 ->setSmsNumber($tt->getTask()->getSmsNumber())
  2084.                 ->setSmsTextSend($tt->getTask()->getSmsTextSend())
  2085.                 ->setTelegramFlagSend($tt->getTask()->getTelegramFlagSend())
  2086.                 ->setTelegramChat($tt->getTask()->getTelegramChat())
  2087.                 ->setTelegramTextSend($tt->getTask()->getTelegramTextSend())
  2088.                 ->setTaskID($tt->getTaskId())
  2089.                 ->setConfigJson($config_json);
  2090.             // $logger->debug("[runChecklistAction] inserimento su  ChklstTask - checklist");
  2091.             $em->persist($ctask);
  2092.             $server = $em->getRepository('App:Task2server')->findByTask($tt);
  2093.             foreach ($server as $s) {
  2094.                 $tserver = new TaskServer();
  2095.                 $tserver
  2096.                     ->setTask($ctask)
  2097.                     ->setHostname($s->getServer()->getHostName())
  2098.                     ->setIpAddress($s->getServer()->getIpAddress())
  2099.                     ->setUsername($s->getServer()->getUsername())
  2100.                     ->setGroupName($s->getServer()->getGroupName())
  2101.                     ->setServerOrder($s->getServerOrder());
  2102.                 // $logger->debug("[runChecklistAction] inserimento su  TaskServer");
  2103.                 $em->persist($tserver);
  2104.             }
  2105.         }
  2106.         $sycore_info = $this->sycoreService->getSycoreInfo();
  2107.         
  2108.         $queue = new Queue();
  2109.         $queue->setChklst($checklist);
  2110.         $queue->setSycoreInstanceUuid($sycore_info->instance_uuid);
  2111.         if ($CallType == 'SCHEDULE') {
  2112.             $date = date_create_from_format('d/m/Y H:i', '31/12/2999 23:59');
  2113.             $queue
  2114.                 ->setScheduleDate($request->request->get('schedule_date'))
  2115.                 ->setIdSchedule($request->request->get('schedule_id'));
  2116.             //->setRunStart($date);
  2117.         }
  2118.         $em->persist($queue);
  2119.         $em->flush();
  2120.         $chklst_run_id = $checklist->getId();
  2121.         // $logger->debug("[runChecklistAction] Valore CheklistID " . json_encode($chklst_run_id));
  2122.         $auditLogger = $auditLoggerFactory->createWorkflow(
  2123.             $template->getName(),
  2124.             $run_user_id,
  2125.             $template_id,
  2126.             $chklst_run_id
  2127.         );
  2128.         
  2129.         $sql = "select param_name, param_value , param_type
  2130.               from chklst_template_parameters
  2131.               where chklst_id = :template_id";
  2132.         $statement = $connection->prepare($sql);
  2133.         $statement->bindValue('template_id',$template_id);
  2134.         $statement->execute();
  2135.         $result = $statement->fetchAll();
  2136.         $auditLogger->log(WorkflowAuditLogger::LEVEL_INFO,WorkflowAuditLogger::EVENT_WFL_START,[
  2137.             'call_type'=> $CallType,
  2138.             'params'=> $result
  2139.         ]);
  2140.         
  2141.         // Gestione modifica parametri a runtime da chiamata API    
  2142.         
  2143.         if ($CallType == 'SCHEDULER') {
  2144.             $logger->debug("[runChecklistAction] Chiamata da SCHEDULER2 - inizio gestione parametri");
  2145.             try {
  2146.                 $parametersOfWorkflow = $result;
  2147.                 $parametersOfSchedule = [];
  2148.                 $tmp = json_decode($request->request->get("params"), true);
  2149.                 foreach ($tmp as $p) {
  2150.                     $parametersOfSchedule[$p['param_name']] = $p['param_value'];
  2151.                 }
  2152.                 foreach ($parametersOfWorkflow as $param) {
  2153.                     if (isset($parametersOfSchedule[$param['param_name']])) {
  2154.                         $param['param_value'] = $parametersOfSchedule[$param['param_name']];
  2155.                     }
  2156.                     $sql = <<<SQL
  2157.                         INSERT INTO chklst_template_parameters_api (chklst_id, param_name, param_value, param_type, chklst_run_id)
  2158.                             VALUES (:template_id, :param_name, :param_value, :param_type, :chklst_run_id)
  2159.                             ON CONFLICT (chklst_id, param_name, chklst_run_id) DO UPDATE SET
  2160.                                 param_name = :param_name,
  2161.                                 param_value = :param_value,
  2162.                                 param_type = :param_type
  2163.                     SQL;
  2164.                     $em->getConnection()->executeQuery($sql, [
  2165.                         'template_id' => $template_id,
  2166.                         'param_name' => $param['param_name'],
  2167.                         'param_value' => $param['param_value'],
  2168.                         'param_type' => $param['param_type'],
  2169.                         'chklst_run_id' => $chklst_run_id
  2170.                     ]);
  2171.                 }
  2172.             } catch (\Exception $e) {
  2173.                 $logger->error("[runChecklistAction] Errore nella decodifica dei parametri da SCHEDULER2: " . $e->getMessage());
  2174.                 throw new \Exception('Errore nella decodifica dei parametri da SCHEDULER2: ' . $e->getMessage());
  2175.             }
  2176.             
  2177.         } else if ($CallType == 'BPMN_API') {
  2178.             
  2179.             foreach ($result as $r) {
  2180.                 if (isset(json_decode($request->getContent(), true)['params'])) {
  2181.                     $input = json_decode($request->getContent(), true);
  2182.                     $flatParams = array_column($input['params'], 'value', 'name');//array_merge(...json_decode($request->getContent(), true)['params']);
  2183.                     if(isset($flatParams[$r['param_name']])){
  2184.                         $param_value = $flatParams[$r['param_name']];    
  2185.                     }    else {
  2186.                             $param_value = $r['param_value'];
  2187.                             // $logger->debug("[runChecklistAction] ELSE: valore Parameter_value " . $param_value);
  2188.                         }                
  2189.                 } else {
  2190.                     $param_value = $r['param_value'];
  2191.                     // $logger->debug("[runChecklistAction] ELSE: valore Parameter_value " . $param_value);
  2192.                 }
  2193.                 $param_name = $r['param_name'];
  2194.                 $param_type = $r['param_type'];
  2195.             
  2196.                 $sql = "insert into chklst_template_parameters_api (chklst_id, param_name, param_value, param_type, chklst_run_id)
  2197.                                 values (:template_id, :param_name, :param_value, :param_type, :chklst_run_id)
  2198.                                 ON CONFLICT (chklst_id, param_name, chklst_run_id) DO UPDATE SET
  2199.                                 param_name = :param_name,
  2200.                                 param_value = :param_value,
  2201.                                 param_type = :param_type ";
  2202.                 // $logger->debug("[runChecklistAction] Upsert " . $sql);
  2203.                 $statement = $connection->prepare($sql);
  2204.                 $statement->bindValue('template_id',$template_id);
  2205.                 $statement->bindValue('param_name',$param_name);
  2206.                 $statement->bindValue('param_value',$param_value);
  2207.                 $statement->bindValue('param_type',$param_type);
  2208.                 $statement->bindValue('chklst_run_id',$chklst_run_id);
  2209.                 $statement->execute();
  2210.             }
  2211.         } else {
  2212.             foreach ($result as $r) {
  2213.                 if (isset($_GET[$r['param_name']])) {
  2214.                     $param_value = $_GET[$r['param_name']];
  2215.                     // $logger->debug("[runChecklistAction] valore Parameter_value " . $param_value);
  2216.                 } else {
  2217.                     $param_value = $r['param_value'];
  2218.                     // $logger->debug("[runChecklistAction] ELSE: valore Parameter_value " . $param_value);
  2219.                 }
  2220.                 $param_name = $r['param_name'];
  2221.                 $param_type = $r['param_type'];
  2222.                 // $logger->debug("[runChecklistAction] valore param_name " . $param_name);
  2223.                 // $logger->debug("[runChecklistAction] valore param_type " . $param_type);
  2224.             
  2225.                 // DA VERIFICARE
  2226.                 $sql = "insert into chklst_template_parameters_api (chklst_id, param_name, param_value, param_type, chklst_run_id)
  2227.                                 values (:template_id, :param_name, :param_value, :param_type, :chklst_run_id)
  2228.                                 ON CONFLICT (chklst_id, param_name, chklst_run_id) DO UPDATE SET
  2229.                                 param_name = :param_name,
  2230.                                 param_value = :param_value,
  2231.                                 param_type = :param_type ";
  2232.                 // $logger->debug("[runChecklistAction] Upsert " . $sql);
  2233.                 $statement = $connection->prepare($sql);
  2234.                 $statement->bindValue('template_id',$template_id);
  2235.                 $statement->bindValue('param_name',$param_name);
  2236.                 $statement->bindValue('param_value',$param_value);
  2237.                 $statement->bindValue('param_type',$param_type);
  2238.                 $statement->bindValue('chklst_run_id',$chklst_run_id);
  2239.                 $statement->execute();
  2240.             }
  2241.         }
  2242.         // Gestione modifica parametri a runtime da frontend
  2243.         $list_param_type = preg_grep("/^form_lista_param_type_" . $template_id . "_*/", array_keys($_POST));
  2244.         foreach ($list_param_type as $l) {
  2245.             $exp = explode("_", $l);
  2246.             $i = end($exp);
  2247.             if (isset($_REQUEST["form_lista_param_type" . '_' . $template_id . '_' . $i]) && isset($_REQUEST["form_lista_param_name" . '_' . $template_id . '_' . $i]) && isset($_REQUEST["form_lista_param_value" . '_' . $template_id . '_' . $i])) {
  2248.                 $param_type = $_REQUEST["form_lista_param_type" . '_' . $template_id . '_' . $i];
  2249.                 $param_name    = $_REQUEST["form_lista_param_name" . '_' . $template_id . '_' . $i];
  2250.                 $param_value =$_REQUEST["form_lista_param_value" . '_' . $template_id . '_' . $i];
  2251.                 // DA VERIFICARE    
  2252.                 $sql = "insert into chklst_template_parameters_api (chklst_id, param_name, param_value, param_type, chklst_run_id)
  2253.                         values (:template_id, :param_name, :param_value, :param_type, :chklst_run_id)
  2254.                         ON CONFLICT (chklst_id, param_name, chklst_run_id) DO UPDATE SET
  2255.                         param_name = :param_name,
  2256.                         param_value = :param_value,
  2257.                         param_type = :param_type ";
  2258.                 // $logger->debug("[runChecklistAction] Upsert " . $sql);
  2259.                 $statement = $connection->prepare($sql);
  2260.                 $statement->bindValue('template_id',$template_id);
  2261.                 $statement->bindValue('param_name',$param_name);
  2262.                 $statement->bindValue('param_value',$param_value);
  2263.                 $statement->bindValue('param_type',$param_type);
  2264.                 $statement->bindValue('chklst_run_id',$chklst_run_id);
  2265.                 $statement->execute();
  2266.             }
  2267.         }
  2268.         
  2269.         if ($CallType == 'API') {
  2270.             $response = new JsonResponse();
  2271.             $response->setData(array('template_id' => $template_id, 'cheklist_id' => $chklst_run_id));
  2272.             return $response;
  2273.         } else if ($CallType == 'BPMN_API' || $CallType == 'SCHEDULER') {
  2274.             $response = new JsonResponse();
  2275.             $response->setData(array('workflow_id' => $template_id, 'workflow_run_id' => $chklst_run_id));
  2276.             return $response;
  2277.         } else {
  2278.             //return $this->redirect($this->generateUrl('home'));
  2279.             return $this->redirect($this->generateUrl('home_old', array('template_id' => $template_id)));
  2280.         }
  2281.     }
  2282.     public function getFullResult($id, LoggerInterface $logger) {
  2283.         
  2284.         $em = $this->getDoctrine()->getManager();
  2285.         $conn = $em->getConnection();
  2286.         $stmt = $conn->prepare("select full_result from task_server where task_id=:id");
  2287.         $stmt->bindValue('id', $id);
  2288.         $stmt->execute();
  2289.         $text = $stmt->fetchOne();        
  2290.         $stmt = $conn->prepare("select replace(name,' ','-') as name from chklst_task where id=:id");
  2291.         $stmt->bindValue('id', $id);
  2292.         $stmt->execute();
  2293.         $name = $stmt->fetchOne();    
  2294.         $response = new Response($text);
  2295.         $disposition = HeaderUtils::makeDisposition(
  2296.             HeaderUtils::DISPOSITION_ATTACHMENT,
  2297.             "Task_" . $name . "_result.txt"
  2298.         );
  2299.         $response->headers->set('Content-Disposition', $disposition);
  2300.         return $response;
  2301.     }
  2302.     public function toByteSize($iUnits, $sUnit)
  2303.     {
  2304.         $aUnits = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8, 'K' => 1, 'M' => 2, 'G' => 3, 'T' => 4, 'P' => 5, 'E' => 6, 'Z' => 7, 'Y' => 8);
  2305.         //  $sUnit = strtoupper(trim(substr($p_sFormatted, -2)));
  2306.         if (intval($sUnit) !== 0) {
  2307.             $sUnit = 'B';
  2308.         }
  2309.         if (!in_array($sUnit, array_keys($aUnits))) {
  2310.             return false;
  2311.         }
  2312.         //  $iUnits = trim(substr($p_sFormatted, 0, strlen($p_sFormatted) - 2));
  2313.         if (!intval($iUnits) == $iUnits) {
  2314.             return false;
  2315.         }
  2316.         return $iUnits * pow(1024, $aUnits[$sUnit]);
  2317.     }
  2318.     public function importChecklistAction(Request $request, LoggerInterface $logger, ParameterBagInterface $params) 
  2319.     {
  2320.         // Temporaneo, testing
  2321.         if ($this->USE_NEW_IMPEXP) {
  2322.             return $this->importChecklistAction_new($request, $logger, $params);
  2323.         } else {
  2324.             return $this->importChecklistAction_old($request, $logger, $params);
  2325.         }
  2326.     }
  2327.     public function importChecklistAction_new(Request $request, LoggerInterface $logger, ParameterBagInterface $params)
  2328.     {
  2329.                 
  2330.         $res_json = new JsonResponse();
  2331.         $upload_only = $request->request->get('upload_only', 'N');
  2332.         $uploaded_file = $request->files->get('xml_fileToUpload_0_1');
  2333.         $uploadDirectory = $this->getParameter('kernel.project_dir') . '/uploads/import/';
  2334.         $uploaded_file->move($uploadDirectory, $uploaded_file->getClientOriginalName());
  2335.         try 
  2336.         {
  2337.             $target_file = $uploadDirectory . $uploaded_file->getClientOriginalName();
  2338.             $importer = 
  2339.                 ImpExp\ImpExp::createImporter(
  2340.                     $target_file, 
  2341.                     $this->getDoctrine()->getManager()->getConnection(), 
  2342.                     $logger
  2343.                 );    
  2344.             if ($upload_only === 'Y') {
  2345.             
  2346.                 $catalog = $importer->getCatalog();
  2347.                 $workflow_data = [];
  2348.                 foreach ($catalog['workflows'] as $w) {
  2349.                     $workflow_data[] = [
  2350.                         'id' => $w['id'],
  2351.                         'workflow' => $w['name']
  2352.                     ];
  2353.                 }
  2354.                 
  2355.                 $res_json->setData(array(
  2356.                     "id_workflow" => 0, 
  2357.                     "workflow" => $workflow_data, 
  2358.                     "extension" => 'sybot'
  2359.                 ));
  2360.                 
  2361.                 return $res_json;
  2362.             }
  2363.             else 
  2364.             {
  2365.                 $importer->import();
  2366.                 
  2367.                 $res_json->setData(array(
  2368.                         "id_workflow" => 0, 
  2369.                         "workflow" => [], 
  2370.                         "extension" => 'sybot'
  2371.                     )
  2372.                 );
  2373.             }
  2374.         } catch (\Exception $e) {
  2375.             $logger->error("Errore durante importazione checklist: " . $e->getMessage() . "trace: " . $e->getTraceAsString());
  2376.             $res_json->setData(array(
  2377.                 "error" => "Errore durante importazione checklist: " . $e->getMessage()
  2378.             ));
  2379.             $res_json->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
  2380.         }
  2381.     
  2382.     
  2383.         return $res_json;
  2384.     }
  2385.     public function importChecklistAction_old(Request $request, LoggerInterface $logger, ParameterBagInterface $params)
  2386.     {
  2387.         try {
  2388.             
  2389.         $csrfToken = $request->request->get('csrftoken');
  2390.         if (!$this->isCsrfTokenValid('import_checklist', $csrfToken)) {
  2391.             throw new \Exception('Csrf token not valid');
  2392.         }
  2393.         $user = $this->getUser();
  2394.         $userId = $user->getId();
  2395.         //$logger = $this->getLogger();
  2396.         $em = $this->getDoctrine()->getManager();
  2397.         $connection = $em->getConnection();
  2398.         $functions = new Functions($this, $logger, $em);
  2399.         $res_json = new JsonResponse();
  2400.         $checklist = null;
  2401.         if (isset($_POST["target_import_dir"])) {
  2402.             $target_dir = $params->get('kernel.project_dir') . '/' . $_POST["target_import_dir"];
  2403.         } else if (isset($_GET["target_import_dir"])) {
  2404.             $target_dir = $params->get('kernel.project_dir') . '/' . $_GET["target_import_dir"];
  2405.         } else {
  2406.             $target_dir = $params->get('kernel.project_dir') . '/uploads/import/';
  2407.         }
  2408.         if (isset($_POST["upload_only"])) {
  2409.             $fl_upload_only = $_POST["upload_only"];
  2410.         } else if (isset($_GET["upload_only"])) {
  2411.             $fl_upload_only = $_GET["upload_only"];
  2412.         } else {
  2413.             $fl_upload_only = "N";
  2414.         }
  2415.         if (isset($_POST["workflow_role"])) {
  2416.             $checklist_role = $_POST["workflow_role"];
  2417.         } else if (isset($_GET["workflow_role"])) {
  2418.             $checklist_role = $_GET["workflow_role"];
  2419.         } else {
  2420.             $checklist_role = "SYBOT";
  2421.         }
  2422.         $cid = 0;
  2423.         $check_files_cnt = 0;
  2424.         if (isset($_FILES["xml_fileToUpload" . '_' . $cid . '_1'])) {
  2425.             $logger->debug("[importChecklistAction] STO DENTRO ISSET xml_FILES");
  2426.             $target_file = $target_dir . basename($_FILES["xml_fileToUpload" . '_' . $cid . '_1']["name"]);
  2427.             if (move_uploaded_file($_FILES["xml_fileToUpload" . '_' . $cid . '_1']["tmp_name"], $target_file)) {
  2428.                 $logger->debug("[importChecklistAction] The xml_file " . basename($_FILES["xml_fileToUpload" . '_' . $cid . '_1']["name"]) . " has been uploaded.");
  2429.             }
  2430.             $check_files_cnt++;
  2431.             $path_parts = pathinfo($target_file);
  2432.             $logger->debug("estensione file: " . $path_parts['extension']);
  2433.             $isSybot = $path_parts['extension'] == "sybot" ? 1 : 0;
  2434.             if ($path_parts['extension'] == "sybot" || $path_parts['extension'] == "acm") {
  2435.                 //DECRITTO E SCOMPATTO IL PACCHETTO .acm
  2436.                 $cipher = new AES(); // could use AES::MODE_CBC
  2437.                 $cipher->setKey($_ENV["KEY_SYBOT"]);
  2438.                 $cipher->setIV($_ENV["IV_SYBOT"]);
  2439.                 $decrypted_contents = base64_decode($cipher->decrypt(file_get_contents($target_file)));
  2440.                 $file_zip = $isSybot? str_replace('.sybot', '.zip', $target_file) : str_replace('.acm', '.zip', $target_file);
  2441.                 file_put_contents($file_zip, $decrypted_contents);
  2442.                 $dir_zip = str_replace('.zip', '', $file_zip);
  2443.                 $zip = new \ZipArchive;
  2444.                 $res = $zip->open($file_zip);
  2445.                 if ($res === TRUE) {
  2446.                     $zip->extractTo($dir_zip);
  2447.                     $zip->close();
  2448.                 }
  2449.                 if (file_exists($file_zip))
  2450.                     unlink($file_zip);
  2451.                 if (file_exists($target_file))
  2452.                     unlink($target_file);
  2453.                 $checklists = json_decode(file_get_contents($dir_zip . '/export.json'), true);
  2454.                 //    $logger -> info("[importChecklistAction] json import: ".json_encode($import_json));
  2455.             } else if ($path_parts['extension'] == "xlsm") {
  2456.                 $excel = new ExcelFactory();
  2457.                 $checklist = $excel->loadTemplate($checklist_role, $target_file);
  2458.             }
  2459.         } else {
  2460.             $path_parts['extension'] = 'xml';
  2461.         }
  2462.         $id_checklist = 0;
  2463.         if ($fl_upload_only != "Y") {
  2464.             $logger->debug("fl_upload_only diverso da Y");
  2465.             if (isset($_POST["nome_file"])) {
  2466.                 $FileName = $_POST['nome_file'];
  2467.                 //        $serializer = new Serializer(array(), array(new XmlEncoder()));
  2468.                 $file[] = file_get_contents($target_dir . $FileName, FILE_USE_INCLUDE_PATH);
  2469.                 $fl_json = 0;
  2470.                 //    $checklists = $serializer->decode($file, 'xml');
  2471.             } else if (isset($_GET["nome_file"])) {
  2472.                 $FileName = $_GET['nome_file'];
  2473.                 //        $serializer = new Serializer(array(), array(new XmlEncoder()));
  2474.                 $file[] = file_get_contents($target_dir . $FileName, FILE_USE_INCLUDE_PATH);
  2475.                 $fl_json = 0;
  2476.                 //    $checklists = $serializer->decode($file, 'xml');
  2477.             } else if ($path_parts['extension'] == "sybot" || $path_parts['extension'] == "acm") {  //PACCHETTO .ACM
  2478.                 $logger->debug("sto nel pacchetto acm: " . json_encode($checklists));
  2479.                 //    $checklists=json_decode(json_encode($checklists));
  2480.                 foreach ($checklists as $c) {
  2481.                     $logger->debug("c: " . json_encode($c));
  2482.                     $isSybot = $path_parts['extension'] == "sybot" ? 1 : 0;
  2483.                     $d = $isSybot ? $c['workflow'] : $c['checklist'];
  2484.                     $logger->debug("file xml: " . $dir_zip . '/' . $d . '/xml/' . $c['xml']);
  2485.                     $file[] = file_get_contents($dir_zip . '/' . $d . '/xml/' . $c['xml'], FILE_USE_INCLUDE_PATH);
  2486.                 }
  2487.                 $fl_json = 0;
  2488.                 //        $file = [];
  2489.             } else if ($path_parts['extension'] == "xlsm") {
  2490.                 $excel = new ExcelFactory();
  2491.                 $checklist = $excel->loadTemplate($checklist_role, $target_file);
  2492.                 $logger->debug('CHECKLIST XLSM:: ' . json_encode($checklist));
  2493.                 $file['json'] = $checklist;
  2494.                 $fl_json = 1;
  2495.             } else if ($check_files_cnt > 0) {
  2496.                 //    for ($i = 1; $i <= 120; $i++) {
  2497.                 if (isset($_FILES["xml_fileToUpload" . '_' . $cid . '_1'])) {
  2498.                     //    $logger -> info("[importChecklistAction] STO DENTRO ISSET xml_FILES");
  2499.                     $file[] = file_get_contents($target_dir . basename($_FILES["xml_fileToUpload" . '_' . $cid . '_1']["name"]), FILE_USE_INCLUDE_PATH);
  2500.                     $logger->debug("sto dentro xml_fileToUpload: " . json_encode($file));
  2501.                     //    if (move_uploaded_file($_FILES["xml_fileToUpload".'_'.$cid.'_'.$i]["tmp_name"], $target_file)) {
  2502.                     //        $logger -> info("[importChecklistAction] The xml_file ". basename( $_FILES["xml_fileToUpload".'_'.$cid.'_'.$i]["name"]). " has been uploaded.");
  2503.                     //
  2504.                     //    }
  2505.                     //    $check_files_cnt++;
  2506.                 }
  2507.                 //    }
  2508.                 $fl_json = 0;
  2509.             } else if (isset($_POST["dati_json"])) {
  2510.                 $checklist = json_decode($_POST["dati_json"]);
  2511.                 $file['json'] = $checklist;
  2512.                 $fl_json = 1;
  2513.             } else if (isset($_GET["dati_json"])) {
  2514.                 $checklist = json_decode($_GET["dati_json"]);
  2515.                 $file['json'] = $checklist;
  2516.                 $fl_json = 1;
  2517.             } else if ($request->request->get('dati_json') != null) {
  2518.                 $logger->debug('DATI JSON:: ' . $request->request->get('dati_json'));
  2519.                 $checklist = json_decode($request->request->get('dati_json'));
  2520.                 $file['json'] = $checklist;
  2521.                 $fl_json = 1;
  2522.             } else {
  2523.                 $FileName = 0;
  2524.                 $checklist = [];
  2525.                 $id_checklist = 0;
  2526.                 $fl_json = 0;
  2527.                 $file = [];
  2528.             }
  2529.             // $logger->debug("[importChecklistAction] file[] " . json_encode($file));
  2530.             $cnt = 0;
  2531.             $templateToImportKeys = preg_grep("/^import_*/", array_keys($_POST));
  2532.             $templateToImport = array_map(function ($val) {
  2533.                 return $_POST[$val];
  2534.             }, $templateToImportKeys);
  2535.             foreach ($file as $f) {
  2536.                 if ($fl_json == 0) {
  2537.                     $serializer = new Serializer(array(), array(new XmlEncoder()));
  2538.                     $checklist = $serializer->decode($f, 'xml');
  2539.                 } else {
  2540.                     $checklist = json_decode(json_encode($f), true);
  2541.                     $logger->debug('CHECKLIST:::: ' . json_encode($checklist));
  2542.                 }
  2543.                 if (!in_array($checklist['name'], $templateToImport)) {
  2544.                     continue;
  2545.                 }
  2546.                 $logger->debug("=============================================================================");
  2547.                 $logger->debug("[importChecklistAction] Nome workflow da importare: " . $checklist['name']);
  2548.                 $logger->debug("=============================================================================");
  2549.                 // qui ci sono tutte le colonne della tabella chklst_template
  2550.                 $wflTemplate = $isSybot ? $checklist['template'] : $checklist; 
  2551.                 $oldTemplateId = $wflTemplate["id"];
  2552.                 // Se non Ã¨ un template Sybot, impostiamo i campi di lock con valori di default
  2553.                 if (!$isSybot) {
  2554.                     if (!isset($wflTemplate['locked'])) $wflTemplate['locked'] = 0;
  2555.                     if (!isset($wflTemplate['lock_session_user_id'])) $wflTemplate['lock_session_user_id'] = '';
  2556.                 }
  2557.                 $sql = "insert into chklst_template (";
  2558.                 foreach ($wflTemplate as $key => $value) {
  2559.                     if ($key == 'id') {
  2560.                         continue;
  2561.                     }
  2562.                     //se Ã¨ acm non ha template e scorro tutta la checklist fino ai ruoli.
  2563.                     if ($key == "roles") {
  2564.                         break;
  2565.                     }
  2566.                     $sql .= $key . ",";
  2567.                 }
  2568.                 if (substr($sql, -1) == ",") {
  2569.                     $sql = substr($sql, 0, -1);
  2570.                 }
  2571.                 $sql .= ") values (";
  2572.                 foreach ($wflTemplate as $key => $value) {
  2573.                     if ($key == 'id') {
  2574.                         continue;
  2575.                     }
  2576.                     //se Ã¨ acm non ha template e scorro tutta la checklist fino ai ruoli.
  2577.                     if ($key == "roles") {
  2578.                         break;
  2579.                     }
  2580.                     if ($key == 'data_creazione') {
  2581.                         $sql .= "now(),";
  2582.                         continue;
  2583.                     }
  2584.                     if ($key == 'data_modifica') {
  2585.                         $sql .= "now(),";
  2586.                         continue;
  2587.                     }
  2588.                     if ($key == 'creato_da') {
  2589.                         $sql .= "$userId,";
  2590.                         continue;
  2591.                     }
  2592.                     if ($key == 'modificato_da') {
  2593.                         $sql .= "$userId,";
  2594.                         continue;
  2595.                     }
  2596.                     if ($key == 'locked') {
  2597.                         if ($value == '') {
  2598.                             $sql .= "0,";
  2599.                         } else {
  2600.                             $sql .= $value . ",";
  2601.                         }
  2602.                         continue;
  2603.                     }
  2604.                     $sql .= "'" . $value . "',";
  2605.                 }
  2606.                 if (substr($sql, -1) == ",") {
  2607.                     $sql = substr($sql, 0, -1);
  2608.                 }
  2609.                 $sql .= ")";
  2610.                 $sql .= " ON CONFLICT (name) DO UPDATE SET ";
  2611.                 foreach ($wflTemplate as $key => $value) {
  2612.                     if ($key == 'id') {
  2613.                         continue;
  2614.                     }
  2615.                     //se Ã¨ acm non ha template e scorro tutta la checklist fino ai ruoli.
  2616.                     if ($key == "roles") {
  2617.                         break;
  2618.                     }
  2619.                     if ($key == 'data_modifica') {
  2620.                         $sql .= "data_modifica = now(),";
  2621.                         continue;
  2622.                     }
  2623.                     if ($key == 'data_creazione') {
  2624.                         if ($value == '') {
  2625.                             $sql .= "data_creazione = now(),";
  2626.                         } else {
  2627.                             $sql .= "data_creazione = '" . $value . "',";
  2628.                         }
  2629.                         continue;
  2630.                     }
  2631.                     if ($key == 'creato_da') {
  2632.                         if ($value == '') {
  2633.                             $sql .= "creato_da = $userId,";
  2634.                         } else {
  2635.                             $sql .= "creato_da = " . $value . ",";
  2636.                         }
  2637.                         continue;
  2638.                     }
  2639.                     if ($key == 'modificato_da') {
  2640.                         $sql .= "modificato_da = $userId,";
  2641.                         continue;
  2642.                     }
  2643.                     if ($key == 'locked') {
  2644.                         if ($value == '') {
  2645.                             $sql .= "locked = 0,";
  2646.                         } else {
  2647.                             $sql .= "locked = " . $value . ",";
  2648.                         }
  2649.                         continue;
  2650.                     }
  2651.                     $sql .= $key . " = '" . $value . "',";
  2652.                 }
  2653.                 if (substr($sql, -1) == ",") {
  2654.                     $sql = substr($sql, 0, -1);
  2655.                 }
  2656.                 $statement = $connection->prepare($sql);
  2657.                 $statement->execute();
  2658.                 //RECUPERO L'ID DELLA CHECKLIST APPENA INSERITA O AGGIORNATA
  2659.                 $sql = "select id
  2660.                       from chklst_template
  2661.                       where name = '" . $checklist['name'] . "'";
  2662.                 $statement = $connection->prepare($sql);
  2663.                 $statement->execute();
  2664.                 $id_checklist = $statement->fetchAll()[0]['id'];                
  2665.                 // INSERISCO EX NOVO I RUOLI DELLA CHECKLIST VERIFICANDO CHE ESISTANO, ALTRIMENTI LI CREO
  2666.                 if (is_array($checklist['roles'])) {
  2667.                     $sql = "delete from chklst_template_role
  2668.                           where id_template = $id_checklist";
  2669.                     $statement = $connection->prepare($sql);
  2670.                     $statement->execute();
  2671.                     foreach ($checklist['roles'] as $role) {
  2672.                         // VERIFICO SE IL RUOLO ESISTE NEL DB
  2673.                         $sql = "select count(1) cnt
  2674.                                 from roles
  2675.                                 where description_roles=:description_roles";
  2676.                         $statement = $connection->prepare($sql);
  2677.                         $statement->bindValue('description_roles', $role['description_roles']);
  2678.                         $statement->execute();
  2679.                         $cnt_role = $statement->fetchAll()[0]['cnt'];
  2680.                         $logger->debug("cnt_role: " . $cnt_role);
  2681.                         if ($cnt_role == 0) { //IL RUOLO NON ESISTE NEL DB, LO CREO
  2682.                             
  2683.                             $sql = "insert into roles (description_roles, note)
  2684.                                     values (:description_roles, 'imported')";
  2685.                             $statement = $connection->prepare($sql);
  2686.                             $statement->bindValue('description_roles', $role['description_roles']);
  2687.                             $statement->execute();
  2688.                             $em->flush();
  2689.                         }
  2690.                         // RECUPERO L'ID DEL RUOLO
  2691.                         $sql = "select id_roles
  2692.                                 from roles
  2693.                                 where description_roles=:description_roles";
  2694.                         $statement = $connection->prepare($sql);
  2695.                         $statement->bindValue('description_roles', $role['description_roles']);
  2696.                         $statement->execute();
  2697.                         $id_role = $statement->fetchAll()[0]['id_roles'];
  2698.                         $logger->debug("id_role: " . $id_role);
  2699.                         // Associa il ruolo importato all'utente corrente se non Ã¨ già stato fatto
  2700.                         $sql = "select 1 from user_profile_roles where id_user = $userId and id_roles = $id_role";
  2701.                         $statement = $connection->prepare($sql);
  2702.                         $statement->execute();
  2703.                         if (!$statement->fetchOne()) {
  2704.                             $sql = 
  2705.                                 "insert into user_profile_roles (id_user, id_profile, id_roles)
  2706.                                 values ($userId, 1, $id_role)";
  2707.                             $statement = $connection->prepare($sql);
  2708.                             $statement->execute();
  2709.                         }
  2710.                         // INSERISCO L'ASSOCIAZIONE RUOLO-CHECKLIST
  2711.                         $sql = "insert into chklst_template_role (id_template, id_roles)
  2712.                                 values ($id_checklist, $id_role)";
  2713.                         $statement = $connection->prepare($sql);
  2714.                         $statement->execute();
  2715.                         $logger->debug("Importato ruolo " . $role['description_roles'] . " con ID $id_role per la checklist $id_checklist");
  2716.                     }
  2717.                 }
  2718.                 // INSERISCO EX NOVO I PARAMETRI DELLA CHECKLIST con flag_file='N'
  2719.                 if (is_array($checklist['parameters'])) {
  2720.                     $sql = "delete from chklst_template_parameters
  2721.                           where chklst_id = $id_checklist
  2722.                           and flag_file='N'";
  2723.                     $statement = $connection->prepare($sql);
  2724.                     $statement->execute();
  2725.                     foreach ($checklist['parameters'] as $parameter) {
  2726.                         //            $parameter=$checklist['parameters'][$ip];
  2727.                         $sql = "insert into chklst_template_parameters (chklst_id,
  2728.                                                                       param_name,
  2729.                                                                       param_value,
  2730.                                                                       param_type,
  2731.                                                                       flag_file)
  2732.                                                           values (:id_checklist,
  2733.                                                                   :param_name,
  2734.                                                                   :param_value,
  2735.                                                                   :param_type,
  2736.                                                                   :flag_file)";
  2737.                         $statement = $connection->prepare($sql);
  2738.                         $statement->bindValue('id_checklist', $id_checklist);
  2739.                         $statement->bindValue('param_name', $parameter['param_name']);
  2740.                         $statement->bindValue('param_value', $parameter['param_value']);
  2741.                         $statement->bindValue('param_type', $parameter['param_type']);
  2742.                         $statement->bindValue('flag_file', $parameter['flag_file']);
  2743.                         $statement->execute();
  2744.                     }
  2745.                 }
  2746.                 // INSERISCO EX NOVO I PARAMETRI FILE DELLA CHECKLIST con flag_file='Y'
  2747.                 if (is_array($checklist['parameters_files'])) {
  2748.                     $sql = "delete from chklst_template_parameters
  2749.                           where chklst_id = $id_checklist
  2750.                           and flag_file='Y'";
  2751.                     $statement = $connection->prepare($sql);
  2752.                     $statement->execute();
  2753.                     $sql = "delete from chklst_template_parameters_files
  2754.                           where chklst_id = $id_checklist";
  2755.                     $statement = $connection->prepare($sql);
  2756.                     $statement->execute();
  2757.                     foreach ($checklist['parameters_files'] as $parameter_files) {
  2758.                         //    $parameter_files=$checklist['parameters_files'][$ipf];
  2759.                         $sql = "insert into chklst_template_parameters_files (chklst_id,
  2760.                                                                       param_name,
  2761.                                                                       param_file_name,
  2762.                                                                       param_file_path,
  2763.                                                                       param_file_type)
  2764.                                                           values (:id_checklist,
  2765.                                                                   :param_name,
  2766.                                                                   :param_file_name,
  2767.                                                                   :param_file_path,
  2768.                                                                   :param_file_type)";
  2769.                         $statement = $connection->prepare($sql);                        
  2770.                         $statement->bindValue('id_checklist', $id_checklist);
  2771.                         $statement->bindValue('param_name', $parameter_files['param_name']);
  2772.                         $statement->bindValue('param_file_name', $parameter_files['param_file_name']);
  2773.                         $statement->bindValue('param_file_path', $parameter_files['param_file_path']);
  2774.                         $statement->bindValue('param_file_type', $parameter_files['param_file_type']);
  2775.                         $statement->execute();
  2776.                         
  2777.                         /*
  2778.                         //INSERISCO IL PARAMETRO DI TIPO STRINGA param_name
  2779.                         $sql = "insert into chklst_template_parameters (chklst_id,
  2780.                                                                       param_name,
  2781.                                                                       param_value,
  2782.                                                                       param_type,
  2783.                                                                       flag_file)
  2784.                                                           values (:id_checklist,
  2785.                                                                   :param_name,
  2786.                                                                   :param_file_name,
  2787.                                                                   'string',
  2788.                                                                   'Y')";
  2789.                         $statement = $connection->prepare($sql);
  2790.                         $statement->bindValue('id_checklist', $id_checklist);
  2791.                         $statement->bindValue('param_name', $parameter_files['param_name']);
  2792.                         $statement->bindValue('param_file_name', $parameter_files['param_file_name']);
  2793.                         $statement->execute();*/
  2794.                         //INSERISCO IL PARAMETRO DI TIPO FILE param_name.filename
  2795.                         $sql = "insert into chklst_template_parameters (chklst_id,
  2796.                                                                       param_name,
  2797.                                                                       param_value,
  2798.                                                                       param_type,
  2799.                                                                       flag_file)
  2800.                                                           values (:id_checklist,
  2801.                                                                   :param_name,
  2802.                                                                   :param_file_name,
  2803.                                                                   'file',
  2804.                                                                   'Y')";
  2805.                         $statement = $connection->prepare($sql);                        
  2806.                         $statement->bindValue('id_checklist', $id_checklist);
  2807.                         $statement->bindValue('param_name', $parameter_files['param_name'] . '.filename');
  2808.                         $statement->bindValue('param_file_name', $parameter_files['param_file_name']);
  2809.                         $statement->execute();
  2810.                         //INSERISCO IL PARAMETRO DI TIPO FILE param_name.file
  2811.                         $sql = "insert into chklst_template_parameters (chklst_id,
  2812.                                                                       param_name,
  2813.                                                                       param_value,
  2814.                                                                       param_type,
  2815.                                                                       flag_file)
  2816.                                                           values (:id_checklist,
  2817.                                                                   :param_name,
  2818.                                                                   :param_file_name,
  2819.                                                                   'file',
  2820.                                                                   'Y')";
  2821.                         $statement = $connection->prepare($sql);
  2822.                         $statement->bindValue('id_checklist', $id_checklist);
  2823.                         $statement->bindValue('param_name', $parameter_files['param_name'] . '.file');
  2824.                         $statement->bindValue('param_file_name', $parameter_files['param_file_name']);
  2825.                         $statement->execute();
  2826.                         //INSERISCO IL PARAMETRO DI TIPO FILE param_name.content
  2827.                         $sql = "insert into chklst_template_parameters (chklst_id,
  2828.                                                                       param_name,
  2829.                                                                       param_value,
  2830.                                                                       param_type,
  2831.                                                                       flag_file)
  2832.                                                           values (:id_checklist,
  2833.                                                                   :param_name,
  2834.                                                                   :param_file_name,
  2835.                                                                   'file',
  2836.                                                                   'Y')";
  2837.                         $statement = $connection->prepare($sql);
  2838.                         $statement->bindValue('id_checklist', $id_checklist);
  2839.                         $statement->bindValue('param_name', $parameter_files['param_name'] . '.content');
  2840.                         $statement->bindValue('param_file_name', $parameter_files['param_file_name']);
  2841.                         $statement->execute();
  2842.                         // IMPORTO I FILE NEL CASO DI PACCHETTO .ACM
  2843.                         if ($path_parts['extension'] == "sybot" || $path_parts['extension'] == "acm") {
  2844.                             $imp_dir = $dir_zip . '/' . $checklist['name'] . '/uploads/';
  2845.                             $imp_file = $imp_dir . $parameter_files['param_file_name'];
  2846.                             $up_dir = $params->get('kernel.project_dir') . '/uploads/' . $id_checklist . '/';
  2847.                             if (!is_dir($up_dir)) {
  2848.                                 mkdir($up_dir, 0777, true);
  2849.                             }
  2850.                             $up_file = $up_dir . $parameter_files['param_file_name'];
  2851.                             $logger->debug("file imp: " . $imp_file . " - file upload: " . $up_file);
  2852.                             copy($imp_file, $up_file);
  2853.                         }
  2854.                     }
  2855.                 }
  2856.                 // INSERISCO EX NOVO IL WORKFLOW FILE
  2857.                 if (is_array($checklist['workflow_file'])) {
  2858.                     $sql = "delete from chklst_template_workflow_files
  2859.                           where chklst_id = $id_checklist";
  2860.                     $statement = $connection->prepare($sql);
  2861.                     $statement->execute();
  2862.                     foreach ($checklist['workflow_file'] as $workflow_file) {
  2863.                         //    $workflow_file=$checklist['workflow_file'][$ip];
  2864.                         $sql = "insert into chklst_template_workflow_files (chklst_id,
  2865.                                                                       param_name,
  2866.                                                                       param_file_name,
  2867.                                                                       param_file_path,
  2868.                                                                       param_file_type,
  2869.                                                                       wf_description)
  2870.                                                           values (:id_checklist,
  2871.                                                                   :param_name,
  2872.                                                                   :param_file_name,
  2873.                                                                   :param_file_path,
  2874.                                                                   :param_file_type,
  2875.                                                                   :wf_description)";
  2876.                         $statement = $connection->prepare($sql);
  2877.                         $statement->bindValue('id_checklist', $id_checklist);
  2878.                         $statement->bindValue('param_name', $workflow_file['param_name']);
  2879.                         $statement->bindValue('param_file_name', $workflow_file['param_file_name']);
  2880.                         $statement->bindValue('param_file_path', $workflow_file['param_file_path']);
  2881.                         $statement->bindValue('param_file_type', $workflow_file['param_file_type']);
  2882.                         $statement->bindValue('wf_description', $workflow_file['param_file_type']);
  2883.                         $statement->execute();
  2884.                         // IMPORTO I WF_FILE NEL CASO DI PACCHETTO .ACM
  2885.                         if ($path_parts['extension'] == "sybot" || $path_parts['extension'] == "acm") {
  2886.                             $imp_wf_dir = $dir_zip . '/' . $checklist['name'] . '/wf_uploads/';
  2887.                             $imp_wf_file = $imp_wf_dir . $workflow_file['param_file_name'];
  2888.                             $up_wf_dir = $params->get('kernel.project_dir') . '/public/wf_uploads/' . $id_checklist . '/';
  2889.                             if (!is_dir($up_wf_dir)) {
  2890.                                 mkdir($up_wf_dir, 0777, true);
  2891.                             }
  2892.                             $up_wf_file = $up_wf_dir . $workflow_file['param_file_name'];
  2893.                             if (file_exists($imp_wf_file)) {
  2894.                                 $logger->debug("wf_file imp: " . $imp_wf_file . " - wf_file upload: " . $up_wf_file);
  2895.                                 copy($imp_wf_file, $up_wf_file);
  2896.                             }
  2897.                         }
  2898.                     }
  2899.                 }
  2900.                 //====================================================
  2901.                 // INSERISCO O AGGIORNO I TASK
  2902.                 //====================================================
  2903.                 $taskList = [];
  2904.                 if (is_array($checklist['tasks'])) {
  2905.                     //PULISCO LA TABELLA pre_chklsttmpl2task PER LA CHECKLIST CHE STO IMPORTANDO
  2906.                     $sql = "delete
  2907.                         from pre_chklsttmpl2task
  2908.                         where chklsttmpl_id = $id_checklist";
  2909.                     $statement = $connection->prepare($sql);
  2910.                     $statement->execute();
  2911.                     
  2912.                     $sql = "delete from task_conditional where id_template=$id_checklist";
  2913.                     $statement = $connection->prepare($sql);
  2914.                     $statement->execute();
  2915.                     foreach ($checklist['tasks'] as $tasks) {
  2916.                         $task = $isSybot ? $tasks['task'] : $tasks;
  2917.                         $taskObj = $isSybot ? $tasks : $tasks;
  2918.                         $taskList[$task['id']] = [];
  2919.                         $taskList[$task['id']]["name"] = $task["name"];
  2920.                         $taskList[$task['id']]["cmdType"] = $task["cmd_type"];
  2921.                         // se Il Task Ã¨ condiviso, salto delete/insert task e reinserisco solo in pre_
  2922.                         $sql = "DELETE FROM task
  2923.                                 WHERE id = :taskId
  2924.                                 AND NOT EXISTS (
  2925.                                     SELECT * 
  2926.                                     FROM pre_chklsttmpl2task 
  2927.                                     WHERE task_id = :taskId
  2928.                                 )";
  2929.                         $statement = $connection->prepare($sql);
  2930.                         $statement->bindValue(":taskId", $task['id'],);
  2931.                         $statement->execute();
  2932.                         if (!array_key_exists('config_json', $task) || $task['config_json'] == "") {
  2933.                             $task['config_json'] = [];
  2934.                             if(!$isSybot && $task['cmd_type'] == "ssh") {
  2935.                                 if($task['cmd_text'] == "ssh <user>@<ip_address>"){
  2936.                                     $task['config_json'] = ['operation'=> "connection"];
  2937.                                 } else {
  2938.                                     $task['config_json'] = ['operation'=> "command"];
  2939.                                 }
  2940.                             }
  2941.                         }
  2942.                         $sql = "insert into task (";
  2943.                         foreach ($task as $key => $value) {
  2944.                             if ($key == '@key') {
  2945.                                 continue;
  2946.                             }
  2947.                             if ($key == 'servers') {
  2948.                                 break;
  2949.                             }                            
  2950.                             if ($key == 'id') {
  2951.                                 continue;
  2952.                             }
  2953.                             if ($key == 'task_order') {
  2954.                                 continue;
  2955.                             }
  2956.                         
  2957.                             
  2958.                             $sql .= $key . ",";
  2959.                         }
  2960.                         if(!$isSybot){
  2961.                             $sql .= " config_json,"; //aggiungo config_json se sto importando da ACM
  2962.                         }
  2963.                         
  2964.                         $sql = substr($sql, 0, -1);
  2965.                         $sql .= ") values (";
  2966.                         foreach ($task as $key => $value) {
  2967.                             if ($key == '@key') {
  2968.                                 continue;
  2969.                             }
  2970.                             if ($key == 'servers') {
  2971.                                 break;
  2972.                             }                                
  2973.                             if ($key == 'id') {
  2974.                                 continue;
  2975.                             }
  2976.                             if ($key == 'task_order') {
  2977.                                 continue;
  2978.                             }
  2979.                             
  2980.                             $sql .= ":" . $key . ",";
  2981.                         }
  2982.                         if(!$isSybot){
  2983.                             $sql .= " :config_json,"; //aggiungo placeholder :config_json se sto importando da ACM
  2984.                         }
  2985.                         $sql = substr($sql, 0, -1);
  2986.                         $sql .= ")";
  2987.                         $statement = $connection->prepare($sql);
  2988.                         //todo fare if con le colonne intero e se null mettere 0
  2989.                         foreach ($task as $key => $value) {
  2990.                             if ($key == '@key') {
  2991.                                 continue;
  2992.                             }
  2993.                                                             
  2994.                             if ($key == 'id') {
  2995.                                 continue;
  2996.                             }
  2997.                             if ($key == 'task_order') {
  2998.                                 continue;
  2999.                             }
  3000.                         
  3001.                             if ($key == 'cmd_max_retry') {
  3002.                                 $intV = (int)$value;
  3003.                                 $statement->bindValue($key, $intV);
  3004.                                 continue;
  3005.                             }
  3006.                             if ($key == 'cmd_time_retry') {
  3007.                                 $intV = (int)$value;
  3008.                                 $statement->bindValue($key, $intV);
  3009.                                 continue;
  3010.                             }
  3011.                             if ($key == 'creato_da') {
  3012.                                 $intV = (int)$value;
  3013.                                 $statement->bindValue($key, $intV);
  3014.                                 continue;
  3015.                             }
  3016.                             if ($key == 'modificato_da') {
  3017.                                 $intV = (int)$userId;
  3018.                                 $statement->bindValue($key, $intV);
  3019.                                 continue;
  3020.                             }
  3021.                             if ($key == 'data_modifica') {
  3022.                                 $dt = date('Y-m-d H:i:s');
  3023.                                 $statement->bindValue($key, $dt);
  3024.                                 continue;
  3025.                             }
  3026.                             if ($key == 'data_creazione') {
  3027.                                 $dt = date('Y-m-d H:i:s');
  3028.                                 $statement->bindValue($key, $dt);
  3029.                                 continue;
  3030.                             }
  3031.                             if($key == "id_message_uccx") {
  3032.                                 $intV = (int)$value;
  3033.                                 $statement->bindValue($key, $intV);
  3034.                                 continue;
  3035.                             }
  3036.                             if ($key == 'servers') {
  3037.                                 break;
  3038.                             }
  3039.                             $statement->bindValue($key, $value);
  3040.                         }
  3041.                         if(!$isSybot && $task["config_json"]) {
  3042.                             $statement->bindValue('config_json', $task['config_json'],Types::JSON);
  3043.                         }
  3044.                         // $logger->debug("[importChecklistAction] sql task: " . $sql);
  3045.                         $statement->execute();
  3046.                         //RECUPERO L'ID DELLA CHECKLIST APPENA INSERITA O AGGIORNATA
  3047.                         $id_task = $connection->lastInsertId();
  3048.                         
  3049.                         $taskList[$task['id']]["newId"] = $id_task;
  3050.                         // INSERISCO I TASK NELLA pre_chklsttmpl2task
  3051.                         $sql = "insert into pre_chklsttmpl2task (chklsttmpl_id, task_id, task_order)
  3052.                             values ($id_checklist, $id_task, " . $task['task_order'] . ")";
  3053.                         $statement = $connection->prepare($sql);
  3054.                         $statement->execute();
  3055.                         if (is_array($taskObj['servers'])) {
  3056.                             //PULISCO LA TABELLA TASK2SERVER PER IL TASK CHE STO IMPORTANDO
  3057.                             $sql = "delete
  3058.                                 from task2server
  3059.                                 where task_id = :id_task";
  3060.                             $statement = $connection->prepare($sql);
  3061.                             $statement->bindValue('id_task', $id_task);
  3062.                             $statement->execute();
  3063.                             // INSERISCO O AGGIORNO I SERVER USANDO COME CHIAVE IP-USERNAME
  3064.                             foreach ($taskObj['servers'] as $server) {
  3065.                                 
  3066.                                 //------------------------------------------------------------------------------------------
  3067.                                 // Se l'importazione Ã¨ di tipo acm, usiamo il vecchio metodo di decodificazione password
  3068.                                 //------------------------------------------------------------------------------------------
  3069.                                 if($isSybot){
  3070.                                     $serverPassword = $server['password'];
  3071.                                 } else {
  3072.                                     $acmPassword  = utf8_decode(hex2bin(utf8_decode(base64_decode($server['password']))));
  3073.                                     $serverPassword = $functions->encrypt($acmPassword);
  3074.                                 }
  3075.                                 $sql = "insert into server (hostname, ip_address, username, group_name, password)
  3076.                                     values (:hostname,
  3077.                                             :ip_address,
  3078.                                             :username,
  3079.                                             :group_name,
  3080.                                             :password)";
  3081.                                 $statement = $connection->prepare($sql);
  3082.                                 $statement->bindValue('hostname', $server['hostname'] );
  3083.                                 $statement->bindValue('ip_address', $server['ip_address']);
  3084.                                 $statement->bindValue('username', $server['username']);
  3085.                                 $statement->bindValue('group_name', $server['group_name']);
  3086.                                 $statement->bindValue('password', $serverPassword);
  3087.                                 $statement->execute();
  3088.                                 //RECUPERO L'ID DEL SERVER APPENA INSERITO O AGGIORNATO
  3089.                                 
  3090.                                 $id_server = $connection->lastInsertId();
  3091.                                 //INSERISCO NELLA TASK2SERVER LA RIGA RELATIVA AL TASK E AL SERVER CHE STO IMPORTANDO
  3092.                                 $sql = "insert into task2server (task_id, server_id, server_order, flag_use_password)
  3093.                                         values (:id_task,
  3094.                                                 :id_server,
  3095.                                                 :server_order,
  3096.                                                 :flag_use_password)";
  3097.                                 $statement = $connection->prepare($sql);
  3098.                                 $statement->bindValue('id_task', $id_task );
  3099.                                 $statement->bindValue('id_server', $id_server );
  3100.                                 $statement->bindValue('server_order', $server['server_order'] );
  3101.                                 $statement->bindValue('flag_use_password', $server['flag_use_password'] );
  3102.                                 $statement->execute();
  3103.                             }
  3104.                         }
  3105.                         if (is_array($taskObj['select']['fields'])) {
  3106.                             //CANCELLO I SELECT FIELDS PER IL TASK CHE STO IMPORTANDO
  3107.                             $sql = "delete from task_select_fields where task_id=$id_task";
  3108.                             $statement = $connection->prepare($sql);
  3109.                             $statement->execute();
  3110.                             //CANCELLO LA SELECT FROM PER IL TASK CHE STO IMPORTANDO
  3111.                             $sql = "delete from task_select_from where task_id=$id_task";
  3112.                             $statement = $connection->prepare($sql);
  3113.                             $statement->execute();
  3114.                             //INSERISCO I SELECT FIELDS PER IL TASK CHE STO IMPORTANDO
  3115.                             foreach ($taskObj['select']['fields'] as $field) {
  3116.                                 if (count($taskObj['select']['fields']) < 1) {
  3117.                                     break;
  3118.                                 }
  3119.                                 $sql = "insert into task_select_fields (task_id,
  3120.                                                                     field_name,
  3121.                                                                     field_value,
  3122.                                                                     field_type,
  3123.                                                                     field_precision,
  3124.                                                                     field_id)
  3125.                                                     values (:id_task,
  3126.                                                             :field_name,
  3127.                                                             :field_value,
  3128.                                                             :field_type,
  3129.                                                             :field_precision,
  3130.                                                             :field_id)";
  3131.                                 $statement = $connection->prepare($sql);
  3132.                                 $statement->bindValue('id_task', $id_task );
  3133.                                 $statement->bindValue('field_name', $field['field_name'] );
  3134.                                 $statement->bindValue('field_value', $field['field_value'] );
  3135.                                 $statement->bindValue('field_type', $field['field_type'] );
  3136.                                 $statement->bindValue('field_precision', $field['field_precision'] );
  3137.                                 $statement->bindValue('field_id', $field['field_id'] );
  3138.                                 $statement->execute();
  3139.                             }
  3140.                             //INSERISCO LA SELECT FROM PER IL TASK CHE STO IMPORTANDO
  3141.                             if(!empty($taskObj['select']['from'])) {
  3142.                                 $fromValue = $taskObj['select']['from']['from_value'];
  3143.                                 $sql = "insert into task_select_from (task_id, from_value)
  3144.                                             values (:id_task, :fromValue)";
  3145.                                 $statement = $connection->prepare($sql);
  3146.                                 $statement->bindValue("id_task", $id_task);
  3147.                                 $statement->bindValue('fromValue', $fromValue);
  3148.                                 $statement->execute();
  3149.                             }    
  3150.                         }
  3151.                     
  3152.                         if (isset($taskObj['conditions'])) {                        
  3153.                             try {
  3154.                                 
  3155.                                 $logger->debug(json_encode($taskObj['conditions']) . "\n\n");
  3156.                                 $conditions = $taskObj['conditions'];
  3157.                                 foreach ($conditions as $condition) 
  3158.                                 {
  3159.                                     $sql = "insert into task_conditional (id_task, nome, tipo, espressione, id_template, order_id) values (:id_task, :nome, :tipo, :espressione, :id_template, :order_id)";
  3160.                                     $statement = $connection->prepare($sql);
  3161.                                     $statement->bindValue("id_task", $id_task);
  3162.                                     $statement->bindValue("nome", $condition['nome']);
  3163.                                     $statement->bindValue("tipo", $condition['tipo']);
  3164.                                     $statement->bindValue("espressione", $condition['espressione']);
  3165.                                     $statement->bindValue("id_template", $id_checklist);
  3166.                                     $statement->bindValue("order_id",  $condition['order_id']);
  3167.                                     $ok = $statement->execute();
  3168.                                     $logger->debug("OK? " . ($ok ? 'true' : 'false'));
  3169.                                 }
  3170.                                 
  3171.                             } catch (\Throwable $ex) {
  3172.                                 $logger->debug(">>>>>> ERRORE: " . $ex->getMessage());
  3173.                             }
  3174.                         }
  3175.                     }
  3176.                 }
  3177.                 /****************  INIZIO INTEGRAZIONE DESIGNER  *********************/
  3178.                 
  3179.                 
  3180.                 $sql = "delete from chklst_jflow where chklst_template = $id_checklist";
  3181.                 $statement = $connection->prepare($sql);
  3182.                 $statement->execute();
  3183.             //    $jflow = $isSybot ? $checklist['jflow'] : $checklist['json_flow'];
  3184.                 $jflow = $checklist['jflow'];
  3185.                 if (count($jflow) > 0) {                    
  3186.             
  3187.                     if(!$isSybot) 
  3188.                     {                        
  3189.                         // Due array associativi ci aiuteranno tra poco nella
  3190.                         // handleACMJflowToSybot()
  3191.                         $tasksById = array();
  3192.                         $tasksByName = array();
  3193.                         
  3194.                         foreach ($checklist['tasks'] as $task) 
  3195.                         {
  3196.                             if($task['hidden']==1){
  3197.                                 continue;
  3198.                             }
  3199.                             
  3200.                             $tasksById[$task['id']] = $task;
  3201.                             $tasksByName[$task['name']] = $task;
  3202.                         }
  3203.                         
  3204.                         $jflowData = $this->handleACMJflowToSybot($tasksById, $tasksByName, $logger, $jflow["json_flow"], $id_checklist, $taskList, $connection);
  3205.                         $jflow["json_flow"] = $jflowData;
  3206.                     }
  3207.                     if($isSybot) {
  3208.                         //$logger->debug(">>>>>>> json_flow [" . $jflow["json_flow"] . "]");
  3209.                         $j = json_decode($jflow["json_flow"], true);
  3210.                         $jflowRemapper = new JFlowRemapper();
  3211.                         $jflowRemapper->go($j, $logger, $connection);
  3212.                         $nda = $j["nodeDataArray"];
  3213.                         $lda = $j["linkDataArray"];
  3214.                         $newNda = [];
  3215.                         $newLda = [];
  3216.                         $index = 1;
  3217.                         foreach ($taskList as $it) {
  3218.                             $newTaskList[$it["newId"]] = $it;
  3219.                         }
  3220.                         
  3221.                         foreach ($nda  as $node) {
  3222.                             if($node["category"]=="CommentGroup"){
  3223.                                 $newNda[] = $node;
  3224.                                 continue;
  3225.                             }
  3226.                             $key = $node["key"];
  3227.                             $key = str_replace("[TASK ","", $key);
  3228.                             $key = str_replace("]","", $key);
  3229.                             $split = explode("_", $key);
  3230.                             $oldIdTemplate = $split[0];
  3231.                             $oldIdTask = $split[1];
  3232.                             $cmdTypeId = $split[2];
  3233.                             $newIdTask = $taskList[$oldIdTask]["newId"];
  3234.                             $newIdTemplate = $id_checklist;
  3235.                             $node["key"] = "[TASK " . $newIdTemplate . "_" . $newIdTask . "_" . $cmdTypeId . "]";
  3236.                             
  3237.                             $newTask = $newTaskList[$newIdTask];
  3238.                             $newRightArray = [];
  3239.                             foreach ($node["rightArray"] as $array) {
  3240.                                 $portId = $array["portId"];
  3241.                                 $split = explode("_", $portId);
  3242.                                 $oldTaskId = $split[2];
  3243.                                 $index = $split[3];
  3244.                                 if(isset($taskList[$oldTaskId])) {
  3245.                                     $newTaskId = $taskList[$oldTaskId]["newId"];
  3246.                                     $array["portId"] = "port_" . $newIdTemplate . "_" . $newTaskId . "_" . $index;
  3247.                                 }
  3248.                                 $newRightArray[] = $array;
  3249.                             }
  3250.                             $node["rightArray"] = $newRightArray;
  3251.    
  3252.                             $newNda[] = $node;
  3253.                         }
  3254.                         $j["nodeDataArray"] = $newNda;
  3255.                         foreach ($lda as $key => $link) {
  3256.                             $key = $link["from"];
  3257.                             $key = str_replace("[TASK ","", $key);
  3258.                             $key = str_replace("]","", $key);
  3259.                             $split = explode("_", $key);
  3260.                             $oldIdTemplate = $split[0];
  3261.                             $oldIdTask = $split[1];
  3262.                             $cmdTypeId = $split[2];
  3263.                             $newIdTask = $taskList[$oldIdTask]["newId"];
  3264.                             $newIdTemplate = $id_checklist;
  3265.                             $link["from"] = "[TASK " . $newIdTemplate . "_" . $newIdTask . "_" . $cmdTypeId . "]";
  3266.                             $key = $link["to"];
  3267.                             $key = str_replace("[TASK ","", $key);
  3268.                             $key = str_replace("]","", $key);
  3269.                             $split = explode("_", $key);
  3270.                             $oldIdTemplate = $split[0];
  3271.                             $oldIdTask = $split[1];
  3272.                             $cmdTypeId = $split[2];
  3273.                             $newIdTask = $taskList[$oldIdTask]["newId"];
  3274.                             $newIdTemplate = $id_checklist;
  3275.                             $link["to"] = "[TASK " . $newIdTemplate . "_" . $newIdTask . "_" . $cmdTypeId . "]";
  3276.                             $portId = $link["fromPort"];
  3277.                             $split = explode("_", $portId);
  3278.                             $oldTaskId = $split[2];
  3279.                             $index = $split[3];
  3280.                             if(isset($taskList[$oldTaskId])) {
  3281.                                 $newTaskId = $taskList[$oldTaskId]["newId"];
  3282.                                 $link["fromPort"] = "port_" . $newIdTemplate . "_" . $newTaskId . "_" . $index;
  3283.                             }
  3284.                             $newLda[] = $link;
  3285.                         }
  3286.                         $j["linkDataArray"] = $newLda;
  3287.                         $jflow["json_flow"] = json_encode($j);
  3288.                     }
  3289.                     $sql = 'insert into chklst_jflow(';
  3290.                     foreach ($jflow as $key => $value) {
  3291.                         if ($key == '@key') {
  3292.                             continue;
  3293.                         }
  3294.                         if ($key == 'id_chklst_jflow') {
  3295.                             continue;
  3296.                         }
  3297.                         /*if ($key == 'task_validate') {
  3298.                             continue;
  3299.                         }*/
  3300.                         $sql .= $key . ',';
  3301.                     }
  3302.                     if (substr($sql, -1) == ",") {
  3303.                         $sql = substr($sql, 0, -1);
  3304.                     }
  3305.                     $sql .= ') values (';
  3306.                     foreach ($jflow as $key => $value) {
  3307.                         if ($key == '@key') {
  3308.                             continue;
  3309.                         }
  3310.                         if ($key == 'id_chklst_jflow') {
  3311.                             continue;
  3312.                         }
  3313.                         $sql .= ":" . $key . ",";
  3314.                     }
  3315.                     if (substr($sql, -1) == ",") {
  3316.                         $sql = substr($sql, 0, -1);
  3317.                     }
  3318.                     $sql .= ')';
  3319.                     $statement = $connection->prepare($sql);
  3320.                     //bind parameters
  3321.                     foreach ($jflow as $key => $value) {
  3322.                         if ($key == '@key') {
  3323.                             continue;
  3324.                         }
  3325.                         if ($key == 'id_chklst_jflow') {
  3326.                             continue;
  3327.                         }
  3328.                         if ($key == 'chklst_template') {
  3329.                             $statement->bindValue($key, $id_checklist);
  3330.                             continue;
  3331.                         }
  3332.                         $statement->bindValue($key, $value);
  3333.                     }
  3334.                     $statement->execute();
  3335.                 }
  3336.                 /****************  FINE INTEGRAZIONE DESIGNER  *********************/                
  3337.             }
  3338.             
  3339.         }
  3340.         
  3341.         if ($path_parts['extension'] == 'sybot' || $path_parts['extension'] == 'acm') {
  3342.             $res_json->setData(array("id_workflow" => $id_checklist, "workflow" => $checklists, "extension" => $path_parts['extension']));
  3343.         } else {            
  3344.             $res_json->setData(array("id_workflow" => $id_checklist, "workflow" => $checklist, "extension" => $path_parts['extension']));
  3345.         }
  3346.         
  3347.     } catch (\Throwable $ex) {
  3348.         $logger->debug("ERRORE: " . $ex->getMessage() . " LINE " .  $ex->getLine());
  3349.         $res_json->setStatusCode(400);
  3350.         return $res_json;
  3351.     }
  3352.             
  3353.         return $res_json;
  3354.     }
  3355.     
  3356.     private function handleACMJflowToSybot(
  3357.         $acmTasksById,    // id   => task acm (secondo l'id nella checklist ACM)
  3358.         $acmTasksByName,  // nome => task acm
  3359.         $logger, 
  3360.         $jflowRaw, 
  3361.         $idTemplate, 
  3362.         $acmTasksExtraInfo, 
  3363.         $connection) : string
  3364.     {
  3365.         $converter = new ACM2SybotJFlowConverter();
  3366.         return $converter->go($acmTasksById, $acmTasksByName, $logger, $jflowRaw, $idTemplate, $acmTasksExtraInfo, $connection);
  3367.     }
  3368.     
  3369.     public function exportChecklist($id_workflow, LoggerInterface $logger, ParameterBagInterface $params)
  3370.     {
  3371.         // Temporaneo, testing - default al vecchio exporter
  3372.         if ($this->USE_NEW_IMPEXP) {
  3373.             return $this->exportChecklist_new($id_workflow, $logger, $params);
  3374.         } else {
  3375.             return $this->exportChecklist_old($id_workflow, $logger, $params);
  3376.         }
  3377.     }
  3378.     
  3379.     
  3380.     public function exportChecklist_new($id_workflow, LoggerInterface $logger, ParameterBagInterface $params)
  3381.     {
  3382.         
  3383.         $target_dir = $params->get('kernel.project_dir') . '/public/chklst_exports/';
  3384.         $basename = 'Sybot_Workflow_Export_' . time();
  3385.         $export_file = $target_dir . $basename;
  3386.         if (is_string($id_workflow)) {
  3387.             $ids_of_workflows_to_export = explode(",", $id_workflow);
  3388.             $ids_of_workflows_to_export = array_map('trim', $ids_of_workflows_to_export);
  3389.             $ids_of_workflows_to_export = array_filter($ids_of_workflows_to_export, function($id) {
  3390.                 return is_numeric($id);
  3391.             });
  3392.         } else {
  3393.             $ids_of_workflows_to_export = [ $id_workflow ];
  3394.         }
  3395.         try {
  3396.             
  3397.             $exporter = ImpExp\ImpExp::createExporter($this->getDoctrine()->getManager()->getConnection(), $logger);
  3398.             
  3399.             foreach ($ids_of_workflows_to_export as $id) {
  3400.                 $exporter->addWorkflowById($id);
  3401.             }
  3402.             $exporter->toFile($export_file);
  3403.             
  3404.         } catch (\Throwable $ex) {
  3405.             $logger->debug("ERRORE: " . $ex->getMessage() . " LINE " .  $ex->getLine() . " FILE " . $ex->getFile() . " TRACE " . $ex->getTraceAsString());
  3406.             throw $ex;
  3407.         }
  3408.         return $basename . '.sybot';
  3409.     }
  3410.     public function exportChecklist_old($id_workflow, LoggerInterface $logger, ParameterBagInterface $params)
  3411.     {
  3412.         
  3413.         $em = $this->getDoctrine()->getManager();
  3414.         $connection = $em->getConnection();
  3415.         $res_json = new JsonResponse();
  3416.         $target_dir = $params->get('kernel.project_dir') . '/public/chklst_exports/';
  3417.         if (isset($id_workflow)) {
  3418.             $idChecklist = $id_workflow;
  3419.         } else {
  3420.             $idChecklist = 'nn';
  3421.         }
  3422.         if ($idChecklist == 'nn')  //ESPORTO TUTTE LE CHECKLIST
  3423.         {
  3424.             $logger->debug("[exportChecklistAction] id Checklist == nn");
  3425.             $sql = "select *
  3426.                   from chklst_template
  3427.                   where hidden = 0";
  3428.             $statement = $connection->prepare($sql);
  3429.             $statement->execute();
  3430.             $checklists['workflow'] = $statement->fetchAll();  //ARRAY CON TUTTE LE CHECKLIST
  3431.         } else  //ESPORTO LA SINGOLA CHECKLIST PASSATA IN INPUT
  3432.         {
  3433.             $logger->debug("[exportChecklistAction] id Checklist <> nn");
  3434.             $sql = "select *
  3435.                   from chklst_template
  3436.                   where id in($idChecklist)
  3437.                   and hidden = 0";
  3438.             $statement = $connection->prepare($sql);
  3439.             $statement->execute();
  3440.             $checklists['workflow'] = $statement->fetchAll(); //ARRAY CON LA SINGOLA CHECKLIST PASSATA IN INPUT
  3441.         }
  3442.         $zip = new \ZipArchive();
  3443.         $zipName = 'Sybot_Workflow_Export_' . time() . ".zip";
  3444.         $zip->open($target_dir . $zipName,  \ZipArchive::CREATE);
  3445.         $wflTemplates = $checklists['workflow'];
  3446.         for ($i = 0; $i < count($wflTemplates); $i++) {
  3447.             $currentTemplate = $wflTemplates[$i];
  3448.             $currentTemplate["template"] = $currentTemplate;
  3449.             $checklist_name = $currentTemplate['name'];
  3450.             $FileName = "Sybot_Workflow_" . $checklist_name . ".xml";
  3451.             // INIZIO GESTIONE RUOLI CHECKLIST
  3452.             $sql = "select r.description_roles
  3453.               from chklst_template_role cr join roles r on cr.id_roles = r.id_roles
  3454.               where id_template=" . $currentTemplate['id'];
  3455.             $stmt = $em->getConnection()->prepare($sql);
  3456.             $stmt->execute();
  3457.             $checklist_roles = $stmt->fetchAll();
  3458.             $currentTemplate['roles'][] = $checklist_roles;
  3459.             // FINE GESTIONE RUOLI CHECKLIST
  3460.             // RECUPERO I PARAMETRI DELLA CHECKLIST
  3461.             $sql = "select param_name,
  3462.                     param_value,
  3463.                     param_type,
  3464.                     flag_file
  3465.                   from chklst_template_parameters
  3466.                   where flag_file = 'N'
  3467.                   and chklst_id = " . $currentTemplate['id'];
  3468.             $statement = $connection->prepare($sql);
  3469.             $statement->execute();
  3470.             $parameters = $statement->fetchAll();
  3471.             $currentTemplate['parameters'][] = $parameters;
  3472.             // RECUPERO I PARAMETRI FILES DELLA CHECKLIST
  3473.             $sql = "select param_name,
  3474.                     param_file_name,
  3475.                     param_file_path,
  3476.                     param_file_type
  3477.                   from chklst_template_parameters_files
  3478.                   where chklst_id = " . $currentTemplate['id'];
  3479.             $statement = $connection->prepare($sql);
  3480.             $statement->execute();
  3481.             $parameters_files = $statement->fetchAll();
  3482.             $currentTemplate['parameters_files'][] = $parameters_files;
  3483.             // RECUPERO IL WORKFLOW FILE DELLA CHECKLIST
  3484.             $sql = "select param_name,
  3485.                     param_file_name,
  3486.                     param_file_path,
  3487.                     param_file_type,
  3488.                     wf_description
  3489.                   from chklst_template_workflow_files
  3490.                   where chklst_id = " . $currentTemplate['id'];
  3491.             $statement = $connection->prepare($sql);
  3492.             $statement->execute();
  3493.             $wf_file = $statement->fetchAll();
  3494.             $currentTemplate['workflow_file'][] = $wf_file;
  3495.             // RECUPERO I TASK DELLA CHECKLIST
  3496.             $sql = "select ct.task_order, tsk.*
  3497.                     from pre_chklsttmpl2task ct
  3498.                         join task tsk on tsk.id = ct.task_id
  3499.                     where ct.chklsttmpl_id= " . $currentTemplate['id'] . "
  3500.                     order by ct.task_order";
  3501.             $statement = $connection->prepare($sql);
  3502.             $statement->execute();
  3503.             $tasks = $statement->fetchAll();
  3504.             // Recupero il disegno del workflow
  3505.             $sql = "select cj.*
  3506.                     from chklst_jflow cj
  3507.                     where cj.chklst_template = " . $currentTemplate['id'];
  3508.             $statement = $connection->prepare($sql);
  3509.             $statement->execute();
  3510.             $Jflow = $statement->fetchAll();
  3511.             
  3512.             $currentTemplate['jflow'] = $Jflow;
  3513.             $taskServers = [];
  3514.             $taskActions = [];
  3515.             $taskSelect = [];
  3516.             $taskSelect['fields'] = [];
  3517.             $taskSelect['from'] = [];
  3518.             // $currentTemplate['servers'] = [];
  3519.             // $currentTemplate['action'] = [];
  3520.             // $currentTemplate['select'] = [];
  3521.             //$currentTemplate['tasks'] = [];
  3522.             $myTask = [];
  3523.             // RECUPERO I SERVER, LA ACTION, I SELECT FIELDS E LA SELECT FROM DI OGNI TASK
  3524.             for ($it = 0; $it < count($tasks); $it++) {
  3525.                 
  3526.                 $logger->debug("EXPORTO TASK " . json_encode($tasks[$it]));
  3527.                 $myTask[$it]["task"] = $tasks[$it];
  3528.                 
  3529.                 //SERVER DEL TASK
  3530.                 $sql = "select ts.server_order, s.*, ts.flag_use_password
  3531.                             from task2server ts join task tsk on tsk.id = ts.task_id
  3532.                             join server s on ts.server_id=s.id
  3533.                             where tsk.id=" . $tasks[$it]['id'] . "
  3534.                             order by ts.server_order";
  3535.                 $statement = $connection->prepare($sql);
  3536.                 $statement->execute();
  3537.                 $servers = $statement->fetchAll();
  3538.                 $myTask[$it]['servers'][] = $servers;
  3539.                 //SELECT FIELDS
  3540.                 $sql = "select s.field_name,
  3541.                             s.field_value,
  3542.                             s.field_type,
  3543.                             s.field_precision,
  3544.                             s.field_id
  3545.                             from task_select_fields s
  3546.                             where s.task_id=" . $tasks[$it]['id'];
  3547.                 $statement = $connection->prepare($sql);
  3548.                 $statement->execute();
  3549.                 $query_fields = $statement->fetchAll();
  3550.                 $myTask[$it]['select']['fields'][] = $query_fields;
  3551.                 //SELECT FROM
  3552.                 $sql = "select f.from_value
  3553.                             from task_select_from f
  3554.                             where f.task_id=" . $tasks[$it]['id'];
  3555.                 $statement = $connection->prepare($sql);
  3556.                 $statement->execute();
  3557.                 $query_from = $statement->fetchAll();
  3558.                 $myTask[$it]['select']['from'] = $query_from;
  3559.                 $sql = "select nome, tipo, espressione, order_id from task_conditional where id_task = :id_task AND id_template = :id_template";
  3560.                 $statement = $connection->prepare($sql);
  3561.                 $statement->bindValue("id_task", $tasks[$it]['id']);
  3562.                 $statement->bindValue("id_template", $currentTemplate['id']);
  3563.                 $statement->execute();
  3564.                 $conditions = $statement->fetchAll();
  3565.                 $myTask[$it]['conditions'][] = $conditions;
  3566.     
  3567.             }
  3568.                 
  3569.             $currentTemplate['tasks'][] = $myTask;
  3570.             $xmlEncoder = new XmlEncoder(["xml_root_node_name" => "workflow"]);
  3571.             $normalizer = new CustomNormalizer();
  3572.             $serializer = new Serializer(array($normalizer), array($xmlEncoder));
  3573.             $output = $serializer->serialize($currentTemplate, 'xml');
  3574.             $file = fopen($target_dir . $FileName, "w");
  3575.             fwrite($file, $output);
  3576.             fclose($file);
  3577.             //        $files[]=$target_dir . $FileName;
  3578.             $zip->addFromString($currentTemplate['name'] . '/xml/' . basename($target_dir . $FileName),  file_get_contents($target_dir . $FileName));
  3579.             unlink($target_dir . $FileName);
  3580.             // PARAMETER FILE UPLOADATI DELLA CHECKLIST
  3581.             $target_uploads_dir = $params->get('kernel.project_dir') . '/uploads/' . $currentTemplate['id'] . '/';
  3582.             $rootPath_uploads = realpath($target_uploads_dir);
  3583.             $uploaded_files = [];
  3584.             // Create recursive directory iterator
  3585.             /** @var SplFileInfo[] $files */
  3586.             //    $logger->debug('rootPath_uploads '.$checklists['checklist'][$i]['id'].': ' . $rootPath_uploads);
  3587.             if (!$rootPath_uploads) {
  3588.                 $files_uploads = [];
  3589.             } else {
  3590.                 $files_uploads = new \RecursiveIteratorIterator(
  3591.                     new \RecursiveDirectoryIterator($rootPath_uploads),
  3592.                     \RecursiveIteratorIterator::LEAVES_ONLY
  3593.                 );
  3594.                 //INSERISCO NELLO ZIP I PARAMETER FILES DELLA CHECKLIST
  3595.                 foreach ($files_uploads as $name => $file) {
  3596.                     // Skip directories (they would be added automatically)
  3597.                     if (!$file->isDir()) {
  3598.                         // Get real and relative path for current file
  3599.                         $filePath = $file->getRealPath();
  3600.                         $relativePath = substr($filePath, strlen($rootPath_uploads) + 1);
  3601.                         // Add current file to archive
  3602.                         $zip->addFile($filePath, $currentTemplate['name'] . '/uploads/' . $relativePath);
  3603.                         $uploaded_files[] = $relativePath;
  3604.                     }
  3605.                 }
  3606.             }
  3607.             // PARAMETER WORKFLOW FILE UPLOADATI DELLA CHECKLIST
  3608.             $target_wf_uploads_dir = $params->get('kernel.project_dir') . '/public/wf_uploads/' . $currentTemplate['id'] . '/';
  3609.             $rootPath_wf_uploads = realpath($target_wf_uploads_dir);
  3610.             $uploaded_wf_files = [];
  3611.             // Create recursive directory iterator
  3612.             /** @var SplFileInfo[] $files */
  3613.             //    $logger->debug('rootPath_wf_uploads '.$checklists['checklist'][$i]['id'].': ' . $rootPath_wf_uploads);
  3614.             if (!$rootPath_wf_uploads) {
  3615.                 $files_wf_uploads = [];
  3616.             } else {
  3617.                 $files_wf_uploads = new \RecursiveIteratorIterator(
  3618.                     new \RecursiveDirectoryIterator($rootPath_wf_uploads),
  3619.                     \RecursiveIteratorIterator::LEAVES_ONLY
  3620.                 );
  3621.                 //INSERISCO NELLO ZIP I PARAMETER WF FILES DELLA CHECKLIST
  3622.                 foreach ($files_wf_uploads as $name => $file) {
  3623.                     // Skip directories (they would be added automatically)
  3624.                     if (!$file->isDir()) {
  3625.                         // Get real and relative path for current file
  3626.                         $filePath = $file->getRealPath();
  3627.                         $relativePath = substr($filePath, strlen($rootPath_wf_uploads) + 1);
  3628.                         // Add current file to archive
  3629.                         $zip->addFile($filePath, $currentTemplate['name'] . '/wf_uploads/' . $relativePath);
  3630.                         $uploaded_wf_files[] = $relativePath;
  3631.                     }
  3632.                 }
  3633.             }
  3634.             //    $logger->debug('files_uploaded json: ' . json_encode($uploaded_files));
  3635.             //CREO LA STRUTTURA PER IL FILE export.json
  3636.             $export[] = array(
  3637.                 'workflow' => $currentTemplate['name'],
  3638.                 'xml'       => basename($target_dir . $FileName),
  3639.                 'uploads'   => $uploaded_files,
  3640.                 'wf_uploads' => $uploaded_wf_files
  3641.             );
  3642.         }
  3643.         $zip->addFromString('export.json',  json_encode($export, JSON_PRETTY_PRINT));
  3644.         $zip->close();
  3645.         //    $logger->debug('export json: ' . json_encode($export));
  3646.         $cipher = new AES(); // could use AES::MODE_CBC
  3647.         // keys are null-padded to the closest valid size
  3648.         // longer than the longest key and it's truncated
  3649.         //$cipher->setKeyLength(256);
  3650.         //    $cipher->setKey('abcdefghijklmnopqrstuvwxyz123456');
  3651.         $cipher->setKey($_ENV["KEY_SYBOT"]);
  3652.         // the IV defaults to all-NULLs if not explicitly defined
  3653.         //$cipher->setIV(Random::string($cipher->getBlockLength() >> 3));
  3654.         $cipher->setIV($_ENV["IV_SYBOT"]);
  3655.         //$size = 10 * 1024;
  3656.         //$plaintext = str_repeat('a', $size);
  3657.         //$plaintext = base64_encode(file_get_contents($target_dir . $FileName));
  3658.         $encrypted_contents = $cipher->encrypt(base64_encode(file_get_contents($target_dir . $zipName)));
  3659.         $file_export = str_replace('.zip', '.sybot', $zipName);
  3660.         file_put_contents($target_dir . $file_export, $encrypted_contents);
  3661.         unlink($target_dir . $zipName);  //ELIMINO LO ZIP NON CIFRATO
  3662.         //$res_json->setData(array('nome_file' => $file_export));
  3663.         return $file_export;
  3664.     }
  3665.     /***************************************************************************************************************************************
  3666.      ***************************************************** INIZIO GESTIONE API ACM **********************************************************
  3667.      ****************************************************************************************************************************************/
  3668.     public function apiGetChecklistStatusDetailsByRunIdAction(Request $request, LoggerInterface $logger, ParameterBagInterface $params)    //ritorna le informazioni dei task circa l'esecuzione passata in input con il parametro run_id (id tabella chklst)
  3669.     {
  3670.         $csrfToken = $_GET['csrftoken'];
  3671.         if (!$this->isCsrfTokenValid('api_get_checklist_status_details_by_id', $csrfToken)) {
  3672.             throw new \Exception('Csrf token not valid');
  3673.         }
  3674.         session_write_close();
  3675.         $res_json = new JsonResponse();
  3676.         $em = $this->getDoctrine()->getManager();
  3677.         $connection = $em->getConnection();
  3678.         //$logger = $this->getLogger();
  3679.         $db_driver = $params->get('db_driver');
  3680.         if (isset($_GET["run_id"])) {
  3681.             $runIdChk = $_GET["run_id"];
  3682.         } else {
  3683.             /*Parametro run_id assente*/
  3684.             $res_json->setData(array('checklist' => 'N/A', 'tasks' => 'N/A', 'code' => 10, 'status' => 'ERROR', 'error_msg' => 'Mandatory run_id parameter not found in request', 'run_id' => -1, 'response_date' => date("Y-m-d H:i:s")));
  3685.             return  $res_json;
  3686.         }
  3687.         /*controllo se run_id della checklist esiste*/
  3688.         $sql = "select c.id run_id, c.from_template_id checklist_id, c.name checklist_name, c.description checklist_description,
  3689.                  c.run_start run_start, c.run_end run_end, c.run_result run_result
  3690.               from chklst c
  3691.               where c.id = '$runIdChk'";
  3692.         $statement = $connection->prepare($sql);
  3693.         $statement->execute();
  3694.         $result = $statement->fetchAll();
  3695.         if (count($result) == 0) {
  3696.             /*runId della checklist inesistente*/
  3697.             $res_json->setData(array('checklist' => 'N/A', 'tasks' => 'N/A', 'code' => 20, 'status' => 'ERROR',  'error_msg' => 'Invalid CheckList run_id: ' . $runIdChk . '', 'run_id' => -1, 'response_date' => date("Y-m-d H:i:s")));
  3698.             return  $res_json;
  3699.         } else {
  3700.             $runId = $result[0]['run_id'];
  3701.             $run_checklist_name = $result[0]['checklist_name'];
  3702.         }
  3703.         //CONTROLLA SE TOKEN Ã© VALIDO E SE I RUOLI DELLA CHECKLIST CORRISPONDONO
  3704.         if (isset($_GET["token"])) {
  3705.             $token = $_GET["token"];
  3706.             $check_token = $this->checkToken($token, $logger, $params); //0: errore / 1:ok
  3707.         } else {
  3708.             $res_json->setData(array('checklist' => 'N/A', 'tasks' => 'N/A', 'code' => 80, 'status' => 'ERROR', 'error_msg' => 'Mandatory token parameter not found in request', 'run_id' => -1, 'response_date' => date("Y-m-d H:i:s")));
  3709.             return  $res_json;
  3710.         }
  3711.         $q = "select count(*) cnt
  3712.                         from chklst_template ct
  3713.                                     join chklst c on c.from_template_id = ct.id
  3714.                                     join chklst_template_role ctr on ctr.id_template = ct.id
  3715.                                     join (select ur.id_roles
  3716.                                                from user_token ut
  3717.                                                          join user_profile_roles ur on ut.id_user = ur.id_user
  3718.                                               where (ut.token = '$token' or '$token'='010101010101010101010101')
  3719.                                              ) ur on ctr.id_roles = ur.id_roles
  3720.                         where c.id = $runIdChk";
  3721.         $statement = $em->getConnection()->prepare($q);
  3722.         $statement->execute();
  3723.         $ResulQuery = $statement->fetchAll()[0];
  3724.         $checklist_role = $ResulQuery['cnt'];
  3725.         if ($check_token == 0) {
  3726.             $res_json->setData(array('checklist' => 'N/A', 'tasks' => 'N/A', 'code' => 150, 'status' => 'ERROR', 'error_msg' => 'Invalid Token', 'run_id' => -1, 'response_date' => date("Y-m-d H:i:s")));
  3727.             return $res_json;
  3728.         } else if ($check_token != 0 && $checklist_role == 0) {
  3729.             $res_json->setData(array('checklist' => 'N/A', 'tasks' => 'N/A', 'code' => 130, 'status' => 'ERROR', 'error_msg' => 'Invalid User role', 'run_id' => -1, 'response_date' => date("Y-m-d H:i:s")));
  3730.             return $res_json;
  3731.         } else {
  3732.             try {
  3733.                 $sql = "select ct.name task_name, ct.description task_description, upper(ct.cmd_type) task_type,
  3734.                                  ct.cmd_text task_cmd, to_char(ct.run_start, 'dd-mm-yyyy hh24:mi:ss') run_start, 
  3735.                                  coalesce(to_char(ct.run_end, 'dd-mm-yyyy hh24:mi:ss'), '') run_end, ct.run_result, ct.id, t.id task_id, tsf.param_file_name spool_file
  3736.                             ,upper(ct.statement_select) statement_select
  3737.                             from chklst_task ct join task t on ct.task_id=t.id 
  3738.                             left join task_spool_files tsf on t.id=tsf.task_id
  3739.                             where ct.chklst_id='$runId'
  3740.                             order by ct.run_start";
  3741.                 $statement = $connection->prepare($sql);
  3742.                 $statement->execute();
  3743.                 $result_task = $statement->fetchAll();
  3744.                 $Directory = $params->get('projectDir') . '/public/spool_file/checklist_status/' . $runId;
  3745.                 if (!is_dir($Directory)) {
  3746.                     $logger->debug(" Creazione Directory  " . $Directory);
  3747.                     mkdir($Directory, 0775, true);
  3748.                 }
  3749.                 $FilenameSpool = $Directory . '/' . $run_checklist_name . '_' . $runId . '_details.csv';
  3750.                 $logger->debug('File salvataggio  : ' . $FilenameSpool);
  3751.                 $file = fopen($FilenameSpool, "w") or die("Unable to open file!");
  3752.                 fwrite($file, 'task_name;task_description;task_type;task_cmd;run_start;run_end;run_result;id;task_id;spool_file;statement_select' . PHP_EOL);
  3753.                 foreach ($result_task as $row) {
  3754.                     //Write the row to the CSV file.
  3755.                     fputcsv($file, $row, ";");
  3756.                 }
  3757.                 fclose($file);
  3758.                 $data_task_db = [];
  3759.                 foreach ($result_task as $r) {
  3760.                     if ($r['task_type'] == 'DB') {
  3761.                         if ($r['statement_select'] == 'Y') {
  3762.                             $FilenameSpoolJsonQuery = [];
  3763.                             $DirectoryJson = $params->get('projectDir')  . '/public/spool_file/' . $r['task_id'] . '/' . $result[0]['run_id'];
  3764.                             if (is_dir($DirectoryJson)) {
  3765.                                 $FilenameSpoolJsonQuery = $DirectoryJson . '/spool.json';
  3766.                                 $result_db_data_task = json_decode(file_get_contents($FilenameSpoolJsonQuery));
  3767.                                 $data_task_db[$r['id']]['data'] = $result_db_data_task;
  3768.                             }                            
  3769.                             
  3770.                         } else {
  3771.                             $data_task_db[$r['id']]['data'] = $r['run_result'];
  3772.                         }
  3773.                     }
  3774.                 }
  3775.             } catch (\Doctrine\DBAL\Exception\TableNotFoundException $e) {
  3776.                 //    $data_task_db[$r['id']]['data']=null;
  3777.                 $logger->debug('Errore nella select dei risultati del task db ' . $e);
  3778.             }
  3779.             $res_json->setData(array('checklist' => $result, 'tasks' => $result_task, 'code' => 0, 'status' => 'OK',  'error_msg' => '', 'run_id' => $runIdChk, 'response_date' => date("Y-m-d H:i:s"), 'data_db_task' => $data_task_db));
  3780.             return $res_json;
  3781.         }
  3782.     }
  3783.     /***************************************************************************************************************************************
  3784.      ***************************************************** FINE GESTIONE API ACM **********************************************************
  3785.      ****************************************************************************************************************************************/
  3786.     public function checkToken($token, LoggerInterface $logger, ParameterBagInterface $params)
  3787.     {
  3788.         $em = $this->getDoctrine()->getManager();
  3789.         $connection = $em->getConnection();
  3790.         $db_driver = $params->get('db_driver');
  3791.         //$logger = $this->getLogger();
  3792.         $q = "select count(*) cnt
  3793.                     from user_token ut
  3794.                              join user_acm u on ut.id_user = u.id
  3795.                     where sysdate() between ut.date_start_validity and ut.date_end_validity
  3796.                           and ut.check_validity = 'Y'
  3797.                           and u.status = 1::bool
  3798.                           and (ut.token = '$token' or '$token'='010101010101010101010101')";
  3799.         $statement = $em->getConnection()->prepare($q);
  3800.         $statement->execute();
  3801.         $ResulQuery = $statement->fetchAll()[0];
  3802.         $cnt = $ResulQuery['cnt'];
  3803.         if ($cnt == 0) {
  3804.             return 0;
  3805.         } else {
  3806.             return 1;
  3807.         }
  3808.     }
  3809.     public function checklistLogAction(LoggerInterface $logger)
  3810.     {
  3811.         $em = $this->getDoctrine()->getManager();
  3812.         $logger->debug('[checklistLogAction] Start');
  3813.         $user = $this->getUser();
  3814.         $sql = "select * from roles";
  3815.         $stmt = $em->getConnection()->prepare($sql);
  3816.         $stmt->execute();
  3817.         $roles = $stmt->fetchAll();
  3818.         return $this->render(
  3819.             'logWorkflow.html.twig',
  3820.             array(
  3821.                 'logged_user' => $user,
  3822.                 'roles' => $roles
  3823.             )
  3824.         );
  3825.     }
  3826.     public function clonaWorkflowAction(LoggerInterface $logger, ParameterBagInterface $params)
  3827.     {
  3828.         $user = $this->getUser();
  3829.         $userId = $user->getId();
  3830.         $res_json = new JsonResponse();
  3831.         $em = $this->getDoctrine()->getManager();
  3832.         $conn = $em->getConnection();
  3833.         $conn->beginTransaction();
  3834.         $csrftoken= $_POST["csrftoken"];
  3835.         if (!$this->isCsrfTokenValid('clonaWorkflow', $csrftoken)) {
  3836.           throw new \Exception('Csrf token not valid');
  3837.         }
  3838.         if (isset($_POST["clona"]) & isset($_POST["workflowName"]) & isset($_POST["newWorkflowName"])) {
  3839.             $clona = $_POST["clona"];
  3840.             $workflowName = $_POST["workflowName"];
  3841.             $newWorkflowName = trim($_POST["newWorkflowName"]);
  3842.             // -------------------------------------------------------------
  3843.             // Nel caso in cui il nome Ã¨ vuoto, genero un nome di default.
  3844.             // -------------------------------------------------------------
  3845.             if($newWorkflowName == "") {
  3846.                 $newWorkflowName = $workflowName . "_copy_" . date("Ymd_His");
  3847.             }
  3848.             
  3849.         } else {
  3850.             $res_json->setData(array("error" => true));
  3851.             return  $res_json;
  3852.         }
  3853.         if (!preg_match("/^[a-zA-Z0-9_ \-]*$/", $newWorkflowName)) {
  3854.             throw new \Exception('Il campo può contenere solo lettere non accentate, numeri, underscore, spazi e trattini. La lunghezza massima consentita Ã¨ di 45 caratteri');
  3855.         }
  3856.         $logger->debug("[clonaWorkflowAction] Clonazione Workflow:  " . $workflowName . " in " . $newWorkflowName . " Con modalita' " . $clona);
  3857.         try {
  3858.             //----------------------------------------------------------
  3859.             // Inizio copia workflow
  3860.             //----------------------------------------------------------
  3861.             $sql = "select * from chklst_template where name = :workflowName ";
  3862.             $stmt = $conn->prepare($sql);
  3863.             $stmt->bindValue('workflowName', $workflowName);
  3864.             $stmt->execute();
  3865.             $templateToClone = $stmt->fetchAll()[0];
  3866.             $idTemplate = $templateToClone["id"];
  3867.             $sql = "insert into chklst_template (";
  3868.             foreach ($templateToClone as $key => $value) {
  3869.                 if ($key == 'id') {
  3870.                     continue;
  3871.                 }
  3872.                 //se Ã¨ acm non ha template e scorro tutta la checklist fino ai ruoli.
  3873.                 if($key == "roles") {
  3874.                     break;
  3875.                 }
  3876.                 $sql .= $key . ",";
  3877.             }
  3878.             if (substr($sql, -1) == ",") {
  3879.                 $sql = substr($sql, 0, -1);
  3880.             }
  3881.             $sql .= ") values (";
  3882.             foreach ($templateToClone as $key => $value) {
  3883.                 if ($key == 'id') {
  3884.                     continue;
  3885.                 }
  3886.                 //se Ã¨ acm non ha template e scorro tutta la checklist fino ai ruoli.
  3887.                 if($key == "roles") {
  3888.                     break;
  3889.                 }                
  3890.                 
  3891.                 $sql .= ":" . $key . ",";
  3892.             }
  3893.             if (substr($sql, -1) == ",") {
  3894.                 $sql = substr($sql, 0, -1);
  3895.             }
  3896.             $sql .= ")";
  3897.             $statement = $conn->prepare($sql);
  3898.             
  3899.             foreach ($templateToClone as $key => $value) {
  3900.                 if ($key == 'id') {
  3901.                     continue;
  3902.                 }
  3903.                 //se Ã¨ acm non ha template e scorro tutta la checklist fino ai ruoli.
  3904.                 if($key == "roles") {
  3905.                     break;
  3906.                 }
  3907.                 if($key == "name") {
  3908.                     $statement->bindValue('name', $newWorkflowName);
  3909.                     continue;
  3910.                 }                    
  3911.                 if ($key == 'data_creazione') {
  3912.                     if(!$value) {
  3913.                         $statement->bindValue('data_creazione', 'now()');
  3914.                     } else {
  3915.                         $statement->bindValue('data_creazione', $value);
  3916.                     }
  3917.                     
  3918.                     continue;
  3919.                 }                                    
  3920.                 if ($key == 'data_modifica') {
  3921.                     $statement->bindValue('data_modifica', 'now()');
  3922.                     continue;
  3923.                 }
  3924.                 if ($key == 'locked') {
  3925.                     if ($value == '') {
  3926.                         $statement->bindValue('locked', 0);
  3927.                     } else {
  3928.                         $statement->bindValue('locked', $value);
  3929.                     }
  3930.                     continue;
  3931.                 }
  3932.                 
  3933.                 $statement->bindValue($key, $value);
  3934.             }
  3935.             $statement->execute();
  3936.             $logger->debug("[clonaWorkflowAction] Insert into chklst_template andata a buon fine");
  3937.             $sql = "select id from chklst_template where name = :workflowName ";
  3938.             $stmt = $conn->prepare($sql);
  3939.             $stmt->bindValue('workflowName', $newWorkflowName);
  3940.             $stmt->execute();
  3941.             $newIdTemplate = $stmt->fetchAll()[0]["id"];
  3942.             $sql = "select id_template,id_roles from chklst_template_role where id_template = :idTemplate ";
  3943.             $stmt = $conn->prepare($sql);
  3944.             $stmt->bindValue('idTemplate', $idTemplate);
  3945.             $stmt->execute();
  3946.             $templateRolesToClone = $stmt->fetchAll();
  3947.             foreach ($templateRolesToClone as $role) {
  3948.                 $sql = "insert into chklst_template_role ( id_template,id_roles) 
  3949.                                                             values ( :idNewTemplate, :idRole  ) ";
  3950.                 $stmt = $conn->prepare($sql);
  3951.                 $stmt->bindValue('idNewTemplate', $newIdTemplate);
  3952.                 $stmt->bindValue('idRole', $role["id_roles"]);
  3953.                 $stmt->execute();
  3954.             }
  3955.             $logger->debug("[clonaWorkflowAction] Insert into chklst_template_role andata a buon fine");
  3956.             $sql = "select param_name, param_file_name, param_file_path, param_file_type, wf_description 
  3957.                     from chklst_template_workflow_files where chklst_id = :idTemplate ";
  3958.             $stmt = $conn->prepare($sql);
  3959.             $stmt->bindValue('idTemplate', $idTemplate);
  3960.             $stmt->execute();
  3961.             $templateWFileToClone = $stmt->fetchAll();
  3962.             foreach ($templateWFileToClone as $wfile) {
  3963.                 $sql = "insert into chklst_template_workflow_files ( chklst_id, param_name, param_file_name, 
  3964.                         param_file_path, param_file_type, wf_description )
  3965.                         values (
  3966.                             :chklst_id,
  3967.                             :param_name,
  3968.                             :param_file_name,
  3969.                             :param_file_path,
  3970.                             :param_file_type,
  3971.                             :wf_description
  3972.                         ) ";
  3973.                 $stmt = $conn->prepare($sql);
  3974.                 $stmt->bindValue('chklst_id', $newIdTemplate);
  3975.                 $stmt->bindValue('param_name', $wfile['param_name']);
  3976.                 $stmt->bindValue('param_file_name', $wfile['param_file_name']);
  3977.                 $stmt->bindValue('param_file_path', $wfile['param_file_path']);
  3978.                 $stmt->bindValue('param_file_type', $wfile['param_file_type']);
  3979.                 $stmt->bindValue('wf_description', $wfile['wf_description']);
  3980.                 $stmt->execute();
  3981.                 $target_dir = $params->get('kernel.project_dir') . '/public/wf_uploads/' . $newIdTemplate . '/';
  3982.                 if (!file_exists($target_dir)) {
  3983.                     mkdir($target_dir, 0777, true);
  3984.                 }
  3985.                 if ($wfile['param_file_name']) {
  3986.                     $fileToCopy = $wfile['param_file_path'] . $wfile['param_file_name'];
  3987.                     if (trim($fileToCopy, " ") &&  file_exists(trim($fileToCopy, " ")))
  3988.                         copy($fileToCopy, $target_dir . $wfile['param_file_name']);
  3989.                 }
  3990.             }
  3991.             $sql = "select param_name, param_value, param_type, flag_file from chklst_template_parameters where chklst_id = :idTemplate ";
  3992.             $stmt = $conn->prepare($sql);
  3993.             $stmt->bindValue('idTemplate', $idTemplate);
  3994.             $stmt->execute();
  3995.             $templateParamsToClone = $stmt->fetchAll();
  3996.             foreach ($templateParamsToClone as $parameter) {
  3997.                 $sql = "insert into chklst_template_parameters (chklst_id, param_name, param_value, param_type, flag_file)
  3998.                         values ( :chklst_id, :param_name, :param_value, :param_type, :flag_file ) ";
  3999.                 $stmt = $conn->prepare($sql);
  4000.                 $stmt->bindValue('chklst_id', $newIdTemplate);
  4001.                 $stmt->bindValue('param_name', $parameter["param_name"]);
  4002.                 $stmt->bindValue('param_value', $parameter["param_value"]);
  4003.                 $stmt->bindValue('param_type', $parameter["param_type"]);
  4004.                 $stmt->bindValue('flag_file', $parameter["flag_file"]);
  4005.                 $stmt->execute();
  4006.             }
  4007.             $logger->debug("[clonaWorkflowAction] Insert into chklst_template_parameters andata a buon fine");
  4008.             $sql = "select param_name, param_file_name, param_file_path, param_file_type from chklst_template_parameters_files where chklst_id = :idTemplate ";
  4009.             $stmt = $conn->prepare($sql);
  4010.             $stmt->bindValue('idTemplate', $idTemplate);
  4011.             $stmt->execute();
  4012.             $templateParamsFilesToClone = $stmt->fetchAll();
  4013.             //-----------------------------------------------------------
  4014.             // Clonazione dei parametri di tipo file
  4015.             //-----------------------------------------------------------
  4016.             foreach ($templateParamsFilesToClone as $f) {
  4017.                 $sql = "insert into chklst_template_parameters_files ( chklst_id, param_name, param_file_name, param_file_path, param_file_type )
  4018.                         values ( :chklst_id, :param_name, :param_file_name, :param_file_path, :param_file_type )  ";
  4019.                 $stmt = $conn->prepare($sql);
  4020.                 $stmt->bindValue('chklst_id', $newIdTemplate);
  4021.                 $stmt->bindValue('param_name', $f["param_name"]);
  4022.                 $stmt->bindValue('param_file_name', $f["param_file_name"]);
  4023.                 $stmt->bindValue('param_file_path', $f["param_file_path"]);
  4024.                 $stmt->bindValue('param_file_type', $f["param_file_type"]);
  4025.                 $stmt->execute();
  4026.                 $target_dir = $params->get('kernel.project_dir') . '/uploads/' . $newIdTemplate . '/';
  4027.                 if (!file_exists($target_dir)) {
  4028.                     mkdir($target_dir, 0777, true);
  4029.                 }
  4030.                 $fileToCopy = $f['param_file_path'] . $f['param_file_name'];
  4031.                 if ($f['param_file_name']) {
  4032.                     if (trim($fileToCopy, " ") && file_exists(trim($fileToCopy, " ")))
  4033.                         copy($fileToCopy, $target_dir . $f['param_file_name']);
  4034.                 }
  4035.                 $logger->debug("[clonaWorkflowAction] Clonazione parametri file andata a buon fine");
  4036.             }
  4037.         switch ($clona) {
  4038.             case 'clonatutto':
  4039.             //--------------------------------------------------------
  4040.             // inizio copia task
  4041.             //--------------------------------------------------------
  4042.             // prendo tutti i task del vecchio workflow
  4043.             $sql = "select task_id from pre_chklsttmpl2task where chklsttmpl_id = :idTemplate ";
  4044.             $stmt = $conn->prepare($sql);
  4045.             $stmt->bindValue('idTemplate', $idTemplate);
  4046.             $stmt->execute();
  4047.             $tasks = $stmt->fetchAll();
  4048.             $mapTasksId = [];
  4049.             $mapTasksId[""] = "";
  4050.             
  4051.             $mapTasksName = [];
  4052.             $mapTasksName[""] = "";
  4053.             if (count($tasks) > 0) {
  4054.                 //inserisco i task e mappo i vecchi id con i nuovi id
  4055.                 $arrayTasks = array_column($tasks, 'task_id');
  4056.                 $inQuery = implode(',', array_fill(0, count($arrayTasks), '?'));
  4057.                 
  4058.                 $sql = "select * from task where id in (" . $inQuery . ") ";
  4059.                 $stmt = $conn->prepare($sql);
  4060.                 foreach ($arrayTasks as $k => $id)
  4061.                     $stmt->bindValue(($k + 1), $id);
  4062.                 //$stmt->bindValue('tasks', array(array_column($tasks,'task_id')), array(\Doctrine\DBAL\Connection::PARAM_INT_ARRAY));
  4063.                 $stmt->execute();
  4064.                 $allTasks = $stmt->fetchAll();
  4065.                 $i = 1;
  4066.                 foreach ($allTasks as $task) {
  4067.                     // Quick fix!
  4068.                     // TODO: Ci sarebbe da rivedere tutta la logica a valle ma per il momento risolviamo così
  4069.                     // $newTaskName = $newWorkflowName . "_" . $i;
  4070.                     $newTaskName = $task['name'];
  4071.                     
  4072.                     $i += 1;
  4073.                     $sql = "insert into task (";
  4074.                     foreach ($task as $key => $value) {
  4075.                         if ($key == '@key') {
  4076.                             continue;
  4077.                         }
  4078.                         if ($key == 'servers') {
  4079.                             break;
  4080.                         }                            
  4081.                         if ($key == 'id') {
  4082.                             continue;
  4083.                         }
  4084.                         if ($key == 'task_order') {
  4085.                             continue;
  4086.                         }
  4087.                         
  4088.                         $sql .= $key . ",";
  4089.                     }
  4090.                     $sql = substr($sql, 0, -1);
  4091.                     $sql .= ") values (";
  4092.                     foreach ($task as $key => $value) {
  4093.                         if ($key == '@key') {
  4094.                             continue;
  4095.                         }
  4096.                         if ($key == 'servers') {
  4097.                             break;
  4098.                         }                                
  4099.                         if ($key == 'id') {
  4100.                             continue;
  4101.                         }
  4102.                         if ($key == 'task_order') {
  4103.                             continue;
  4104.                         }
  4105.                         
  4106.                         $sql .= ":" . $key . ",";
  4107.                     }
  4108.                     $sql = substr($sql, 0, -1);
  4109.                     $sql .= ")";
  4110.                     $sql .= " on conflict(id) do update SET ";
  4111.                     foreach ($task as $key => $value) {
  4112.                         if ($key == '@key') {
  4113.                             continue;
  4114.                         }
  4115.                         if ($key == 'servers') {
  4116.                             break;
  4117.                         }                                
  4118.                         if ($key == 'id') {
  4119.                             continue;
  4120.                         }
  4121.                         if ($key == 'task_order') {
  4122.                             continue;
  4123.                         }
  4124.                         
  4125.                         $sql .= $key . "=:" . $key . ",";
  4126.                     }
  4127.                     $sql = substr($sql, 0, -1);
  4128.                     $statement = $conn->prepare($sql);
  4129.                     foreach ($task as $key => $value) {
  4130.                         if ($key == '@key') {
  4131.                             continue;
  4132.                         }
  4133.                         if ($key == 'servers') {
  4134.                             break;
  4135.                         }                                
  4136.                         if ($key == 'id') {
  4137.                             continue;
  4138.                         }
  4139.                         if ($key == 'task_order') {
  4140.                             continue;
  4141.                         }
  4142.                         
  4143.                         if ($key == 'cmd_max_retry') {
  4144.                             $intV = (int)$value;
  4145.                             $statement->bindValue($key, $intV);
  4146.                             continue;
  4147.                         }
  4148.                         if ($key == 'cmd_time_retry') {
  4149.                             $intV = (int)$value;
  4150.                             $statement->bindValue($key, $intV);
  4151.                             continue;
  4152.                         }
  4153.                         if ($key == 'creato_da') {
  4154.                             $intV = (int)$value;
  4155.                             $statement->bindValue($key, $intV);
  4156.                             continue;
  4157.                         }
  4158.                         if ($key == 'modificato_da') {
  4159.                             $intV = (int)$userId;
  4160.                             $statement->bindValue($key, $intV);
  4161.                             continue;
  4162.                         }
  4163.                         if ($key == 'data_modifica') {
  4164.                             $dt = date('Y-m-d H:i:s');
  4165.                             $statement->bindValue($key, $dt);
  4166.                             continue;
  4167.                         }
  4168.                         if($key == "name") {
  4169.                             $statement->bindValue($key, $newTaskName);
  4170.                             continue;                            
  4171.                         }
  4172.                         $statement->bindValue($key, $value);
  4173.                     }
  4174.                     $statement->execute();
  4175.                     $newTaskId = $conn->lastInsertId();
  4176.                     //prendo il nuovo id e lo mappo col vecchio
  4177.                     $mapTasksId[$task["id"]] = $newTaskId;                
  4178.                     // Non Ã¨ più necessario rimappare i nomi
  4179.                     // $mapTasksName[$task["name"]] = $newTaskName;
  4180.                     // Quick fix! 
  4181.                     // TODO: Ci sarebbe da rivedere tutta la logica a valle ma per il momento risolviamo così
  4182.                     $mapTasksName[$task["name"]] = $task["name"];
  4183.                     
  4184.                 }
  4185.                 $logger->debug("[clonaWorkflowAction] Insert into task andata a buon fine");
  4186.                 
  4187.                 $columnToCheck = array_keys($allTasks[0]);
  4188.                 //per ogni task
  4189.                 foreach ($allTasks as $t) {
  4190.                     //per tutte le colonne del task
  4191.                     foreach ($columnToCheck as $col) {
  4192.                         $value = $t[$col];
  4193.                         //per tutti i valori da cercare
  4194.                         foreach ($mapTasksName as $findKey => $findValue) {
  4195.                             if (!$findKey)
  4196.                                 continue;
  4197.                             if (strpos($value, $findKey)) {
  4198.                                 //se lo trovo faccio update
  4199.                                 $newVal = str_replace($findKey, $findValue, $value);
  4200.                                 $sql = "update task set " . $col . " = :nextVal where id = :id ";
  4201.                                 $stmt = $conn->prepare($sql);
  4202.                                 $stmt->bindValue('nextVal', $newVal);
  4203.                                 $stmt->bindValue('id', $mapTasksId[$t["id"]]);
  4204.                                 $stmt->execute();
  4205.                                 
  4206.                             }
  4207.                         }
  4208.                         
  4209.                     }
  4210.                 }
  4211.                 $sql = "select task_id, server_id, server_order, flag_use_password from task2server where task_id in (" . $inQuery . ") ";
  4212.                 $stmt = $conn->prepare($sql);
  4213.                 foreach ($arrayTasks as $k => $id)
  4214.                     $stmt->bindValue(($k + 1), $id);
  4215.                 $stmt->execute();
  4216.                 $task2Server = $stmt->fetchAll();
  4217.                 foreach ($task2Server as $s) {
  4218.                     $sql = "insert into task2server (task_id, server_id, server_order, flag_use_password)
  4219.                             values ( :task_id, :server_id, :server_order, :flag_use_password  ) ";
  4220.                     $stmt = $conn->prepare($sql);
  4221.                     $stmt->bindValue('task_id', $mapTasksId[$s["task_id"]]);
  4222.                     $stmt->bindValue('server_id', $s["server_id"]);
  4223.                     $stmt->bindValue('server_order', $s["server_order"]);
  4224.                     $stmt->bindValue('flag_use_password', $s["flag_use_password"]);
  4225.                     $stmt->execute();
  4226.                 }
  4227.                 $logger->debug("[clonaWorkflowAction] Insert into task2server andata a buon fine");
  4228.                 $sql = "select task_id, field_name, field_value, field_type, 
  4229.                         field_precision, field_id 
  4230.                         from task_select_fields where task_id in (" . $inQuery . ") ";
  4231.                 $stmt = $conn->prepare($sql);
  4232.                 foreach ($arrayTasks as $k => $id)
  4233.                     $stmt->bindValue(($k + 1), $id);
  4234.                 $stmt->execute();
  4235.                 $taskSelectFields = $stmt->fetchAll();
  4236.                 foreach ($taskSelectFields as $field) {
  4237.                     $sql = "insert into task_select_fields ( task_id, field_name, field_value, field_type, field_precision, field_id )
  4238.                             values ( :task_id, :field_name, :field_value, :field_type, :field_precision, :field_id ) ";
  4239.                     $stmt = $conn->prepare($sql);
  4240.                     $stmt->bindValue('task_id', $mapTasksId[$field["task_id"]]);
  4241.                     $stmt->bindValue('field_name', $field["field_name"]);
  4242.                     $stmt->bindValue('field_value', $field["field_value"]);
  4243.                     $stmt->bindValue('field_type', $field["field_type"]);
  4244.                     $stmt->bindValue('field_precision', $field["field_precision"]);
  4245.                     $stmt->bindValue('field_id', $field["field_id"]);
  4246.                     $stmt->execute();
  4247.                 }
  4248.                 $logger->debug("[clonaWorkflowAction] Insert into task_select_fields andata a buon fine");
  4249.                 $sql = "select task_id, from_value from task_select_from where task_id in (" . $inQuery . ") ";
  4250.                 $stmt = $conn->prepare($sql);
  4251.                 foreach ($arrayTasks as $k => $id)
  4252.                     $stmt->bindValue(($k + 1), $id);
  4253.                 $stmt->execute();
  4254.                 $taskSelectFrom = $stmt->fetchAll();
  4255.                 foreach ($taskSelectFrom as $selectFrom) {
  4256.                     $sql = "insert into task_select_from ( task_id, from_value ) 
  4257.                             values ( :task_id, :from_value )";
  4258.                     $stmt = $conn->prepare($sql);
  4259.                     $stmt->bindValue('task_id', $mapTasksId[$selectFrom["task_id"]]);
  4260.                     $stmt->bindValue('from_value', $selectFrom["from_value"]);
  4261.                     $stmt->execute();
  4262.                 }
  4263.                 $logger->debug("[clonaWorkflowAction] Insert into task_select_from andata a buon fine");
  4264.             } // fine if count task > 0
  4265.             //clono la tabella task_conditional
  4266.             $sql = "select id_task, nome, tipo, espressione, id_template from task_conditional where id_template = :idTemplate ";
  4267.             $stmt = $conn->prepare($sql);
  4268.             $stmt->bindValue('idTemplate', $idTemplate);
  4269.             $stmt->execute();
  4270.             $oldConditions = $stmt->fetchAll();
  4271.         
  4272.             foreach ($oldConditions as $condition) {
  4273.                 if (!array_key_exists($condition["id_task"], $mapTasksId)) {
  4274.                     continue;
  4275.                 }
  4276.                 //make insert with new idtemplate and new tasks ids
  4277.                 $sql = "insert into task_conditional (id_task, nome, tipo, espressione, id_template) values (:idTask, :nome, :tipo, :espressione, :idTemplate) ";                
  4278.                 $stmt = $conn->prepare($sql);                
  4279.                 $stmt->bindValue('idTask', $mapTasksId[$condition["id_task"]]);                
  4280.                 $stmt->bindValue('nome', $condition["nome"]);                
  4281.                 $stmt->bindValue('tipo', $condition["tipo"]);                
  4282.                 $stmt->bindValue('espressione', $condition["espressione"]);                
  4283.                 $stmt->bindValue('idTemplate', $newIdTemplate);        
  4284.                 $stmt->execute();
  4285.             }
  4286.                     // clono tutto, workflow, parametri, task. ai task metto il suffisso numerico e come prefisso il nome del nuovo workflow.
  4287.                     $sql = "select param_name, param_file_name, param_file_path, param_file_type from task_spool_files where task_id in (" . $inQuery . ") ";
  4288.                     $stmt = $conn->prepare($sql);
  4289.                     foreach ($arrayTasks as $k => $id)
  4290.                         $stmt->bindValue(($k + 1), $id);
  4291.                     $stmt->execute();
  4292.                     $taskSpoolFiles = $stmt->fetchAll();
  4293.                     foreach ($taskSpoolFiles as $spoolFile) {
  4294.                         foreach ($mapTasksName as $taskKey => $taskName) {
  4295.                             if ($taskName)
  4296.                                 if (str_contains($spoolFile["param_name"], $taskKey)) {
  4297.                                     $spoolTaskName = str_replace(".queryspool.file", "", $spoolFile["param_name"]);
  4298.                                     $pName = $taskName . ".queryspool.file";
  4299.                                     $pFileName =
  4300.                                         str_replace($spoolTaskName, $mapTasksName[$spoolTaskName], $spoolFile["param_file_name"]);
  4301.                                     $spoolPath = pathinfo($spoolFile["param_file_path"]);
  4302.                                     $pFilePath = $spoolPath["dirname"] . "/" . $mapTasksId[$spoolPath['basename']] . "/";
  4303.                                     $sql = "insert into task_spool_files (task_id, param_name, param_file_name, param_file_path, param_file_type)
  4304.                                         values (:task_id, :param_name, :param_file_name, :param_file_path, :param_file_type ) ";
  4305.                                     $stmt = $conn->prepare($sql);
  4306.                                     $stmt->bindValue('task_id', $mapTasksId[$spoolPath['basename']]);
  4307.                                     $stmt->bindValue('param_name', $pName);
  4308.                                     $stmt->bindValue('param_file_name', $pFileName);
  4309.                                     $stmt->bindValue('param_file_path', $pFilePath);
  4310.                                     $stmt->bindValue('param_file_type', $spoolFile["param_file_type"]);
  4311.                                     $stmt->execute();
  4312.                                     break;
  4313.                                 }
  4314.                         }
  4315.                     }
  4316.                     $logger->debug("[clonaWorkflowAction] Insert into task_spool_files andata a buon fine");
  4317.                     $sql = "select chklsttmpl_id, task_id, task_order, ko_task,
  4318.                     slave, flag_bitmask, run_bitmask
  4319.                     from pre_chklsttmpl2task where chklsttmpl_id = :idTemplate ";
  4320.                     $stmt = $conn->prepare($sql);
  4321.                     $stmt->bindValue('idTemplate', $idTemplate);
  4322.                     $stmt->execute();
  4323.                     $workflow2Task = $stmt->fetchAll();
  4324.                     //-----------------------------------------------------------
  4325.                     // Aggiungiamo i task clonati al nuovo workflow.
  4326.                     //-----------------------------------------------------------
  4327.                     foreach ($workflow2Task as $w2t) {
  4328.             
  4329.                         //---------------------------------------------------------------------------
  4330.                         // normalizza il campo slave, nel db Ã¨ di tipo boolean
  4331.                         // bindValue() trasforma false in stringa vuota, 
  4332.                         // causando errori in fase di insert quindi lo convertiamo in 1 o 0
  4333.                         //---------------------------------------------------------------------------
  4334.                         $slave = $w2t['slave'] ? 1 : 0;
  4335.                         
  4336.                         $sql = "insert into pre_chklsttmpl2task ( chklsttmpl_id, task_id, task_order, ko_task,
  4337.                         slave, flag_bitmask, run_bitmask )
  4338.                         values ( :chklsttmpl_id, :task_id, :task_order, :ko_task,
  4339.                         :slave, :flag_bitmask, :run_bitmask ) ";
  4340.                         $stmt = $conn->prepare($sql);
  4341.                         $stmt->bindValue('chklsttmpl_id', $newIdTemplate);
  4342.                         $stmt->bindValue('task_id', $mapTasksId[$w2t["task_id"]]);
  4343.                         $stmt->bindValue('task_order', $w2t["task_order"]);
  4344.                         $stmt->bindValue('ko_task', $w2t["ko_task"]);
  4345.                         $stmt->bindValue('slave', $slave);
  4346.                         $stmt->bindValue('flag_bitmask', $w2t["flag_bitmask"]);
  4347.                         $stmt->bindValue('run_bitmask', $w2t["run_bitmask"]);
  4348.                         $stmt->execute();
  4349.                     }
  4350.                     $logger->debug("[clonaWorkflowAction] Insert into pre_chklsttmpl2task andata a buon fine");
  4351.                     //se clono tutto devo modificare i nomi dei task e gli id
  4352.                     $sql = "select chklst_template, json_flow,task_jorder, task_jump, task_action_ok,
  4353.                     task_action_ko, 'N' task_validate 
  4354.                     from chklst_jflow where chklst_template = :idTemplate ";
  4355.                     $stmt = $conn->prepare($sql);
  4356.                     $stmt->bindValue('idTemplate', $idTemplate);
  4357.                     $stmt->execute();
  4358.                     $templateJFlowToClone = $stmt->fetchAll()[0];
  4359.                     if ($templateJFlowToClone["json_flow"] != "") {
  4360.                         $arrayJFlow = json_decode($templateJFlowToClone["json_flow"]);
  4361.                         foreach ($arrayJFlow->{"nodeDataArray"} as $nodeDataArray) {
  4362.                             if ($nodeDataArray->category == 'CommentGroup') {
  4363.                                 continue;
  4364.                             }
  4365.                             $taskIdToReplace = str_replace("]", "", explode("_", $nodeDataArray->{"key"})[1]);
  4366.                             if (array_key_exists($taskIdToReplace, $mapTasksId))
  4367.                                 $nodeDataArray->{"key"} = str_replace($idTemplate . "_" . $taskIdToReplace, $newIdTemplate . "_" . $mapTasksId[$taskIdToReplace], $nodeDataArray->{"key"});
  4368.                             if (array_key_exists($nodeDataArray->{"text"}, $mapTasksName))
  4369.                                 $nodeDataArray->{"text"} = $mapTasksName[$nodeDataArray->{"text"}];
  4370.                         }
  4371.                         foreach ($arrayJFlow->{"linkDataArray"} as $linkDataArray) {
  4372.                             $taskIdToReplaceFrom = str_replace("]", "", explode("_", $linkDataArray->{"from"})[1]);
  4373.                             $taskIdToReplaceTo = str_replace("]", "", explode("_", $linkDataArray->{"to"})[1]);
  4374.                             if (array_key_exists($taskIdToReplaceFrom, $mapTasksId))
  4375.                                 $linkDataArray->{"from"} = str_replace($idTemplate . "_" . $taskIdToReplaceFrom, $newIdTemplate . "_" . $mapTasksId[$taskIdToReplaceFrom], $linkDataArray->{"from"});
  4376.                             if (array_key_exists($taskIdToReplaceTo, $mapTasksId))
  4377.                                 $linkDataArray->{"to"} = str_replace($idTemplate . "_" . $taskIdToReplaceTo, $newIdTemplate . "_" . $mapTasksId[$taskIdToReplaceTo], $linkDataArray->{"to"});
  4378.                         }
  4379.                         $stringJFlow = json_encode($arrayJFlow);
  4380.                         $sql = "insert into chklst_jflow ( chklst_template, json_flow, task_jorder, task_jump, task_action_ok,
  4381.                         task_action_ko, task_validate )
  4382.                         values ( :chklst_template, :json_flow, :task_jorder, :task_jump, :task_action_ok,
  4383.                         :task_action_ko, 'N' ) ";
  4384.                         $stmt = $conn->prepare($sql);
  4385.                         $stmt->bindValue('chklst_template', $newIdTemplate);
  4386.                         $stmt->bindValue('json_flow', $stringJFlow);
  4387.                         $newTaskOrder = $this->getTaskSplit($templateJFlowToClone["task_jorder"], $mapTasksId + $mapTasksName);
  4388.                         $stmt->bindValue('task_jorder', $newTaskOrder);
  4389.                         $stmt->bindValue('task_jump', $this->getTaskSplit($templateJFlowToClone["task_jump"], $mapTasksId + $mapTasksName));
  4390.                         $stmt->bindValue('task_action_ok', $this->getTaskSplit($templateJFlowToClone["task_action_ok"], $mapTasksId + $mapTasksName));
  4391.                         $stmt->bindValue('task_action_ko', $this->getTaskSplit($templateJFlowToClone["task_action_ko"], $mapTasksId + $mapTasksName));
  4392.                         $stmt->execute();
  4393.                     }
  4394.                     break;
  4395.                 case 'clonasoloworkflow':
  4396.                     
  4397.                     //--------------------------------------------------------------
  4398.                     // Clona e mantieni i task:
  4399.                     // - clono l’intero workflow con parametri e file
  4400.                     // - i task restano quelli dell’originale
  4401.                     // - copio il JSON del disegno 
  4402.                     //-------------------------------------------------------------
  4403.                     //clono la tabella task_conditional
  4404.                     $sql = "select id_task, nome, tipo, espressione, id_template from task_conditional where id_template = :idTemplate ";
  4405.                     $stmt = $conn->prepare($sql);
  4406.                     $stmt->bindValue('idTemplate', $idTemplate);
  4407.                     $stmt->execute();
  4408.                     $oldConditions = $stmt->fetchAll();
  4409.                 
  4410.                     foreach ($oldConditions as $condition) {
  4411.                         $sql = "insert into task_conditional (id_task, nome, tipo, espressione, id_template) values (:idTask, :nome, :tipo, :espressione, :idTemplate) ";                
  4412.                         $stmt = $conn->prepare($sql);                
  4413.                         $stmt->bindValue('idTask', $condition["id_task"]);                
  4414.                         $stmt->bindValue('nome', $condition["nome"]);                
  4415.                         $stmt->bindValue('tipo', $condition["tipo"]);                
  4416.                         $stmt->bindValue('espressione', $condition["espressione"]);                
  4417.                         $stmt->bindValue('idTemplate', $newIdTemplate);        
  4418.                         $stmt->execute();
  4419.                     }
  4420.                     $sql = "select chklsttmpl_id, task_id, task_order, ko_task,
  4421.                     slave, flag_bitmask, run_bitmask
  4422.                     from pre_chklsttmpl2task where chklsttmpl_id = :idTemplate ";
  4423.                     $stmt = $conn->prepare($sql);
  4424.                     $stmt->bindValue('idTemplate', $idTemplate);
  4425.                     $stmt->execute();
  4426.                     $workflow2Task = $stmt->fetchAll();
  4427.                     foreach ($workflow2Task as $w2t) {
  4428.                         //---------------------------------------------------------------------------
  4429.                         // normalizza il campo slave, nel db Ã¨ di tipo boolean
  4430.                         // bindValue() trasforma false in stringa vuota, 
  4431.                         // causando errori in fase di insert quindi lo convertiamo in 1 o 0
  4432.                         //---------------------------------------------------------------------------
  4433.                         $slave = $w2t['slave'] ? 1 : 0;
  4434.                         $sql = "insert into pre_chklsttmpl2task ( chklsttmpl_id, task_id, task_order, ko_task,
  4435.                         slave, flag_bitmask, run_bitmask )
  4436.                         values ( :chklsttmpl_id, :task_id, :task_order, :ko_task,
  4437.                         :slave, :flag_bitmask, :run_bitmask ) ";
  4438.                         $stmt = $conn->prepare($sql);
  4439.                         $stmt->bindValue('chklsttmpl_id', $newIdTemplate);
  4440.                         $stmt->bindValue('task_id', $w2t["task_id"]);
  4441.                         $stmt->bindValue('task_order', $w2t["task_order"]);
  4442.                         $stmt->bindValue('ko_task', $w2t["ko_task"]);
  4443.                         $stmt->bindValue('slave', $slave);
  4444.                         $stmt->bindValue('flag_bitmask', $w2t["flag_bitmask"]);
  4445.                         $stmt->bindValue('run_bitmask', $w2t["run_bitmask"]);
  4446.                         $stmt->execute();
  4447.                     }
  4448.                     $logger->debug("[clonaWorkflowAction] Insert into pre_chklsttmpl2task andata a buon fine");
  4449.                     $sql = "select chklst_template, json_flow,task_jorder, task_jump, task_action_ok,
  4450.                     task_action_ko, 'N' task_validate 
  4451.                     from chklst_jflow where chklst_template = :idTemplate ";
  4452.                     $stmt = $conn->prepare($sql);
  4453.                     $stmt->bindValue('idTemplate', $idTemplate);
  4454.                     $stmt->execute();
  4455.                     $templateJFlowToClone = $stmt->fetchAll()[0];
  4456.                     if ($templateJFlowToClone["json_flow"] != "") {
  4457.                         $arrayJFlow = json_decode($templateJFlowToClone["json_flow"]);
  4458.                         foreach ($arrayJFlow->{"nodeDataArray"} as $nodeDataArray) {
  4459.                             if ($nodeDataArray->category == 'CommentGroup') {
  4460.                                 continue;
  4461.                             }
  4462.                             $splitKey =  explode("_", explode(" ", $nodeDataArray->{"key"})[1]);
  4463.                             $taskIdToMantain = str_replace("]", "", $splitKey[1]);
  4464.                             $nodeDataArray->{"key"} = str_replace($idTemplate . "_" . $taskIdToMantain, $newIdTemplate . "_" . $taskIdToMantain, $nodeDataArray->{"key"});
  4465.                         }
  4466.                         foreach ($arrayJFlow->{"linkDataArray"} as $linkDataArray) {
  4467.                             $splitKeyFrom =  explode("_", explode(" ", $linkDataArray->{"from"})[1]);
  4468.                             $taskIdToMantainFrom = str_replace("]", "", $splitKeyFrom[1]);
  4469.                             $splitKeyTo =  explode("_", explode(" ", $linkDataArray->{"to"})[1]);
  4470.                             $taskIdToMantainTo = str_replace("]", "", $splitKeyTo[1]);
  4471.                             $linkDataArray->{"from"} = str_replace($idTemplate . "_" . $taskIdToMantainFrom, $newIdTemplate . "_" . $taskIdToMantainFrom, $linkDataArray->{"from"});
  4472.                             $linkDataArray->{"to"} = str_replace($idTemplate . "_" . $taskIdToMantainTo, $newIdTemplate . "_" . $taskIdToMantainTo, $linkDataArray->{"to"});
  4473.                         }
  4474.                         $stringJFlow = json_encode($arrayJFlow);
  4475.                         $sql = "insert into chklst_jflow ( chklst_template, json_flow, task_jorder, task_jump, task_action_ok,
  4476.                         task_action_ko, task_validate )
  4477.                         values ( :chklst_template, :json_flow, :task_jorder, :task_jump, :task_action_ok,
  4478.                         :task_action_ko, 'N' ) ";
  4479.                         $stmt = $conn->prepare($sql);
  4480.                         $stmt->bindValue('chklst_template', $newIdTemplate);
  4481.                         $stmt->bindValue('json_flow', $stringJFlow);
  4482.                         $stmt->bindValue('task_jorder', $templateJFlowToClone["task_jorder"]);
  4483.                         $stmt->bindValue('task_jump', $templateJFlowToClone["task_jump"]);
  4484.                         $stmt->bindValue('task_action_ok', $templateJFlowToClone["task_action_ok"]);
  4485.                         $stmt->bindValue('task_action_ko', $templateJFlowToClone["task_action_ko"]);
  4486.                         $stmt->execute();
  4487.                     }
  4488.                     break;
  4489.                 default:
  4490.                     break;
  4491.             }
  4492.             $logger->debug("[clonaWorkflowAction] Commit");
  4493.             $conn->commit();
  4494.             return $this->json(['error' => false]);
  4495.         } catch (\Exception $e) {
  4496.             $conn->rollBack();
  4497.             throw $e;
  4498.         }
  4499.     }
  4500.     function getTaskSplit($incomeTask, $mapTasks): string
  4501.     {
  4502.         if ($incomeTask == "")
  4503.             return "";
  4504.         $newTaskOrderSplitPipe = explode("|", substr($incomeTask, 0, -1));
  4505.         $newTaskOrderPipe = [];
  4506.         foreach ($newTaskOrderSplitPipe as $splitPipe) {
  4507.             $newTaskOrderSplitComma = explode(";", $splitPipe);
  4508.             $newTaskComma = [];
  4509.             foreach ($newTaskOrderSplitComma as $splitComma) {
  4510.                 if (array_key_exists($splitComma, $mapTasks))
  4511.                     $newTaskComma[] = $mapTasks[$splitComma];
  4512.                 else
  4513.                     $newTaskComma[] = $splitComma;
  4514.             }
  4515.             $newTaskOrderPipe[] = implode(";", $newTaskComma);
  4516.         }
  4517.         $newTaskOrder = implode("|", $newTaskOrderPipe);
  4518.         $newTaskOrder .= "|";
  4519.         return $newTaskOrder;
  4520.     }
  4521.     public function getWorkflowIdByNameAction(Request $request, LoggerInterface $logger)
  4522.     {
  4523.         $csrfToken = $_POST['csrftoken'];
  4524.         if (!$this->isCsrfTokenValid('checklistWorkflowIdByName', $csrfToken)) {
  4525.             throw new \Exception('Csrf token not valid');
  4526.         }
  4527.         $em = $this->getDoctrine()->getManager();
  4528.         $conn = $em->getConnection();
  4529.         $wName = $_POST['workflowName'];
  4530.         $sql = "select id 
  4531.                 from chklst_template where name = :workflowName ";
  4532.         $stmt = $conn->prepare($sql);
  4533.         $stmt->bindValue('workflowName', $wName);
  4534.         $stmt->execute();
  4535.         $wId = $stmt->fetchAll()[0]["id"];
  4536.         return $this->json(['data' => ['workflowId' => $wId]]);
  4537.     }
  4538.     function checkCorrelatedWorkflowNamesByTaskAction(Request $request, LoggerInterface $logger)
  4539.     {
  4540.         $csrfToken = $_POST['csrftoken'];
  4541.         if (!$this->isCsrfTokenValid('checkCorrelatedWorkflowNamesByTask', $csrfToken)) {
  4542.             throw new \Exception('Csrf token not valid');
  4543.         }
  4544.         $em = $this->getDoctrine()->getManager();
  4545.         $conn = $em->getConnection();
  4546.         $taskId = $_POST['taskId'];
  4547.         $sql = "
  4548.                 select
  4549.                 t.id,
  4550.                 t.name,
  4551.                 pct.chklsttmpl_id,
  4552.                 ct.name
  4553.             from
  4554.                 task t
  4555.             join pre_chklsttmpl2task pct on
  4556.                 (t.id = pct.task_id)
  4557.             join chklst_template ct on
  4558.                 (pct.chklsttmpl_id = ct.id)
  4559.             where
  4560.                 t.id = :taskId    
  4561.         ";
  4562.         $stmt = $conn->prepare($sql);
  4563.         $stmt->bindValue('taskId', $taskId);
  4564.         $stmt->execute();
  4565.         $workflowRelated = $stmt->fetchAll();
  4566.         if (count($workflowRelated) < 2) {
  4567.             return $this->json(['data' => ['workflowNames' => ""]]);
  4568.         }
  4569.         $workflowNames = [];
  4570.         foreach ($workflowRelated as $val) {
  4571.             $workflowNames[] = $val["name"];
  4572.         }
  4573.         return $this->json(['data' => ['workflowNames' => $workflowNames]]);
  4574.     }
  4575.     //funzione che ritorna il prossimo id workflow per la creazione di un nuovo workflow
  4576.     public function nextValNewWorkflowAction(Request $request, LoggerInterface $logger)
  4577.     {
  4578.         $logger->debug("[NextValNewWorkflow] start");
  4579.         $em = $this->getDoctrine()->getManager();
  4580.         $conn = $em->getConnection();
  4581.         $sql = "select nextval('chklst_template_id_seq') as id";
  4582.         $statement = $conn->prepare($sql);
  4583.         $statement->execute();
  4584.         $nextval = $statement->fetchAll();
  4585.         $logger->debug("[NextValNewWorkflow] end");
  4586.         return $this->json(["id" => $nextval[0]["id"]]);
  4587.     }
  4588.     private function getParametersByWorkflowId($wflId)
  4589.     {
  4590.         $sqlParameters = "select chklst_id, param_name, param_value, param_type, flag_file from chklst_template_parameters where chklst_id = :wflId";
  4591.         $em = $this->getDoctrine()->getManager();
  4592.         $conn = $em->getConnection();
  4593.         $stmt = $conn->prepare($sqlParameters);
  4594.         $stmt->bindValue('wflId', $wflId);
  4595.         $stmt->execute();
  4596.         $sqlParameters = $stmt->fetchAll();
  4597.         if (empty($sqlParameters)) {
  4598.             $sqlParameters = [];
  4599.         }
  4600.         return $sqlParameters;
  4601.     }
  4602.     public function checkWflLockStatusAction(Request $request, LoggerInterface $logger)
  4603.     {
  4604.         // $logger->debug("[checkWflLockStatusAction] start");
  4605.         $csrfToken = $_POST['csrftoken'];
  4606.         if (!$this->isCsrfTokenValid('checkWflLockStatus', $csrfToken)) {
  4607.             throw new \Exception('Csrf token not valid');
  4608.         }
  4609.         $session = $request->getSession();
  4610.         $sessionId = $session->getId();
  4611.         $idTemplate = $request->request->get('idTemplate');
  4612.         // $logger->debug("[checkWflLockStatusAction] idTemplate: " . $idTemplate);
  4613.         if (empty($idTemplate)) {
  4614.             // $logger->debug("[checkWflLockStatusAction] idTemplate is empty");
  4615.             return $this->json(["status" => 0, "username" => ""]);
  4616.         }
  4617.         $em = $this->getDoctrine()->getManager();
  4618.         $conn = $em->getConnection();
  4619.         $sql = "select ct.locked, ct.lock_session_user_id, ct.modificato_da, ua.username
  4620.         from chklst_template ct join user_acm ua on ua.id = ct.modificato_da 
  4621.         where ct.id = :idTemplate";
  4622.         $stmt = $conn->prepare($sql);
  4623.         $stmt->bindValue('idTemplate', $idTemplate);
  4624.         $stmt->execute();
  4625.         $lockStatus = $stmt->fetchAll();
  4626.         // $logger->debug("[checkWflLockStatusAction] end");
  4627.         if (empty($lockStatus)) {
  4628.             return $this->json(["status" => 0, "locked_by" => ""]);
  4629.         }
  4630.         $userId = $this->getUser()->getId();
  4631.         $modificatoDa = $lockStatus[0]["modificato_da"];
  4632.         $lockSessionUserId = $lockStatus[0]["lock_session_user_id"];
  4633.         $message = "";
  4634.         if($userId == $modificatoDa && $lockSessionUserId != $sessionId) {
  4635.             $message = "stesso utente con una sessione diversa";
  4636.         }
  4637.         return $this->json(["status" => $lockStatus[0]["locked"], "locked_by" => $lockStatus[0]["username"], "message" => $message]);
  4638.     }
  4639.     public function lockWflAction(Request $request, LoggerInterface $logger)
  4640.     {
  4641.         // $logger->debug("[lockWflAction] start");
  4642.         $csrfToken = $_POST['csrftoken'];
  4643.         if (!$this->isCsrfTokenValid('lockWfl', $csrfToken)) {
  4644.             throw new \Exception('Csrf token not valid');
  4645.         }
  4646.         $em = $this->getDoctrine()->getManager();
  4647.         $conn = $em->getConnection();
  4648.         $session = $request->getSession();
  4649.         $sessionId = $session->getId();
  4650.         $idTemplate = $request->request->get('idTemplate');
  4651.         if (empty($idTemplate)) {
  4652.             // $logger->debug("[lockWflAction] idTemplate is empty");
  4653.             return $this->json(["status" => false]);
  4654.         }
  4655.         // $logger->debug("[lockWflAction] idTemplate: " . $idTemplate);
  4656.         $sql = "select ct.id
  4657.         from chklst_template ct 
  4658.         where ct.id = :idTemplate";
  4659.         $stmt = $conn->prepare($sql);
  4660.         $stmt->bindValue('idTemplate', $idTemplate);
  4661.         $stmt->execute();
  4662.         $currentTemplate = $stmt->fetchAll();
  4663.         if (empty($currentTemplate) || count($currentTemplate) > 1) {
  4664.             // $logger->debug("[lockWflAction] Not Found or more than one wfl");
  4665.             return $this->json(["status" => false]);
  4666.         }
  4667.         $sql = "update chklst_template set locked = 1, modificato_da = :idUser, lock_session_user_id = :sessionId where id = :idTemplate";
  4668.         $stmt = $conn->prepare($sql);
  4669.         $stmt->bindValue('idTemplate', $idTemplate);
  4670.         $stmt->bindValue('idUser', $this->getUser()->getId());
  4671.         $stmt->bindValue('sessionId', $sessionId);
  4672.         $stmt->execute();
  4673.         // $logger->debug("[lockWflAction] end");
  4674.         return $this->json(["status" => true]);
  4675.     }
  4676.     public function unlockWflAction(Request $request, LoggerInterface $logger)
  4677.     {
  4678.         $user = $this->getUser();
  4679.         $userId = $user->getId();
  4680.         $session = $request->getSession();
  4681.         $sessionId = $session->getId();
  4682.         $logger->debug("[unlockWflAction] start");
  4683.         $csrfToken = $_POST['csrftoken'];
  4684.         if (!$this->isCsrfTokenValid('unlockWfl', $csrfToken)) {
  4685.             throw new \Exception('Csrf token not valid');
  4686.         }
  4687.         $em = $this->getDoctrine()->getManager();
  4688.         $conn = $em->getConnection();
  4689.         $idTemplate = $request->request->get('idTemplate');
  4690.         if (empty($idTemplate)) {
  4691.             $logger->debug("[unlockWflAction] idTemplate is empty");
  4692.             return $this->json(["status" => false]);
  4693.         }
  4694.         $logger->debug("[unlockWflAction] idTemplate: " . $idTemplate);
  4695.         $sql = "select ct.id
  4696.         from chklst_template ct 
  4697.         where ct.id = :idTemplate";
  4698.         $stmt = $conn->prepare($sql);
  4699.         $stmt->bindValue('idTemplate', $idTemplate);
  4700.         $stmt->execute();
  4701.         $currentTemplate = $stmt->fetchAll();
  4702.         if (empty($currentTemplate) || count($currentTemplate) > 1) {
  4703.             $logger->debug("[lockWflAction] Not Found or more than one wfl");
  4704.             return $this->json(["status" => false]);
  4705.         }
  4706.         
  4707.         $sql='select  ct.modificato_da, ct.data_modifica, ct.lock_session_user_id 
  4708.                     from chklst_template ct where ct.id = :idTemplate';
  4709.         $statement=$conn -> prepare($sql);
  4710.         $statement -> bindValue('idTemplate',$idTemplate);
  4711.         $statement -> execute();
  4712.         $infoTemplateLock= $statement->fetchAll()[0];
  4713.         
  4714.         $id_user_lock= $infoTemplateLock['modificato_da'];
  4715.         $data_lock= $infoTemplateLock['data_modifica'];
  4716.         $id_session_lock= $infoTemplateLock['lock_session_user_id'];
  4717.   
  4718.         $sql='insert into wfl_unlock_history (id_user_lock,data_lock,id_session_lock,id_user_unlock,id_session_unlock,id_wfl_template)  values
  4719.             (:id_user_lock,:data_lock,:id_session_lock,:id_user_unlock, :id_session_unlock, :idTemplate)';
  4720.         $statement= $conn -> prepare($sql);
  4721.         $statement -> bindValue('id_user_lock',$id_user_lock);
  4722.         $statement -> bindValue('data_lock',$data_lock);
  4723.         $statement -> bindValue('id_session_lock',$id_session_lock);
  4724.         $statement -> bindValue('id_user_unlock',$userId);
  4725.         $statement -> bindValue('id_session_unlock',$sessionId);
  4726.         $statement -> bindValue('idTemplate',$idTemplate);
  4727.         $statement -> execute();
  4728.         $sql = "update chklst_template set locked = 0, modificato_da = :idUser, lock_session_user_id = '' where id = :idTemplate";
  4729.         $stmt = $conn->prepare($sql);
  4730.         $stmt->bindValue('idTemplate', $idTemplate);
  4731.         $stmt->bindValue('idUser', $this->getUser()->getId());
  4732.         $stmt->execute();
  4733.         $logger->debug("[unlockWflAction] end");
  4734.         return $this->json(["status" => true]);
  4735.     }
  4736.     public function stopWflByRunIdAction(Request $request, LoggerInterface $logger, WorkflowAuditLoggerFactory $auditLoggerFactory)
  4737.     {
  4738.         $logger->debug("[stopWflByRunIdAction] start");
  4739.         // Il controllo CSRF resta solo qui (punto di ingresso WEB)
  4740.         $csrfToken = $_POST['csrftoken'] ?? ''; 
  4741.         if (!$this->isCsrfTokenValid('stopWflByRunId', $csrfToken)) {
  4742.             throw new \Exception('Csrf token not valid');
  4743.         }
  4744.         $runId = $request->request->get('runId');
  4745.         $em = $this->getDoctrine()->getManager();
  4746.         $conn = $em->getConnection();
  4747.         // Chiamata al metodo statico "sporco"
  4748.         $result = self::_stopWflByRunId($runId, $conn, $logger, $auditLoggerFactory);
  4749.         return $this->json($result);
  4750.     }
  4751.     public static function _stopWflByRunId($runId, $conn, $logger, $auditLoggerFactory)
  4752.     {
  4753.         if (empty($runId)) {
  4754.             $logger->debug("[doStopLogic] runId is empty");
  4755.             return ["stopped" => false];
  4756.         }
  4757.         try {
  4758.             $sql = "SELECT id, run_user_id, from_template_id, name FROM chklst WHERE id = :runId";
  4759.             $stmt = $conn->prepare($sql);
  4760.             $stmt->bindValue('runId', $runId);
  4761.             $stmt->execute();
  4762.             $info = $stmt->fetch();
  4763.             if (!$info) {
  4764.                 $logger->debug("[doStopLogic] Record non trovato per ID: " . $runId);
  4765.                 return ["stopped" => false, "error" => "not_found"];
  4766.             }
  4767.             $sql = "SELECT pid FROM chklst WHERE id = :run_id";
  4768.             $stmt = $conn->prepare($sql);
  4769.             $stmt->bindValue('run_id', $runId);
  4770.             $stmt->execute();
  4771.             $row = $stmt->fetch();
  4772.             if ($row && $row['pid'] != 0) {
  4773.                 $pid = $row['pid'];
  4774.                 exec("kill -9 $pid");
  4775.             }
  4776.             // 3. Update task
  4777.             $sql = "UPDATE chklst_task SET run_result='STOPPED', run_end=NOW() WHERE chklst_id=:run_id";
  4778.             $stmt = $conn->prepare($sql);
  4779.             $stmt->bindValue('run_id', $runId);
  4780.             $stmt->execute();
  4781.             // 4. Update testata
  4782.             $sql = "UPDATE chklst SET run_end = SYSDATE(), run_result = 'STOPPED', 
  4783.                     run_start = COALESCE(run_start, SYSDATE()) WHERE id = :runId";
  4784.             $stmt = $conn->prepare($sql);
  4785.             $stmt->bindValue('runId', $runId);
  4786.             $stmt->execute();
  4787.             // 5. Audit Log
  4788.             $auditLogger = $auditLoggerFactory->createWorkflow(
  4789.                 $info['name'],
  4790.                 $info['run_user_id'],
  4791.                 $info['from_template_id'],
  4792.                 $runId
  4793.             );
  4794.             $auditLogger->log(WorkflowAuditLogger::LEVEL_INFO, WorkflowAuditLogger::EVENT_WFL_STOP, [
  4795.                 'status' => WorkflowAuditLogger::STATUS_STOPPED
  4796.             ]);
  4797.             return ["stopped" => true];
  4798.         } catch (\Throwable $ex) {
  4799.             $logger->error("[doStopLogic] Errore critico: " . $ex->getMessage());
  4800.             return ["stopped" => false, "exception" => $ex->getMessage()];
  4801.         }
  4802.     }
  4803.     /*
  4804.     public function stopWflByRunIdAction(Request $request, LoggerInterface $logger,WorkflowAuditLoggerFactory $auditLoggerFactory)
  4805.     {
  4806.         $logger->debug("[stopWflByRunIdAction] start");
  4807.         $csrfToken = $_POST['csrftoken'];
  4808.         if (!$this->isCsrfTokenValid('stopWflByRunId', $csrfToken)) {
  4809.             throw new \Exception('Csrf token not valid');
  4810.         }
  4811.         $em = $this->getDoctrine()->getManager();
  4812.         $conn = $em->getConnection();
  4813.         $runId = $request->request->get('runId');
  4814.         if (empty($runId)) {
  4815.             $logger->debug("[stopWflByRunIdAction] runId is empty");
  4816.             return $this->json(["stopped" => false]);
  4817.         }
  4818.         $logger->debug("[stopWflByRunIdAction] idTemplate: " . $runId);
  4819.         try {
  4820.             $sql = "
  4821.             SELECT 
  4822.                 c.id,
  4823.                 c.run_user_id,
  4824.                 c.from_template_id,
  4825.                 c.name
  4826.             FROM chklst c
  4827.             where c.id= :runId
  4828.             ";
  4829.             $stmt = $conn->prepare($sql);
  4830.             $stmt->bindValue('runId', $runId);
  4831.             $stmt->execute();
  4832.             $info = $stmt->fetch();
  4833.             
  4834.             $sql = "select pid from chklst where id = :run_id";
  4835.             $stmt = $conn->prepare($sql);
  4836.             $stmt->bindValue('run_id', $runId);
  4837.             $stmt->execute();
  4838.             $row = $stmt->fetch();
  4839.             if ($row) {
  4840.                 $pid = $row['pid'];
  4841.                 if ($pid != 0) {
  4842.                     exec("kill -9 $pid");
  4843.                 }                
  4844.             } else {
  4845.                 $logger->debug("Attenzione: pid non trovato");
  4846.             }
  4847.             $sql = "update chklst_task set run_result='STOPPED', run_end=now() where chklst_id=:run_id";
  4848.             $stmt = $conn->prepare($sql);
  4849.             $stmt->bindValue('run_id', $runId);
  4850.             $stmt->execute();
  4851.         } catch (Exception $ex) {
  4852.             $logger->debug("[stopWflByRunIdAction] Update failed:" . $ex->getMessage());
  4853.             return $this->json(["stopped" => false, "exception" => $ex->getMessage()]);
  4854.         }
  4855.         try {
  4856.             $sql = "
  4857.             update chklst set run_end = sysdate(),
  4858.             run_result = 'STOPPED',
  4859.             run_start = coalesce(run_start, sysdate())
  4860.             where id = :runId";
  4861.             $stmt = $conn->prepare($sql);
  4862.             $stmt->bindValue('runId', $runId);
  4863.             $stmt->execute();
  4864.             $logger->debug("[stopWflByRunIdAction] end");
  4865.             $auditLogger = $auditLoggerFactory->createWorkflow(
  4866.                 $info['name'],
  4867.                 $info['run_user_id'],
  4868.                 $info['from_template_id'],
  4869.                 $runId
  4870.             );
  4871.             $auditLogger->log(WorkflowAuditLogger::LEVEL_INFO,WorkflowAuditLogger::EVENT_WFL_STOP,[
  4872.                 'status' => WorkflowAuditLogger::STATUS_STOPPED
  4873.             ]);
  4874.             return $this->json(["stopped" => true]);
  4875.         } catch (\Throwable $th) {
  4876.             $logger->debug("[stopWflByRunIdAction] Update failed");
  4877.             return $this->json(["stopped" => false]);
  4878.         }
  4879.     }
  4880.     */
  4881.     function selectExportWorkflowDocuemntAction( Request $request, LoggerInterface $logger,ParameterBagInterface $params)
  4882.     {
  4883.         $em = $this->getDoctrine()->getManager();
  4884.         $conn = $em->getConnection();
  4885.         $res_json = new JsonResponse();
  4886.         $id_export_workflow = $request->request->get('id_export_workflow');
  4887.         $id_export_document = $request->request->get('id_export_document');
  4888.         
  4889.         $csrftoken = $request->request->get('csrftoken');
  4890.         $csrftokenPDF = $request->request->get('csrftokenPDF');
  4891.         
  4892.         if (!$this->isCsrfTokenValid('select_export_workflow_document', $csrftoken)) {
  4893.             throw new \Exception('Csrf token not valid');
  4894.         }
  4895.         if ( isset($id_export_workflow) && !isset($id_export_document))
  4896.         {
  4897.             $logger->debug("workflow definito e documenti non definito");
  4898.             $expWorkflow=$this->exportChecklist($id_export_workflow,  $logger,  $params);
  4899.             $logger->debug("expWorkflow ".json_decode($expWorkflow));
  4900.             $exDoc="Non Definito";
  4901.         }
  4902.         else if (!isset($id_export_workflow) && isset($id_export_document))
  4903.         {
  4904.             $logger->debug("workflow non definito e documenti definito ");
  4905.             $exDoc=$this->downloadPDFAction($id_export_document, $csrftokenPDF,  'internal',  $logger,  $params);
  4906.             $logger->debug("exDoc ".json_encode($exDoc));
  4907.             $expWorkflow="Non Definito";    
  4908.         }
  4909.         else if (isset($id_export_workflow) && isset($id_export_document))
  4910.         {
  4911.             $logger->debug("documenti  e workflow definito ");
  4912.             $expWorkflow=$this->exportChecklist($id_export_workflow,  $logger,  $params);
  4913.             $exDoc=$this->downloadPDFAction($id_export_document,  $csrftokenPDF, 'internal', $logger,  $params);
  4914.             $logger->debug("expWorkflow ".json_encode($expWorkflow));
  4915.             $logger->debug("exDoc ".json_encode($exDoc));    
  4916.         }
  4917.         return $res_json->setData(array('nome_file_workflow' => $expWorkflow,
  4918.                                         'nome_file_documentazione' => $exDoc));
  4919.         
  4920.     }
  4921.     function generatePDFAction( Request $request, LoggerInterface $logger,ParameterBagInterface $params )
  4922.     {
  4923.         
  4924.                 $em = $this->getDoctrine()->getManager();
  4925.                 $conn = $em->getConnection();
  4926.                 $id = $request->request->get('id');            
  4927.                 $csrftoken = $request->request->get('csrftoken');
  4928.         
  4929.             if (!$this->isCsrfTokenValid('generate_pdf', $csrftoken)) {
  4930.                 throw new \Exception('Csrf token not valid');
  4931.             }
  4932.                 
  4933.                 $sql="select ct.id id_template, ct.name  , ct.description, ct.flag_type_checklist, cj.flow_image
  4934.                     from chklst_template ct left  join chklst_jflow cj on ( ct.id = cj.chklst_template)
  4935.                     where  ct.id = :idTemplate";
  4936.                 
  4937.         
  4938.             $stmt = $conn->prepare($sql);
  4939.             $stmt->bindValue('idTemplate', $id);
  4940.             $stmt->execute();
  4941.             $NomeWorkflow =$stmt->fetchAll()[0];
  4942.             
  4943.             
  4944.         $PathImg=$params->get('kernel.project_dir') .'/public/'. $NomeWorkflow['flow_image'];
  4945.             $logger -> debug("PathImg ".$PathImg);
  4946.                 if (file_exists($PathImg)) {
  4947.                     $logger -> debug("The file $PathImg exists");
  4948.                     $Workflow[]=array('id_template' => $NomeWorkflow['id_template'],
  4949.                                     'name' => $NomeWorkflow['name'],
  4950.                                     'description' => $NomeWorkflow['description'],
  4951.                                     'flow_image' => $NomeWorkflow['flow_image'],
  4952.                                     'type' => $NomeWorkflow['flag_type_checklist'],
  4953.                                     'file_exist' => 'Y');
  4954.                 } else {
  4955.                     $logger -> debug( "The file $PathImg does not exist" );
  4956.                     $Workflow[]=array('id_template' => $NomeWorkflow['id_template'],
  4957.                                     'name' => $NomeWorkflow['name'],
  4958.                                     'description' => $NomeWorkflow['description'],
  4959.                                     'flow_image' => $NomeWorkflow['flow_image'],
  4960.                                     'type' => $NomeWorkflow['flag_type_checklist'],
  4961.                                     'file_exist' => 'N');
  4962.                 }
  4963.                 
  4964.                     
  4965.             $sql1="select  t.*, s.* ,ta.*
  4966.                 from task t left join pre_chklsttmpl2task pct on (t.id=pct.task_id )
  4967.                             left join chklst_template ct on (pct.chklsttmpl_id = ct.id )
  4968.                             left join task2server ts on (t.id = ts.task_id)
  4969.                             left join server s on (ts.server_id = s.id)
  4970.                             left join task_anagrafica ta on (t.cmd_type = ta.tipo_task)
  4971.                 where  ct.id = :idTemplate
  4972.                 order by pct.task_order";
  4973.             
  4974.             $stmt1 = $conn->prepare($sql1);
  4975.             $stmt1->bindValue('idTemplate', $id);
  4976.             $stmt1->execute();
  4977.             $TaskWorkflow = $stmt1->fetchAll();
  4978.             foreach($TaskWorkflow as $obj)
  4979.             {
  4980.                 $ObjWlf[]=array("NomeTask" =>$obj['name'],
  4981.                                 "description" =>$obj['description'],
  4982.                                 "cmd_type" =>$obj['cmd_type'],
  4983.                                 "cmd_text" =>$obj['cmd_text'],
  4984.                                 "config_json" => json_decode($obj['config_json'], true),
  4985.                                 "descrizione_task" =>$obj["descrizione_task"],
  4986.                                 //task anagrafica
  4987.                                 "tipologia_task" =>$obj['tipologia_task'],
  4988.                                 "path_image_task" =>$obj['path_image_task'],
  4989.                                 //db
  4990.                                 "type_db" =>$obj['type_db'],
  4991.                                 "ip_db" =>$obj['ip_db'],
  4992.                                 "port_db" =>$obj['port_db'],
  4993.                                 "name_db" =>$obj['name_db'],
  4994.                                 "service" =>$obj['service'],
  4995.                                 "connection_direct" => ($obj['connection_direct'] == 'Y' ? 'SI' : 'NO'),
  4996.                                 "use_certificate_db" => $obj['use_certificate_db'],
  4997.                                 //ssh
  4998.                                 "ip_address" =>$obj['ip_address'],
  4999.                                 "hostname" =>$obj['hostname'],
  5000.                                 "username" =>$obj['username'],
  5001.                                 "ssh_port" =>$obj['ssh_port'],
  5002.                                 "flag_run_as" =>$obj['flag_run_as'],
  5003.                                 "run_as_user" =>$obj['run_as_user'],
  5004.                                 "flag_run_as_user_password" =>$obj['flag_run_as_user_password'],
  5005.                                 "run_as_password" =>$obj['run_as_password'],
  5006.                                 //mail
  5007.                                 "flag_mail_attachment" =>$obj['flag_mail_attachment'],
  5008.                                 "mail_attachment" =>$obj['mail_attachment'],
  5009.                                 "send_to_mail" =>$obj['send_to_mail'],
  5010.                                 "send_cc_mail" =>$obj['send_cc_mail'],
  5011.                                 "send_text_mail" =>$obj['send_text_mail'],
  5012.                                 "send_object_mail" =>$obj['send_object_mail']
  5013.                             
  5014.                             );
  5015.             }
  5016.             $user = $this->getUser();
  5017.             
  5018.             $sql="select * from roles";
  5019.             $stmt = $em->getConnection()->prepare($sql);
  5020.             $stmt->execute();
  5021.             $roles = $stmt->fetchAll();
  5022.             $logger->debug("---> ".json_encode($ObjWlf));
  5023.             
  5024.             return $this->render('generatePDF.html.twig',
  5025.             array(    
  5026.                 "NomeWorkflow" => $Workflow,
  5027.                 "TaskWorkflow" => $ObjWlf,                
  5028.                 'logged_user' => $user,
  5029.                 'roles' => $roles
  5030.                 ) );
  5031.     }
  5032.     function createPdf($id, LoggerInterface $logger, ParameterBagInterface $params)
  5033.     {
  5034.         $em = $this->getDoctrine()->getManager();
  5035.         $conn = $em->getConnection();
  5036.         $sql="select ct.id id_template, ct.name  , ct.description, cj.flow_image
  5037.                     from chklst_template ct left  join chklst_jflow cj on ( ct.id = cj.chklst_template)
  5038.                     where  ct.id = :idTemplate";
  5039.                 
  5040.             $stmt = $conn->prepare($sql);
  5041.             $stmt->bindValue('idTemplate', $id);
  5042.             $stmt->execute();
  5043.             $NomeWorkflow =$stmt->fetchAll()[0];
  5044.             
  5045.             $date = new \DateTime();
  5046.             $DataPdf = $date->format('Y-m-d');
  5047.             $NomePDF=$NomeWorkflow['name'].'_'.$DataPdf.'.pdf';
  5048.             $logger->debug("Nome PDF ".$NomePDF);
  5049.         
  5050.             $PathImg=$params->get('kernel.project_dir') .'/public/'. $NomeWorkflow['flow_image'];    
  5051.         
  5052.             $logger -> info("PathImg ".$PathImg);
  5053.                 if (file_exists($PathImg)) {
  5054.                     $logger -> info("The file $PathImg exists");
  5055.                     $Workflow[]=array('id_template' => $NomeWorkflow['id_template'],
  5056.                                         'name' => $NomeWorkflow['name'],
  5057.                                         'description' => $NomeWorkflow['description'],
  5058.                                         'flow_image' => $NomeWorkflow['flow_image'],
  5059.                                         'file_exist' => 'Y');
  5060.                 } else {
  5061.                     $logger -> info( "The file $PathImg does not exist" );
  5062.                     $Workflow[]=array('id_template' => $NomeWorkflow['id_template'],
  5063.                                     'name' => $NomeWorkflow['name'],
  5064.                                         'description' => $NomeWorkflow['description'],
  5065.                                         'flow_image' => $NomeWorkflow['flow_image'],
  5066.                                         'file_exist' => 'N');
  5067.                 }
  5068.                 $logger -> info("Workflow ".json_encode($Workflow));
  5069.             
  5070.         
  5071.             
  5072.     $sql1 = "select  t.*, s.* ,ta.*
  5073.                 from task t left join pre_chklsttmpl2task pct on (t.id=pct.task_id )
  5074.                             left join chklst_template ct on (pct.chklsttmpl_id = ct.id )
  5075.                             left join task2server ts on (t.id = ts.task_id)
  5076.                             left join server s on (ts.server_id = s.id)
  5077.                             left join task_anagrafica ta on (t.cmd_type = ta.tipo_task)
  5078.                 where  ct.id = :idTemplate
  5079.                 order by pct.task_order";
  5080.     $stmt1 = $conn->prepare($sql1);
  5081.             $stmt1->bindValue('idTemplate', $id);
  5082.             $stmt1->execute();
  5083.             $TaskWorkflow1 = $stmt1->fetchAll();
  5084.             foreach($TaskWorkflow1 as $obj)
  5085.             {
  5086.                 $ObjWlf[]=array("NomeTask" =>$obj['name'],
  5087.                                 "description" =>$obj['description'],
  5088.                                 "cmd_type" =>$obj['cmd_type'],
  5089.                                 "cmd_text" =>$obj['cmd_text'],
  5090.                                 "config_json" => json_decode($obj['config_json'], true),
  5091.                                 "descrizione_task" =>$obj["descrizione_task"],
  5092.                                 //task anagrafica
  5093.                                 "tipologia_task" =>$obj['tipologia_task'],
  5094.                                 "path_image_task" =>$obj['path_image_task'],
  5095.                                 //db
  5096.                                 "type_db" =>$obj['type_db'],
  5097.                                 "ip_db" =>$obj['ip_db'],
  5098.                                 "port_db" =>$obj['port_db'],
  5099.                                 "name_db" =>$obj['name_db'],
  5100.                                 "service" =>$obj['service'],
  5101.                                 "connection_direct" => ($obj['connection_direct'] == 'Y' ? 'SI' : 'NO'),
  5102.                                 "use_certificate_db" => $obj['use_certificate_db'],
  5103.                                 //ssh
  5104.                                 "ip_address" =>$obj['ip_address'],
  5105.                                 "hostname" =>$obj['hostname'],
  5106.                                 "username" =>$obj['username'],
  5107.                                 "ssh_port" =>$obj['ssh_port'],
  5108.                                 "flag_run_as" =>$obj['flag_run_as'],
  5109.                                 "run_as_user" =>$obj['run_as_user'],
  5110.                                 "flag_run_as_user_password" =>$obj['flag_run_as_user_password'],
  5111.                                 "run_as_password" =>$obj['run_as_password'],
  5112.                                 //mail
  5113.                                 "flag_mail_attachment" =>$obj['flag_mail_attachment'],
  5114.                                 "mail_attachment" =>$obj['mail_attachment'],
  5115.                                 "send_to_mail" =>$obj['send_to_mail'],
  5116.                                 "send_cc_mail" =>$obj['send_cc_mail'],
  5117.                                 "send_text_mail" =>$obj['send_text_mail'],
  5118.                                 "send_object_mail" =>$obj['send_object_mail']
  5119.                             
  5120.                             );
  5121.             }
  5122.             $pdfOptions = new Options();
  5123.             
  5124.             
  5125.             $logger->debug("renderView templatePDF");
  5126.             $html = $this->renderView('templatePDF.html.twig', [
  5127.             // 'title' => "Welcome to our PDF Test",
  5128.                 'NomeWorkflow' => $Workflow,
  5129.                 'TasksWorkflow' => $ObjWlf,
  5130.                 'BasePath' =>$params->get('kernel.project_dir').'/public'
  5131.             ]);
  5132.     
  5133.         // Configura Dompdf e genera il PDF
  5134.         $logger->debug("Configura Dompdf e genera il PDF");
  5135.         //$pdfOptions->set('defaultFont', 'Helvetica');
  5136.         //$pdfOptions->set('isRemoteEnabled', true);
  5137.         //$pdfOptions->set('isHtml5ParserEnabled', true);
  5138.         $pdfOptions->set('chroot', $params->get('kernel.project_dir')); // Assicurati che sia il percorso corretto
  5139.         $dompdf = new Dompdf($pdfOptions);
  5140.         $logger->debug("setBasePath");
  5141.             $dompdf->setBasePath($params->get('kernel.project_dir').'/public'); // Imposta il percorso base dove risiedono i CSS
  5142.             
  5143.             $logger->debug("carica html");
  5144.             $dompdf->loadHtml($html);
  5145.             $logger->debug("stampo html ".$html);
  5146.         
  5147.             // (Opzionale) Imposta le dimensioni del foglio e l'orientamento
  5148.             $logger->debug("setpaper");
  5149.             $dompdf->setPaper('A4', 'landscape');
  5150.         
  5151.             // Renderizza il PDF
  5152.             $dompdf->render();
  5153.             $logger->debug("render");
  5154.     
  5155.                 // Invia il PDF al browser
  5156.             /*$dompdf->stream($NomePDF, [  "Attachment" => true // Per visualizzare il PDF nel browser 
  5157.             ]);*/
  5158.             // Dopo aver generato il PDF
  5159.             $pdfOutput = $dompdf->output(); 
  5160.             $response = new Response($pdfOutput);
  5161.             $response->headers->set('Content-Type', 'application/pdf');
  5162.             $response->headers->set('Content-Disposition', 'attachment; filename="'.$NomePDF.'"'); 
  5163.             $publicDirectory = $params->get('kernel.project_dir') . '/public/chklst_exports/doc_pdf/';
  5164.             // e.g /var/www/project/public/mypdf.pdf
  5165.             $pdfFilepath =  $publicDirectory . $NomePDF;
  5166.             
  5167.             if (!file_exists($publicDirectory)) {
  5168.                 mkdir($publicDirectory, 0777, true);
  5169.             }
  5170.             
  5171.             // Write file to the desired path
  5172.             file_put_contents($pdfFilepath, $pdfOutput);
  5173.             
  5174.             return  $NomePDF;  
  5175.     }
  5176.     public function downloadPDFAction($id, $csrftoken, $typeCall, LoggerInterface $logger, ParameterBagInterface $params)
  5177.         {
  5178.             
  5179.             if (!$this->isCsrfTokenValid('download_pdf', $csrftoken)) {
  5180.                 throw new \Exception('Csrf token not valid');
  5181.             }
  5182.             $em = $this->getDoctrine()->getManager();
  5183.             $conn = $em->getConnection();
  5184.             $res_json = new JsonResponse();
  5185.             
  5186.             $logger->debug("[downloadPDFAction] idTemplate ".$id);
  5187.             
  5188.             $arrayId = strpos($id, ',');
  5189.             $logger->debug("[downloadPDFAction] arrayId ".$arrayId);
  5190.             if (!$arrayId)
  5191.             {
  5192.                 $logger->debug("[downloadPDFAction] Workflow Singolo ".$id);
  5193.                 $file=$this->createPdf($id,  $logger, $params);
  5194.                 if ($typeCall == 'internal')
  5195.                 {
  5196.                     return $file;
  5197.                 }
  5198.                 else
  5199.                 {
  5200.                     return $res_json->setData(array('nome_file' => $file));
  5201.                 }
  5202.                 
  5203.                 
  5204.             }            
  5205.             else
  5206.             {
  5207.                 $logger->debug("[downloadPDFAction] Scarico piu workflow ".$arrayId);
  5208.                 $zip = new \ZipArchive();
  5209.                 $target_dir = $params->get('kernel.project_dir') . '/public/chklst_exports/doc_pdf/';            
  5210.                 $logger->debug("[downloadPDFAction] Creo zip file su directory ".$target_dir    );
  5211.             
  5212.                 $zipName = 'Sybot_Documentazione_Workflow_' . time() . ".zip";
  5213.                 $logger->debug("[downloadPDFAction] Nome Zip ".$zipName);
  5214.             
  5215.                 if ($zip->open($target_dir . $zipName, \ZipArchive::CREATE )!==TRUE) {
  5216.                     
  5217.                     $logger->debug("[downloadPDFAction]non posso aprire ".$target_dir . $zipName);
  5218.                 }
  5219.                 else
  5220.                 {
  5221.                 
  5222.                 $logger->debug("[downloadPDFAction] Apro lo zip");
  5223.                 $array = explode(',', $id);
  5224.                 foreach( $array as $a)
  5225.                 {
  5226.                     $logger->debug("[downloadPDFAction] Scarico piu workflow ".$a);
  5227.                     $file=$this->createPdf($a,  $logger, $params);
  5228.                     $logger->debug("[downloadPDFAction] File creato ".$file);
  5229.                     if (file_exists($target_dir.$file))
  5230.                     {                
  5231.                         $logger->debug("[downloadPDFAction] il file ".$file."  esiste");
  5232.                         //$zip->addFromString($zipName, 'Aggiunto File '.$file);
  5233.                     $zip->addFile($target_dir.$file, $file );
  5234.                     
  5235.                     $logger->debug("[downloadPDFAction] File aggiunto allo zip ");
  5236.                 }
  5237.                 else
  5238.                 {$logger->debug("[downloadPDFAction] il file ".$file." non esiste");}
  5239.                 }
  5240.                 $zip->close();
  5241.                 }
  5242.                 $logger->debug("[downloadPDFAction] Chiudo lo Zip");
  5243.                 if ($typeCall == 'internal')
  5244.                 {
  5245.                     return $zipName;
  5246.                 }
  5247.                 else
  5248.                 {
  5249.                     return $res_json->setData(array('nome_file' => $zipName));
  5250.                 }
  5251.                 
  5252.                 
  5253.                 
  5254.             }
  5255.         }
  5256.     public function getTaskResultJson($id, LoggerInterface $logger): Response
  5257.     {
  5258.         $em = $this->getDoctrine()->getManager();
  5259.         $conn = $em->getConnection();
  5260.         $stmt = $conn->prepare("
  5261.             SELECT name, result_json 
  5262.             FROM v_log_execution_task 
  5263.             WHERE chklst_task_id = :id
  5264.         ");
  5265.         $stmt->bindValue('id', $id);
  5266.         $stmt->execute();
  5267.         $res = $stmt->fetch();
  5268.         if (!$res) {
  5269.             return new Response('Not found', 404);
  5270.         }
  5271.         //Format JSON con indentazione
  5272.         $raw = trim($res['result_json']);
  5273.         $raw = preg_replace('/^\xEF\xBB\xBF/', '', $raw);
  5274.         $decoded = json_decode($raw, true);
  5275.         // se non Ã¨ JSON valido, lo restituisco così com’è
  5276.         $pretty = $decoded !== null
  5277.             ? json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
  5278.             : $raw;
  5279.         $response = new Response($pretty);
  5280.         $disposition = HeaderUtils::makeDisposition(
  5281.             HeaderUtils::DISPOSITION_ATTACHMENT,
  5282.             sprintf('Task_%s_result.json', $res['name'])
  5283.         );
  5284.         $response->headers->set('Content-Type', 'application/json; charset=UTF-8');
  5285.         $response->headers->set('Content-Disposition', $disposition);
  5286.         return $response;
  5287.     }
  5288.     public function getWorkflowResultJson($id, LoggerInterface $logger): Response
  5289.     {
  5290.         $em = $this->getDoctrine()->getManager();
  5291.         $conn = $em->getConnection();
  5292.         $stmt = $conn->prepare("select name, result_json from v_log_execution_workflow where chklst_id=:id");
  5293.         $stmt->bindValue('id', $id);
  5294.         $stmt->execute();
  5295.         $res = $stmt->fetch();
  5296.         if (!$res) {
  5297.             return new Response('Not found', 404);
  5298.         }
  5299.         //Format JSON con indentazione
  5300.         $raw = trim($res['result_json']);
  5301.         $raw = preg_replace('/^\xEF\xBB\xBF/', '', $raw);
  5302.         $decoded = json_decode($raw, true);
  5303.         // se non Ã¨ JSON valido, lo restituisco così com’è
  5304.         $pretty = $decoded !== null
  5305.             ? json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
  5306.             : $raw;
  5307.         $response = new Response($pretty);
  5308.         $disposition = HeaderUtils::makeDisposition(
  5309.             HeaderUtils::DISPOSITION_ATTACHMENT,
  5310.             sprintf('Workflow_%s_result.json', $res['name'])
  5311.         );
  5312.         $response->headers->set('Content-Type', 'application/json; charset=UTF-8');
  5313.         $response->headers->set('Content-Disposition', $disposition);
  5314.         return $response;
  5315.     }
  5316. }
  5317. // ----------------------------------------------------------------------------
  5318. // JFlowRemapper
  5319. // ----------------------------------------------------------------------------
  5320. class JFlowRemapper {
  5321.     private $logger;
  5322.     public function go(&$jflow, $logger, $connection) {
  5323.         $sql = "select id, tipo_task from task_anagrafica";
  5324.         $statement = $connection->prepare($sql);
  5325.         $statement->execute();
  5326.             
  5327.         foreach ($statement->fetchAll() as $row) {
  5328.             $taskType2Id[$row['tipo_task']] = $row['id'];
  5329.         }
  5330.         foreach ($jflow['nodeDataArray'] as &$node) 
  5331.         {                        
  5332.             if($node["category"]=="CommentGroup"){
  5333.                 continue;
  5334.             }
  5335.             $key   = $node["key"];
  5336.             $origKey = $key;
  5337.             $key   = str_replace("[TASK ","", $key);
  5338.             $key   = str_replace("]","", $key);
  5339.             $parts = explode("_", $key);
  5340.             $origAnagraficaId = $parts[2];
  5341.             $taskType = $node["taskType"];
  5342.             $currAnagraficaId = $taskType2Id[$taskType];
  5343.             $orig2CurrAnagraficaId[$origAnagraficaId] = $currAnagraficaId;
  5344.             $remappedKey = "[TASK $parts[0]_$parts[1]_$currAnagraficaId]";                        
  5345.             $node["key"] = $remappedKey;
  5346.         }
  5347.         foreach ($jflow['linkDataArray'] as &$link) 
  5348.         {
  5349.             $key   = $link["from"];
  5350.             $origKey = $key;
  5351.             $key   = str_replace("[TASK ","", $key);
  5352.             $key   = str_replace("]","", $key);
  5353.             $parts = explode("_", $key);
  5354.             $currAnagraficaId = $orig2CurrAnagraficaId[$parts[2]];
  5355.             $key   = "[TASK $parts[0]_$parts[1]_$currAnagraficaId]";
  5356.             $link["from"] = $key;
  5357.             $key   = $link["to"];
  5358.             $origKey = $key;
  5359.             $key   = str_replace("[TASK ","", $key);
  5360.             $key   = str_replace("]","", $key);
  5361.             $parts = explode("_", $key);
  5362.             $currAnagraficaId = $orig2CurrAnagraficaId[$parts[2]];
  5363.             $key   = "[TASK $parts[0]_$parts[1]_$currAnagraficaId]";
  5364.             $link["to"] = $key;
  5365.         }
  5366.     }
  5367. }
  5368. // ----------------------------------------------------------------------------
  5369. // ACM2SybotJFlowConverter
  5370. // ----------------------------------------------------------------------------
  5371. class ACM2SybotJFlowConverter {
  5372.     private $logger;
  5373.     private $connection;
  5374.     private $idTemplate;
  5375.     private $conditionIndex = 1;
  5376.     private $nextFreeTopPortIndex = [];
  5377.     private $sybotNodes = [];
  5378.     private $sybotLinkDataArray = [];
  5379.     public function go(
  5380.         $acmTasksById,    // id   => task acm (secondo l'id nella checklist ACM)
  5381.         $acmTasksByName,  // nome => task acm
  5382.         $logger, 
  5383.         $jflowRaw, 
  5384.         $idTemplate, 
  5385.         $acmTasksExtraInfo, 
  5386.         $connection) 
  5387.     {
  5388.         $this->logger = $logger;
  5389.         $this->connection = $connection;
  5390.         $this->idTemplate = $idTemplate;
  5391.         
  5392.         $jflow = json_decode($jflowRaw, true);
  5393.         $jflow["linkFromPortIdProperty"] = "fromPort";
  5394.         $jflow["linkToPortIdProperty"] = "toPort";
  5395.         
  5396.         $acmNodeDataArray = $jflow["nodeDataArray"];
  5397.         $acmLinkDataArray = $jflow["linkDataArray"];
  5398.         // --------------------------------------------------------------------
  5399.         // 
  5400.         // --------------------------------------------------------------------
  5401.         
  5402.         // --------------------------------------------------------------------
  5403.         // Fase 0 - Nodi (1° parte)
  5404.         // --------------------------------------------------------------------
  5405.         
  5406.         foreach ($acmNodeDataArray as $acmNode) 
  5407.         {
  5408.             if($acmNode["category"] == "End") {
  5409.                 continue;
  5410.             }
  5411.             $acmKey          = $acmNode["key"];
  5412.             $acmKey          = str_replace("[TASK ","", $acmKey);
  5413.             $acmKey          = str_replace("]","", $acmKey);
  5414.             $parts           = explode("_", $acmKey);
  5415.             $acmTaskId       = $parts[1];
  5416.             $acmTask         = $acmTasksById[$acmTaskId];
  5417.             $currentTaskInfo = $acmTasksExtraInfo[$acmTaskId];
  5418.             $sybotTaskId     = $currentTaskInfo["newId"];
  5419.             $cmdType         = $currentTaskInfo["cmdType"];
  5420.             $sql = "select id, tipologia_task, descrizione_task, tipo_task from task_anagrafica where tipo_task = :cmdType";
  5421.             $statement = $connection->prepare($sql);
  5422.             $statement->bindValue("cmdType", $cmdType);
  5423.             $statement->execute();
  5424.             $queryResult = $statement->fetchAll();
  5425.             $idTaskAnagrafica = $queryResult[0]["id"];
  5426.             $acmTasksExtraInfo[$acmTaskId]['cmdTypeId'] = $idTaskAnagrafica;
  5427.         }
  5428.         // --------------------------------------------------------------------
  5429.         // Fase 1 - Nodi (2° parte)
  5430.         // --------------------------------------------------------------------
  5431.         $logger->debug("------- FASE 1");
  5432.         foreach ($acmNodeDataArray as $acmNode) 
  5433.         {
  5434.             if($acmNode["category"] == "End") {
  5435.                 continue;
  5436.             }
  5437.             $acmKey          = $acmNode["key"];
  5438.             $acmKey          = str_replace("[TASK ","", $acmKey);
  5439.             $acmKey          = str_replace("]","", $acmKey);
  5440.             $parts           = explode("_", $acmKey);
  5441.             $acmTaskId       = $parts[1];
  5442.             $acmTask         = $acmTasksById[$acmTaskId];
  5443.             $currentTaskInfo = $acmTasksExtraInfo[$acmTaskId];
  5444.             $sybotTaskId     = $currentTaskInfo["newId"];
  5445.             $cmdType         = $currentTaskInfo["cmdType"];
  5446.             $idTaskAnagrafica = $acmTasksExtraInfo[$acmTaskId]['cmdTypeId'];
  5447.             $sybotNode = array_merge(
  5448.                 $acmNode,
  5449.                 [
  5450.                     "key"              => "[TASK " . $idTemplate . "_" . $sybotTaskId . "_" . $idTaskAnagrafica . "]",
  5451.                     "taskType"         => $cmdType,
  5452.                     "descr_anagrafica" => $queryResult[0]["descrizione_task"],
  5453.                     "tipo_anagrafica"  => $queryResult[0]["tipologia_task"],
  5454.                     "statusCode"       => "success",
  5455.                     "statusText"       => "Task salvato con successo",
  5456.                     "leftArray"        => [],
  5457.                     "bottomArray"      => [],
  5458.                     "topArray"         => [],
  5459.                     "rightArray"       => []
  5460.                 ]
  5461.             );    
  5462.             for ($i=0; $i<5; $i++) {
  5463.                 $sybotNode["topArray"][] = [
  5464.                     "portId" => "top$i",
  5465.                     "portColor" => "transparent"    
  5466.                 ];                
  5467.             }
  5468.             for ($i=0; $i<5; $i++) {
  5469.                 $sybotNode["leftArray"][] = [
  5470.                     "portId" => "left$i",
  5471.                     "portColor" => "transparent"    
  5472.                 ];                
  5473.             }
  5474.             $this->sybotNodes[$sybotTaskId] = $sybotNode;
  5475.             // ----------------------------------------------------------------
  5476.             // Cleanup
  5477.             // ----------------------------------------------------------------
  5478.             $sql = "delete from task_conditional where id_task = :idTask and id_template = :idTemplate";
  5479.             $statement = $connection->prepare($sql);
  5480.             $statement->bindValue("idTask", $sybotTaskId);
  5481.             $statement->bindValue("idTemplate", $idTemplate);
  5482.             $statement->execute();
  5483.             // ----------------------------------------------------------------
  5484.             // Condizioni da XML
  5485.             // ----------------------------------------------------------------
  5486.             
  5487.             $acmOKTaskName = $acmTask['next_task'];
  5488.             $acmKOTaskName = $acmTask['action']['next_task_act'];
  5489.             try {
  5490.                                     
  5491.                 if ($cmdType == 'db' && $acmTask['flag_check_count_query'] == 'Y') 
  5492.                 {
  5493.                     $match_operator = $acmTask['match_operator'];
  5494.                     $match_value = $acmTask['match_value'];
  5495.                     if ($match_operator == "=") {
  5496.                         $match_operator = "==";
  5497.                     }
  5498.                     if ($acmOKTaskName) 
  5499.                     {
  5500.                         $acmOKTaskInfo = $acmTasksExtraInfo[$acmTasksByName[$acmOKTaskName]];
  5501.                         $expr = "#>" . $acmTask['name'] . ".count#< $match_operator $match_value";
  5502.                         $this->makeLink($currentTaskInfo, $acmOKTaskInfo, "custom", $expr);
  5503.                     }
  5504.                     
  5505.                     if ($acmKOTaskName) 
  5506.                     {
  5507.                         $expr = "!(#>" . $acmTask['name'] . ".count#< $match_operator $match_value)";
  5508.                         $acmKOTaskInfo = $acmTasksExtraInfo[$acmTasksByName[$acmKOTaskName]['id']];
  5509.                         $this->makeLink($currentTaskInfo, $acmKOTaskInfo, "custom", $expr);
  5510.                     }
  5511.             
  5512.                 } 
  5513.                 else if ($cmdType == 'ssh') {                
  5514.                     $match_operator = $acmTask['match_operator'];
  5515.                     $match_value = $acmTask['match_value'];
  5516.                     $return_type = $acmTask['return_type'];
  5517.                     if ($acmTask['flag_check_exit_status'] == 'Y') 
  5518.                     {
  5519.                         
  5520.                         if ($match_operator == "=") {
  5521.                             $match_operator = "==";
  5522.                         }
  5523.                         if ($acmOKTaskName) 
  5524.                         {
  5525.                             $acmOKTaskInfo = $acmTasksExtraInfo[$acmTasksByName[$acmOKTaskName]];
  5526.                             $expr = "#>" . $acmTask['name'] . ".exitStatus#< $match_operator $match_value";
  5527.                             $this->makeLink($currentTaskInfo, $acmOKTaskInfo, "custom", $expr);
  5528.                         }
  5529.                         
  5530.                         if ($acmKOTaskName) 
  5531.                         {
  5532.                             $expr = "!(#>" . $acmTask['name'] . ".exitStatus#< $match_operator $match_value)";
  5533.                             $acmKOTaskInfo = $acmTasksExtraInfo[$acmTasksByName[$acmKOTaskName]['id']];
  5534.                             $this->makeLink($currentTaskInfo, $acmKOTaskInfo, "custom", $expr);
  5535.                         }
  5536.                     } else {
  5537.                         if ($return_type == 'text') {
  5538.                             $str1 = "#>" . $acmTask['name'] . ".result<#";
  5539.                             switch ($match_operator) 
  5540.                             {
  5541.                                 case "starts with":
  5542.                                     $expr = "startswith($str1, \"$match_value\")";
  5543.                                     break;
  5544.                                 case "contains":
  5545.                                     $expr = "contains($str1, \"$match_value\")";
  5546.                                     break;
  5547.                                 case "ends with":
  5548.                                     $expr = "endswith($str1, \"$match_value\")";
  5549.                                     break;
  5550.                                 case "equal to":
  5551.                                     $expr = "$str1 == \"$match_value\"";
  5552.                                     break;
  5553.                                 case "regexp":
  5554.                                     $expr = "regexp($str1, \"$match_value\")";
  5555.                                     break;
  5556.                                 default:
  5557.                                     break;                                    
  5558.                             }
  5559.                             if ($acmOKTaskName) {
  5560.                                 $acmOKTaskInfo = $acmTasksExtraInfo[$acmTasksByName[$acmOKTaskName]['id']];
  5561.                                 $this->makeLink($currentTaskInfo, $acmOKTaskInfo, "custom", $expr);
  5562.                             }
  5563.                             
  5564.                             if ($acmKOTaskName) {
  5565.                                 $acmKOTaskInfo = $acmTasksExtraInfo[$acmTasksByName[$acmKOTaskName]['id']];
  5566.                                 $this->makeLink($currentTaskInfo, $acmKOTaskInfo, "custom", $expr);
  5567.                             }
  5568.                         
  5569.                         } else if ($return_type == 'number') {
  5570.                             if ($match_operator == "=") {
  5571.                                 $match_operator = "==";
  5572.                             }
  5573.     
  5574.                             if ($acmOKTaskName) 
  5575.                             {
  5576.                                 
  5577.                                 $acmOKTaskInfo = $acmTasksExtraInfo[$acmTasksByName[$acmOKTaskName]['id']];
  5578.                                 $expr = "#>" . $acmTask['name'] . ".result#< $match_operator $match_value";
  5579.                                 $this->makeLink($currentTaskInfo, $acmOKTaskInfo, "custom", $expr);
  5580.                             } 
  5581.                             
  5582.                             if ($acmKOTaskName) 
  5583.                             {
  5584.                                 $expr = "!(#>" . $acmTask['name'] . ".result#< $match_operator $match_value)";
  5585.                                 $acmKOTaskInfo = $acmTasksExtraInfo[$acmTasksByName[$acmKOTaskName]['id']];
  5586.                                 $this->makeLink($currentTaskInfo, $acmKOTaskInfo, "custom", $expr);
  5587.                             }
  5588.                         }
  5589.                     }
  5590.                 }                                
  5591.                 else 
  5592.                 {
  5593.                     if ($acmOKTaskName) 
  5594.                     {
  5595.                         $acmOKTaskInfo = $acmTasksExtraInfo[$acmTasksByName[$acmOKTaskName]['id']];
  5596.                         $this->makeLink($currentTaskInfo, $acmOKTaskInfo, "default");
  5597.                     }
  5598.                     if ($acmKOTaskName) 
  5599.                     {
  5600.                         $acmKOTaskInfo = $acmTasksExtraInfo[$acmTasksByName[$acmKOTaskName]['id']];
  5601.                         $this->makeLink($currentTaskInfo, $acmKOTaskInfo, "ko");
  5602.                     }
  5603.                 }
  5604.                 
  5605.             } catch (\Error $err) {
  5606.                 $logger->debug("Eccezione: " . $err->getMessage() . " line: " . $err->getLine());
  5607.             }
  5608.         }
  5609.         // --------------------------------------------------------------------
  5610.         // Fase 2 - Links
  5611.         // --------------------------------------------------------------------
  5612.         $logger->debug("------- FASE 2");
  5613.         
  5614.         foreach ($acmLinkDataArray as $acmLink) 
  5615.         {
  5616.             if(str_contains($acmLink["to"], "END")) { 
  5617.                 continue;
  5618.             }
  5619.     
  5620.             if(str_contains($acmLink["from"], "END")) { 
  5621.                 continue;
  5622.             }    
  5623.             if(array_key_exists("color", $acmLink)) {
  5624.                 continue;
  5625.             }
  5626.             
  5627.             $keyFrom = $acmLink["from"];
  5628.             $keyFrom = str_replace("[TASK ","", $keyFrom);
  5629.             $keyFrom = str_replace("]","", $keyFrom);
  5630.             $parts = explode("_", $keyFrom);
  5631.             $acmIdOfTaskFrom = $parts[1];
  5632.             $taskFromInfo = $acmTasksExtraInfo[$acmIdOfTaskFrom];
  5633.             if (array_key_exists('default_done', $taskFromInfo)) {
  5634.                 continue;
  5635.             }
  5636.             
  5637.             $taskFromInfo['default_done'] = true;
  5638.             $keyTo = $acmLink["to"];
  5639.             $keyTo = str_replace("[TASK ","", $keyTo);
  5640.             $keyTo = str_replace("]","", $keyTo);
  5641.             $parts = explode("_", $keyTo);
  5642.             $acmIdOfTaskTo = $parts[1];
  5643.             $taskToInfo = $acmTasksExtraInfo[$acmIdOfTaskTo];    
  5644.             $this->makeLink($taskFromInfo, $taskToInfo, "default");
  5645.         }
  5646.         // --------------------------------------------------------------------
  5647.         // Fase 3 - output
  5648.         // --------------------------------------------------------------------
  5649.         $lastTask = end($jflow["nodeDataArray"]);
  5650.         $this->makeLastLink($lastTask, $acmTasksExtraInfo, $logger);
  5651.         $jflow["nodeDataArray"] = array_values($this->sybotNodes);
  5652.         $jflow["linkDataArray"] = $this->sybotLinkDataArray;
  5653.         return json_encode($jflow);
  5654.         
  5655.     }
  5656.     private function makeLastLink($lastTask, $acmTasksExtraInfo, $logger) {
  5657.         $logger->debug("[ACM] [END] Inserimento ultimo link [{$lastTask['text']}]");
  5658.         $conditionIndex = $this->conditionIndex;
  5659.         $taskKeyRaw         = $lastTask['key'];                               // Es: [TASK 8_27]
  5660.         $taskKeyClean       = str_replace(["[TASK ", "]"], "", $taskKeyRaw); // Es: 8_27
  5661.         $taskKeyParts       = explode("_", $taskKeyClean);                     // Es: ["8", "27"]
  5662.         $taskSequenceNumber = end($taskKeyParts);                            // Es: 27
  5663.         $lastTaskId = $acmTasksExtraInfo[$taskSequenceNumber];
  5664.         $node = &$this->sybotNodes[$lastTaskId['newId']];
  5665.         $node["rightArray"][] = [
  5666.             "portId" => "port_" . $this->idTemplate . "_" . $lastTaskId['newId'] . "_" . $conditionIndex,
  5667.             "portColor" => "green",
  5668.             "portConditionType" => "default"
  5669.         ];
  5670.     }
  5671.     
  5672.     private function makeLink($taskFromInfo, $taskToInfo, $conditionType, $expr=null) {
  5673.         $conditionIndex = $this->conditionIndex;
  5674.         $node = &$this->sybotNodes[$taskFromInfo['newId']];
  5675.         switch ($conditionType) {
  5676.             case "default":
  5677.                 $color = "green";
  5678.                 break;
  5679.             case "ko":
  5680.                 $color = "red";
  5681.                 break;
  5682.             case "custom":
  5683.                 $color = "dodgerblue";
  5684.                 break;
  5685.             default:
  5686.                 $color = "gray";
  5687.                 break;
  5688.         }
  5689.         $node["rightArray"][] = [
  5690.             "portId" => "port_" . $this->idTemplate . "_" . $taskFromInfo['newId'] . "_" . $conditionIndex,
  5691.             "portColor" => $color,
  5692.             "portConditionType" => $conditionType
  5693.         ];
  5694.         $link = array();
  5695.         $link["from"] = "[TASK " . $this->idTemplate . "_" . $taskFromInfo['newId'] . "_" . $taskFromInfo['cmdTypeId'] . "]";
  5696.         $link["to"] = "[TASK " . $this->idTemplate . "_" . $taskToInfo['newId'] . "_" . $taskToInfo['cmdTypeId'] . "]";
  5697.         
  5698.         $link["fromPort"] = "port_" . $this->idTemplate . "_" . $taskFromInfo['newId'] . "_" . $conditionIndex;
  5699.         if (!isset($this->nextFreeTopPortIndex[$taskToInfo['newId']])) {
  5700.             $this->nextFreeTopPortIndex[$taskToInfo['newId']] = 1;
  5701.         }
  5702.         $link["toPort"] = "top" . $this->nextFreeTopPortIndex[$taskToInfo['newId']];
  5703.         if ($this->nextFreeTopPortIndex[$taskToInfo['newId']] < 5) {                    
  5704.             $this->nextFreeTopPortIndex[$taskToInfo['newId']] ++;
  5705.         }
  5706.         if ($this->linkAlreadyExists($link)) {
  5707.             $this->logger->debug("evito di creare link duplicato", json_encode($link));
  5708.             return;
  5709.         }
  5710.         $sql = 
  5711.             "insert into task_conditional (id_task, nome, tipo, espressione, id_template) 
  5712.             values (:idTask, 'Condizione ". $conditionIndex . "', '$conditionType', :expr, :idTemplate)";
  5713.         $statement = $this->connection->prepare($sql);
  5714.         $statement->bindValue("idTask", $taskFromInfo['newId']);
  5715.         $statement->bindValue("idTemplate", $this->idTemplate);
  5716.         $statement->bindValue("expr", $expr);
  5717.         $statement->execute();            
  5718.         $link["color"] = $color;
  5719.         $link["text"] = "Condizione " . $conditionIndex;    
  5720.         $this->conditionIndex ++;
  5721.         $this->sybotLinkDataArray[] = $link;
  5722.     }
  5723.     private function linkAlreadyExists($link) {
  5724.         foreach ($this->sybotLinkDataArray as $existingLink) {
  5725.             if ($existingLink['from'] == $link['from'] &&
  5726.                 $existingLink['to'] == $link['to'] &&
  5727.                 $existingLink['fromPort'] == $link['fromPort'] &&
  5728.                 $existingLink['toPort'] == $link['toPort']) {                
  5729.                 return true;
  5730.             }
  5731.         }
  5732.         return false;
  5733.     }
  5734. }