static function defaultAction(Request $request, Service $service, $repositoryName)
 {
     $repository = $service->getRepository($repositoryName);
     if ($repository) {
         $response = new JsonResponse();
         $etag = md5($repository->getLastModifiedDate());
         $response->setEtag($etag);
         if ($response->isNotModified($request)) {
             $response->send();
             return $response;
         }
         $result = [];
         $result['content'] = [];
         foreach ($repository->getContentTypeDefinitions() as $definition) {
             $result['content'][$definition->getName()]['title'] = $definition->getTitle() ? $definition->getTitle() : $definition->getName();
             $result['content'][$definition->getName()]['lastchange_content'] = $repository->getLastModifiedDate($definition->getName());
             $result['content'][$definition->getName()]['lastchange_cmdl'] = 0;
             // TODO
         }
         $response->setContent(json_encode($result, JSON_PRETTY_PRINT));
         $response->setEtag($etag);
         $response->setPublic();
         return $response;
     }
 }
 public function indexAction()
 {
     $util = new Util();
     //$key = $request->query->get('key',0);
     $vvaList = $this->getDoctrine()->getRepository('IglesysGeneralBundle:ValorVariable')->findAll();
     $response = new JsonResponse();
     $response->setContent($util->getSerialize($vvaList));
     return $response;
 }
 /**
  * @Route("/upcoming")
  */
 public function getEventCategoriesAction(Request $request)
 {
     $events = $this->get('event_manager')->getUpcomingEvents();
     $serializer = $this->get('jms_serializer');
     $jsonContent = $serializer->serialize($events, 'json');
     $response = new JsonResponse();
     $response->setContent($jsonContent);
     return $response;
 }
示例#4
0
 /**
  *
  * @param User $mainUser
  * @param User $secendaryUser
  * @param Request $request
  *
  * @ParamConverter("mainUser", class="AppBundle:User", options={"id" = "mainUserId"})
  * @ParamConverter("secendaryUser", class="AppBundle:User", options={"id" = "secendaryUserId"})
  */
 public function conversationShowAction(User $mainUser, User $secendaryUser, Request $request)
 {
     $repo = $this->getDoctrine()->getRepository('AppBundle:Message');
     $order = $request->query->get('order', 'desc');
     $messages = $repo->getConversation($mainUser, $secendaryUser, $order);
     $serializer = $this->get('serializer');
     $response = new JsonResponse();
     $response->setContent($serializer->serialize($messages, 'json', array('groups' => array('main'))));
     return $response;
 }
 /**
  * method checks if there are jobs which are enabled but did not return 0 on last execution or are locked.<br>
  * if a match is found, HTTP status 417 is sent along with an array which contains name, return code and locked-state.
  * if no matches found, HTTP status 200 is sent with an empty array
  *
  * @return JsonResponse
  */
 public function monitorAction()
 {
     $scheduledCommands = $this->getMonitoringData();
     $failed = $this->monitorService->processCommandsJSON($scheduledCommands);
     $status = count($failed) > 0 ? Response::HTTP_EXPECTATION_FAILED : Response::HTTP_OK;
     $response = new JsonResponse();
     $response->setContent(json_encode($failed));
     $response->setStatusCode($status);
     return $response;
 }
 /**
  * @Route("/")
  */
 public function getEventCategoriesAction(Request $request)
 {
     $repository = $this->getDoctrine()->getRepository('AppBundle:EventCategory');
     $categories = $repository->findAll();
     $serializer = $this->get('jms_serializer');
     $jsonContent = $serializer->serialize($categories, 'json');
     $response = new JsonResponse();
     $response->setContent($jsonContent);
     return $response;
 }
示例#7
0
 public function subjectAction($name)
 {
     $url = "/subject?name=" . $name;
     $response = $this->request($url);
     $responseBodyJson = $response->getBody();
     $serializer = $this->get('serializer');
     $responseBody = $serializer->deserialize($responseBodyJson, 'array', 'json');
     //$responseBody = json_decode($responseBodyJson, true);
     $preferredNames = array();
     foreach ($responseBody as $element) {
         if (isset($element["@graph"])) {
             if (isset($element["@graph"][0]["@type"])) {
                 $types = $element["@graph"][0]["@type"];
                 $geographicNameIdentifierFound = false;
                 $territoryOrAdministrativeUnitIdenitifierFound = false;
                 if (is_array($types)) {
                     foreach ($types as $type) {
                         if ($type == "http://d-nb.info/standards/elementset/gnd#PlaceOrGeographicName") {
                             $geographicNameIdentifierFound = true;
                             continue;
                         }
                         if ($type == "http://d-nb.info/standards/elementset/gnd#TerritorialCorporateBodyOrAdministrativeUnit") {
                             $territoryOrAdministrativeUnitIdenitifierFound = true;
                         }
                     }
                 } else {
                     // not necessary to check here?
                 }
                 if ($geographicNameIdentifierFound && $territoryOrAdministrativeUnitIdenitifierFound) {
                     if (isset($element["@graph"][0]["preferredNameForThePlaceOrGeographicName"])) {
                         if (is_array($element["@graph"][0]["preferredNameForThePlaceOrGeographicName"])) {
                             foreach ($element["@graph"][0]["preferredNameForThePlaceOrGeographicName"] as $name) {
                                 $name = addslashes(trim($name));
                                 if (!in_array($name, $preferredNames)) {
                                     $preferredNames[] = $name;
                                 }
                             }
                         } else {
                             $this->getLogger()->debug("Possible preferred Names: " . $element["@graph"][0]["preferredNameForThePlaceOrGeographicName"]);
                             $singleName = addslashes(trim($element["@graph"][0]["preferredNameForThePlaceOrGeographicName"]));
                             if (!in_array($singleName, $preferredNames)) {
                                 $preferredNames[] = $singleName;
                             }
                         }
                     }
                 }
             }
         }
     }
     //Lipsk
     $jsonResponse = new JsonResponse();
     $jsonResponse->setContent($serializer->serialize($preferredNames, 'json'));
     return $jsonResponse;
 }
 public function findPossibleRelativesAction($ID)
 {
     $this->getLogger()->info("FindPossibleRelativesAction called: " . $ID);
     $em = $this->get('doctrine')->getManager('final');
     $possibleRelatives = $this->get('possible_relatives_finder.service')->findPossibleRelatives($em, $ID);
     $serializer = $this->container->get('serializer');
     $json = $serializer->serialize($possibleRelatives, 'json');
     $response = new JsonResponse();
     $response->setContent($json);
     return $response;
 }
示例#9
0
 public function getJSONResponse($obj)
 {
     if (get_class($obj) == self::PERSON_CLASS) {
         //$this->LOGGER->debug("PERSON: " . $obj . " has Sources: " . count($obj->getSources()));
     }
     $serializer = $this->container->get('serializer');
     $json = $serializer->serialize($obj, 'json');
     $response = new JsonResponse();
     $response->setContent($json);
     return $response;
 }
示例#10
0
 public function directIdAction($ID)
 {
     $relationShipLoader = $this->get('relationship_loader.service');
     $em = $this->get('doctrine')->getManager('new');
     $relatives = $relationShipLoader->loadOnlyDirectRelatives($em, $ID);
     $serializer = $this->container->get('serializer');
     $json = $serializer->serialize($relatives, 'json');
     $response = new JsonResponse();
     $response->setContent($json);
     return $response;
 }
示例#11
0
 public function deleteAction($id)
 {
     $util = new Util();
     //$key = $request->query->get('key',0);
     $valorVariable = $this->getDoctrine()->getRepository('IglesysGeneralBundle:ValorVariable')->find($id);
     if (!$valorVariable) {
         throw $this->createNotFoundException('No se encuentra el registro solicitado.');
     }
     $response = new JsonResponse();
     $response->setContent($util->getSerialize($valorVariable));
     return $response;
 }
 public function coletaAction(Request $request)
 {
     $logger = $this->get('logger');
     $status = $request->getContent();
     $em = $this->getDoctrine()->getManager();
     $dados = json_decode($status, true);
     if (empty($dados)) {
         $logger->error("JSON INVÁLIDO!!!!!!!!!!!!!!!!!!! Erro na COLETA");
         // Retorna erro se o JSON for inválido
         $error_msg = '{
             "message": "JSON Inválido",
             "codigo": 1
         }';
         $response = new JsonResponse();
         $response->setStatusCode('500');
         $response->setContent($error_msg);
         return $response;
     }
     $computador = $this->getComputador($dados, $request);
     if (empty($computador)) {
         // Se não identificar o computador, manda para o getUpdate
         $logger->error("Computador não identificado no getConfig. Necessário executar getUpdate");
         $error_msg = '{
             "message": "Computador não identificado",
             "codigo": 2
         }';
         $response = new JsonResponse();
         $response->setStatusCode('500');
         $response->setContent($error_msg);
         return $response;
     }
     //Verifica se a coleta foi forçada
     if ($computador->getForcaColeta() == 'true') {
         $computador->setForcaColeta('false');
         $this->getDoctrine()->getManager()->persist($computador);
         $this->getDoctrine()->getManager()->flush();
     }
     $result1 = $this->setHardware($dados['hardware'], $computador);
     $result2 = $this->setSoftware($dados['software'], $computador);
     $response = new JsonResponse();
     if ($result1 && $result2) {
         $response->setStatusCode('200');
     } else {
         $response->setStatusCode('500');
     }
     return $response;
 }
示例#13
0
 public function loadPersonListAction()
 {
     $content = $this->get("request")->getContent();
     if (!empty($content)) {
         $serializer = $this->get('serializer');
         $personIds = $serializer->deserialize($content, 'array', 'json');
         $personData = $this->loadPersonData($personIds);
         $json = $serializer->serialize($personData, 'json');
         $jsonResponse = new JsonResponse();
         $jsonResponse->setContent($json);
         return $jsonResponse;
     } else {
         $response = new Response();
         $response->setContent("Missing Content.");
         $response->setStatusCode("406");
         return $response;
     }
 }
示例#14
0
 public function findPossibleRelativesAction($database, $OID)
 {
     $em = null;
     if ($database == 'final') {
         $em = $this->get('doctrine')->getManager('final');
     } else {
         if ($database == 'new') {
             $em = $this->get('doctrine')->getManager('new');
         } else {
             throw new Exception("Invalid database");
         }
     }
     $possibleRelatives = $this->get('possible_relatives_finder.service')->findPossibleRelatives($em, $OID);
     $serializer = $this->container->get('serializer');
     $json = $serializer->serialize($possibleRelatives, 'json');
     $response = new JsonResponse();
     $response->setContent($json);
     return $response;
 }
示例#15
0
 /**
  * @Route("/api/users/get/", name="api_get_user_by_id")
  * @Template()
  */
 public function getUserByIdAction()
 {
     $data = array();
     $request = $this->getRequest();
     $encoders = array(new JsonEncoder());
     $normalizers = array(new GetSetMethodNormalizer());
     $serializer = new Serializer($normalizers, $encoders);
     // checking if was a post request
     if ($request->isMethod('POST')) {
         // getting post data
         $post_data = $request->request->all();
         $em = $this->getDoctrine()->getManager();
         $user_repository = $em->getRepository('Proethos2ModelBundle:User');
         $data = $user_repository->find($post_data['id']);
     }
     $jsonContent = $serializer->serialize($data, 'json');
     var_dump($jsonContent);
     $response = new JsonResponse();
     $response->setContent($jsonContent);
     return $response;
 }
 /**
  * List all members in Json format.
  * 
  * @example
  * {
  *   "members": [
  *     {
  *       "id": 1,
  *       "name": "Bland",
  *       "firstName": "\u00a0Angie",
  *       "phone": "0611111111"
  *     }
  *   ],
  *   "count": 1
  * }
  * 
  * @Route("/api/members")
  */
 public function listAction()
 {
     $response = new JsonResponse();
     $response->setCharset('UTF-8');
     $response->setEncodingOptions(JSON_PRETTY_PRINT);
     try {
         $this->initialize();
         $memberList = $this->memberRepository->findAll();
         if (empty($memberList)) {
             $response->setData('Aucun adhérent n’est présent');
         } else {
             $response->setData($this->memberFormatter->formatList($memberList));
         }
     } catch (FileNotFoundException $e) {
         $response->setContent("Le fichier d’entrée est introuvable");
         $response->setStatusCode(JsonResponse::HTTP_NOT_FOUND);
     } catch (\Exception $e) {
         $response->setStatusCode(JsonResponse::HTTP_INTERNAL_SERVER_ERROR);
     }
     return $response;
 }
示例#17
0
 /**
  * @ParamConverter("user", class="AppBundle:User")
  */
 public function updateAction(Request $request, User $user)
 {
     $form = $this->createForm(new UserType(), $user);
     $form->handleRequest($request);
     var_dump($form->getData());
     die;
     if (!$form->isValid()) {
         $ers = $form->getErrors(true, true);
         var_dump(count($ers));
         foreach ($ers as $er) {
             var_dump($er->getMessage());
         }
         return new Response('Data is not valid', Response::HTTP_BAD_REQUEST);
     }
     $entityManager = $this->getDoctrine()->getManager();
     $entityManager->flush();
     $serializer = $this->get('serializer');
     $response = new JsonResponse();
     $response->setContent($serializer->serialize($user, 'json', array('groups' => array('main'))));
     return $response;
 }
示例#18
0
 protected function processRequest(Request $request, Task &$task)
 {
     $response = new JsonResponse();
     $requestContent = json_decode($request->getContent(), true);
     if (!isset($requestContent['task'])) {
         return $response->setStatusCode(400)->setContent($this->serialize(['error' => ['params' => 'Malformed request, missing parameters']]));
     }
     $taskParams = $requestContent['task'];
     $task->setName($taskParams['name']);
     $task->setStartDate(new \DateTime($taskParams['startDate']));
     $task->setEndDate(new \DateTime($taskParams['endDate']));
     $task->setBandColor($taskParams['bandColor']);
     $errors = $this->get('validator')->validate($task);
     if (count($errors) > 0) {
         return $response->setStatusCode(400)->setContent($this->serialize(['error' => $errors]));
     }
     $this->getDoctrine()->getManager()->persist($task);
     $this->getDoctrine()->getManager()->flush();
     $response->setStatusCode(200);
     return $response->setContent($this->serialize(['task' => $task]));
 }
 public function loadDuplicatesAction($ID)
 {
     $this->getLogger()->debug("Loading duplicates: " . $ID);
     $em = $this->get('doctrine')->getManager('final');
     $duplicatePersons = $this->get('possible_duplicates_finder.service')->findPossibleDuplicates($em, $ID);
     if (count($duplicatePersons) > 0) {
         $duplicatesData = array();
         for ($i = 0; $i < count($duplicatePersons); $i++) {
             $duplicatesData[] = $this->loadPersonWithRelativesFromObj($duplicatePersons[$i]);
         }
         $serializer = $this->get('serializer');
         $json = $serializer->serialize($duplicatesData, 'json');
         $jsonResponse = new JsonResponse();
         $jsonResponse->setContent($json);
         return $jsonResponse;
     } else {
         $response = new Response();
         $response->setStatusCode("204");
         return $response;
     }
 }
 /**
  * @Route("{institutionCode}/{collectionCode}/export/{type}/", name="export", requirements={"type": "csv|dwc"})
  * @param UserInterface|User $user
  * @param string  $type
  * @param Request $request
  * @param string  $collectionCode
  * @param string  $institutionCode
  * @return JsonResponse
  * @throws \Exception
  */
 public function exportAction(UserInterface $user, $institutionCode, $collectionCode, $type, Request $request)
 {
     set_time_limit(0);
     $collection = $this->get('utility')->getCollection($institutionCode, $collectionCode, $user);
     /** @var ExportPrefs $exportPrefs */
     $exportPrefs = unserialize($request->get('exportPrefs'));
     if (!$exportPrefs instanceof ExportPrefs) {
         throw new \Exception('parameters must be an instance of ExportPrefs');
     }
     /* @var $exportManager \AppBundle\Manager\ExportManager */
     $exportManager = $this->get('exportmanager')->init($this->getUser())->setCollection($collection);
     $file = $exportManager->export($type, $exportPrefs);
     $response = new JsonResponse();
     if (is_null($file)) {
         $message = $this->get('translator')->trans('export.probleme');
         $response->setContent($message);
         $this->addFlash('error', $message);
         $response->setStatusCode(400);
         return $response;
     }
     return $response->setData(['file' => urlencode($file)]);
 }
 public function nextAction()
 {
     $this->getLogger()->debug("Next person action called.");
     $response = array();
     $systemDBManager = $this->get('doctrine')->getManager('system');
     $personData = $systemDBManager->getRepository('AmburgerBundle:PersonData')->getRandomEntities(1);
     if (is_null($personData) || count($personData) == 0) {
         $this->getLogger()->debug("There exists no uncorrected person anymore.");
         throw $this->createNotFoundException("There exists no uncorrected person anymore.");
     }
     $this->getLogger()->debug("Found " . count($personData) . " uncorrected persons.");
     if (count($personData) >= 1) {
         //get first
         $personData = $personData[0];
     }
     $this->getLogger()->debug("Next person found: " . $personData->getPersonId());
     $response["id"] = $personData->getPersonId();
     $serializer = $this->get('serializer');
     $json = $serializer->serialize($response, 'json');
     $jsonResponse = new JsonResponse();
     $jsonResponse->setContent($json);
     return $jsonResponse;
 }
 public function onKernelException(GetResponseForExceptionEvent $event)
 {
     $responseType = function () use($event) {
         $request = $event->getRequest();
         $accepts = $request->headers->get('accept', null);
         $contentType = $request->getContentType();
         return $accepts ? $accepts : $contentType;
     };
     if (strstr($responseType(), 'application/json') !== false) {
         $e = $event->getException();
         $response = new JsonResponse();
         $code = 500;
         if ($e instanceof NotFoundHttpException) {
             $code = 404;
         }
         if ($e instanceof AccessDeniedException) {
             $code = 403;
         }
         $response->setContent(json_encode(['error' => $e->getMessage(), 'code' => $code], true))->setStatusCode($code);
         $event->setResponse($response);
     } else {
         parent::onKernelException($event);
     }
 }
 private function aObtenerDatosLibro($idLibrop)
 {
     $em = $this->getDoctrine()->getManager();
     $libro = $em->getRepository('UciBaseDatosBundle:Libro')->find($idLibrop);
     $idLibro = $libro ? $libro->getId() : 0;
     $idPmbok = $libro ? $idPmbok = $libro->getEsPmbok() == 1 ? $libro->getPmbok()->getId() : 0 : 0;
     $response = new JsonResponse();
     if ($idLibro == 0) {
         $qb1 = $em->getRepository('UciBaseDatosBundle:AreaConocimiento')->createQueryBuilder('a');
         $areas = $qb1->getQuery()->getArrayResult();
         $qb2 = $em->getRepository('UciBaseDatosBundle:GrupoProcesos')->createQueryBuilder('g');
         $grupos = $qb2->getQuery()->getArrayResult();
         $qb3 = $em->getRepository('UciBaseDatosBundle:TrianguloTalento')->createQueryBuilder('t');
         $triangulos = $qb3->getQuery()->getArrayResult();
         $qb4 = $em->getRepository('UciBaseDatosBundle:Capitulo')->createQueryBuilder('c');
         $capitulos = $qb4->getQuery()->getArrayResult();
     } else {
         $capitulos = $em->getRepository('UciBaseDatosBundle:Capitulo')->createQueryBuilder('u')->innerJoin('u.libro', 'g')->where('g.id = :id')->setParameter('id', $idLibro)->orderBy('u.nombreCapitulo', 'ASC')->getQuery()->getArrayResult();
         $areas = $em->getRepository('UciBaseDatosBundle:AreaConocimiento')->createQueryBuilder('u')->innerJoin('u.pmbok', 'g')->where('g.id = :id')->setParameter('id', $idPmbok)->orderBy('u.nombreArea', 'ASC')->getQuery()->getArrayResult();
         $grupos = $em->getRepository('UciBaseDatosBundle:GrupoProcesos')->createQueryBuilder('u')->innerJoin('u.pmbok', 'g')->where('g.id = :id')->setParameter('id', $idPmbok)->orderBy('u.nombreGrupo', 'ASC')->getQuery()->getArrayResult();
         $triangulos = $em->getRepository('UciBaseDatosBundle:TrianguloTalento')->createQueryBuilder('u')->innerJoin('u.pmbok', 'g')->where('g.id = :id')->setParameter('id', $idPmbok)->orderBy('u.nombreTalento', 'ASC')->getQuery()->getArrayResult();
     }
     $response_array = array();
     $response_array['capitulos'] = empty($capitulos) ? array('id' => '0') : $capitulos;
     $response_array['areas'] = empty($areas) ? array('id' => '0') : $areas;
     $response_array['grupos'] = empty($grupos) ? array('id' => '0') : $grupos;
     $response_array['triangulos'] = empty($triangulos) ? array('id' => '0') : $triangulos;
     $response->setContent(json_encode($response_array));
     return $response;
 }
示例#24
0
 /**
  * Update computador. JSON Recebido:
  *
  * {
  *       "host": "127.0.0.1",
  *       "mac_address": "00:00:00:00:00:00",
  *       "ping_date": "2015-12-03 10:44:55.614790",
  *       "network_ip": "10.209.111.0",
  *       "local": "DEPEX",
  *       "netmask": "255.255.255.0",
  *       "so_name": "Microsoft Windows Vista SP0 - SP2, Server 2008, or Windows 7 Ultimate",
  *       "so_version": "Microsoft Windows Vista SP0 - SP2, Server 2008, or Windows 7 Ultimate",
  *       "accuracy": "100",
  *       "so_vendor": "Microsoft",
  *       "so_os_family": "Windows",
  *       "so_type": "general purpose",
  *       "so_cpe": ""
  * }
  *
  * @param $host
  * @Route("/computador/{host}", name="computador_ping")
  * @Method("POST")
  *
  */
 public function computadorPingAction($host, Request $request)
 {
     $em = $this->getDoctrine()->getManager();
     $logger = $this->get('logger');
     $status = $request->getContent();
     $dados = json_decode($status, true);
     if (empty($dados)) {
         $logger->error("JSON INVÁLIDO!!!!!!!!!!!!!!!!!!! Erro no envio das informações do computador {$host}");
         // Retorna erro se o JSON for inválido
         $error_msg = '{
             "message": "JSON Inválido",
             "codigo": 1
         }';
         $response = new JsonResponse();
         $response->setStatusCode('500');
         $response->setContent($error_msg);
         return $response;
     }
     $logger->debug("Atualizando informações para o computador com IP = {$host}\n" . $status);
     // Primeiro procura computador pelo MAC
     if (!empty($dados['mac_address'])) {
         $computador = $em->getRepository("CocarBundle:Computador")->findOneBy(array('mac_address' => $dados['mac_address']));
         // Ve se ja existe um de mesmo IP cadastrado
         $computador_ip = $em->getRepository("CocarBundle:Computador")->findOneBy(array('host' => $dados['host']));
         if (empty($computador) && empty($computador_ip)) {
             // Nao achei nem pelo MAC nem pelo IP. Cria um computador
             $logger->debug("Adicionando computador com IP = " . $dados['host'] . " e MAC = " . $dados['mac_address']);
             $computador = new Computador();
         } elseif (empty($computador) && !empty($computador_ip)) {
             // Nao achei pelo MAC, mas achei pelo IP. Considera esse
             $computador = $computador_ip;
         } elseif (!empty($computador_ip)) {
             // Aqui o MAC não é vazio nem o IP. Verifica se é uma atualização de MAC
             $ip_old = $computador_ip->getHost();
             $ip = $computador->getHost();
             if ($ip != $ip_old) {
                 $logger->debug("Atualização de IP. Adicionando MAC " . $dados['mac_address'] . " para o IP {$ip}. Removendo MAc do IP {$ip_old}");
                 // O MAC mudou de IP. O IP velho fica sem MAC
                 $computador_ip->setMacAddress(null);
                 $em->persist($computador_ip);
             }
         } else {
             // Para todos os outros casos considero somente o MAC atual. Não precisa fazer nada
         }
     } else {
         $computador = $em->getRepository("CocarBundle:Computador")->findOneBy(array('host' => $dados['host']));
         if (empty($computador)) {
             // Cria o computador
             $computador = new Computador();
         }
     }
     // Adiciona informações da coleta
     $computador->setHost($dados['host']);
     $computador->setMacAddress($dados['mac_address']);
     $computador->setLocal($dados['local']);
     $computador->setName($dados['name']);
     $computador->setNetmask($dados['netmask']);
     $computador->setAccuracy($dados['accuracy']);
     $computador->setSoCpe($dados['so_cpe']);
     $computador->setSoName($dados['so_name']);
     $computador->setSoOsFamily($dados['so_os_family']);
     $computador->setSoType($dados['so_type']);
     $computador->setSoVendor($dados['so_vendor']);
     $computador->setSoVersion($dados['so_version']);
     // Verifica se o Cacic esta instalado e procura o computador
     $cacic = $this->container->get('kernel')->getBundle('CacicCommonBundle');
     if (!empty($cacic)) {
         $cacic_id = $computador->getCacicId();
         if (empty($cacic_id)) {
             // Procura primeiro pelo MAC
             $cacic_comp = $em->getRepository("CacicCommonBundle:Computador")->findOneBy(array('teNodeAddress' => $computador->getMacAddress()));
             if (empty($cacic_comp)) {
                 $cacic_comp = $em->getRepository("CacicCommonBundle:Computador")->findOneBy(array('teIpComputador' => $computador->getHost()));
             }
             if (!empty($cacic_comp)) {
                 // Vê se o computador é considerado ativo no Cacic
                 $computador->setCacicId($cacic_comp->getIdComputador());
                 $computador->setActive($cacic_comp->getAtivo());
             }
         } else {
             $cacic_comp = $em->getRepository("CacicCommonBundle:Computador")->find($cacic_id);
             $computador->setActive($cacic_comp->getAtivo());
         }
     }
     // Registra o ping
     $ping = new PingComputador();
     $ping->setComputador($computador);
     $ping_date = new \DateTime($dados['ping_date']);
     $ping->setDate($ping_date);
     // Persiste as informações
     try {
         $em->persist($computador);
         $em->flush();
         $em->persist($ping);
         $em->flush();
     } catch (\Exception $e) {
         // Ainda assim retorna como sucesso
         $logger->error("Entrada repetida para computador " . $dados['host'] . " na data " . $dados['ping_date']);
         $logger->error($e->getMessage());
     }
     // Se tudo deu certo, retorna
     $response = new JsonResponse();
     $response->setStatusCode('200');
     return $response;
 }
示例#25
0
 /**
  * [AJAX] Desativar notificações para o relatório
  *
  * @param Request $request
  * @return JsonResponse
  */
 public function notificarDelAction(Request $request)
 {
     $em = $this->getDoctrine()->getManager();
     if (!$request->isXmlHttpRequest()) {
         throw $this->createNotFoundException('Página não encontrada');
     }
     $relatorio = $em->getRepository('CacicCommonBundle:SoftwareRelatorio')->find($request->get('id'));
     if (empty($relatorio)) {
         $this->get('session')->getFlashBag()->add('error', 'Relatório não encontrado!');
         throw $this->createNotFoundException('Relatório não encontrado');
     }
     // Usuário só pode editar seus próprios relatórios
     if (!$this->get('security.context')->isGranted('ROLE_GESTAO')) {
         if ($this->getUser()->getIdUsuario() != $relatorio->getIdUsuario()->getIdUsuario()) {
             $this->get('session')->getFlashBag()->add('error', 'Usuário só pode editar seus próprios relatórios!');
             throw $this->createAccessDeniedException("Usuário só pode editar seus próprios relatórios");
         }
     }
     // Habilita notificação
     $relatorio->setHabilitaNotificacao(false);
     $em->persist($relatorio);
     $em->flush();
     $this->get('session')->getFlashBag()->add('success', 'Notificação removida com sucesso!');
     $response = new JsonResponse();
     $response->setContent(json_encode(array('status' => 'ok')));
     $response->setStatusCode(200);
     return $response;
 }
示例#26
0
 public function excluirCadastradosAction(Request $request)
 {
     $em = $this->getDoctrine()->getManager();
     if (!$request->isXmlHttpRequest()) {
         throw $this->createNotFoundException('Página não encontrada');
     }
     $relatorio = $em->getRepository('CacicCommonBundle:SoftwareRelatorio')->find($request->get('id'));
     if (empty($relatorio)) {
         throw $this->createNotFoundException('Relatório não encontrado');
     }
     // Usuário só pode editar seus próprios relatórios
     if (!$this->get('security.context')->isGranted('ROLE_ADMIN')) {
         if ($this->getUser()->getIdUsuario() != $relatorio->getIdUsuario()->getIdUsuario()) {
             throw $this->createAccessDeniedException("Usuário só pode editar seus próprios relatórios");
         }
     }
     $em->remove($relatorio);
     // Registra no log de atividades
     $log = new Log();
     $log->setIdUsuario($this->getUser());
     $log->setCsAcao("DEL");
     $log->setDtAcao(new \DateTime());
     $log->setNmScript("Cadastro de relatórios");
     $log->setNmTabela("software_relatorio");
     $log->setTeIpOrigem($request->getClientIp());
     $em->persist($log);
     $em->flush();
     $this->get('session')->getFlashBag()->add('success', 'Relatório removido com sucesso!');
     $response = new JsonResponse();
     $response->setContent(json_encode(array('status' => 'ok')));
     $response->setStatusCode(200);
     return $response;
 }
示例#27
0
 /**
  * Lista de SO no formato JSON
  *
  * @param Request $request
  * @return JsonResponse
  */
 public function ajaxSoAction(Request $request)
 {
     $logger = $this->get('logger');
     $em = $this->getDoctrine()->getManager();
     $redes = $request->get('redes');
     $so = $em->getRepository("CacicCommonBundle:So")->ajaxSo($redes);
     // Retorna JSON dos sistemas operacionais
     $json_so = json_encode($so, true);
     $response = new JsonResponse();
     $response->setStatusCode(200);
     $response->setContent($json_so);
     return $response;
 }
示例#28
0
 /**
  * Registra erros do Agente
  *
  * @param Request $request
  * @return JsonResponse
  */
 public function logErroAction(Request $request)
 {
     $logger = $this->get('logger');
     $status = $request->getContent();
     $em = $this->getDoctrine()->getManager();
     $dados = json_decode($status, true);
     $response = new JsonResponse();
     if (empty($dados)) {
         $logger->error("LOG ERRO: JSON INVÁLIDO!!!!!!!!!!!!!!!!!!!");
         // Retorna erro se o JSON for inválido
         $error_msg = '{
             "message": "JSON Inválido",
             "codigo": 1
         }';
         $response = new JsonResponse();
         $response->setStatusCode('500');
         $response->setContent($error_msg);
         return $response;
     }
     // Identifica computador
     $computador = $this->getComputador($dados, $request);
     if (empty($computador)) {
         $logger->error("LOG ERRO: Erro na identificação do computador no registro de erros.");
         $error_msg = '{
             "message": "Computador não identificado",
             "codigo": 2
         }';
         $response = new JsonResponse();
         $response->setStatusCode('500');
         $response->setContent($error_msg);
         return $response;
     }
     $info = @$dados['logInfo'];
     if (!empty($info)) {
         foreach ($info as $entry) {
             $timestamp = \DateTime::createFromFormat('d-m-Y H:i:s.u', $entry['timestamp']);
             $log_erro = $em->getRepository("CacicCommonBundle:ErrosAgente")->findOneBy(array('computador' => $computador->getIdComputador(), 'timestampErro' => $timestamp));
             if (empty($log_erro)) {
                 $logger->debug("Inserindo novo log para o computador = " . $computador->getTeIpComputador() . " timestamp = " . $timestamp->format('d-m-Y H:i:s.u'));
                 $log_erro = new ErrosAgente();
                 $log_erro->setTimestampErro($timestamp);
                 $log_erro->setComputador($computador);
                 $log_erro->setNivelErro('info');
                 $log_erro->setMensagem($entry['message']);
                 $em->persist($log_erro);
             }
         }
     }
     $erros = @$dados['logError'];
     if (!empty($erros)) {
         foreach ($erros as $entry) {
             $timestamp = \DateTime::createFromFormat('d-m-Y H:i:s.u', $entry['timestamp']);
             $log_erro = $em->getRepository("CacicCommonBundle:ErrosAgente")->findOneBy(array('computador' => $computador->getIdComputador(), 'timestampErro' => $timestamp));
             if (empty($log_erro)) {
                 $logger->debug("Inserindo novo log para o computador = " . $computador->getTeIpComputador() . " timestamp = " . $timestamp->format('d-m-Y H:i:s.u'));
                 $log_erro = new ErrosAgente();
                 $log_erro->setTimestampErro($timestamp);
                 $log_erro->setComputador($computador);
                 $log_erro->setNivelErro('error');
                 $log_erro->setMensagem($entry['message']);
                 $em->persist($log_erro);
             }
         }
     }
     $em->flush();
     $response->setStatusCode('200');
     return $response;
 }
 public function downloadMsiAction(Request $request)
 {
     $logger = $this->get('logger');
     $status = $request->getContent();
     $em = $this->getDoctrine()->getManager();
     $dados = json_decode($status, true);
     if (empty($dados)) {
         // Pego IP da conexão e considero a máscara padrão
         $ip_computador = $request->getClientIp();
         $rede = $em->getRepository("CacicCommonBundle:Rede")->getDadosRedePreColeta($ip_computador);
     } else {
         // Verifica se o IP não é localhost ou genérico
         if ($dados['ip_address'] == '127.0.0.1' || $dados['ip_address'] == '0.0.0.0') {
             $ip_computador = $request->getClientIp();
         } else {
             $ip_computador = $dados['ip_address'];
         }
         $netmask = @$dados['netmask'];
         if (!empty($netmask)) {
             $rede = $em->getRepository("CacicCommonBundle:Rede")->getDadosRedePreColeta($ip_computador, $netmask);
         } else {
             $rede = $em->getRepository("CacicCommonBundle:Rede")->getDadosRedePreColeta($ip_computador);
         }
     }
     $path = $rede->getTePathServUpdates();
     if (!empty($path)) {
         $url = $rede->getTeServUpdates() . "/" . $path . "/" . "Cacic.msi";
     } else {
         $url = $rede->getTeServUpdates() . "/Cacic.msi";
     }
     $retorno = array('valor' => $url);
     $modulo = json_encode($retorno, true);
     $response = new JsonResponse();
     $response->setStatusCode('200');
     $response->setContent($modulo);
     return $response;
 }
示例#30
0
 /**
  * Pega lista de redes no formato JSON
  *
  * @param Request $request
  * @return JsonResponse
  */
 public function ajaxRedeAction(Request $request)
 {
     $logger = $this->get('logger');
     $em = $this->getDoctrine()->getManager();
     $dados = $request->get('locais');
     $redes = $em->getRepository("CacicCommonBundle:Rede")->ajaxRede($dados);
     // Retorna JSON das redes
     $json_redes = json_encode($redes, true);
     $response = new JsonResponse();
     $response->setStatusCode(200);
     $response->setContent($json_redes);
     return $response;
 }